Exemplo n.º 1
0
class ReprojectionDialog(wx.Dialog):
    """ """
    def __init__(self,
                 parent,
                 giface,
                 data,
                 id=wx.ID_ANY,
                 title=_("Reprojection"),
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
        self.parent = parent  # GMFrame
        self._giface = giface  # used to add layers

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

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

        # list of layers
        columns = [_('Layer id'), _('Name for output GRASS map')]

        self.layerBox = StaticBox(parent=self.panel, id=wx.ID_ANY)
        self.layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)

        self.list = GListCtrl(parent=self.panel)

        for i in range(len(columns)):
            self.list.InsertColumn(i, columns[i])

        width = (65, 180)

        for i in range(len(width)):
            self.list.SetColumnWidth(col=i, width=width[i])

        self.list.LoadData(data)
        self.list.SelectAll(True)

        self.labelText = StaticText(
            parent=self.panel,
            id=wx.ID_ANY,
            label=
            _("Projection of following layers do not match with projection of current location. "
              ))

        label = _("Layers to be reprojected")
        self.layerBox.SetLabel(" %s - %s " %
                               (label, _("right click to (un)select all")))

        #
        # buttons
        #
        # cancel
        self.btn_close = Button(parent=self.panel, id=wx.ID_CANCEL)

        # run
        self.btn_run = Button(parent=self.panel,
                              id=wx.ID_OK,
                              label=_("&Import && reproject"))
        self.btn_run.SetToolTip(_("Reproject selected layers"))
        self.btn_run.SetDefault()

        self.doLayout()

    def doLayout(self):
        """Do layout"""
        dialogSizer = wx.BoxSizer(wx.VERTICAL)

        dialogSizer.Add(self.labelText, flag=wx.ALL | wx.EXPAND, border=5)

        self.layerSizer.Add(self.list,
                            proportion=1,
                            flag=wx.ALL | wx.EXPAND,
                            border=5)

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

        #
        # buttons
        #
        btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)

        btnsizer.Add(self.btn_close,
                     proportion=0,
                     flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
                     border=10)

        btnsizer.Add(self.btn_run,
                     proportion=0,
                     flag=wx.RIGHT | wx.ALIGN_CENTER,
                     border=10)

        dialogSizer.Add(btnsizer,
                        proportion=0,
                        flag=wx.BOTTOM | wx.ALIGN_RIGHT,
                        border=10)

        self.panel.SetSizer(dialogSizer)
        dialogSizer.Fit(self.panel)

        self.Layout()

    def GetData(self, checked):

        return self.list.GetData(checked)
Exemplo n.º 2
0
    def __init__(self,
                 parent,
                 title,
                 data,
                 keyEditable=(-1, True),
                 id=wx.ID_ANY,
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
        """Dialog for inserting/updating table record

        :param data: a list: [(column, value)]
        :param keyEditable: (id, editable?) indicates if textarea for
                            key column is editable(True) or not
        """
        # parent -> VDigitWindow
        wx.Dialog.__init__(self, parent, id, title, style=style)

        self.CenterOnParent()

        self.keyId = keyEditable[0]

        box = StaticBox(parent=self, id=wx.ID_ANY)
        box.Hide()
        self.dataPanel = scrolled.ScrolledPanel(parent=self,
                                                id=wx.ID_ANY,
                                                style=wx.TAB_TRAVERSAL)
        self.dataPanel.SetupScrolling(scroll_x=False)

        # buttons
        self.btnCancel = Button(self, wx.ID_CANCEL)
        self.btnSubmit = Button(self, wx.ID_OK, _("&Submit"))
        self.btnSubmit.SetDefault()

        # data area
        self.widgets = []
        cId = 0
        self.usebox = False
        self.cat = None
        winFocus = False

        for column, ctype, ctypeStr, value in data:
            if self.keyId == cId:
                self.cat = int(value)
                if not keyEditable[1]:
                    self.usebox = True
                    box.SetLabel(" %s %d " % (_("Category"), self.cat))
                    box.Show()
                    self.boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
                    cId += 1
                    continue
                else:
                    valueWin = SpinCtrl(parent=self.dataPanel,
                                        id=wx.ID_ANY,
                                        value=value,
                                        min=-1e9,
                                        max=1e9,
                                        size=(250, -1))
            else:
                valueWin = TextCtrl(parent=self.dataPanel,
                                    id=wx.ID_ANY,
                                    value=value,
                                    size=(250, -1))
                if ctype == int:
                    valueWin.SetValidator(IntegerValidator())
                elif ctype == float:
                    valueWin.SetValidator(FloatValidator())
                if not winFocus:
                    wx.CallAfter(valueWin.SetFocus)
                    winFocus = True

            label = StaticText(parent=self.dataPanel,
                               id=wx.ID_ANY,
                               label=column)
            ctype = StaticText(parent=self.dataPanel,
                               id=wx.ID_ANY,
                               label="[%s]:" % ctypeStr.lower())
            self.widgets.append(
                (label.GetId(), ctype.GetId(), valueWin.GetId()))

            cId += 1

        self._layout()
Exemplo n.º 3
0
class ImportDialog(wx.Dialog):
    """Dialog for bulk import of various data (base class)"""
    def __init__(self,
                 parent,
                 giface,
                 itype,
                 id=wx.ID_ANY,
                 title=_("Multiple import"),
                 style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
        self.parent = parent  # GMFrame
        self._giface = giface  # used to add layers
        self.importType = itype
        self.options = dict()  # list of options
        self.options_par = dict()

        self.commandId = -1  # id of running command

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

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

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

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

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

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

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

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

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

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

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

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

        self.createSettingsPage()

    def createSettingsPage(self):

        self._blackList = {
            'enabled': True,
            'items': {
                self._getCommand(): {
                    'params': self._getBlackListedParameters(),
                    'flags': self._getBlackListedFlags()
                }
            }
        }

        grass_task = gtask.parse_interface(self._getCommand(),
                                           blackList=self._blackList)

        self.advancedPagePanel = CmdPanel(parent=self,
                                          giface=None,
                                          task=grass_task,
                                          frame=None)

        self.notebook.AddPage(page=self.advancedPagePanel,
                              text=_('Import settings'),
                              name='settings')

    def doLayout(self):
        """Do layout"""
        dialogSizer = wx.BoxSizer(wx.VERTICAL)

        # dsn input
        dialogSizer.Add(self.dsnInput, proportion=0, flag=wx.EXPAND)

        #
        # list of DXF layers
        #
        layerSizer = wx.StaticBoxSizer(self.layerBox, wx.HORIZONTAL)

        layerSizer.Add(self.list,
                       proportion=1,
                       flag=wx.ALL | wx.EXPAND,
                       border=5)

        dialogSizer.Add(layerSizer,
                        proportion=1,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
                        border=5)

        dialogSizer.Add(self.override,
                        proportion=0,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
                        border=5)

        dialogSizer.Add(self.overwrite,
                        proportion=0,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
                        border=5)

        dialogSizer.Add(self.add,
                        proportion=0,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
                        border=5)

        dialogSizer.Add(self.closeOnFinish,
                        proportion=0,
                        flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
                        border=5)
        #
        # buttons
        #
        btnsizer = wx.BoxSizer(orient=wx.HORIZONTAL)

        btnsizer.Add(self.btn_close,
                     proportion=0,
                     flag=wx.LEFT | wx.RIGHT | wx.ALIGN_CENTER,
                     border=10)

        btnsizer.Add(self.btn_run,
                     proportion=0,
                     flag=wx.RIGHT | wx.ALIGN_CENTER,
                     border=10)

        dialogSizer.Add(btnsizer,
                        proportion=0,
                        flag=wx.BOTTOM | wx.ALIGN_RIGHT,
                        border=10)

        # dialogSizer.SetSizeHints(self.panel)
        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(dialogSizer)
        dialogSizer.Fit(self.panel)

        # auto-layout seems not work here - FIXME
        size = wx.Size(globalvar.DIALOG_GSELECT_SIZE[0] + 322, 550)
        self.SetMinSize(size)
        self.SetSize((size.width, size.height + 100))
        # width = self.GetSize()[0]
        # self.list.SetColumnWidth(col = 1, width = width / 2 - 50)
        self.Layout()

    def _getCommand(self):
        """Get command"""
        raise NotImplementedError()

    def _getBlackListedParameters(self):
        """Get parameters which will not be showed in Settings page"""
        raise NotImplementedError()

    def _getBlackListedFlags(self):
        """Get flags which will not be showed in Settings page"""
        raise NotImplementedError()

    def _nameValidationFailed(self, layers_list):
        """Output map name validation callback

        :param layers_list: LayersList class instance
        """
        if isinstance(layers_list.output_map, list):
            maps = ['<{}>'.format(m) for m in layers_list.output_map]
            message = _("Output map names %(names)s exist. ") % {
                'names': ', '.join(maps)
            }
        else:
            message = _("Output map name <%(name)s> exist. ") % {
                'name': layers_list.output_map
            }
        GError(parent=self, message=message, caption=_("Invalid name"))

    def _validateOutputMapName(self):
        """Enable/disable output map name validation according the
        overwrite state"""
        if not self.overwrite.IsChecked():
            if not self.list.GetValidator().\
               Validate(win=self.list, validate_all=True):
                return False
        return True

    def OnClose(self, event=None):
        """Close dialog"""
        self.Close()

    def OnRun(self, event):
        """Import/Link data (each layes as separate vector map)"""
        pass

    def OnCheckOverwrite(self, event):
        """Check/uncheck overwrite checkbox widget"""
        if self.overwrite.IsChecked():
            self.list.validate = False
        else:
            self.list.validate = True

    def AddLayers(self, returncode, cmd=None, userData=None):
        """Add imported/linked layers into layer tree"""
        if not self.add.IsChecked() or returncode != 0:
            return

        # TODO: if importing map creates more map the following does not work
        # * do nothing if map does not exist or
        # * try to determine names using regexp or
        # * persuade import tools to report map names
        self.commandId += 1
        layer, output = self.list.GetLayers()[self.commandId][:2]

        if '@' not in output:
            name = output + '@' + grass.gisenv()['MAPSET']
        else:
            name = output

        # add imported layers into layer tree
        # an alternative would be emit signal (mapCreated) and (optionally)
        # connect to this signal
        llist = self._giface.GetLayerList()
        if self.importType == 'gdal':
            if userData:
                nBands = int(userData.get('nbands', 1))
            else:
                nBands = 1

            if UserSettings.Get(group='rasterLayer',
                                key='opaque',
                                subkey='enabled'):
                nFlag = True
            else:
                nFlag = False

            for i in range(1, nBands + 1):
                nameOrig = name
                if nBands > 1:
                    mapName, mapsetName = name.split('@')
                    mapName += '.%d' % i
                    name = mapName + '@' + mapsetName

                cmd = ['d.rast', 'map=%s' % name]
                if nFlag:
                    cmd.append('-n')

                llist.AddLayer(ltype='raster',
                               name=name,
                               checked=True,
                               cmd=cmd)
                name = nameOrig
        else:
            llist.AddLayer(ltype='vector',
                           name=name,
                           checked=True,
                           cmd=['d.vect', 'map=%s' % name] +
                           GetDisplayVectSettings())

        self._giface.GetMapWindow().ZoomToMap()

    def OnAbort(self, event):
        """Abort running import

        .. todo::
            not yet implemented
        """
        pass

    def OnCmdDone(self, event):
        """Do what has to be done after importing"""
        pass

    def _getLayersToReprojetion(self, projMatch_idx, grassName_idx):
        """If there are layers with different projection from loation projection,
           show dialog to user to explicitly select layers which will be reprojected..."""
        differentProjLayers = []
        data = self.list.GetData(checked=True)

        for itm in data:

            layerId = itm[-1]

            # select only layers with different projetion
            if self.layersData[layerId][projMatch_idx] == 0:
                dt = [itm[0], itm[grassName_idx]]
                differentProjLayers.append(tuple(dt))

        layers = self.list.GetLayers()

        if not self.link and \
           differentProjLayers and \
           not self.override.IsChecked(): # '-o' not in self.getSettingsPageCmd():

            dlg = ReprojectionDialog(parent=self,
                                     giface=self._giface,
                                     data=differentProjLayers)

            ret = dlg.ShowModal()

            if ret == wx.ID_OK:

                # do not import unchecked layers
                for itm in reversed(list(dlg.GetData(checked=False))):
                    idx = itm[-1]
                    layers.pop(idx)
            else:
                return None

        return layers

    def getSettingsPageCmd(self):

        return self.advancedPagePanel.createCmd(ignoreErrors=True,
                                                ignoreRequired=True)