Source

wxPython / wx / py / crustslices.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
"""PySlices combines the slices and filling into one control."""

__author__ = "David N. Mashburn <david.n.mashburn@gmail.com> / "
__author__ += "Patrick K. O'Brien <pobrien@orbtech.com>"
__cvsid__ = "$Id: crustslices.py 44235 2007-01-17 23:05:14Z RD $"
__revision__ = "$Revision: 44235 $"[11:-2]

import wx

import os
import pprint
import re
import sys

import dispatcher
import crust
import document
import editwindow
import editor
from filling import Filling
import frame
from sliceshell import SlicesShell
from version import VERSION


class CrustSlices(crust.Crust):
    """Slices based on SplitterWindow."""

    name = 'Slices'
    revision = __revision__
    sashoffset = 300

    def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=wx.SP_3D|wx.SP_LIVE_UPDATE,
                 name='Slices Window', rootObject=None, rootLabel=None,
                 rootIsNamespace=True, intro='', locals=None,
                 InterpClass=None,
                 startupScript=None, execStartupScript=True,
                 showPySlicesTutorial=True,
                 enableShellMode=False, hideFoldingMargin=False,
                 *args, **kwds):
        """Create CrustSlices instance."""
        wx.SplitterWindow.__init__(self, parent, id, pos, size, style, name)

        # Turn off the tab-traversal style that is automatically
        # turned on by wx.SplitterWindow.  We do this because on
        # Windows the event for Ctrl-Enter is stolen and used as a
        # navigation key, but the SlicesShell window uses it to insert lines.
        style = self.GetWindowStyle()
        self.SetWindowStyle(style & ~wx.TAB_TRAVERSAL)
        
        self.sliceshell = SlicesShell(parent=self, introText=intro,
                                 locals=locals, InterpClass=InterpClass,
                                 startupScript=startupScript,
                                 execStartupScript=execStartupScript,
                                 showPySlicesTutorial=showPySlicesTutorial,
                                 enableShellMode=enableShellMode,
                                 hideFoldingMargin=hideFoldingMargin,
                                 *args, **kwds)
        
        self.editor = self.sliceshell
        self.shell = self.sliceshell
        if rootObject is None:
            rootObject = self.sliceshell.interp.locals
        self.notebook = wx.Notebook(parent=self, id=-1)
        self.sliceshell.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.sliceshell.interp.locals['filling'] = self.filling
        self.notebook.AddPage(page=self.filling, text='Namespace', select=True)
        
        self.display = crust.Display(parent=self.notebook)
        self.notebook.AddPage(page=self.display, text='Display')
        # Add 'pp' (pretty print) to the interpreter's locals.
        self.sliceshell.interp.locals['pp'] = self.display.setItem
        self.display.nbTab = self.notebook.GetPageCount()-1
        
        self.calltip = crust.Calltip(parent=self.notebook,ShellClassName='SlicesShell')
        self.notebook.AddPage(page=self.calltip, text='Calltip')
        
        self.sessionlisting = crust.SessionListing(parent=self.notebook,ShellClassName='SlicesShell')
        self.notebook.AddPage(page=self.sessionlisting, text='History')
        
        self.dispatcherlisting = crust.DispatcherListing(parent=self.notebook)
        self.notebook.AddPage(page=self.dispatcherlisting, text='Dispatcher')

        
        # Initialize in an unsplit mode, and check later after loading
        # settings if we should split or not.
        self.sliceshell.Hide()
        self.notebook.Hide()
        self.Initialize(self.sliceshell)
        self._shouldsplit = True
        wx.CallAfter(self._CheckShouldSplit)
        self.SetMinimumPaneSize(100)

        self.Bind(wx.EVT_SIZE, self.SplitterOnSize)
        self.Bind(wx.EVT_SPLITTER_SASH_POS_CHANGED, self.OnChanged)
        self.Bind(wx.EVT_SPLITTER_DCLICK, self.OnSashDClick)

class CrustSlicesFrame(crust.CrustFrame):
    """Frame containing all the PySlices components."""

    name = 'SliceFrame'
    revision = __revision__


    def __init__(self, parent=None, id=-1, title='PySlices',
                 pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=wx.DEFAULT_FRAME_STYLE,
                 rootObject=None, rootLabel=None, rootIsNamespace=True,
                 locals=None, InterpClass=None,
                 config=None, dataDir=None, filename=None,
                 *args, **kwds):
        """Create CrustFrame instance."""
        frame.Frame.__init__(self, parent, id, title, pos, size, style,
                             shellName='PySlices')
        frame.ShellFrameMixin.__init__(self, config, dataDir)
        
        if size == wx.DefaultSize:
            self.SetSize((800, 600))
        
        intro = 'PySlices %s - The Flakiest Python Shell... Cut up!' % VERSION
        
        self.SetStatusText(intro.replace('\n', ', '))
        self.crust = CrustSlices(parent=self, intro=intro,
                                 rootObject=rootObject,
                                 rootLabel=rootLabel,
                                 rootIsNamespace=rootIsNamespace,
                                 locals=locals,
                                 InterpClass=InterpClass,
                                 startupScript=self.startupScript,
                                 execStartupScript=self.execStartupScript,
                                 showPySlicesTutorial=self.showPySlicesTutorial,
                                 enableShellMode=self.enableShellMode,
                                 hideFoldingMargin=self.hideFoldingMargin,
                                 *args, **kwds)
        self.sliceshell = self.crust.sliceshell
        self.buffer = self.sliceshell.buffer
        # 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.sliceshell.setStatusText = self.SetStatusText
        
        self.sliceshell.SetFocus()
        self.LoadSettings()
        
        self.currentDirectory = os.path.expanduser('~')
        
        if filename!=None:
            self.bufferOpen(filename)
        
        self.Bind(wx.EVT_IDLE, self.OnIdle)

    def OnClose(self, event):
        """Event handler for closing."""
        self.bufferClose()
    
    def OnAbout(self, event):
        """Display an About window."""
        title = 'About PySlices'
        text = 'PySlices %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.sliceshell.revision + \
               'Interpreter Revision: %s\n\n' % self.sliceshell.interp.revision + \
               'Platform: %s\n' % sys.platform + \
               'Python Version: %s\n' % sys.version.split()[0] + \
               'wxPython Version: %s\n' % wx.VERSION_STRING + \
               ('\t(%s)\n' % ", ".join(wx.PlatformInfo[1:]))
        dialog = wx.MessageDialog(self, text, title,
                                  wx.OK | wx.ICON_INFORMATION)
        dialog.ShowModal()
        dialog.Destroy()

    def OnEnableShellMode(self,event):
        """Change between Slices Mode and Shell Mode"""
        frame.Frame.OnEnableShellMode(self,event)
        self.sliceshell.ToggleShellMode(self.enableShellMode)
    
    def OnHideFoldingMargin(self,event):
        """Change between Slices Mode and Shell Mode"""
        frame.Frame.OnHideFoldingMargin(self,event)
        self.sliceshell.ToggleFoldingMargin(self.hideFoldingMargin)

    # Stolen Straight from editor.EditorFrame
    # Modified a little... :)
    # ||
    # \/
    def OnIdle(self, event):
        """Event handler for idle time."""
        self._updateTitle()
        event.Skip()
    
    def _updateTitle(self):
        """Show current title information."""
        title = self.GetTitle()
        if self.bufferHasChanged():
            if title.startswith('* '):
                pass
            else:
                self.SetTitle('* ' + title)
        else:
            if title.startswith('* '):
                self.SetTitle(title[2:])
    
    def hasBuffer(self):
        """Return True if there is a current buffer."""
        if self.buffer:
            return True
        else:
            return False

    def bufferClose(self):
        """Close buffer."""
        if self.buffer.hasChanged():
            cancel = self.bufferSuggestSave()
            if cancel:
                #event.Veto()
                return cancel
        self.SaveSettings()
        self.crust.sliceshell.destroy()
        self.bufferDestroy()
        self.Destroy()
        
        return False

    def bufferCreate(self, filename=None):
        """Create new buffer."""
        self.bufferDestroy()
        buffer = Buffer()
        self.panel = panel = wx.Panel(parent=self, id=-1)
        panel.Bind (wx.EVT_ERASE_BACKGROUND, lambda x: x)        
        editor = Editor(parent=panel)
        panel.editor = editor
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(editor.window, 1, wx.EXPAND)
        panel.SetSizer(sizer)
        panel.SetAutoLayout(True)
        sizer.Layout()
        buffer.addEditor(editor)
        buffer.open(filename)
        self.setEditor(editor)
        self.editor.setFocus()
        self.SendSizeEvent()
        

    def bufferDestroy(self):
        """Destroy the current buffer."""
        if self.buffer:
            self.editor = None
            self.buffer = None


    def bufferHasChanged(self):
        """Return True if buffer has changed since last save."""
        if self.buffer:
            return self.buffer.hasChanged()
        else:
            return False

    def bufferNew(self):
        """Create new buffer."""
        cancel = self.bufferSuggestSave()
        if cancel:
            return cancel
        self.sliceshell.clear()
        self.SetTitle( 'PySlices')
        self.sliceshell.NeedsCheckForSave=False
        self.sliceshell.SetSavePoint()
        self.buffer.doc = document.Document()
        self.buffer.name = 'This shell'
        self.buffer.modulename = self.buffer.doc.filebase
        #self.bufferCreate()
        cancel = False
        return cancel

    def bufferOpen(self,file=None):
        """Open file in buffer."""
        if self.bufferHasChanged():
            cancel = self.bufferSuggestSave()
            if cancel:
                return cancel
        
        if file==None:
            file=wx.FileSelector('Open a PySlices File',
                                 wildcard='*.pyslices',
                                 default_path=self.currentDirectory)
        if file!=None and file!=u'':
            fid=open(file,'r')
            self.sliceshell.LoadPySlicesFile(fid)
            fid.close()
            self.currentDirectory = os.path.split(file)[0]
            self.SetTitle( os.path.split(file)[1] + ' - PySlices')
            self.sliceshell.NeedsCheckForSave=False
            self.sliceshell.SetSavePoint()
            self.buffer.doc = document.Document(file)
            self.buffer.name = self.buffer.doc.filename
            self.buffer.modulename = self.buffer.doc.filebase
            self.sliceshell.ScrollToLine(0)
        return
    
##     def bufferPrint(self):
##         """Print buffer."""
##         pass

##     def bufferRevert(self):
##         """Revert buffer to version of file on disk."""
##         pass
    
    # was self.buffer.save(self): # """Save buffer."""
    def simpleSave(self,confirmed=False):
        filepath = self.buffer.doc.filepath
        self.buffer.confirmed = confirmed
        if not filepath:
            return  # XXX Get filename
        if not os.path.exists(filepath):
            self.buffer.confirmed = True
        if not self.buffer.confirmed:
            self.buffer.confirmed = self.buffer.overwriteConfirm(filepath)
        if self.buffer.confirmed:
            try:
                fid = open(filepath, 'wb')
                self.sliceshell.SavePySlicesFile(fid)
            finally:
                if fid:
                    fid.close()
            self.sliceshell.SetSavePoint()
            self.SetTitle( os.path.split(filepath)[1] + ' - PySlices')
            self.sliceshell.NeedsCheckForSave=False
    
    def bufferSave(self):
        """Save buffer to its file."""
        if self.buffer.doc.filepath:
            # self.buffer.save()
            self.simpleSave(confirmed=True)
            cancel = False
        else:
            cancel = self.bufferSaveAs()
        return cancel

    def bufferSaveAs(self):
        """Save buffer to a new filename."""
        if self.bufferHasChanged() and self.buffer.doc.filepath:
            cancel = self.bufferSuggestSave()
            if cancel:
                return cancel
        filedir = ''
        if self.buffer and self.buffer.doc.filedir:
            filedir = self.buffer.doc.filedir
        result = editor.saveSingle(title='Save PySlices File',directory=filedir,
                                   wildcard='PySlices Files (*.pyslices)|*.pyslices')
        if result.path not in ['',None]:
            if result.path[-9:]!=".pyslices":
                result.path+=".pyslices"
            
            self.buffer.doc = document.Document(result.path)
            self.buffer.name = self.buffer.doc.filename
            self.buffer.modulename = self.buffer.doc.filebase
            self.simpleSave(confirmed=True) # allow overwrite
            cancel = False
        else:
            cancel = True
        return cancel
    
    def bufferSaveACopy(self):
        """Save buffer to a new filename."""
        filedir = ''
        if self.buffer and self.buffer.doc.filedir:
            filedir = self.buffer.doc.filedir
        result = editor.saveSingle(title='Save a Copy of PySlices File',directory=filedir,
                                   wildcard='PySlices Files (*.pyslices)|*.pyslices')
        
        if result.path not in ['',None]:
            if result.path[-9:]!=".pyslices":
                result.path+=".pyslices"
            
            # if not os.path.exists(result.path):
            try: # Allow overwrite...
                fid = open(result.path, 'wb')
                self.sliceshell.SavePySlicesFile(fid)
            finally:
                if fid:
                    fid.close()
                
            cancel = False
        else:
            cancel = True
        return cancel
    
    def bufferSuggestSave(self):
        """Suggest saving changes.  Return True if user selected Cancel."""
        result = editor.messageDialog(parent=None,
                               message='%s has changed.\n'
                                       'Would you like to save it first'
                                       '?' % self.buffer.name,
                               title='Save current file?',
                               style=wx.YES_NO | wx.CANCEL | wx.NO_DEFAULT |
                                     wx.CENTRE | wx.ICON_QUESTION )
        if result.positive:
            cancel = self.bufferSave()
        else:
            cancel = result.text == 'Cancel'
        return cancel

    def updateNamespace(self):
        """Update the buffer namespace for autocompletion and calltips."""
        if self.buffer.updateNamespace():
            self.SetStatusText('Namespace updated')
        else:
            self.SetStatusText('Error executing, unable to update namespace')