[GRASS-SVN] r51789 - grass/trunk/gui/wxpython/gui_core

svn_grass at osgeo.org svn_grass at osgeo.org
Sat May 26 10:40:37 EDT 2012


Author: martinl
Date: 2012-05-26 07:40:36 -0700 (Sat, 26 May 2012)
New Revision: 51789

Modified:
   grass/trunk/gui/wxpython/gui_core/goutput.py
   grass/trunk/gui/wxpython/gui_core/prompt.py
Log:
wxGUI: implement cmd protocol functionality
       fix GPrompt.OnRunCmd() to be called correctly


Modified: grass/trunk/gui/wxpython/gui_core/goutput.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/goutput.py	2012-05-26 14:26:30 UTC (rev 51788)
+++ grass/trunk/gui/wxpython/gui_core/goutput.py	2012-05-26 14:40:36 UTC (rev 51789)
@@ -264,16 +264,20 @@
             self.btnCmdClear.Hide()
         self.btnOutputSave  = wx.Button(parent = self.panelOutput, id = wx.ID_SAVE)
         self.btnOutputSave.SetToolTipString(_("Save output window content to the file"))
-        # abort
         self.btnCmdAbort = wx.Button(parent = self.panelOutput, id = wx.ID_STOP)
         self.btnCmdAbort.SetToolTipString(_("Abort running command"))
         self.btnCmdAbort.Enable(False)
+        self.btnCmdProtocol = wx.ToggleButton(parent = self.panelOutput, id = wx.ID_ANY,
+                                              label = _("&Protocol"))
+        self.btnCmdProtocol.SetToolTipString(_("Toggle to save list of executed commands into file; "
+                                               "content saved when switching off."))
         
         self.btnCmdClear.Bind(wx.EVT_BUTTON,     self.cmdPrompt.OnCmdErase)
-        self.btnOutputClear.Bind(wx.EVT_BUTTON,  self.ClearHistory)
-        self.btnOutputSave.Bind(wx.EVT_BUTTON,   self.SaveHistory)
+        self.btnOutputClear.Bind(wx.EVT_BUTTON,  self.OnOutputClear)
+        self.btnOutputSave.Bind(wx.EVT_BUTTON,   self.OnOutputSave)
         self.btnCmdAbort.Bind(wx.EVT_BUTTON,     self.OnCmdAbort)
         self.btnCmdAbort.Bind(EVT_CMD_ABORT,     self.OnCmdAbort)
+        self.btnCmdProtocol.Bind(wx.EVT_TOGGLEBUTTON, self.OnCmdProtocol)
         
         self._layout()
         
@@ -301,14 +305,16 @@
         outBtnSizer.Add(item = self.btnOutputSave, proportion = 1,
                         flag = wx.ALIGN_RIGHT | wx.RIGHT, border = 5)
         
+        cmdBtnSizer.Add(item = self.btnCmdProtocol, proportion = 1,
+                        flag = wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border = 5)
         cmdBtnSizer.Add(item = self.btnCmdClear, proportion = 1,
-                        flag = wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border = 5)
+                        flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
         cmdBtnSizer.Add(item = self.btnCmdAbort, proportion = 1,
                         flag = wx.ALIGN_CENTER | wx.RIGHT, border = 5)
         
-        btnSizer.Add(item = outBtnSizer, proportion = 1,
+        btnSizer.Add(item = outBtnSizer, proportion = 2,
                      flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
-        btnSizer.Add(item = cmdBtnSizer, proportion = 1,
+        btnSizer.Add(item = cmdBtnSizer, proportion = 3,
                      flag = wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
         outputSizer.Add(item = btnSizer, proportion = 0,
                         flag = wx.EXPAND)
@@ -474,7 +480,8 @@
                                                    '.bash_history'),
                                       encoding = 'utf-8', mode = 'a')
         except IOError, e:
-            self.WriteError(e)
+            GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e),
+                   parent = self.parent)
             fileHistory = None
         
         if fileHistory:
@@ -608,8 +615,8 @@
                                       onDone = onDone, onPrepare = onPrepare, userData = userData)
             self.cmdOutputTimer.Start(50)
         
-    def ClearHistory(self, event):
-        """!Clear history of commands"""
+    def OnOutputClear(self, event):
+        """!Clear content of output window"""
         self.cmdOutput.SetReadOnly(False)
         self.cmdOutput.ClearAll()
         self.cmdOutput.SetReadOnly(True)
@@ -629,30 +636,35 @@
         
         return self.cmdStdOut
     
-    def SaveHistory(self, event):
-        """!Save history of commands"""
-        self.history = self.cmdOutput.GetSelectedText()
-        if self.history == '':
-            self.history = self.cmdOutput.GetText()
-
+    def OnOutputSave(self, event):
+        """!Save (selected) text from output window to the file"""
+        text = self.cmdOutput.GetSelectedText()
+        if not text:
+            text = self.cmdOutput.GetText()
+        
         # add newline if needed
-        if len(self.history) > 0 and self.history[-1] != '\n':
-            self.history += '\n'
-
-        wildcard = "Text file (*.txt)|*.txt"
-        dlg = wx.FileDialog(self, message = _("Save file as..."), defaultDir = os.getcwd(),
-                            defaultFile = "grass_cmd_history.txt", wildcard = wildcard,
+        if len(text) > 0 and text[-1] != '\n':
+            text += '\n'
+        
+        dlg = wx.FileDialog(self, message = _("Save file as..."),
+                            defaultFile = "grass_cmd_output.txt",
+                            wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
                             style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
-
+        
         # Show the dialog and retrieve the user response. If it is the OK response,
         # process the data.
         if dlg.ShowModal() == wx.ID_OK:
             path = dlg.GetPath()
-
-            output = open(path, "w")
-            output.write(self.history)
-            output.close()
-
+            
+            try:
+                output = open(path, "w")
+                output.write(text)
+            except IOError, e:
+                GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
+            finally:
+                output.close()
+            self.parent.SetStatusText(_("Commands output saved as '%s'") % path)
+        
         dlg.Destroy()
 
     def GetCmd(self):
@@ -749,6 +761,37 @@
         """!Update progress message info"""
         self.progressbar.SetValue(event.value)
 
+    def OnCmdProtocol(self, event):
+        """!Save commands into file"""
+        if not self.btnCmdProtocol.GetValue():
+            # stop capturing commands, save list of commands to the
+            # protocol file
+            if hasattr(self, 'cmdFileProtocol'):
+                try:
+                    output = open(self.cmdFileProtocol, "w")
+                    cmds = self.cmdPrompt.GetCommands()
+                    output.write('\n'.join(cmds))
+                    if len(cmds) > 0:
+                        output.write('\n')
+                except IOError, e:
+                    GError(_("Unable to write file '%s'.\n\nDetails: %s") % (path, e))
+                finally:
+                    output.close()
+            
+                self.parent.SetStatusText(_("List of commands saved as '%s'") % self.cmdFileProtocol)
+                del self.cmdFileProtocol
+        else:
+            # start capturing commands
+            self.cmdPrompt.ClearCommands()
+            # ask for the file
+            dlg = wx.FileDialog(self, message = _("Save file as..."),
+                                defaultFile = "grass_cmd_protocol.txt",
+                                wildcard = _("%s (*.txt)|*.txt|%s (*)|*") % (_("Text files"), _("Files")),
+                                style = wx.SAVE | wx.FD_OVERWRITE_PROMPT)
+            if dlg.ShowModal() == wx.ID_OK:
+                self.cmdFileProtocol = dlg.GetPath()
+            dlg.Destroy()
+            
     def OnCmdAbort(self, event):
         """!Abort running command"""
         self.cmdThread.abort()

Modified: grass/trunk/gui/wxpython/gui_core/prompt.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/prompt.py	2012-05-26 14:26:30 UTC (rev 51788)
+++ grass/trunk/gui/wxpython/gui_core/prompt.py	2012-05-26 14:40:36 UTC (rev 51789)
@@ -486,7 +486,7 @@
             else:
                 self.moduleDesc = parent.parent.menubar.GetData().GetModules()
             self.moduleList = self._getListOfModules()
-            self.mapList = self._getListOfMaps()
+            self.mapList    = self._getListOfMaps()
             self.mapsetList = utils.ListOfMapsets()
         else:
             self.moduleDesc = self.moduleList = self.mapList = None
@@ -496,10 +496,13 @@
         self.autoCompFilter = None
         
         # command description (gtask.grassTask)
-        self.cmdDesc = None
+        self.cmdDesc   = None
         self.cmdbuffer = self._readHistory()
-        self.cmdindex = len(self.cmdbuffer)
+        self.cmdindex  = len(self.cmdbuffer)
         
+        # list of traced commands
+        self.commands = list()
+        
     def _readHistory(self):
         """!Get list of commands from history file"""
         hist = list()
@@ -588,25 +591,42 @@
         result['vector'] = grass.list_strings('vect')
         
         return result
-
-    def OnRunCmd(self, event):
-        """!Run command"""
-        cmdString = event.GetString()
+    
+    def _runCmd(self, cmdString):
+        """!Run command
         
-        if self.standAlone:
+        @param cmdString command to run (given as a string)
+        """
+        if self.parent.GetName() == "ModelerDialog":
+            self.parent.OnOk(None)
             return
         
+        if not cmdString or self.standAlone:
+            return
+        
         if cmdString[:2] == 'd.' and not self.parent.curr_page:
-            self.parent.NewDisplay(show=True)
+            self.parent.NewDisplay(show = True)
+                
+        self.commands.append(cmdString) # trace commands
+
+        # parse command into list
+        try:
+            cmd = utils.split(str(cmdString))
+        except UnicodeError:
+            cmd = utils.split(EncodeString((cmdString)))
+        cmd = map(DecodeString, cmd)
         
-        cmd = utils.split(cmdString)
-        if len(cmd) > 1:
-            self.parent.RunCmd(cmd, switchPage = True)
+        # send the command list to the processor 
+        if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
+            self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
         else:
-            self.parent.RunCmd(cmd, switchPage = False)
+            self.parent.RunCmd(cmd)
+            
+        # add command to history & clean prompt
+        self.UpdateCmdHistory(cmd)
+        self.OnCmdErase(None)
+        self.parent.parent.statusbar.SetStatusText('')
         
-        self.OnUpdateStatusBar(None)
-        
     def OnUpdateStatusBar(self, event):
         """!Update Layer Manager status bar"""
         if self.standAlone:
@@ -643,6 +663,14 @@
             else:
                 self.dataList = self._getListOfMaps()
         
+    def GetCommands(self):
+        """!Get list of launched commands"""
+        return self.commands
+    
+    def ClearCommands(self):
+        """!Clear list of commands"""
+        del self.commands[:]
+        
 class GPromptPopUp(GPrompt, TextCtrlAutoComplete):
     """!Interactive wxGUI prompt - popup version"""
     def __init__(self, parent):
@@ -678,6 +706,10 @@
         """!Erase command prompt"""
         self.input.SetValue('')
 
+    def OnRunCmd(self, event):
+        """!Run command"""
+        self._runCmd(event.GetString())
+        
 class GPromptSTC(GPrompt, wx.stc.StyledTextCtrl):
     """!Styled wxGUI prompt with autocomplete and calltips"""    
     def __init__(self, parent, id = wx.ID_ANY, margin = False):
@@ -1080,34 +1112,8 @@
         elif event.GetKeyCode() == wx.WXK_RETURN and \
                 self.AutoCompActive() == False:
             # run command on line when <return> is pressed
-            
-            if self.parent.GetName() == "ModelerDialog":
-                self.parent.OnOk(None)
-                return
-            
-            # find the command to run
-            line = self.GetCurLine()[0].strip()
-            if len(line) == 0:
-                return
-            
-            # parse command into list
-            try:
-                cmd = utils.split(str(line))
-            except UnicodeError:
-                cmd = utils.split(EncodeString((line)))
-            cmd = map(DecodeString, cmd)
-            
-            #  send the command list to the processor 
-            if cmd[0] in ('r.mapcalc', 'r3.mapcalc') and len(cmd) == 1:
-                self.parent.parent.OnMapCalculator(event = None, cmd = cmd)
-            else:
-                self.parent.RunCmd(cmd)
-            
-            # add command to history & clean prompt
-            self.UpdateCmdHistory(cmd)
-            self.OnCmdErase(None)
-            self.parent.parent.statusbar.SetStatusText('')
-            
+            self._runCmd(self.GetCurLine()[0].strip())
+                        
         elif event.GetKeyCode() == wx.WXK_SPACE:
             items = self.GetTextLeft().split()
             if len(items) == 1:



More information about the grass-commit mailing list