Ejemplo n.º 1
0
    def __init__(self, giface, cmdfile=None, mapfile=None):
        """Map composition (stack of map layers and overlays)

        :param cmdline: full path to the cmd file (defined by d.mon)
        :param mapfile: full path to the map file (defined by d.mon)
        """

        Map.__init__(self)

        self._giface = giface

        # environment settings
        self.env   = dict()

        self.cmdfile = cmdfile

        # list of layers for rendering added from cmd file
        # TODO temporary solution, layer managment by different tools in GRASS should be resovled
        self.ownedLayers = []

        if mapfile:
            self.mapfileCmd = mapfile
            self.maskfileCmd = os.path.splitext(mapfile)[0] + '.pgm'

        # generated file for g.pnmcomp output for rendering the map
        self.mapfile = monFile['map']
        if os.path.splitext(self.mapfile)[1] != '.ppm':
            self.mapfile += '.ppm'
        
        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute is cmd
        self.saveToFile = Signal('DMonMap.saveToFile')
        self.dToRast = Signal('DMonMap.dToRast')
        # signal sent when d.what.rast/vect appears in cmd file, attribute is cmd
        self.query = Signal('DMonMap.query')
Ejemplo n.º 2
0
    def __init__(self, giface, cmdfile=None, mapfile=None):
        """Map composition (stack of map layers and overlays)

        :param cmdline: full path to the cmd file (defined by d.mon)
        :param mapfile: full path to the map file (defined by d.mon)
        """

        Map.__init__(self)

        self._giface = giface

        # environment settings
        self.env = dict()

        self.cmdfile = cmdfile

        # list of layers for rendering added from cmd file
        # TODO temporary solution, layer managment by different tools in GRASS should be resovled
        self.ownedLayers = []

        if mapfile:
            self.mapfileCmd = mapfile
            self.maskfileCmd = os.path.splitext(mapfile)[0] + '.pgm'

        # generated file for g.pnmcomp output for rendering the map
        self.mapfile = monFile['map'] + '.ppm'
        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute is cmd
        self.saveToFile = Signal('DMonMap.saveToFile')
        self.dToRast = Signal('DMonMap.dToRast')
        # signal sent when d.what.rast/vect appears in cmd file, attribute is cmd
        self.query = Signal('DMonMap.query')
Ejemplo n.º 3
0
    def __init__(self, parent, giface, id=wx.ID_ANY,
                 title = _("GRASS GIS Histogramming Tool (d.histogram)"),
                 size = wx.Size(500, 350),
                 style = wx.DEFAULT_FRAME_STYLE, **kwargs):
        wx.Frame.__init__(self, parent, id, title, size = size, style = style, **kwargs)
        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))

        self._giface = giface
        self.Map   = Map()         # instance of render.Map to be associated with display
        self.layer = None          # reference to layer with histogram
        
        # Init variables
        self.params = {}  # previously set histogram parameters
        self.propwin = '' # ID of properties dialog
        
        self.font = ""
        self.encoding = 'ISO-8859-1' # default encoding for display fonts
        
        self.toolbar = HistogramToolbar(parent = self)
        # workaround for http://trac.wxwidgets.org/ticket/13888
        if sys.platform != 'darwin':
            self.SetToolBar(self.toolbar)

        # find selected map
        # might by moved outside this class
        # setting to None but honestly we do not handle no map case
        # TODO: when self.mapname is None content of map window is showed
        self.mapname = None
        layers = self._giface.GetLayerList().GetSelectedLayers(checkedOnly=False)
        if len(layers) > 0:
            self.mapname = layers[0].maplayer.name

        # Add statusbar
        self.statusbar = self.CreateStatusBar(number = 1, style = 0)
        # self.statusbar.SetStatusWidths([-2, -1])
        hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
        for i in range(len(hist_frame_statusbar_fields)):
            self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)
        
        # Init map display
        self.InitDisplay() # initialize region values
        
        # initialize buffered DC
        self.HistWindow = BufferedWindow(self, id = wx.ID_ANY, Map = self.Map) # initialize buffered DC
        
        # Bind various events
        self.Bind(wx.EVT_CLOSE,    self.OnCloseWindow)
        
        # Init print module and classes
        self.printopt = PrintOptions(self, self.HistWindow)
        
        # Add layer to the map
        self.layer = self.Map.AddLayer(ltype = "command", name = 'histogram', command = [['d.histogram']],
                                       active = False, hidden = False, opacity = 1, render = False)
        if self.mapname:
            self.SetHistLayer(self.mapname, None)
        else:
            self.OnErase(None)
            wx.CallAfter(self.OnOptions, None)
Ejemplo n.º 4
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()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()

    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()
Ejemplo n.º 5
0
    def __init__(self, giface, cmdfile=None, mapfile=None):
        """Map composition (stack of map layers and overlays)

        :param cmdline: full path to the cmd file (defined by d.mon)
        :param mapfile: full path to the map file (defined by d.mon)
        """
        Map.__init__(self)

        self._giface = giface

        # environment settings
        self.env = dict()

        self.cmdfile = cmdfile

        # list of layers for rendering added from cmd file
        # TODO temporary solution, layer management by different tools in GRASS
        # should be resolved
        self.ownedLayers = []
        self.oldOverlays = []

        if mapfile:
            self.mapfileCmd = mapfile
            self.maskfileCmd = os.path.splitext(mapfile)[0] + '.pgm'

        # generated file for g.pnmcomp output for rendering the map
        self.mapfile = monFile['map']
        if os.path.splitext(self.mapfile)[1] != '.ppm':
            self.mapfile += '.ppm'

        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute
        # is cmd
        self.saveToFile = Signal('DMonMap.saveToFile')
        self.dToRast = Signal('DMonMap.dToRast')
        # signal sent when d.what.rast/vect appears in cmd file, attribute is
        # cmd
        self.query = Signal('DMonMap.query')

        self.renderMgr = RenderMapMgr(self)

        # update legend file variable with the one d.mon uses
        with open(monFile['env'], 'r') as f:
            lines = f.readlines()
            for line in lines:
                if 'GRASS_LEGEND_FILE' in line:
                    legfile = line.split('=', 1)[1].strip()
                    self.renderMgr.UpdateRenderEnv(
                        {'GRASS_LEGEND_FILE': legfile})
                    break
Ejemplo n.º 6
0
    def __init__(self, giface, cmdfile=None, mapfile=None):
        """Map composition (stack of map layers and overlays)

        :param cmdline: full path to the cmd file (defined by d.mon)
        :param mapfile: full path to the map file (defined by d.mon)
        """
        Map.__init__(self)

        self._giface = giface

        # environment settings
        self.env = dict()

        self.cmdfile = cmdfile

        # list of layers for rendering added from cmd file
        # TODO temporary solution, layer managment by different tools in GRASS
        # should be resovled
        self.ownedLayers = []
        self.oldOverlays = []

        if mapfile:
            self.mapfileCmd = mapfile
            self.maskfileCmd = os.path.splitext(mapfile)[0] + '.pgm'

        # generated file for g.pnmcomp output for rendering the map
        self.mapfile = monFile['map']
        if os.path.splitext(self.mapfile)[1] != '.ppm':
            self.mapfile += '.ppm'

        # signal sent when d.out.file/d.to.rast appears in cmd file, attribute
        # is cmd
        self.saveToFile = Signal('DMonMap.saveToFile')
        self.dToRast = Signal('DMonMap.dToRast')
        # signal sent when d.what.rast/vect appears in cmd file, attribute is
        # cmd
        self.query = Signal('DMonMap.query')

        self.renderMgr = RenderMapMgr(self)

        # update legend file variable with the one d.mon uses
        with open(monFile['env'], 'r') as f:
            lines = f.readlines()
            for line in lines:
                if 'GRASS_LEGEND_FILE' in line:
                    legfile = line.split('=', 1)[1].strip()
                    self.renderMgr.UpdateRenderEnv({'GRASS_LEGEND_FILE': legfile})
                    break
Ejemplo n.º 7
0
    def OnInit(self):
        if not globalvar.CheckWxVersion([2, 9]):
            wx.InitAllImageHandlers()
        if __name__ == "__main__":
            self.cmdTimeStamp = os.path.getmtime(monFile['cmd'])
            self.Map = Map(cmdfile=monFile['cmd'],
                           mapfile=monFile['map'],
                           envfile=monFile['env'],
                           monitor=monName)
        else:
            self.Map = None

        self.mapFrm = MapFrame(parent=None,
                               id=wx.ID_ANY,
                               Map=self.Map,
                               size=monSize)
        # self.SetTopWindow(Map)
        self.mapFrm.Show()

        if __name__ == "__main__":
            self.timer = wx.PyTimer(self.watcher)
            #check each 0.5s
            global mtime
            mtime = 500
            self.timer.Start(mtime)

        return True
Ejemplo n.º 8
0
        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()
Ejemplo n.º 9
0
        def __init__(self, vectorMap):
            MapFrame.__init__(
                self,
                parent=None,
                Map=Map(),
                giface=DMonGrassInterface(None),
                title=_("Vector Digitizer - GRASS GIS"),
                size=(850, 600),
            )
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype="vector",
                name=vectorMap,
                command=["d.vect", "map=%s" % vectorMap],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

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

            # start editing
            self.toolbars["vdigit"].StartEditing(mapLayer)
Ejemplo n.º 10
0
    def Render(self, *args, **kwargs):
        """Render layer to image.

        For input params and returned data see overridden method in Map class.
        """
        ret = Map.Render(self, *args, **kwargs)

        return ret
Ejemplo n.º 11
0
    def __buildPreviewPanel(self):
        """
        Creates preview panel.
        :return: void
        """
        #Output preview
        self.map = Map()
        self.width = self.map.width = 400
        self.height = self.map.height = 300
        self.map.geom = self.width, self.height

        self.preview = BufferedWindow(parent=self,
                                      id=wx.NewId(),
                                      size=(400, 300),
                                      Map=self.map)
        self.preview.EraseMap()
Ejemplo n.º 12
0
    def AddLayer(self, *args, **kwargs):
        """Adds generic map layer to list of layers.

        For input params and returned data see overridden method in Map class.
        """
        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"

        layer = Map.AddLayer(self, *args, **kwargs)

        del os.environ["GRASS_RENDER_IMMEDIATE"]

        return layer
Ejemplo n.º 13
0
        def __init__(self, parent, vectorMap):
            MapPanel.__init__(self,
                              parent=parent,
                              Map=Map(),
                              giface=DMonGrassInterface(None))

            # set system icon
            parent.SetIcon(
                wx.Icon(os.path.join(ICONDIR, "grass_map.ico"),
                        wx.BITMAP_TYPE_ICO))

            # bindings
            parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

            # extend shortcuts and create frame accelerator table
            self.shortcuts_table.append(
                (self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
            self._initShortcuts()

            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype="vector",
                name=vectorMap,
                command=["d.vect", "map=%s" % vectorMap],
                active=True,
                hidden=False,
                opacity=1.0,
                render=True,
            )

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

            # start editing
            self.toolbars["vdigit"].StartEditing(mapLayer)
            # use Close instead of QuitVDigit for standalone tool
            self.toolbars["vdigit"].quitDigitizer.disconnect(self.QuitVDigit)
            self.toolbars["vdigit"].quitDigitizer.connect(lambda: self.Close())

            # add Map Display panel to Map Display frame
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self, proportion=1, flag=wx.EXPAND)
            parent.SetSizer(sizer)
            parent.Layout()
Ejemplo n.º 14
0
class HistogramFrame(wx.Frame):
    """Main frame for hisgram display window. Uses d.histogram
    rendered onto canvas
    """
    def __init__(self,
                 parent,
                 giface,
                 id=wx.ID_ANY,
                 title=_("GRASS GIS Histogramming Tool (d.histogram)"),
                 size=wx.Size(500, 350),
                 style=wx.DEFAULT_FRAME_STYLE,
                 **kwargs):
        wx.Frame.__init__(self,
                          parent,
                          id,
                          title,
                          size=size,
                          style=style,
                          **kwargs)
        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, 'grass.ico'),
                    wx.BITMAP_TYPE_ICO))

        self._giface = giface
        self.Map = Map(
        )  # instance of render.Map to be associated with display
        self.layer = None  # reference to layer with histogram

        # Init variables
        self.params = {}  # previously set histogram parameters
        self.propwin = ''  # ID of properties dialog

        self.font = ""
        self.encoding = 'ISO-8859-1'  # default encoding for display fonts

        self.toolbar = HistogramToolbar(parent=self)
        # workaround for http://trac.wxwidgets.org/ticket/13888
        if sys.platform != 'darwin':
            self.SetToolBar(self.toolbar)

        # find selected map
        # might by moved outside this class
        # setting to None but honestly we do not handle no map case
        # TODO: when self.mapname is None content of map window is showed
        self.mapname = None
        layers = self._giface.GetLayerList().GetSelectedLayers(
            checkedOnly=False)
        if len(layers) > 0:
            self.mapname = layers[0].maplayer.name

        # Add statusbar
        self.statusbar = self.CreateStatusBar(number=1, style=0)
        # self.statusbar.SetStatusWidths([-2, -1])
        hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
        for i in range(len(hist_frame_statusbar_fields)):
            self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)

        # Init map display
        self.InitDisplay()  # initialize region values

        # initialize buffered DC
        self.HistWindow = BufferedWindow(
            self, id=wx.ID_ANY, Map=self.Map)  # initialize buffered DC

        # Bind various events
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # Init print module and classes
        self.printopt = PrintOptions(self, self.HistWindow)

        # Add layer to the map
        self.layer = self.Map.AddLayer(ltype="command",
                                       name='histogram',
                                       command=[['d.histogram']],
                                       active=False,
                                       hidden=False,
                                       opacity=1,
                                       render=False)
        if self.mapname:
            self.SetHistLayer(self.mapname, None)
        else:
            self.OnErase(None)
            wx.CallAfter(self.OnOptions, None)

    def InitDisplay(self):
        """Initialize histogram display, set dimensions and region
        """
        self.width, self.height = self.GetClientSize()
        self.Map.geom = self.width, self.height

    def OnOptions(self, event):
        """Change histogram settings"""
        cmd = ['d.histogram']
        if self.mapname != '':
            cmd.append('map=%s' % self.mapname)
        module = GUI(parent=self)
        module.ParseCommand(cmd,
                            completed=(self.GetOptData, None, self.params))

    def GetOptData(self, dcmd, layer, params, propwin):
        """Callback method for histogram command generated by dialog
        created in menuform.py
        """
        if dcmd:
            name, found = GetLayerNameFromCmd(dcmd,
                                              fullyQualified=True,
                                              layerType='raster')
            if not found:
                GError(parent=propwin,
                       message=_("Raster map <%s> not found") % name)
                return

            self.SetHistLayer(name, dcmd)
        self.params = params
        self.propwin = propwin
        self.HistWindow.UpdateHist()

    def SetHistLayer(self, name, cmd=None):
        """Set histogram layer
        """
        self.mapname = name
        if not cmd:
            cmd = ['d.histogram', ('map=%s' % self.mapname)]
        self.layer = self.Map.ChangeLayer(layer=self.layer,
                                          command=[cmd],
                                          active=True)

        return self.layer

    def SetHistFont(self, event):
        """Set font for histogram. If not set, font will be default
        display font.
        """
        dlg = DefaultFontDialog(parent=self,
                                id=wx.ID_ANY,
                                title=_('Select font for histogram text'))
        dlg.fontlb.SetStringSelection(self.font, True)

        if dlg.ShowModal() == wx.ID_CANCEL:
            dlg.Destroy()
            return

        # set default font type, font, and encoding to whatever selected in dialog
        if dlg.font != None:
            self.font = dlg.font
        if dlg.encoding != None:
            self.encoding = dlg.encoding

        dlg.Destroy()
        self.HistWindow.UpdateHist()

    def OnErase(self, event):
        """Erase the histogram display
        """
        self.HistWindow.Draw(self.HistWindow.pdc, pdctype='clear')

    def OnRender(self, event):
        """Re-render histogram
        """
        self.HistWindow.UpdateHist()

    def GetWindow(self):
        """Get buffered window"""
        return self.HistWindow

    def SaveToFile(self, event):
        """Save to file
        """
        filetype, ltype = GetImageHandlers(self.HistWindow.img)

        # get size
        dlg = ImageSizeDialog(self)
        dlg.CentreOnParent()
        if dlg.ShowModal() != wx.ID_OK:
            dlg.Destroy()
            return
        width, height = dlg.GetValues()
        dlg.Destroy()

        # get filename
        dlg = wx.FileDialog(parent=self,
                            message=_("Choose a file name to save the image "
                                      "(no need to add extension)"),
                            wildcard=filetype,
                            style=wx.SAVE | wx.FD_OVERWRITE_PROMPT)

        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            if not path:
                dlg.Destroy()
                return

            base, ext = os.path.splitext(path)
            fileType = ltype[dlg.GetFilterIndex()]['type']
            extType = ltype[dlg.GetFilterIndex()]['ext']
            if ext != extType:
                path = base + '.' + extType

            self.HistWindow.SaveToFile(path, fileType, width, height)

        self.HistWindow.UpdateHist()
        dlg.Destroy()

    def PrintMenu(self, event):
        """Print options and output menu
        """
        point = wx.GetMousePosition()
        printmenu = wx.Menu()
        # Add items to the menu
        setup = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Page setup'))
        printmenu.AppendItem(setup)
        self.Bind(wx.EVT_MENU, self.printopt.OnPageSetup, setup)

        preview = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Print preview'))
        printmenu.AppendItem(preview)
        self.Bind(wx.EVT_MENU, self.printopt.OnPrintPreview, preview)

        doprint = wx.MenuItem(printmenu, id=wx.ID_ANY, text=_('Print display'))
        printmenu.AppendItem(doprint)
        self.Bind(wx.EVT_MENU, self.printopt.OnDoPrint, doprint)

        # Popup the menu.  If an item is selected then its handler
        # will be called before PopupMenu returns.
        self.PopupMenu(printmenu)
        printmenu.Destroy()

    def OnQuit(self, event):
        self.Close(True)

    def OnCloseWindow(self, event):
        """Window closed
        Also remove associated rendered images
        """
        try:
            self.propwin.Close(True)
        except:
            pass
        self.Map.Clean()
        self.Destroy()
Ejemplo n.º 15
0
    def __init__(self, parent, samplingType, icon=None, map_=None):
        wx.Panel.__init__(self, parent=parent)

        self.mapWindowProperties = MapWindowProperties()
        self.mapWindowProperties.setValuesFromUserSettings()
        giface = StandaloneGrassInterface()
        self.samplingtype = samplingType
        self.parent = parent

        if map_:
            self.map_ = map_
        else:
            self.map_ = Map()
        self.map_.region = self.map_.GetRegion()

        self._mgr = wx.aui.AuiManager(self)
        self.mapWindow = BufferedMapWindow(parent=self, giface=giface,
                                           Map=self.map_,
                                           properties=self.mapWindowProperties)
        self._mgr.AddPane(self.mapWindow, wx.aui.AuiPaneInfo().CentrePane().
                          Dockable(True).BestSize((-1, -1)).Name('mapwindow').
                          CloseButton(False).DestroyOnClose(True).
                          Layer(0))
        self._toolSwitcher = ToolSwitcher()
        self._toolSwitcher.toggleToolChanged.connect(self._onToolChanged)
        self.toolbar = RLiSetupToolbar(self, self._toolSwitcher)

        self.catId = 1

        self._mgr.AddPane(self.toolbar,
                          wx.aui.AuiPaneInfo().
                          Name("maptoolbar").Caption(_("Map Toolbar")).
                          ToolbarPane().Left().Name('mapToolbar').
                          CloseButton(False).Layer(1).Gripper(False).
                          BestSize((self.toolbar.GetBestSize())))
        self._mgr.Update()

        if self.samplingtype == SamplingType.REGIONS:
            self.afterRegionDrawn = Signal('RLiSetupMapPanel.afterRegionDrawn')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='line')
        elif self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
            self.sampleFrameChanged = Signal(
                'RLiSetupMapPanel.sampleFrameChanged')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='rectangle')
        elif self.samplingtype in [SamplingType.MUNITSC, SamplingType.MMVWINC]:
            self.afterCircleDrawn = Signal('RLiSetupMapPanel.afterCircleDrawn')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='line')
        else:
            self.sampleFrameChanged = Signal(
                'RLiSetupMapPanel.sampleFrameChanged')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='rectangle')

        self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=2,
                                                           style=wx.SOLID))
        self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]],
                                         penName='rlisetup', hide=True)

        if self.samplingtype != SamplingType.VECT:
            self.toolbar.SelectDefault()
Ejemplo n.º 16
0
class RLiSetupMapPanel(wx.Panel):
    """Panel with mapwindow used in r.li.setup"""

    def __init__(self, parent, samplingType, icon=None, map_=None):
        wx.Panel.__init__(self, parent=parent)

        self.mapWindowProperties = MapWindowProperties()
        self.mapWindowProperties.setValuesFromUserSettings()
        giface = StandaloneGrassInterface()
        self.samplingtype = samplingType
        self.parent = parent

        if map_:
            self.map_ = map_
        else:
            self.map_ = Map()
        self.map_.region = self.map_.GetRegion()

        self._mgr = wx.aui.AuiManager(self)
        self.mapWindow = BufferedMapWindow(parent=self, giface=giface,
                                           Map=self.map_,
                                           properties=self.mapWindowProperties)
        self._mgr.AddPane(self.mapWindow, wx.aui.AuiPaneInfo().CentrePane().
                          Dockable(True).BestSize((-1, -1)).Name('mapwindow').
                          CloseButton(False).DestroyOnClose(True).
                          Layer(0))
        self._toolSwitcher = ToolSwitcher()
        self._toolSwitcher.toggleToolChanged.connect(self._onToolChanged)
        self.toolbar = RLiSetupToolbar(self, self._toolSwitcher)

        self.catId = 1

        self._mgr.AddPane(self.toolbar,
                          wx.aui.AuiPaneInfo().
                          Name("maptoolbar").Caption(_("Map Toolbar")).
                          ToolbarPane().Left().Name('mapToolbar').
                          CloseButton(False).Layer(1).Gripper(False).
                          BestSize((self.toolbar.GetBestSize())))
        self._mgr.Update()

        if self.samplingtype == SamplingType.REGIONS:
            self.afterRegionDrawn = Signal('RLiSetupMapPanel.afterRegionDrawn')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='line')
        elif self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
            self.sampleFrameChanged = Signal(
                'RLiSetupMapPanel.sampleFrameChanged')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='rectangle')
        elif self.samplingtype in [SamplingType.MUNITSC, SamplingType.MMVWINC]:
            self.afterCircleDrawn = Signal('RLiSetupMapPanel.afterCircleDrawn')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='line')
        else:
            self.sampleFrameChanged = Signal(
                'RLiSetupMapPanel.sampleFrameChanged')
            self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
                graphicsType='rectangle')

        self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=2,
                                                           style=wx.SOLID))
        self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]],
                                         penName='rlisetup', hide=True)

        if self.samplingtype != SamplingType.VECT:
            self.toolbar.SelectDefault()

    def GetMap(self):
        return self.map_

    def OnPan(self, event):
        """Panning, set mouse to drag."""
        self.mapWindow.SetModePan()

    def OnZoomIn(self, event):
        """Zoom in the map."""
        self.mapWindow.SetModeZoomIn()

    def OnZoomOut(self, event):
        """Zoom out the map."""
        self.mapWindow.SetModeZoomOut()

    def OnZoomToMap(self, event):
        layers = self.map_.GetListOfLayers()
        self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)

    def OnDrawRadius(self, event):
        """Start draw mode"""
        self.mapWindow.mouse['use'] = "None"
        self.mapWindow.mouse['box'] = "line"
        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
                                    style=wx.SHORT_DASH)
        self.mapWindow.SetNamedCursor('cross')
        self.mapWindow.mouseLeftUp.connect(self._radiusDrawn)

    def OnDigitizeRegion(self, event):
        """Start draw mode"""
        self.mapWindow.mouse['use'] = "None"
        self.mapWindow.mouse['box'] = "line"
        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
                                    style=wx.SHORT_DASH)
        self.mapWindow.SetNamedCursor('cross')
        self.mapWindow.mouseLeftUp.connect(self._lineSegmentDrawn)
        self.mapWindow.mouseDClick.connect(self._mouseDbClick)

        self._registeredGraphics.GetItem(0).SetCoords([])

    def OnDraw(self, event):
        """Start draw mode"""
        self.mapWindow.mouse['use'] = "None"
        self.mapWindow.mouse['box'] = "box"
        self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2,
                                    style=wx.SHORT_DASH)
        self.mapWindow.SetNamedCursor('cross')
        self.mapWindow.mouseLeftUp.connect(self._rectangleDrawn)

    def _lineSegmentDrawn(self, x, y):
        item = self._registeredGraphics.GetItem(0)
        coords = item.GetCoords()
        if len(coords) == 0:
            coords.extend([self.mapWindow.Pixel2Cell(
                self.mapWindow.mouse['begin'])])
        coords.extend([[x, y]])

        item.SetCoords(coords)
        item.SetPropertyVal('hide', False)
        self.mapWindow.ClearLines()
        self._registeredGraphics.Draw()

    def _mouseDbClick(self, x, y):
        item = self._registeredGraphics.GetItem(0)
        coords = item.GetCoords()
        coords.extend([[x, y]])
        item.SetCoords(coords)
        item.SetPropertyVal('hide', False)
        self.mapWindow.ClearLines()
        self._registeredGraphics.Draw()
        self.createRegion()

    def createRegion(self):
        dlg = wx.TextEntryDialog(None, 'Name of sample region',
                                 'Create region', 'region' + str(self.catId))
        ret = dlg.ShowModal()
        while True:
            if ret == wx.ID_OK:
                raster = dlg.GetValue()
                if checkMapExists(raster):
                    GMessage(
                        parent=self, message=_(
                            "The raster file %s already"
                            " exists, please change name") %
                        raster)
                    ret = dlg.ShowModal()
                else:
                    dlg.Destroy()
                    marea = self.writeArea(
                        self._registeredGraphics.GetItem(0).GetCoords(), raster)
                    self.nextRegion(next=True, area=marea)
                    break
            else:
                self.nextRegion(next=False)
                break

    def nextRegion(self, next=True, area=None):
        self.mapWindow.ClearLines()
        item = self._registeredGraphics.GetItem(0)
        item.SetCoords([])
        item.SetPropertyVal('hide', True)

        layers = self.map_.GetListOfLayers()
        self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
        if next is True:
            self.afterRegionDrawn.emit(marea=area)
        else:
            gcmd.GMessage(parent=self.parent, message=_(
                "Raster map not created. Please redraw region."))

    def writeArea(self, coords, rasterName):
        polyfile = tempfile.NamedTemporaryFile(delete=False)
        polyfile.write("AREA\n")
        for coor in coords:
            east, north = coor
            point = " %s %s\n" % (east, north)
            polyfile.write(point)

        catbuf = "=%d a\n" % self.catId
        polyfile.write(catbuf)
        self.catId = self.catId + 1

        polyfile.close()
        region_settings = grass.parse_command('g.region', flags='p',
                                              delimiter=':')
        pname = polyfile.name.split('/')[-1]
        tmpraster = "rast_" + pname
        tmpvector = "vect_" + pname
        wx.BeginBusyCursor()
        wx.GetApp().Yield()
        RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
                   rows=region_settings['rows'], overwrite=True)

        RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
                   type='area', overwrite=True)

        RunCommand('v.to.rast', input=tmpvector, output=rasterName,
                   value=1, use='val')
        wx.EndBusyCursor()
        grass.use_temp_region()
        grass.run_command('g.region', vector=tmpvector)
        region = grass.region()

        marea = MaskedArea(region, rasterName)

        RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
        RunCommand('g.remove', flags='f', type='vector', name=tmpvector)

        os.unlink(polyfile.name)
        return marea

    def _onToolChanged(self):
        """Helper function to disconnect drawing"""
        try:
            self.mapWindow.mouseLeftUp.disconnect(self._rectangleDrawn)
            self.mapWindow.mouseLeftUp.disconnect(self._radiusDrawn)
            self.mapWindow.mouseMoving.disconnect(self._mouseMoving)
            self.mapWindow.mouseLeftDown.disconnect(self._mouseLeftDown)
            self.mapWindow.mouseDClick.disconnect(self._mouseDbClick)
        except DispatcherKeyError:
            pass

    def _radiusDrawn(self, x, y):
        """When drawing finished, get region values"""
        mouse = self.mapWindow.mouse
        item = self._registeredGraphics.GetItem(0)
        p1 = mouse['begin']
        p2 = mouse['end']
        dist, (north, east) = self.mapWindow.Distance(p1, p2, False)
        circle = Circle(p1, dist)
        self.mapWindow.ClearLines()
        self.mapWindow.pdcTmp.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
        pen = wx.Pen(colour=wx.RED, width=2)
        self.mapWindow.pdcTmp.SetPen(pen)
        self.mapWindow.pdcTmp.DrawCircle(circle.point[0], circle.point[1],
                                         circle.radius)
        self._registeredGraphics.Draw()
        self.createCricle(circle)

    def createCricle(self, c):
        dlg = wx.TextEntryDialog(None,
                                 'Name of sample circle region',
                                 'Create circle region',
                                 'circle' + str(self.catId))
        ret = dlg.ShowModal()
        while True:
            if ret == wx.ID_OK:
                raster = dlg.GetValue()
                if checkMapExists(raster):
                    GMessage(
                        parent=self, message=_(
                            "The raster file %s already"
                            " exists, please change name") %
                        raster)
                    ret = dlg.ShowModal()
                else:
                    dlg.Destroy()
                    circle = self.writeCircle(c, raster)
                    self.nextCircle(next=True, circle=circle)
                    break
            else:
                self.nextCircle(next=False)
                break

    def nextCircle(self, next=True, circle=None):
        self.mapWindow.ClearLines()
        item = self._registeredGraphics.GetItem(0)
        item.SetPropertyVal('hide', True)
        layers = self.map_.GetListOfLayers()
        self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
        if next is True:
            self.afterCircleDrawn.emit(region=circle)
        else:
            gcmd.GMessage(parent=self.parent, message=_(
                "Raster map not created. redraw region again."))

    def writeCircle(self, circle, rasterName):
        coords = self.mapWindow.Pixel2Cell(circle.point)
        RunCommand('r.circle', output=rasterName, max=circle.radius,
                   coordinate=coords, flags="b")
        grass.use_temp_region()
        grass.run_command('g.region', zoom=rasterName)
        region = grass.region()
        marea = MaskedArea(region, rasterName, circle.radius)
        return marea

    def _rectangleDrawn(self):
        """When drawing finished, get region values"""
        mouse = self.mapWindow.mouse
        item = self._registeredGraphics.GetItem(0)
        p1 = self.mapWindow.Pixel2Cell(mouse['begin'])
        p2 = self.mapWindow.Pixel2Cell(mouse['end'])
        item.SetCoords([p1, p2])
        region = {'n': max(p1[1], p2[1]),
                  's': min(p1[1], p2[1]),
                  'w': min(p1[0], p2[0]),
                  'e': max(p1[0], p2[0])}
        item.SetPropertyVal('hide', False)
        self.mapWindow.ClearLines()
        self._registeredGraphics.Draw()
        if self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
            dlg = wx.MessageDialog(self, "Is this area ok?",
                                   "select sampling unit",
                                   wx.YES_NO | wx.ICON_QUESTION)
            ret = dlg.ShowModal()
            if ret == wx.ID_YES:
                grass.use_temp_region()
                grass.run_command('g.region', n=region['n'], s=region['s'],
                                  e=region['e'], w=region['w'])
                tregion = grass.region()
                self.sampleFrameChanged.emit(region=tregion)
                self.mapWindow.ClearLines()
                item = self._registeredGraphics.GetItem(0)
                item.SetPropertyVal('hide', True)
                layers = self.map_.GetListOfLayers()
                self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False,
                                         render=True)
            else:
                self.nextRegion(next=False)
            dlg.Destroy()

        elif self.samplingtype != SamplingType.WHOLE:
            """When drawing finished, get region values"""
            self.sampleFrameChanged.emit(region=region)
Ejemplo n.º 17
0
    def __init__(
        self,
        parent,
        giface,
        title=_("Example Tool"),
        toolbars=["MiscToolbar", "MapToolbar", "MainToolbar"],
        size=(800, 600),
        name="exampleWindow",
        **kwargs,
    ):
        """!Map Frame constructor

        @param parent (no parent is expected)
        @param title window title
        @param toolbars list of active toolbars (default value represents all toolbars)
        @param size default size
        """
        SingleMapFrame.__init__(
            self, parent=parent, title=title, name=name, Map=Map(), **kwargs
        )

        # Place debug message where appropriate
        # and set debug level from 1 to 5 (higher to lower level functions).
        # To enable debug mode write:
        # > g.gisenv set=WX_DEBUG=5
        Debug.msg(1, "ExampleMapFrame.__init__()")

        #
        # Add toolbars to aui manager
        #
        toolbarsCopy = toolbars[:]
        # workaround to have the same toolbar order on all platforms
        if sys.platform == "win32":
            toolbarsCopy.reverse()

        for toolbar in toolbarsCopy:
            self.AddToolbar(toolbar)

        self.mapWindowProperties = MapWindowProperties()
        self.mapWindowProperties.setValuesFromUserSettings()
        self.mapWindowProperties.autoRenderChanged.connect(
            lambda value: self.OnRender(None) if value else None
        )
        #
        # Add statusbar
        #

        # choose items in statusbar choice, which makes sense for your application
        self.statusbarItems = [
            sb.SbCoordinates,
            sb.SbRegionExtent,
            sb.SbCompRegionExtent,
            sb.SbShowRegion,
            sb.SbAlignExtent,
            sb.SbResolution,
            sb.SbDisplayGeometry,
            sb.SbMapScale,
            sb.SbGoTo,
            sb.SbProjection,
        ]

        # create statusbar and its manager
        statusbar = self.CreateStatusBar(number=4, style=0)
        statusbar.SetStatusWidths([-5, -2, -1, -1])
        self.statusbarManager = sb.SbManager(mapframe=self, statusbar=statusbar)

        # fill statusbar manager
        self.statusbarManager.AddStatusbarItemsByClass(
            self.statusbarItems, mapframe=self, statusbar=statusbar
        )
        self.statusbarManager.AddStatusbarItem(
            sb.SbMask(self, statusbar=statusbar, position=2)
        )
        self.statusbarManager.AddStatusbarItem(
            sb.SbRender(self, statusbar=statusbar, position=3)
        )

        self.statusbarManager.Update()

        # create map window
        self.MapWindow = BufferedMapWindow(
            parent=self,
            Map=self.GetMap(),
            properties=self.mapWindowProperties,
            giface=self,
        )
        self._setUpMapWindow(self.MapWindow)
        self.MapWindow.InitZoomHistory()

        # create whatever you want, here it is a widget for displaying raster info
        self.info = ExampleInfoTextManager(self)

        # add map window (and other widgets) to aui manager
        self._addPanes()
        self._mgr.Update()

        # initialize variables related to your application functionality
        self.InitVariables()

        # default action
        self.GetMapToolbar().SelectDefault()

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        self.SetSize(size)
Ejemplo n.º 18
0
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 title=_("GRASS GIS Histogramming Tool (d.histogram)"),
                 size=wx.Size(500, 350),
                 style=wx.DEFAULT_FRAME_STYLE,
                 **kwargs):
        wx.Frame.__init__(self,
                          parent,
                          id,
                          title,
                          size=size,
                          style=style,
                          **kwargs)
        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'),
                    wx.BITMAP_TYPE_ICO))

        self.Map = Map(
        )  # instance of render.Map to be associated with display
        self.layer = None  # reference to layer with histogram

        # Init variables
        self.params = {}  # previously set histogram parameters
        self.propwin = ''  # ID of properties dialog

        self.font = ""
        self.encoding = 'ISO-8859-1'  # default encoding for display fonts

        self.toolbar = HistogramToolbar(parent=self)
        self.SetToolBar(self.toolbar)

        # find selected map
        self.mapname = None
        if parent.GetName() == "MapWindow" and not parent.IsStandalone():
            tree = parent.GetLayerManager().GetLayerTree()

            if tree.layer_selected and tree.GetPyData(
                    tree.layer_selected)[0]['type'] == 'raster':
                self.mapname = tree.GetPyData(
                    tree.layer_selected)[0]['maplayer'].name

        # Add statusbar
        self.statusbar = self.CreateStatusBar(number=1, style=0)
        # self.statusbar.SetStatusWidths([-2, -1])
        hist_frame_statusbar_fields = ["Histogramming %s" % self.mapname]
        for i in range(len(hist_frame_statusbar_fields)):
            self.statusbar.SetStatusText(hist_frame_statusbar_fields[i], i)

        # Init map display
        self.InitDisplay()  # initialize region values

        # initialize buffered DC
        self.HistWindow = BufferedWindow(
            self, id=wx.ID_ANY, Map=self.Map)  # initialize buffered DC

        # Bind various events
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        # Init print module and classes
        self.printopt = PrintOptions(self, self.HistWindow)

        # Add layer to the map
        self.layer = self.Map.AddLayer(type="command",
                                       name='histogram',
                                       command=[['d.histogram']],
                                       l_active=False,
                                       l_hidden=False,
                                       l_opacity=1,
                                       l_render=False)
        if self.mapname:
            self.SetHistLayer(self.mapname, None)
        else:
            self.OnErase(None)
Ejemplo n.º 19
0
    def __init__(self,
                 parent=None,
                 size=wx.Size(700, 400),
                 style=wx.DEFAULT_FRAME_STYLE,
                 rasterList=[],
                 **kwargs):

        wx.Frame.__init__(self,
                          parent,
                          id=wx.ID_ANY,
                          size=size,
                          style=style,
                          **kwargs)

        self.parent = parent  # MapFrame for a plot type
        self.Map = Map(
        )  # instance of render.Map to be associated with display
        self.rasterList = rasterList  # list of rasters to plot
        self.raster = {
        }  # dictionary of raster maps and their plotting parameters
        self.plottype = ''

        self.linestyledict = {
            'solid': wx.SOLID,
            'dot': wx.DOT,
            'long-dash': wx.LONG_DASH,
            'short-dash': wx.SHORT_DASH,
            'dot-dash': wx.DOT_DASH
        }

        self.ptfilldict = {'transparent': wx.TRANSPARENT, 'solid': wx.SOLID}

        #
        # Icon
        #
        self.SetIcon(
            wx.Icon(os.path.join(ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))

        #
        # Add statusbar
        #
        self.statusbar = self.CreateStatusBar(number=2, style=0)
        self.statusbar.SetStatusWidths([-2, -1])

        #
        # Define canvas and settings
        #
        #
        self.client = plot.PlotCanvas(self)

        # define the function for drawing pointLabels
        self.client.SetPointLabelFunc(self.DrawPointLabel)

        # Create mouse event for showing cursor coords in status bar
        self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)

        # Show closest point when enabled
        self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)

        self.plotlist = []  # list of things to plot
        self.plot = None  # plot draw object
        self.ptitle = ""  # title of window
        self.xlabel = ""  # default X-axis label
        self.ylabel = ""  # default Y-axis label

        self.CentreOnScreen()

        self._createColorDict()
Ejemplo n.º 20
0
        def __init__(
            self,
            parent,
            new_map=None,
            base_map=None,
            edit_map=None,
            map_type=None,
        ):
            MapPanel.__init__(self,
                              parent=parent,
                              Map=Map(),
                              giface=DMonGrassInterface(None))

            # set system icon
            parent.SetIcon(
                wx.Icon(os.path.join(ICONDIR, "grass_map.ico"),
                        wx.BITMAP_TYPE_ICO))

            # bindings
            parent.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

            # extend shortcuts and create frame accelerator table
            self.shortcuts_table.append(
                (self.OnFullScreen, wx.ACCEL_NORMAL, wx.WXK_F11))
            self._initShortcuts()

            # 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())

            # add Map Display panel to Map Display frame
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self, proportion=1, flag=wx.EXPAND)
            parent.SetSizer(sizer)
            parent.Layout()
Ejemplo n.º 21
0
    def __init__(
        self, parent=None, giface=None, title=_("Map Swipe"), name="swipe", **kwargs
    ):
        DoubleMapPanel.__init__(
            self,
            parent=parent,
            title=title,
            name=name,
            firstMap=Map(),
            secondMap=Map(),
            **kwargs,
        )
        Debug.msg(1, "SwipeMapPanel.__init__()")
        #
        # Add toolbars
        #
        for name in ("swipeMain", "swipeMap", "swipeMisc"):
            self.AddToolbar(name)
        self._mgr.Update()

        self._giface = giface
        #
        # create widgets
        #
        self.splitter = MapSplitter(parent=self, id=wx.ID_ANY)

        self.sliderH = Slider(self, id=wx.ID_ANY, style=wx.SL_HORIZONTAL)
        self.sliderV = Slider(self, id=wx.ID_ANY, style=wx.SL_VERTICAL)

        self.mapWindowProperties.autoRenderChanged.connect(self.OnAutoRenderChanged)
        self.firstMapWindow = SwipeBufferedWindow(
            parent=self.splitter,
            giface=self._giface,
            properties=self.mapWindowProperties,
            Map=self.firstMap,
        )
        self.secondMapWindow = SwipeBufferedWindow(
            parent=self.splitter,
            giface=self._giface,
            properties=self.mapWindowProperties,
            Map=self.secondMap,
        )
        # bind query signal
        self.firstMapWindow.mapQueried.connect(self.Query)
        self.secondMapWindow.mapQueried.connect(self.Query)

        # bind tracking cursosr to mirror it
        self.firstMapWindow.Bind(wx.EVT_MOTION, lambda evt: self.TrackCursor(evt))
        self.secondMapWindow.Bind(wx.EVT_MOTION, lambda evt: self.TrackCursor(evt))

        self.MapWindow = self.firstMapWindow  # current by default
        self.firstMapWindow.zoomhistory = self.secondMapWindow.zoomhistory
        self.SetBindRegions(True)

        self._mode = "swipe"

        # statusbar items
        statusbarItems = [
            sb.SbCoordinates,
            sb.SbRegionExtent,
            sb.SbCompRegionExtent,
            sb.SbDisplayGeometry,
            sb.SbMapScale,
            sb.SbGoTo,
        ]
        self.statusbar = self.CreateStatusbar(statusbarItems)

        self._addPanes()
        self._bindWindowsActivation()
        self._setUpMapWindow(self.firstMapWindow)
        self._setUpMapWindow(self.secondMapWindow)

        self._mgr.GetPane("sliderV").Hide()
        self._mgr.GetPane("sliderH").Show()
        self.slider = self.sliderH

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_IDLE, self.OnIdle)

        self.SetSize((800, 600))

        self._mgr.Update()

        self.rasters = {"first": None, "second": None}

        self._inputDialog = None
        self._preferencesDialog = None
        self._queryDialog = None

        # default action in map toolbar
        self.GetMapToolbar().SelectDefault()

        self.resize = False

        wx.CallAfter(self.CallAfterInit)
Ejemplo n.º 22
0
    def __init__(
        self,
        parent=None,
        giface=None,
        title=_("Raster Digitizer"),
        toolbars=["digitMap", "rdigit"],
        size=(875, 600),
        name="RDigitWindow",
        **kwargs
    ):
        """!
        @param parent (no parent is expected)
        @param title window title
        @param toolbars dictionary of active toolbars (defalult value represents all toolbars)
        @param size default size
        """
        SingleMapFrame.__init__(
            self, parent=parent, title=title, name=name, Map=Map(), **kwargs
        )
        self._giface = giface

        self.MapWindow = RDigitWindow(
            parent=self, giface=self._giface, id=wx.ID_ANY, frame=self, Map=self.Map
        )
        self.outMapName = None

        self.mapManager = MapManager(self, mapWindow=self.MapWindow, Map=self.GetMap())
        self.SetSize(size)
        # MapWindowRDigit

        # Add toolbars
        toolbarsCopy = toolbars[:]
        if sys.platform == "win32":
            self.AddToolbar(toolbarsCopy.pop(1))
            toolbarsCopy.reverse()
        else:
            self.AddToolbar(toolbarsCopy.pop(0))
        for toolb in toolbarsCopy:
            self.AddToolbar(toolb)

        self.GetMapToolbar().Bind(wx.EVT_CHOICE, self.OnUpdateActive)

        # items for choice
        self.statusbarItems = [
            sb.SbCoordinates,
            sb.SbRegionExtent,
            sb.SbCompRegionExtent,
            sb.SbShowRegion,
            sb.SbAlignExtent,
            sb.SbResolution,
            sb.SbDisplayGeometry,
            sb.SbMapScale,
            sb.SbGoTo,
            sb.SbProjection,
        ]

        # create statusbar and its manager
        statusbar = self.CreateStatusBar(number=4, style=0)
        statusbar.SetStatusWidths([-5, -2, -1, -1])
        self.statusbarManager = sb.SbManager(mapframe=self, statusbar=statusbar)

        # fill statusbar manager
        self.statusbarManager.AddStatusbarItemsByClass(
            self.statusbarItems, mapframe=self, statusbar=statusbar
        )
        self.statusbarManager.AddStatusbarItem(
            sb.SbMask(self, statusbar=statusbar, position=2)
        )
        self.statusbarManager.AddStatusbarItem(
            sb.SbRender(self, statusbar=statusbar, position=3)
        )
        self.statusbarManager.Update()

        self.changes = False

        self._addPanes()
        self._mgr.Update()

        self.mapManager.SetToolbar(self.toolbars["digitMap"])

        # default action
        self.OnPan(event=None)

        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
Ejemplo n.º 23
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()
Ejemplo n.º 24
0
    def __init__(self, parent=None, giface=None,
                 title=_("GRASS GIS Map Swipe"), name="swipe", **kwargs):
        DoubleMapFrame.__init__(self, parent=parent, title=title, name=name,
                                firstMap=Map(), secondMap=Map(), **kwargs)
        Debug.msg(1, "SwipeMapFrame.__init__()")
        #
        # Add toolbars
        #
        self.AddToolbars()
        self._giface = giface
        #
        # create widgets
        #
        self.splitter = MapSplitter(parent=self, id=wx.ID_ANY)

        self.sliderH = wx.Slider(self, id=wx.ID_ANY, style=wx.SL_HORIZONTAL)
        self.sliderV = wx.Slider(self, id=wx.ID_ANY, style=wx.SL_VERTICAL)

        self.mapWindowProperties = MapWindowProperties()
        self.mapWindowProperties.setValuesFromUserSettings()
        self.mapWindowProperties.autoRenderChanged.connect(
            self.OnAutoRenderChanged)
        self.firstMapWindow = SwipeBufferedWindow(
            parent=self.splitter, giface=self._giface,
            properties=self.mapWindowProperties, Map=self.firstMap)
        self.secondMapWindow = SwipeBufferedWindow(
            parent=self.splitter, giface=self._giface,
            properties=self.mapWindowProperties, Map=self.secondMap)
        # bind query signal
        self.firstMapWindow.mapQueried.connect(self.Query)
        self.secondMapWindow.mapQueried.connect(self.Query)

        # bind tracking cursosr to mirror it
        self.firstMapWindow.Bind(
            wx.EVT_MOTION,
            lambda evt: self.TrackCursor(evt))
        self.secondMapWindow.Bind(
            wx.EVT_MOTION,
            lambda evt: self.TrackCursor(evt))

        self.MapWindow = self.firstMapWindow  # current by default
        self.firstMapWindow.zoomhistory = self.secondMapWindow.zoomhistory
        self.SetBindRegions(True)

        self._mode = 'swipe'

        self._addPanes()
        self._bindWindowsActivation()
        self._setUpMapWindow(self.firstMapWindow)
        self._setUpMapWindow(self.secondMapWindow)

        self._mgr.GetPane('sliderV').Hide()
        self._mgr.GetPane('sliderH').Show()
        self.slider = self.sliderH

        self.InitStatusbar()

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_IDLE, self.OnIdle)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

        self.SetSize((800, 600))

        self._mgr.Update()

        self.rasters = {'first': None, 'second': None}

        self._inputDialog = None
        self._preferencesDialog = None
        self._queryDialog = None

        # default action in map toolbar
        self.GetMapToolbar().SelectDefault()

        self.resize = False

        wx.CallAfter(self.CallAfterInit)
Ejemplo n.º 25
0
    def GetLayersFromCmdFile(self):
        """Get list of map layers from cmdfile
        """
        if not self.cmdfile:
            return

        nlayers = 0

        try:
            fd = open(self.cmdfile, 'r')
            lines = fd.readlines()
            fd.close()
            # detect d.out.file, delete the line from the cmd file and export graphics
            if len(lines) > 0:
                if lines[-1].startswith('d.out.file') or lines[-1].startswith(
                        'd.to.rast'):
                    dCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if lines[-1].startswith('d.out.file'):
                        self.saveToFile.emit(cmd=utils.split(dCmd))
                    else:
                        self.dToRast.emit(cmd=utils.split(dCmd))
                    return
                if lines[-1].startswith('d.what'):
                    dWhatCmd = lines[-1].strip()
                    fd = open(self.cmdfile, 'w')
                    fd.writelines(lines[:-1])
                    fd.close()
                    if '=' in utils.split(dWhatCmd)[1]:
                        maps = utils.split(dWhatCmd)[1].split('=')[1].split(
                            ',')
                    else:
                        maps = utils.split(dWhatCmd)[1].split(',')
                    self.query.emit(
                        ltype=utils.split(dWhatCmd)[0].split('.')[-1],
                        maps=maps)
                    return

            existingLayers = self.GetListOfLayers()

            # holds new rendreing order for every layer in existingLayers
            layersOrder = [-1] * len(self.GetListOfLayers())

            # next number in rendering order
            next_layer = 0

            for line in lines:
                cmd = utils.split(line.strip())
                ltype = None

                try:
                    ltype = utils.command2ltype[cmd[0]]
                except KeyError:
                    grass.warning(_("Unsupported command %s.") % cmd[0])
                    continue

                name = utils.GetLayerNameFromCmd(cmd,
                                                 fullyQualified=True,
                                                 layerType=ltype)[0]

                # creating temporary layer object to compare commands
                # neccessary to get the same format
                # supposing that there are no side effects
                tmpMapLayer = MapLayer(ltype=ltype,
                                       name=name,
                                       cmd=cmd,
                                       Map=None,
                                       active=False,
                                       hidden=True,
                                       opacity=0)
                exists = False
                for i, layer in enumerate(existingLayers):
                    if layer.GetCmd(string=True) == tmpMapLayer.GetCmd(
                            string=True):
                        exists = True

                        if layersOrder[i] == -1:
                            layersOrder[i] = next_layer
                            next_layer += 1
                        # layer must be put higher in render order (same cmd was insered more times)
                        # TODO delete rendurant cmds from cmd file?
                        else:
                            for j, l_order in enumerate(layersOrder):
                                if l_order > layersOrder[i]:
                                    layersOrder[j] -= 1
                            layersOrder[i] = next_layer - 1

                        break
                if exists:
                    continue

                newLayer = Map.AddLayer(self,
                                        ltype=ltype,
                                        command=cmd,
                                        active=True,
                                        name=name)

                existingLayers.append(newLayer)
                self.ownedLayers.append(newLayer)

                layersOrder.append(next_layer)
                next_layer += 1

                nlayers += 1

            reorderedLayers = [-1] * next_layer
            for i, layer in enumerate(existingLayers):

                # owned layer was not found in cmd file -> is deleted
                if layersOrder[i] == -1 and layer in self.ownedLayers:
                    self.ownedLayers.remove(layer)
                    self.DeleteLayer(layer)

                # other layer e. g. added by wx.vnet are added to the top
                elif layersOrder[i] == -1 and layer not in self.ownedLayers:
                    reorderedLayers.append(layer)

                # owned layer found in cmd file is added into proper rendering position
                else:
                    reorderedLayers[layersOrder[i]] = layer

            self.SetLayers(reorderedLayers)

        except IOError as e:
            grass.warning(_("Unable to read cmdfile '%(cmd)s'. Details: %(det)s") % \
                              { 'cmd' : self.cmdfile, 'det' : e })
            return

        self._giface.updateMap.emit()

        Debug.msg(1, "Map.GetLayersFromCmdFile(): cmdfile=%s" % self.cmdfile)
        Debug.msg(1, "                            nlayers=%d" % nlayers)