Changeset 5d1c1f4 in sasview


Ignore:
Timestamp:
Dec 7, 2011 2:56:35 PM (12 years ago)
Author:
Jae Cho <jhjcho@…>
Branches:
master, ESS_GUI, ESS_GUI_Docs, ESS_GUI_batch_fitting, ESS_GUI_bumps_abstraction, ESS_GUI_iss1116, ESS_GUI_iss879, ESS_GUI_iss959, ESS_GUI_opencl, ESS_GUI_ordering, ESS_GUI_sync_sascalc, costrafo411, magnetic_scatt, release-4.1.1, release-4.1.2, release-4.2.2, release_4.0.1, ticket-1009, ticket-1094-headless, ticket-1242-2d-resolution, ticket-1243, ticket-1249, ticket885, unittest-saveload
Children:
8bac371
Parents:
a41034c
Message:

added compile, run and help in pyeditor

Files:
3 edited

Legend:

Unmodified
Added
Removed
  • calculatorview/src/sans/perspectives/calculator/pyconsole.py

    rfb58234 r5d1c1f4  
    33""" 
    44import sys 
     5import os 
    56import wx 
    6 #import wx.py.crust as crust 
     7import wx.lib.dialogs 
    78import wx.py.editor as editor 
     9import wx.py.frame as frame 
     10import py_compile 
     11 
    812if sys.platform.count("win32")>0: 
    913    PANEL_WIDTH = 800 
     
    1418    PANEL_HEIGHT = 620 
    1519    FONT_VARIANT = 1 
    16      
     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 
    1735class PyConsole(editor.EditorNotebookFrame): 
    1836    ## Internal nickname for the window, used by the AUI manager 
    19     window_name = "Python Shell/Editor" 
     37    window_name = "Custom Model Editor" 
    2038    ## Name to appear on the window title bar 
    21     window_caption = "Python Shell/Editor" 
     39    window_caption = "Custom Model Editor" 
    2240    ## Flag to tell the AUI manager to put this panel in the center pane 
    2341    CENTER_PANE = False 
    24     def __init__(self, parent=None, manager=None, 
     42    def __init__(self, parent=None, manager=None, panel=None, 
    2543                    title='Python Shell/Editor', filename=None, 
    2644                    size=(PANEL_WIDTH, PANEL_HEIGHT)): 
    27         #if parent != None: 
    28         #    dataDir = parent._default_save_location 
    29         #else: 
    30         #     dataDir = None 
    31         #wx.py.crust.CrustFrame.__init__(self, parent=parent,  
    32         #                                title=title, size=size, 
    33         #                                dataDir=dataDir) 
    3445        self.config = None 
    3546        editor.EditorNotebookFrame.__init__(self, parent=parent,  
    3647                                        title=title, size=size, 
    3748                                        filename=filename) 
    38         self._import_site() 
    3949        self.parent = parent 
    4050        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 
    4160        self.Centre() 
    42  
    43     def _import_site(self): 
    44         """ 
    45         Import site for exe 
    46         """ 
    47         import site 
    48          
     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 
    4997    def set_manager(self, manager): 
    5098        """ 
     
    61109                           wx.OK|wx.ICON_INFORMATION)   
    62110        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 
    63199              
     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             
    64256ABOUT =  "Welcome to Python %s! \n\n"% sys.version.split()[0] 
    65 ABOUT += "This uses Py Shell in wx (developed by Patrick K. O'Brien).\n" 
     257ABOUT += "This uses Py Shell/Editor in wx (developed by Patrick K. O'Brien).\n" 
    66258ABOUT += "If this is your first time using Python, \n" 
    67259ABOUT += "you should definitely check out the tutorial " 
  • fittingview/src/sans/perspectives/fitting/fitting.py

    r7b1ca97 r5d1c1f4  
    219219         
    220220        self.menu1.AppendSeparator() 
    221         self.id_editmodel = wx.NewId() 
     221        self.edit_model_menu = wx.Menu() 
     222        # Find and put files name in menu 
     223        try: 
     224            self.set_edit_menu(owner=owner) 
     225        except: 
     226            raise 
     227         
     228        self.id_edit = wx.NewId() 
    222229        editmodel_help = "Edit cusomized model sample file"  
    223         self.menu1.Append(self.id_editmodel, "Edit Custom Model",  
    224                                    editmodel_help)  
    225         wx.EVT_MENU(owner, self.id_editmodel,  self.edit_custom_model) 
    226          
     230        self.menu1.AppendMenu(self.id_edit, "Edit Custom Model",  
     231                              self.edit_model_menu, editmodel_help) 
    227232        #create  menubar items 
    228233        return [(self.menu1, self.sub_menu)] 
     
    232237        Get the python editor panel 
    233238        """ 
    234         from editmodel import PyConsole 
    235         filename = os.path.join("plugins", "testmodel.py") 
    236         frame = PyConsole(parent=self.parent, filename=filename) 
     239        id = event.GetId() 
     240        label = self.edit_model_menu.GetLabel(id) 
     241        from sans.perspectives.calculator.pyconsole import PyConsole 
     242        filename = os.path.join(models.find_plugins_dir(), label) 
     243        frame = PyConsole(parent=self.parent, manager=self, panel= self.fit_panel, 
     244                          title='Custom Model Editor', filename=filename) 
    237245        self.put_icon(frame) 
    238246        frame.Show(True)  
    239247         
     248    def set_edit_menu(self, owner):     
     249        """ 
     250        Set list of the edit model menu labels 
     251        """ 
     252        list_fnames = os.listdir(models.find_plugins_dir()) 
     253        for item in list_fnames: 
     254            name = os.path.basename(item) 
     255            toks = os.path.splitext(name) 
     256            if toks[1]=='.py' and not toks[0]=='__init__': 
     257                has_file = False 
     258                for item in self.edit_model_menu.GetMenuItems(): 
     259                    if name == self.edit_model_menu.GetLabel(item.GetId()): 
     260                        has_file = True 
     261                if not has_file: 
     262                    id = wx.NewId() 
     263                    self.edit_model_menu.Append(id, name)  
     264                    wx.EVT_MENU(owner, id,  self.edit_custom_model) 
     265                    has_file = False 
     266 
    240267    def put_icon(self, frame): 
    241268        """ 
  • fittingview/src/sans/perspectives/fitting/models.py

    r4ad076b r5d1c1f4  
    1010import time 
    1111import logging 
    12  
     12import py_compile 
    1313from sans.guiframe.events import StatusEvent   
    1414# Explicitly import from the pluginmodel module so that py2exe 
     
    6969    return model 
    7070   
    71    
    72 def _findModels(dir): 
    73     """ 
    74     """ 
    75     # List of plugin objects 
    76     plugins = {} 
    77     # Go through files in plug-in directory 
    78     #always recompile the folder plugin 
    79     import compileall 
     71def find_plugins_dir(): 
     72    """ 
     73    Find path of the plugins dir 
     74    """ 
    8075    dir = os.path.abspath(PLUGIN_DIR) 
    8176    if not os.path.isdir(dir): 
     
    8580    if not os.path.isdir(dir): 
    8681        dir = os.path.join(os.path.dirname(os.path.sys.path[0]), PLUGIN_DIR) 
     82    return dir 
     83 
     84class ReportProblem: 
     85    def __nonzero__(self): 
     86        type, value, traceback = sys.exc_info() 
     87        if type is not None and issubclass(type, py_compile.PyCompileError): 
     88            print "Problem with", repr(value) 
     89            raise type, value, traceback 
     90        return 1 
     91     
     92report_problem = ReportProblem() 
     93 
     94def compile_file(dir): 
     95    """ 
     96    Compile a py file 
     97    """ 
     98    try: 
     99        import compileall 
     100        compileall.compile_dir(dir=dir, ddir=dir, force=1, quiet=report_problem) 
     101    except: 
     102        type, value, traceback = sys.exc_info() 
     103        return value 
     104    return None 
     105 
     106def _findModels(dir): 
     107    """ 
     108    """ 
     109    # List of plugin objects 
     110    plugins = {} 
     111    # Go through files in plug-in directory 
     112    #always recompile the folder plugin 
     113    import compileall 
     114    dir = find_plugins_dir() 
    87115    if not os.path.isdir(dir): 
    88116        msg = "SansView couldn't locate Model plugin folder." 
     
    92120    else: 
    93121        log("looking for models in: %s" % str(dir)) 
    94         compileall.compile_dir(dir=dir, ddir=dir, force=1, quiet=True) 
     122        compile_file(dir) 
    95123        logging.info("pluging model dir: %s\n" % str(dir)) 
    96124    try: 
     
    438466        is_modified = False 
    439467        if os.path.isdir(PLUGIN_DIR): 
    440             temp =  os.path.getmtime(PLUGIN_DIR) 
     468            # getmtime doesn't seem to work well: use getatime 
     469            temp =  os.path.getatime(PLUGIN_DIR) 
    441470            if  self.last_time_dir_modified != temp: 
    442471                is_modified = True 
     
    460489        else: 
    461490            return {} 
    462          
     491     
     492              
    463493    def populate_menu(self, modelmenu, event_owner): 
    464494        """ 
Note: See TracChangeset for help on using the changeset viewer.