Ejemplo n.º 1
0
    def publishPgTable(self, tree, explorer):
        if not xmlNameIsValid(self.element.name, xmlNameRegex()):
            QtGui.QMessageBox.warning(explorer, "Invalid name",
                                      ("The table name (%s) is not a valid XML name.\n"
                                      + "This could cause problems when published to GeoServer.\n"
                                      + "Please rename it and retry publishing.") % self.element.name)
            return
        dlg = PublishLayerDialog(explorer.catalogs(), self.element)
        dlg.exec_()
        if dlg.catalog is None:
            return
        cat = dlg.catalog
        catItem = tree.findFirstItem(cat)
        toUpdate = [catItem]
        if int(self.element.srid) == 0:
            explorer.setWarning("PostGIS table '{0}' has no SRID; ESPG:4326 "
                                "will be assigned.".format(self.element.name))
        if explorer.run(publishTable,
                        "Publish table '" + self.element.name + "'",
                        toUpdate,
                        self.element, cat, dlg.workspace, True, dlg.layername):

            # add existing style to layer, or later some operations may fail,
            # like malformed XML when getting capabilities for OWS connections
            pglyr = cat.get_layer(dlg.layername)
            pgitem = tree.findFirstItem(pglyr)
            if pgitem is None:
                return
            if not pgitem.addStyleToLayer(explorer):  # handles refresh of item
                # user cancelled AddStyleToLayerDialog
                noDefaultStyleError(explorer, dlg.layername)
            else:
                catItem.layersItem.refreshContent(explorer)
Ejemplo n.º 2
0
    def publishPgTable(self, tree, explorer):
        if not xmlNameIsValid(self.element.name, xmlNameRegex()):
            QtGui.QMessageBox.warning(
                explorer, "Invalid name",
                ("The table name (%s) is not a valid XML name.\n" +
                 "This could cause problems when published to GeoServer.\n" +
                 "Please rename it and retry publishing.") % self.element.name)
            return
        dlg = PublishLayerDialog(explorer.catalogs(), self.element)
        dlg.exec_()
        if dlg.catalog is None:
            return
        cat = dlg.catalog
        catItem = tree.findFirstItem(cat)
        toUpdate = [catItem]
        if int(self.element.srid) == 0:
            explorer.setWarning("PostGIS table '{0}' has no SRID; ESPG:4326 "
                                "will be assigned.".format(self.element.name))
        if explorer.run(publishTable,
                        "Publish table '" + self.element.name + "'", toUpdate,
                        self.element, cat, dlg.workspace, True, dlg.layername):

            # add existing style to layer, or later some operations may fail,
            # like malformed XML when getting capabilities for OWS connections
            pglyr = cat.get_layer(dlg.layername)
            pgitem = tree.findFirstItem(pglyr)
            if pgitem is None:
                return
            if not pgitem.addStyleToLayer(explorer):  # handles refresh of item
                # user cancelled AddStyleToLayerDialog
                noDefaultStyleError(explorer, dlg.layername)
            else:
                catItem.layersItem.refreshContent(explorer)
Ejemplo n.º 3
0
    def testGSNameWidgetInvalidName(self):
        # base invalid name is empty
        nw = GSNameWidget(name='')
        self.assertFalse(nw.isValid())

        nw.validateName('')
        self.assertFalse(nw.isValid())
        nw.highlightName()
        self.assertNotEqual(nw.nameBox.lineEdit().styleSheet(), '')

        invalidnames = ['xMl_name', 'name with spaces', '9starts_with_number',
                        ':starts_with_punctuation']

        # XML invalid name
        nw.setNameRegex(xmlNameRegex(), xmlNameRegexMsg())
        self.assertFalse(nw.isValid())
        self.assertIsNone(nw.definedName())
        for ivname in invalidnames:
            nw.setName(ivname)
            self.assertFalse(nw.isValid())

        # empty name regex
        nw.setName('')
        nw.setNameRegex(xmlNameEmptyRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        self.assertEqual(nw.definedName(), '')
        for ivname in invalidnames:
            nw.setName(ivname)
            self.assertFalse(nw.isValid())

        # custom regex invalid name
        nw.setNameRegex(r'^(?!XML|\d|\W)[a-z](\S(?!::))*', 'regex message')
        nw.setName('my::name')
        self.assertFalse(nw.isValid())
Ejemplo n.º 4
0
    def testGSNameWidgetValidName(self):
        nw = GSNameWidget(name='my_pg_connection')
        self.assertTrue(nw.isValid())
        self.assertIsNotNone(nw.definedName())
        self.assertEqual(nw.definedName(), 'my_pg_connection')

        nw.validateName('my_pg_connection')
        self.assertTrue(nw.isValid())
        nw.highlightName()
        self.assertEqual(nw.nameBox.lineEdit().styleSheet(), '')

        validnames = ['name_8291', 'name.with.dots', 'name:with::colons',
                      '_name_with_underscore']

        # XML valid name
        nw.setNameRegex(xmlNameRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        for vname in validnames:
            nw.setName(vname)
            self.assertTrue(nw.isValid())

        # empty name regex
        nw.setName('')
        nw.setNameRegex(xmlNameEmptyRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        nw.setAllowEmpty(True)
        self.assertTrue(nw.isValid())
        self.assertEqual(nw.definedName(), '')
        for vname in validnames:
            nw.setName(vname)
            self.assertTrue(nw.isValid())
Ejemplo n.º 5
0
    def testGSNameWidgetValidName(self):
        nw = GSNameWidget(name='my_pg_connection')
        self.assertTrue(nw.isValid())
        self.assertIsNotNone(nw.definedName())
        self.assertEqual(nw.definedName(), 'my_pg_connection')

        nw.validateName('my_pg_connection')
        self.assertTrue(nw.isValid())
        nw.highlightName()
        self.assertEqual(nw.nameBox.lineEdit().styleSheet(), '')

        validnames = ['name_8291', 'name.with.dots', 'name:with::colons',
                      '_name_with_underscore']

        # XML valid name
        nw.setNameRegex(xmlNameRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        for vname in validnames:
            nw.setName(vname)
            self.assertTrue(nw.isValid())

        # empty name regex
        nw.setName('')
        nw.setNameRegex(xmlNameEmptyRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        nw.setAllowEmpty(True)
        self.assertTrue(nw.isValid())
        self.assertEqual(nw.definedName(), '')
        for vname in validnames:
            nw.setName(vname)
            self.assertTrue(nw.isValid())
Ejemplo n.º 6
0
    def testGSNameWidgetInvalidName(self):
        # base invalid name is empty
        nw = GSNameWidget(name='')
        self.assertFalse(nw.isValid())

        nw.validateName('')
        self.assertFalse(nw.isValid())
        nw.highlightName()
        self.assertNotEqual(nw.nameBox.lineEdit().styleSheet(), '')

        invalidnames = ['xMl_name', 'name with spaces', '9starts_with_number',
                        ':starts_with_punctuation']

        # XML invalid name
        nw.setNameRegex(xmlNameRegex(), xmlNameRegexMsg())
        self.assertFalse(nw.isValid())
        self.assertIsNone(nw.definedName())
        for ivname in invalidnames:
            nw.setName(ivname)
            self.assertFalse(nw.isValid())

        # empty name regex
        nw.setName('')
        nw.setNameRegex(xmlNameEmptyRegex(), xmlNameRegexMsg())
        self.assertTrue(nw.isValid())
        self.assertEqual(nw.definedName(), '')
        for ivname in invalidnames:
            nw.setName(ivname)
            self.assertFalse(nw.isValid())

        # custom regex invalid name
        nw.setNameRegex(r'^(?!XML|\d|\W)[a-z](\S(?!::))*', 'regex message')
        nw.setName('my::name')
        self.assertFalse(nw.isValid())
Ejemplo n.º 7
0
	def okPressed(self):
		self.name = unicode(self.editName.text())
		self.editName.setStyleSheet("QLineEdit{background: white}")
		if not xmlNameIsValid(self.name, xmlNameRegex()):
			self.editName.setStyleSheet("QLineEdit{background: yellow}")
			return
		if self.table.rowCount() == 0:
			QMessageBox.information(self, self.tr("Sorry"), self.tr("add some fields!"))
			return

		self.useGeomColumn = self.chkGeomColumn.isChecked()
		if self.useGeomColumn:
			self.geomColumn = unicode(self.editGeomColumn.text())
			if len(self.geomColumn) == 0:
				self.editGeomColumn.setStyleSheet("QLineEdit{background: yellow}")
				return

			self.geomType = self.GEOM_TYPES[ self.cboGeomType.currentIndex() ]
			self.geomDim = self.spinGeomDim.value()
			try:
				self.geomSrid = int(self.editGeomSrid.text())
			except ValueError:
				self.geomSrid = -1
			self.useSpatialIndex = self.chkSpatialIndex.isChecked()

		self.fields = []
		for i in xrange(self.table.rowCount()):
			name = self.table.cellWidget(i, 0).text()
			type = self.table.cellWidget(i, 1).currentText()
			null = self.table.cellWidget(i, 2).currentIndex == 0
			self.fields.append(TableField(name, type, null))
		self.pk = self.cboPrimaryKey.currentText()
		self.ok = True
		self.close()
Ejemplo n.º 8
0
 def testGSNameWidgetInit(self):
     nw = GSNameWidget(
         namemsg='Sample is generated from PostgreSQL connection name',
         name=xmlNameFixUp('My PG connection'),
         nameregex=xmlNameRegex(),
         nameregexmsg=xmlNameRegexMsg(),
         names=['name_one', 'name_two', 'name_three'],
         unique=False,
         maxlength=10)
     self.assertEqual(nw.nameBox.count(), 4)  # name is prepended to list
Ejemplo n.º 9
0
 def testGSNameWidgetInit(self):
     nw = GSNameWidget(
         namemsg='Sample is generated from PostgreSQL connection name',
         name=xmlNameFixUp('My PG connection'),
         nameregex=xmlNameRegex(),
         nameregexmsg=xmlNameRegexMsg(),
         names=['name_one', 'name_two', 'name_three'],
         unique=False,
         maxlength=10)
     self.assertEqual(nw.nameBox.count(), 4)  # name is prepended to list
Ejemplo n.º 10
0
    def initGui(self):     
        self.setWindowTitle('New workspace')                    
        verticalLayout = QtGui.QVBoxLayout()                                
                        
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setSpacing(30)
        horizontalLayout.setMargin(0)        
        nameLabel = QtGui.QLabel('Workspace name')
        nameLabel.setMinimumWidth(150)
        self.nameBox = GSNameWidget(
            namemsg='',
            name='workspace',
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.workspaces,
            unique=True,
            maxlength=10)
        self.nameBox.setMinimumWidth(250)
        horizontalLayout.addWidget(nameLabel)
        horizontalLayout.addWidget(self.nameBox)
        verticalLayout.addLayout(horizontalLayout)
        
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setSpacing(30)
        horizontalLayout.setMargin(0)        
        uriLabel = QtGui.QLabel('URI')
        uriLabel.setMinimumWidth(150)
        self.uriBox = QtGui.QLineEdit()
        self.uriBox.setText('')
        self.uriBox.setPlaceholderText('Required')
        self.uriBox.setMinimumWidth(250)
        horizontalLayout.addWidget(uriLabel)
        horizontalLayout.addWidget(self.uriBox)
        verticalLayout.addLayout(horizontalLayout)
        
        self.groupBox = QtGui.QGroupBox()        
        self.groupBox.setLayout(verticalLayout)
        
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.groupBox)   
        self.spacer = QtGui.QSpacerItem(20,20, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        layout.addItem(self.spacer)
        
        self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.nameBox.nameValidityChanged.connect(self.updateOkButton)
        self.uriBox.textChanged.connect(self.updateOkButton)
        self.updateOkButton()
Ejemplo n.º 11
0
 def testGSNameStaticUtils(self):
     n = xmlNameFixUp('My PG connection')
     self.assertTrue(n == 'My_PG_connection')
     n = xmlNameFixUp('0Name_with_number')
     self.assertTrue(n == '_0Name_with_number')
     n = xmlNameFixUp('xml_starts_name')
     self.assertTrue(n == '_xml_starts_name')
     n = xmlNameFixUp(':Name_startswith_punctuation')
     self.assertTrue(n == '_:Name_startswith_punctuation')
     nr = xmlNameRegex()
     self.assertTrue(QRegExp(nr, 0).isValid())
     nrm = xmlNameRegexMsg()
     self.assertTrue('XML name' in nrm)
Ejemplo n.º 12
0
 def __init__(self, **kwargs):
     unique = kwargs.get('unique', False)
     super(PostGisTableNameDialog, self).__init__(
         boxtitle='Table name',
         boxmsg='Define valid table name',
         name=xmlNameFixUp(kwargs.get('name', '')),
         namemsg=kwargs.get('namemsg', ''),
         nameregex=kwargs.get('nameregex', xmlNameRegex()),
         nameregexmsg=kwargs.get('nameregexmsg', xmlNameRegexMsg()),
         names=kwargs.get('names', None),
         unique=unique,
         maxlength=kwargs.get('maxlength', 0),
         parent=kwargs.get('parent', None))
Ejemplo n.º 13
0
 def testGSNameStaticUtils(self):
     n = xmlNameFixUp('My PG connection')
     self.assertTrue(n == 'My_PG_connection')
     n = xmlNameFixUp('0Name_with_number')
     self.assertTrue(n == '_0Name_with_number')
     n = xmlNameFixUp('xml_starts_name')
     self.assertTrue(n == '_xml_starts_name')
     n = xmlNameFixUp(':Name_startswith_punctuation')
     self.assertTrue(n == '_:Name_startswith_punctuation')
     nr = xmlNameRegex()
     self.assertTrue(QRegExp(nr, 0).isValid())
     nrm = xmlNameRegexMsg()
     self.assertTrue('XML name' in nrm)
Ejemplo n.º 14
0
    def setupUi(self):
        self.resize(600, 350)
        self.setWindowTitle("Publish Group")
        vertlayout = QtGui.QVBoxLayout(self)
        vertlayout.setSpacing(2)
        vertlayout.setMargin(6)
        horizlayout = QtGui.QHBoxLayout(self)
        # horizlayout.setSpacing(30)
        horizlayout.setMargin(0)
        self.nameLabel = QtGui.QLabel("Group name")
        self.nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Preferred))
        self.nameBox = GSNameWidget(
            name=xmlNameFixUp(self.groupname),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.groupnames,
            unique=not self.overwritegrp)
        self.nameBox.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                              QtGui.QSizePolicy.Preferred))
        horizlayout.addWidget(self.nameLabel)
        horizlayout.addWidget(self.nameBox)
        vertlayout.addLayout(horizlayout)

        self.lyrstable = PublishLayersDialog(
            {0: self.catalog}, self.layers,
            workspace=self.workspace, overwrite=self.overwritelyrs)
        self.lyrstable.buttonBox.setVisible(False)
        vertlayout.addWidget(self.lyrstable)

        self.buttonBox = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        vertlayout.addWidget(self.buttonBox)

        self.setLayout(vertlayout)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())

        self.lyrstable.itemValidityChanged.connect(self.okButton.setEnabled)
        self.okButton.setEnabled(self.lyrstable.layerNamesValid())
Ejemplo n.º 15
0
 def __init__(self, kind, **kwargs):
     unique = kwargs.get('unique', False)
     super(GSXmlNameDialog, self).__init__(
         boxtitle='GeoServer {0} name'.format(kind),
         boxmsg='Define unique {0}'.format(kind) +
                ' or overwrite existing' if not unique else '',
         name=xmlNameFixUp(kwargs.get('name', '')),
         namemsg=kwargs.get('namemsg', ''),
         nameregex=kwargs.get('nameregex', xmlNameRegex()),
         nameregexmsg=kwargs.get('nameregexmsg', xmlNameRegexMsg()),
         names=kwargs.get('names', None),
         unique=unique,
         maxlength=kwargs.get('maxlength', 0),
         parent=kwargs.get('parent', None))
Ejemplo n.º 16
0
 def __init__(self, **kwargs):
     unique = kwargs.get('unique', False)
     super(PostGisTableNameDialog,
           self).__init__(boxtitle='Table name',
                          boxmsg='Define valid table name',
                          name=xmlNameFixUp(kwargs.get('name', '')),
                          namemsg=kwargs.get('namemsg', ''),
                          nameregex=kwargs.get('nameregex', xmlNameRegex()),
                          nameregexmsg=kwargs.get('nameregexmsg',
                                                  xmlNameRegexMsg()),
                          names=kwargs.get('names', None),
                          unique=unique,
                          maxlength=kwargs.get('maxlength', 0),
                          parent=kwargs.get('parent', None))
Ejemplo n.º 17
0
 def __init__(self, kind, **kwargs):
     unique = kwargs.get('unique', False)
     super(GSXmlNameDialog,
           self).__init__(boxtitle='GeoServer {0} name'.format(kind),
                          boxmsg='Define unique {0}'.format(kind) +
                          ' or overwrite existing' if not unique else '',
                          name=xmlNameFixUp(kwargs.get('name', '')),
                          namemsg=kwargs.get('namemsg', ''),
                          nameregex=kwargs.get('nameregex', xmlNameRegex()),
                          nameregexmsg=kwargs.get('nameregexmsg',
                                                  xmlNameRegexMsg()),
                          names=kwargs.get('names', None),
                          unique=unique,
                          maxlength=kwargs.get('maxlength', 0),
                          parent=kwargs.get('parent', None))
Ejemplo n.º 18
0
    def testGSNameDialog(self):
        ndlg = GSNameDialog(
            boxtitle='GeoServer data store name',
            boxmsg='My groupbox message',
            namemsg='Sample is generated from PostgreSQL connection name.',
            name=xmlNameFixUp('My PG connection'),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=['name_one', 'name_two', 'name_three'],
            unique=True,
            maxlength=10)

        # maxlength > 10
        self.assertFalse(ndlg.okButton.isEnabled())
        self.assertIsNone(ndlg.definedName())
        self.assertFalse(ndlg.overwritingName())

        # maxlength = 10
        ndlg.nameBox.setName('my_pg_conn')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertEqual(ndlg.definedName(), 'my_pg_conn')
        self.assertFalse(ndlg.overwritingName())

        # unique = True
        ndlg.nameBox.setName('name_one')
        self.assertIsNone(ndlg.definedName())
        self.assertFalse(ndlg.okButton.isEnabled())
        self.assertFalse(ndlg.overwritingName())

        del ndlg
        # unique=False
        ndlg = GSNameDialog(
            boxtitle='GeoServer data store name',
            boxmsg='My groupbox message',
            name='name',
            names=['name_one', 'name_two', 'name_three'],
            unique=False)

        # not overwriting
        self.assertEqual(ndlg.definedName(), 'name')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertFalse(ndlg.overwritingName())
        # overwriting
        ndlg.nameBox.setName('name_one')
        self.assertEqual(ndlg.definedName(), 'name_one')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertTrue(ndlg.overwritingName())
Ejemplo n.º 19
0
    def testGSNameDialog(self):
        ndlg = GSNameDialog(
            boxtitle='GeoServer data store name',
            boxmsg='My groupbox message',
            namemsg='Sample is generated from PostgreSQL connection name.',
            name=xmlNameFixUp('My PG connection'),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=['name_one', 'name_two', 'name_three'],
            unique=True,
            maxlength=10)

        # maxlength > 10
        self.assertFalse(ndlg.okButton.isEnabled())
        self.assertIsNone(ndlg.definedName())
        self.assertFalse(ndlg.overwritingName())

        # maxlength = 10
        ndlg.nameBox.setName('my_pg_conn')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertEqual(ndlg.definedName(), 'my_pg_conn')
        self.assertFalse(ndlg.overwritingName())

        # unique = True
        ndlg.nameBox.setName('name_one')
        self.assertIsNone(ndlg.definedName())
        self.assertFalse(ndlg.okButton.isEnabled())
        self.assertFalse(ndlg.overwritingName())

        del ndlg
        # unique=False
        ndlg = GSNameDialog(
            boxtitle='GeoServer data store name',
            boxmsg='My groupbox message',
            name='name',
            names=['name_one', 'name_two', 'name_three'],
            unique=False)

        # not overwriting
        self.assertEqual(ndlg.definedName(), 'name')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertFalse(ndlg.overwritingName())
        # overwriting
        ndlg.nameBox.setName('name_one')
        self.assertEqual(ndlg.definedName(), 'name_one')
        self.assertTrue(ndlg.okButton.isEnabled())
        self.assertTrue(ndlg.overwritingName())
Ejemplo n.º 20
0
    def setupUi(self):
        self.resize(600, 350)
        self.setWindowTitle("Publish Group")
        vertlayout = QtGui.QVBoxLayout(self)
        vertlayout.setSpacing(2)
        vertlayout.setMargin(6)
        horizlayout = QtGui.QHBoxLayout(self)
        # horizlayout.setSpacing(30)
        horizlayout.setMargin(0)
        self.nameLabel = QtGui.QLabel("Group name")
        self.nameLabel.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred))
        self.nameBox = GSNameWidget(
            name=xmlNameFixUp(self.groupname),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.groupnames,
            unique=not self.overwritegrp,
        )
        self.nameBox.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred))
        horizlayout.addWidget(self.nameLabel)
        horizlayout.addWidget(self.nameBox)
        vertlayout.addLayout(horizlayout)

        self.lyrstable = PublishLayersDialog(
            {0: self.catalog}, self.layers, workspace=self.workspace, overwrite=self.overwritelyrs
        )
        self.lyrstable.buttonBox.setVisible(False)
        vertlayout.addWidget(self.lyrstable)

        self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        vertlayout.addWidget(self.buttonBox)

        self.setLayout(vertlayout)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())

        self.lyrstable.itemValidityChanged.connect(self.okButton.setEnabled)
        self.okButton.setEnabled(self.lyrstable.layerNamesValid())
Ejemplo n.º 21
0
def publishDraggedTable(tree, explorer, table, workspace):
    if not xmlNameIsValid(table.name, xmlNameRegex()):
        QtGui.QMessageBox.warning(
            explorer, "Invalid name",
            ("The table name (%s) is not a valid XML name.\n" +
             "This could cause problems when published to GeoServer.\n" +
             "Please rename it and retry publishing.") % table.name)
        return False
    cat = workspace.catalog
    if int(table.srid) == 0:
        explorer.setWarning("PostGIS table '{0}' has no SRID; ESPG:4326 will "
                            "be assigned.".format(table.name))

    gslayers = [lyr.name for lyr in cat.get_layers()]
    try:
        lyrname = getGSLayerName(name=xmlNameFixUp(table.name + "_table"),
                                 names=gslayers,
                                 unique=False)
    except UserCanceledOperation:
        return False

    catItem = tree.findFirstItem(cat)
    toUpdate = [catItem.layersItem]
    res = explorer.run(publishTable,
                       "Publish table from table '" + table.name + "'",
                       toUpdate, table, cat, workspace, True, lyrname)
    if res:
        # add existing style to layer, or later some operations may fail,
        # like malformed XML when getting capabilities for OWS connections
        pglyr = cat.get_layer(lyrname)
        pgitem = tree.findFirstItem(pglyr)
        if pgitem is None:
            print "pgitem not found"
            return False
        if not pgitem.addStyleToLayer(explorer):  # handles refresh of item
            # user cancelled AddStyleToLayerDialog
            noDefaultStyleError(explorer, lyrname)
            return False
        else:
            catItem.layersItem.refreshContent(explorer)
    return res
Ejemplo n.º 22
0
def publishDraggedTable(tree, explorer, table, workspace):
    if not xmlNameIsValid(table.name, xmlNameRegex()):
        QtGui.QMessageBox.warning(explorer, "Invalid name",
                                  ("The table name (%s) is not a valid XML name.\n"
                                  + "This could cause problems when published to GeoServer.\n"
                                  + "Please rename it and retry publishing.") % table.name)
        return False
    cat = workspace.catalog
    if int(table.srid) == 0:
        explorer.setWarning("PostGIS table '{0}' has no SRID; ESPG:4326 will "
                            "be assigned.".format(table.name))

    gslayers = [lyr.name for lyr in cat.get_layers()]
    try:
        lyrname = getGSLayerName(name=xmlNameFixUp(table.name + "_table"),
                                 names=gslayers,
                                 unique=False)
    except UserCanceledOperation:
        return False

    catItem = tree.findFirstItem(cat)
    toUpdate = [catItem.layersItem]
    res = explorer.run(publishTable,
                       "Publish table from table '" + table.name + "'",
                       toUpdate,
                       table, cat, workspace, True, lyrname)
    if res:
        # add existing style to layer, or later some operations may fail,
        # like malformed XML when getting capabilities for OWS connections
        pglyr = cat.get_layer(lyrname)
        pgitem = tree.findFirstItem(pglyr)
        if pgitem is None:
            print "pgitem not found"
            return False
        if not pgitem.addStyleToLayer(explorer):  # handles refresh of item
            # user cancelled AddStyleToLayerDialog
            noDefaultStyleError(explorer, lyrname)
            return False
        else:
            catItem.layersItem.refreshContent(explorer)
    return res
Ejemplo n.º 23
0
    def okPressed(self):
        self.name = unicode(self.editName.text())
        self.editName.setStyleSheet("QLineEdit{background: white}")
        if not xmlNameIsValid(self.name, xmlNameRegex()):
            self.editName.setStyleSheet("QLineEdit{background: yellow}")
            return
        if self.table.rowCount() == 0:
            QMessageBox.information(self, self.tr("Sorry"),
                                    self.tr("add some fields!"))
            return

        self.useGeomColumn = self.chkGeomColumn.isChecked()
        if self.useGeomColumn:
            self.geomColumn = unicode(self.editGeomColumn.text())
            if len(self.geomColumn) == 0:
                self.editGeomColumn.setStyleSheet(
                    "QLineEdit{background: yellow}")
                return

            self.geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()]
            self.geomDim = self.spinGeomDim.value()
            try:
                self.geomSrid = int(self.editGeomSrid.text())
            except ValueError:
                self.geomSrid = -1
            self.useSpatialIndex = self.chkSpatialIndex.isChecked()

        self.fields = []
        for i in xrange(self.table.rowCount()):
            name = self.table.cellWidget(i, 0).text()
            type = self.table.cellWidget(i, 1).currentText()
            null = self.table.cellWidget(i, 2).currentIndex == 0
            self.fields.append(TableField(name, type, null))
        self.pk = self.cboPrimaryKey.currentText()
        self.ok = True
        self.close()
Ejemplo n.º 24
0
    def setupUi(self):                
        self.resize(600, 350)
        self.setWindowTitle("Group definition")
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.setSpacing(2)
        self.verticalLayout.setMargin(6)
        self.horizontalLayout = QtGui.QHBoxLayout()
        # self.horizontalLayout.setSpacing(30)
        self.horizontalLayout.setMargin(0)
        self.nameLabel = QtGui.QLabel("Group name")
        self.nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred))
        defaultname = "Group"
        if self.previousgroup:
            defaultname = self.previousgroup.name
        self.nameBox = GSNameWidget(
            namemsg='',
            name=defaultname,
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.groupnames,
            unique=False if self.previousgroup else True)
        if self.previousgroup:
            self.nameBox.setEnabled(False)
        self.nameBox.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred))

        self.horizontalLayout.addWidget(self.nameLabel)
        self.horizontalLayout.addWidget(self.nameBox)
        self.verticalLayout.addLayout(self.horizontalLayout)        
        self.horizontalLayout = QtGui.QHBoxLayout(self)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setMargin(0)
        self.buttonBox = QtGui.QDialogButtonBox()
        self.buttonBox.setOrientation(QtCore.Qt.Vertical)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(2)
        self.table.setColumnWidth(0,300)
        self.table.verticalHeader().setVisible(False)
        self.table.horizontalHeader().setVisible(True)
        self.table.setHorizontalHeaderLabels(["Layer", "Style"])
        self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.selectAllButton = QtGui.QPushButton()
        self.selectAllButton.setText("(de)Select all")
        self.setTableContent()
        self.buttonBox.addButton(self.selectAllButton, QtGui.QDialogButtonBox.ActionRole)
        self.horizontalLayout.addWidget(self.table)
        self.horizontalLayout.addWidget(self.buttonBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.setLayout(self.verticalLayout)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.selectAllButton.clicked.connect(self.selectAll)
        QtCore.QMetaObject.connectSlotsByName(self)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())
Ejemplo n.º 25
0
    def initGui(self):
        self.setWindowTitle('Publish layer')
        layout = QtGui.QVBoxLayout()

        gridLayout = QtGui.QGridLayout()
        gridLayout.setSpacing(10)
        gridLayout.setMargin(10)
        catalogLabel = QtGui.QLabel('Catalog')
        catalogLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(catalogLabel, 0, 0)
        self.catalogBox = QtGui.QComboBox()
        self.catalogBox.addItems(self.catalogs.keys())
        self.catalogBox.currentIndexChanged.connect(self.catalogHasChanged)
        gridLayout.addWidget(self.catalogBox, 0, 1)

        workspaceLabel = QtGui.QLabel('Workspace')
        workspaceLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(workspaceLabel, 1, 0)
        self.workspaceBox = QtGui.QComboBox()
        cat = self.catalogs[self.catalogs.keys()[0]]
        self.workspaces = cat.get_workspaces()
        try:
            defaultWorkspace = cat.get_default_workspace()
            defaultWorkspace.fetch()
            defaultName = defaultWorkspace.dom.find('name').text
        except:
            defaultName = None
        workspaceNames = [w.name for w in self.workspaces]
        self.workspaceBox.addItems(workspaceNames)
        if defaultName is not None:
            self.workspaceBox.setCurrentIndex(
                workspaceNames.index(defaultName))
        gridLayout.addWidget(self.workspaceBox, 1, 1)

        nameLabel = QtGui.QLabel('Layer')
        nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(nameLabel, 2, 0)
        gslayers = [lyr.name for lyr in cat.get_layers()]
        name = ''
        # handle PG Table, whose name attribute is not callable
        if self.layer is not None and hasattr(self.layer, 'name'):
            if isinstance(self.layer, Table):
                name = self.layer.name + "_table"
            else:  # QgsMapLayer
                name = self.layer.name()
                if layers.isPostGisLayer(self.layer):
                    name += "_table"
        self.nameBox = GSNameWidget(name=xmlNameFixUp(name),
                                    nameregex=xmlNameRegex(),
                                    nameregexmsg=xmlNameRegexMsg(),
                                    names=gslayers,
                                    unique=False)
        gridLayout.addWidget(self.nameBox, 2, 1)

        self.destGroupBox = QtGui.QGroupBox()
        self.destGroupBox.setLayout(gridLayout)

        layout.addWidget(self.destGroupBox)

        self.spacer = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum,
                                        QtGui.QSizePolicy.Expanding)
        layout.addItem(self.spacer)

        self.buttonBox = QtGui.QDialogButtonBox(
            QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(
            QtGui.QDialogButtonBox.Cancel)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        # respond to intial validation
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())

        self.resize(400, 160)
Ejemplo n.º 26
0
    def setTableContent(self):
        self.table.setRowCount(len(self.layers))
        cat = self.catalogs.values()[0]
        catlayers = [lyr.name for lyr in cat.get_layers()]
        for idx, layer in enumerate(self.layers):

            lyritem = QtGui.QTableWidgetItem(layer.name())
            lyritem.setToolTip(layer.name())
            lyritem.setFlags(QtCore.Qt.ItemIsEnabled)
            self.table.setItem(idx, self.getColumn("Layer"), lyritem)

            lyrname = layer.name()
            if layers.isPostGisLayer(layer):
                lyrname += "_table"

            nameBox = GSNameWidget(name=xmlNameFixUp(lyrname),
                                   nameregex=xmlNameRegex(),
                                   nameregexmsg=xmlNameRegexMsg(),
                                   names=catlayers,
                                   unique=not self.overwrite)
            self.table.setCellWidget(idx, self.getColumn(self.name), nameBox)

            self.nameBoxes.append(nameBox)

            overwriteBox = QtGui.QCheckBox()
            overwriteBox.setEnabled(False)
            overwriteBox.setToolTip("Overwrite existing layer")
            self.table.setCellWidget(idx, self.getColumn(self.ow),
                                     overwriteBox)

            nameBox.nameValidityChanged.connect(self.validateNames)
            nameBox.overwritingChanged[bool].connect(overwriteBox.setChecked)
            overwriteBox.setChecked(
                nameBox.overwritingName())  # initial update

            if self.showCatalogCol:
                catalogBox = QtGui.QComboBox()
                catalogBox.setSizePolicy(
                    QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                      QtGui.QSizePolicy.Fixed))
                catalogBox.addItems(self.catalogs.keys())
                catalogBox.currentIndexChanged.connect(
                    partial(self.catalogHasChanged, idx))
                self.table.setCellWidget(idx, self.getColumn(self.cat),
                                         catalogBox)

            workspaceBox = QtGui.QComboBox()
            workspaceBox.setSizePolicy(
                QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                  QtGui.QSizePolicy.Fixed))
            if self.workspace is not None:
                workspaces = [self.workspace]
                defaultName = None
            else:
                workspaces = cat.get_workspaces()
                try:
                    defaultWorkspace = cat.get_default_workspace()
                    defaultWorkspace.fetch()
                    defaultName = defaultWorkspace.dom.find('name').text
                except:
                    defaultName = None
            workspaceNames = [w.name for w in workspaces]
            workspaceBox.addItems(workspaceNames)
            if defaultName is not None:
                workspaceBox.setCurrentIndex(workspaceNames.index(defaultName))
            self.table.setCellWidget(idx, self.getColumn(self.wrksp),
                                     workspaceBox)
Ejemplo n.º 27
0
    def initGui(self):
        self.setWindowTitle('Publish layer')
        layout = QtGui.QVBoxLayout()

        gridLayout = QtGui.QGridLayout()
        gridLayout.setSpacing(10)
        gridLayout.setMargin(10)
        catalogLabel = QtGui.QLabel('Catalog')
        catalogLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(catalogLabel, 0, 0)
        self.catalogBox = QtGui.QComboBox()
        self.catalogBox.addItems(self.catalogs.keys())
        self.catalogBox.currentIndexChanged.connect(self.catalogHasChanged)
        gridLayout.addWidget(self.catalogBox, 0, 1)

        workspaceLabel = QtGui.QLabel('Workspace')
        workspaceLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(workspaceLabel, 1, 0)
        self.workspaceBox = QtGui.QComboBox()
        cat = self.catalogs[self.catalogs.keys()[0]]
        self.workspaces = cat.get_workspaces()
        try:
            defaultWorkspace = cat.get_default_workspace()
            defaultWorkspace.fetch()
            defaultName = defaultWorkspace.dom.find('name').text
        except:
            defaultName = None
        workspaceNames = [w.name for w in self.workspaces]
        self.workspaceBox.addItems(workspaceNames)
        if defaultName is not None:
            self.workspaceBox.setCurrentIndex(workspaceNames.index(defaultName))
        gridLayout.addWidget(self.workspaceBox, 1, 1)

        nameLabel = QtGui.QLabel('Layer')
        nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        gridLayout.addWidget(nameLabel, 2, 0)
        gslayers = [lyr.name for lyr in cat.get_layers()]
        name = ''
        # handle PG Table, whose name attribute is not callable
        if self.layer is not None and hasattr(self.layer, 'name'):
            if isinstance(self.layer, Table):
                name = self.layer.name + "_table"
            else:  # QgsMapLayer
                name = self.layer.name()
                if layers.isPostGisLayer(self.layer):
                        name += "_table"
        self.nameBox = GSNameWidget(
            name=xmlNameFixUp(name),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=gslayers,
            unique=False)
        gridLayout.addWidget(self.nameBox, 2, 1)

        self.destGroupBox = QtGui.QGroupBox()
        self.destGroupBox.setLayout(gridLayout)

        layout.addWidget(self.destGroupBox)

        self.spacer = QtGui.QSpacerItem(20,40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
        layout.addItem(self.spacer)

        self.buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        # respond to intial validation
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())

        self.resize(400,160)
Ejemplo n.º 28
0
    def setTableContent(self):
        self.table.setRowCount(len(self.layers))
        cat = self.catalogs.values()[0]
        catlayers = [lyr.name for lyr in cat.get_layers()]
        for idx, layer in enumerate(self.layers):

            lyritem = QtGui.QTableWidgetItem(layer.name())
            lyritem.setToolTip(layer.name())
            lyritem.setFlags(QtCore.Qt.ItemIsEnabled)
            self.table.setItem(idx, self.getColumn("Layer"), lyritem)

            lyrname = layer.name()
            if layers.isPostGisLayer(layer):
                lyrname += "_table"

            nameBox = GSNameWidget(
                name=xmlNameFixUp(lyrname),
                nameregex=xmlNameRegex(),
                nameregexmsg=xmlNameRegexMsg(),
                names=catlayers,
                unique=not self.overwrite)
            self.table.setCellWidget(idx, self.getColumn(self.name), nameBox)

            self.nameBoxes.append(nameBox)

            overwriteBox = QtGui.QCheckBox()
            overwriteBox.setEnabled(False)
            overwriteBox.setToolTip("Overwrite existing layer")
            self.table.setCellWidget(idx, self.getColumn(self.ow), overwriteBox)

            nameBox.nameValidityChanged.connect(self.validateNames)
            nameBox.overwritingChanged[bool].connect(overwriteBox.setChecked)
            overwriteBox.setChecked(nameBox.overwritingName())  # initial update

            if self.showCatalogCol:
                catalogBox = QtGui.QComboBox()
                catalogBox.setSizePolicy(
                    QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                      QtGui.QSizePolicy.Fixed))
                catalogBox.addItems(self.catalogs.keys())
                catalogBox.currentIndexChanged.connect(partial(self.catalogHasChanged, idx))
                self.table.setCellWidget(idx, self.getColumn(self.cat), catalogBox)

            workspaceBox = QtGui.QComboBox()
            workspaceBox.setSizePolicy(
                QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                                  QtGui.QSizePolicy.Fixed))
            if self.workspace is not None:
                workspaces = [self.workspace]
                defaultName = None
            else:
                workspaces = cat.get_workspaces()
                try:
                    defaultWorkspace = cat.get_default_workspace()
                    defaultWorkspace.fetch()
                    defaultName = defaultWorkspace.dom.find('name').text
                except:
                    defaultName = None
            workspaceNames = [w.name for w in workspaces]
            workspaceBox.addItems(workspaceNames)
            if defaultName is not None:
                workspaceBox.setCurrentIndex(workspaceNames.index(defaultName))
            self.table.setCellWidget(idx, self.getColumn(self.wrksp), workspaceBox)
Ejemplo n.º 29
0
    def initGui(self):                         
        verticalLayout = QtGui.QVBoxLayout()                                
        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Close)
        self.okButton = buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = buttonBox.button(QtGui.QDialogButtonBox.Close)
        self.setWindowTitle('Create style from layer')
        
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setMargin(0)
        layerLabel = QtGui.QLabel('Layer')
        layerLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        self.layerBox = QtGui.QComboBox()
        self.alllayers = [layer.name() for layer in layers.getAllLayers()]
        self.layerBox.addItems(self.alllayers)
        self.layerBox.setMinimumWidth(250)
        horizontalLayout.addWidget(layerLabel)
        horizontalLayout.addWidget(self.layerBox)
        verticalLayout.addLayout(horizontalLayout)
               
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setMargin(0)
        nameLabel = QtGui.QLabel('Name')
        nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        defaultname = ''
        if len(self.alllayers) > 0:
            defaultname = xmlNameFixUp(self.alllayers[0])
        self.nameBox = GSNameWidget(
            namemsg='',
            name=defaultname,
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.styles,
            unique=False)
        self.nameBox.setMinimumWidth(250)
        horizontalLayout.addWidget(nameLabel)
        horizontalLayout.addWidget(self.nameBox)
        verticalLayout.addLayout(horizontalLayout)
        
        self.groupBox = QtGui.QGroupBox()
        self.groupBox.setTitle("")
        self.groupBox.setLayout(verticalLayout)
        
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.groupBox) 
        layout.addWidget(buttonBox)
              
        self.setLayout(layout)

        buttonBox.accepted.connect(self.okPressed)
        buttonBox.rejected.connect(self.cancelPressed)

        self.layerBox.currentIndexChanged[str].connect(self.updateNameBox)
        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())
        
        self.resize(400,150)
Ejemplo n.º 30
0
    def initGui(self):                         
        verticalLayout = QtGui.QVBoxLayout()                                
        buttonBox = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Close)
        self.okButton = buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = buttonBox.button(QtGui.QDialogButtonBox.Close)
        self.setWindowTitle('Publish style')
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setMargin(0)
        catalogLabel = QtGui.QLabel('Catalog')
        catalogLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        self.catalogBox = QtGui.QComboBox()        
        self.catalogBox.addItems(self.catalognames)
        self.catalogBox.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                              QtGui.QSizePolicy.Fixed))
        horizontalLayout.addWidget(catalogLabel)
        horizontalLayout.addWidget(self.catalogBox)
        verticalLayout.addLayout(horizontalLayout)
        
        horizontalLayout = QtGui.QHBoxLayout()
        horizontalLayout.setMargin(0)
        nameLabel = QtGui.QLabel('Name')
        nameLabel.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum,
                              QtGui.QSizePolicy.Fixed))
        self.nameBox = GSNameWidget(
            namemsg='',
            name=xmlNameFixUp(self.layername),
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=[],
            unique=False)
        self.nameBox.setSizePolicy(
            QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                              QtGui.QSizePolicy.Fixed))
        horizontalLayout.addWidget(nameLabel)
        horizontalLayout.addWidget(self.nameBox)
        verticalLayout.addLayout(horizontalLayout)
               

        self.groupBox = QtGui.QGroupBox()
        self.groupBox.setTitle("")
        self.groupBox.setLayout(verticalLayout)
        
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.groupBox) 
        layout.addWidget(buttonBox)
                               
        self.setLayout(layout)

        buttonBox.accepted.connect(self.okPressed)
        buttonBox.rejected.connect(self.cancelPressed)

        self.catalogBox.currentIndexChanged[str].connect(self.updateCatalogStyles)
        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)

        self.updateCatalogStyles(self.catalogBox.currentText())
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())
        
        self.resize(400,200)
Ejemplo n.º 31
0
    def setupUi(self):
        self.resize(600, 350)
        self.setWindowTitle("Group definition")
        self.verticalLayout = QtGui.QVBoxLayout(self)
        self.verticalLayout.setSpacing(2)
        self.verticalLayout.setMargin(6)
        self.horizontalLayout = QtGui.QHBoxLayout()
        # self.horizontalLayout.setSpacing(30)
        self.horizontalLayout.setMargin(0)
        self.nameLabel = QtGui.QLabel("Group name")
        self.nameLabel.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred))
        defaultname = "Group"
        if self.previousgroup:
            defaultname = self.previousgroup.name
        self.nameBox = GSNameWidget(
            namemsg="",
            name=defaultname,
            nameregex=xmlNameRegex(),
            nameregexmsg=xmlNameRegexMsg(),
            names=self.groupnames,
            unique=False if self.previousgroup else True,
        )
        if self.previousgroup:
            self.nameBox.setEnabled(False)
        self.nameBox.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Preferred))

        self.horizontalLayout.addWidget(self.nameLabel)
        self.horizontalLayout.addWidget(self.nameBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout = QtGui.QHBoxLayout(self)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setMargin(0)
        self.buttonBox = QtGui.QDialogButtonBox()
        self.buttonBox.setOrientation(QtCore.Qt.Vertical)
        self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok)
        self.okButton = self.buttonBox.button(QtGui.QDialogButtonBox.Ok)
        self.cancelButton = self.buttonBox.button(QtGui.QDialogButtonBox.Cancel)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(2)
        self.table.setColumnWidth(0, 300)
        self.table.verticalHeader().setVisible(False)
        self.table.horizontalHeader().setVisible(True)
        self.table.setHorizontalHeaderLabels(["Layer", "Style"])
        self.table.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.selectAllButton = QtGui.QPushButton()
        self.selectAllButton.setText("(de)Select all")
        self.setTableContent()
        self.buttonBox.addButton(self.selectAllButton, QtGui.QDialogButtonBox.ActionRole)
        self.horizontalLayout.addWidget(self.table)
        self.horizontalLayout.addWidget(self.buttonBox)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.setLayout(self.verticalLayout)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.selectAllButton.clicked.connect(self.selectAll)
        QtCore.QMetaObject.connectSlotsByName(self)

        self.nameBox.nameValidityChanged.connect(self.okButton.setEnabled)
        self.nameBox.overwritingChanged.connect(self.updateButtons)
        self.okButton.setEnabled(self.nameBox.isValid())
        self.updateButtons(self.nameBox.overwritingName())
Ejemplo n.º 32
0

def getGSStyleName(**kwargs):
    return getGSXmlName('layer style', **kwargs)


if __name__ == '__main__':
    from opengeo.gui.gsnameutils import \
        xmlNameFixUp, xmlNameRegex, xmlNameRegexMsg
    gdlg = GSNameDialog(
        boxtitle='GeoServer data store name',
        boxmsg='My groupbox message',
        namemsg='Sample is generated from PostgreSQL connection name.',
        # name=xmlNameFixUp('My PG connection'),
        name='name_one',
        nameregex=xmlNameRegex(),
        nameregexmsg=xmlNameRegexMsg(),
        names=['name_one', 'name_two'],
        unique=False,
        maxlength=10)
    gdlg.exec_()
    print gdlg.definedName()
    print gdlg.overwritingName()
    # and with no kwargs
    gdlg = GSNameDialog()
    gdlg.exec_()
    print gdlg.definedName()
    print gdlg.overwritingName()
    # gdlg.show()
    # gdlg.raise_()
    # gdlg.activateWindow()
Ejemplo n.º 33
0
    return getGSXmlName('layer group', **kwargs)

def getGSStyleName(**kwargs):
    return getGSXmlName('layer style', **kwargs)


if __name__ == '__main__':
    from opengeo.gui.gsnameutils import \
        xmlNameFixUp, xmlNameRegex, xmlNameRegexMsg
    gdlg = GSNameDialog(
        boxtitle='GeoServer data store name',
        boxmsg='My groupbox message',
        namemsg='Sample is generated from PostgreSQL connection name.',
        # name=xmlNameFixUp('My PG connection'),
        name='name_one',
        nameregex=xmlNameRegex(),
        nameregexmsg=xmlNameRegexMsg(),
        names=['name_one', 'name_two'],
        unique=False,
        maxlength=10)
    gdlg.exec_()
    print gdlg.definedName()
    print gdlg.overwritingName()
    # and with no kwargs
    gdlg = GSNameDialog()
    gdlg.exec_()
    print gdlg.definedName()
    print gdlg.overwritingName()
    # gdlg.show()
    # gdlg.raise_()
    # gdlg.activateWindow()
Ejemplo n.º 34
0
    def importFileOrLayer(self, source, schema, tablename, overwrite, singleGeom = False):

        if isinstance(source, basestring):
            layerName = QtCore.QFileInfo(source).completeBaseName()
        else:
            layerName = source.name()

        if tablename is None:
            tablename = layerName

        if not xmlNameIsValid(tablename, xmlNameRegex()):
            tablename = getPostGisTableName(name=tablename, names=[], unique=False)

        if overwrite:
            pk = "id"
            geom = "geom"
            providerName = "postgres"

            uri = QgsDataSourceURI()
            uri.setConnection(self.geodb.host, str(self.geodb.port), self.geodb.dbname, self.geodb.user, self.geodb.passwd)
            uri.setDataSource(schema, tablename, geom, "", pk)

            options = {}
            options['overwrite'] = True
            if singleGeom:
                options['forceSinglePartGeometryType'] = True

            if isinstance(source, basestring):
                layer = QgsVectorLayer(source, layerName, "ogr")
                if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer:
                    layer.deleteLater()
                    raise WrongLayerFileError("Error reading file {} or it is not a valid vector layer file".format(source))
            else:
                layer = source
                if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer:
                    raise WrongLayerFileError("Layer '%s' is not valid or is not a vector layer".format(layer.name()))

            ret, errMsg = QgsVectorLayerImport.importLayer(layer, uri.uri(), providerName, layer.crs(), False, False, options)
            if ret != 0:
                raise Exception(errMsg)
        else:
            if isinstance(source, QgsMapLayer):
                source = source.source()

            args = ["shp2pgsql", "-a"]
            if singleGeom:
                args.append("-S")
            args.extend([source, schema + "." + tablename])
            if os.name == 'nt':
                cmdline = subprocess.list2cmdline(args)
                data = None

                p = os.popen3(cmdline)
                data = p[1].read()

                cursor = self.geodb.con.cursor()
                newcommand = re.compile(";$", re.MULTILINE)

                # split the commands
                cmds = newcommand.split(data)
                for cmd in cmds[:-1]:
                    # run SQL commands within current DB connection
                    self.geodb._exec_sql(cursor, cmd)
                data = cmds[-1]

                self.geodb.con.commit()

                if data is None or len(data) == 0:
                    raise Exception("".join(p[2].readlines()))
            else:
                # start shp2pgsql as subprocess
                p = subprocess.Popen(args=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                # read the output while the process is running
                data = ''
                cursor = self.geodb.con.cursor()
                newcommand = re.compile(";$", re.MULTILINE)
                while p.poll() == None:
                    data += p.stdout.read()

                    # split the commands
                    cmds = newcommand.split(data)
                    for cmd in cmds[:-1]:
                        # run SQL commands within current DB connection
                        self.geodb._exec_sql(cursor, cmd)
                    data = cmds[-1]

                # commit!
                self.db.con.commit()

                if p.returncode != 0:
                    raise Exception(p.stderr.readlines().join("\n"))