Esempio n. 1
0
    def _onLeftDown(self, event):
        """Left mouse button donw - vector digitizer various actions"""
        try:
            mapLayer = self.toolbar.GetLayer().GetName()
        except:
            GMessage(parent=self,
                     message=_("No vector map selected for editing."))
            event.Skip()
            return

        action = self.toolbar.GetAction()

        if not action:
            GMessage(
                parent=self,
                message=_("Nothing to do. "
                          "Choose appropriate tool from digitizer toolbar."),
            )
            event.Skip()
            return

        if action not in ("moveVertex", "addVertex", "removeVertex",
                          "editLine"):
            # set pen
            self.pen = wx.Pen(
                colour=UserSettings.Get(group="vdigit",
                                        key="symbol",
                                        subkey=["newSegment", "color"]),
                width=2,
                style=wx.SHORT_DASH,
            )
            self.polypen = wx.Pen(
                colour=UserSettings.Get(group="vdigit",
                                        key="symbol",
                                        subkey=["newLine", "color"]),
                width=2,
                style=wx.SOLID,
            )

        if action in ("addVertex", "removeVertex", "splitLines"):
            # unselect
            self.digit.GetDisplay().SetSelected([])

        if action == "addLine":
            self.OnLeftDownAddLine(event)

        elif action == "editLine" and hasattr(self, "moveInfo"):
            self.OnLeftDownEditLine(event)

        elif action in ("moveLine", "moveVertex",
                        "editLine") and not hasattr(self, "moveInfo"):
            self.OnLeftDownMoveLine(event)

        elif action in ("displayAttrs" "displayCats"):
            self.OnLeftDownDisplayCA(event)

        elif action in ("copyCats", "copyAttrs"):
            self.OnLeftDownCopyCA(event)

        elif action == "copyLine":
            self.OnLeftDownCopyLine(event)

        elif action == "zbulkLine":
            self.OnLeftDownBulkLine(event)
Esempio n. 2
0
File: base.py Progetto: seyi/grass
    def InitRasterOpts(self, rasterList, plottype):
        """Initialize or update raster dictionary for plotting
        """

        rdict = {}  # initialize a dictionary
        self.properties['raster'] = UserSettings.Get(group=self.plottype,
                                                     key='raster')

        for r in rasterList:
            idx = rasterList.index(r)

            try:
                ret = grass.raster_info(r)
            except:
                continue
                # if r.info cannot parse map, skip it

            self.raster[r] = self.properties['raster']  # some default settings
            rdict[r] = {
            }  # initialize sub-dictionaries for each raster in the list

            rdict[r]['units'] = ''
            if ret['units'] not in ('(none)', '"none"', '', None):
                rdict[r]['units'] = ret['units']

            rdict[r]['plegend'] = r  # use fully-qualified names
            # list of cell value,frequency pairs for plotting histogram
            rdict[r]['datalist'] = []
            rdict[r]['pline'] = None
            rdict[r]['datatype'] = ret['datatype']

            #
            # initialize with saved values
            #
            if self.properties['raster']['pwidth'] is not None:
                rdict[r]['pwidth'] = self.properties['raster']['pwidth']
            else:
                rdict[r]['pwidth'] = 1

            if self.properties['raster']['pstyle'] is not None and \
                    self.properties['raster']['pstyle'] != '':
                rdict[r]['pstyle'] = self.properties['raster']['pstyle']
            else:
                rdict[r]['pstyle'] = 'solid'

            if idx < len(self.colorList):
                if idx == 0:
                    # use saved color for first plot
                    if self.properties['raster']['pcolor'] is not None:
                        rdict[r]['pcolor'] = self.properties['raster'][
                            'pcolor']
                    else:
                        rdict[r]['pcolor'] = self.colorDict[
                            self.colorList[idx]]
                else:
                    rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
            else:
                r = randint(0, 255)
                b = randint(0, 255)
                g = randint(0, 255)
                rdict[r]['pcolor'] = ((r, g, b, 255))

        return rdict
Esempio n. 3
0
def main():
    """Sets the GRASS display driver
    """
    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

    # TODO: message format should not be GUI
    # TODO: should messages here be translatable?
    # (for test its great, for translator not)

    options, flags = grass.parser()
    test = options['test']

    app = wx.App()
    map_ = Map()

    if options['raster']:
        names = options['raster']
        for name in names.split(','):
            cmdlist = ['d.rast', 'map=%s' % name]
            map_.AddLayer(ltype='raster',
                          command=cmdlist,
                          active=True,
                          name=name,
                          hidden=False,
                          opacity=1.0,
                          render=True)
    if options['vector']:
        names = options['vector']
        for name in names.split(','):
            cmdlist = ['d.vect', 'map=%s' % name]
            map_.AddLayer(ltype='vector',
                          command=cmdlist,
                          active=True,
                          name=name,
                          hidden=False,
                          opacity=1.0,
                          render=True)

    giface = MapdispGrassInterface(map_=map_)
    tester = Tester()

    if test == 'mapwindow':
        tester.testMapWindow(giface, map_)
    elif test == 'mapdisplay':
        tester.testMapDisplay(giface, map_)
    elif test == 'apitest':
        tester.testMapWindowApi(giface, map_)
    elif test == 'distance':
        tester.testMapWindowDistance(giface, map_)
    elif test == 'profile':
        tester.testMapWindowProfile(giface, map_)
    elif test == 'rlisetup':
        tester.testMapWindowRlisetup(map_)
    else:
        # TODO: this should not happen but happens
        import grass.script as sgrass
        sgrass.fatal(_("Unknown value %s of test parameter." % test))

    app.MainLoop()
Esempio n. 4
0
    def StartEditing(self, mapLayer):
        """Start editing selected vector map layer.

        :param mapLayer: MapLayer to be edited
        """
        # check if topology is available (skip for hidden - temporary
        # maps, see iclass for details)
        if (not mapLayer.IsHidden()
                and grass.vector_info(mapLayer.GetName())["level"] != 2):
            dlg = wx.MessageDialog(
                parent=self.MapWindow,
                message=
                _("Topology for vector map <%s> is not available. "
                  "Topology is required by digitizer.\nDo you want to "
                  "rebuild topology (takes some time) and open the vector map "
                  "for editing?") % mapLayer.GetName(),
                caption=_("Digitizer error"),
                style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION
                | wx.CENTRE,
            )
            if dlg.ShowModal() == wx.ID_YES:
                RunCommand("v.build", map=mapLayer.GetName())
            else:
                return

        # deactive layer
        self.Map.ChangeLayerActive(mapLayer, False)

        # clean map canvas
        self.MapWindow.EraseMap()

        # unset background map if needed
        if mapLayer:
            if (UserSettings.Get(
                    group="vdigit",
                    key="bgmap",
                    subkey="value",
                    settings_type="internal",
            ) == mapLayer.GetName()):
                UserSettings.Set(
                    group="vdigit",
                    key="bgmap",
                    subkey="value",
                    value="",
                    settings_type="internal",
                )

            self.parent.SetStatusText(
                _("Please wait, "
                  "opening vector map <%s> for editing...") %
                mapLayer.GetName(),
                0,
            )

        self.MapWindow.pdcVector = PseudoDC()
        self.digit = self.MapWindow.digit = self.digitClass(
            giface=self._giface, mapwindow=self.MapWindow)

        self.mapLayer = mapLayer
        # open vector map (assume that 'hidden' map layer is temporary vector
        # map)
        if self.digit.OpenMap(mapLayer.GetName(),
                              tmp=mapLayer.IsHidden()) is None:
            self.mapLayer = None
            self.StopEditing()
            return False

        # check feature type (only for OGR layers)
        self.fType = self.digit.GetFeatureType()
        self.EnableAll()
        self.EnableUndo(False)
        self.EnableRedo(False)

        if self.fType == "point":
            for tool in (
                    self.addLine,
                    self.addArea,
                    self.moveVertex,
                    self.addVertex,
                    self.removeVertex,
                    self.editLine,
            ):
                self.EnableTool(tool, False)
        elif self.fType == "linestring":
            for tool in (self.addPoint, self.addArea):
                self.EnableTool(tool, False)
        elif self.fType == "polygon":
            for tool in (self.addPoint, self.addLine):
                self.EnableTool(tool, False)
        elif self.fType:
            GError(
                parent=self,
                message=_(
                    "Unsupported feature type '%(type)s'. Unable to edit "
                    "OGR layer <%(layer)s>.") % {
                        "type": self.fType,
                        "layer": mapLayer.GetName()
                    },
            )
            self.digit.CloseMap()
            self.mapLayer = None
            self.StopEditing()
            return False

        # update toolbar
        if self.combo:
            self.combo.SetValue(mapLayer.GetName())
        if "map" in self.parent.toolbars:
            self.parent.toolbars["map"].combo.SetValue(_("Vector digitizer"))

        # here was dead code to enable vdigit button in toolbar
        # with if to ignore iclass
        # some signal (DigitizerStarted) can be emitted here

        Debug.msg(
            4, "VDigitToolbar.StartEditing(): layer=%s" % mapLayer.GetName())

        # change cursor
        if self.MapWindow.mouse["use"] == "pointer":
            self.MapWindow.SetNamedCursor("cross")

        if not self.MapWindow.resize:
            self.MapWindow.UpdateMap(render=True)

        # respect opacity
        opacity = mapLayer.GetOpacity()

        if opacity < 1.0:
            alpha = int(opacity * 255)
            self.digit.GetDisplay().UpdateSettings(alpha=alpha)

        # emit signal
        layerTree = self._giface.GetLayerTree()
        if layerTree:
            item = layerTree.FindItemByData("maplayer", self.mapLayer)
        else:
            item = None
        self.editingStarted.emit(vectMap=mapLayer.GetName(),
                                 digit=self.digit,
                                 layerItem=item)

        return True
Esempio n. 5
0
    def _export(self, exportInfo, decorations):
        size = self.frame.animationPanel.GetSize()
        if self.temporalMode == TemporalMode.TEMPORAL:
            timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
            frameCount = len(timeLabels)
        else:
            frameCount = self.animationData[
                0].mapCount  # should be the same for all

        animWinSize = []
        animWinPos = []
        animWinIndex = []
        legends = [anim.legendCmd for anim in self.animationData]
        # determine position and sizes of bitmaps
        for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
            if anim.IsActive():
                pos = win.GetPosition()
                animWinPos.append(pos)
                animWinSize.append(win.GetSize())
                animWinIndex.append(i)

        images = []
        busy = wx.BusyInfo(_("Preparing export, please wait..."),
                           parent=self.frame)
        wx.GetApp().Yield()
        lastBitmaps = {}
        fgcolor = UserSettings.Get(group='animation',
                                   key='font',
                                   subkey='fgcolor')
        bgcolor = UserSettings.Get(group='animation',
                                   key='font',
                                   subkey='bgcolor')
        for frameIndex in range(frameCount):
            image = EmptyImage(*size)
            image.Replace(0, 0, 0, 255, 255, 255)
            # collect bitmaps of all windows and paste them into the one
            for i in animWinIndex:
                frameId = self.animations[i].GetFrame(frameIndex)
                if not UserSettings.Get(group='animation',
                                        key='temporal',
                                        subkey=['nodata', 'enable']):
                    if frameId is not None:
                        bitmap = self.bitmapProvider.GetBitmap(frameId)
                        lastBitmaps[i] = bitmap
                    else:
                        if i not in lastBitmaps:
                            lastBitmaps[i] = wx.NullBitmap()
                else:
                    bitmap = self.bitmapProvider.GetBitmap(frameId)
                    lastBitmaps[i] = bitmap

                im = ImageFromBitmap(lastBitmaps[i])

                # add legend if used
                legend = legends[i]
                if legend:
                    legendBitmap = self.bitmapProvider.LoadOverlay(legend)
                    x, y = self.mapwindows[i].GetOverlayPos()
                    legImage = ImageFromBitmap(legendBitmap)
                    # not so nice result, can we handle the transparency
                    # otherwise?
                    legImage.ConvertAlphaToMask()
                    im.Paste(legImage, x, y)

                if im.GetSize() != animWinSize[i]:
                    im.Rescale(*animWinSize[i])
                image.Paste(im, *animWinPos[i])
            # paste decorations
            for decoration in decorations:
                # add image
                x = decoration['pos'][0] / 100. * size[0]
                y = decoration['pos'][1] / 100. * size[1]
                if decoration['name'] == 'image':
                    decImage = wx.Image(decoration['file'])
                elif decoration['name'] == 'time':
                    timeLabel = timeLabels[frameIndex]
                    if timeLabel[1]:  # interval
                        text = _("%(from)s %(dash)s %(to)s") % {
                            'from': timeLabel[0],
                            'dash': u"\u2013",
                            'to': timeLabel[1]
                        }
                    else:
                        if self.temporalManager.GetTemporalType(
                        ) == TemporalType.ABSOLUTE:
                            text = timeLabel[0]
                        else:
                            text = _("%(start)s %(unit)s") % \
                                {'start': timeLabel[0], 'unit': timeLabel[2]}

                    decImage = RenderText(text, decoration['font'], bgcolor,
                                          fgcolor).ConvertToImage()
                elif decoration['name'] == 'text':
                    text = decoration['text']
                    decImage = RenderText(text, decoration['font'], bgcolor,
                                          fgcolor).ConvertToImage()

                image.Paste(decImage, x, y)

            images.append(image)
        del busy

        # export
        pilImages = [WxImageToPil(image) for image in images]
        self.busy = wx.BusyInfo(_("Exporting animation, please wait..."),
                                parent=self.frame)
        wx.GetApp().Yield()
        try:

            def export_avi_callback(event):
                error = event.ret
                del self.busy
                if error:
                    GError(parent=self.frame, message=error)
                    return

            if exportInfo['method'] == 'sequence':
                filename = os.path.join(
                    exportInfo['directory'],
                    exportInfo['prefix'] + '.' + exportInfo['format'].lower())
                writeIms(filename=filename, images=pilImages)
            elif exportInfo['method'] == 'gif':
                writeGif(filename=exportInfo['file'],
                         images=pilImages,
                         duration=self.timeTick / float(1000),
                         repeat=True)
            elif exportInfo['method'] == 'swf':
                writeSwf(filename=exportInfo['file'],
                         images=pilImages,
                         duration=self.timeTick / float(1000),
                         repeat=True)
            elif exportInfo['method'] == 'avi':
                thread = gThread()
                thread.Run(
                    callable=writeAvi,
                    filename=exportInfo['file'],
                    images=pilImages,
                    duration=self.timeTick / float(1000),
                    encoding=exportInfo['encoding'],
                    inputOptions=exportInfo['options'],
                    bg_task=True,
                    ondone=export_avi_callback,
                )
        except Exception as e:
            del self.busy
            GError(parent=self.frame, message=str(e))
            return
        if exportInfo['method'] in ('sequence', 'gif', 'swf'):
            del self.busy
Esempio n. 6
0
    def _createViewPage(self, notebook):
        """Create notebook page for view settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel, text=" %s " % _("View"))

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("View")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
        row = 0
        # perspective
        pvals = UserSettings.Get(group="nviz", key="view", subkey="persp")
        ipvals = UserSettings.Get(
            group="nviz", key="view", subkey="persp", settings_type="internal"
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Perspective:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")),
            pos=(row, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        pval = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=pvals["value"],
            min=ipvals["min"],
            max=ipvals["max"],
        )
        self.winId["nviz:view:persp:value"] = pval.GetId()
        gridSizer.Add(pval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("step:")),
            pos=(row, 3),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        pstep = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=pvals["step"],
            min=ipvals["min"],
            max=ipvals["max"] - 1,
        )
        self.winId["nviz:view:persp:step"] = pstep.GetId()
        gridSizer.Add(pstep, pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # position
        posvals = UserSettings.Get(group="nviz", key="view", subkey="position")
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Position:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("x:")),
            pos=(row, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        px = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=posvals["x"] * 100,
            min=0,
            max=100,
        )
        self.winId["nviz:view:position:x"] = px.GetId()
        gridSizer.Add(px, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label="y:"),
            pos=(row, 3),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        py = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=posvals["y"] * 100,
            min=0,
            max=100,
        )
        self.winId["nviz:view:position:y"] = py.GetId()
        gridSizer.Add(py, pos=(row, 4), flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # height is computed dynamically

        # twist
        tvals = UserSettings.Get(group="nviz", key="view", subkey="twist")
        itvals = UserSettings.Get(
            group="nviz", key="view", subkey="twist", settings_type="internal"
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Twist:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")),
            pos=(row, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        tval = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=tvals["value"],
            min=itvals["min"],
            max=itvals["max"],
        )
        self.winId["nviz:view:twist:value"] = tval.GetId()
        gridSizer.Add(tval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # z-exag
        zvals = UserSettings.Get(group="nviz", key="view", subkey="z-exag")
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Z-exag:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("value:")),
            pos=(row, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        zval = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=zvals["value"],
            min=-1e6,
            max=1e6,
        )
        self.winId["nviz:view:z-exag:value"] = zval.GetId()
        gridSizer.Add(zval, pos=(row, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
        pageSizer.Add(
            boxSizer,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=3,
        )

        box = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " % (_("Image Appearance"))
        )
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        # background color
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Background color:")),
            pos=(0, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        color = csel.ColourSelect(
            panel,
            id=wx.ID_ANY,
            colour=UserSettings.Get(
                group="nviz", key="view", subkey=["background", "color"]
            ),
            size=globalvar.DIALOG_COLOR_SIZE,
        )
        color.SetName("GetColour")
        self.winId["nviz:view:background:color"] = color.GetId()
        gridSizer.Add(color, pos=(0, 1))

        gridSizer.AddGrowableCol(0)
        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(boxSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)

        panel.SetSizer(pageSizer)

        return panel
Esempio n. 7
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)
Esempio n. 8
0
    def OnLeftUpVarious(self, event):
        """Left mouse button released - vector digitizer various
        actions
        """
        pos1 = self.Pixel2Cell(self.mouse['begin'])
        pos2 = self.Pixel2Cell(self.mouse['end'])

        nselected = 0
        action = self.toolbar.GetAction()
        # -> delete line || move line || move vertex
        if action in ("moveVertex", "editLine"):
            if len(self.digit.GetDisplay().GetSelected()) == 0:
                nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)
                                ['line'] != -1)

                if action == "editLine":
                    try:
                        selVertex = self.digit.GetDisplay().GetSelectedVertex(
                            pos1)[0]
                    except IndexError:
                        selVertex = None

                    if selVertex:
                        # self.UpdateMap(render=False)
                        ids = self.digit.GetDisplay().GetSelected(
                            grassId=False)
                        # move this line to tmp layer
                        self.polycoords = []
                        for id in ids:
                            if id % 2:  # register only vertices
                                e, n = self.Pixel2Cell(
                                    self.pdcVector.GetIdBounds(id)[0:2])
                                self.polycoords.append((e, n))
                        self.digit.GetDisplay().DrawSelected(False)

                        if selVertex < ids[-1] / 2:
                            # choose first or last node of line
                            self.moveInfo['id'].reverse()
                            self.polycoords.reverse()
                    else:
                        # unselect
                        self.digit.GetDisplay().SetSelected([])
                        del self.moveInfo

                    self.UpdateMap(render=False)

        elif action in ("copyCats", "copyAttrs"):
            if not hasattr(self, "copyCatsIds"):
                # 'from' -> select by point
                nselected = int(self.digit.GetDisplay().SelectLineByPoint(pos1)
                                ['line'] != -1)
                if nselected:
                    self.copyCatsList = self.digit.GetDisplay().GetSelected()
            else:
                # -> 'to' -> select by bbox
                self.digit.GetDisplay().SetSelected([])
                # return number of selected features (by box/point)
                nselected = self.digit.GetDisplay().SelectLinesByBox(
                    (pos1, pos2))
                if nselected == 0:
                    nselected = int(self.digit.GetDisplay().SelectLineByPoint(
                        pos1)['line'] != -1)

                if nselected > 0:
                    self.copyCatsIds = self.digit.GetDisplay().GetSelected()

        elif action == "queryLine":
            selected = self.digit.SelectLinesByQuery(bbox=(pos1, pos2))
            nselected = len(selected)
            if nselected > 0:
                self.digit.GetDisplay().SetSelected(selected)

        else:
            # -> moveLine || deleteLine, etc. (select by point/box)
            if action == 'moveLine' and \
                    len(self.digit.GetDisplay().GetSelected()) > 0:
                nselected = 0
            else:
                if action == 'deleteArea':
                    nselected = int(self.digit.GetDisplay().SelectAreaByPoint(
                        pos1)['area'] != -1)
                else:
                    if action == 'moveLine':
                        drawSeg = True
                    else:
                        drawSeg = False

                    nselected = self.digit.GetDisplay().SelectLinesByBox(
                        bbox=(pos1, pos2), drawSeg=drawSeg)
                    if nselected == 0:
                        nselected = int(self.digit.GetDisplay().
                                        SelectLineByPoint(pos1)['line'] != -1)

        if nselected > 0:
            if action in ("moveLine", "moveVertex") and \
                    hasattr(self, "moveInfo"):
                # get pseudoDC id of objects which should be redrawn
                if action == "moveLine":
                    # -> move line
                    self.moveInfo['id'] = self.digit.GetDisplay().GetSelected(
                        grassId=False)
                else:  # moveVertex
                    self.moveInfo['id'] = self.digit.GetDisplay(
                    ).GetSelectedVertex(pos1)
                    if len(self.moveInfo['id']) == 0:  # no vertex found
                        self.digit.GetDisplay().SetSelected([])

            #
            # check for duplicates
            #
            if UserSettings.Get(group='vdigit',
                                key='checkForDupl',
                                subkey='enabled'):
                dupl = self.digit.GetDisplay().GetDuplicates()
                self.UpdateMap(render=False)

                if dupl:
                    posWindow = self.ClientToScreen(
                        (self.mouse['end'][0] + self.dialogOffset,
                         self.mouse['end'][1] + self.dialogOffset))

                    dlg = VDigitDuplicatesDialog(parent=self,
                                                 data=dupl,
                                                 pos=posWindow)

                    if dlg.ShowModal() == wx.ID_OK:
                        self.digit.GetDisplay().UnSelect(dlg.GetUnSelected())
                        # update selected
                        self.UpdateMap(render=False)

            if action != "editLine":
                # -> move line || move vertex
                self.UpdateMap(render=False)

        else:  # no vector object found
            if not (action in ("moveLine",
                               "moveVertex") and \
                        hasattr(self, "moveInfo") and \
                        len(self.moveInfo['id']) > 0):
                # avoid left-click when features are already selected
                self.UpdateMap(render=False, renderVector=False)
Esempio n. 9
0
    def _onRightUp(self, event):
        """Right mouse button released (confirm action)
        """
        action = self.toolbar.GetAction()
        if action == "addLine" and \
                self.toolbar.GetAction('type') in ["line", "boundary", "area"]:
            # -> add new line / boundary
            try:
                mapName = self.toolbar.GetLayer().GetName()
            except:
                mapName = None
                GError(parent=self,
                       message=_("No vector map selected for editing."))

            if mapName:
                if self.toolbar.GetAction('type') == 'line':
                    line = True
                else:
                    line = False

                if len(self.polycoords) < 2:  # ignore 'one-point' lines
                    return

                nfeat, fids = self.digit.AddFeature(
                    self.toolbar.GetAction('type'), self.polycoords)
                if nfeat < 0:
                    return

                position = self.Cell2Pixel(self.polycoords[-1])
                self.polycoords = []
                self.UpdateMap(render=False)
                self.redrawAll = True
                self.Refresh()

                # add new record into atribute table
                if self._addRecord() and (line is True or
                                          (not line and nfeat > 0)):
                    posWindow = self.ClientToScreen(
                        (position[0] + self.dialogOffset,
                         position[1] + self.dialogOffset))

                    # select attributes based on layer and category
                    cats = {
                        fids[0]: {
                            UserSettings.Get(group='vdigit',
                                             key="layer",
                                             subkey='value'):
                            (UserSettings.Get(group='vdigit',
                                              key="category",
                                              subkey='value'), )
                        }
                    }

                    addRecordDlg = DisplayAttributesDialog(parent=self,
                                                           map=mapName,
                                                           cats=cats,
                                                           pos=posWindow,
                                                           action="add",
                                                           ignoreError=True)

                    for fid in fids:
                        self._geomAttrb(fid, addRecordDlg, 'length')
                        # auto-placing centroid
                        self._geomAttrb(fid, addRecordDlg, 'area')
                        self._geomAttrb(fid, addRecordDlg, 'perimeter')

                    if addRecordDlg.IsFound():
                        addRecordDlg.ShowModal()
                    addRecordDlg.Destroy()

        elif action == "deleteLine":
            # -> delete selected vector features
            if self.digit.DeleteSelectedLines() < 0:
                return
            self._updateATM()
        elif action == "deleteArea":
            # -> delete selected vector areas
            if self.digit.DeleteSelectedAreas() < 0:
                return
            self._updateATM()
        elif action == "splitLine":
            # split line
            if self.digit.SplitLine(self.Pixel2Cell(self.mouse['begin'])) < 0:
                return
        elif action == "addVertex":
            # add vertex
            fid = self.digit.AddVertex(self.Pixel2Cell(self.mouse['begin']))
            if fid < 0:
                return
        elif action == "removeVertex":
            # remove vertex
            fid = self.digit.RemoveVertex(self.Pixel2Cell(self.mouse['begin']))
            if fid < 0:
                return
            self._geomAttrbUpdate([
                fid,
            ])
        elif action in ("copyCats", "copyAttrs"):
            if action == 'copyCats':
                if self.digit.CopyCats(self.copyCatsList,
                                       self.copyCatsIds,
                                       copyAttrb=False) < 0:
                    return
            else:
                if self.digit.CopyCats(self.copyCatsList,
                                       self.copyCatsIds,
                                       copyAttrb=True) < 0:
                    return

            del self.copyCatsList
            del self.copyCatsIds

            self._updateATM()

        elif action == "editLine" and \
                hasattr(self, "moveInfo"):
            line = self.digit.GetDisplay().GetSelected()[0]
            if self.digit.EditLine(line, self.polycoords) < 0:
                return

            del self.moveInfo

        elif action == "flipLine":
            if self.digit.FlipLine() < 0:
                return
        elif action == "mergeLine":
            if self.digit.MergeLine() < 0:
                return
        elif action == "breakLine":
            if self.digit.BreakLine() < 0:
                return
        elif action == "snapLine":
            if self.digit.SnapLine() < 0:
                return
        elif action == "connectLine":
            if len(self.digit.GetDisplay().GetSelected()) > 1:
                if self.digit.ConnectLine() < 0:
                    return
        elif action == "copyLine":
            if self.digit.CopyLine(self.copyIds) < 0:
                return
            del self.copyIds
            if self.layerTmp:
                self.Map.DeleteLayer(self.layerTmp)
                self.UpdateMap(render=True, renderVector=False)
            del self.layerTmp

        elif action == "zbulkLine" and len(self.polycoords) == 2:
            pos1 = self.polycoords[0]
            pos2 = self.polycoords[1]

            selected = self.digit.GetDisplay().GetSelected()
            dlg = VDigitZBulkDialog(parent=self,
                                    title=_("Z bulk-labeling dialog"),
                                    nselected=len(selected))
            if dlg.ShowModal() == wx.ID_OK:
                if self.digit.ZBulkLines(pos1, pos2, dlg.value.GetValue(),
                                         dlg.step.GetValue()) < 0:
                    return
            self.UpdateMap(render=False)
        elif action == "typeConv":
            # -> feature type conversion
            # - point <-> centroid
            # - line <-> boundary
            if self.digit.TypeConvForSelectedLines() < 0:
                return

        if action != "addLine":
            # unselect and re-render
            self.digit.GetDisplay().SetSelected([])
            self.polycoords = []
            self.UpdateMap(render=False)
Esempio n. 10
0
 def _addRecord(self):
     return UserSettings.Get(group='vdigit',
                             key="addRecord",
                             subkey='enabled')
Esempio n. 11
0
    def OnLeftDownDisplayCA(self, event):
        """Left mouse button pressed - vector digitizer display categories
        or attributes action
        """
        try:
            mapLayer = self.toolbar.GetLayer().GetName()
        except:
            return

        coords = self.Pixel2Cell(self.mouse['begin'])

        # unselect
        self.digit.GetDisplay().SetSelected([])

        # select feature by point
        cats = {}
        self.digit.GetDisplay().SelectLineByPoint(coords)

        if not self.digit.GetDisplay().GetSelected():
            for key in ('attributes', 'category'):
                if self.parent.dialogs[key] and \
                        self.parent.dialogs[key].IsShown():
                    self.parent.dialogs[key].Hide()
            self.UpdateMap(render=False, renderVector=True)
            return

        if UserSettings.Get(group='vdigit',
                            key='checkForDupl',
                            subkey='enabled'):
            lines = self.digit.GetDisplay().GetSelected()
        else:
            lines = (self.digit.GetDisplay().GetSelected()[0],
                     )  # only first found

        for line in lines:
            cats[line] = self.digit.GetLineCats(line)

        posWindow = self.ClientToScreen(
            (self.mouse['end'][0] + self.dialogOffset,
             self.mouse['end'][1] + self.dialogOffset))

        if self.toolbar.GetAction() == "displayAttrs":
            # select attributes based on coordinates (all layers)
            if self.parent.dialogs['attributes'] is None:
                self.parent.dialogs['attributes'] = \
                    DisplayAttributesDialog(parent = self, map = mapLayer,
                                            cats = cats,
                                            action = "update")
            else:
                # upgrade dialog
                self.parent.dialogs['attributes'].UpdateDialog(cats=cats)

            if self.parent.dialogs['attributes'] and \
                    self.parent.dialogs['attributes'].mapDBInfo:
                if len(cats.keys()) > 0:
                    # highlight feature & re-draw map
                    if not self.parent.dialogs['attributes'].IsShown():
                        self.parent.dialogs['attributes'].Show()
                else:
                    if self.parent.dialogs['attributes'] and \
                            self.parent.dialogs['attributes'].IsShown():
                        self.parent.dialogs['attributes'].Hide()

        else:  # displayCats
            if self.parent.dialogs['category'] is None:
                # open new dialog
                dlg = VDigitCategoryDialog(parent=self,
                                           vectorName=mapLayer,
                                           cats=cats,
                                           pos=posWindow,
                                           title=_("Update categories"))
                self.parent.dialogs['category'] = dlg
            else:
                # update currently open dialog
                self.parent.dialogs['category'].UpdateDialog(cats=cats)

            if self.parent.dialogs['category']:
                if len(cats.keys()) > 0:
                    # highlight feature & re-draw map
                    if not self.parent.dialogs['category'].IsShown():
                        self.parent.dialogs['category'].Show()
                else:
                    if self.parent.dialogs['category'].IsShown():
                        self.parent.dialogs['category'].Hide()

        self.UpdateMap(render=False, renderVector=True)
Esempio n. 12
0
    def ReprojectRegionFromMap(self, region, useDefinedProjection, precision,
                               format):
        """Reproject region values

        .. todo::
            reorganize this method to remove code useful only for derived class SbCompRegionExtent
        """
        if useDefinedProjection:
            settings = UserSettings.Get(group="projection",
                                        key="statusbar",
                                        subkey="proj4")

            if not settings:
                raise SbException(
                    _("Projection not defined (check the settings)"))
            else:
                projOut = settings
                proj, coord1 = utils.ReprojectCoordinates(coord=(region["w"],
                                                                 region["s"]),
                                                          projOut=projOut,
                                                          flags="d")
                proj, coord2 = utils.ReprojectCoordinates(coord=(region["e"],
                                                                 region["n"]),
                                                          projOut=projOut,
                                                          flags="d")
                # useless, used in derived class
                proj, coord3 = utils.ReprojectCoordinates(coord=(0.0, 0.0),
                                                          projOut=projOut,
                                                          flags="d")
                proj, coord4 = utils.ReprojectCoordinates(
                    coord=(region["ewres"], region["nsres"]),
                    projOut=projOut,
                    flags="d")
                if coord1 and coord2:
                    if proj in ("ll", "latlong",
                                "longlat") and format == "DMS":
                        w, s = utils.Deg2DMS(coord1[0],
                                             coord1[1],
                                             string=False,
                                             precision=precision)
                        e, n = utils.Deg2DMS(coord2[0],
                                             coord2[1],
                                             string=False,
                                             precision=precision)
                        ewres, nsres = utils.Deg2DMS(
                            abs(coord3[0]) - abs(coord4[0]),
                            abs(coord3[1]) - abs(coord4[1]),
                            string=False,
                            hemisphere=False,
                            precision=precision,
                        )
                        return self._formatRegion(w=w,
                                                  s=s,
                                                  e=e,
                                                  n=n,
                                                  ewres=ewres,
                                                  nsres=nsres)
                    else:
                        w, s = coord1
                        e, n = coord2
                        ewres, nsres = coord3
                        return self._formatRegion(
                            w=w,
                            s=s,
                            e=e,
                            n=n,
                            ewres=ewres,
                            nsres=nsres,
                            precision=precision,
                        )
                else:
                    raise SbException(
                        _("Error in projection (check the settings)"))

        else:
            if self.mapFrame.GetMap(
            ).projinfo["proj"] == "ll" and format == "DMS":
                w, s = utils.Deg2DMS(region["w"],
                                     region["s"],
                                     string=False,
                                     precision=precision)
                e, n = utils.Deg2DMS(region["e"],
                                     region["n"],
                                     string=False,
                                     precision=precision)
                ewres, nsres = utils.Deg2DMS(region["ewres"],
                                             region["nsres"],
                                             string=False,
                                             precision=precision)
                return self._formatRegion(w=w,
                                          s=s,
                                          e=e,
                                          n=n,
                                          ewres=ewres,
                                          nsres=nsres)
            else:
                w, s = region["w"], region["s"]
                e, n = region["e"], region["n"]
                ewres, nsres = region["ewres"], region["nsres"]
                return self._formatRegion(w=w,
                                          s=s,
                                          e=e,
                                          n=n,
                                          ewres=ewres,
                                          nsres=nsres,
                                          precision=precision)
Esempio n. 13
0
 def _getSnapTresh(self):
     return UserSettings.Get(group='scatt',
                             key='selection',
                             subkey='snap_tresh')
Esempio n. 14
0
import copy
import six

import wx

from core.settings import UserSettings
from core.utils import _

# default icon set
from .grass_icons import iconSet as g_iconSet
from .grass_icons import iconPath as g_iconPath
iconSetDefault = g_iconSet
iconPathDefault = g_iconPath

iconTheme = UserSettings.Get(group='appearance',
                             key='iconTheme',
                             subkey='type')
if iconTheme != 'grass':
    sys.stderr.write(
        _("Unknown iconset '%s', using default 'grass'...\n") % (iconTheme))

iconSet = iconSetDefault
iconPath = iconPathDefault

# join paths
try:
    if iconPath and not os.path.exists(iconPath):
        raise OSError

    for key, img in six.iteritems(iconSet):
        if key not in iconSet or \
Esempio n. 15
0
    def _createSurfacePage(self, notebook):
        """Create notebook page for surface settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel, text=" %s " % _("Surface"))

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        # draw

        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Draw")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        # mode
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Mode:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(0, 0),
        )
        mode = wx.Choice(
            parent=panel,
            id=wx.ID_ANY,
            size=(-1, -1),
            choices=[_("coarse"), _("fine"), _("both")],
        )
        self.winId["nviz:surface:draw:mode"] = mode.GetId()
        mode.SetName("GetSelection")
        mode.SetSelection(
            UserSettings.Get(group="nviz", key="surface", subkey=["draw", "mode"])
        )
        gridSizer.Add(mode, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 1))

        # fine
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Fine mode:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(1, 0),
        )
        res = UserSettings.Get(group="nviz", key="surface", subkey=["draw", "res-fine"])
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("resolution:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(1, 1),
        )
        fine = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=res, min=1, max=100
        )
        self.winId["nviz:surface:draw:res-fine"] = fine.GetId()

        gridSizer.Add(fine, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 2))

        # coarse
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Coarse mode:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(2, 0),
        )
        res = UserSettings.Get(
            group="nviz", key="surface", subkey=["draw", "res-coarse"]
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("resolution:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(2, 1),
        )
        coarse = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=res, min=1, max=100
        )
        self.winId["nviz:surface:draw:res-coarse"] = coarse.GetId()

        gridSizer.Add(coarse, flag=wx.ALIGN_CENTER_VERTICAL, pos=(2, 2))
        # style
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("style:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(3, 1),
        )
        style = wx.Choice(
            parent=panel, id=wx.ID_ANY, size=(-1, -1), choices=[_("wire"), _("surface")]
        )
        self.winId["nviz:surface:draw:style"] = style.GetId()
        style.SetName("GetSelection")
        style.SetSelection(
            UserSettings.Get(group="nviz", key="surface", subkey=["draw", "style"])
        )
        self.winId["nviz:surface:draw:style"] = style.GetId()

        gridSizer.Add(style, flag=wx.ALIGN_CENTER_VERTICAL, pos=(3, 2))
        # wire color
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("wire color:")),
            flag=wx.ALIGN_CENTER_VERTICAL,
            pos=(4, 1),
        )
        color = csel.ColourSelect(
            panel,
            id=wx.ID_ANY,
            colour=UserSettings.Get(
                group="nviz", key="surface", subkey=["draw", "wire-color"]
            ),
            size=globalvar.DIALOG_COLOR_SIZE,
        )
        color.SetName("GetColour")
        self.winId["nviz:surface:draw:wire-color"] = color.GetId()
        gridSizer.Add(color, flag=wx.ALIGN_CENTER_VERTICAL, pos=(4, 2))

        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(
            boxSizer,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=5,
        )

        panel.SetSizer(pageSizer)

        return panel
Esempio n. 16
0
def main():
    """
    Sets the GRASS display driver
    """
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.settings import UserSettings
    from core.globalvar import CheckWxVersion
    from core.giface import StandaloneGrassInterface
    from image2target.ii2t_manager import GCPWizard

    driver = UserSettings.Get(group='display', key='driver', subkey='type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'

#    if options['source_location']:
#        src_loc = options['source_location']
#    else:
#        gscript.fatal(_("No georeferenced source location provided"))

#    if options['source_mapset']:
#        src_mpt = options['source_mapset']
#    else:
#        gscript.fatal(_("No georeferenced source mapset provided"))

#    if options['source_group']:
#        src_grp = options['source_group']
#    else:
#        gscript.fatal(_("Please provide a source group name to process"))

#    if options['source_image']:
#        src_ras = options['source_image']
#    else:
#        gscript.fatal(_("Please provide a source image map name to process"))

#    if options['target_image']:
#        tgt_ras = options['target_image']
#    else:
#        gscript.fatal(_("No georeferenced target map provided"))

#    if options['camera']:
#        camera = options['camera']
#    else:
#        gscript.fatal(_("Please provide a camera name (generated by i.ortho.camera)"))

#    if options['order']:
#        order = options['order']
#    else:
#        gscript.fatal(_("Please provive an order value"))

#    if options['extension']:
#        extension = options['extension']
#    else:
#        gscript.fatal(_("Please provide an output file extension"))

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()


#    wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface(),
#            srcloc=src_loc,srcmpt=src_mpt,srcgrp=src_grp,srcras=src_ras,
#            tgtras=tgt_ras,camera=camera, order=order, extension=extension)

    wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface())
    app.MainLoop()
Esempio n. 17
0
    def _createVectorPage(self, notebook):
        """Create notebook page for vector settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel, text=" %s " % _("Vector"))

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        # vector lines
        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Vector lines")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        row = 0
        # icon size
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Width:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        iwidth = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=12, min=1, max=100
        )
        self.winId["nviz:vector:lines:width"] = iwidth.GetId()
        iwidth.SetValue(
            UserSettings.Get(group="nviz", key="vector", subkey=["lines", "width"])
        )
        gridSizer.Add(iwidth, pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL)

        # icon color
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")),
            pos=(row, 4),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        icolor = csel.ColourSelect(
            panel, id=wx.ID_ANY, size=globalvar.DIALOG_COLOR_SIZE
        )
        icolor.SetName("GetColour")
        self.winId["nviz:vector:lines:color"] = icolor.GetId()
        icolor.SetColour(
            UserSettings.Get(group="nviz", key="vector", subkey=["lines", "color"])
        )
        gridSizer.Add(icolor, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 5))
        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(
            boxSizer,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=5,
        )

        # vector points
        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Vector points")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=5)

        row = 0
        # icon size
        autosize = CheckBox(parent=panel, label=_("Automatic size"))
        autosize.SetToolTip(
            _("Icon size is set automatically based on landscape dimensions.")
        )
        gridSizer.Add(autosize, pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
        self.winId["nviz:vector:points:autosize"] = autosize.GetId()
        autosize.SetValue(
            UserSettings.Get(group="nviz", key="vector", subkey=["points", "autosize"])
        )

        row += 1
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Size:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        isize = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=100, min=1, max=1e6
        )
        self.winId["nviz:vector:points:size"] = isize.GetId()
        isize.SetValue(
            UserSettings.Get(group="nviz", key="vector", subkey=["points", "size"])
        )
        gridSizer.Add(isize, pos=(row, 1), flag=wx.ALIGN_CENTER_VERTICAL)

        # icon symbol
        row += 1
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Marker:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        isym = wx.Choice(
            parent=panel,
            id=wx.ID_ANY,
            size=(100, -1),
            choices=UserSettings.Get(
                group="nviz",
                key="vector",
                subkey=["points", "marker"],
                settings_type="internal",
            ),
        )
        isym.SetName("GetSelection")
        self.winId["nviz:vector:points:marker"] = isym.GetId()
        isym.SetSelection(
            UserSettings.Get(group="nviz", key="vector", subkey=["points", "marker"])
        )
        gridSizer.Add(isym, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 1))

        # icon color
        row += 1
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")),
            pos=(row, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        icolor = csel.ColourSelect(
            panel, id=wx.ID_ANY, size=globalvar.DIALOG_COLOR_SIZE
        )
        icolor.SetName("GetColour")
        self.winId["nviz:vector:points:color"] = icolor.GetId()
        icolor.SetColour(
            UserSettings.Get(group="nviz", key="vector", subkey=["points", "color"])
        )
        gridSizer.Add(icolor, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 1))

        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(
            boxSizer,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=5,
        )

        panel.SetSizer(pageSizer)

        return panel
Esempio n. 18
0
    def __init__(
        self,
        parent,
        giface,
        itype,
        id=wx.ID_ANY,
        title=_("Multiple import"),
        style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
    ):
        self.parent = parent  # GMFrame
        self._giface = giface  # used to add layers
        self.importType = itype
        self.options = dict()  # list of options
        self.options_par = dict()

        self.commandId = -1  # id of running command

        wx.Dialog.__init__(
            self, parent, id, title, style=style, name="MultiImportDialog"
        )

        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        self.layerBox = StaticBox(parent=self.panel, id=wx.ID_ANY)
        if self.importType == "gdal":
            label = _("List of raster layers")
        elif self.importType == "ogr":
            label = _("List of vector layers")
        else:
            label = _("List of %s layers") % self.importType.upper()
        self.layerBox.SetLabel(
            " %s - %s " % (label, _("right click to (un)select all"))
        )

        # list of layers
        columns = [
            _("Layer id"),
            _("Layer name"),
            _("Name for output GRASS map (editable)"),
        ]
        if itype == "ogr":
            columns.insert(2, _("Feature type"))
            columns.insert(3, _("Projection match"))
        elif itype == "gdal":
            columns.insert(2, _("Projection match"))

        self.list = LayersList(parent=self.panel, columns=columns)
        self.list.LoadData()

        self.override = wx.CheckBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=_("Override projection check (use current location's projection)"),
        )

        self.overwrite = wx.CheckBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=_("Allow output files to overwrite existing files"),
        )
        self.overwrite.SetValue(
            UserSettings.Get(group="cmd", key="overwrite", subkey="enabled")
        )
        self.overwrite.Bind(wx.EVT_CHECKBOX, self.OnCheckOverwrite)
        if UserSettings.Get(group="cmd", key="overwrite", subkey="enabled"):
            self.list.validate = False

        self.add = wx.CheckBox(parent=self.panel, id=wx.ID_ANY)
        self.closeOnFinish = wx.CheckBox(
            parent=self.panel, id=wx.ID_ANY, label=_("Close dialog on finish")
        )
        self.closeOnFinish.SetValue(
            UserSettings.Get(group="cmd", key="closeDlg", subkey="enabled")
        )

        #
        # buttons
        #
        # cancel
        self.btn_close = CloseButton(parent=self.panel)
        self.btn_close.SetToolTip(_("Close dialog"))
        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
        # run
        self.btn_run = Button(parent=self.panel, id=wx.ID_OK, label=_("&Import"))
        self.btn_run.SetToolTip(_("Import selected layers"))
        self.btn_run.SetDefault()
        self.btn_run.Bind(wx.EVT_BUTTON, self.OnRun)

        self.Bind(wx.EVT_CLOSE, lambda evt: self.Destroy())

        self.notebook = GNotebook(parent=self, style=globalvar.FNPageDStyle)

        self.notebook.AddPage(page=self.panel, text=_("Source settings"), name="source")

        self.createSettingsPage()
Esempio n. 19
0
def main():
    gscript.set_raise_on_error(False)
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.settings import UserSettings
    from iclass.frame import IClassMapFrame

    group_name = subgroup_name = map_name = trainingmap_name = None

    if options["group"]:
        if not options["subgroup"]:
            gscript.fatal(_("Name of subgroup required"))
        group_name = gscript.find_file(name=options["group"],
                                       element="group")["name"]
        if not group_name:
            gscript.fatal(_("Group <%s> not found") % options["group"])
        subgroups = gscript.read_command("i.group",
                                         group=group_name,
                                         flags="sg").splitlines()
        if options["subgroup"] not in subgroups:
            gscript.fatal(_("Subgroup <%s> not found") % options["subgroup"])
        subgroup_name = options["subgroup"]

    if options["map"]:
        map_name = gscript.find_file(name=options["map"],
                                     element="cell")["fullname"]
        if not map_name:
            gscript.fatal(_("Raster map <%s> not found") % options["map"])

    if options["trainingmap"]:
        trainingmap_name = gscript.find_file(name=options["trainingmap"],
                                             element="vector")["fullname"]
        if not trainingmap_name:
            gscript.fatal(
                _("Vector map <%s> not found") % options["trainingmap"])

    # define display driver
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    # launch application
    app = wx.App()

    # show main frame
    frame = IClassMapFrame(
        parent=None,
        giface=None,
        title=_("Supervised Classification Tool - GRASS GIS"),
    )
    if not flags["m"]:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        frame.giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        frame.giface.WriteLog(
            _("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags["m"]:
        frame.Maximize()
    app.MainLoop()
Esempio n. 20
0
    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        self.commandId = -1
        data = self.list.GetLayers()

        data = self._getLayersToReprojetion(2, 3)

        if data is None:
            return

        if not data:
            GMessage(_("No layers selected. Operation canceled."), parent=self)
            return

        if not self._validateOutputMapName():
            return

        dsn = self.dsnInput.GetDsn()
        ext = self.dsnInput.GetFormatExt()

        for layer, output, listId in data:
            userData = {}

            if self.dsnInput.GetType() == "dir":
                idsn = os.path.join(dsn, layer)
            else:
                idsn = dsn

            # check number of bands
            nBandsStr = RunCommand("r.in.gdal", flags="p", input=idsn, read=True)
            nBands = -1
            if nBandsStr:
                try:
                    nBands = int(nBandsStr.rstrip("\n"))
                except:
                    pass
            if nBands < 0:
                GWarning(_("Unable to determine number of raster bands"), parent=self)
                nBands = 1

            userData["nbands"] = nBands
            cmd = self.getSettingsPageCmd()
            cmd.append("input=%s" % idsn)
            cmd.append("output=%s" % output)

            if self.override.IsChecked():
                cmd.append("-o")

            if self.overwrite.IsChecked():
                cmd.append("--overwrite")

            if (
                UserSettings.Get(group="cmd", key="overwrite", subkey="enabled")
                and "--overwrite" not in cmd
            ):
                cmd.append("--overwrite")

            # run in Layer Manager
            self._giface.RunCmd(
                cmd, onDone=self.OnCmdDone, userData=userData, addLayer=False
            )
Esempio n. 21
0
    def StopEditing(self):
        """Stop editing of selected vector map layer.

        :return: True on success
        :return: False on failure
        """
        item = None

        if self.combo:
            self.combo.SetValue(_("Select vector map"))

        # save changes
        if self.mapLayer:
            Debug.msg(
                4, "VDigitToolbar.StopEditing(): layer=%s" %
                self.mapLayer.GetName())
            if (UserSettings.Get(group="vdigit",
                                 key="saveOnExit",
                                 subkey="enabled") is False):
                if self.digit.GetUndoLevel() > -1:
                    dlg = wx.MessageDialog(
                        parent=self.parent,
                        message=_("Do you want to save changes "
                                  "in vector map <%s>?") %
                        self.mapLayer.GetName(),
                        caption=_("Save changes?"),
                        style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
                    )
                    if dlg.ShowModal() == wx.ID_NO:
                        # revert changes
                        self.digit.Undo(0)
                    dlg.Destroy()

            self.parent.SetStatusText(
                _("Please wait, "
                  "closing and rebuilding topology of "
                  "vector map <%s>...") % self.mapLayer.GetName(),
                0,
            )
            self.digit.CloseMap()

            # close open background map if any
            bgMap = UserSettings.Get(group="vdigit",
                                     key="bgmap",
                                     subkey="value",
                                     settings_type="internal")
            if bgMap:
                self.digit.CloseBackgroundMap()
                self.editingBgMap.emit(mapName=bgMap, unset=True)

            self._giface.GetProgress().SetValue(0)
            self._giface.WriteCmdLog(
                _("Editing of vector map <%s> successfully finished") %
                self.mapLayer.GetName(),
                notification=Notification.HIGHLIGHT,
            )
            # re-active layer
            layerTree = self._giface.GetLayerTree()
            if layerTree:
                item = layerTree.FindItemByData("maplayer", self.mapLayer)
                if item and layerTree.IsItemChecked(item):
                    self.Map.ChangeLayerActive(self.mapLayer, True)

        # change cursor
        self.MapWindow.SetNamedCursor("default")
        self.MapWindow.pdcVector = None

        # close dialogs
        for dialog in ("attributes", "category"):
            if self.parent.dialogs[dialog]:
                self.parent.dialogs[dialog].Close()
                self.parent.dialogs[dialog] = None

        self.digit = None
        self.MapWindow.digit = None

        self.editingStopped.emit(layerItem=item)

        self.mapLayer = None

        self.MapWindow.redrawAll = True

        return True
Esempio n. 22
0
    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        self.commandId = -1
        data = self.list.GetLayers()

        data = self._getLayersToReprojetion(3, 4)

        if data is None:
            return

        if not data:
            GMessage(_("No layers selected. Operation canceled."), parent=self)
            return

        if not self._validateOutputMapName():
            return

        dsn = self.dsnInput.GetDsn()
        ext = self.dsnInput.GetFormatExt()

        # determine data driver for PostGIS links
        self.popOGR = False
        if (
            self.dsnInput.GetType() == "db"
            and self.dsnInput.GetFormat() == "PostgreSQL"
            and "GRASS_VECTOR_OGR" not in os.environ
        ):
            self.popOGR = True
            os.environ["GRASS_VECTOR_OGR"] = "1"

        for layer, output, listId in data:
            userData = {}

            if ext and layer.rfind(ext) > -1:
                layer = layer.replace("." + ext, "")
            if "|" in layer:
                layer, geometry = layer.split("|", 1)
            else:
                geometry = None

                # TODO: v.import has no geometry option
                # if geometry:
                #    cmd.append('geometry=%s' % geometry)

            cmd = self.getSettingsPageCmd()
            cmd.append("input=%s" % dsn)
            cmd.append("layer=%s" % layer)
            cmd.append("output=%s" % output)

            if self.override.IsChecked():
                cmd.append("-o")

            if self.overwrite.IsChecked():
                cmd.append("--overwrite")

            # TODO options
            if (
                UserSettings.Get(group="cmd", key="overwrite", subkey="enabled")
                and "--overwrite" not in cmd
            ):
                cmd.append("--overwrite")

            # run in Layer Manager
            self._giface.RunCmd(
                cmd, onDone=self.OnCmdDone, userData=userData, addLayer=False
            )
Esempio n. 23
0
 def _showConfEllipses(self):
     return UserSettings.Get(group='scatt',
                             key="ellipses",
                             subkey="show_ellips")
Esempio n. 24
0
    def __init__(self,
                 parent,
                 giface,
                 cmd,
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
                 **kwargs):
        self.parent = parent
        self._giface = giface

        if self.parent:
            self.log = self.parent.GetLogWindow()
        else:
            self.log = None

        # grass command
        self.cmd = cmd

        if self.cmd == 'r.mapcalc':
            self.rast3d = False
            title = _('GRASS GIS Raster Map Calculator')
        if self.cmd == 'r3.mapcalc':
            self.rast3d = True
            title = _('GRASS GIS 3D Raster Map Calculator')

        wx.Frame.__init__(self, parent, id=id, title=title, **kwargs)
        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'),
                    wx.BITMAP_TYPE_ICO))

        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.CreateStatusBar()

        #
        # variables
        #
        self.heading = _('mapcalc statement')
        self.funct_dict = {
            'abs(x)': 'abs()',
            'acos(x)': 'acos()',
            'asin(x)': 'asin()',
            'atan(x)': 'atan()',
            'atan(x,y)': 'atan( , )',
            'cos(x)': 'cos()',
            'double(x)': 'double()',
            'eval([x,y,...,]z)': 'eval()',
            'exp(x)': 'exp()',
            'exp(x,y)': 'exp( , )',
            'float(x)': 'float()',
            'graph(x,x1,y1[x2,y2..])': 'graph( , , )',
            'if(x)': 'if()',
            'if(x,a)': 'if( , )',
            'if(x,a,b)': 'if( , , )',
            'if(x,a,b,c)': 'if( , , , )',
            'int(x)': 'int()',
            'isnull(x)': 'isnull()',
            'log(x)': 'log(',
            'log(x,b)': 'log( , )',
            'max(x,y[,z...])': 'max( , )',
            'median(x,y[,z...])': 'median( , )',
            'min(x,y[,z...])': 'min( , )',
            'mode(x,y[,z...])': 'mode( , )',
            'nmax(x,y[,z...])': 'nmax( , )',
            'nmedian(x,y[,z...])': 'nmedian( , )',
            'nmin(x,y[,z...])': 'nmin( , )',
            'nmode(x,y[,z...])': 'nmode( , )',
            'not(x)': 'not()',
            'pow(x,y)': 'pow( , )',
            'rand(a,b)': 'rand( , )',
            'round(x)': 'round()',
            'round(x,y)': 'round( , )',
            'round(x,y,z)': 'round( , , )',
            'sin(x)': 'sin()',
            'sqrt(x)': 'sqrt()',
            'tan(x)': 'tan()',
            'xor(x,y)': 'xor( , )',
            'row()': 'row()',
            'col()': 'col()',
            'nrows()': 'nrows()',
            'ncols()': 'ncols()',
            'x()': 'x()',
            'y()': 'y()',
            'ewres()': 'ewres()',
            'nsres()': 'nsres()',
            'area()': 'area()',
            'null()': 'null()'
        }

        if self.rast3d:
            self.funct_dict['z()'] = 'z()'
            self.funct_dict['tbres()'] = 'tbres()'
            element = 'raster_3d'
        else:
            element = 'cell'

        # characters which can be in raster map name but the map name must be
        # then quoted
        self.charactersToQuote = '+-&!<>%~?^|'
        # stores last typed map name in Select widget to distinguish typing
        # from selection
        self.lastMapName = ''

        self.operatorBox = StaticBox(parent=self.panel,
                                     id=wx.ID_ANY,
                                     label=" %s " % _('Operators'))
        self.outputBox = StaticBox(parent=self.panel,
                                   id=wx.ID_ANY,
                                   label=" %s " % _('Output'))
        self.operandBox = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _('Operands'))
        self.expressBox = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _('Expression'))

        #
        # Buttons
        #
        self.btn_clear = Button(parent=self.panel, id=wx.ID_CLEAR)
        self.btn_help = Button(parent=self.panel, id=wx.ID_HELP)
        self.btn_run = Button(parent=self.panel, id=wx.ID_ANY, label=_("&Run"))
        self.btn_run.SetForegroundColour(wx.Colour(35, 142, 35))
        self.btn_run.SetDefault()
        self.btn_close = Button(parent=self.panel, id=wx.ID_CLOSE)
        self.btn_save = Button(parent=self.panel, id=wx.ID_SAVE)
        self.btn_save.SetToolTip(_('Save expression to file'))
        self.btn_load = Button(parent=self.panel,
                               id=wx.ID_ANY,
                               label=_("&Load"))
        self.btn_load.SetToolTip(_('Load expression from file'))
        self.btn_copy = Button(parent=self.panel, id=wx.ID_COPY)
        self.btn_copy.SetToolTip(
            _("Copy the current command string to the clipboard"))

        self.btn = dict()
        self.btn['pow'] = Button(parent=self.panel, id=wx.ID_ANY, label="^")
        self.btn['pow'].SetToolTip(_('exponent'))
        self.btn['div'] = Button(parent=self.panel, id=wx.ID_ANY, label="/")
        self.btn['div'].SetToolTip(_('divide'))
        self.btn['add'] = Button(parent=self.panel, id=wx.ID_ANY, label="+")
        self.btn['add'].SetToolTip(_('add'))
        self.btn['minus'] = Button(parent=self.panel, id=wx.ID_ANY, label="-")
        self.btn['minus'].SetToolTip(_('subtract'))
        self.btn['mod'] = Button(parent=self.panel, id=wx.ID_ANY, label="%")
        self.btn['mod'].SetToolTip(_('modulus'))
        self.btn['mult'] = Button(parent=self.panel, id=wx.ID_ANY, label="*")
        self.btn['mult'].SetToolTip(_('multiply'))

        self.btn['parenl'] = Button(parent=self.panel, id=wx.ID_ANY, label="(")
        self.btn['parenr'] = Button(parent=self.panel, id=wx.ID_ANY, label=")")
        self.btn['lshift'] = Button(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label="<<")
        self.btn['lshift'].SetToolTip(_('left shift'))
        self.btn['rshift'] = Button(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=">>")
        self.btn['rshift'].SetToolTip(_('right shift'))
        self.btn['rshiftu'] = Button(parent=self.panel,
                                     id=wx.ID_ANY,
                                     label=">>>")
        self.btn['rshiftu'].SetToolTip(_('right shift (unsigned)'))
        self.btn['gt'] = Button(parent=self.panel, id=wx.ID_ANY, label=">")
        self.btn['gt'].SetToolTip(_('greater than'))
        self.btn['gteq'] = Button(parent=self.panel, id=wx.ID_ANY, label=">=")
        self.btn['gteq'].SetToolTip(_('greater than or equal to'))
        self.btn['lt'] = Button(parent=self.panel, id=wx.ID_ANY, label="<")
        self.btn['lt'].SetToolTip(_('less than'))
        self.btn['lteq'] = Button(parent=self.panel, id=wx.ID_ANY, label="<=")
        self.btn['lteq'].SetToolTip(_('less than or equal to'))
        self.btn['eq'] = Button(parent=self.panel, id=wx.ID_ANY, label="==")
        self.btn['eq'].SetToolTip(_('equal to'))
        self.btn['noteq'] = Button(parent=self.panel, id=wx.ID_ANY, label="!=")
        self.btn['noteq'].SetToolTip(_('not equal to'))

        self.btn['compl'] = Button(parent=self.panel, id=wx.ID_ANY, label="~")
        self.btn['compl'].SetToolTip(_('one\'s complement'))
        self.btn['not'] = Button(parent=self.panel, id=wx.ID_ANY, label="!")
        self.btn['not'].SetToolTip(_('NOT'))
        self.btn['andbit'] = Button(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label='&&')
        self.btn['andbit'].SetToolTip(_('bitwise AND'))
        self.btn['orbit'] = Button(parent=self.panel, id=wx.ID_ANY, label="|")
        self.btn['orbit'].SetToolTip(_('bitwise OR'))
        self.btn['and'] = Button(parent=self.panel, id=wx.ID_ANY, label="&&&&")
        self.btn['and'].SetToolTip(_('logical AND'))
        self.btn['andnull'] = Button(parent=self.panel,
                                     id=wx.ID_ANY,
                                     label="&&&&&&")
        self.btn['andnull'].SetToolTip(_('logical AND (ignores NULLs)'))
        self.btn['or'] = Button(parent=self.panel, id=wx.ID_ANY, label="||")
        self.btn['or'].SetToolTip(_('logical OR'))
        self.btn['ornull'] = Button(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label="|||")
        self.btn['ornull'].SetToolTip(_('logical OR (ignores NULLs)'))
        self.btn['cond'] = Button(parent=self.panel,
                                  id=wx.ID_ANY,
                                  label="a ? b : c")
        self.btn['cond'].SetToolTip(_('conditional'))

        #
        # Text area
        #
        self.text_mcalc = TextCtrl(parent=self.panel,
                                   id=wx.ID_ANY,
                                   size=(-1, 100),
                                   style=wx.TE_MULTILINE)
        wx.CallAfter(self.text_mcalc.SetFocus)

        #
        # Map and function insertion text and ComboBoxes
        self.newmaplabel = StaticText(parent=self.panel, id=wx.ID_ANY)
        if self.rast3d:
            self.newmaplabel.SetLabel(
                _('Name for new 3D raster map to create'))
        else:
            self.newmaplabel.SetLabel(_('Name for new raster map to create'))
        # As we can write only to current mapset, names should not be fully qualified
        # to not confuse end user about writing in other mapset
        self.newmaptxt = Select(parent=self.panel,
                                id=wx.ID_ANY,
                                size=(250, -1),
                                type=element,
                                multiple=False,
                                fullyQualified=False)
        self.mapsellabel = StaticText(parent=self.panel, id=wx.ID_ANY)
        if self.rast3d:
            self.mapsellabel.SetLabel(_('Insert existing 3D raster map'))
        else:
            self.mapsellabel.SetLabel(_('Insert existing raster map'))
        self.mapselect = Select(parent=self.panel,
                                id=wx.ID_ANY,
                                size=(250, -1),
                                type=element,
                                multiple=False)
        self.functlabel = StaticText(parent=self.panel,
                                     id=wx.ID_ANY,
                                     label=_('Insert mapcalc function'))
        self.function = wx.ComboBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    size=(250, -1),
                                    choices=sorted(self.funct_dict.keys()),
                                    style=wx.CB_DROPDOWN | wx.CB_READONLY
                                    | wx.TE_PROCESS_ENTER)

        self.overwrite = wx.CheckBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=_("Allow output files to overwrite existing files"))
        self.overwrite.SetValue(
            UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))

        self.randomSeed = wx.CheckBox(
            parent=self.panel, label=_("Generate random seed for rand()"))
        self.randomSeedStaticText = StaticText(parent=self.panel,
                                               label=_("Seed:"))
        self.randomSeedText = TextCtrl(parent=self.panel,
                                       size=(100, -1),
                                       validator=IntegerValidator())
        self.randomSeedText.SetToolTip(_("Integer seed for rand() function"))
        self.randomSeed.SetValue(True)
        self.randomSeedStaticText.Disable()
        self.randomSeedText.Disable()

        self.addbox = wx.CheckBox(
            parent=self.panel,
            label=_('Add created raster map into layer tree'),
            style=wx.NO_BORDER)
        self.addbox.SetValue(
            UserSettings.Get(group='cmd', key='addNewLayer', subkey='enabled'))
        if not self.parent or self.parent.GetName() != 'LayerManager':
            self.addbox.Hide()

        #
        # Bindings
        #
        for btn in self.btn.keys():
            self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)

        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
        self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
        self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
        self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.btn_save.Bind(wx.EVT_BUTTON, self.OnSaveExpression)
        self.btn_load.Bind(wx.EVT_BUTTON, self.OnLoadExpression)
        self.btn_copy.Bind(wx.EVT_BUTTON, self.OnCopy)

        # self.mapselect.Bind(wx.EVT_TEXT, self.OnSelectTextEvt)
        self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
        self.function.Bind(wx.EVT_COMBOBOX, self._return_funct)
        self.function.Bind(wx.EVT_TEXT_ENTER, self.OnSelect)
        self.newmaptxt.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
        self.text_mcalc.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)
        self.overwrite.Bind(wx.EVT_CHECKBOX, self.OnUpdateStatusBar)
        self.randomSeed.Bind(wx.EVT_CHECKBOX, self.OnUpdateStatusBar)
        self.randomSeed.Bind(wx.EVT_CHECKBOX, self.OnSeedFlag)
        self.randomSeedText.Bind(wx.EVT_TEXT, self.OnUpdateStatusBar)

        self._layout()

        self.SetMinSize(self.panel.GetBestSize())
        # workaround for http://trac.wxwidgets.org/ticket/13628
        self.SetSize(self.panel.GetBestSize())
Esempio n. 25
0
File: base.py Progetto: seyi/grass
    def InitPlotOpts(self, plottype):
        """Initialize options for entire plot
        """
        self.plottype = plottype  # histogram, profile, or scatter

        self.properties = {}  # plot properties
        self.properties['font'] = {}
        self.properties['font']['prop'] = UserSettings.Get(group=self.plottype,
                                                           key='font')
        self.properties['font']['wxfont'] = wx.Font(11, wx.FONTFAMILY_SWISS,
                                                    wx.FONTSTYLE_NORMAL,
                                                    wx.FONTWEIGHT_NORMAL)

        self.properties['raster'] = {}
        self.properties['raster'] = UserSettings.Get(group=self.plottype,
                                                     key='raster')
        colstr = str(self.properties['raster']['pcolor'])
        self.properties['raster']['pcolor'] = tuple(
            int(colval) for colval in colstr.strip('()').split(','))

        if self.plottype == 'profile':
            self.properties['marker'] = UserSettings.Get(group=self.plottype,
                                                         key='marker')
            # changing color string to tuple for markers/points
            colstr = str(self.properties['marker']['color'])
            self.properties['marker']['color'] = tuple(
                int(colval) for colval in colstr.strip('()').split(','))

        self.properties['grid'] = UserSettings.Get(group=self.plottype,
                                                   key='grid')
        # changing color string to tuple
        colstr = str(self.properties['grid']['color'])
        self.properties['grid']['color'] = tuple(
            int(colval) for colval in colstr.strip('()').split(','))

        self.properties['x-axis'] = {}
        self.properties['x-axis']['prop'] = UserSettings.Get(
            group=self.plottype, key='x-axis')
        self.properties['x-axis']['axis'] = None

        self.properties['y-axis'] = {}
        self.properties['y-axis']['prop'] = UserSettings.Get(
            group=self.plottype, key='y-axis')
        self.properties['y-axis']['axis'] = None

        self.properties['legend'] = UserSettings.Get(group=self.plottype,
                                                     key='legend')

        self.zoom = False  # zooming disabled
        self.drag = False  # draging disabled
        # vertical and horizontal scrollbars
        self.client.showScrollbars = True

        # x and y axis set to normal (non-log)
        self.client.logScale = (False, False)
        if self.properties['x-axis']['prop']['type']:
            self.client.xSpec = self.properties['x-axis']['prop']['type']
        else:
            self.client.xSpec = 'auto'

        if self.properties['y-axis']['prop']['type']:
            self.client.ySpec = self.properties['y-axis']['prop']['type']
        else:
            self.client.ySpec = 'auto'
Esempio n. 26
0
    def _createViewPage(self, notebook):
        """Create notebook page for view settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel,
                         text=" %s " % _("View"))

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
                           label=" %s " % (_("View")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)
        row = 0
        # perspective
        pvals = UserSettings.Get(group='nviz', key='view', subkey='persp')
        ipvals = UserSettings.Get(
            group='nviz',
            key='view',
            subkey='persp',
            settings_type='internal')
        gridSizer.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
                                    label=_("Perspective:")),
                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        pval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                        initial=pvals['value'],
                        min=ipvals['min'],
                        max=ipvals['max'])
        self.winId['nviz:view:persp:value'] = pval.GetId()
        gridSizer.Add(pval, pos=(row, 2),
                      flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label=_("step:")), pos=(
                row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        pstep = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                         initial=pvals['step'],
                         min=ipvals['min'],
                         max=ipvals['max'] - 1)
        self.winId['nviz:view:persp:step'] = pstep.GetId()
        gridSizer.Add(pstep, pos=(row, 4),
                      flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # position
        posvals = UserSettings.Get(group='nviz', key='view', subkey='position')
        gridSizer.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
                                    label=_("Position:")),
                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label=_("x:")), pos=(
                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        px = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                      initial=posvals['x'] * 100,
                      min=0,
                      max=100)
        self.winId['nviz:view:position:x'] = px.GetId()
        gridSizer.Add(px, pos=(row, 2),
                      flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label="y:"), pos=(
                row, 3), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        py = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                      initial=posvals['y'] * 100,
                      min=0,
                      max=100)
        self.winId['nviz:view:position:y'] = py.GetId()
        gridSizer.Add(py, pos=(row, 4),
                      flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # height is computed dynamically

        # twist
        tvals = UserSettings.Get(group='nviz', key='view', subkey='twist')
        itvals = UserSettings.Get(
            group='nviz',
            key='view',
            subkey='twist',
            settings_type='internal')
        gridSizer.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
                                    label=_("Twist:")),
                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        tval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                        initial=tvals['value'],
                        min=itvals['min'],
                        max=itvals['max'])
        self.winId['nviz:view:twist:value'] = tval.GetId()
        gridSizer.Add(tval, pos=(row, 2),
                      flag=wx.ALIGN_CENTER_VERTICAL)
        row += 1

        # z-exag
        zvals = UserSettings.Get(group='nviz', key='view', subkey='z-exag')
        gridSizer.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
                                    label=_("Z-exag:")),
                      pos=(row, 0), flag=wx.ALIGN_CENTER_VERTICAL)
        gridSizer.Add(
            wx.StaticText(
                parent=panel, id=wx.ID_ANY, label=_("value:")), pos=(
                row, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)

        zval = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
                        initial=zvals['value'],
                        min=-1e6,
                        max=1e6)
        self.winId['nviz:view:z-exag:value'] = zval.GetId()
        gridSizer.Add(zval, pos=(row, 2),
                      flag=wx.ALIGN_CENTER_VERTICAL)

        boxSizer.Add(gridSizer, proportion=1,
                     flag=wx.ALL | wx.EXPAND, border=3)
        pageSizer.Add(boxSizer, proportion=0,
                      flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
                      border=3)

        box = wx.StaticBox(parent=panel, id=wx.ID_ANY,
                           label=" %s " % (_("Image Appearance")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        # background color
        gridSizer.Add(wx.StaticText(parent=panel, id=wx.ID_ANY,
                                    label=_("Background color:")),
                      pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL)

        color = csel.ColourSelect(
            panel,
            id=wx.ID_ANY,
            colour=UserSettings.Get(
                group='nviz',
                key='view',
                subkey=[
                    'background',
                    'color']),
            size=globalvar.DIALOG_COLOR_SIZE)
        color.SetName('GetColour')
        self.winId['nviz:view:background:color'] = color.GetId()
        gridSizer.Add(color, pos=(0, 1))

        gridSizer.AddGrowableCol(0)
        boxSizer.Add(gridSizer, proportion=1,
                     flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(boxSizer, proportion=0,
                      flag=wx.EXPAND | wx.ALL,
                      border=5)

        panel.SetSizer(pageSizer)

        return panel
Esempio n. 27
0
File: base.py Progetto: seyi/grass
    def InitRasterPairs(self, rasterList, plottype):
        """Initialize or update raster dictionary with raster pairs for
            bivariate scatterplots
        """

        if len(rasterList) == 0:
            return

        rdict = {}  # initialize a dictionary
        for rpair in rasterList:
            idx = rasterList.index(rpair)

            try:
                ret0 = grass.raster_info(rpair[0])
                ret1 = grass.raster_info(rpair[1])

            except:
                continue
                # if r.info cannot parse map, skip it

            self.raster[rpair] = UserSettings.Get(
                group=plottype, key='rasters')  # some default settings
            # initialize sub-dictionaries for each raster in the list
            rdict[rpair] = {}
            rdict[rpair][0] = {}
            rdict[rpair][1] = {}
            rdict[rpair][0]['units'] = ''
            rdict[rpair][1]['units'] = ''

            if ret0['units'] not in ('(none)', '"none"', '', None):
                rdict[rpair][0]['units'] = ret0['units']
            if ret1['units'] not in ('(none)', '"none"', '', None):
                rdict[rpair][1]['units'] = ret1['units']

            rdict[rpair]['plegend'] = rpair[0].split(
                '@')[0] + ' vs ' + rpair[1].split('@')[0]
            # list of cell value,frequency pairs for plotting histogram
            rdict[rpair]['datalist'] = []
            rdict[rpair][0]['datatype'] = ret0['datatype']
            rdict[rpair][1]['datatype'] = ret1['datatype']

            #
            # initialize with saved values
            #
            if self.properties['raster']['ptype'] is not None and \
                    self.properties['raster']['ptype'] != '':
                rdict[rpair]['ptype'] = self.properties['raster']['ptype']
            else:
                rdict[rpair]['ptype'] = 'dot'
            if self.properties['raster']['psize'] is not None:
                rdict[rpair]['psize'] = self.properties['raster']['psize']
            else:
                rdict[rpair]['psize'] = 1
            if self.properties['raster']['pfill'] is not None and \
                    self.properties['raster']['pfill'] != '':
                rdict[rpair]['pfill'] = self.properties['raster']['pfill']
            else:
                rdict[rpair]['pfill'] = 'solid'

            if idx <= len(self.colorList):
                rdict[rpair]['pcolor'] = self.colorDict[self.colorList[idx]]
            else:
                r = randint(0, 255)
                b = randint(0, 255)
                g = randint(0, 255)
                rdict[rpair]['pcolor'] = ((r, g, b, 255))

        return rdict
Esempio n. 28
0
    def _createLightPage(self, notebook):
        """Create notebook page for light settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel, text=" %s " % _("Lighting"))

        pageSizer = wx.BoxSizer(wx.VERTICAL)

        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % (_("Light")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        # position
        posvals = UserSettings.Get(group="nviz", key="light", subkey="position")
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Position:")),
            pos=(0, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("x:")),
            pos=(0, 1),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        px = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=posvals["x"] * 100,
            min=-100,
            max=100,
        )
        self.winId["nviz:light:position:x"] = px.GetId()
        gridSizer.Add(px, pos=(0, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label="y:"),
            pos=(0, 3),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        py = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=posvals["y"] * 100,
            min=-100,
            max=100,
        )
        self.winId["nviz:light:position:y"] = py.GetId()
        gridSizer.Add(py, pos=(0, 4), flag=wx.ALIGN_CENTER_VERTICAL)

        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("z:")),
            pos=(0, 5),
            flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT,
        )

        pz = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            size=(65, -1),
            initial=posvals["z"],
            min=0,
            max=100,
        )
        self.winId["nviz:light:position:z"] = pz.GetId()
        gridSizer.Add(pz, pos=(0, 6), flag=wx.ALIGN_CENTER_VERTICAL)

        # brightness
        brightval = UserSettings.Get(group="nviz", key="light", subkey="bright")
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Brightness:")),
            pos=(1, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        bright = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=brightval, min=0, max=100
        )
        self.winId["nviz:light:bright"] = bright.GetId()
        gridSizer.Add(bright, pos=(1, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        # ambient
        ambval = UserSettings.Get(group="nviz", key="light", subkey="ambient")
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Ambient:")),
            pos=(2, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        amb = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(65, -1), initial=ambval, min=0, max=100
        )
        self.winId["nviz:light:ambient"] = amb.GetId()
        gridSizer.Add(amb, pos=(2, 2), flag=wx.ALIGN_CENTER_VERTICAL)

        # light color
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Color:")),
            pos=(3, 0),
            flag=wx.ALIGN_CENTER_VERTICAL,
        )

        color = csel.ColourSelect(
            panel,
            id=wx.ID_ANY,
            colour=UserSettings.Get(group="nviz", key="light", subkey="color"),
            size=globalvar.DIALOG_COLOR_SIZE,
        )
        color.SetName("GetColour")
        self.winId["nviz:light:color"] = color.GetId()
        gridSizer.Add(color, pos=(3, 2))

        boxSizer.Add(gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=5)
        pageSizer.Add(boxSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)

        panel.SetSizer(pageSizer)

        return panel
Esempio n. 29
0
def main():
    gs.set_raise_on_error(False)

    options, flags = gs.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class RDigitMapFrame(MapFrame):
        def __init__(
            self,
            new_map=None,
            base_map=None,
            edit_map=None,
            map_type=None,
        ):
            MapFrame.__init__(
                self,
                parent=None,
                Map=Map(),
                giface=DMonGrassInterface(None),
                title=_("Raster Digitizer - GRASS GIS"),
                size=(850, 600),
            )
            # this giface issue not solved yet, we must set mapframe afterwards
            self._giface._mapframe = self
            self._giface.mapCreated.connect(self.OnMapCreated)
            self._mapObj = self.GetMap()

            # load raster map
            self._addLayer(name=new_map if new_map else edit_map)

            # switch toolbar
            self.AddToolbar("rdigit", fixed=True)

            rdigit = self.toolbars["rdigit"]
            if new_map:
                rdigit._mapSelectionCombo.Unbind(wx.EVT_COMBOBOX)
                self.rdigit.SelectNewMap(
                    standalone=True,
                    mapName=new_map,
                    bgMap=base_map,
                    mapType=map_type,
                )
                rdigit._mapSelectionCombo.Bind(
                    wx.EVT_COMBOBOX,
                    rdigit.OnMapSelection,
                )
            else:
                rdigit._mapSelectionCombo.SetSelection(n=1)
                rdigit.OnMapSelection()
            # use Close instead of QuitRDigit for standalone tool
            self.rdigit.quitDigitizer.disconnect(self.QuitRDigit)
            self.rdigit.quitDigitizer.connect(lambda: self.Close())

        def _addLayer(self, name, ltype="raster"):
            """Add layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            mapLayer = self._mapObj.AddLayer(
                ltype=ltype,
                name=name,
                command=["d.rast", "map={}".format(name)],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

        def OnMapCreated(self, name, ltype):
            """Add new created raster layer into map

            :param str name: map name
            :param str ltype: layer type
            """
            self._mapObj.Clean()
            self._addLayer(name=name, ltype=ltype)
            self.GetMapWindow().UpdateMap()

    kwargs = {
        "new_map": options["create"],
        "base_map": options["base"],
        "edit_map": options["edit"],
        "map_type": options["type"],
    }

    mapset = gs.gisenv()["MAPSET"]

    if kwargs["edit_map"]:
        edit_map = gs.find_file(
            name=kwargs["edit_map"],
            element="raster",
            mapset=mapset,
        )["fullname"]

        if not edit_map:
            gs.fatal(
                _(
                    "Raster map <{}> not found in current mapset.".format(
                        options["edit"], ), ), )
        else:
            kwargs["edit_map"] = edit_map
    else:
        if kwargs["base_map"]:
            base_map = gs.find_file(
                name=kwargs["base_map"],
                element="raster",
                mapset=mapset,
            )["fullname"]
            if not base_map:
                gs.fatal(
                    _(
                        "Base raster map <{}> not found in "
                        "current mapset.".format(options["base"], ), ), )
            kwargs["base_map"] = base_map

    # allow immediate rendering
    driver = UserSettings.Get(
        group="display",
        key="driver",
        subkey="type",
    )
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    app = wx.App()
    frame = RDigitMapFrame(**kwargs)
    frame.Show()

    app.MainLoop()
Esempio n. 30
0
 def _addRecord(self):
     return UserSettings.Get(group="vdigit",
                             key="addRecord",
                             subkey="enabled")