Exemple #1
0
    def _runCmd(self, cmdString):
        """!Run command
        
        @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.parent.GetMapDisplay():
            self.parent.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)

        # 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('')
Exemple #2
0
 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(text) > 0 and text[-1] != '\n':
         text += '\n'
     
     dlg = wx.FileDialog(self, message = _("Save file as..."),
                         defaultFile = "grass_cmd_output.txt",
                         wildcard = _("%(txt)s (*.txt)|*.txt|%(files)s (*)|*") % 
                         {'txt': _("Text files"), 'files': _("Files")},
                         style = wx.FD_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()
         
         try:
             output = open(path, "w")
             output.write(EncodeString(text))
         except IOError as e:
             GError(_("Unable to write file '%(path)s'.\n\nDetails: %(error)s") % {'path': path, 'error': e})
         finally:
             output.close()
         message = _("Command output saved into '%s'") % path
         self.showNotification.emit(message = message)
     
     dlg.Destroy()
Exemple #3
0
 def _getCmd(self):
     line = self.cmd_prompt.GetCurLine()[0].strip()
     if len(line) == 0:
         cmd = list()
     else:
         try:
             cmd = utils.split(str(line))
         except UnicodeError:
             cmd = utils.split(EncodeString((line)))
     return cmd
Exemple #4
0
    def _createMenuItem(
        self,
        menu,
        label,
        description,
        handler,
        command,
        keywords,
        shortcut="",
        icon="",
        wxId=wx.ID_ANY,
        kind=wx.ITEM_NORMAL,
    ):
        """Creates menu items
        There are three menu styles (menu item text styles).
        1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
        """
        if not label:
            menu.AppendSeparator()
            return

        if command:
            helpString = command + " -- " + description
        else:
            helpString = description

        if shortcut:
            label += "\t" + shortcut

        menuItem = wx.MenuItem(menu, wxId, label, helpString, kind)
        if icon:
            menuItem.SetBitmap(MetaIcon(img=icon).GetBitmap(self.bmpsize))
        menu.AppendItem(menuItem)

        self.menucmd[menuItem.GetId()] = command

        if command:
            try:
                cmd = utils.split(str(command))
            except UnicodeError:
                cmd = utils.split(EncodeString((command)))
            # disable only grass commands which are not present (e.g.
            # r.in.lidar)
            if (
                cmd
                and cmd[0] not in globalvar.grassCmd
                and re.match("[rvdipmgt][3bs]?\.([a-z0-9\.])+", cmd[0])
            ):
                menuItem.Enable(False)

        rhandler = eval("self.parent." + handler)
        self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Exemple #5
0
def _encode_string(string):
    """Encode a unicode *string* using the system encoding

    If it is not possible to use system encoding, UTF-8 is used.
    """
    try:
        from core.gcmd import EncodeString
        return EncodeString(string)
    except ImportError:
        # This is the case when we have errors during compilation but
        # the environment is not complete (compilation, custom setups
        # of GRASS environmet) and we cannot import wx correctly.
        # UTF-8 is pretty good guess for most cases (and should work for
        # Mac OS X where wx 32 vs 64 bit issue is happaning).
        return string.encode('utf-8')
    def AddTextWrapped(self, txt, wrap=None):
        """Add string to text area.

        String is wrapped and linesep is also added to the end
        of the string"""
        # allow writing to output window
        self.SetReadOnly(False)

        if wrap:
            txt = textwrap.fill(txt, wrap) + '\n'
        else:
            if txt[-1] != '\n':
                txt += '\n'

        if '\r' in txt:
            self.linePos = -1
            for seg in txt.split('\r'):
                if self.linePos > -1:
                    self.SetCurrentPos(self.linePos)
                    self.ReplaceSelection(seg)
                else:
                    self.linePos = self.GetCurrentPos()
                    self.AddText(seg)
        else:
            self.linePos = self.GetCurrentPos()

            try:
                self.AddText(txt)
            except UnicodeDecodeError:
                # TODO: this might be dead code for Py3, txt is already unicode?
                enc = UserSettings.Get(group='atm',
                                       key='encoding',
                                       subkey='value')
                if enc:
                    txt = unicode(txt, enc, errors='replace')
                elif 'GRASS_DB_ENCODING' in os.environ:
                    txt = unicode(txt,
                                  os.environ['GRASS_DB_ENCODING'],
                                  errors='replace')
                else:
                    txt = EncodeString(txt)

                self.AddText(txt)

        # reset output window to read only
        self.SetReadOnly(True)
Exemple #7
0
    def _createMenuItem(self,
                        menu,
                        menustyle,
                        label,
                        help,
                        handler,
                        gcmd,
                        keywords,
                        shortcut='',
                        wxId=wx.ID_ANY,
                        kind=wx.ITEM_NORMAL):
        """!Creates menu items
        There are three menu styles (menu item text styles).
        1 -- label only, 2 -- label and cmd name, 3 -- cmd name only
        """
        if not label:
            menu.AppendSeparator()
            return

        if len(gcmd) > 0:
            helpString = gcmd + ' -- ' + help
            if menustyle == 1:
                label += '   [' + gcmd + ']'
            elif menustyle == 2:
                label = '      [' + gcmd + ']'
        else:
            helpString = help

        if shortcut:
            label += '\t' + shortcut

        menuItem = menu.Append(wxId, label, helpString, kind)

        self.menucmd[menuItem.GetId()] = gcmd

        if gcmd:
            try:
                cmd = utils.split(str(gcmd))
            except UnicodeError:
                cmd = utils.split(EncodeString((gcmd)))
            if cmd and cmd[0] not in globalvar.grassCmd:
                menuItem.Enable(False)

        rhandler = eval('self.parent.' + handler)

        self.parent.Bind(wx.EVT_MENU, rhandler, menuItem)
Exemple #8
0
    def _runCmd(self, cmdString):
        """Run command

        :param str cmdString: command to run
        """
        if not cmdString:
            return

        # parse command into list
        try:
            cmd = utils.split(str(cmdString))
        except UnicodeError:
            cmd = utils.split(EncodeString((cmdString)))
        cmd = list(map(DecodeString, cmd))

        self.promptRunCmd.emit(cmd=cmd)

        self.OnCmdErase(None)
        self.ShowStatusText('')
Exemple #9
0
    def _runCmd(self, cmdString):
        """Run command
        
        :param str cmdString: command to run
        """
        if not cmdString:
            return

        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)

        self.promptRunCmd.emit(cmd=cmd)

        # add command to history & clean prompt
        ### self.UpdateCmdHistory(cmd)
        self.OnCmdErase(None)
        self.ShowStatusText('')
Exemple #10
0
def module_template():
    """Template from which to start writing GRASS module"""
    import getpass
    author = getpass.getuser()

    properties = {}
    properties['name'] = 'module name'
    properties['author'] = author
    properties['description'] = 'Module description'

    output = StringIO()
    # header
    output.write(
        r"""#!/usr/bin/env python
#
#%s
#
# MODULE:       %s
#
# AUTHOR(S):    %s
#
# PURPOSE:      %s
#
# DATE:         %s
#
#%s
""" % ('#' * 72,
            EncodeString(properties['name']),
            EncodeString(properties['author']),
            EncodeString('\n# '.join(properties['description'].splitlines())),
            time.asctime(),
            '#' * 72))

    # UI
    output.write(
        r"""
#%%module
#%% description: %s
#%%end
""" % (EncodeString(' '.join(properties['description'].splitlines()))))

    # import modules
    output.write(
        r"""
import sys
import os
import atexit

import grass.script as gscript
""")

    # cleanup()
    output.write(
        r"""
RAST_REMOVE = []

def cleanup():
""")
    output.write(
        r"""    gscript.run_command('g.remove', flags='f', type='raster',
                          name=RAST_REMOVE)
""")
    output.write("\ndef main():\n")
    output.write(
        r"""    options, flags = gscript.parser()
    gscript.run_command('g.remove', flags='f', type='raster',
                        name=RAST_REMOVE)
""")

    output.write("\n    return 0\n")

    output.write(
        r"""
if __name__ == "__main__":
    atexit.register(cleanup)
    sys.exit(main())
""")
    return output.getvalue()