Example #1
0
 def OnOptions(self, event):
     """Change histogram settings"""
     cmd = ["d.histogram"]
     if self.mapname != "":
         cmd.append("map=%s" % self.mapname)
     module = GUI(parent=self)
     module.ParseCommand(cmd, completed=(self.GetOptData, None, self.params))
Example #2
0
 def OnAddRGB(self, event):
     """Opens d.rgb dialog and adds layer.
     Dummy layer is added first."""
     cmd = ['d.rgb']
     layer = self.AddRGB(name='', cmd=cmd, hidden=True, dialog=None)
     GUI(parent=self, giface=None, modal=self._modal).ParseCommand(cmd=cmd,
                                                 completed=(self.GetOptData, layer, ''))
     event.Skip()
Example #3
0
 def OnAddRast3d(self, event):
     """Opens d.rast3d dialog and adds layer.
     Dummy layer is added first."""
     cmd = ["d.rast3d"]
     layer = self.AddRast3d(name="", cmd=cmd, hidden=True, dialog=None)
     GUI(parent=self, giface=None,
         modal=self._modal).ParseCommand(cmd=cmd,
                                         completed=(self.GetOptData, layer,
                                                    ""))
     event.Skip()
Example #4
0
    def OnCmdDone(self, event):
        """Command done (or aborted)

        Sends signal mapCreated if map is recognized in output
        parameters or for specific modules (as r.colors).
        """
        # Process results here
        try:
            ctime = time.time() - event.time
            if ctime < 60:
                stime = _("%d sec") % int(ctime)
            else:
                mtime = int(ctime / 60)
                stime = _("%(min)d min %(sec)d sec") % {
                    "min": mtime,
                    "sec": int(ctime - (mtime * 60)),
                }
        except KeyError:
            # stopped deamon
            stime = _("unknown")

        if event.aborted:
            # Thread aborted (using our convention of None return)
            self.WriteWarning(
                _(
                    "Please note that the data are left in"
                    " inconsistent state and may be corrupted"
                )
            )
            msg = _("Command aborted")
        else:
            msg = _("Command finished")

        self.WriteCmdLog(
            "(%s) %s (%s)" % (str(time.ctime()), msg, stime),
            notification=event.notification,
        )

        if event.onDone:
            event.onDone(event)

        self.cmdOutputTimer.Stop()

        if event.cmd[0] == "g.gisenv":
            Debug.SetLevel()
            self.Redirect()

        # do nothing when no map added
        if event.returncode != 0 or event.aborted:
            event.Skip()
            return

        if event.cmd[0] not in globalvar.grassCmd:
            return

        # find which maps were created
        try:
            task = GUI(show=None).ParseCommand(event.cmd)
        except GException as e:
            print(e, file=sys.stderr)
            task = None
            return

        name = task.get_name()
        for p in task.get_options()["params"]:
            prompt = p.get("prompt", "")
            if prompt in ("raster", "vector", "raster_3d") and p.get("value", None):
                if p.get("age", "old") == "new" or name in (
                    "r.colors",
                    "r3.colors",
                    "v.colors",
                    "v.proj",
                    "r.proj",
                ):
                    # if multiple maps (e.g. r.series.interp), we need add each
                    if p.get("multiple", False):
                        lnames = p.get("value").split(",")
                        # in case multiple input (old) maps in r.colors
                        # we don't want to rerender it multiple times! just
                        # once
                        if p.get("age", "old") == "old":
                            lnames = lnames[0:1]
                    else:
                        lnames = [p.get("value")]
                    for lname in lnames:
                        if "@" not in lname:
                            lname += "@" + grass.gisenv()["MAPSET"]
                        if grass.find_file(lname, element=p.get("element"))["fullname"]:
                            self.mapCreated.emit(
                                name=lname, ltype=prompt, add=event.addLayer
                            )
                            gisenv = grass.gisenv()
                            self._giface.grassdbChanged.emit(
                                grassdb=gisenv["GISDBASE"],
                                location=gisenv["LOCATION_NAME"],
                                mapset=gisenv["MAPSET"],
                                action="new",
                                map=lname.split("@")[0],
                                element=prompt,
                            )
        if name == "r.mask":
            action = "new"
            for p in task.get_options()["flags"]:
                if p.get("name") == "r" and p.get("value"):
                    action = "delete"
            gisenv = grass.gisenv()
            self._giface.grassdbChanged.emit(
                grassdb=gisenv["GISDBASE"],
                location=gisenv["LOCATION_NAME"],
                mapset=gisenv["MAPSET"],
                action=action,
                map="MASK",
                element="raster",
            )

        event.Skip()
Example #5
0
    def RunCmd(
        self,
        command,
        compReg=True,
        env=None,
        skipInterface=False,
        onDone=None,
        onPrepare=None,
        userData=None,
        addLayer=None,
        notification=Notification.MAKE_VISIBLE,
    ):
        """Run command typed into console command prompt (GPrompt).

        .. todo::
            Document the other event.
        .. todo::
            Solve problem with the other event (now uses gOutputText
            event but there is no text, use onPrepare handler instead?)
        .. todo::
            Skip interface is ignored and determined always automatically.

        Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
        (according to ignoredCmdPattern) is run.
        For example, see layer manager which handles d.* on its own.

        :param command: command given as a list (produced e.g. by utils.split())
        :param compReg: True use computation region
        :param notification: form of notification
        :param bool skipInterface: True to do not launch GRASS interface
                                   parser when command has no arguments
                                   given
        :param onDone: function to be called when command is finished
        :param onPrepare: function to be called before command is launched
        :param addLayer: to be passed in the mapCreated signal
        :param userData: data defined for the command
        """
        if len(command) == 0:
            Debug.msg(2, "GPrompt:RunCmd(): empty command")
            return

        # update history file
        self.UpdateHistoryFile(" ".join(command))

        if command[0] in globalvar.grassCmd:
            # send GRASS command without arguments to GUI command interface
            # except ignored commands (event is emitted)
            if (
                self._ignoredCmdPattern
                and re.compile(self._ignoredCmdPattern).search(" ".join(command))
                and "--help" not in command
                and "--ui" not in command
            ):
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            else:
                # other GRASS commands (r|v|g|...)
                try:
                    task = GUI(show=None).ParseCommand(command)
                except GException as e:
                    GError(parent=self._guiparent, message=str(e), showTraceback=False)
                    return

                hasParams = False
                if task:
                    options = task.get_options()
                    hasParams = options["params"] and options["flags"]
                    # check for <input>=-
                    for p in options["params"]:
                        if (
                            p.get("prompt", "") == "input"
                            and p.get("element", "") == "file"
                            and p.get("age", "new") == "old"
                            and p.get("value", "") == "-"
                        ):
                            GError(
                                parent=self._guiparent,
                                message=_(
                                    "Unable to run command:\n%(cmd)s\n\n"
                                    "Option <%(opt)s>: read from standard input is not "
                                    "supported by wxGUI"
                                )
                                % {"cmd": " ".join(command), "opt": p.get("name", "")},
                            )
                            return

                if len(command) == 1:
                    if command[0].startswith("g.gui."):
                        import imp
                        import inspect

                        pyFile = command[0]
                        if sys.platform == "win32":
                            pyFile += ".py"
                        pyPath = os.path.join(os.environ["GISBASE"], "scripts", pyFile)
                        if not os.path.exists(pyPath):
                            pyPath = os.path.join(
                                os.environ["GRASS_ADDON_BASE"], "scripts", pyFile
                            )
                        if not os.path.exists(pyPath):
                            GError(
                                parent=self._guiparent,
                                message=_("Module <%s> not found.") % command[0],
                            )
                        pymodule = imp.load_source(command[0].replace(".", "_"), pyPath)
                        try:  # PY3
                            pymain = inspect.getfullargspec(pymodule.main)
                        except AttributeError:
                            pymain = inspect.getargspec(pymodule.main)
                        if pymain and "giface" in pymain.args:
                            pymodule.main(self._giface)
                            return

                    # no arguments given
                    if hasParams and not isinstance(self._guiparent, FormNotebook):
                        # also parent must be checked, see #3135 for details
                        try:
                            GUI(
                                parent=self._guiparent, giface=self._giface
                            ).ParseCommand(command)
                        except GException as e:
                            print(e, file=sys.stderr)

                        return

                if env:
                    env = env.copy()
                else:
                    env = os.environ.copy()
                # activate computational region (set with g.region)
                # for all non-display commands.
                if compReg and "GRASS_REGION" in env:
                    del env["GRASS_REGION"]

                # process GRASS command with argument
                self.cmdThread.RunCmd(
                    command,
                    stdout=self.cmdStdOut,
                    stderr=self.cmdStdErr,
                    onDone=onDone,
                    onPrepare=onPrepare,
                    userData=userData,
                    addLayer=addLayer,
                    env=env,
                    notification=notification,
                )
                self.cmdOutputTimer.Start(50)

                # we don't need to change computational region settings
                # because we work on a copy
        else:
            # Send any other command to the shell. Send output to
            # console output window
            #
            # Check if the script has an interface (avoid double-launching
            # of the script)

            # check if we ignore the command (similar to grass commands part)
            if self._ignoredCmdPattern and re.compile(self._ignoredCmdPattern).search(
                " ".join(command)
            ):
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            skipInterface = True
            if os.path.splitext(command[0])[1] in (".py", ".sh"):
                try:
                    sfile = open(command[0], "r")
                    for line in sfile.readlines():
                        if len(line) < 2:
                            continue
                        if line[0] == "#" and line[1] == "%":
                            skipInterface = False
                            break
                    sfile.close()
                except IOError:
                    pass

            if len(command) == 1 and not skipInterface:
                try:
                    task = gtask.parse_interface(command[0])
                except:
                    task = None
            else:
                task = None

            if task:
                # process GRASS command without argument
                GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
            else:
                self.cmdThread.RunCmd(
                    command,
                    stdout=self.cmdStdOut,
                    stderr=self.cmdStdErr,
                    onDone=onDone,
                    onPrepare=onPrepare,
                    userData=userData,
                    addLayer=addLayer,
                    env=env,
                    notification=notification,
                )
            self.cmdOutputTimer.Start(50)
Example #6
0
    def run(self):
        os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
        while True:
            requestId, args, kwds = self.requestQ.get()
            for key in (
                "callable",
                "onDone",
                "onPrepare",
                "userData",
                "addLayer",
                "notification",
            ):
                if key in kwds:
                    vars()[key] = kwds[key]
                    del kwds[key]
                else:
                    vars()[key] = None

            if not vars()["callable"]:
                vars()["callable"] = GrassCmd

            requestTime = time.time()

            # prepare
            if self.receiver:
                event = wxCmdPrepare(
                    cmd=args[0],
                    time=requestTime,
                    pid=requestId,
                    onPrepare=vars()["onPrepare"],
                    userData=vars()["userData"],
                )

                wx.PostEvent(self.receiver, event)

                # run command
                event = wxCmdRun(
                    cmd=args[0], pid=requestId, notification=vars()["notification"]
                )

                wx.PostEvent(self.receiver, event)

            time.sleep(0.1)
            self.requestCmd = vars()["callable"](*args, **kwds)
            if self._want_abort_all and self.requestCmd is not None:
                self.requestCmd.abort()
                if self.requestQ.empty():
                    self._want_abort_all = False

            self.resultQ.put((requestId, self.requestCmd.run()))

            try:
                returncode = self.requestCmd.module.returncode
            except AttributeError:
                returncode = 0  # being optimistic

            try:
                aborted = self.requestCmd.aborted
            except AttributeError:
                aborted = False

            time.sleep(0.1)

            # set default color table for raster data
            if (
                UserSettings.Get(
                    group="rasterLayer", key="colorTable", subkey="enabled"
                )
                and args[0][0][:2] == "r."
            ):
                colorTable = UserSettings.Get(
                    group="rasterLayer", key="colorTable", subkey="selection"
                )
                mapName = None
                if args[0][0] == "r.mapcalc":
                    try:
                        mapName = args[0][1].split("=", 1)[0].strip()
                    except KeyError:
                        pass
                else:
                    moduleInterface = GUI(show=None).ParseCommand(args[0])
                    outputParam = moduleInterface.get_param(
                        value="output", raiseError=False
                    )
                    if outputParam and outputParam["prompt"] == "raster":
                        mapName = outputParam["value"]

                if mapName:
                    argsColor = list(args)
                    argsColor[0] = [
                        "r.colors",
                        "map=%s" % mapName,
                        "color=%s" % colorTable,
                    ]
                    self.requestCmdColor = vars()["callable"](*argsColor, **kwds)
                    self.resultQ.put((requestId, self.requestCmdColor.run()))

            if self.receiver:
                event = wxCmdDone(
                    cmd=args[0],
                    aborted=aborted,
                    returncode=returncode,
                    time=requestTime,
                    pid=requestId,
                    onDone=vars()["onDone"],
                    userData=vars()["userData"],
                    addLayer=vars()["addLayer"],
                    notification=vars()["notification"],
                )

                # send event
                wx.PostEvent(self.receiver, event)
Example #7
0
 def OnAddRGB(self, event):
     cmd = ['d.rgb']
     GUI(parent=self.parent).ParseCommand(cmd,
                                          completed=(self.GetOptData, '',
                                                     ''))
Example #8
0
    def RunCmd(self, command, compReg=True, env=None, skipInterface=False,
               onDone=None, onPrepare=None, userData=None, addLayer=None,
               notification=Notification.MAKE_VISIBLE):
        """Run command typed into console command prompt (GPrompt).

        .. todo::
            Document the other event.
        .. todo::
            Solve problem with the other event (now uses gOutputText
            event but there is no text, use onPrepare handler instead?)
        .. todo::
            Skip interface is ignored and determined always automatically.

        Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
        (according to ignoredCmdPattern) is run.
        For example, see layer manager which handles d.* on its own.

        :param command: command given as a list (produced e.g. by utils.split())
        :param compReg: True use computation region
        :param notification: form of notification
        :param bool skipInterface: True to do not launch GRASS interface
                                   parser when command has no arguments
                                   given
        :param onDone: function to be called when command is finished
        :param onPrepare: function to be called before command is launched
        :param addLayer: to be passed in the mapCreated signal
        :param userData: data defined for the command
        """
        if len(command) == 0:
            Debug.msg(2, "GPrompt:RunCmd(): empty command")
            return

        # update history file
        self.UpdateHistoryFile(' '.join(command))

        if command[0] in globalvar.grassCmd:
            # send GRASS command without arguments to GUI command interface
            # except ignored commands (event is emitted)
            if self._ignoredCmdPattern and \
                    re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
                    '--help' not in command and '--ui' not in command:
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            else:
                # other GRASS commands (r|v|g|...)
                try:
                    task = GUI(show=None).ParseCommand(command)
                except GException as e:
                    GError(parent=self._guiparent,
                           message=unicode(e),
                           showTraceback=False)
                    return

                hasParams = False
                if task:
                    options = task.get_options()
                    hasParams = options['params'] and options['flags']
                    # check for <input>=-
                    for p in options['params']:
                        if p.get('prompt', '') == 'input' and \
                                p.get('element', '') == 'file' and \
                                p.get('age', 'new') == 'old' and \
                                p.get('value', '') == '-':
                            GError(
                                parent=self._guiparent,
                                message=_(
                                    "Unable to run command:\n%(cmd)s\n\n"
                                    "Option <%(opt)s>: read from standard input is not "
                                    "supported by wxGUI") % {
                                    'cmd': ' '.join(command),
                                    'opt': p.get(
                                        'name',
                                        '')})
                            return

                if len(command) == 1:
                    if command[0].startswith('g.gui.'):
                        import imp
                        import inspect
                        pyFile = command[0]
                        if sys.platform == 'win32':
                            pyFile += '.py'
                        pyPath = os.path.join(
                            os.environ['GISBASE'], 'scripts', pyFile)
                        if not os.path.exists(pyPath):
                            pyPath = os.path.join(
                                os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile)
                        if not os.path.exists(pyPath):
                            GError(
                                parent=self._guiparent,
                                message=_("Module <%s> not found.") %
                                command[0])
                        pymodule = imp.load_source(
                            command[0].replace('.', '_'), pyPath)
                        pymain = inspect.getargspec(pymodule.main)
                        if pymain and 'giface' in pymain.args:
                            pymodule.main(self._giface)
                            return

                    # no arguments given
                    if hasParams and \
                       not isinstance(self._guiparent, FormNotebook):
                        # also parent must be checked, see #3135 for details
                        try:
                            GUI(parent=self._guiparent,
                                giface=self._giface).ParseCommand(command)
                        except GException as e:
                            print >> sys.stderr, e

                        return

                if env:
                    env = env.copy()
                else:
                    env = os.environ.copy()
                # activate computational region (set with g.region)
                # for all non-display commands.
                if compReg and "GRASS_REGION" in env:
                    del env["GRASS_REGION"]

                # process GRASS command with argument
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone, onPrepare=onPrepare,
                                      userData=userData, addLayer=addLayer,
                                      env=env,
                                      notification=notification)
                self.cmdOutputTimer.Start(50)

                # we don't need to change computational region settings
                # because we work on a copy
        else:
            # Send any other command to the shell. Send output to
            # console output window
            #
            # Check if the script has an interface (avoid double-launching
            # of the script)

            # check if we ignore the command (similar to grass commands part)
            if self._ignoredCmdPattern and \
               re.compile(self._ignoredCmdPattern).search(' '.join(command)):
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            skipInterface = True
            if os.path.splitext(command[0])[1] in ('.py', '.sh'):
                try:
                    sfile = open(command[0], "r")
                    for line in sfile.readlines():
                        if len(line) < 2:
                            continue
                        if line[0] is '#' and line[1] is '%':
                            skipInterface = False
                            break
                    sfile.close()
                except IOError:
                    pass

            if len(command) == 1 and not skipInterface:
                try:
                    task = gtask.parse_interface(command[0])
                except:
                    task = None
            else:
                task = None

            if task:
                # process GRASS command without argument
                GUI(parent=self._guiparent,
                    giface=self._giface).ParseCommand(command)
            else:
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone, onPrepare=onPrepare,
                                      userData=userData, addLayer=addLayer,
                                      env=env,
                                      notification=notification)
            self.cmdOutputTimer.Start(50)
Example #9
0
    def RunCmd(self, command, compReg=True, skipInterface=False,
               onDone=None, onPrepare=None, userData=None, notification=Notification.MAKE_VISIBLE):
        """Run command typed into console command prompt (GPrompt).

        .. todo::
            Document the other event.
        .. todo::
            Solve problem with the other event (now uses gOutputText
            event but there is no text, use onPrepare handler instead?)

        Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
        (according to ignoredCmdPattern) is run.
        For example, see layer manager which handles d.* on its own.

        :param command: command given as a list (produced e.g. by utils.split())
        :param compReg: True use computation region
        :param notification: form of notification
        :param bool skipInterface: True to do not launch GRASS interface
                                   parser when command has no arguments
                                   given
        :param onDone: function to be called when command is finished
        :param onPrepare: function to be called before command is launched
        :param userData: data defined for the command
        """
        if len(command) == 0:
            Debug.msg(2, "GPrompt:RunCmd(): empty command")
            return

        # update history file
        self.UpdateHistoryFile(' '.join(command))
        
        if command[0] in globalvar.grassCmd:
            # send GRASS command without arguments to GUI command interface
            # except ignored commands (event is emitted)

            if self._ignoredCmdPattern and \
              re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
              '--help' not in command and '--ui' not in command:
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return
            
            else:
                # other GRASS commands (r|v|g|...)
                try:
                    task = GUI(show=None).ParseCommand(command)
                except GException as e:
                    GError(parent=self._guiparent,
                           message=unicode(e),
                           showTraceback=False)
                    return

                hasParams = False
                if task:
                    options = task.get_options()
                    hasParams = options['params'] and options['flags']
                    # check for <input>=-
                    for p in options['params']:
                        if p.get('prompt', '') == 'input' and \
                                p.get('element', '') == 'file' and \
                                p.get('age', 'new') == 'old' and \
                                p.get('value', '') == '-':
                            GError(parent=self._guiparent,
                                   message=_("Unable to run command:\n%(cmd)s\n\n"
                                             "Option <%(opt)s>: read from standard input is not "
                                             "supported by wxGUI") % {'cmd': ' '.join(command),
                                                                      'opt': p.get('name', '')})
                            return

                if len(command) == 1 and hasParams and \
                        command[0] != 'v.krige':
                    # no arguments given
                    try:
                        GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
                    except GException as e:
                        print >> sys.stderr, e
                    return

                # activate computational region (set with g.region)
                # for all non-display commands.
                if compReg:
                    tmpreg = os.getenv("GRASS_REGION")
                    if "GRASS_REGION" in os.environ:
                        del os.environ["GRASS_REGION"]

                # process GRASS command with argument
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone, onPrepare=onPrepare,
                                      userData=userData,
                                      env=os.environ.copy(),
                                      notification=notification)
                self.cmdOutputTimer.Start(50)

                # deactivate computational region and return to display settings
                if compReg and tmpreg:
                    os.environ["GRASS_REGION"] = tmpreg
        else:
            # Send any other command to the shell. Send output to
            # console output window
            #
            # Check if the script has an interface (avoid double-launching
            # of the script)

            # check if we ignore the command (similar to grass commands part)
            if self._ignoredCmdPattern and \
               re.compile(self._ignoredCmdPattern).search(' '.join(command)):
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            skipInterface = True
            if os.path.splitext(command[0])[1] in ('.py', '.sh'):
                try:
                    sfile = open(command[0], "r")
                    for line in sfile.readlines():
                        if len(line) < 2:
                            continue
                        if line[0] is '#' and line[1] is '%':
                            skipInterface = False
                            break
                    sfile.close()
                except IOError:
                    pass
            
            if len(command) == 1 and not skipInterface:
                try:
                    task = gtask.parse_interface(command[0])
                except:
                    task = None
            else:
                task = None

            if task:
                # process GRASS command without argument
                GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
            else:
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone, onPrepare=onPrepare,
                                      userData=userData,
                                      notification=notification)
            self.cmdOutputTimer.Start(50)
Example #10
0
 def OnCmdDialog(self, event):
     """!Shows command dialog"""
     GUI(parent = self).ParseCommand(cmd = ['g.extension.py'])
Example #11
0
 def OnCmdDialog(self, event):
     """!Shows command dialog"""
     GUI(parent = self).ParseCommand(cmd = self._getCmd())
Example #12
0
 def _layerChangeProperties(self, layer):
     """Opens new module dialog or recycles it."""
     GUI(parent=self, giface=None,
         modal=self._modal).ParseCommand(cmd=layer.cmd,
                                         completed=(self.GetOptData, layer,
                                                    ""))
Example #13
0
 def OnAddRGB(self, event):
     cmd = ["d.rgb"]
     GUI(parent=self.parent).ParseCommand(cmd, completed=(self.GetOptData, "", ""))
Example #14
0
 def GuiParseCommand(self, cmd):
     """Generic handler"""
     GUI(parent=self, giface=self.giface).ParseCommand(cmd=[cmd])
Example #15
0
    def run(self):
        os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
        while True:
            requestId, args, kwds = self.requestQ.get()
            for key in ('callable', 'onDone', 'onPrepare', 'userData',
                        'addLayer', 'notification'):
                if key in kwds:
                    vars()[key] = kwds[key]
                    del kwds[key]
                else:
                    vars()[key] = None

            if not vars()['callable']:
                vars()['callable'] = GrassCmd

            requestTime = time.time()

            # prepare
            if self.receiver:
                event = wxCmdPrepare(cmd=args[0],
                                     time=requestTime,
                                     pid=requestId,
                                     onPrepare=vars()['onPrepare'],
                                     userData=vars()['userData'])

                wx.PostEvent(self.receiver, event)

                # run command
                event = wxCmdRun(cmd=args[0],
                                 pid=requestId,
                                 notification=vars()['notification'])

                wx.PostEvent(self.receiver, event)

            time.sleep(.1)
            self.requestCmd = vars()['callable'](*args, **kwds)
            if self._want_abort_all and self.requestCmd is not None:
                self.requestCmd.abort()
                if self.requestQ.empty():
                    self._want_abort_all = False

            self.resultQ.put((requestId, self.requestCmd.run()))

            try:
                returncode = self.requestCmd.module.returncode
            except AttributeError:
                returncode = 0  # being optimistic

            try:
                aborted = self.requestCmd.aborted
            except AttributeError:
                aborted = False

            time.sleep(.1)

            # set default color table for raster data
            if UserSettings.Get(group='rasterLayer',
                                key='colorTable', subkey='enabled') and \
                    args[0][0][:2] == 'r.':
                colorTable = UserSettings.Get(group='rasterLayer',
                                              key='colorTable',
                                              subkey='selection')
                mapName = None
                if args[0][0] == 'r.mapcalc':
                    try:
                        mapName = args[0][1].split('=', 1)[0].strip()
                    except KeyError:
                        pass
                else:
                    moduleInterface = GUI(show=None).ParseCommand(args[0])
                    outputParam = moduleInterface.get_param(value='output',
                                                            raiseError=False)
                    if outputParam and outputParam['prompt'] == 'raster':
                        mapName = outputParam['value']

                if mapName:
                    argsColor = list(args)
                    argsColor[0] = [
                        'r.colors',
                        'map=%s' % mapName,
                        'color=%s' % colorTable
                    ]
                    self.requestCmdColor = vars()['callable'](*argsColor,
                                                              **kwds)
                    self.resultQ.put((requestId, self.requestCmdColor.run()))

            if self.receiver:
                event = wxCmdDone(cmd=args[0],
                                  aborted=aborted,
                                  returncode=returncode,
                                  time=requestTime,
                                  pid=requestId,
                                  onDone=vars()['onDone'],
                                  userData=vars()['userData'],
                                  addLayer=vars()['addLayer'],
                                  notification=vars()['notification'])

                # send event
                wx.PostEvent(self.receiver, event)
Example #16
0
    def run(self):
        os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
        while True:
            requestId, args, kwds = self.requestQ.get()
            for key in ('callable', 'onDone', 'onPrepare', 'userData', 'notification'):
                if key in kwds:
                    vars()[key] = kwds[key]
                    del kwds[key]
                else:
                    vars()[key] = None

            if not vars()['callable']:
                vars()['callable'] = GrassCmd

            requestTime = time.time()

            # prepare
            if self.receiver:
                event = wxCmdPrepare(cmd=args[0],
                                     time=requestTime,
                                     pid=requestId,
                                     onPrepare=vars()['onPrepare'],
                                     userData=vars()['userData'])

                wx.PostEvent(self.receiver, event)

                # run command
                event = wxCmdRun(cmd=args[0],
                                 pid=requestId,
                                 notification=vars()['notification'])

                wx.PostEvent(self.receiver, event)

            time.sleep(.1)
            self.requestCmd = vars()['callable'](*args, **kwds)
            if self._want_abort_all and self.requestCmd is not None:
                self.requestCmd.abort()
                if self.requestQ.empty():
                    self._want_abort_all = False

            self.resultQ.put((requestId, self.requestCmd.run()))

            try:
                returncode = self.requestCmd.module.returncode
            except AttributeError:
                returncode = 0  # being optimistic

            try:
                aborted = self.requestCmd.aborted
            except AttributeError:
                aborted = False

            time.sleep(.1)

            # set default color table for raster data
            if UserSettings.Get(group='rasterLayer',
                                key='colorTable', subkey='enabled') and \
                    args[0][0][:2] == 'r.':
                colorTable = UserSettings.Get(group='rasterLayer',
                                              key='colorTable',
                                              subkey='selection')
                mapName = None
                if args[0][0] == 'r.mapcalc':
                    try:
                        mapName = args[0][1].split('=', 1)[0].strip()
                    except KeyError:
                        pass
                else:
                    moduleInterface = GUI(show=None).ParseCommand(args[0])
                    outputParam = moduleInterface.get_param(value='output',
                                                            raiseError=False)
                    if outputParam and outputParam['prompt'] == 'raster':
                        mapName = outputParam['value']

                if mapName:
                    argsColor = list(args)
                    argsColor[0] = ['r.colors',
                                    'map=%s' % mapName,
                                    'color=%s' % colorTable]
                    self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
                    self.resultQ.put((requestId, self.requestCmdColor.run()))

            if self.receiver:
                event = wxCmdDone(cmd=args[0],
                                  aborted=aborted,
                                  returncode=returncode,
                                  time=requestTime,
                                  pid=requestId,
                                  onDone=vars()['onDone'],
                                  userData=vars()['userData'],
                                  notification=vars()['notification'])

                # send event
                wx.PostEvent(self.receiver, event)
Example #17
0
    def OnCmdDone(self, event):
        """Command done (or aborted)

        Sends signal mapCreated if map is recognized in output
        parameters or for specific modules (as r.colors).
        """
        # Process results here
        try:
            ctime = time.time() - event.time
            if ctime < 60:
                stime = _("%d sec") % int(ctime)
            else:
                mtime = int(ctime / 60)
                stime = _("%(min)d min %(sec)d sec") % {
                    'min': mtime,
                    'sec': int(ctime - (mtime * 60))
                }
        except KeyError:
            # stopped deamon
            stime = _("unknown")

        if event.aborted:
            # Thread aborted (using our convention of None return)
            self.WriteWarning(
                _('Please note that the data are left in'
                  ' inconsistent state and may be corrupted'))
            msg = _('Command aborted')
        else:
            msg = _('Command finished')

        self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime),
                         notification=event.notification)

        if event.onDone:
            event.onDone(event)

        self.cmdOutputTimer.Stop()

        if event.cmd[0] == 'g.gisenv':
            Debug.SetLevel()
            self.Redirect()

        # do nothing when no map added
        if event.returncode != 0 or event.aborted:
            event.Skip()
            return

        if event.cmd[0] not in globalvar.grassCmd:
            return

        # find which maps were created
        try:
            task = GUI(show=None).ParseCommand(event.cmd)
        except GException as e:
            print(e, file=sys.stderr)
            task = None
            return

        name = task.get_name()
        for p in task.get_options()['params']:
            prompt = p.get('prompt', '')
            if prompt in ('raster', 'vector', 'raster_3d') and p.get(
                    'value', None):
                if p.get('age',
                         'old') == 'new' or name in ('r.colors', 'r3.colors',
                                                     'v.colors', 'v.proj',
                                                     'r.proj'):
                    # if multiple maps (e.g. r.series.interp), we need add each
                    if p.get('multiple', False):
                        lnames = p.get('value').split(',')
                        # in case multiple input (old) maps in r.colors
                        # we don't want to rerender it multiple times! just
                        # once
                        if p.get('age', 'old') == 'old':
                            lnames = lnames[0:1]
                    else:
                        lnames = [p.get('value')]
                    for lname in lnames:
                        if '@' not in lname:
                            lname += '@' + grass.gisenv()['MAPSET']
                        if grass.find_file(
                                lname, element=p.get('element'))['fullname']:
                            self.mapCreated.emit(name=lname,
                                                 ltype=prompt,
                                                 add=event.addLayer)
        if name == 'r.mask':
            self.updateMap.emit()

        event.Skip()
Example #18
0
    def OnCmdDone(self, event):
        """Command done (or aborted)

        Sends signal mapCreated if map is recognized in output
        parameters or for specific modules (as r.colors).
        """
        # Process results here
        try:
            ctime = time.time() - event.time
            if ctime < 60:
                stime = _("%d sec") % int(ctime)
            else:
                mtime = int(ctime / 60)
                stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
                                                        'sec': int(ctime - (mtime * 60))}
        except KeyError:
            # stopped deamon
            stime = _("unknown")

        if event.aborted:
            # Thread aborted (using our convention of None return)
            self.WriteWarning(_('Please note that the data are left in'
                                ' inconsistent state and may be corrupted'))
            msg = _('Command aborted')
        else:
            msg = _('Command finished')

        self.WriteCmdLog('(%s) %s (%s)' % (str(time.ctime()), msg, stime),
                         notification=event.notification)

        if event.onDone:
            event.onDone(cmd=event.cmd, returncode=event.returncode)

        self.cmdOutputTimer.Stop()

        if event.cmd[0] == 'g.gisenv':
            Debug.SetLevel()
            self.Redirect()

        # do nothing when no map added
        if event.returncode != 0 or event.aborted:
            event.Skip()
            return

        if event.cmd[0] not in globalvar.grassCmd:
            return

        # find which maps were created
        try:
            task = GUI(show=None).ParseCommand(event.cmd)
        except GException as e:
            print >> sys.stderr, e
            task = None
            return

        name = task.get_name()
        for p in task.get_options()['params']:
            prompt = p.get('prompt', '')
            if prompt in ('raster', 'vector', '3d-raster') and p.get('value', None):
                if p.get('age', 'old') == 'new' or \
                        name in ('r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
                    # if multiple maps (e.g. r.series.interp), we need add each
                    if p.get('multiple', False):
                        lnames = p.get('value').split(',')
                        # in case multiple input (old) maps in r.colors
                        # we don't want to rerender it multiple times! just once
                        if p.get('age', 'old') == 'old':
                            lnames = lnames[0:1]
                    else:
                        lnames = [p.get('value')]
                    for lname in lnames:
                        if '@' not in lname:
                            lname += '@' + grass.gisenv()['MAPSET']
                        self.mapCreated.emit(name=lname, ltype=prompt)
        if name == 'r.mask':
            self.updateMap.emit()
        
        event.Skip()
Example #19
0
    def RunCmd(self,
               command,
               compReg=True,
               skipInterface=False,
               onDone=None,
               onPrepare=None,
               userData=None,
               addLayer=None,
               notification=Notification.MAKE_VISIBLE):
        """Run command typed into console command prompt (GPrompt).

        .. todo::
            Document the other event.
        .. todo::
            Solve problem with the other event (now uses gOutputText
            event but there is no text, use onPrepare handler instead?)

        Posts event EVT_IGNORED_CMD_RUN when command which should be ignored
        (according to ignoredCmdPattern) is run.
        For example, see layer manager which handles d.* on its own.

        :param command: command given as a list (produced e.g. by utils.split())
        :param compReg: True use computation region
        :param notification: form of notification
        :param bool skipInterface: True to do not launch GRASS interface
                                   parser when command has no arguments
                                   given
        :param onDone: function to be called when command is finished
        :param onPrepare: function to be called before command is launched
        :param addLayer: to be passed in the mapCreated signal
        :param userData: data defined for the command
        """
        if len(command) == 0:
            Debug.msg(2, "GPrompt:RunCmd(): empty command")
            return

        # update history file
        self.UpdateHistoryFile(' '.join(command))

        if command[0] in globalvar.grassCmd:
            # send GRASS command without arguments to GUI command interface
            # except ignored commands (event is emitted)
            if self._ignoredCmdPattern and \
              re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
              '--help' not in command and '--ui' not in command:
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            else:
                # other GRASS commands (r|v|g|...)
                try:
                    task = GUI(show=None).ParseCommand(command)
                except GException as e:
                    GError(parent=self._guiparent,
                           message=unicode(e),
                           showTraceback=False)
                    return

                hasParams = False
                if task:
                    options = task.get_options()
                    hasParams = options['params'] and options['flags']
                    # check for <input>=-
                    for p in options['params']:
                        if p.get('prompt', '') == 'input' and \
                                p.get('element', '') == 'file' and \
                                p.get('age', 'new') == 'old' and \
                                p.get('value', '') == '-':
                            GError(
                                parent=self._guiparent,
                                message=
                                _("Unable to run command:\n%(cmd)s\n\n"
                                  "Option <%(opt)s>: read from standard input is not "
                                  "supported by wxGUI") % {
                                      'cmd': ' '.join(command),
                                      'opt': p.get('name', '')
                                  })
                            return

                if len(command) == 1:
                    if command[0].startswith('g.gui.'):
                        import imp
                        import inspect
                        pyFile = command[0]
                        if sys.platform == 'win32':
                            pyFile += '.py'
                        pyPath = os.path.join(os.environ['GISBASE'], 'scripts',
                                              pyFile)
                        if not os.path.exists(pyPath):
                            pyPath = os.path.join(
                                os.environ['GRASS_ADDON_BASE'], 'scripts',
                                pyFile)
                        if not os.path.exists(pyPath):
                            GError(parent=self._guiparent,
                                   message=_("Module <%s> not found.") %
                                   command[0])
                        pymodule = imp.load_source(
                            command[0].replace('.', '_'), pyPath)
                        pymain = inspect.getargspec(pymodule.main)
                        if pymain and 'giface' in pymain.args:
                            pymodule.main(self._giface)
                            return

                    if hasParams and command[0] != 'v.krige':
                        # no arguments given
                        try:
                            GUI(parent=self._guiparent,
                                giface=self._giface).ParseCommand(command)
                        except GException as e:
                            print >> sys.stderr, e

                        return

                # activate computational region (set with g.region)
                # for all non-display commands.
                if compReg:
                    tmpreg = os.getenv("GRASS_REGION")
                    if "GRASS_REGION" in os.environ:
                        del os.environ["GRASS_REGION"]

                # process GRASS command with argument
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone,
                                      onPrepare=onPrepare,
                                      userData=userData,
                                      addLayer=addLayer,
                                      env=os.environ.copy(),
                                      notification=notification)
                self.cmdOutputTimer.Start(50)

                # deactivate computational region and return to display settings
                if compReg and tmpreg:
                    os.environ["GRASS_REGION"] = tmpreg
        else:
            # Send any other command to the shell. Send output to
            # console output window
            #
            # Check if the script has an interface (avoid double-launching
            # of the script)

            # check if we ignore the command (similar to grass commands part)
            if self._ignoredCmdPattern and \
               re.compile(self._ignoredCmdPattern).search(' '.join(command)):
                event = gIgnoredCmdRun(cmd=command)
                wx.PostEvent(self, event)
                return

            skipInterface = True
            if os.path.splitext(command[0])[1] in ('.py', '.sh'):
                try:
                    sfile = open(command[0], "r")
                    for line in sfile.readlines():
                        if len(line) < 2:
                            continue
                        if line[0] is '#' and line[1] is '%':
                            skipInterface = False
                            break
                    sfile.close()
                except IOError:
                    pass

            if len(command) == 1 and not skipInterface:
                try:
                    task = gtask.parse_interface(command[0])
                except:
                    task = None
            else:
                task = None

            if task:
                # process GRASS command without argument
                GUI(parent=self._guiparent,
                    giface=self._giface).ParseCommand(command)
            else:
                self.cmdThread.RunCmd(command,
                                      stdout=self.cmdStdOut,
                                      stderr=self.cmdStdErr,
                                      onDone=onDone,
                                      onPrepare=onPrepare,
                                      userData=userData,
                                      addLayer=addLayer,
                                      notification=notification)
            self.cmdOutputTimer.Start(50)