コード例 #1
0
class GRASSStartup(wx.Frame):
    exit_success = 0
    # 2 is file not found from python interpreter
    exit_user_requested = 5
    """GRASS start-up screen"""
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_FRAME_STYLE):

        #
        # GRASS variables
        #
        self.gisbase = os.getenv("GISBASE")
        self.grassrc = self._readGisRC()
        self.gisdbase = self.GetRCValue("GISDBASE")

        #
        # list of locations/mapsets
        #
        self.listOfLocations = []
        self.listOfMapsets = []
        self.listOfMapsetsSelectable = []

        wx.Frame.__init__(self, parent=parent, id=id, style=style)

        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)

        # scroll panel was used here but not properly and is probably not need
        # as long as it is not high too much
        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        # i18N

        #
        # graphical elements
        #
        # image
        try:
            if os.getenv('ISISROOT'):
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner_isis.png")
            else:
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner.png")
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY,
                wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG))
        except:
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY,
                wx.BitmapFromImage(wx.EmptyImage(530, 150)))

        # labels
        # crashes when LOCATION doesn't exist
        # get version & revision
        versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
        versionLine = versionFile.readline().rstrip('\n')
        versionFile.close()
        try:
            grassVersion, grassRevision = versionLine.split(' ', 1)
            if grassVersion.endswith('dev'):
                grassRevisionStr = ' (%s)' % grassRevision
            else:
                grassRevisionStr = ''
        except ValueError:
            grassVersion = versionLine
            grassRevisionStr = ''

        self.gisdbase_box = StaticBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=" %s " % _("1. Select GRASS GIS database directory"))
        self.location_box = StaticBox(parent=self.panel,
                                      id=wx.ID_ANY,
                                      label=" %s " %
                                      _("2. Select GRASS Location"))
        self.mapset_box = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _("3. Select GRASS Mapset"))

        self.lmessage = StaticText(parent=self.panel)
        # It is not clear if all wx versions supports color, so try-except.
        # The color itself may not be correct for all platforms/system settings
        # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
        # there is no 'warning' color.
        try:
            self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
        except AttributeError:
            pass

        self.gisdbase_panel = wx.Panel(parent=self.panel)
        self.location_panel = wx.Panel(parent=self.panel)
        self.mapset_panel = wx.Panel(parent=self.panel)

        self.ldbase = StaticText(
            parent=self.gisdbase_panel,
            id=wx.ID_ANY,
            label=_("GRASS GIS database directory contains Locations."))

        self.llocation = StaticWrapText(
            parent=self.location_panel,
            id=wx.ID_ANY,
            label=_("All data in one Location is in the same "
                    " coordinate reference system (projection)."
                    " One Location can be one project."
                    " Location contains Mapsets."),
            style=wx.ALIGN_LEFT)

        self.lmapset = StaticWrapText(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            label=_("Mapset contains GIS data related"
                    " to one project, task within one project,"
                    " subregion or user."),
            style=wx.ALIGN_LEFT)

        try:
            for label in [self.ldbase, self.llocation, self.lmapset]:
                label.SetForegroundColour(
                    wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        except AttributeError:
            # for explanation of try-except see above
            pass

        # buttons
        self.bstart = Button(parent=self.panel,
                             id=wx.ID_ANY,
                             label=_("Start &GRASS session"))
        self.bstart.SetDefault()
        self.bexit = Button(parent=self.panel, id=wx.ID_EXIT)
        self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
        self.bhelp = Button(parent=self.panel, id=wx.ID_HELP)
        self.bbrowse = Button(parent=self.gisdbase_panel,
                              id=wx.ID_ANY,
                              label=_("&Browse"))
        self.bmapset = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC New mapset
            label=_("&New"))
        self.bmapset.SetToolTip(_("Create a new Mapset in selected Location"))
        self.bwizard = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC New location
            label=_("N&ew"))
        self.bwizard.SetToolTip(
            _("Create a new location using location wizard."
              " After location is created successfully,"
              " GRASS session is started."))
        self.rename_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Rename location
            label=_("Ren&ame"))
        self.rename_location_button.SetToolTip(_("Rename selected location"))
        self.delete_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Delete location
            label=_("De&lete"))
        self.delete_location_button.SetToolTip(_("Delete selected location"))
        self.rename_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Rename mapset
            label=_("&Rename"))
        self.rename_mapset_button.SetToolTip(_("Rename selected mapset"))
        self.delete_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Delete mapset
            label=_("&Delete"))
        self.delete_mapset_button.SetToolTip(_("Delete selected mapset"))

        # textinputs
        self.tgisdbase = TextCtrl(parent=self.gisdbase_panel,
                                  id=wx.ID_ANY,
                                  value="",
                                  size=(300, -1),
                                  style=wx.TE_PROCESS_ENTER)

        # Locations
        self.lblocations = GListBox(parent=self.location_panel,
                                    id=wx.ID_ANY,
                                    size=(180, 200),
                                    choices=self.listOfLocations)
        self.lblocations.SetColumnWidth(0, 180)

        # TODO: sort; but keep PERMANENT on top of list
        # Mapsets
        self.lbmapsets = GListBox(parent=self.mapset_panel,
                                  id=wx.ID_ANY,
                                  size=(180, 200),
                                  choices=self.listOfMapsets)
        self.lbmapsets.SetColumnWidth(0, 180)

        # layout & properties, first do layout so everything is created
        self._do_layout()
        self._set_properties(grassVersion, grassRevisionStr)

        # events
        self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
        self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
        self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
        self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
        self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)

        self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
        self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
        self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
        self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)

        self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
        self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

    def _set_properties(self, version, revision):
        """Set frame properties"""
        self.SetTitle(_("GRASS GIS %s startup%s") % (version, revision))
        self.SetIcon(
            wx.Icon(os.path.join(globalvar.ICONDIR, "grass.ico"),
                    wx.BITMAP_TYPE_ICO))

        self.bstart.SetForegroundColour(wx.Colour(35, 142, 35))
        self.bstart.SetToolTip(_("Enter GRASS session"))
        self.bstart.Enable(False)
        self.bmapset.Enable(False)
        # this all was originally a choice, perhaps just mapset needed
        self.rename_location_button.Enable(False)
        self.delete_location_button.Enable(False)
        self.rename_mapset_button.Enable(False)
        self.delete_mapset_button.Enable(False)

        # set database
        if not self.gisdbase:
            # sets an initial path for gisdbase if nothing in GISRC
            if os.path.isdir(os.getenv("HOME")):
                self.gisdbase = os.getenv("HOME")
            else:
                self.gisdbase = os.getcwd()
        try:
            self.tgisdbase.SetValue(self.gisdbase)
        except UnicodeDecodeError:
            wx.MessageBox(parent=self,
                          caption=_("Error"),
                          message=_("Unable to set GRASS database. "
                                    "Check your locale settings."),
                          style=wx.OK | wx.ICON_ERROR | wx.CENTRE)

        self.OnSetDatabase(None)
        location = self.GetRCValue("LOCATION_NAME")
        if location == "<UNKNOWN>":
            return
        if not os.path.isdir(os.path.join(self.gisdbase, location)):
            location = None

        # list of locations
        self.UpdateLocations(self.gisdbase)
        try:
            self.lblocations.SetSelection(self.listOfLocations.index(location),
                                          force=True)
            self.lblocations.EnsureVisible(
                self.listOfLocations.index(location))
        except ValueError:
            sys.stderr.write(
                _("ERROR: Location <%s> not found\n") %
                self.GetRCValue("LOCATION_NAME"))
            if len(self.listOfLocations) > 0:
                self.lblocations.SetSelection(0, force=True)
                self.lblocations.EnsureVisible(0)
                location = self.listOfLocations[0]
            else:
                return

        # list of mapsets
        self.UpdateMapsets(os.path.join(self.gisdbase, location))
        mapset = self.GetRCValue("MAPSET")
        if mapset:
            try:
                self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
                                            force=True)
                self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
            except ValueError:
                sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
                self.lbmapsets.SetSelection(0, force=True)
                self.lbmapsets.EnsureVisible(0)

    def _do_layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer = sizer  # for the layout call after changing message
        dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)

        location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)

        gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
        gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)

        btns_sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.gisdbase_panel.SetSizer(gisdbase_panel_sizer)

        # gis data directory

        gisdbase_boxsizer.Add(self.gisdbase_panel,
                              proportion=1,
                              flag=wx.EXPAND | wx.ALL,
                              border=1)

        gisdbase_panel_sizer.Add(dbase_sizer,
                                 proportion=1,
                                 flag=wx.EXPAND | wx.ALL,
                                 border=1)
        gisdbase_panel_sizer.Add(self.ldbase,
                                 proportion=0,
                                 flag=wx.EXPAND | wx.ALL,
                                 border=1)

        dbase_sizer.Add(self.tgisdbase,
                        proportion=1,
                        flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                        border=1)
        dbase_sizer.Add(self.bbrowse,
                        proportion=0,
                        flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                        border=1)

        gisdbase_panel_sizer.Fit(self.gisdbase_panel)

        # location and mapset lists

        def layout_list_box(box, panel, list_box, buttons, description):
            panel_sizer = wx.BoxSizer(wx.VERTICAL)
            main_sizer = wx.BoxSizer(wx.HORIZONTAL)
            box_sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
            buttons_sizer = wx.BoxSizer(wx.VERTICAL)

            panel.SetSizer(panel_sizer)
            panel_sizer.Fit(panel)

            main_sizer.Add(list_box,
                           proportion=1,
                           flag=wx.EXPAND | wx.ALL,
                           border=1)
            main_sizer.Add(buttons_sizer,
                           proportion=0,
                           flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
                           border=1)
            for button in buttons:
                buttons_sizer.Add(button,
                                  proportion=0,
                                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT
                                  | wx.BOTTOM,
                                  border=3)
            box_sizer.Add(panel,
                          proportion=1,
                          flag=wx.EXPAND | wx.ALL,
                          border=1)
            panel_sizer.Add(main_sizer,
                            proportion=1,
                            flag=wx.EXPAND | wx.ALL,
                            border=1)
            panel_sizer.Add(description,
                            proportion=0,
                            flag=wx.EXPAND | wx.ALL,
                            border=1)
            return box_sizer

        location_boxsizer = layout_list_box(box=self.location_box,
                                            panel=self.location_panel,
                                            list_box=self.lblocations,
                                            buttons=[
                                                self.bwizard,
                                                self.rename_location_button,
                                                self.delete_location_button
                                            ],
                                            description=self.llocation)
        mapset_boxsizer = layout_list_box(box=self.mapset_box,
                                          panel=self.mapset_panel,
                                          list_box=self.lbmapsets,
                                          buttons=[
                                              self.bmapset,
                                              self.rename_mapset_button,
                                              self.delete_mapset_button
                                          ],
                                          description=self.lmapset)

        # location and mapset sizer
        location_mapset_sizer.Add(location_boxsizer,
                                  proportion=1,
                                  flag=wx.LEFT | wx.RIGHT | wx.EXPAND,
                                  border=3)
        location_mapset_sizer.Add(mapset_boxsizer,
                                  proportion=1,
                                  flag=wx.RIGHT | wx.EXPAND,
                                  border=3)

        # buttons
        btns_sizer.Add(self.bstart,
                       proportion=0,
                       flag=wx.ALIGN_CENTER_HORIZONTAL
                       | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                       border=5)
        btns_sizer.Add(self.bexit,
                       proportion=0,
                       flag=wx.ALIGN_CENTER_HORIZONTAL
                       | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                       border=5)
        btns_sizer.Add(self.bhelp,
                       proportion=0,
                       flag=wx.ALIGN_CENTER_HORIZONTAL
                       | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                       border=5)

        # main sizer
        sizer.Add(self.hbitmap,
                  proportion=0,
                  flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL
                  | wx.ALL,
                  border=3)  # image
        sizer.Add(gisdbase_boxsizer,
                  proportion=0,
                  flag=wx.ALIGN_CENTER_HORIZONTAL | wx.RIGHT | wx.LEFT | wx.TOP
                  | wx.EXPAND,
                  border=3)  # GISDBASE setting

        # warning/error message
        sizer.Add(self.lmessage,
                  proportion=0,
                  flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT | wx.ALL
                  | wx.EXPAND,
                  border=5)
        sizer.Add(location_mapset_sizer,
                  proportion=1,
                  flag=wx.RIGHT | wx.LEFT | wx.EXPAND,
                  border=1)
        sizer.Add(btns_sizer,
                  proportion=0,
                  flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_CENTER_HORIZONTAL
                  | wx.RIGHT | wx.LEFT,
                  border=3)

        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(sizer)
        sizer.Fit(self.panel)
        sizer.SetSizeHints(self)
        self.Layout()

    def _readGisRC(self):
        """Read variables from $HOME/.grass7/rc file
        """
        grassrc = {}

        gisrc = os.getenv("GISRC")

        if gisrc and os.path.isfile(gisrc):
            try:
                rc = open(gisrc, "r")
                for line in rc.readlines():
                    try:
                        key, val = line.split(":", 1)
                    except ValueError as e:
                        sys.stderr.write(
                            _('Invalid line in GISRC file (%s):%s\n' %
                              (e, line)))
                    grassrc[key.strip()] = DecodeString(val.strip())
            finally:
                rc.close()

        return grassrc

    def _showWarning(self, text):
        """Displays a warning, hint or info message to the user.

        This function can be used for all kinds of messages except for
        error messages.

        .. note::
            There is no cleaning procedure. You should call _hideMessage when
            you know that there is everything correct now.
        """
        self.lmessage.SetLabel(text)
        self.lmessage.Wrap(self.GetClientSize()[0])
        self.sizer.Layout()

    def _showError(self, text):
        """Displays a error message to the user.

        This function should be used only when something serious and unexpected
        happens, otherwise _showWarning should be used.

        .. note::
            There is no cleaning procedure. You should call _hideMessage when
            you know that there is everything correct now.
        """
        self.lmessage.SetLabel(_("Error: {text}").format(text=text))
        self.lmessage.Wrap(self.GetClientSize()[0])
        self.sizer.Layout()

    def _hideMessage(self):
        """Clears/hides the error message."""
        # we do no hide widget
        # because we do not want the dialog to change the size
        self.lmessage.SetLabel("")
        self.sizer.Layout()

    def GetRCValue(self, value):
        """Return GRASS variable (read from GISRC)
        """
        if value in self.grassrc:
            return self.grassrc[value]
        else:
            return None

    def OnWizard(self, event):
        """Location wizard started"""
        from location_wizard.wizard import LocationWizard
        gWizard = LocationWizard(parent=self,
                                 grassdatabase=self.tgisdbase.GetValue())
        if gWizard.location is not None:
            self.tgisdbase.SetValue(gWizard.grassdatabase)
            self.OnSetDatabase(None)
            self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
            self.lblocations.SetSelection(
                self.listOfLocations.index(gWizard.location))
            self.lbmapsets.SetSelection(0)
            self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
            if gWizard.georeffile:
                message = _(
                    "Do you want to import <%(name)s> to the newly created location?"
                ) % {
                    'name': gWizard.georeffile
                }
                dlg = wx.MessageDialog(parent=self,
                                       message=message,
                                       caption=_("Import data?"),
                                       style=wx.YES_NO | wx.YES_DEFAULT
                                       | wx.ICON_QUESTION)
                dlg.CenterOnParent()
                if dlg.ShowModal() == wx.ID_YES:
                    self.ImportFile(gWizard.georeffile)
                dlg.Destroy()
            if gWizard.default_region:
                defineRegion = RegionDef(self, location=gWizard.location)
                defineRegion.CenterOnParent()
                defineRegion.ShowModal()
                defineRegion.Destroy()

            if gWizard.user_mapset:
                dlg = TextEntryDialog(
                    parent=self,
                    message=_("New mapset:"),
                    caption=_("Create new mapset"),
                    defaultValue=self._getDefaultMapsetName(),
                    validator=GenericValidator(grass.legal_name,
                                               self._nameValidationFailed),
                    style=wx.OK | wx.CANCEL | wx.HELP)
                help = dlg.FindWindowById(wx.ID_HELP)
                help.Bind(wx.EVT_BUTTON, self.OnHelp)
                if dlg.ShowModal() == wx.ID_OK:
                    mapsetName = dlg.GetValue()
                    self.CreateNewMapset(mapsetName)

    def ImportFile(self, filePath):
        """Tries to import file as vector or raster.

        If successfull sets default region from imported map.
        """
        RunCommand('db.connect', flags='c')
        mapName = os.path.splitext(os.path.basename(filePath))[0]
        vectors = RunCommand('v.in.ogr', input=filePath, flags='l', read=True)

        wx.BeginBusyCursor()
        wx.Yield()
        if mapName in vectors:
            # vector detected
            returncode, error = RunCommand('v.in.ogr',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        else:
            returncode, error = RunCommand('r.in.gdal',
                                           input=filePath,
                                           output=mapName,
                                           flags='e',
                                           getErrorMsg=True)
        wx.EndBusyCursor()

        if returncode != 0:
            GError(parent=self,
                   message=_("Import of <%(name)s> failed.\n"
                             "Reason: %(msg)s") % ({
                                 'name': filePath,
                                 'msg': error
                             }))
        else:
            GMessage(message=_(
                "Data file <%(name)s> imported successfully. "
                "The location's default region was set from this imported map."
            ) % {'name': filePath},
                     parent=self)

    # the event can be refactored out by using lambda in bind
    def RenameMapset(self, event):
        """Rename selected mapset
        """
        location = self.listOfLocations[self.lblocations.GetSelection()]
        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
        if mapset == 'PERMANENT':
            GMessage(
                parent=self,
                message=_(
                    'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
                    'This mapset cannot be renamed.'))
            return

        dlg = TextEntryDialog(
            parent=self,
            message=_('Current name: %s\n\nEnter new name:') % mapset,
            caption=_('Rename selected mapset'),
            validator=GenericValidator(grass.legal_name,
                                       self._nameValidationFailed))

        if dlg.ShowModal() == wx.ID_OK:
            newmapset = dlg.GetValue()
            if newmapset == mapset:
                dlg.Destroy()
                return

            if newmapset in self.listOfMapsets:
                wx.MessageBox(
                    parent=self,
                    caption=_('Message'),
                    message=_('Unable to rename mapset.\n\n'
                              'Mapset <%s> already exists in location.') %
                    newmapset,
                    style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
            else:
                try:
                    os.rename(os.path.join(self.gisdbase, location, mapset),
                              os.path.join(self.gisdbase, location, newmapset))
                    self.OnSelectLocation(None)
                    self.lbmapsets.SetSelection(
                        self.listOfMapsets.index(newmapset))
                except Exception as e:
                    wx.MessageBox(parent=self,
                                  caption=_('Error'),
                                  message=_('Unable to rename mapset.\n\n%s') %
                                  e,
                                  style=wx.OK | wx.ICON_ERROR | wx.CENTRE)

        dlg.Destroy()

    def RenameLocation(self, event):
        """Rename selected location
        """
        location = self.listOfLocations[self.lblocations.GetSelection()]

        dlg = TextEntryDialog(
            parent=self,
            message=_('Current name: %s\n\nEnter new name:') % location,
            caption=_('Rename selected location'),
            validator=GenericValidator(grass.legal_name,
                                       self._nameValidationFailed))

        if dlg.ShowModal() == wx.ID_OK:
            newlocation = dlg.GetValue()
            if newlocation == location:
                dlg.Destroy()
                return

            if newlocation in self.listOfLocations:
                wx.MessageBox(
                    parent=self,
                    caption=_('Message'),
                    message=_(
                        'Unable to rename location.\n\n'
                        'Location <%s> already exists in GRASS database.') %
                    newlocation,
                    style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
            else:
                try:
                    os.rename(os.path.join(self.gisdbase, location),
                              os.path.join(self.gisdbase, newlocation))
                    self.UpdateLocations(self.gisdbase)
                    self.lblocations.SetSelection(
                        self.listOfLocations.index(newlocation))
                    self.UpdateMapsets(newlocation)
                except Exception as e:
                    wx.MessageBox(
                        parent=self,
                        caption=_('Error'),
                        message=_('Unable to rename location.\n\n%s') % e,
                        style=wx.OK | wx.ICON_ERROR | wx.CENTRE)

        dlg.Destroy()

    def DeleteMapset(self, event):
        """Delete selected mapset
        """
        location = self.listOfLocations[self.lblocations.GetSelection()]
        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
        if mapset == 'PERMANENT':
            GMessage(
                parent=self,
                message=_(
                    'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
                    'This mapset cannot be deleted.'))
            return

        dlg = wx.MessageDialog(
            parent=self,
            message=_(
                "Do you want to continue with deleting mapset <%(mapset)s> "
                "from location <%(location)s>?\n\n"
                "ALL MAPS included in this mapset will be "
                "PERMANENTLY DELETED!") % {
                    'mapset': mapset,
                    'location': location
                },
            caption=_("Delete selected mapset"),
            style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        if dlg.ShowModal() == wx.ID_YES:
            try:
                shutil.rmtree(os.path.join(self.gisdbase, location, mapset))
                self.OnSelectLocation(None)
                self.lbmapsets.SetSelection(0)
            except:
                wx.MessageBox(message=_('Unable to delete mapset'))

        dlg.Destroy()

    def DeleteLocation(self, event):
        """
        Delete selected location
        """

        location = self.listOfLocations[self.lblocations.GetSelection()]

        dlg = wx.MessageDialog(
            parent=self,
            message=_("Do you want to continue with deleting "
                      "location <%s>?\n\n"
                      "ALL MAPS included in this location will be "
                      "PERMANENTLY DELETED!") % (location),
            caption=_("Delete selected location"),
            style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)

        if dlg.ShowModal() == wx.ID_YES:
            try:
                shutil.rmtree(os.path.join(self.gisdbase, location))
                self.UpdateLocations(self.gisdbase)
                self.lblocations.SetSelection(0)
                self.OnSelectLocation(None)
                self.lbmapsets.SetSelection(0)
            except:
                wx.MessageBox(message=_('Unable to delete location'))

        dlg.Destroy()

    def UpdateLocations(self, dbase):
        """Update list of locations"""
        try:
            self.listOfLocations = GetListOfLocations(dbase)
        except (UnicodeEncodeError, UnicodeDecodeError) as e:
            GError(parent=self,
                   message=_(
                       "Unicode error detected. "
                       "Check your locale settings. Details: {0}").format(e),
                   showTraceback=False)

        self.lblocations.Clear()
        self.lblocations.InsertItems(self.listOfLocations, 0)

        if len(self.listOfLocations) > 0:
            self._hideMessage()
            self.lblocations.SetSelection(0)
        else:
            self.lblocations.SetSelection(wx.NOT_FOUND)
            self._showWarning(
                _("No GRASS Location found in '%s'."
                  " Create a new Location or choose different"
                  " GRASS database directory.") % self.gisdbase)

        return self.listOfLocations

    def UpdateMapsets(self, location):
        """Update list of mapsets"""
        self.FormerMapsetSelection = wx.NOT_FOUND  # for non-selectable item

        self.listOfMapsetsSelectable = list()
        self.listOfMapsets = GetListOfMapsets(self.gisdbase, location)

        self.lbmapsets.Clear()

        # disable mapset with denied permission
        locationName = os.path.basename(location)

        ret = RunCommand('g.mapset',
                         read=True,
                         flags='l',
                         location=locationName,
                         gisdbase=self.gisdbase)

        if ret:
            for line in ret.splitlines():
                self.listOfMapsetsSelectable += line.split(' ')
        else:
            RunCommand("g.gisenv", set="GISDBASE=%s" % self.gisdbase)
            RunCommand("g.gisenv", set="LOCATION_NAME=%s" % locationName)
            RunCommand("g.gisenv", set="MAPSET=PERMANENT")
            # first run only
            self.listOfMapsetsSelectable = copy.copy(self.listOfMapsets)

        disabled = []
        idx = 0
        for mapset in self.listOfMapsets:
            if mapset not in self.listOfMapsetsSelectable or \
                    os.path.isfile(os.path.join(self.gisdbase,
                                                locationName,
                                                mapset, ".gislock")):
                disabled.append(idx)
            idx += 1

        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)

        return self.listOfMapsets

    def OnSelectLocation(self, event):
        """Location selected"""
        if event:
            self.lblocations.SetSelection(event.GetIndex())

        if self.lblocations.GetSelection() != wx.NOT_FOUND:
            self.UpdateMapsets(
                os.path.join(
                    self.gisdbase,
                    self.listOfLocations[self.lblocations.GetSelection()]))
        else:
            self.listOfMapsets = []

        disabled = []
        idx = 0
        try:
            locationName = self.listOfLocations[
                self.lblocations.GetSelection()]
        except IndexError:
            locationName = ''

        for mapset in self.listOfMapsets:
            if mapset not in self.listOfMapsetsSelectable or \
                    os.path.isfile(os.path.join(self.gisdbase,
                                                locationName,
                                                mapset, ".gislock")):
                disabled.append(idx)
            idx += 1

        self.lbmapsets.Clear()
        self.lbmapsets.InsertItems(self.listOfMapsets, 0, disabled=disabled)

        if len(self.listOfMapsets) > 0:
            self.lbmapsets.SetSelection(0)
            if locationName:
                # enable start button when location and mapset is selected
                self.bstart.Enable()
                self.bstart.SetFocus()
                self.bmapset.Enable()
                # replacing disabled choice, perhaps just mapset needed
                self.rename_location_button.Enable()
                self.delete_location_button.Enable()
                self.rename_mapset_button.Enable()
                self.delete_mapset_button.Enable()
        else:
            self.lbmapsets.SetSelection(wx.NOT_FOUND)
            self.bstart.Enable(False)
            self.bmapset.Enable(False)
            # this all was originally a choice, perhaps just mapset needed
            self.rename_location_button.Enable(False)
            self.delete_location_button.Enable(False)
            self.rename_mapset_button.Enable(False)
            self.delete_mapset_button.Enable(False)

    def OnSelectMapset(self, event):
        """Mapset selected"""
        self.lbmapsets.SetSelection(event.GetIndex())

        if event.GetText() not in self.listOfMapsetsSelectable:
            self.lbmapsets.SetSelection(self.FormerMapsetSelection)
        else:
            self.FormerMapsetSelection = event.GetIndex()
            event.Skip()

    def OnSetDatabase(self, event):
        """Database set"""
        gisdbase = self.tgisdbase.GetValue()
        self._hideMessage()
        if not os.path.exists(gisdbase):
            self._showError(_("Path '%s' doesn't exist.") % gisdbase)
            return

        self.gisdbase = self.tgisdbase.GetValue()
        self.UpdateLocations(self.gisdbase)

        self.OnSelectLocation(None)

    def OnBrowse(self, event):
        """'Browse' button clicked"""
        if not event:
            defaultPath = os.getenv('HOME')
        else:
            defaultPath = ""

        dlg = wx.DirDialog(parent=self,
                           message=_("Choose GIS Data Directory"),
                           defaultPath=defaultPath,
                           style=wx.DD_DEFAULT_STYLE)

        if dlg.ShowModal() == wx.ID_OK:
            self.gisdbase = dlg.GetPath()
            self.tgisdbase.SetValue(self.gisdbase)
            self.OnSetDatabase(event)

        dlg.Destroy()

    def OnCreateMapset(self, event):
        """Create new mapset"""
        dlg = TextEntryDialog(parent=self,
                              message=_('Enter name for new mapset:'),
                              caption=_('Create new mapset'),
                              defaultValue=self._getDefaultMapsetName(),
                              validator=GenericValidator(
                                  grass.legal_name,
                                  self._nameValidationFailed))
        if dlg.ShowModal() == wx.ID_OK:
            mapset = dlg.GetValue()
            return self.CreateNewMapset(mapset=mapset)
        else:
            return False

    def CreateNewMapset(self, mapset):
        if mapset in self.listOfMapsets:
            GMessage(parent=self,
                     message=_("Mapset <%s> already exists.") % mapset)
            return False

        if mapset.lower() == 'ogr':
            dlg1 = wx.MessageDialog(
                parent=self,
                message=_(
                    "Mapset <%s> is reserved for direct "
                    "read access to OGR layers. Please consider to use "
                    "another name for your mapset.\n\n"
                    "Are you really sure that you want to create this mapset?")
                % mapset,
                caption=_("Reserved mapset name"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
            ret = dlg1.ShowModal()
            dlg1.Destroy()
            if ret == wx.ID_NO:
                dlg1.Destroy()
                return False

        try:
            self.gisdbase = self.tgisdbase.GetValue()
            location = self.listOfLocations[self.lblocations.GetSelection()]
            os.mkdir(os.path.join(self.gisdbase, location, mapset))
            # copy WIND file and its permissions from PERMANENT and set
            # permissions to u+rw,go+r
            shutil.copy(
                os.path.join(self.gisdbase, location, 'PERMANENT', 'WIND'),
                os.path.join(self.gisdbase, location, mapset))
            # os.chmod(os.path.join(database,location,mapset,'WIND'), 0644)
            self.OnSelectLocation(None)
            self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset))
            self.bstart.SetFocus()

            return True
        except Exception as e:
            GError(parent=self,
                   message=_("Unable to create new mapset: %s") % e,
                   showTraceback=False)
            return False

    def OnStart(self, event):
        """'Start GRASS' button clicked"""
        dbase = self.tgisdbase.GetValue()
        location = self.listOfLocations[self.lblocations.GetSelection()]
        mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]

        lockfile = os.path.join(dbase, location, mapset, '.gislock')
        if os.path.isfile(lockfile):
            dlg = wx.MessageDialog(
                parent=self,
                message=_(
                    "GRASS is already running in selected mapset <%(mapset)s>\n"
                    "(file %(lock)s found).\n\n"
                    "Concurrent use not allowed.\n\n"
                    "Do you want to try to remove .gislock (note that you "
                    "need permission for this operation) and continue?") % {
                        'mapset': mapset,
                        'lock': lockfile
                    },
                caption=_("Lock file found"),
                style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)

            ret = dlg.ShowModal()
            dlg.Destroy()
            if ret == wx.ID_YES:
                dlg1 = wx.MessageDialog(
                    parent=self,
                    message=
                    _("ARE YOU REALLY SURE?\n\n"
                      "If you really are running another GRASS session doing this "
                      "could corrupt your data. Have another look in the processor "
                      "manager just to be sure..."),
                    caption=_("Lock file found"),
                    style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION
                    | wx.CENTRE)

                ret = dlg1.ShowModal()
                dlg1.Destroy()

                if ret == wx.ID_YES:
                    try:
                        os.remove(lockfile)
                    except IOError as e:
                        GError(
                            _("Unable to remove '%(lock)s'.\n\n"
                              "Details: %(reason)s") % {
                                  'lock': lockfile,
                                  'reason': e
                              })
                else:
                    return
            else:
                return
        self.SetLocation(dbase, location, mapset)
        self.ExitSuccessfully()

    def SetLocation(self, dbase, location, mapset):
        RunCommand("g.gisenv", set="GISDBASE=%s" % dbase)
        RunCommand("g.gisenv", set="LOCATION_NAME=%s" % location)
        RunCommand("g.gisenv", set="MAPSET=%s" % mapset)

    def _getDefaultMapsetName(self):
        """Returns default name for mapset."""
        try:
            defaultName = getpass.getuser()
            # raise error if not ascii (not valid mapset name)
            defaultName.encode('ascii')
        except:  # whatever might go wrong
            defaultName = 'user'

        return defaultName

    def ExitSuccessfully(self):
        self.Destroy()
        sys.exit(self.exit_success)

    def OnExit(self, event):
        """'Exit' button clicked"""
        self.Destroy()
        sys.exit(self.exit_user_requested)

    def OnHelp(self, event):
        """'Help' button clicked"""

        # help text in lib/init/helptext.html
        RunCommand('g.manual', entry='helptext')

    def OnCloseWindow(self, event):
        """Close window event"""
        event.Skip()
        sys.exit(self.exit_user_requested)

    def _nameValidationFailed(self, ctrl):
        message = _(
            "Name <%(name)s> is not a valid name for location or mapset. "
            "Please use only ASCII characters excluding %(chars)s "
            "and space.") % {
                'name': ctrl.GetValue(),
                'chars': '/"\'@,=*~'
            }
        GError(parent=self, message=message, caption=_("Invalid name"))
コード例 #2
0
    def __init__(self,
                 parent=None,
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_FRAME_STYLE):

        #
        # GRASS variables
        #
        self.gisbase = os.getenv("GISBASE")
        self.grassrc = sgui.read_gisrc()
        self.gisdbase = self.GetRCValue("GISDBASE")

        #
        # list of locations/mapsets
        #
        self.listOfLocations = []
        self.listOfMapsets = []
        self.listOfMapsetsSelectable = []

        wx.Frame.__init__(self, parent=parent, id=id, style=style)

        self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)

        # scroll panel was used here but not properly and is probably not need
        # as long as it is not high too much
        self.panel = wx.Panel(parent=self, id=wx.ID_ANY)

        # i18N

        #
        # graphical elements
        #
        # image
        try:
            if os.getenv('ISISROOT'):
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner_isis.png")
            else:
                name = os.path.join(globalvar.GUIDIR, "images",
                                    "startup_banner.png")
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY,
                wx.Bitmap(name=name, type=wx.BITMAP_TYPE_PNG))
        except:
            self.hbitmap = wx.StaticBitmap(
                self.panel, wx.ID_ANY, BitmapFromImage(wx.EmptyImage(530,
                                                                     150)))

        # labels
        # crashes when LOCATION doesn't exist
        # get version & revision
        grassVersion, grassRevisionStr = sgui.GetVersion()

        self.gisdbase_box = StaticBox(
            parent=self.panel,
            id=wx.ID_ANY,
            label=" %s " % _("1. Select GRASS GIS database directory"))
        self.location_box = StaticBox(parent=self.panel,
                                      id=wx.ID_ANY,
                                      label=" %s " %
                                      _("2. Select GRASS Location"))
        self.mapset_box = StaticBox(parent=self.panel,
                                    id=wx.ID_ANY,
                                    label=" %s " % _("3. Select GRASS Mapset"))

        self.lmessage = StaticWrapText(parent=self.panel)
        # It is not clear if all wx versions supports color, so try-except.
        # The color itself may not be correct for all platforms/system settings
        # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
        # there is no 'warning' color.
        try:
            self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
        except AttributeError:
            pass

        self.gisdbase_panel = wx.Panel(parent=self.panel)
        self.location_panel = wx.Panel(parent=self.panel)
        self.mapset_panel = wx.Panel(parent=self.panel)

        self.ldbase = StaticText(
            parent=self.gisdbase_panel,
            id=wx.ID_ANY,
            label=_("GRASS GIS database directory contains Locations."))

        self.llocation = StaticWrapText(
            parent=self.location_panel,
            id=wx.ID_ANY,
            label=_("All data in one Location is in the same "
                    " coordinate reference system (projection)."
                    " One Location can be one project."
                    " Location contains Mapsets."),
            style=wx.ALIGN_LEFT)

        self.lmapset = StaticWrapText(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            label=_("Mapset contains GIS data related"
                    " to one project, task within one project,"
                    " subregion or user."),
            style=wx.ALIGN_LEFT)

        try:
            for label in [self.ldbase, self.llocation, self.lmapset]:
                label.SetForegroundColour(
                    wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        except AttributeError:
            # for explanation of try-except see above
            pass

        # buttons
        self.bstart = Button(parent=self.panel,
                             id=wx.ID_ANY,
                             label=_("Start &GRASS session"))
        self.bstart.SetDefault()
        self.bexit = Button(parent=self.panel, id=wx.ID_EXIT)
        self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
        self.bhelp = Button(parent=self.panel, id=wx.ID_HELP)
        self.bbrowse = Button(parent=self.gisdbase_panel,
                              id=wx.ID_ANY,
                              label=_("&Browse"))
        self.bmapset = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC New mapset
            label=_("&New"))
        self.bmapset.SetToolTip(_("Create a new Mapset in selected Location"))
        self.bwizard = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC New location
            label=_("N&ew"))
        self.bwizard.SetToolTip(
            _("Create a new location using location wizard."
              " After location is created successfully,"
              " GRASS session is started."))
        self.rename_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Rename location
            label=_("Ren&ame"))
        self.rename_location_button.SetToolTip(_("Rename selected location"))
        self.delete_location_button = Button(
            parent=self.location_panel,
            id=wx.ID_ANY,
            # GTC Delete location
            label=_("De&lete"))
        self.delete_location_button.SetToolTip(_("Delete selected location"))
        self.download_location_button = Button(parent=self.location_panel,
                                               id=wx.ID_ANY,
                                               label=_("Do&wnload"))
        self.download_location_button.SetToolTip(_("Download sample location"))

        self.rename_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Rename mapset
            label=_("&Rename"))
        self.rename_mapset_button.SetToolTip(_("Rename selected mapset"))
        self.delete_mapset_button = Button(
            parent=self.mapset_panel,
            id=wx.ID_ANY,
            # GTC Delete mapset
            label=_("&Delete"))
        self.delete_mapset_button.SetToolTip(_("Delete selected mapset"))

        # textinputs
        self.tgisdbase = TextCtrl(parent=self.gisdbase_panel,
                                  id=wx.ID_ANY,
                                  value="",
                                  size=(300, -1),
                                  style=wx.TE_PROCESS_ENTER)

        # Locations
        self.lblocations = GListBox(parent=self.location_panel,
                                    id=wx.ID_ANY,
                                    size=(180, 200),
                                    choices=self.listOfLocations)
        self.lblocations.SetColumnWidth(0, 180)

        # TODO: sort; but keep PERMANENT on top of list
        # Mapsets
        self.lbmapsets = GListBox(parent=self.mapset_panel,
                                  id=wx.ID_ANY,
                                  size=(180, 200),
                                  choices=self.listOfMapsets)
        self.lbmapsets.SetColumnWidth(0, 180)

        # layout & properties, first do layout so everything is created
        self._do_layout()
        self._set_properties(grassVersion, grassRevisionStr)

        # events
        self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
        self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
        self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
        self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
        self.bwizard.Bind(wx.EVT_BUTTON, self.OnCreateLocation)

        self.rename_location_button.Bind(wx.EVT_BUTTON, self.OnRenameLocation)
        self.delete_location_button.Bind(wx.EVT_BUTTON, self.OnDeleteLocation)
        self.download_location_button.Bind(wx.EVT_BUTTON,
                                           self.OnDownloadLocation)
        self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.OnRenameMapset)
        self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.OnDeleteMapset)

        self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
        self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
        self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
        self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
コード例 #3
0
ファイル: preferences.py プロジェクト: xtistosm/grass-ci
    def _createActionPage(self, notebook):
        """Create notebook page for action settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Command"))

        # colors
        border = wx.BoxSizer(wx.VERTICAL)
        box = StaticBox(parent=panel, id=wx.ID_ANY,
                        label=" %s " % _("Color"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

        row = 0
        gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
                                 label=_("Valid:")),
                      flag=wx.ALIGN_LEFT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 0))
        vColor = csel.ColourSelect(
            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
                group='modeler', key='action', subkey=(
                    'color', 'valid')), size=globalvar.DIALOG_COLOR_SIZE)
        vColor.SetName('GetColour')
        self.winId['modeler:action:color:valid'] = vColor.GetId()

        gridSizer.Add(vColor,
                      flag=wx.ALIGN_RIGHT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

        row += 1
        gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
                                 label=_("Invalid:")),
                      flag=wx.ALIGN_LEFT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 0))
        iColor = csel.ColourSelect(
            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
                group='modeler', key='action', subkey=(
                    'color', 'invalid')), size=globalvar.DIALOG_COLOR_SIZE)
        iColor.SetName('GetColour')
        self.winId['modeler:action:color:invalid'] = iColor.GetId()

        gridSizer.Add(iColor,
                      flag=wx.ALIGN_RIGHT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

        row += 1
        gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
                                 label=_("Running:")),
                      flag=wx.ALIGN_LEFT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 0))
        rColor = csel.ColourSelect(
            parent=panel, id=wx.ID_ANY, colour=self.settings.Get(
                group='modeler', key='action', subkey=(
                    'color', 'running')), size=globalvar.DIALOG_COLOR_SIZE)
        rColor.SetName('GetColour')
        self.winId['modeler:action:color:running'] = rColor.GetId()

        gridSizer.Add(rColor,
                      flag=wx.ALIGN_RIGHT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        # size
        box = StaticBox(parent=panel, id=wx.ID_ANY,
                        label=" %s " % _("Shape size"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

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

        width = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            min=0,
            max=500,
            initial=self.settings.Get(
                group='modeler',
                key='action',
                subkey=(
                    'size',
                    'width')))
        width.SetName('GetValue')
        self.winId['modeler:action:size:width'] = width.GetId()

        gridSizer.Add(width,
                      flag=wx.ALIGN_RIGHT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        height = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            min=0,
            max=500,
            initial=self.settings.Get(
                group='modeler',
                key='action',
                subkey=(
                    'size',
                    'height')))
        height.SetName('GetValue')
        self.winId['modeler:action:size:height'] = height.GetId()

        gridSizer.Add(height,
                      flag=wx.ALIGN_RIGHT |
                      wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        panel.SetSizer(border)

        return panel
コード例 #4
0
    def _requestPage(self):
        """Create request page"""
        self.req_page_panel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.notebook.AddPage(page=self.req_page_panel,
                              text=_('Request'),
                              name='request')

        # list of layers
        self.layersBox = StaticBox(parent=self.req_page_panel,
                                   id=wx.ID_ANY,
                                   label=_("List of layers "))

        style = wx.TR_DEFAULT_STYLE | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT
        if self.drv_props['req_multiple_layers']:
            style = style | wx.TR_MULTIPLE
        if 'WMS' not in self.ws:
            style = style | wx.TR_HIDE_ROOT

        self.list = LayersList(parent=self.req_page_panel,
                               web_service=self.ws,
                               style=style)

        self.params['format'] = None

        self.params['srs'] = None
        if 'srs' not in self.drv_props['ignored_params']:
            projText = StaticText(parent=self.req_page_panel,
                                  id=wx.ID_ANY,
                                  label=_("Source projection:"))
            self.params['srs'] = wx.Choice(parent=self.req_page_panel,
                                           id=wx.ID_ANY)

        self.list.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnListSelChanged)

        # layout
        self.req_page_sizer = wx.BoxSizer(wx.VERTICAL)

        layersSizer = wx.StaticBoxSizer(self.layersBox, wx.HORIZONTAL)

        layersSizer.Add(self.list,
                        proportion=1,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
                        border=5)

        self.req_page_sizer.Add(layersSizer,
                                proportion=1,
                                flag=wx.LEFT | wx.RIGHT | wx.BOTTOM
                                | wx.EXPAND,
                                border=5)

        self.source_sizer = wx.BoxSizer(wx.HORIZONTAL)

        if self.params['format'] is not None:
            self.source_sizer.Add(self.params['format'],
                                  flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
                                  border=5)

        if self.params['srs'] is not None:
            self.source_sizer.Add(projText,
                                  flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
                                  border=5)
            self.source_sizer.Add(self.params['srs'],
                                  flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT
                                  | wx.TOP | wx.BOTTOM,
                                  border=5)

        self.req_page_sizer.Add(self.source_sizer,
                                flag=wx.LEFT | wx.RIGHT | wx.BOTTOM
                                | wx.EXPAND,
                                border=5)

        self.req_page_panel.SetSizer(self.req_page_sizer)
コード例 #5
0
class SearchModuleWindow(wx.Panel):
    """Menu tree and search widget for searching modules.

    Signal:
        showNotification - attribute 'message'
    """
    def __init__(self,
                 parent,
                 handlerObj,
                 giface,
                 model,
                 id=wx.ID_ANY,
                 **kwargs):
        self.parent = parent
        self._handlerObj = handlerObj
        self._giface = giface

        self.showNotification = Signal('SearchModuleWindow.showNotification')
        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        # tree
        self._tree = CTreeView(model=model, parent=self)
        self._tree.SetToolTip(
            _("Double-click or Ctrl-Enter to run selected module"))

        #        self._dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
        #                                     label = " %s " % _("Module tree"))

        # search widget
        self._search = SearchModuleWidget(parent=self,
                                          model=model,
                                          showChoice=False)
        self._search.showSearchResult.connect(
            lambda result: self._tree.Select(result))
        self._search.showNotification.connect(self.showNotification)

        self._helpText = StaticText(
            parent=self,
            id=wx.ID_ANY,
            label="Press Enter for next match, Ctrl+Enter to run command")
        self._helpText.SetForegroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        # buttons
        self._btnRun = Button(self, id=wx.ID_OK, label=_("&Run"))
        self._btnRun.SetToolTip(_("Run selected module from the tree"))
        self._btnHelp = Button(self, id=wx.ID_ANY, label=_("H&elp"))
        self._btnHelp.SetToolTip(
            _("Show manual for selected module from the tree"))
        self._btnAdvancedSearch = Button(self,
                                         id=wx.ID_ANY,
                                         label=_("Adva&nced search..."))
        self._btnAdvancedSearch.SetToolTip(
            _("Do advanced search using %s module") % 'g.search.module')

        # bindings
        self._btnRun.Bind(wx.EVT_BUTTON, lambda evt: self.Run())
        self._btnHelp.Bind(wx.EVT_BUTTON, lambda evt: self.Help())
        self._btnAdvancedSearch.Bind(wx.EVT_BUTTON,
                                     lambda evt: self.AdvancedSearch())
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self._tree.selectionChanged.connect(self.OnItemSelected)
        self._tree.itemActivated.connect(lambda node: self.Run(node))

        self._layout()

        self._search.SetFocus()

    def _layout(self):
        """Do dialog layout"""
        sizer = wx.BoxSizer(wx.VERTICAL)

        # body
        dataSizer = wx.BoxSizer(wx.HORIZONTAL)
        dataSizer.Add(self._tree, proportion=1, flag=wx.EXPAND)

        # buttons
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(self._btnAdvancedSearch, proportion=0)
        btnSizer.AddStretchSpacer()
        btnSizer.Add(self._btnHelp, proportion=0)
        btnSizer.Add(self._btnRun, proportion=0)

        sizer.Add(dataSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)

        sizer.Add(self._search,
                  proportion=0,
                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
                  border=5)

        sizer.Add(btnSizer,
                  proportion=0,
                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
                  border=5)

        sizer.Add(self._helpText,
                  proportion=0,
                  flag=wx.EXPAND | wx.LEFT,
                  border=5)

        sizer.Fit(self)
        sizer.SetSizeHints(self)

        self.SetSizer(sizer)

        self.Fit()
        self.SetAutoLayout(True)
        self.Layout()

    def _GetSelectedNode(self):
        selection = self._tree.GetSelected()
        if not selection:
            return None
        return selection[0]

    def Run(self, node=None):
        """Run selected command.

        :param node: a tree node associated with the module or other item
        """
        if not node:
            node = self._GetSelectedNode()
        # nothing selected
        if not node:
            return
        data = node.data
        # non-leaf nodes
        if not data:
            return

        # extract name of the handler and create a new call
        handler = 'self._handlerObj.' + data['handler'].lstrip('self.')

        if data['command']:
            eval(handler)(event=None, cmd=data['command'].split())
        else:
            eval(handler)(event=None)

    def Help(self, node=None):
        """Show documentation for a module"""
        if not node:
            node = self._GetSelectedNode()
        # nothing selected
        if not node:
            return
        data = node.data
        # non-leaf nodes
        if not data:
            return

        if not data['command']:
            # showing nothing for non-modules
            return
        # strip parameters from command if present
        name = data['command'].split()[0]
        self._giface.Help(name)
        self.showNotification.emit(
            message=_("Documentation for %s is now open in the web browser") %
            name)

    def AdvancedSearch(self):
        """Show advanced search window"""
        self._handlerObj.RunMenuCmd(cmd=['g.search.modules'])

    def OnKeyUp(self, event):
        """Key or key combination pressed"""
        if event.ControlDown() and \
                event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER):
            self.Run()

    def OnItemSelected(self, node):
        """Item selected"""
        data = node.data
        if not data or 'command' not in data:
            return

        if data['command']:
            label = data['command']
            if data['description']:
                label += ' -- ' + data['description']
        else:
            label = data['description']

        self.showNotification.emit(message=label)
コード例 #6
0
ファイル: preferences.py プロジェクト: petrasovaa/grass
    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
コード例 #7
0
ファイル: dialogs.py プロジェクト: anikaweinmann/grass-ci
    def _createWidgets(self):

        settingsFile = os.path.join(GetSettingsPath(), 'wxWS')

        self.settsManager = WSManageSettingsWidget(
            parent=self,
            settingsFile=settingsFile,
            default_servers=self.default_servers)

        self.settingsBox = StaticBox(parent=self,
                                     id=wx.ID_ANY,
                                     label=_(" Server settings "))

        self.serverText = StaticText(parent=self,
                                     id=wx.ID_ANY,
                                     label=_("Server:"))
        self.server = TextCtrl(parent=self, id=wx.ID_ANY)

        self.btn_connect = Button(parent=self,
                                  id=wx.ID_ANY,
                                  label=_("&Connect"))
        self.btn_connect.SetToolTip(_("Connect to the server"))
        if not self.server.GetValue():
            self.btn_connect.Enable(False)

        self.infoCollapseLabelExp = _('Show advanced connection settings')
        self.infoCollapseLabelCol = _('Hide advanced connection settings')

        self.adv_conn = wx.CollapsiblePane(parent=self,
                                           label=self.infoCollapseLabelExp,
                                           style=wx.CP_DEFAULT_STYLE
                                           | wx.CP_NO_TLW_RESIZE | wx.EXPAND)

        self.MakeAdvConnPane(pane=self.adv_conn.GetPane())
        self.adv_conn.Collapse(True)
        self.Bind(wx.EVT_COLLAPSIBLEPANE_CHANGED, self.OnAdvConnPaneChanged,
                  self.adv_conn)

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

        self.layerNameBox = StaticBox(parent=self.reqDataPanel,
                                      id=wx.ID_ANY,
                                      label=_(" Layer Manager Settings "))

        self.layerNameText = StaticText(parent=self.reqDataPanel,
                                        id=wx.ID_ANY,
                                        label=_("Output layer name:"))
        self.layerName = TextCtrl(parent=self.reqDataPanel, id=wx.ID_ANY)

        for ws in six.iterkeys(self.ws_panels):
            # set class WSPanel argument layerNameTxtCtrl
            self.ws_panels[ws]['panel'] = WSPanel(parent=self.reqDataPanel,
                                                  web_service=ws)
            self.ws_panels[ws]['panel'].capParsed.connect(
                self.OnPanelCapParsed)
            self.ws_panels[ws]['panel'].layerSelected.connect(
                self.OnLayerSelected)

        # buttons
        self.btn_close = Button(parent=self, id=wx.ID_CLOSE)
        self.btn_close.SetToolTip(_("Close dialog"))

        # statusbar
        self.statusbar = wx.StatusBar(parent=self, id=wx.ID_ANY)

        # bindings
        self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.btn_connect.Bind(wx.EVT_BUTTON, self.OnConnect)

        self.server.Bind(wx.EVT_TEXT, self.OnServer)
        self.layerName.Bind(wx.EVT_TEXT, self.OnOutputLayerName)

        self.settsManager.settingsChanged.connect(self.OnSettingsChanged)
        self.settsManager.settingsSaving.connect(self.OnSettingsSaving)
コード例 #8
0
class MapCalcFrame(wx.Frame):
    """Mapcalc Frame class. Calculator-style window to create and run
    r(3).mapcalc statements.
    """
    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 = _('Raster Map Calculator')
        if self.cmd == 'r3.mapcalc':
            self.rast3d = True
            title = _('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 = ClearButton(parent=self.panel)
        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.SetDefault()
        self.btn_close = CloseButton(parent=self.panel)
        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_ANY,
                               label=_("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.OnCopyCommand)

        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)

        # bind closing to ESC
        self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_CANCEL)
        accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CANCEL)]
        accelTable = wx.AcceleratorTable(accelTableList)
        self.SetAcceleratorTable(accelTable)

        self._layout()

        self.SetMinSize(self.panel.GetBestSize())
        # workaround for http://trac.wxwidgets.org/ticket/13628
        self.SetSize(self.panel.GetBestSize())

    def _return_funct(self, event):
        i = event.GetString()
        self._addSomething(self.funct_dict[i])

        # reset
        win = self.FindWindowById(event.GetId())
        win.SetValue('')

    def _layout(self):
        sizer = wx.BoxSizer(wx.VERTICAL)

        controlSizer = wx.BoxSizer(wx.HORIZONTAL)
        operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
        outOpeSizer = wx.BoxSizer(wx.VERTICAL)

        buttonSizer1 = wx.GridBagSizer(5, 1)
        buttonSizer1.Add(self.btn['add'], pos=(0, 0))
        buttonSizer1.Add(self.btn['minus'], pos=(0, 1))
        buttonSizer1.Add(self.btn['mod'], pos=(5, 0))
        buttonSizer1.Add(self.btn['mult'], pos=(1, 0))
        buttonSizer1.Add(self.btn['div'], pos=(1, 1))
        buttonSizer1.Add(self.btn['pow'], pos=(5, 1))
        buttonSizer1.Add(self.btn['gt'], pos=(2, 0))
        buttonSizer1.Add(self.btn['gteq'], pos=(2, 1))
        buttonSizer1.Add(self.btn['eq'], pos=(4, 0))
        buttonSizer1.Add(self.btn['lt'], pos=(3, 0))
        buttonSizer1.Add(self.btn['lteq'], pos=(3, 1))
        buttonSizer1.Add(self.btn['noteq'], pos=(4, 1))

        buttonSizer2 = wx.GridBagSizer(5, 1)
        buttonSizer2.Add(self.btn['and'], pos=(0, 0))
        buttonSizer2.Add(self.btn['andbit'], pos=(1, 0))
        buttonSizer2.Add(self.btn['andnull'], pos=(2, 0))
        buttonSizer2.Add(self.btn['or'], pos=(0, 1))
        buttonSizer2.Add(self.btn['orbit'], pos=(1, 1))
        buttonSizer2.Add(self.btn['ornull'], pos=(2, 1))
        buttonSizer2.Add(self.btn['lshift'], pos=(3, 0))
        buttonSizer2.Add(self.btn['rshift'], pos=(3, 1))
        buttonSizer2.Add(self.btn['rshiftu'], pos=(4, 0))
        buttonSizer2.Add(self.btn['cond'], pos=(5, 0))
        buttonSizer2.Add(self.btn['compl'], pos=(5, 1))
        buttonSizer2.Add(self.btn['not'], pos=(4, 1))

        outputSizer = wx.StaticBoxSizer(self.outputBox, wx.VERTICAL)
        outputSizer.Add(self.newmaplabel,
                        flag=wx.ALIGN_CENTER | wx.TOP,
                        border=5)
        outputSizer.Add(self.newmaptxt, flag=wx.EXPAND | wx.ALL, border=5)

        operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)

        buttonSizer3 = wx.GridBagSizer(7, 1)
        buttonSizer3.Add(self.functlabel,
                         pos=(0, 0),
                         span=(1, 2),
                         flag=wx.ALIGN_CENTER | wx.EXPAND)
        buttonSizer3.Add(self.function, pos=(1, 0), span=(1, 2))
        buttonSizer3.Add(self.mapsellabel,
                         pos=(2, 0),
                         span=(1, 2),
                         flag=wx.ALIGN_CENTER)
        buttonSizer3.Add(self.mapselect, pos=(3, 0), span=(1, 2))
        threebutton = wx.GridBagSizer(1, 2)
        threebutton.Add(self.btn['parenl'],
                        pos=(0, 0),
                        span=(1, 1),
                        flag=wx.ALIGN_LEFT)
        threebutton.Add(self.btn['parenr'],
                        pos=(0, 1),
                        span=(1, 1),
                        flag=wx.ALIGN_CENTER)
        threebutton.Add(self.btn_clear,
                        pos=(0, 2),
                        span=(1, 1),
                        flag=wx.ALIGN_RIGHT)
        buttonSizer3.Add(threebutton,
                         pos=(4, 0),
                         span=(1, 1),
                         flag=wx.ALIGN_CENTER)

        buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
        buttonSizer4.Add(self.btn_load, flag=wx.ALL, border=5)
        buttonSizer4.Add(self.btn_save, flag=wx.ALL, border=5)
        buttonSizer4.Add(self.btn_copy, flag=wx.ALL, border=5)
        buttonSizer4.AddSpacer(30)
        buttonSizer4.Add(self.btn_help, flag=wx.ALL, border=5)
        buttonSizer4.Add(self.btn_run, flag=wx.ALL, border=5)
        buttonSizer4.Add(self.btn_close, flag=wx.ALL, border=5)

        operatorSizer.Add(buttonSizer1,
                          proportion=0,
                          flag=wx.ALL | wx.EXPAND,
                          border=5)
        operatorSizer.Add(buttonSizer2,
                          proportion=0,
                          flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
                          border=5)

        operandSizer.Add(buttonSizer3, proportion=0, flag=wx.ALL, border=5)

        controlSizer.Add(operatorSizer,
                         proportion=1,
                         flag=wx.RIGHT | wx.EXPAND,
                         border=5)
        outOpeSizer.Add(outputSizer, proportion=0, flag=wx.EXPAND)
        outOpeSizer.Add(operandSizer,
                        proportion=1,
                        flag=wx.EXPAND | wx.TOP,
                        border=5)
        controlSizer.Add(outOpeSizer, proportion=0, flag=wx.EXPAND)

        expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
        expressSizer.Add(self.text_mcalc, proportion=1, flag=wx.EXPAND)

        sizer.Add(controlSizer,
                  proportion=0,
                  flag=wx.EXPAND | wx.ALL,
                  border=5)
        sizer.Add(expressSizer,
                  proportion=1,
                  flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
                  border=5)
        sizer.Add(buttonSizer4,
                  proportion=0,
                  flag=wx.ALIGN_RIGHT | wx.ALL,
                  border=3)

        randomSizer = wx.BoxSizer(wx.HORIZONTAL)
        randomSizer.Add(self.randomSeed,
                        proportion=0,
                        flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                        border=20)
        randomSizer.Add(self.randomSeedStaticText,
                        proportion=0,
                        flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL,
                        border=5)
        randomSizer.Add(self.randomSeedText, proportion=0)
        sizer.Add(randomSizer, proportion=0, flag=wx.LEFT | wx.RIGHT, border=5)

        sizer.Add(self.overwrite,
                  proportion=0,
                  flag=wx.LEFT | wx.RIGHT,
                  border=5)
        if self.addbox.IsShown():
            sizer.Add(self.addbox,
                      proportion=0,
                      flag=wx.LEFT | wx.RIGHT,
                      border=5)

        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(sizer)
        sizer.Fit(self.panel)

        self.Layout()

    def AddMark(self, event):
        """Sends operators to insertion method
        """
        if event.GetId() == self.btn['compl'].GetId():
            mark = "~"
        elif event.GetId() == self.btn['not'].GetId():
            mark = "!"
        elif event.GetId() == self.btn['pow'].GetId():
            mark = "^"
        elif event.GetId() == self.btn['div'].GetId():
            mark = "/"
        elif event.GetId() == self.btn['add'].GetId():
            mark = "+"
        elif event.GetId() == self.btn['minus'].GetId():
            mark = "-"
        elif event.GetId() == self.btn['mod'].GetId():
            mark = "%"
        elif event.GetId() == self.btn['mult'].GetId():
            mark = "*"
        elif event.GetId() == self.btn['lshift'].GetId():
            mark = "<<"
        elif event.GetId() == self.btn['rshift'].GetId():
            mark = ">>"
        elif event.GetId() == self.btn['rshiftu'].GetId():
            mark = ">>>"
        elif event.GetId() == self.btn['gt'].GetId():
            mark = ">"
        elif event.GetId() == self.btn['gteq'].GetId():
            mark = ">="
        elif event.GetId() == self.btn['lt'].GetId():
            mark = "<"
        elif event.GetId() == self.btn['lteq'].GetId():
            mark = "<="
        elif event.GetId() == self.btn['eq'].GetId():
            mark = "=="
        elif event.GetId() == self.btn['noteq'].GetId():
            mark = "!="
        elif event.GetId() == self.btn['andbit'].GetId():
            mark = "&"
        elif event.GetId() == self.btn['orbit'].GetId():
            mark = "|"
        elif event.GetId() == self.btn['or'].GetId():
            mark = "||"
        elif event.GetId() == self.btn['ornull'].GetId():
            mark = "|||"
        elif event.GetId() == self.btn['and'].GetId():
            mark = "&&"
        elif event.GetId() == self.btn['andnull'].GetId():
            mark = "&&&"
        elif event.GetId() == self.btn['cond'].GetId():
            mark = " ? : "
        elif event.GetId() == self.btn['parenl'].GetId():
            mark = "("
        elif event.GetId() == self.btn['parenr'].GetId():
            mark = ")"
        self._addSomething(mark)

    # unused
    # def OnSelectTextEvt(self, event):
    #     """Checks if user is typing or the event was emited by map selection.
    #     Prevents from changing focus.
    #     """
    #     item = self.mapselect.GetValue().strip()
    #     if not (abs(len(item) - len(self.lastMapName)) == 1 and \
    #         self.lastMapName in item or item in self.lastMapName):
    #         self.OnSelect(event)

    #     self.lastMapName = item

    def OnSelect(self, event):
        """Gets raster map or function selection and send it to
        insertion method.

        Checks for characters which can be in raster map name but
        the raster map name must be then quoted.
        """
        win = self.FindWindowById(event.GetId())
        item = win.GetValue().strip()
        if any((char in item) for char in self.charactersToQuote):
            item = '"' + item + '"'
        self._addSomething(item)

        win.ChangeValue('')  # reset
        # Map selector likes to keep focus. Set it back to expression input area
        wx.CallAfter(self.text_mcalc.SetFocus)

    def OnUpdateStatusBar(self, event):
        """Update statusbar text"""
        command = self._getCommand()
        self.SetStatusText(command)
        event.Skip()

    def OnSeedFlag(self, event):
        checked = self.randomSeed.IsChecked()
        self.randomSeedText.Enable(not checked)
        self.randomSeedStaticText.Enable(not checked)

        event.Skip()

    def _getCommand(self):
        """Returns entire command as string."""
        expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
        cmd = 'r.mapcalc'
        if self.rast3d:
            cmd = 'r3.mapcalc'
        overwrite = ''
        if self.overwrite.IsChecked():
            overwrite = ' --overwrite'
        seed_flag = seed = ''
        if re.search(pattern="rand *\(.+\)", string=expr):
            if self.randomSeed.IsChecked():
                seed_flag = ' -s'
            else:
                seed = " seed={val}".format(
                    val=self.randomSeedText.GetValue().strip())

        return ('{cmd} expression="{new} = {expr}"{seed}{seed_flag}{overwrite}'
                .format(cmd=cmd,
                        expr=expr,
                        new=self.newmaptxt.GetValue(),
                        seed_flag=seed_flag,
                        seed=seed,
                        overwrite=overwrite))

    def _addSomething(self, what):
        """Inserts operators, map names, and functions into text area
        """
        mcalcstr = self.text_mcalc.GetValue()
        position = self.text_mcalc.GetInsertionPoint()

        newmcalcstr = mcalcstr[:position]

        position_offset = 0
        try:
            if newmcalcstr[-1] != ' ':
                newmcalcstr += ' '
                position_offset += 1
        except:
            pass

        newmcalcstr += what

        # Do not add extra space if there is already one
        try:
            if newmcalcstr[-1] != ' ' and mcalcstr[position] != ' ':
                newmcalcstr += ' '
        except:
            newmcalcstr += ' '

        newmcalcstr += mcalcstr[position:]

        self.text_mcalc.SetValue(newmcalcstr)
        if len(what) > 0:
            match = re.search(pattern="\(.*\)", string=what)
            if match:
                position_offset += match.start() + 1
            else:
                position_offset += len(what)
                try:
                    if newmcalcstr[position + position_offset] == ' ':
                        position_offset += 1
                except:
                    pass

        self.text_mcalc.SetInsertionPoint(position + position_offset)
        self.text_mcalc.Update()
        self.text_mcalc.SetFocus()

    def OnMCalcRun(self, event):
        """Builds and runs r.mapcalc statement
        """
        name = self.newmaptxt.GetValue().strip()
        if not name:
            GError(parent=self,
                   message=_("You must enter the name of "
                             "a new raster map to create."))
            return

        if not (name[0] == '"' and name[-1] == '"') and any(
            (char in name) for char in self.charactersToQuote):
            name = '"' + name + '"'

        expr = self.text_mcalc.GetValue().strip().replace("\n", " ")
        if not expr:
            GError(parent=self,
                   message=_("You must enter an expression "
                             "to create a new raster map."))
            return

        seed_flag = seed = None
        if re.search(pattern="rand *\(.+\)", string=expr):
            if self.randomSeed.IsChecked():
                seed_flag = '-s'
            else:
                seed = self.randomSeedText.GetValue().strip()
        if self.log:
            cmd = [self.cmd]
            if seed_flag:
                cmd.append('-s')
            if seed:
                cmd.append("seed={val}".format(val=seed))
            if self.overwrite.IsChecked():
                cmd.append('--overwrite')
            cmd.append(str('expression=%s = %s' % (name, expr)))

            self.log.RunCmd(cmd, onDone=self.OnDone)
            self.parent.Raise()
        else:
            if self.overwrite.IsChecked():
                overwrite = True
            else:
                overwrite = False
            params = dict(expression="%s=%s" % (name, expr),
                          overwrite=overwrite)
            if seed_flag:
                params['flags'] = 's'
            if seed:
                params['seed'] = seed

            RunCommand(self.cmd, **params)

    def OnDone(self, event):
        """Add create map to the layer tree

        Sends the mapCreated signal from the grass interface.
        """
        if event.returncode != 0:
            return
        name = self.newmaptxt.GetValue().strip(
            ' "') + '@' + grass.gisenv()['MAPSET']
        ltype = 'raster'
        if self.rast3d:
            ltype = 'raster_3d'
        self._giface.mapCreated.emit(name=name,
                                     ltype=ltype,
                                     add=self.addbox.IsChecked())
        gisenv = grass.gisenv()
        self._giface.grassdbChanged.emit(grassdb=gisenv['GISDBASE'],
                                         location=gisenv['LOCATION_NAME'],
                                         mapset=gisenv['MAPSET'],
                                         action='new',
                                         map=name.split('@')[0],
                                         element=ltype)

    def OnSaveExpression(self, event):
        """Saves expression to file
        """
        mctxt = self.newmaptxt.GetValue() + ' = ' + self.text_mcalc.GetValue(
        ) + os.linesep

        # dialog
        dlg = wx.FileDialog(
            parent=self,
            message=_("Choose a file name to save the expression"),
            wildcard=_("Expression file (*)|*"),
            style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            if not path:
                dlg.Destroy()
                return

            try:
                fobj = open(path, 'w')
                fobj.write(mctxt)
            finally:
                fobj.close()

        dlg.Destroy()

    def OnLoadExpression(self, event):
        """Load expression from file
        """
        dlg = wx.FileDialog(
            parent=self,
            message=_("Choose a file name to load the expression"),
            wildcard=_("Expression file (*)|*"),
            style=wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            if not path:
                dlg.Destroy()
                return

            try:
                fobj = open(path, 'r')
                mctxt = fobj.read()
            finally:
                fobj.close()

            try:
                result, exp = mctxt.split('=', 1)
            except ValueError:
                result = ''
                exp = mctxt

            self.newmaptxt.SetValue(result.strip())
            self.text_mcalc.SetValue(exp.strip())
            self.text_mcalc.SetFocus()
            self.text_mcalc.SetInsertionPointEnd()

        dlg.Destroy()

    def OnCopyCommand(self, event):
        command = self._getCommand()
        cmddata = wx.TextDataObject()
        cmddata.SetText(command)
        if wx.TheClipboard.Open():
            wx.TheClipboard.SetData(cmddata)
            wx.TheClipboard.Close()
            self.SetStatusText(
                _("'{cmd}' copied to clipboard").format(cmd=command))

    def OnClear(self, event):
        """Clears text area
        """
        self.text_mcalc.SetValue('')

    def OnHelp(self, event):
        """Launches r.mapcalc help
        """
        RunCommand('g.manual', parent=self, entry=self.cmd)

    def OnClose(self, event):
        """Close window"""
        self.Destroy()
コード例 #9
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 = _('Raster Map Calculator')
        if self.cmd == 'r3.mapcalc':
            self.rast3d = True
            title = _('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 = ClearButton(parent=self.panel)
        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.SetDefault()
        self.btn_close = CloseButton(parent=self.panel)
        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_ANY,
                               label=_("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.OnCopyCommand)

        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)

        # bind closing to ESC
        self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_CANCEL)
        accelTableList = [(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, wx.ID_CANCEL)]
        accelTable = wx.AcceleratorTable(accelTableList)
        self.SetAcceleratorTable(accelTable)

        self._layout()

        self.SetMinSize(self.panel.GetBestSize())
        # workaround for http://trac.wxwidgets.org/ticket/13628
        self.SetSize(self.panel.GetBestSize())
コード例 #10
0
    def _createQueryPage(self, notebook):
        """Create notebook page for query tool"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Query tool"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # query tool box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Choose query tool"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        LocUnits = self.parent.MapWindow.Map.GetProjInfo()['units']

        self.queryBox = CheckBox(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select by box"))
        self.queryBox.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="query",
                subkey='box'))

        sizer.Add(
            self.queryBox,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        sizer.Add((0, 5))

        #
        # length
        #
        self.queryLength = wx.RadioButton(
            parent=panel, id=wx.ID_ANY, label=_("length"))
        self.queryLength.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
        sizer.Add(
            self.queryLength,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        txt = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select lines"))
        self.queryLengthSL = wx.Choice(
            parent=panel, id=wx.ID_ANY, choices=[
                _("shorter than"), _("longer than")])
        self.queryLengthSL.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="queryLength",
                subkey='than-selection'))
        self.queryLengthValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(
                100, -1), initial=1, min=0, max=1e6)
        self.queryLengthValue.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="queryLength",
                subkey='thresh'))
        units = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label="%s" %
            LocUnits)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.queryLengthSL,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.queryLengthValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(
            flexSizer,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        #
        # dangle
        #
        self.queryDangle = wx.RadioButton(
            parent=panel, id=wx.ID_ANY, label=_("dangle"))
        self.queryDangle.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
        sizer.Add(
            self.queryDangle,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        txt = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select dangles"))
        self.queryDangleSL = wx.Choice(
            parent=panel, id=wx.ID_ANY, choices=[
                _("shorter than"), _("longer than")])
        self.queryDangleSL.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="queryDangle",
                subkey='than-selection'))
        self.queryDangleValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(
                100, -1), initial=1, min=0, max=1e6)
        self.queryDangleValue.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="queryDangle",
                subkey='thresh'))
        units = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label="%s" %
            LocUnits)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.queryDangleSL,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.queryDangleValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(
            flexSizer,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        if UserSettings.Get(group='vdigit', key="query",
                            subkey='selection') == 0:
            self.queryLength.SetValue(True)
        else:
            self.queryDangle.SetValue(True)

        # enable & disable items
        self.OnChangeQuery(None)

        border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        panel.SetSizer(border)

        return panel
コード例 #11
0
    def _createAttributesPage(self, notebook):
        """Create notebook page for attributes"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Attributes"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # add new record
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Digitize new feature"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        # checkbox
        self.addRecord = CheckBox(parent=panel, id=wx.ID_ANY,
                                  label=_("Add new record into table"))
        self.addRecord.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="addRecord",
                subkey='enabled'))
        sizer.Add(
            self.addRecord,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        # settings
        flexSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
        flexSizer.AddGrowableCol(0)
        settings = ((_("Layer"), 1), (_("Category"), 1),
                    (_("Mode"), _("Next to use")))
        # layer
        text = StaticText(parent=panel, id=wx.ID_ANY, label=_("Layer"))
        self.layer = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(125, -1),
                              min=1, max=1e3)
        self.layer.SetValue(int(UserSettings.Get(
            group='vdigit', key="layer", subkey='value')))
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.layer, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        # category number
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Category number"))
        self.category = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(125, -1),
            initial=UserSettings.Get(
                group='vdigit', key="category", subkey='value'),
            min=-1e9, max=1e9)
        if UserSettings.Get(group='vdigit', key="categoryMode",
                            subkey='selection') != 1:
            self.category.Enable(False)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.category, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        # category mode
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Category mode"))
        self.categoryMode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
            125, -1), choices=[_("Next to use"), _("Manual entry"), _("No category")])
        self.categoryMode.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="categoryMode",
                subkey='selection'))
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.categoryMode, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)

        sizer.Add(
            flexSizer,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0,
                   flag=wx.ALL | wx.EXPAND, border=5)

        #
        # delete existing record
        #
        box = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " %
            _("Delete existing feature(s)"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        # checkbox
        self.deleteRecord = CheckBox(parent=panel, id=wx.ID_ANY,
                                        label=_("Delete record from table"))
        self.deleteRecord.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="delRecord",
                subkey='enabled'))
        sizer.Add(
            self.deleteRecord,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0,
                   flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)

        #
        # geometry attributes (currently only length and area are supported)
        #
        box = StaticBox(parent=panel, id=wx.ID_ANY,
                        label=" %s " % _("Geometry attributes"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
        self.geomAttrb = {'length': {'label': _('length')},
                          'area': {'label': _('area')},
                          'perimeter': {'label': _('perimeter')}}

        digitToolbar = self.parent.toolbars['vdigit']
        try:
            vectorName = digitToolbar.GetLayer().GetName()
        except AttributeError:
            vectorName = None  # no vector selected for editing
        layer = UserSettings.Get(group='vdigit', key="layer", subkey='value')
        mapLayer = self.parent.toolbars['vdigit'].GetLayer()
        tree = self.parent.tree
        if tree:
            item = tree.FindItemByData('maplayer', mapLayer)
        else:
            item = None
        row = 0
        for attrb in ['length', 'area', 'perimeter']:
            # checkbox
            check = CheckBox(parent=panel, id=wx.ID_ANY,
                             label=self.geomAttrb[attrb]['label'])
            ### self.deleteRecord.SetValue(UserSettings.Get(group='vdigit', key="delRecord", subkey='enabled'))
            check.Bind(wx.EVT_CHECKBOX, self.OnGeomAttrb)
            # column (only numeric)
            column = ColumnSelect(parent=panel, size=(200, -1))
            column.InsertColumns(vector=vectorName,
                                 layer=layer, excludeKey=True,
                                 type=['integer', 'double precision'])
            # units
            if attrb == 'area':
                choices = Units.GetUnitsList('area')
            else:
                choices = Units.GetUnitsList('length')
            win_units = wx.Choice(parent=panel, id=wx.ID_ANY,
                                  choices=choices, size=(120, -1))

            # default values
            check.SetValue(False)
            if item and tree.GetLayerInfo(item, key='vdigit') and \
                    'geomAttr' in tree.GetLayerInfo(item, key='vdigit') and \
                    attrb in tree.GetLayerInfo(item, key='vdigit')['geomAttr']:
                check.SetValue(True)
                column.SetStringSelection(
                    tree.GetLayerInfo(item, key='vdigit')['geomAttr']
                    [attrb]['column'])
                if attrb == 'area':
                    type = 'area'
                else:
                    type = 'length'
                unitsIdx = Units.GetUnitsIndex(type, tree.GetLayerInfo(
                    item, key='vdigit')['geomAttr'][attrb]['units'])
                win_units.SetSelection(unitsIdx)

            if not vectorName:
                check.Enable(False)
                column.Enable(False)

            if not check.IsChecked():
                column.Enable(False)

            self.geomAttrb[attrb]['check'] = check.GetId()
            self.geomAttrb[attrb]['column'] = column.GetId()
            self.geomAttrb[attrb]['units'] = win_units.GetId()

            gridSizer.Add(check,
                          flag=wx.ALIGN_CENTER_VERTICAL,
                          pos=(row, 0))
            gridSizer.Add(column,
                          pos=(row, 1))
            gridSizer.Add(win_units,
                          pos=(row, 2))
            row += 1

        note = '\n'.join(textwrap.wrap(_("Note: These settings are stored "
                                         "in the workspace not in the vector digitizer "
                                         "preferences."), 55))
        gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
                                 label=note),
                      pos=(3, 0), span=(1, 3))

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

        # bindings
        self.Bind(wx.EVT_CHECKBOX, self.OnChangeAddRecord, self.addRecord)
        self.Bind(wx.EVT_CHOICE, self.OnChangeCategoryMode, self.categoryMode)
        self.Bind(wx.EVT_SPINCTRL, self.OnChangeLayer, self.layer)

        panel.SetSizer(border)

        return panel
コード例 #12
0
class VDigitSettingsDialog(wx.Dialog):

    def __init__(self, parent, giface, title=_("Digitization settings"),
                 style=wx.DEFAULT_DIALOG_STYLE):
        """Standard settings dialog for digitization purposes
        """
        wx.Dialog.__init__(
            self,
            parent=parent,
            id=wx.ID_ANY,
            title=title,
            style=style)

        self._giface = giface
        self.parent = parent                     # MapFrame
        self.digit = self.parent.MapWindow.digit

        # notebook
        notebook = wx.Notebook(parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
        self._createGeneralPage(notebook)
        self._createSymbologyPage(notebook)
        self.digit.SetCategory()
        self._createAttributesPage(notebook)
        self._createQueryPage(notebook)

        # buttons
        btnApply = Button(self, wx.ID_APPLY)
        btnCancel = Button(self, wx.ID_CLOSE)
        btnSave = Button(self, wx.ID_SAVE)
        btnSave.SetDefault()

        # bindigs
        btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
        btnApply.SetToolTip(_("Apply changes for this session"))
        btnApply.SetDefault()
        btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
        btnSave.SetToolTip(
            _("Close dialog and save changes to user settings file"))
        btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
        btnCancel.SetToolTip(_("Close dialog and ignore changes"))

        # sizers
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(btnCancel, proportion=0,
                     flag=wx.ALL, border=5)
        btnSizer.Add(btnApply, proportion=0,
                     flag=wx.ALL, border=5)
        btnSizer.Add(btnSave, proportion=0,
                     flag=wx.ALL, border=5)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(
            notebook,
            proportion=1,
            flag=wx.EXPAND | wx.ALL,
            border=5)
        mainSizer.Add(btnSizer, proportion=0,
                      flag=wx.ALIGN_RIGHT, border=5)

        self.Bind(wx.EVT_CLOSE, self.OnCancel)

        self.SetSizer(mainSizer)
        mainSizer.Fit(self)

    def _createSymbologyPage(self, notebook):
        """Create notebook page concerning symbology settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Symbology"))

        sizer = wx.BoxSizer(wx.VERTICAL)

        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)

        self.symbology = {}
        for label, key in self._symbologyData():
            textLabel = StaticText(panel, wx.ID_ANY, label)
            color = csel.ColourSelect(
                panel, id=wx.ID_ANY, colour=UserSettings.Get(
                    group='vdigit', key='symbol', subkey=[
                        key, 'color']), size=(
                    40, 25))
            isEnabled = UserSettings.Get(group='vdigit', key='symbol',
                                         subkey=[key, 'enabled'])
            if isEnabled is not None:
                enabled = CheckBox(panel, id=wx.ID_ANY, label="")
                enabled.SetValue(isEnabled)
                self.symbology[key] = (enabled, color)
            else:
                enabled = (1, 1)
                self.symbology[key] = (None, color)

            flexSizer.Add(
                textLabel,
                proportion=0,
                flag=wx.ALIGN_CENTER_VERTICAL)
            flexSizer.Add(
                enabled,
                proportion=0,
                flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
            flexSizer.Add(
                color,
                proportion=0,
                flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
            color.SetName("GetColour")

        sizer.Add(
            flexSizer,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=10)

        panel.SetSizer(sizer)

        return panel

    def _createGeneralPage(self, notebook):
        """Create notebook page concerning general settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("General"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # display section
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Display"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        # line width
        text = StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width"))
        self.lineWidthValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='value'),
            min=1, max=1e6)
        units = StaticText(
            parent=panel, id=wx.ID_ANY, size=(115, -1),
            label=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='units'),
            style=wx.ALIGN_LEFT)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.lineWidthValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            units,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
            border=10)

        sizer.Add(
            flexSizer,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        #
        # snapping section
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Snapping"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)

        # snapping
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Snapping threshold"))
        self.snappingValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="snapping", subkey='value'),
            min=-1, max=1e6)
        self.snappingValue.Bind(wx.EVT_SPINCTRL, self.OnChangeSnappingValue)
        self.snappingValue.Bind(wx.EVT_TEXT, self.OnChangeSnappingValue)
        self.snappingUnit = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
            125, -1), choices=[_("screen pixels"), _("map units")])
        try:
            self.snappingUnit.SetSelection(UserSettings.Get(group='vdigit',
                                                            key="snapping",
                                                            subkey='unit'))
        except:
            self.snappingUnit.SetSelection(0)
        self.snappingUnit.Bind(wx.EVT_CHOICE, self.OnChangeSnappingUnits)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.snappingValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.snappingUnit,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)

        vertexSizer = wx.BoxSizer(wx.VERTICAL)
        self.snapVertex = CheckBox(parent=panel, id=wx.ID_ANY,
                                   label=_("Snap also to vertex"))
        self.snapVertex.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="snapToVertex",
                subkey='enabled'))
        vertexSizer.Add(self.snapVertex, proportion=0, flag=wx.EXPAND)
        self.mapUnits = self.parent.MapWindow.Map.GetProjInfo()['units']
        self.snappingInfo = StaticText(
            parent=panel, id=wx.ID_ANY,
            label=_("Snapping threshold is %(value).1f %(units)s") %
            {'value': self.digit.GetDisplay().GetThreshold(),
             'units': self.mapUnits})
        vertexSizer.Add(self.snappingInfo, proportion=0,
                        flag=wx.ALL | wx.EXPAND, border=1)

        sizer.Add(flexSizer, proportion=1, flag=wx.EXPAND)
        sizer.Add(vertexSizer, proportion=1, flag=wx.EXPAND)
        border.Add(sizer, proportion=0, flag=wx.LEFT |
                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)

        #
        # select box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Select vector features"))
        # feature type
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        inSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.selectFeature = {}
        for feature in ('point', 'line',
                        'centroid', 'boundary'):
            chkbox = CheckBox(parent=panel, label=feature)
            self.selectFeature[feature] = chkbox.GetId()
            chkbox.SetValue(UserSettings.Get(group='vdigit', key='selectType',
                                             subkey=[feature, 'enabled']))
            inSizer.Add(chkbox, proportion=0,
                        flag=wx.EXPAND | wx.ALL, border=5)
        sizer.Add(inSizer, proportion=0, flag=wx.EXPAND)
        # threshold
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select threshold"))
        self.selectThreshValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="selectThresh", subkey='value'),
            min=1, max=1e6)
        units = StaticText(
            parent=panel, id=wx.ID_ANY, size=(115, -1),
            label=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='units'),
            style=wx.ALIGN_LEFT)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.selectThreshValue, proportion=0,
                      flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            units,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
            border=10)

        self.selectIn = CheckBox(parent=panel, id=wx.ID_ANY, label=_(
            "Select only features inside of selection bounding box"))
        self.selectIn.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="selectInside",
                subkey='enabled'))
        self.selectIn.SetToolTip(
            _("By default are selected all features overlapping selection bounding box "))

        self.checkForDupl = CheckBox(parent=panel, id=wx.ID_ANY,
                                     label=_("Check for duplicates"))
        self.checkForDupl.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="checkForDupl",
                subkey='enabled'))

        sizer.Add(flexSizer, proportion=0, flag=wx.EXPAND)
        sizer.Add(
            self.selectIn,
            proportion=0,
            flag=wx.EXPAND | wx.ALL,
            border=1)
        sizer.Add(
            self.checkForDupl,
            proportion=0,
            flag=wx.EXPAND | wx.ALL,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # digitize lines box
        #
        box = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " %
            _("Digitize lines/boundaries"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        self.intersect = CheckBox(
            parent=panel, label=_("Break lines at intersection"))
        self.intersect.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='breakLines',
                subkey='enabled'))

        sizer.Add(
            self.intersect,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # digitize areas box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Digitize areas"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        self.closeBoundary = CheckBox(
            parent=panel, label=_("Close boundary (snap to the start node)"))
        self.closeBoundary.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='closeBoundary',
                subkey='enabled'))

        sizer.Add(
            self.closeBoundary,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # save-on-exit box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Save changes"))
        # save changes on exit?
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        self.save = CheckBox(parent=panel, label=_("Save changes on exit"))
        self.save.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='saveOnExit',
                subkey='enabled'))
        sizer.Add(
            self.save,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        panel.SetSizer(border)

        return panel

    def _createQueryPage(self, notebook):
        """Create notebook page for query tool"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Query tool"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # query tool box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Choose query tool"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        LocUnits = self.parent.MapWindow.Map.GetProjInfo()['units']

        self.queryBox = CheckBox(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select by box"))
        self.queryBox.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="query",
                subkey='box'))

        sizer.Add(
            self.queryBox,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        sizer.Add((0, 5))

        #
        # length
        #
        self.queryLength = wx.RadioButton(
            parent=panel, id=wx.ID_ANY, label=_("length"))
        self.queryLength.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
        sizer.Add(
            self.queryLength,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        txt = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select lines"))
        self.queryLengthSL = wx.Choice(
            parent=panel, id=wx.ID_ANY, choices=[
                _("shorter than"), _("longer than")])
        self.queryLengthSL.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="queryLength",
                subkey='than-selection'))
        self.queryLengthValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(
                100, -1), initial=1, min=0, max=1e6)
        self.queryLengthValue.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="queryLength",
                subkey='thresh'))
        units = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label="%s" %
            LocUnits)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.queryLengthSL,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.queryLengthValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(
            flexSizer,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        #
        # dangle
        #
        self.queryDangle = wx.RadioButton(
            parent=panel, id=wx.ID_ANY, label=_("dangle"))
        self.queryDangle.Bind(wx.EVT_RADIOBUTTON, self.OnChangeQuery)
        sizer.Add(
            self.queryDangle,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        flexSizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        txt = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select dangles"))
        self.queryDangleSL = wx.Choice(
            parent=panel, id=wx.ID_ANY, choices=[
                _("shorter than"), _("longer than")])
        self.queryDangleSL.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="queryDangle",
                subkey='than-selection'))
        self.queryDangleValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(
                100, -1), initial=1, min=0, max=1e6)
        self.queryDangleValue.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="queryDangle",
                subkey='thresh'))
        units = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label="%s" %
            LocUnits)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.queryDangleSL,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.queryDangleValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(units, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(
            flexSizer,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        if UserSettings.Get(group='vdigit', key="query",
                            subkey='selection') == 0:
            self.queryLength.SetValue(True)
        else:
            self.queryDangle.SetValue(True)

        # enable & disable items
        self.OnChangeQuery(None)

        border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        panel.SetSizer(border)

        return panel

    def _createAttributesPage(self, notebook):
        """Create notebook page for attributes"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Attributes"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # add new record
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Digitize new feature"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        # checkbox
        self.addRecord = CheckBox(parent=panel, id=wx.ID_ANY,
                                  label=_("Add new record into table"))
        self.addRecord.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="addRecord",
                subkey='enabled'))
        sizer.Add(
            self.addRecord,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        # settings
        flexSizer = wx.FlexGridSizer(cols=2, hgap=3, vgap=3)
        flexSizer.AddGrowableCol(0)
        settings = ((_("Layer"), 1), (_("Category"), 1),
                    (_("Mode"), _("Next to use")))
        # layer
        text = StaticText(parent=panel, id=wx.ID_ANY, label=_("Layer"))
        self.layer = SpinCtrl(parent=panel, id=wx.ID_ANY, size=(125, -1),
                              min=1, max=1e3)
        self.layer.SetValue(int(UserSettings.Get(
            group='vdigit', key="layer", subkey='value')))
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.layer, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        # category number
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Category number"))
        self.category = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(125, -1),
            initial=UserSettings.Get(
                group='vdigit', key="category", subkey='value'),
            min=-1e9, max=1e9)
        if UserSettings.Get(group='vdigit', key="categoryMode",
                            subkey='selection') != 1:
            self.category.Enable(False)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.category, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        # category mode
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Category mode"))
        self.categoryMode = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
            125, -1), choices=[_("Next to use"), _("Manual entry"), _("No category")])
        self.categoryMode.SetSelection(
            UserSettings.Get(
                group='vdigit',
                key="categoryMode",
                subkey='selection'))
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.categoryMode, proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)

        sizer.Add(
            flexSizer,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0,
                   flag=wx.ALL | wx.EXPAND, border=5)

        #
        # delete existing record
        #
        box = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " %
            _("Delete existing feature(s)"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        # checkbox
        self.deleteRecord = CheckBox(parent=panel, id=wx.ID_ANY,
                                        label=_("Delete record from table"))
        self.deleteRecord.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="delRecord",
                subkey='enabled'))
        sizer.Add(
            self.deleteRecord,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0,
                   flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)

        #
        # geometry attributes (currently only length and area are supported)
        #
        box = StaticBox(parent=panel, id=wx.ID_ANY,
                        label=" %s " % _("Geometry attributes"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
        self.geomAttrb = {'length': {'label': _('length')},
                          'area': {'label': _('area')},
                          'perimeter': {'label': _('perimeter')}}

        digitToolbar = self.parent.toolbars['vdigit']
        try:
            vectorName = digitToolbar.GetLayer().GetName()
        except AttributeError:
            vectorName = None  # no vector selected for editing
        layer = UserSettings.Get(group='vdigit', key="layer", subkey='value')
        mapLayer = self.parent.toolbars['vdigit'].GetLayer()
        tree = self.parent.tree
        if tree:
            item = tree.FindItemByData('maplayer', mapLayer)
        else:
            item = None
        row = 0
        for attrb in ['length', 'area', 'perimeter']:
            # checkbox
            check = CheckBox(parent=panel, id=wx.ID_ANY,
                             label=self.geomAttrb[attrb]['label'])
            ### self.deleteRecord.SetValue(UserSettings.Get(group='vdigit', key="delRecord", subkey='enabled'))
            check.Bind(wx.EVT_CHECKBOX, self.OnGeomAttrb)
            # column (only numeric)
            column = ColumnSelect(parent=panel, size=(200, -1))
            column.InsertColumns(vector=vectorName,
                                 layer=layer, excludeKey=True,
                                 type=['integer', 'double precision'])
            # units
            if attrb == 'area':
                choices = Units.GetUnitsList('area')
            else:
                choices = Units.GetUnitsList('length')
            win_units = wx.Choice(parent=panel, id=wx.ID_ANY,
                                  choices=choices, size=(120, -1))

            # default values
            check.SetValue(False)
            if item and tree.GetLayerInfo(item, key='vdigit') and \
                    'geomAttr' in tree.GetLayerInfo(item, key='vdigit') and \
                    attrb in tree.GetLayerInfo(item, key='vdigit')['geomAttr']:
                check.SetValue(True)
                column.SetStringSelection(
                    tree.GetLayerInfo(item, key='vdigit')['geomAttr']
                    [attrb]['column'])
                if attrb == 'area':
                    type = 'area'
                else:
                    type = 'length'
                unitsIdx = Units.GetUnitsIndex(type, tree.GetLayerInfo(
                    item, key='vdigit')['geomAttr'][attrb]['units'])
                win_units.SetSelection(unitsIdx)

            if not vectorName:
                check.Enable(False)
                column.Enable(False)

            if not check.IsChecked():
                column.Enable(False)

            self.geomAttrb[attrb]['check'] = check.GetId()
            self.geomAttrb[attrb]['column'] = column.GetId()
            self.geomAttrb[attrb]['units'] = win_units.GetId()

            gridSizer.Add(check,
                          flag=wx.ALIGN_CENTER_VERTICAL,
                          pos=(row, 0))
            gridSizer.Add(column,
                          pos=(row, 1))
            gridSizer.Add(win_units,
                          pos=(row, 2))
            row += 1

        note = '\n'.join(textwrap.wrap(_("Note: These settings are stored "
                                         "in the workspace not in the vector digitizer "
                                         "preferences."), 55))
        gridSizer.Add(StaticText(parent=panel, id=wx.ID_ANY,
                                 label=note),
                      pos=(3, 0), span=(1, 3))

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

        # bindings
        self.Bind(wx.EVT_CHECKBOX, self.OnChangeAddRecord, self.addRecord)
        self.Bind(wx.EVT_CHOICE, self.OnChangeCategoryMode, self.categoryMode)
        self.Bind(wx.EVT_SPINCTRL, self.OnChangeLayer, self.layer)

        panel.SetSizer(border)

        return panel

    def _symbologyData(self):
        """Data for _createSymbologyPage()

        label | checkbox | color
        """

        return (
            (_("Digitize new line segment"), "newSegment"),
            (_("Digitize new line/boundary"), "newLine"),
            (_("Highlight"), "highlight"),
            (_("Highlight (duplicates)"), "highlightDupl"),
            (_("Point"), "point"),
            (_("Line"), "line"),
            (_("Boundary (no area)"), "boundaryNo"),
            (_("Boundary (one area)"), "boundaryOne"),
            (_("Boundary (two areas)"), "boundaryTwo"),
            (_("Centroid (in area)"), "centroidIn"),
            (_("Centroid (outside area)"), "centroidOut"),
            (_("Centroid (duplicate in area)"), "centroidDup"),
            (_("Node (one line)"), "nodeOne"),
            (_("Node (two lines)"), "nodeTwo"),
            (_("Vertex"), "vertex"),
            (_("Area (closed boundary + centroid)"), "area"),
            (_("Direction"), "direction"),)

    def OnGeomAttrb(self, event):
        """Register geometry attributes (enable/disable)
        """
        checked = event.IsChecked()
        id = event.GetId()
        key = None
        for attrb, val in six.iteritems(self.geomAttrb):
            if val['check'] == id:
                key = attrb
                break

        column = self.FindWindowById(self.geomAttrb[key]['column'])
        if checked:
            column.Enable()
        else:
            column.Enable(False)

    def OnChangeCategoryMode(self, event):
        """Change category mode
        """
        mode = event.GetSelection()
        UserSettings.Set(
            group='vdigit',
            key="categoryMode",
            subkey='selection',
            value=mode)
        if mode == 1:  # manual entry
            self.category.Enable(True)
        elif self.category.IsEnabled():  # disable
            self.category.Enable(False)

        if mode == 2 and self.addRecord.IsChecked():  # no category
            self.addRecord.SetValue(False)

        self.digit.SetCategory()
        self.category.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='category',
                subkey='value'))

    def OnChangeLayer(self, event):
        """Layer changed
        """
        layer = event.GetInt()
        if layer > 0:
            UserSettings.Set(
                group='vdigit',
                key='layer',
                subkey='value',
                value=layer)
            self.digit.SetCategory()
            self.category.SetValue(
                UserSettings.Get(
                    group='vdigit',
                    key='category',
                    subkey='value'))

        event.Skip()

    def OnChangeAddRecord(self, event):
        """Checkbox 'Add new record' status changed
        """
        pass
        # self.category.SetValue(self.digit.SetCategory())

    def OnChangeSnappingValue(self, event):
        """Change snapping value - update static text
        """
        value = self.snappingValue.GetValue()

        if value < 0:
            region = self.parent.MapWindow.Map.GetRegion()
            res = (region['nsres'] + region['ewres']) / 2.
            threshold = self.digit.GetDisplay().GetThreshold(value=res)
        else:
            if self.snappingUnit.GetSelection() == 1:  # map units
                threshold = value
            else:
                threshold = self.digit.GetDisplay().GetThreshold(value=value)

        if value == 0:
            self.snappingInfo.SetLabel(_("Snapping disabled"))
        elif value < 0:
            self.snappingInfo.SetLabel(
                _(
                    "Snapping threshold is %(value).1f %(units)s "
                    "(based on comp. resolution)") %
                {'value': threshold, 'units': self.mapUnits.lower()})
        else:
            self.snappingInfo.SetLabel(
                _("Snapping threshold is %(value).1f %(units)s") %
                {'value': threshold, 'units': self.mapUnits.lower()})

        event.Skip()

    def OnChangeSnappingUnits(self, event):
        """Snapping units change -> update static text
        """
        value = self.snappingValue.GetValue()
        units = self.snappingUnit.GetSelection()
        threshold = self.digit.GetDisplay().GetThreshold(value=value, units=units)

        if units == 1:  # map units
            self.snappingInfo.SetLabel(
                _("Snapping threshold is %(value).1f %(units)s") %
                {'value': value, 'units': self.mapUnits})
        else:
            self.snappingInfo.SetLabel(
                _("Snapping threshold is %(value).1f %(units)s") %
                {'value': threshold, 'units': self.mapUnits})

        event.Skip()

    def OnChangeQuery(self, event):
        """Change query
        """
        if self.queryLength.GetValue():
            # length
            self.queryLengthSL.Enable(True)
            self.queryLengthValue.Enable(True)
            self.queryDangleSL.Enable(False)
            self.queryDangleValue.Enable(False)
        else:
            # dangle
            self.queryLengthSL.Enable(False)
            self.queryLengthValue.Enable(False)
            self.queryDangleSL.Enable(True)
            self.queryDangleValue.Enable(True)

    def OnSave(self, event):
        """Button 'Save' pressed
        """
        self.UpdateSettings()
        self.parent.toolbars['vdigit'].settingsDialog = None

        fileSettings = {}
        UserSettings.ReadSettingsFile(settings=fileSettings)
        fileSettings['vdigit'] = UserSettings.Get(group='vdigit')

        sfile = UserSettings.SaveToFile(fileSettings)
        self._giface.WriteLog(
            _('Vector digitizer settings saved to file <%s>.') %
            sfile)

        self.Destroy()

        event.Skip()

    def OnApply(self, event):
        """Button 'Apply' pressed
        """
        self.UpdateSettings()

    def OnCancel(self, event):
        """Button 'Cancel' pressed
        """
        self.parent.toolbars['vdigit'].settingsDialog = None
        self.Destroy()

        if event:
            event.Skip()

    def UpdateSettings(self):
        """Update digitizer settings

        .. todo::
            Needs refactoring
        """
        # TODO: it seems that it needs to be replaced by signal
        # but if it makes sense generally for wxGUI it can be added to giface
        if self.parent.GetLayerManager():
            self.parent.GetLayerManager().WorkspaceChanged()  # geometry attributes
        # symbology
        for key, (enabled, color) in six.iteritems(self.symbology):
            if enabled:
                UserSettings.Set(group='vdigit', key='symbol',
                                 subkey=[key, 'enabled'],
                                 value=enabled.IsChecked())
                UserSettings.Set(group='vdigit', key='symbol',
                                 subkey=[key, 'color'],
                                 value=tuple(color.GetColour()))
            else:
                UserSettings.Set(group='vdigit', key='symbol',
                                 subkey=[key, 'color'],
                                 value=tuple(color.GetColour()))
        # display
        UserSettings.Set(group='vdigit', key="lineWidth", subkey='value',
                         value=int(self.lineWidthValue.GetValue()))

        # snapping
        UserSettings.Set(group='vdigit', key="snapping", subkey='value',
                         value=int(self.snappingValue.GetValue()))
        UserSettings.Set(group='vdigit', key="snapping", subkey='unit',
                         value=self.snappingUnit.GetSelection())
        UserSettings.Set(group='vdigit', key="snapToVertex", subkey='enabled',
                         value=self.snapVertex.IsChecked())

        # digitize new feature
        UserSettings.Set(group='vdigit', key="addRecord", subkey='enabled',
                         value=self.addRecord.IsChecked())
        UserSettings.Set(group='vdigit', key="layer", subkey='value',
                         value=int(self.layer.GetValue()))
        UserSettings.Set(group='vdigit', key="category", subkey='value',
                         value=int(self.category.GetValue()))
        UserSettings.Set(
            group='vdigit',
            key="categoryMode",
            subkey='selection',
            value=self.categoryMode.GetSelection())

        # delete existing feature
        UserSettings.Set(group='vdigit', key="delRecord", subkey='enabled',
                         value=self.deleteRecord.IsChecked())

        # geometry attributes (workspace)
        mapLayer = self.parent.toolbars['vdigit'].GetLayer()
        tree = self._giface.GetLayerTree()
        if tree:
            item = tree.FindItemByData('maplayer', mapLayer)
        else:
            item = None
        for key, val in six.iteritems(self.geomAttrb):
            checked = self.FindWindowById(val['check']).IsChecked()
            column = self.FindWindowById(val['column']).GetValue()
            unitsIdx = self.FindWindowById(val['units']).GetSelection()
            if item and not tree.GetLayerInfo(item, key='vdigit'):
                tree.SetLayerInfo(
                    item, key='vdigit', value={
                        'geomAttr': dict()})

            if checked:  # enable
                if key == 'area':
                    type = key
                else:
                    type = 'length'
                unitsKey = Units.GetUnitsKey(type, unitsIdx)
                tree.GetLayerInfo(item, key='vdigit')['geomAttr'][key] = {
                    'column': column, 'units': unitsKey}
            else:
                if item and tree.GetLayerInfo(
                        item, key='vdigit') and key in tree.GetLayerInfo(
                        item, key='vdigit')['geomAttr']:
                    del tree.GetLayerInfo(item, key='vdigit')['geomAttr'][key]

        # query tool
        if self.queryLength.GetValue():
            UserSettings.Set(group='vdigit', key="query", subkey='selection',
                             value=0)
        else:
            UserSettings.Set(group='vdigit', key="query", subkey='type',
                             value=1)
        UserSettings.Set(group='vdigit', key="query", subkey='box',
                         value=self.queryBox.IsChecked())
        UserSettings.Set(
            group='vdigit',
            key="queryLength",
            subkey='than-selection',
            value=self.queryLengthSL.GetSelection())
        UserSettings.Set(group='vdigit', key="queryLength", subkey='thresh',
                         value=int(self.queryLengthValue.GetValue()))
        UserSettings.Set(
            group='vdigit',
            key="queryDangle",
            subkey='than-selection',
            value=self.queryDangleSL.GetSelection())
        UserSettings.Set(group='vdigit', key="queryDangle", subkey='thresh',
                         value=int(self.queryDangleValue.GetValue()))

        # select features
        for feature in ('point', 'line',
                        'centroid', 'boundary'):
            UserSettings.Set(
                group='vdigit', key='selectType', subkey=[
                    feature, 'enabled'], value=self.FindWindowById(
                    self.selectFeature[feature]).IsChecked())
        UserSettings.Set(group='vdigit', key="selectThresh", subkey='value',
                         value=int(self.selectThreshValue.GetValue()))
        UserSettings.Set(group='vdigit', key="checkForDupl", subkey='enabled',
                         value=self.checkForDupl.IsChecked())
        UserSettings.Set(group='vdigit', key="selectInside", subkey='enabled',
                         value=self.selectIn.IsChecked())

        # on-exit
        UserSettings.Set(group='vdigit', key="saveOnExit", subkey='enabled',
                         value=self.save.IsChecked())

        # break lines
        UserSettings.Set(group='vdigit', key="breakLines", subkey='enabled',
                         value=self.intersect.IsChecked())

        # close boundary
        UserSettings.Set(group='vdigit', key="closeBoundary", subkey='enabled',
                         value=self.closeBoundary.IsChecked())

        self.digit.UpdateSettings()

        # redraw map if auto-rendering is enabled
        if self.parent.IsAutoRendered():
            self.parent.OnRender(None)
コード例 #13
0
    def _createGeneralPage(self, notebook):
        """Create notebook page concerning general settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("General"))

        border = wx.BoxSizer(wx.VERTICAL)

        #
        # display section
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Display"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        # line width
        text = StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width"))
        self.lineWidthValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='value'),
            min=1, max=1e6)
        units = StaticText(
            parent=panel, id=wx.ID_ANY, size=(115, -1),
            label=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='units'),
            style=wx.ALIGN_LEFT)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.lineWidthValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            units,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
            border=10)

        sizer.Add(
            flexSizer,
            proportion=1,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        #
        # snapping section
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Snapping"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)

        # snapping
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Snapping threshold"))
        self.snappingValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="snapping", subkey='value'),
            min=-1, max=1e6)
        self.snappingValue.Bind(wx.EVT_SPINCTRL, self.OnChangeSnappingValue)
        self.snappingValue.Bind(wx.EVT_TEXT, self.OnChangeSnappingValue)
        self.snappingUnit = wx.Choice(parent=panel, id=wx.ID_ANY, size=(
            125, -1), choices=[_("screen pixels"), _("map units")])
        try:
            self.snappingUnit.SetSelection(UserSettings.Get(group='vdigit',
                                                            key="snapping",
                                                            subkey='unit'))
        except:
            self.snappingUnit.SetSelection(0)
        self.snappingUnit.Bind(wx.EVT_CHOICE, self.OnChangeSnappingUnits)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(
            self.snappingValue,
            proportion=0,
            flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            self.snappingUnit,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)

        vertexSizer = wx.BoxSizer(wx.VERTICAL)
        self.snapVertex = CheckBox(parent=panel, id=wx.ID_ANY,
                                   label=_("Snap also to vertex"))
        self.snapVertex.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="snapToVertex",
                subkey='enabled'))
        vertexSizer.Add(self.snapVertex, proportion=0, flag=wx.EXPAND)
        self.mapUnits = self.parent.MapWindow.Map.GetProjInfo()['units']
        self.snappingInfo = StaticText(
            parent=panel, id=wx.ID_ANY,
            label=_("Snapping threshold is %(value).1f %(units)s") %
            {'value': self.digit.GetDisplay().GetThreshold(),
             'units': self.mapUnits})
        vertexSizer.Add(self.snappingInfo, proportion=0,
                        flag=wx.ALL | wx.EXPAND, border=1)

        sizer.Add(flexSizer, proportion=1, flag=wx.EXPAND)
        sizer.Add(vertexSizer, proportion=1, flag=wx.EXPAND)
        border.Add(sizer, proportion=0, flag=wx.LEFT |
                   wx.RIGHT | wx.BOTTOM | wx.EXPAND, border=5)

        #
        # select box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Select vector features"))
        # feature type
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        inSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.selectFeature = {}
        for feature in ('point', 'line',
                        'centroid', 'boundary'):
            chkbox = CheckBox(parent=panel, label=feature)
            self.selectFeature[feature] = chkbox.GetId()
            chkbox.SetValue(UserSettings.Get(group='vdigit', key='selectType',
                                             subkey=[feature, 'enabled']))
            inSizer.Add(chkbox, proportion=0,
                        flag=wx.EXPAND | wx.ALL, border=5)
        sizer.Add(inSizer, proportion=0, flag=wx.EXPAND)
        # threshold
        flexSizer = wx.FlexGridSizer(cols=3, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)
        text = StaticText(
            parent=panel,
            id=wx.ID_ANY,
            label=_("Select threshold"))
        self.selectThreshValue = SpinCtrl(
            parent=panel, id=wx.ID_ANY, size=(75, -1),
            initial=UserSettings.Get(
                group='vdigit', key="selectThresh", subkey='value'),
            min=1, max=1e6)
        units = StaticText(
            parent=panel, id=wx.ID_ANY, size=(115, -1),
            label=UserSettings.Get(
                group='vdigit', key="lineWidth", subkey='units'),
            style=wx.ALIGN_LEFT)
        flexSizer.Add(text, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.selectThreshValue, proportion=0,
                      flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)
        flexSizer.Add(
            units,
            proportion=0,
            flag=wx.ALIGN_RIGHT | wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
            border=10)

        self.selectIn = CheckBox(parent=panel, id=wx.ID_ANY, label=_(
            "Select only features inside of selection bounding box"))
        self.selectIn.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="selectInside",
                subkey='enabled'))
        self.selectIn.SetToolTip(
            _("By default are selected all features overlapping selection bounding box "))

        self.checkForDupl = CheckBox(parent=panel, id=wx.ID_ANY,
                                     label=_("Check for duplicates"))
        self.checkForDupl.SetValue(
            UserSettings.Get(
                group='vdigit',
                key="checkForDupl",
                subkey='enabled'))

        sizer.Add(flexSizer, proportion=0, flag=wx.EXPAND)
        sizer.Add(
            self.selectIn,
            proportion=0,
            flag=wx.EXPAND | wx.ALL,
            border=1)
        sizer.Add(
            self.checkForDupl,
            proportion=0,
            flag=wx.EXPAND | wx.ALL,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # digitize lines box
        #
        box = StaticBox(
            parent=panel, id=wx.ID_ANY, label=" %s " %
            _("Digitize lines/boundaries"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        self.intersect = CheckBox(
            parent=panel, label=_("Break lines at intersection"))
        self.intersect.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='breakLines',
                subkey='enabled'))

        sizer.Add(
            self.intersect,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # digitize areas box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Digitize areas"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        self.closeBoundary = CheckBox(
            parent=panel, label=_("Close boundary (snap to the start node)"))
        self.closeBoundary.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='closeBoundary',
                subkey='enabled'))

        sizer.Add(
            self.closeBoundary,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)

        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        #
        # save-on-exit box
        #
        box = StaticBox(
            parent=panel,
            id=wx.ID_ANY,
            label=" %s " %
            _("Save changes"))
        # save changes on exit?
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        self.save = CheckBox(parent=panel, label=_("Save changes on exit"))
        self.save.SetValue(
            UserSettings.Get(
                group='vdigit',
                key='saveOnExit',
                subkey='enabled'))
        sizer.Add(
            self.save,
            proportion=0,
            flag=wx.ALL | wx.EXPAND,
            border=1)
        border.Add(sizer, proportion=0, flag=wx.EXPAND |
                   wx.LEFT | wx.RIGHT | wx.BOTTOM, border=5)

        panel.SetSizer(border)

        return panel
コード例 #14
0
ファイル: frame.py プロジェクト: xtistosm/grass-ci
    def _layout(self):
        """Creates the main panel with all the controls on it:
             * mpl canvas
             * mpl navigation toolbar
             * Control panel for interaction
        """
        self.panel = wx.Panel(self)

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        # color =  wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
        self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
        self.canvas = FigCanvas(self.panel, wx.ID_ANY, self.fig)
        # axes are initialized later
        self.axes2d = None
        self.axes3d = None

        # Create the navigation toolbar, tied to the canvas
        #
        self.toolbar = NavigationToolbar(self.canvas)

        #
        # Layout
        #

        self.vbox = wx.BoxSizer(wx.VERTICAL)
        self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
        self.vbox.Add(self.toolbar, 0, wx.EXPAND)
        self.vbox.AddSpacer(10)

        gridSizer = wx.GridBagSizer(hgap=5, vgap=5)

        self.datasetSelect = gselect.Select(parent=self.panel,
                                            id=wx.ID_ANY,
                                            size=globalvar.DIALOG_GSELECT_SIZE,
                                            type='stds',
                                            multiple=True)
        self.drawButton = Button(self.panel, id=wx.ID_ANY, label=_("Draw"))
        self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
        self.helpButton = Button(self.panel, id=wx.ID_ANY, label=_("Help"))
        self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
        self.view3dCheck = wx.CheckBox(
            self.panel,
            id=wx.ID_ANY,
            label=_("3D plot of spatio-temporal extents"))
        self.view3dCheck.Bind(wx.EVT_CHECKBOX, self.OnRedraw)
        if not check_version(1, 0, 0):
            self.view3dCheck.SetLabel(
                _("3D plot of spatio-temporal extents "
                  "(matplotlib >= 1.0.0)"))
            self.view3dCheck.Disable()

        gridSizer.Add(StaticText(self.panel,
                                 id=wx.ID_ANY,
                                 label=_("Select space time dataset(s):")),
                      pos=(0, 0),
                      flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
        gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND)
        gridSizer.Add(self.drawButton, pos=(1, 1), flag=wx.EXPAND)
        gridSizer.Add(self.helpButton, pos=(1, 2), flag=wx.EXPAND)
        gridSizer.Add(self.view3dCheck,
                      pos=(2, 0),
                      flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)

        self.vbox.Add(gridSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL,
                      border=10)

        self.panel.SetSizer(self.vbox)
        self.vbox.Fit(self)
コード例 #15
0
ファイル: preferences.py プロジェクト: petrasovaa/grass
    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
コード例 #16
0
    def _createCommentPage(self, notebook):
        """Create notebook page for comment settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)
        notebook.AddPage(page=panel, text=_("Comment"))

        # colors
        border = wx.BoxSizer(wx.VERTICAL)
        box = StaticBox(parent=panel, id=wx.ID_ANY, label=" %s " % _("Color"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

        row = 0
        gridSizer.Add(
            StaticText(parent=panel, id=wx.ID_ANY, label=_("Valid:")),
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
            pos=(row, 0),
        )
        vColor = csel.ColourSelect(
            parent=panel,
            id=wx.ID_ANY,
            colour=self.settings.Get(group="modeler",
                                     key="comment",
                                     subkey="color"),
            size=globalvar.DIALOG_COLOR_SIZE,
        )
        vColor.SetName("GetColour")
        self.winId["modeler:comment:color"] = vColor.GetId()

        gridSizer.Add(vColor,
                      flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        # size
        box = StaticBox(parent=panel,
                        id=wx.ID_ANY,
                        label=" %s " % _("Shape size"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)

        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

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

        width = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            min=0,
            max=500,
            initial=self.settings.Get(group="modeler",
                                      key="comment",
                                      subkey=("size", "width")),
        )
        width.SetName("GetValue")
        self.winId["modeler:comment:size:width"] = width.GetId()

        gridSizer.Add(width,
                      flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        height = SpinCtrl(
            parent=panel,
            id=wx.ID_ANY,
            min=0,
            max=500,
            initial=self.settings.Get(group="modeler",
                                      key="comment",
                                      subkey=("size", "height")),
        )
        height.SetName("GetValue")
        self.winId["modeler:comment:size:height"] = height.GetId()

        gridSizer.Add(height,
                      flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 1))

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

        panel.SetSizer(border)

        return panel
コード例 #17
0
ファイル: preferences.py プロジェクト: petrasovaa/grass
    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
コード例 #18
0
    def _layout(self):
        metaSizer = wx.StaticBoxSizer(self.metaBox, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
        gridSizer.Add(
            StaticText(parent=self, id=wx.ID_ANY, label=_("Name:")),
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
            pos=(0, 0),
        )
        gridSizer.Add(
            self.name,
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
            pos=(0, 1),
        )
        gridSizer.Add(
            StaticText(parent=self, id=wx.ID_ANY, label=_("Description:")),
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
            pos=(1, 0),
        )
        gridSizer.Add(
            self.desc,
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
            pos=(1, 1),
        )
        gridSizer.Add(
            StaticText(parent=self, id=wx.ID_ANY, label=_("Author(s):")),
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
            pos=(2, 0),
        )
        gridSizer.Add(
            self.author,
            flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
            pos=(2, 1),
        )
        gridSizer.AddGrowableCol(1)
        gridSizer.AddGrowableRow(1)
        metaSizer.Add(gridSizer, proportion=1, flag=wx.EXPAND)

        cmdSizer = wx.StaticBoxSizer(self.cmdBox, wx.VERTICAL)
        cmdSizer.Add(self.overwrite, flag=wx.EXPAND | wx.ALL, border=3)

        btnStdSizer = wx.StdDialogButtonSizer()
        btnStdSizer.AddButton(self.btnCancel)
        btnStdSizer.AddButton(self.btnOk)
        btnStdSizer.Realize()

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(metaSizer,
                      proportion=1,
                      flag=wx.EXPAND | wx.ALL,
                      border=5)
        mainSizer.Add(
            cmdSizer,
            proportion=0,
            flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
            border=5,
        )
        mainSizer.Add(btnStdSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL,
                      border=5)

        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
コード例 #19
0
ファイル: query.py プロジェクト: petrasovaa/grass
    def __init__(self, parent, data=None):
        wx.Dialog.__init__(self,
                           parent,
                           id=wx.ID_ANY,
                           title=_("Query results"),
                           size=(420, 400),
                           style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        # send query output to console
        self.redirectOutput = Signal('QueryDialog.redirectOutput')

        self.data = data

        self.panel = wx.Panel(self, id=wx.ID_ANY)
        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        helpText = StaticText(
            self.panel,
            wx.ID_ANY,
            label=_("Right click to copy selected values to clipboard."))
        helpText.SetForegroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))
        self.mainSizer.Add(helpText, proportion=0, flag=wx.ALL, border=5)

        self._colNames = [_("Feature"), _("Value")]
        self._model = QueryTreeBuilder(self.data, column=self._colNames[1])
        self.tree = TreeListView(model=self._model,
                                 parent=self.panel,
                                 columns=self._colNames,
                                 style=wx.TR_DEFAULT_STYLE | wx.TR_HIDE_ROOT
                                 | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_MULTIPLE)

        self.tree.SetColumnWidth(0, 220)
        self.tree.SetColumnWidth(1, 1000)
        self.tree.ExpandAll(self._model.root)
        self.tree.RefreshItems()
        self.tree.contextMenu.connect(self.ShowContextMenu)
        self.mainSizer.Add(self.tree,
                           proportion=1,
                           flag=wx.EXPAND | wx.ALL,
                           border=5)

        close = Button(self.panel, id=wx.ID_CLOSE)
        close.Bind(wx.EVT_BUTTON, lambda event: self.Close())
        copy = Button(self.panel,
                      id=wx.ID_ANY,
                      label=_("Copy all to clipboard"))
        copy.Bind(wx.EVT_BUTTON, self.Copy)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.redirect = wx.CheckBox(self.panel, label=_("Redirect to console"))
        self.redirect.SetValue(False)
        self.redirect.Bind(wx.EVT_CHECKBOX,
                           lambda evt: self._onRedirect(evt.IsChecked()))

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.redirect,
                 proportion=0,
                 flag=wx.EXPAND | wx.RIGHT,
                 border=5)
        hbox.AddStretchSpacer(1)
        hbox.Add(copy, proportion=0, flag=wx.EXPAND | wx.RIGHT, border=5)
        hbox.Add(close, proportion=0, flag=wx.EXPAND | wx.ALL, border=0)

        self.mainSizer.Add(hbox,
                           proportion=0,
                           flag=wx.EXPAND | wx.ALL,
                           border=5)
        self.panel.SetSizer(self.mainSizer)
        self.mainSizer.Fit(self.panel)
        # for Windows
        self.SendSizeEvent()
コード例 #20
0
class VDigitCategoryDialog(wx.Dialog, listmix.ColumnSorterMixin):
    def __init__(self,
                 parent,
                 title,
                 vectorName,
                 query=None,
                 cats=None,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                 **kwargs):
        """Dialog used to display/modify categories of vector objects

        :param parent:
        :param title: dialog title
        :param query: {coordinates, qdist} - used by v.edit/v.what
        :param cats: directory of lines (layer/categories) - used by vdigit
        :param style: dialog style
        """
        self.parent = parent  # map window class instance
        self.digit = parent.digit

        # map name
        self.vectorName = vectorName

        # line : {layer: [categories]}
        self.cats = {}

        # do not display dialog if no line is found (-> self.cats)
        if cats is None:
            if self._getCategories(query[0], query[1]) == 0 or not self.line:
                Debug.msg(3, "VDigitCategoryDialog(): nothing found!")
        else:
            self.cats = cats
            for line in cats.keys():
                for layer in cats[line].keys():
                    self.cats[line][layer] = list(cats[line][layer])

            layers = []
            for layer in self.digit.GetLayers():
                layers.append(str(layer))

        # make copy of cats (used for 'reload')
        self.cats_orig = copy.deepcopy(self.cats)

        wx.Dialog.__init__(self,
                           parent=self.parent,
                           id=wx.ID_ANY,
                           title=title,
                           style=style,
                           **kwargs)

        # list of categories
        box = StaticBox(parent=self,
                        id=wx.ID_ANY,
                        label=" %s " %
                        _("List of categories - right-click to delete"))
        listSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        self.list = CategoryListCtrl(parent=self,
                                     id=wx.ID_ANY,
                                     style=wx.LC_REPORT | wx.BORDER_NONE
                                     | wx.LC_SORT_ASCENDING | wx.LC_HRULES
                                     | wx.LC_VRULES)
        # sorter
        self.fid = list(self.cats.keys())[0]
        self.itemDataMap = self.list.Populate(self.cats[self.fid])
        listmix.ColumnSorterMixin.__init__(self, 2)
        self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY, size=(150, -1))
        self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
        self.fidText = StaticText(parent=self, id=wx.ID_ANY)
        if len(self.cats.keys()) == 1:
            self.fidMulti.Show(False)
            self.fidText.SetLabel(str(self.fid))
        else:
            self.fidText.Show(False)
            choices = []
            for fid in self.cats.keys():
                choices.append(str(fid))
            self.fidMulti.SetItems(choices)
            self.fidMulti.SetSelection(0)

        listSizer.Add(self.list, proportion=1, flag=wx.EXPAND)

        # add new category
        box = StaticBox(parent=self,
                        id=wx.ID_ANY,
                        label=" %s " % _("Add new category"))
        addSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=5, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(3)

        layerNewTxt = StaticText(parent=self,
                                 id=wx.ID_ANY,
                                 label="%s:" % _("Layer"))
        self.layerNew = wx.Choice(parent=self,
                                  id=wx.ID_ANY,
                                  size=(75, -1),
                                  choices=layers)
        if len(layers) > 0:
            self.layerNew.SetSelection(0)

        catNewTxt = StaticText(parent=self,
                               id=wx.ID_ANY,
                               label="%s:" % _("Category"))

        try:
            newCat = max(self.cats[self.fid][1]) + 1
        except KeyError:
            newCat = 1
        self.catNew = SpinCtrl(parent=self,
                               id=wx.ID_ANY,
                               size=(75, -1),
                               initial=newCat,
                               min=0,
                               max=1e9)
        btnAddCat = Button(self, wx.ID_ADD)
        flexSizer.Add(layerNewTxt,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.layerNew,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(catNewTxt,
                      proportion=0,
                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
                      border=10)
        flexSizer.Add(self.catNew,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(btnAddCat,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
        addSizer.Add(flexSizer,
                     proportion=1,
                     flag=wx.ALL | wx.EXPAND,
                     border=5)

        # buttons
        btnApply = Button(self, wx.ID_APPLY)
        btnApply.SetToolTip(_("Apply changes"))
        btnCancel = Button(self, wx.ID_CANCEL)
        btnCancel.SetToolTip(_("Ignore changes and close dialog"))
        btnOk = Button(self, wx.ID_OK)
        btnOk.SetToolTip(_("Apply changes and close dialog"))
        btnOk.SetDefault()

        # sizers
        btnSizer = wx.StdDialogButtonSizer()
        btnSizer.AddButton(btnCancel)
        # btnSizer.AddButton(btnReload)
        # btnSizer.SetNegativeButton(btnReload)
        btnSizer.AddButton(btnApply)
        btnSizer.AddButton(btnOk)
        btnSizer.Realize()

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(listSizer,
                      proportion=1,
                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                      border=5)
        mainSizer.Add(addSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT
                      | wx.BOTTOM,
                      border=5)
        fidSizer = wx.BoxSizer(wx.HORIZONTAL)
        fidSizer.Add(StaticText(parent=self,
                                id=wx.ID_ANY,
                                label=_("Feature id:")),
                     proportion=0,
                     border=5,
                     flag=wx.ALIGN_CENTER_VERTICAL)
        fidSizer.Add(self.fidMulti,
                     proportion=0,
                     flag=wx.EXPAND | wx.ALL,
                     border=5)
        fidSizer.Add(self.fidText,
                     proportion=0,
                     flag=wx.EXPAND | wx.ALL,
                     border=5)
        mainSizer.Add(fidSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL,
                      border=5)
        mainSizer.Add(btnSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                      border=5)

        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
        self.SetAutoLayout(True)

        # set min size for dialog
        self.SetMinSize(self.GetBestSize())

        # bindings
        btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
        btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
        btnAddCat.Bind(wx.EVT_BUTTON, self.OnAddCat)
        btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
        self.Bind(wx.EVT_CLOSE, lambda evt: self.Hide())

        # list
        self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp)  # wxMSW
        self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)  # wxGTK
        self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
        self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit, self.list)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)

    def GetListCtrl(self):
        """Used by ColumnSorterMixin
        """
        return self.list

    def OnColClick(self, event):
        """Click on column header (order by)
        """
        event.Skip()

    def OnBeginEdit(self, event):
        """Editing of item started
        """
        event.Allow()

    def OnEndEdit(self, event):
        """Finish editing of item
        """
        itemIndex = event.GetIndex()
        layerOld = int(self.list.GetItem(itemIndex, 0).GetText())
        catOld = int(self.list.GetItem(itemIndex, 1).GetText())

        if event.GetColumn() == 0:
            layerNew = int(event.GetLabel())
            catNew = catOld
        else:
            layerNew = layerOld
            catNew = int(event.GetLabel())

        try:
            if layerNew not in self.cats[self.fid].keys():
                self.cats[self.fid][layerNew] = []
            self.cats[self.fid][layerNew].append(catNew)
            self.cats[self.fid][layerOld].remove(catOld)
        except:
            event.Veto()
            self.list.SetStringItem(itemIndex, 0, str(layerNew))
            self.list.SetStringItem(itemIndex, 1, str(catNew))
            dlg = wx.MessageDialog(
                self,
                _("Unable to add new layer/category <%(layer)s/%(category)s>.\n"
                  "Layer and category number must be integer.\n"
                  "Layer number must be greater than zero.") % {
                      'layer': self.layerNew.GetStringSelection(),
                      'category': str(self.catNew.GetValue())
                  }, _("Error"), wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()
            return False

    def OnRightDown(self, event):
        """Mouse right button down
        """
        x = event.GetX()
        y = event.GetY()
        item, flags = self.list.HitTest((x, y))

        if item !=  wx.NOT_FOUND and \
                flags & wx.LIST_HITTEST_ONITEM:
            self.list.Select(item)

        event.Skip()

    def OnRightUp(self, event):
        """Mouse right button up
        """
        if not hasattr(self, "popupID1"):
            self.popupID1 = NewId()
            self.popupID2 = NewId()
            self.popupID3 = NewId()
            self.Bind(wx.EVT_MENU, self.OnItemDelete, id=self.popupID1)
            self.Bind(wx.EVT_MENU, self.OnItemDeleteAll, id=self.popupID2)
            self.Bind(wx.EVT_MENU, self.OnReload, id=self.popupID3)

        # generate popup-menu
        menu = Menu()
        menu.Append(self.popupID1, _("Delete selected"))
        if self.list.GetFirstSelected() == -1:
            menu.Enable(self.popupID1, False)

        menu.Append(self.popupID2, _("Delete all"))
        menu.AppendSeparator()
        menu.Append(self.popupID3, _("Reload"))

        self.PopupMenu(menu)
        menu.Destroy()

    def OnItemSelected(self, event):
        """Item selected
        """
        event.Skip()

    def OnItemDelete(self, event):
        """Delete selected item(s) from the list (layer/category pair)
        """
        item = self.list.GetFirstSelected()
        while item != -1:
            layer = int(self.list.GetItem(item, 0).GetText())
            cat = int(self.list.GetItem(item, 1).GetText())
            self.list.DeleteItem(item)
            self.cats[self.fid][layer].remove(cat)

            item = self.list.GetFirstSelected()

        event.Skip()

    def OnItemDeleteAll(self, event):
        """Delete all items from the list
        """
        self.list.DeleteAllItems()
        self.cats[self.fid] = {}

        event.Skip()

    def OnFeature(self, event):
        """Feature id changed (on duplicates)
        """
        self.fid = int(event.GetString())

        self.itemDataMap = self.list.Populate(self.cats[self.fid], update=True)

        try:
            newCat = max(self.cats[self.fid][1]) + 1
        except KeyError:
            newCat = 1

        self.catNew.SetValue(newCat)

        event.Skip()

    def _getCategories(self, coords, qdist):
        """Get layer/category pairs for all available
        layers

        :return: True line found or False if not found
        """
        ret = RunCommand('v.what',
                         parent=self,
                         quiet=True,
                         map=self.vectorName,
                         east_north='%f,%f' %
                         (float(coords[0]), float(coords[1])),
                         distance=qdist)

        if not ret:
            return False

        for item in ret.splitlines():
            litem = item.lower()
            if "id:" in litem:  # get line id
                self.line = int(item.split(':')[1].strip())
            elif "layer:" in litem:  # add layer
                layer = int(item.split(':')[1].strip())
                if layer not in self.cats.keys():
                    self.cats[layer] = []
            elif "category:" in litem:  # add category
                self.cats[layer].append(int(item.split(':')[1].strip()))

        return True

    def OnReload(self, event):
        """Reload button pressed
        """
        # restore original list
        self.cats = copy.deepcopy(self.cats_orig)

        # polulate list
        self.itemDataMap = self.list.Populate(self.cats[self.fid], update=True)

        event.Skip()

    def OnCancel(self, event):
        """Cancel button pressed
        """
        self.parent.parent.dialogs['category'] = None
        if self.digit:
            self.digit.GetDisplay().SetSelected([])
            self.parent.UpdateMap(render=False)
        else:
            self.parent.parent.OnRender(None)

        self.Close()

    def OnApply(self, event):
        """Apply button pressed
        """
        for fid in self.cats.keys():
            newfid = self.ApplyChanges(fid)
            if fid == self.fid and newfid > 0:
                self.fid = newfid

    def ApplyChanges(self, fid):
        """Apply changes

        :param fid: feature id
        """
        cats = self.cats[fid]
        cats_orig = self.cats_orig[fid]

        # action : (catsFrom, catsTo)
        check = {'catadd': (cats, cats_orig), 'catdel': (cats_orig, cats)}

        newfid = -1

        # add/delete new category
        for action, catsCurr in six.iteritems(check):
            for layer in catsCurr[0].keys():
                catList = []
                for cat in catsCurr[0][layer]:
                    if layer not in catsCurr[1].keys() or \
                            cat not in catsCurr[1][layer]:
                        catList.append(cat)
                if catList != []:
                    if action == 'catadd':
                        add = True
                    else:
                        add = False

                    newfid = self.digit.SetLineCats(fid, layer, catList, add)
                    if len(self.cats.keys()) == 1:
                        self.fidText.SetLabel("%d" % newfid)
                    else:
                        choices = self.fidMulti.GetItems()
                        choices[choices.index(str(fid))] = str(newfid)
                        self.fidMulti.SetItems(choices)
                        self.fidMulti.SetStringSelection(str(newfid))

                    self.cats[newfid] = self.cats[fid]
                    del self.cats[fid]

                    fid = newfid
                    if self.fid < 0:
                        wx.MessageBox(
                            parent=self,
                            message=_("Unable to update vector map."),
                            caption=_("Error"),
                            style=wx.OK | wx.ICON_ERROR)

        self.cats_orig[fid] = copy.deepcopy(cats)

        return newfid

    def OnOK(self, event):
        """OK button pressed
        """
        self.OnApply(event)
        self.OnCancel(event)

    def OnAddCat(self, event):
        """Button 'Add' new category pressed
        """
        try:
            layer = int(self.layerNew.GetStringSelection())
            cat = int(self.catNew.GetValue())
            if layer <= 0:
                raise ValueError
        except ValueError:
            GError(
                parent=self,
                message=
                _("Unable to add new layer/category <%(layer)s/%(category)s>.\n"
                  "Layer and category number must be integer.\n"
                  "Layer number must be greater than zero.") % {
                      'layer': str(self.layerNew.GetValue()),
                      'category': str(self.catNew.GetValue())
                  })
            return False

        if layer not in self.cats[self.fid].keys():
            self.cats[self.fid][layer] = []

        self.cats[self.fid][layer].append(cat)

        # reload list
        self.itemDataMap = self.list.Populate(self.cats[self.fid], update=True)

        # update category number for add
        self.catNew.SetValue(cat + 1)

        event.Skip()

        return True

    def GetLine(self):
        """Get id of selected line of 'None' if no line is selected
        """
        return self.cats.keys()

    def UpdateDialog(self, query=None, cats=None):
        """Update dialog

        :param query: {coordinates, distance} - v.what
        :param cats:  directory layer/cats    - vdigit
        :return: True if updated otherwise False
        """
        # line: {layer: [categories]}
        self.cats = {}
        # do not display dialog if no line is found (-> self.cats)
        if cats is None:
            ret = self._getCategories(query[0], query[1])
        else:
            self.cats = cats
            for line in cats.keys():
                for layer in cats[line].keys():
                    self.cats[line][layer] = list(cats[line][layer])
            ret = 1
        if ret == 0 or len(self.cats.keys()) < 1:
            Debug.msg(3, "VDigitCategoryDialog(): nothing found!")
            return False

        # make copy of cats (used for 'reload')
        self.cats_orig = copy.deepcopy(self.cats)

        # polulate list
        self.fid = list(self.cats.keys())[0]
        self.itemDataMap = self.list.Populate(self.cats[self.fid], update=True)

        try:
            newCat = max(self.cats[self.fid][1]) + 1
        except KeyError:
            newCat = 1
        self.catNew.SetValue(newCat)

        if len(self.cats.keys()) == 1:
            self.fidText.Show(True)
            self.fidMulti.Show(False)
            self.fidText.SetLabel("%d" % self.fid)
        else:
            self.fidText.Show(False)
            self.fidMulti.Show(True)
            choices = []
            for fid in self.cats.keys():
                choices.append(str(fid))
            self.fidMulti.SetItems(choices)
            self.fidMulti.SetSelection(0)

        self.Layout()

        return True
コード例 #21
0
ファイル: dialogs.py プロジェクト: anikaweinmann/grass-ci
    def _createWidgets(self):

        self.labels = {}
        self.params = {}

        self.labels['output'] = StaticText(
            parent=self, id=wx.ID_ANY, label=_("Name for output raster map:"))

        self.params['output'] = Select(parent=self,
                                       type='raster',
                                       mapsets=[grass.gisenv()['MAPSET']],
                                       size=globalvar.DIALOG_GSELECT_SIZE)

        self.regionStBoxLabel = StaticBox(parent=self,
                                          id=wx.ID_ANY,
                                          label=" %s " % _("Export region"))

        self.region_types_order = ['display', 'comp', 'named']
        self.region_types = {}
        self.region_types['display'] = wx.RadioButton(parent=self,
                                                      label=_("Map display"),
                                                      style=wx.RB_GROUP)
        self.region_types['comp'] = wx.RadioButton(
            parent=self, label=_("Computational region"))
        self.region_types['named'] = wx.RadioButton(parent=self,
                                                    label=_("Named region"))
        self.region_types['display'].SetToolTipString(
            _("Extent and resolution"
              " are based on Map Display geometry."))
        self.region_types['comp'].SetToolTipString(
            _("Extent and resolution"
              " are based on computational region."))
        self.region_types['named'].SetToolTipString(
            _("Extent and resolution"
              " are based on named region."))
        self.region_types['display'].SetValue(
            True)  # set default as map display

        self.overwrite = wx.CheckBox(parent=self,
                                     id=wx.ID_ANY,
                                     label=_("Overwrite existing raster map"))

        self.named_reg_panel = wx.Panel(parent=self, id=wx.ID_ANY)
        self.labels['region'] = StaticText(parent=self.named_reg_panel,
                                           id=wx.ID_ANY,
                                           label=_("Choose named region:"))

        self.params['region'] = Select(parent=self.named_reg_panel,
                                       type='region',
                                       size=globalvar.DIALOG_GSELECT_SIZE)

        # buttons
        self.btn_close = Button(parent=self, id=wx.ID_CLOSE)
        self.SetEscapeId(self.btn_close.GetId())
        self.btn_close.SetToolTip(_("Close dialog"))

        self.btn_ok = Button(parent=self, label=_("&Save layer"))
        self.btn_ok.SetToolTip(_("Save web service layer as raster map"))

        # statusbar
        self.statusbar = wx.StatusBar(parent=self, id=wx.ID_ANY)

        self._layout()
コード例 #22
0
    def __init__(self,
                 parent,
                 title,
                 vectorName,
                 query=None,
                 cats=None,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
                 **kwargs):
        """Dialog used to display/modify categories of vector objects

        :param parent:
        :param title: dialog title
        :param query: {coordinates, qdist} - used by v.edit/v.what
        :param cats: directory of lines (layer/categories) - used by vdigit
        :param style: dialog style
        """
        self.parent = parent  # map window class instance
        self.digit = parent.digit

        # map name
        self.vectorName = vectorName

        # line : {layer: [categories]}
        self.cats = {}

        # do not display dialog if no line is found (-> self.cats)
        if cats is None:
            if self._getCategories(query[0], query[1]) == 0 or not self.line:
                Debug.msg(3, "VDigitCategoryDialog(): nothing found!")
        else:
            self.cats = cats
            for line in cats.keys():
                for layer in cats[line].keys():
                    self.cats[line][layer] = list(cats[line][layer])

            layers = []
            for layer in self.digit.GetLayers():
                layers.append(str(layer))

        # make copy of cats (used for 'reload')
        self.cats_orig = copy.deepcopy(self.cats)

        wx.Dialog.__init__(self,
                           parent=self.parent,
                           id=wx.ID_ANY,
                           title=title,
                           style=style,
                           **kwargs)

        # list of categories
        box = StaticBox(parent=self,
                        id=wx.ID_ANY,
                        label=" %s " %
                        _("List of categories - right-click to delete"))
        listSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        self.list = CategoryListCtrl(parent=self,
                                     id=wx.ID_ANY,
                                     style=wx.LC_REPORT | wx.BORDER_NONE
                                     | wx.LC_SORT_ASCENDING | wx.LC_HRULES
                                     | wx.LC_VRULES)
        # sorter
        self.fid = list(self.cats.keys())[0]
        self.itemDataMap = self.list.Populate(self.cats[self.fid])
        listmix.ColumnSorterMixin.__init__(self, 2)
        self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY, size=(150, -1))
        self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
        self.fidText = StaticText(parent=self, id=wx.ID_ANY)
        if len(self.cats.keys()) == 1:
            self.fidMulti.Show(False)
            self.fidText.SetLabel(str(self.fid))
        else:
            self.fidText.Show(False)
            choices = []
            for fid in self.cats.keys():
                choices.append(str(fid))
            self.fidMulti.SetItems(choices)
            self.fidMulti.SetSelection(0)

        listSizer.Add(self.list, proportion=1, flag=wx.EXPAND)

        # add new category
        box = StaticBox(parent=self,
                        id=wx.ID_ANY,
                        label=" %s " % _("Add new category"))
        addSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=5, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(3)

        layerNewTxt = StaticText(parent=self,
                                 id=wx.ID_ANY,
                                 label="%s:" % _("Layer"))
        self.layerNew = wx.Choice(parent=self,
                                  id=wx.ID_ANY,
                                  size=(75, -1),
                                  choices=layers)
        if len(layers) > 0:
            self.layerNew.SetSelection(0)

        catNewTxt = StaticText(parent=self,
                               id=wx.ID_ANY,
                               label="%s:" % _("Category"))

        try:
            newCat = max(self.cats[self.fid][1]) + 1
        except KeyError:
            newCat = 1
        self.catNew = SpinCtrl(parent=self,
                               id=wx.ID_ANY,
                               size=(75, -1),
                               initial=newCat,
                               min=0,
                               max=1e9)
        btnAddCat = Button(self, wx.ID_ADD)
        flexSizer.Add(layerNewTxt,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.layerNew,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(catNewTxt,
                      proportion=0,
                      flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
                      border=10)
        flexSizer.Add(self.catNew,
                      proportion=0,
                      flag=wx.FIXED_MINSIZE | wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(btnAddCat,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALIGN_RIGHT | wx.FIXED_MINSIZE)
        addSizer.Add(flexSizer,
                     proportion=1,
                     flag=wx.ALL | wx.EXPAND,
                     border=5)

        # buttons
        btnApply = Button(self, wx.ID_APPLY)
        btnApply.SetToolTip(_("Apply changes"))
        btnCancel = Button(self, wx.ID_CANCEL)
        btnCancel.SetToolTip(_("Ignore changes and close dialog"))
        btnOk = Button(self, wx.ID_OK)
        btnOk.SetToolTip(_("Apply changes and close dialog"))
        btnOk.SetDefault()

        # sizers
        btnSizer = wx.StdDialogButtonSizer()
        btnSizer.AddButton(btnCancel)
        # btnSizer.AddButton(btnReload)
        # btnSizer.SetNegativeButton(btnReload)
        btnSizer.AddButton(btnApply)
        btnSizer.AddButton(btnOk)
        btnSizer.Realize()

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(listSizer,
                      proportion=1,
                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                      border=5)
        mainSizer.Add(addSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT
                      | wx.BOTTOM,
                      border=5)
        fidSizer = wx.BoxSizer(wx.HORIZONTAL)
        fidSizer.Add(StaticText(parent=self,
                                id=wx.ID_ANY,
                                label=_("Feature id:")),
                     proportion=0,
                     border=5,
                     flag=wx.ALIGN_CENTER_VERTICAL)
        fidSizer.Add(self.fidMulti,
                     proportion=0,
                     flag=wx.EXPAND | wx.ALL,
                     border=5)
        fidSizer.Add(self.fidText,
                     proportion=0,
                     flag=wx.EXPAND | wx.ALL,
                     border=5)
        mainSizer.Add(fidSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL,
                      border=5)
        mainSizer.Add(btnSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                      border=5)

        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
        self.SetAutoLayout(True)

        # set min size for dialog
        self.SetMinSize(self.GetBestSize())

        # bindings
        btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
        btnOk.Bind(wx.EVT_BUTTON, self.OnOK)
        btnAddCat.Bind(wx.EVT_BUTTON, self.OnAddCat)
        btnCancel.Bind(wx.EVT_BUTTON, self.OnCancel)
        self.Bind(wx.EVT_CLOSE, lambda evt: self.Hide())

        # list
        self.list.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightUp)  # wxMSW
        self.list.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)  # wxGTK
        self.Bind(wx.EVT_LIST_BEGIN_LABEL_EDIT, self.OnBeginEdit, self.list)
        self.Bind(wx.EVT_LIST_END_LABEL_EDIT, self.OnEndEdit, self.list)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)
コード例 #23
0
    def _advancedSettsPage(self):
        """Create advanced settings page
        """
        # TODO parse maxcol, maxrow, settings from d.wms module?
        # TODO OnEarth driver - add selection of time
        adv_setts_panel = ScrolledPanel(parent=self,
                                        id=wx.ID_ANY,
                                        style=wx.TAB_TRAVERSAL
                                        | wx.SUNKEN_BORDER)
        self.notebook.AddPage(page=adv_setts_panel,
                              text=_('Advanced request settings'),
                              name='adv_req_setts')

        labels = {}
        self.l_odrder_list = None
        if 'WMS' in self.ws:
            labels['l_order'] = StaticBox(parent=adv_setts_panel,
                                          id=wx.ID_ANY,
                                          label=_("Order of layers in raster"))
            self.l_odrder_list = wx.ListBox(adv_setts_panel,
                                            id=wx.ID_ANY,
                                            choices=[],
                                            style=wx.LB_SINGLE
                                            | wx.LB_NEEDED_SB)
            self.btnUp = Button(adv_setts_panel, id=wx.ID_ANY, label=_("Up"))
            self.btnDown = Button(adv_setts_panel,
                                  id=wx.ID_ANY,
                                  label=_("Down"))

            self.btnUp.Bind(wx.EVT_BUTTON, self.OnUp)
            self.btnDown.Bind(wx.EVT_BUTTON, self.OnDown)

        labels['method'] = StaticText(parent=adv_setts_panel,
                                      id=wx.ID_ANY,
                                      label=_("Reprojection method:"))

        self.reproj_methods = ['nearest', 'linear', 'cubic', 'cubicspline']
        self.params['method'] = wx.Choice(parent=adv_setts_panel,
                                          id=wx.ID_ANY,
                                          choices=[
                                              _('Nearest neighbor'),
                                              _('Linear interpolation'),
                                              _('Cubic interpolation'),
                                              _('Cubic spline interpolation')
                                          ])

        labels['maxcols'] = StaticText(
            parent=adv_setts_panel,
            id=wx.ID_ANY,
            label=_("Maximum columns to request from server at time:"))
        self.params['maxcols'] = SpinCtrl(parent=adv_setts_panel,
                                          id=wx.ID_ANY,
                                          size=(100, -1))

        labels['maxrows'] = StaticText(
            parent=adv_setts_panel,
            id=wx.ID_ANY,
            label=_("Maximum rows to request from server at time:"))
        self.params['maxrows'] = SpinCtrl(parent=adv_setts_panel,
                                          id=wx.ID_ANY,
                                          size=(100, -1))

        min = 100
        max = 10000
        self.params['maxcols'].SetRange(min, max)
        self.params['maxrows'].SetRange(min, max)

        val = 500
        self.params['maxcols'].SetValue(val)
        self.params['maxrows'].SetValue(val)

        self.flags['o'] = self.params['bgcolor'] = None
        if 'o' not in self.drv_props['ignored_flags']:
            self.flags['o'] = wx.CheckBox(
                parent=adv_setts_panel,
                id=wx.ID_ANY,
                label=_("Do not request transparent data"))

            self.flags['o'].Bind(wx.EVT_CHECKBOX, self.OnTransparent)
            labels['bgcolor'] = StaticText(parent=adv_setts_panel,
                                           id=wx.ID_ANY,
                                           label=_("Background color:"))
            self.params['bgcolor'] = csel.ColourSelect(
                parent=adv_setts_panel,
                id=wx.ID_ANY,
                colour=(255, 255, 255),
                size=globalvar.DIALOG_COLOR_SIZE)
            self.params['bgcolor'].Enable(False)

        self.params['urlparams'] = None
        if self.params['urlparams'] not in self.drv_props['ignored_params']:
            labels['urlparams'] = StaticText(
                parent=adv_setts_panel,
                id=wx.ID_ANY,
                label=_("Additional query parameters for server:"))
            self.params['urlparams'] = TextCtrl(parent=adv_setts_panel,
                                                id=wx.ID_ANY)

        # layout

        border = wx.BoxSizer(wx.VERTICAL)

        if 'WMS' in self.ws:

            boxSizer = wx.StaticBoxSizer(labels['l_order'], wx.VERTICAL)
            gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

            gridSizer.Add(self.l_odrder_list,
                          pos=(0, 0),
                          span=(4, 1),
                          flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
                          border=0)

            gridSizer.Add(self.btnUp,
                          pos=(0, 1),
                          flag=wx.ALIGN_CENTER_VERTICAL,
                          border=0)

            gridSizer.Add(self.btnDown,
                          pos=(1, 1),
                          flag=wx.ALIGN_CENTER_VERTICAL,
                          border=0)

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

            border.Add(boxSizer,
                       flag=wx.LEFT | wx.RIGHT | wx.UP | wx.EXPAND,
                       border=5)

        gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

        row = 0
        for k in ['method', 'maxcols', 'maxrows', 'o', 'bgcolor']:

            if k in self.params:
                param = self.params[k]
            elif k in self.flags:
                param = self.flags[k]

            if param is None:
                continue

            if k in labels or k == 'o':
                if k != 'o':
                    label = labels[k]
                else:
                    label = param

                gridSizer.Add(label,
                              flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
                              pos=(row, 0))

            if k != 'o':
                gridSizer.Add(param,
                              flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL,
                              pos=(row, 1))
            row += 1

        gridSizer.AddGrowableCol(0)
        border.Add(gridSizer,
                   flag=wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
                   border=5)

        if self.params['urlparams']:
            gridSizer = wx.GridBagSizer(hgap=3, vgap=3)

            row = 0
            gridSizer.Add(labels['urlparams'],
                          flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
                          pos=(row, 0))

            gridSizer.Add(self.params['urlparams'],
                          flag=wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL
                          | wx.EXPAND,
                          pos=(row, 1))

            gridSizer.AddGrowableCol(1)

            border.Add(gridSizer,
                       flag=wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
                       border=5)

        adv_setts_panel.SetSizer(border)
        adv_setts_panel.SetAutoLayout(True)
        adv_setts_panel.SetupScrolling()
コード例 #24
0
    def __init__(self,
                 parent,
                 title,
                 nselected,
                 style=wx.DEFAULT_DIALOG_STYLE):
        """Dialog used for Z bulk-labeling tool
        """
        wx.Dialog.__init__(self,
                           parent=parent,
                           id=wx.ID_ANY,
                           title=title,
                           style=style)

        self.parent = parent  # map window class instance

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

        border = wx.BoxSizer(wx.VERTICAL)

        txt = StaticText(parent=self,
                         label=_("%d lines selected for z bulk-labeling") %
                         nselected)
        border.Add(txt, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)

        box = StaticBox(parent=self,
                        id=wx.ID_ANY,
                        label=" %s " % _("Set value"))
        sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        flexSizer.AddGrowableCol(0)

        # starting value
        txt = StaticText(parent=self, label=_("Starting value"))
        self.value = SpinCtrl(parent=self,
                              id=wx.ID_ANY,
                              size=(150, -1),
                              initial=0,
                              min=-1e6,
                              max=1e6)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.value,
                      proportion=0,
                      flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)

        # step
        txt = StaticText(parent=self, label=_("Step"))
        self.step = SpinCtrl(parent=self,
                             id=wx.ID_ANY,
                             size=(150, -1),
                             initial=0,
                             min=0,
                             max=1e6)
        flexSizer.Add(txt, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        flexSizer.Add(self.step,
                      proportion=0,
                      flag=wx.ALIGN_CENTER | wx.FIXED_MINSIZE)

        sizer.Add(flexSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=1)
        border.Add(sizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=0)

        # buttons
        btnCancel = Button(self, wx.ID_CANCEL)
        btnOk = Button(self, wx.ID_OK)
        btnOk.SetDefault()

        # sizers
        btnSizer = wx.StdDialogButtonSizer()
        btnSizer.AddButton(btnCancel)
        btnSizer.AddButton(btnOk)
        btnSizer.Realize()

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(border, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        mainSizer.Add(btnSizer,
                      proportion=0,
                      flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                      border=5)

        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
コード例 #25
0
    def __init__(self,
                 parent,
                 handlerObj,
                 giface,
                 model,
                 id=wx.ID_ANY,
                 **kwargs):
        self.parent = parent
        self._handlerObj = handlerObj
        self._giface = giface

        self.showNotification = Signal('SearchModuleWindow.showNotification')
        wx.Panel.__init__(self, parent=parent, id=id, **kwargs)

        # tree
        self._tree = CTreeView(model=model, parent=self)
        self._tree.SetToolTip(
            _("Double-click or Ctrl-Enter to run selected module"))

        #        self._dataBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
        #                                     label = " %s " % _("Module tree"))

        # search widget
        self._search = SearchModuleWidget(parent=self,
                                          model=model,
                                          showChoice=False)
        self._search.showSearchResult.connect(
            lambda result: self._tree.Select(result))
        self._search.showNotification.connect(self.showNotification)

        self._helpText = StaticText(
            parent=self,
            id=wx.ID_ANY,
            label="Press Enter for next match, Ctrl+Enter to run command")
        self._helpText.SetForegroundColour(
            wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        # buttons
        self._btnRun = Button(self, id=wx.ID_OK, label=_("&Run"))
        self._btnRun.SetToolTip(_("Run selected module from the tree"))
        self._btnHelp = Button(self, id=wx.ID_ANY, label=_("H&elp"))
        self._btnHelp.SetToolTip(
            _("Show manual for selected module from the tree"))
        self._btnAdvancedSearch = Button(self,
                                         id=wx.ID_ANY,
                                         label=_("Adva&nced search..."))
        self._btnAdvancedSearch.SetToolTip(
            _("Do advanced search using %s module") % 'g.search.module')

        # bindings
        self._btnRun.Bind(wx.EVT_BUTTON, lambda evt: self.Run())
        self._btnHelp.Bind(wx.EVT_BUTTON, lambda evt: self.Help())
        self._btnAdvancedSearch.Bind(wx.EVT_BUTTON,
                                     lambda evt: self.AdvancedSearch())
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self._tree.selectionChanged.connect(self.OnItemSelected)
        self._tree.itemActivated.connect(lambda node: self.Run(node))

        self._layout()

        self._search.SetFocus()
コード例 #26
0
ファイル: preferences.py プロジェクト: petrasovaa/grass
    def _createFlyPage(self, notebook):
        """Create notebook page for view settings"""
        panel = wx.Panel(parent=notebook, id=wx.ID_ANY)

        notebook.AddPage(page=panel, text=" %s " % _("Fly-through"))
        pageSizer = wx.BoxSizer(wx.VERTICAL)
        # fly throuhg mode
        box = StaticBox(parent=panel,
                        id=wx.ID_ANY,
                        label=" %s " % (_("Fly-through mode")))
        boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=3, hgap=3)

        # move exag
        gridSizer.Add(StaticText(parent=panel,
                                 id=wx.ID_ANY,
                                 label=_("Move exag:")),
                      pos=(0, 0),
                      flag=wx.ALIGN_CENTER_VERTICAL)

        moveExag = SpinCtrl(panel,
                            id=wx.ID_ANY,
                            min=1,
                            max=20,
                            initial=UserSettings.Get(group='nviz',
                                                     key='fly',
                                                     subkey=['exag', 'move']),
                            size=(65, -1))
        self.winId['nviz:fly:exag:move'] = moveExag.GetId()
        gridSizer.Add(moveExag, pos=(0, 1))

        # turn exag
        gridSizer.Add(StaticText(parent=panel,
                                 id=wx.ID_ANY,
                                 label=_("Turn exag:")),
                      pos=(1, 0),
                      flag=wx.ALIGN_CENTER_VERTICAL)

        turnExag = SpinCtrl(panel,
                            id=wx.ID_ANY,
                            min=1,
                            max=20,
                            initial=UserSettings.Get(group='nviz',
                                                     key='fly',
                                                     subkey=['exag', 'turn']),
                            size=(65, -1))
        self.winId['nviz:fly:exag:turn'] = turnExag.GetId()
        gridSizer.Add(turnExag, pos=(1, 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
コード例 #27
0
    def __init__(self, parent, giface, controller, toolSwitcher):
        """RDigit toolbar constructor
        """
        BaseToolbar.__init__(self, parent, toolSwitcher)
        self._controller = controller
        self._giface = giface
        self.InitToolbar(self._toolbarData())

        self._mapSelectionCombo = wx.ComboBox(self,
                                              id=wx.ID_ANY,
                                              value=_("Select raster map"),
                                              choices=[],
                                              size=(120, -1))
        self._mapSelectionCombo.Bind(wx.EVT_COMBOBOX, self.OnMapSelection)
        self._mapSelectionCombo.SetEditable(False)
        self.InsertControl(0, self._mapSelectionCombo)
        self._previousMap = self._mapSelectionCombo.GetValue()

        self._color = ColourSelect(parent=self, colour=wx.GREEN, size=(30, 30))
        self._color.Bind(csel.EVT_COLOURSELECT,
                         lambda evt: self._changeDrawColor())
        self._color.SetToolTip(_("Set drawing color (not raster cell color)"))
        self.InsertControl(4, self._color)

        self._cellValues = set(['1'])
        # validator does not work with combobox, SetBackgroundColor is not
        # working
        self._valueCombo = wx.ComboBox(self,
                                       id=wx.ID_ANY,
                                       choices=list(self._cellValues),
                                       size=(80, -1),
                                       validator=FloatValidator())
        self._valueCombo.Bind(wx.EVT_COMBOBOX,
                              lambda evt: self._cellValueChanged())
        self._valueCombo.Bind(wx.EVT_TEXT,
                              lambda evt: self._cellValueChanged())
        self._valueCombo.SetSelection(0)
        self._cellValueChanged()
        labelValue = StaticText(self, label=" %s" % _("Cell value:"))
        self.InsertControl(6, labelValue)
        self.InsertControl(7, self._valueCombo)

        # validator does not work with combobox, SetBackgroundColor is not
        # working
        self._widthValue = TextCtrl(self,
                                    id=wx.ID_ANY,
                                    value='0',
                                    size=(80, -1),
                                    validator=FloatValidator())
        self._widthValue.Bind(wx.EVT_TEXT,
                              lambda evt: self._widthValueChanged())
        self._widthValueChanged()
        self._widthValue.SetToolTip(
            _("Width of currently digitized line or diameter of a digitized point in map units."
              ))
        labelWidth = StaticText(self, label=" %s" % _("Width:"))
        self.InsertControl(8, labelWidth)
        self.InsertControl(9, self._widthValue)

        for tool in (self.area, self.line, self.point):
            self.toolSwitcher.AddToolToGroup(group='mouseUse',
                                             toolbar=self,
                                             tool=tool)
        self.toolSwitcher.toggleToolChanged.connect(self.CheckSelectedTool)
        self._default = self.area
        # realize the toolbar
        self.Realize()
        # workaround Mac bug
        for t in (self._mapSelectionCombo, self._color, self._valueCombo,
                  self._widthValue, labelValue, labelWidth):
            t.Hide()
            t.Show()
コード例 #28
0
ファイル: preferences.py プロジェクト: petrasovaa/grass
    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
コード例 #29
0
    def __init__(self,
                 parent,
                 id,
                 title,
                 scatt_mgr,
                 pos=wx.DefaultPosition,
                 size=wx.DefaultSize,
                 style=wx.DEFAULT_DIALOG_STYLE):
        """Settings dialog"""
        wx.Dialog.__init__(self, parent, id, title, pos, size, style)

        self.scatt_mgr = scatt_mgr

        maxValue = 1e8
        self.parent = parent
        self.settings = {}

        settsLabels = {}

        self.settings["show_ellips"] = wx.CheckBox(
            parent=self, id=wx.ID_ANY, label=_('Show confidence ellipses'))
        show_ellips = UserSettings.Get(group='scatt',
                                       key="ellipses",
                                       subkey="show_ellips")
        self.settings["show_ellips"].SetValue(show_ellips)

        self.colorsSetts = {
            "sel_pol": ["selection",
                        _("Selection polygon color:")],
            "sel_pol_vertex":
            ["selection", _("Color of selection polygon vertex:")],
            "sel_area": ["selection", _("Selected area color:")]
        }

        for settKey, sett in six.iteritems(self.colorsSetts):
            settsLabels[settKey] = StaticText(parent=self,
                                              id=wx.ID_ANY,
                                              label=sett[1])
            col = UserSettings.Get(group='scatt', key=sett[0], subkey=settKey)
            self.settings[settKey] = csel.ColourSelect(parent=self,
                                                       id=wx.ID_ANY,
                                                       colour=wx.Colour(
                                                           col[0], col[1],
                                                           col[2], 255))

        self.sizeSetts = {
            "snap_tresh": ["selection",
                           _("Snapping threshold in pixels:")],
            "sel_area_opacty": ["selection",
                                _("Selected area opacity:")]
        }

        for settKey, sett in six.iteritems(self.sizeSetts):
            settsLabels[settKey] = StaticText(parent=self,
                                              id=wx.ID_ANY,
                                              label=sett[1])
            self.settings[settKey] = SpinCtrl(parent=self,
                                              id=wx.ID_ANY,
                                              min=0,
                                              max=100)
            size = int(
                UserSettings.Get(group='scatt', key=sett[0], subkey=settKey))
            self.settings[settKey].SetValue(size)

        # buttons
        self.btnSave = Button(self, wx.ID_SAVE)
        self.btnApply = Button(self, wx.ID_APPLY)
        self.btnClose = Button(self, wx.ID_CLOSE)
        self.btnApply.SetDefault()

        # bindings
        self.btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
        self.btnApply.SetToolTip(_("Apply changes for the current session"))
        self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
        self.btnSave.SetToolTip(
            _("Apply and save changes to user settings file (default for next sessions)"
              ))
        self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
        self.btnClose.SetToolTip(_("Close dialog"))

        # Layout

        # Analysis result style layout
        self.SetMinSize(self.GetBestSize())

        sizer = wx.BoxSizer(wx.VERTICAL)

        sel_pol_box = StaticBox(parent=self,
                                id=wx.ID_ANY,
                                label=" %s " % _("Selection style:"))
        selPolBoxSizer = wx.StaticBoxSizer(sel_pol_box, wx.VERTICAL)

        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)

        row = 0
        setts = dict()
        setts.update(self.colorsSetts)
        setts.update(self.sizeSetts)

        settsOrder = [
            "sel_pol", "sel_pol_vertex", "sel_area", "sel_area_opacty",
            "snap_tresh"
        ]
        for settKey in settsOrder:
            sett = setts[settKey]
            gridSizer.Add(settsLabels[settKey],
                          flag=wx.ALIGN_CENTER_VERTICAL,
                          pos=(row, 0))
            gridSizer.Add(self.settings[settKey],
                          flag=wx.ALIGN_RIGHT | wx.ALL,
                          border=5,
                          pos=(row, 1))
            row += 1

        gridSizer.AddGrowableCol(1)
        selPolBoxSizer.Add(gridSizer, flag=wx.EXPAND)

        ell_box = StaticBox(parent=self,
                            id=wx.ID_ANY,
                            label=" %s " % _("Ellipses settings:"))
        ellPolBoxSizer = wx.StaticBoxSizer(ell_box, wx.VERTICAL)
        gridSizer = wx.GridBagSizer(vgap=1, hgap=1)

        sett = setts[settKey]

        row = 0
        gridSizer.Add(self.settings["show_ellips"],
                      flag=wx.ALIGN_CENTER_VERTICAL,
                      pos=(row, 0))

        gridSizer.AddGrowableCol(0)
        ellPolBoxSizer.Add(gridSizer, flag=wx.EXPAND)

        btnSizer = wx.BoxSizer(wx.HORIZONTAL)
        btnSizer.Add(self.btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
        btnSizer.Add(self.btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
        btnSizer.Add(self.btnClose, flag=wx.LEFT | wx.RIGHT, border=5)

        sizer.Add(selPolBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
        sizer.Add(ellPolBoxSizer, flag=wx.EXPAND | wx.ALL, border=5)
        sizer.Add(btnSizer, flag=wx.EXPAND | wx.ALL, border=5, proportion=0)

        self.SetSizer(sizer)
        sizer.Fit(self)
コード例 #30
0
ファイル: dialogs.py プロジェクト: xtistosm/grass-ci
    def __layout(self):
        """Do layout"""
        sizer = wx.BoxSizer(wx.VERTICAL)

        dataSizer = wx.BoxSizer(wx.VERTICAL)

        dataSizer.Add(StaticText(parent=self.panel,
                                 id=wx.ID_ANY,
                                 label=_("Enter name of signature file:")),
                      proportion=0,
                      flag=wx.ALL,
                      border=3)
        self.fileNameCtrl = TextCtrl(parent=self.panel,
                                     id=wx.ID_ANY,
                                     size=(400, -1))
        if self.fileName:
            self.fileNameCtrl.SetValue(self.fileName)
        dataSizer.Add(self.fileNameCtrl,
                      proportion=0,
                      flag=wx.ALL | wx.EXPAND,
                      border=3)

        dataSizer.Add(StaticText(parent=self.panel,
                                 id=wx.ID_ANY,
                                 label=_("Signature file path:")),
                      proportion=0,
                      flag=wx.ALL,
                      border=3)

        self.pathPanel = scrolled.ScrolledPanel(self.panel, size=(-1, 40))
        pathSizer = wx.BoxSizer()
        self.filePathText = StaticText(parent=self.pathPanel,
                                       id=wx.ID_ANY,
                                       label=self.baseFilePath)
        pathSizer.Add(self.filePathText,
                      proportion=1,
                      flag=wx.ALL | wx.EXPAND,
                      border=1)
        self.pathPanel.SetupScrolling(scroll_x=True, scroll_y=False)
        self.pathPanel.SetSizer(pathSizer)

        dataSizer.Add(self.pathPanel,
                      proportion=0,
                      flag=wx.ALL | wx.EXPAND,
                      border=3)

        # buttons
        btnSizer = wx.StdDialogButtonSizer()
        btnSizer.AddButton(self.btnCancel)
        btnSizer.AddButton(self.btnOK)
        btnSizer.Realize()

        sizer.Add(dataSizer,
                  proportion=1,
                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                  border=5)

        sizer.Add(btnSizer,
                  proportion=0,
                  flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
                  border=5)

        self.panel.SetSizer(sizer)
        sizer.Fit(self)

        self.SetMinSize(self.GetSize())