source: sasview/calculatorview/src/sans/perspectives/calculator/pyconsole.py @ d760c0a

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since d760c0a was 5d1c1f4, checked in by Jae Cho <jhjcho@…>, 13 years ago

added compile, run and help in pyeditor

  • Property mode set to 100644
File size: 8.7 KB
Line 
1"""
2Console Module display Python console
3"""
4import sys
5import os
6import wx
7import wx.lib.dialogs
8import wx.py.editor as editor
9import wx.py.frame as frame
10import py_compile
11
12if sys.platform.count("win32")>0:
13    PANEL_WIDTH = 800
14    PANEL_HEIGHT = 600
15    FONT_VARIANT = 0
16else:
17    PANEL_WIDTH = 830
18    PANEL_HEIGHT = 620
19    FONT_VARIANT = 1
20ID_COMPILE = wx.NewId() 
21ID_RUN = wx.NewId() 
22
23def compile_file(path):
24    """
25    Compile a python file
26    """
27    try:
28        import py_compile
29        py_compile.compile(file=path, doraise=True)
30    except:
31        type, value, traceback = sys.exc_info()
32        return value
33    return None 
34
35class PyConsole(editor.EditorNotebookFrame):
36    ## Internal nickname for the window, used by the AUI manager
37    window_name = "Custom Model Editor"
38    ## Name to appear on the window title bar
39    window_caption = "Custom Model Editor"
40    ## Flag to tell the AUI manager to put this panel in the center pane
41    CENTER_PANE = False
42    def __init__(self, parent=None, manager=None, panel=None,
43                    title='Python Shell/Editor', filename=None,
44                    size=(PANEL_WIDTH, PANEL_HEIGHT)):
45        self.config = None
46        editor.EditorNotebookFrame.__init__(self, parent=parent, 
47                                        title=title, size=size,
48                                        filename=filename)
49        self.parent = parent
50        self._manager = manager
51        self.panel = panel
52        self._add_menu()
53        if filename != None:
54            dataDir = os.path.dirname(filename)
55        elif self.parent != None:
56            dataDir = self.parent._default_save_location
57        else:
58             dataDir = None
59        self.dataDir = dataDir
60        self.Centre()
61        self.fileMenu.FindItemById(wx.ID_NEW).Enable(False)
62        self.fileMenu.Enable(wx.ID_OPEN, False)
63        self.Bind(wx.EVT_MENU, self.OnSaveFile, id=wx.ID_SAVE)
64        self.Bind(wx.EVT_MENU, self.OnSaveAsFile, id=wx.ID_SAVEAS)
65        self.Bind(wx.EVT_MENU, self.OnCompile, id=ID_COMPILE)
66        self.Bind(wx.EVT_MENU, self.OnRun, id=ID_RUN)
67        self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateCompileMenu, id=ID_COMPILE)
68        self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateCompileMenu, id=ID_RUN)
69       
70    def _add_menu(self):
71        """
72        Add menu
73        """
74        self.compileMenu = wx.Menu()
75        self.compileMenu.Append(ID_COMPILE, 'Compile',
76                 'Compile the file')
77        self.compileMenu.AppendSeparator()
78        self.compileMenu.Append(ID_RUN, 'Run',
79                 'Run the file in the Python Shell')
80        self.MenuBar.Insert(3, self.compileMenu, '&Compile')
81   
82    def OnHelp(self, event):
83        """
84        Show a help dialog.
85        """
86        import  wx.lib.dialogs
87        title = 'Help on key bindings'
88        text = wx.py.shell.HELP_TEXT
89        dlg = wx.lib.dialogs.ScrolledMessageDialog(self, text, title,
90                                                   size = ((700, 540)))
91        fnt = wx.Font(10, wx.TELETYPE, wx.NORMAL, wx.NORMAL)
92        dlg.GetChildren()[0].SetFont(fnt)
93        dlg.GetChildren()[0].SetInsertionPoint(0)
94        dlg.ShowModal()
95        dlg.Destroy()
96
97    def set_manager(self, manager):
98        """
99        Set the manager of this window
100        """
101        self._manager = manager
102       
103    def OnAbout(self, event):
104        """
105        On About
106        """
107        message = ABOUT
108        dial = wx.MessageDialog(self, message, 'About',
109                           wx.OK|wx.ICON_INFORMATION) 
110        dial.ShowModal()
111       
112    def OnSaveFile(self, event):
113        """
114        OnFileSave overwrite   
115        """
116        self.OnFileSave(event)
117        self.Show(False)
118        self.Show(True)
119       
120    def OnSaveAsFile(self, event):
121        """
122        OnFileSaveAs overwrite   
123        """
124        self.OnFileSaveAs(event)
125        self.Show(False)
126        self.Show(True)
127
128    def bufferSaveAs(self):
129        """
130        Save buffer to a new filename: Bypass the annoying suggest save
131        """
132        filedir = ''
133        if self.buffer and self.buffer.doc.filedir:
134            filedir = self.buffer.doc.filedir
135        result = editor.saveSingle(directory=filedir)
136        if result.path:
137            self.buffer.saveAs(result.path)
138            cancel = False
139        else:
140            cancel = True
141        return cancel
142   
143    def update_custom_combo(self):
144        """
145        Update custom model combo box in fit_panel
146        """
147        try:
148            page = self.panel.get_current_page()
149            temp = self.panel.update_model_list()
150            if temp:
151                page.model_list_box = temp
152                current_val = page.formfactorbox.GetValue()
153                pos = page.formfactorbox.GetSelection()
154                page._show_combox_helper()
155                page.formfactorbox.SetSelection(pos)
156                page.formfactorbox.SetValue(current_val)
157        except:
158            pass
159       
160    def OnRun(self, event):
161        """
162        Run
163        """
164        if self._check_changed():
165            return True
166        if self.buffer and self.buffer.doc.filepath:
167            self.editor.setFocus()
168            # Why we have to do this (Otherwise problems on Windows)?
169            forward_path = self.buffer.doc.filepath.replace('\\', '/')
170            self.shell.Execute("execfile('%s')"% forward_path)
171            self.shell.Hide()
172            self.shell.Show(True)
173            self.shell.SetFocus()
174        else:
175            mssg = "\n This is not a python file."
176            title = 'Error'
177            icon = wx.ICON_ERROR
178            wx.MessageBox(str(mssg), title, style=icon)
179       
180    def OnCompile(self, event):
181        """
182        Compile
183        """
184        if self._check_changed():
185            return True
186        if self._get_err_msg():
187            if self._manager != None and self.panel != None:
188                self._manager.set_edit_menu(self.parent)
189                wx.CallAfter(self.update_custom_combo)
190   
191    def _check_changed(self):   
192        """
193        If content was changed, suggest to save it first
194        """
195        if self.bufferHasChanged() and self.buffer.doc.filepath:
196            cancel = self.bufferSuggestSave()
197            if cancel:
198                return cancel
199             
200    def _get_err_msg(self):
201        """
202        Get err_msg
203        """
204        name = None
205        mssg = "\n This is not a python file."
206        title = 'Error'
207        icon = wx.ICON_ERROR
208        try:
209            fname = self.editor.getStatus()[0]
210            name = os.path.basename(fname)
211            if name.split('.')[-1] != 'py':
212                wx.MessageBox(str(mssg), title, style=icon)
213                return False
214            msg = compile_file(fname)
215        except:
216            msg = None
217        if name == None:
218            wx.MessageBox(str(mssg), title, style=icon)
219            return False
220        mssg = "Compiling '%s'...\n"% name
221        if msg != None:
222            mssg += "Error occurred:\n"
223            mssg += str(msg)
224            title = 'Warning'
225            icon = wx.ICON_WARNING
226        else:
227            mssg += "Successful."
228            title = 'Info'
229            icon = wx.ICON_INFORMATION
230        dlg = wx.lib.dialogs.ScrolledMessageDialog(self, mssg, title, 
231                                                   size = ((550, 250)))
232        fnt = wx.Font(10, wx.TELETYPE, wx.NORMAL, wx.NORMAL)
233        dlg.GetChildren()[0].SetFont(fnt)
234        dlg.GetChildren()[0].SetInsertionPoint(0)
235        dlg.ShowModal()
236        dlg.Destroy()
237        return True
238   
239    def OnUpdateCompileMenu(self, event):
240        """
241        Update Compile menu items based on current tap.
242        """
243        win = wx.Window.FindFocus()
244        id = event.GetId()
245        event.Enable(True)
246        try:
247            if id == ID_COMPILE or id == ID_RUN:
248                menu_on = False
249                if self.buffer and self.buffer.doc.filepath:
250                    menu_on = True
251                event.Enable(menu_on)
252        except AttributeError:
253            # This menu option is not supported in the current context.
254            event.Enable(False)
255           
256ABOUT =  "Welcome to Python %s! \n\n"% sys.version.split()[0]
257ABOUT += "This uses Py Shell/Editor in wx (developed by Patrick K. O'Brien).\n"
258ABOUT += "If this is your first time using Python, \n"
259ABOUT += "you should definitely check out the tutorial "
260ABOUT += "on the Internet at http://www.python.org/doc/tut/."
261 
262       
263if __name__ == "__main__":
264   
265    app  = wx.App()
266    dlg = PyConsole()
267    dlg.Show()
268    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.