Esempio n. 1
0
    def testMapToolChange(self):

        if isinstance(IFACE, QgisStubInterface):
            advDigitizeWidget = QgsAdvancedDigitizingDockWidget(CANVAS, CANVAS)

            if (version.parse(QtCore.qVersion()) < version.parse("5.11.0")):
                toolMode = QgsMapToolCapture.CaptureLine
            else:
                toolMode = QgsMapToolCapture.CaptureMode.CaptureLine

            captureMapTool = QgsMapToolCapture(CANVAS, advDigitizeWidget,
                                               toolMode)

            self.coordinator.reset()
            CANVAS.setMapTool(QgsMapToolPan(CANVAS))
            self.assertFalse(self.dw.addFeatureButton.isEnabled())
            QTest.keyClicks(self.dw.inLeft, "8")
            self.assertFalse(self.dw.addFeatureButton.isEnabled())

            CANVAS.setMapTool(captureMapTool)

            self.assertTrue(self.dw.addFeatureButton.isEnabled())

            CANVAS.setMapTool(QgsMapToolPan(CANVAS))
            self.assertFalse(self.dw.addFeatureButton.isEnabled())

            self.coordinator.reset()
            self.assertFalse(self.dw.addFeatureButton.isEnabled())
            CANVAS.setMapTool(captureMapTool)
            # add Feature Button should not be enabled when there is no input
            self.assertFalse(self.dw.addFeatureButton.isEnabled())
        else:
            self.skipTest("not yet implemented for QGIS GUI tests")
Esempio n. 2
0
    def connectButtons(self):
        """
        Connect the default buttons in the interface. Zoom, pan, etc
        """
        def connectAction(action, tool):
            action.toggled.connect(partial(self.setMapTool, tool))

        def cursor(name):
            pix = QPixmap(name)
            pix = pix.scaled(QSize(24, 24))
            return QCursor(pix)

        self.zoomInTool = QgsMapToolZoom(self.canvas, False)
        self.zoomOutTool = QgsMapToolZoom(self.canvas, True)
        self.panTool = QgsMapToolPan(self.canvas)
        self.infoTool = InfoTool(self.canvas)

        self.infoTool.setAction(self.actionInfo)
        self.zoomInTool.setAction(self.actionZoom_In)
        self.zoomOutTool.setAction(self.actionZoom_Out)
        self.panTool.setAction(self.actionPan)

        connectAction(self.actionZoom_In, self.zoomInTool)
        connectAction(self.actionZoom_Out, self.zoomOutTool)
        connectAction(self.actionPan, self.panTool)
        connectAction(self.actionInfo, self.infoTool)

        self.zoomInTool.setCursor(cursor(':/icons/in'))
        self.zoomOutTool.setCursor(cursor(':/icons/out'))
        self.infoTool.setCursor(cursor(':/icons/select'))

        self.actionRaster.triggered.connect(self.toggle_raster_layers)
        self.actionHome.triggered.connect(self.homeview)
 def __init__(self, inp_sparql, triplestoreconf, endpointIndex):
     super(QDialog, self).__init__()
     self.setupUi(self)
     self.inp_sparql = inp_sparql
     self.triplestoreconf = triplestoreconf
     self.endpointIndex = endpointIndex
     self.vl = QgsVectorLayer("Point", "temporary_points", "memory")
     self.map_canvas = QgsMapCanvas(self)
     self.layerExtentOrBBOX = False
     self.map_canvas.setMinimumSize(500, 475)
     self.map_canvas.move(0, 30)
     self.nominatimmap = {}
     actionPan = QAction("Pan", self)
     actionPan.setCheckable(True)
     actionPan.triggered.connect(self.pan)
     self.toolPan = QgsMapToolPan(self.map_canvas)
     self.toolPan.setAction(actionPan)
     uri = "url=http://a.tile.openstreetmap.org/{z}/{x}/{y}.png&zmin=0&type=xyz"
     self.mts_layer = QgsRasterLayer(uri, 'OSM', 'wms')
     if not self.mts_layer.isValid():
         print("Layer failed to load!")
     self.rect_tool = RectangleMapTool(self.map_canvas)
     self.circ_tool = CircleMapTool(self.map_canvas, 1)
     self.poly_tool = PolygonMapTool(self.map_canvas)
     self.map_canvas.setMapTool(self.rect_tool)
     self.map_canvas.setExtent(self.mts_layer.extent())
     self.map_canvas.setLayers([self.vl, self.mts_layer])
     self.map_canvas.setCurrentLayer(self.mts_layer)
     self.pan()
     self.selectCircle.hide()
     self.geocodeSearch = NominatimText(self, self.nominatimmap,
                                        self.map_canvas)
     self.move(120, 0)
     self.crsdialog = QgsProjectionSelectionWidget(self)
     self.crsdialog.move(160, 540)
     self.crsdialog.resize(331, 30)
     self.crsdialog.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
     self.crsdialog.show()
     self.nominatimurl = 'https://nominatim.openstreetmap.org/search?format=json&q={address}'
     self.panButton.clicked.connect(self.pan)
     self.selectCircle.clicked.connect(self.selectcircle)
     self.selectPolygon.clicked.connect(self.selectpolygon)
     self.selectButton.clicked.connect(self.selectarea)
     self.zoomIn.clicked.connect(self.map_canvas.zoomIn)
     self.zoomOut.clicked.connect(self.map_canvas.zoomOut)
     self.b2.clicked.connect(self.setBBOXExtentQuery)
     self.searchButton.hide()
     self.searchPlace.hide()
     self.geocodeSearch.hide()
     layers = QgsProject.instance().layerTreeRoot().children()
     for layer in layers:
         self.chooseBBOXLayer.addItem(layer.name())
     self.searchButton.clicked.connect(self.geocode)
     self.b1.clicked.connect(self.setBBOXInQuery)
Esempio n. 4
0
    def __init__(self):
        QMainWindow.__init__(self)

        # creating map canvas, which draws the maplayers
        # setting up features like canvas color
        self.canvas = QgsMapCanvas()
        self.canvas.setMinimumSize(550, 700)
        self.canvas.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)

        # Qmainwindow requires a central widget. Canvas is placed
        self.setCentralWidget(self.canvas)

        # creating each desired action
        self.actionGet = QAction("Return polygon and close", self)
        self.actionPan = QAction("Pan tool", self)
        self.actionDraw = QAction("Polygon tool", self)
        self.actionConnect = QAction("Connect polygon", self)
        self.actionClear = QAction("Clear", self)
        self.actionCancel = QAction("Cancel and close", self)

        # these two function as on/off. the rest are clickable
        self.actionPan.setCheckable(True)
        self.actionDraw.setCheckable(True)

        # when actions are clicked, do corresponding function
        self.actionPan.triggered.connect(self.pan)
        self.actionDraw.triggered.connect(self.draw)
        self.actionClear.triggered.connect(self.clear)
        self.actionGet.triggered.connect(self.finishedSelection)
        self.actionConnect.triggered.connect(self.connect)
        self.actionCancel.triggered.connect(self.cancel)

        # toolbar at the top of the screen: houses actions as buttons
        # change order here to change their placement on toolbar
        self.toolbar = self.addToolBar("Canvas actions")
        self.toolbar.setContextMenuPolicy(Qt.PreventContextMenu)
        self.toolbar.setMovable(False)
        self.toolbar.addAction(self.actionGet)
        self.toolbar.addAction(self.actionPan)
        self.toolbar.addAction(self.actionDraw)
        self.toolbar.addAction(self.actionConnect)
        self.toolbar.addAction(self.actionClear)
        self.toolbar.addAction(self.actionCancel)

        # link actions to premade map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(self.actionPan)
        self.toolDraw = PolygonMapTool(self.canvas)
        self.toolDraw.setAction(self.actionDraw)

        # set draw tool by default
        self.draw()
    def __init__(self, geogiglayer, fid):
        super(VersionViewerDialog, self).__init__(iface.mainWindow())
        self.geogiglayer = geogiglayer
        self.fid = fid
        self.layer = None
        self.setupUi(self)

        self.listWidget.itemClicked.connect(self.commitClicked)

        horizontalLayout = QHBoxLayout()
        horizontalLayout.setSpacing(0)
        horizontalLayout.setMargin(0)
        self.mapCanvas = QgsMapCanvas()
        self.mapCanvas.setCanvasColor(Qt.white)
        horizontalLayout.addWidget(self.mapCanvas)
        self.mapWidget.setLayout(horizontalLayout)
        self.panTool = QgsMapToolPan(self.mapCanvas)
        self.mapCanvas.setMapTool(self.panTool)

        path = geogiglayer.layername + "/" + fid
        ids, commits = geogiglayer.server.log(geogiglayer.user,
                                              geogiglayer.repo, "master", path)
        if commits:
            for commit in commits.values():
                item = CommitListItem(commit, geogiglayer, fid)
                self.listWidget.addItem(item)
        else:
            raise GeogigError("The selected feature is not versioned yet")
    def initGui(self):
        layout = QVBoxLayout()
        self.tab = QTabWidget()
        self.table = QTableView()

        self.setLayout(layout)
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        settings = QSettings()
        self.canvas.enableAntiAliasing(
            settings.value("/qgis/enable_anti_aliasing", False, type=bool))
        self.canvas.useImageToRender(
            settings.value("/qgis/use_qimage_to_render", False, type=bool))
        self.canvas.mapSettings().setDestinationCrs(self.crs)
        action = settings.value("/qgis/wheel_action", 0, type=float)
        zoomFactor = settings.value("/qgis/zoom_factor", 2, type=float)
        self.canvas.setWheelAction(QgsMapCanvas.WheelAction(action),
                                   zoomFactor)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)

        execute(self.createLayers)

        model = GeomDiffTableModel(self.data)
        self.table.setModel(model)
        self.table.resizeColumnsToContents()
        self.table.resizeRowsToContents()
        self.tab.addTab(self.canvas, "Map view")
        self.tab.addTab(self.table, "Table view")
        layout.addWidget(self.tab)

        self.resize(600, 500)
        self.setWindowTitle("Geometry comparison")
Esempio n. 7
0
    def load_inputs(self):
        if 'soil_layer' in self.input_layers:
            QgsMapLayerRegistry.instance().removeMapLayer(
                self.input_layers['soil_layer'])
        if 'lulc_layer' in self.input_layers:
            QgsMapLayerRegistry.instance().removeMapLayer(
                self.input_layers['lulc_layer'])
        if 'slope_layer' in self.input_layers:
            QgsMapLayerRegistry.instance().removeMapLayer(
                self.input_layers['slope_layer'])
        path = self.folder_path.text()
        self.input_layers['soil_layer'] = self.iface.addVectorLayer(
            os.path.join(path, 'Soil.shp'), 'Soil Cover', 'ogr')
        self.input_layers['lulc_layer'] = self.iface.addVectorLayer(
            os.path.join(path, 'LULC.shp'), 'Land-Use-Land-Cover', 'ogr')
        self.input_layers['slope_layer'] = self.iface.addRasterLayer(
            os.path.join(path, 'Slope.tif'), 'Slope')
        self.iface.mapCanvas().setExtent(
            self.input_layers['slope_layer'].extent())

        if os.path.exists(os.path.join(path, 'Rainfall.csv')):
            self.rainfall_csv_filepath.setText(
                os.path.join(path, 'Rainfall.csv'))
        et0_dict = list(csv.DictReader(open(os.path.join(path, 'ET0.csv'))))[0]
        for month, i in zip([
                'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'Jan', 'Feb',
                'Mar', 'Apr', 'May'
        ], range(12)):
            self.ET0.setItem(i, 0, QtGui.QTableWidgetItem(et0_dict[month]))
        #Reset picking mode for any newly loaded dataset
        self.picking_mode = False
        self.pick_point_button.setText('Pick a Point')
        self.iface.mapCanvas().setMapTool(QgsMapToolPan(
            self.iface.mapCanvas()))
Esempio n. 8
0
    def unload(self):
        if self.prevTool and self.prevTool != self.swipe_tool:
            self.map_canvas.setMapTool(self.prevTool)
        else:
            self.map_canvas.setMapTool(QgsMapToolPan(self.iface.mapCanvas()))

        del self.tool_bar
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.thematic_file_classes = None

        self.map_tool_pan = QgsMapToolPan(self.render_widget.canvas)
        self.render_widget.canvas.setMapTool(self.map_tool_pan, clean=True)
Esempio n. 10
0
 def unload(self):
     if self.prevTool and self.prevTool != self.tool:
         self.canvas.setMapTool(self.prevTool)
     else:
         self.canvas.setMapTool(QgsMapToolPan(self.iface.mapCanvas()))
     self.iface.removeToolBarIcon(self.widget_action)
     del self.widget_action
Esempio n. 11
0
 def reject(self):
     scene = define._canvas.scene()
     scene.removeItem(self.CaptureTHRCoordTool.rubberBand)
     scene.removeItem(self.CaptureENDCoordTool.rubberBand)
     #         self.CaptureTHRCoordTool.rubberBand.hide()
     #         self.CaptureENDCoordTool.rubberBand.hide()
     define._canvas.setMapTool(QgsMapToolPan(define._canvas))
     self.reject()
Esempio n. 12
0
    def __init__(self, parent=None, iface=None):
        """Constructor for import dialog.

        :param parent: Optional widget to use as parent
        :type parent: QWidget

        :param iface: An instance of QGisInterface
        :type iface: QGisInterface
        """
        QDialog.__init__(self, parent)
        self.parent = parent
        self.setupUi(self)

        self.setWindowTitle(self.tr('InaSAFE OpenStreetMap Downloader'))

        self.iface = iface
        self.buildings_url = 'http://osm.linfiniti.com/buildings-shp'
        self.building_points_url = \
            'http://osm.linfiniti.com/building-points-shp'
        self.roads_url = 'http://osm.linfiniti.com/roads-shp'

        self.help_context = 'openstreetmap_downloader'
        # creating progress dialog for download
        self.progress_dialog = QProgressDialog(self)
        self.progress_dialog.setAutoClose(False)
        title = self.tr('InaSAFE OpenStreetMap Downloader')
        self.progress_dialog.setWindowTitle(title)
        # Set up context help
        help_button = self.button_box.button(QtGui.QDialogButtonBox.Help)
        help_button.clicked.connect(self.show_help)

        self.show_info()

        # set up the validator for the file name prefix
        expression = QRegExp('^[A-Za-z0-9-_]*$')
        validator = QRegExpValidator(expression, self.filename_prefix)
        self.filename_prefix.setValidator(validator)

        # Set Proxy in webpage
        proxy = get_proxy()
        self.network_manager = QNetworkAccessManager(self)
        if proxy is not None:
            self.network_manager.setProxy(proxy)
        self.restore_state()

        # Setup the rectangle map tool
        self.canvas = iface.mapCanvas()
        self.rectangle_map_tool = \
            RectangleMapTool(self.canvas)
        self.rectangle_map_tool.rectangle_created.connect(
            self.update_extent_from_rectangle)
        self.button_extent_rectangle.clicked.connect(
            self.drag_rectangle_on_map_canvas)

        # Setup pan tool
        self.pan_tool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.pan_tool)
        self.update_extent_from_map_canvas()
Esempio n. 13
0
 def close(self):
     scene = define._canvas.scene()
     scene.removeItem(self.CaptureTHRCoordTool.rubberBandClick)
     scene.removeItem(self.CaptureENDCoordTool.rubberBandClick)
     scene.removeItem(self.bearingTool.rubberBand)
     scene.removeItem(self.distanceMeasureTool.rubberBand)
     #         self.CaptureTHRCoordTool.rubberBand.hide()
     #         self.CaptureENDCoordTool.rubberBand.hide()
     define._canvas.setMapTool(QgsMapToolPan(define._canvas))
 def saveCanvasAreasToAvoidLayer(self):
     name = "avoid_areas"
     CanvasLayerSaver(
         name,
         self.areasToAvoid,
         crs=self.canvas.mapSettings().destinationCrs(),
         color=AVOID_AREA_COLOR,
         style=AVOID_AREA_STYLE,
     )
     iface.mapCanvas().setMapTool(QgsMapToolPan(iface.mapCanvas()))
Esempio n. 15
0
 def savePatrolAreaLayer(self):
     name = "patrol_area"
     CanvasLayerSaver(
         name,
         [self.patrolArea],
         crs=self.canvas.mapSettings().destinationCrs(),
         color=PATROL_AREA_COLOR,
         style=PATROL_AREA_STYLE,
     )
     iface.mapCanvas().setMapTool(QgsMapToolPan(iface.mapCanvas()))
Esempio n. 16
0
 def manualEvent(self, index):
     QgisHelper.ClearRubberBandInCanvas(define._canvas)
     self.manualPolygon = None
     if index != 0:
         self.toolSelectByPolygon = RubberBandPolygon(define._canvas)
         define._canvas.setMapTool(self.toolSelectByPolygon)
         self.connect(self.toolSelectByPolygon, SIGNAL("outputResult"), self.outputResultMethod)
     else:
         self.mapToolPan = QgsMapToolPan(define._canvas)
         define._canvas.setMapTool(self.mapToolPan )
Esempio n. 17
0
    def __init__(self, conflicts):
        super(ConflictDialog,
              self).__init__(None,
                             Qt.WindowSystemMenuHint | Qt.WindowTitleHint)
        self.solved = False
        self.resolvedConflicts = {}
        self.conflicts = conflicts
        self.setupUi(self)

        self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint
                            | Qt.WindowMinMaxButtonsHint)

        self.zoomButton.clicked.connect(self.zoomToFullExtent)
        self.solveButton.clicked.connect(self.solve)
        self.conflictsTree.itemClicked.connect(self.treeItemClicked)
        self.attributesTable.cellClicked.connect(self.cellClicked)
        self.solveAllLocalButton.clicked.connect(self.solveAllLocal)
        self.solveAllRemoteButton.clicked.connect(self.solveAllRemote)
        self.solveLocalButton.clicked.connect(self.solveLocal)
        self.solveRemoteButton.clicked.connect(self.solveRemote)

        self.showRemoteCheck.stateChanged.connect(self.showGeoms)
        self.showLocalCheck.stateChanged.connect(self.showGeoms)

        self.lastSelectedItem = None
        self.currentPath = None
        self.currentConflict = None
        self.theirsLayer = None
        self.oursLayer = None

        settings = QSettings()
        horizontalLayout = QHBoxLayout()
        horizontalLayout.setSpacing(0)
        horizontalLayout.setMargin(0)
        self.mapCanvas = QgsMapCanvas()
        self.mapCanvas.setCanvasColor(Qt.white)
        self.mapCanvas.enableAntiAliasing(
            settings.value("/qgis/enable_anti_aliasing", False, type=bool))
        self.mapCanvas.useImageToRender(
            settings.value("/qgis/use_qimage_to_render", False, type=bool))
        self.mapCanvas.mapRenderer().setProjectionsEnabled(True)
        action = settings.value("/qgis/wheel_action", 0, type=float)
        zoomFactor = settings.value("/qgis/zoom_factor", 2, type=float)
        self.mapCanvas.setWheelAction(QgsMapCanvas.WheelAction(action),
                                      zoomFactor)
        horizontalLayout.addWidget(self.mapCanvas)
        self.canvasWidget.setLayout(horizontalLayout)
        self.panTool = QgsMapToolPan(self.mapCanvas)
        self.mapCanvas.setMapTool(self.panTool)

        self.solveButton.setEnabled(False)
        self.solveLocalButton.setEnabled(False)
        self.solveRemoteButton.setEnabled(False)

        self.fillConflictsTree()
Esempio n. 18
0
 def set_point_coords(self, point, button):
     log("Set point coords")
     #TODO: Show a messagebar while tool is active, and then remove the bar when a point is chosen.
     self.point = point
     # Disable the choose point tool
     self.canvas.setMapTool(QgsMapToolPan(self.canvas))
     self.show()
     self.point = self.canvas.getCoordinateTransform().toMapCoordinates(self.canvas.mouseLastXY())
     log("Chose point: {}, {}.".format(self.point.x(), self.point.y()))
     self.point_x.setText("{:.8f}".format(self.point.x()))
     self.point_y.setText("{:.8f}".format(self.point.y()))
    def initGui(self):
        layout = QVBoxLayout()
        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)

        self.history = HistoryTree(self.dialog)
        self.history.updateContent(self.server, self.user, self.repo, self.graph, self.layer)
        self.historyWithFilter = HistoryTreeWrapper(self.history)
        if self.simplifyLog:
            self.historyWithFilter.simplify(True)
        splitter.addWidget(self.historyWithFilter)
        self.tabWidget = QTabWidget()
        self.tabCanvas = QWidget()
        tabLayout = QVBoxLayout()
        tabLayout.setMargin(0)        
        self.canvas = QgsMapCanvas(self.tabCanvas)
        self.canvas.setCanvasColor(Qt.white)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)
        tabLayout.addWidget(self.canvas)
        self.labelNoChanges = QLabel("This commit doesn't change any geometry")
        self.labelNoChanges.setAlignment(Qt.AlignCenter)
        self.labelNoChanges.setVisible(False)
        tabLayout.addWidget(self.labelNoChanges)
        self.tabCanvas.setLayout(tabLayout)
        self.summaryTextBrowser = QTextBrowser()
        self.summaryTextBrowser.setOpenLinks(False)
        self.summaryTextBrowser.anchorClicked.connect(self.summaryTextBrowserAnchorClicked)
        self.tabWidget.addTab(self.summaryTextBrowser, "Commit Summary")
        self.tabWidget.addTab(self.tabCanvas, "Map")
        tabLayout = QVBoxLayout()
        tabLayout.setMargin(0)
        self.tabDiffViewer = QWidget()
        self.diffViewer = DiffViewerWidget({})
        tabLayout.addWidget(self.diffViewer)
        self.tabDiffViewer.setLayout(tabLayout)
        self.tabWidget.addTab(self.tabDiffViewer, "Attributes")
        splitter.addWidget(self.tabWidget)
        self.label = QTextBrowser()
        self.label.setVisible(False)
        splitter.addWidget(self.label)
        self.tabWidget.setCurrentWidget(self.tabDiffViewer)

        layout.addWidget(splitter)
        self.setLayout(layout)

        exportDiffButton = QPushButton("Export this commit's DIFF for all layers")
        exportDiffButton.clicked.connect(self.exportDiffAllLayers)

        layout.addWidget(exportDiffButton)
        self.label.setMinimumHeight(self.tabWidget.height())        
        self.setWindowTitle("Repository history")
Esempio n. 20
0
    def setupUi(self):
        self.setObjectName("mirrormap")

        gridLayout = QGridLayout(self)
        gridLayout.setContentsMargins(0, 0, gridLayout.verticalSpacing(),
                                      gridLayout.verticalSpacing())

        self.canvas = QgsMapCanvas(self)
        self.canvas.setCanvasColor(QColor(255, 255, 255))
        settings = QSettings()
        gridLayout.addWidget(self.canvas, 0, 0, 1, 5)

        self.addLayerBtn = QToolButton(self)
        # self.addLayerBtn.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        # self.addLayerBtn.setText("Add current layer")
        self.addLayerBtn.setIcon(GuiUtils.get_icon("add.png"))

        self.addLayerBtn.clicked.connect(self.tool_add_layer)
        gridLayout.addWidget(self.addLayerBtn, 1, 0, 1, 1)

        self.delLayerBtn = QToolButton(self)
        # self.delLayerBtn.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        # self.delLayerBtn.setText("Remove current layer")
        self.delLayerBtn.setIcon(GuiUtils.get_icon("remove.png"))
        self.delLayerBtn.clicked.connect(self.tool_remove_layer)
        gridLayout.addWidget(self.delLayerBtn, 1, 1, 1, 1)

        self.renderCheck = QCheckBox("Render", self)
        self.renderCheck.toggled.connect(self.toggleRender)
        self.renderCheck.setChecked(True)
        gridLayout.addWidget(self.renderCheck, 1, 2, 1, 1)

        self.scaleFactorLabel = QLabel(self)
        self.scaleFactorLabel.setText("Scale factor:")
        self.scaleFactorLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        gridLayout.addWidget(self.scaleFactorLabel, 1, 3, 1, 1)
        self.scaleFactor = QDoubleSpinBox(self)
        self.scaleFactor.setMinimum(0.0)
        self.scaleFactor.setMaximum(1000.0)
        self.scaleFactor.setDecimals(3)
        self.scaleFactor.setValue(1)
        self.scaleFactor.setObjectName("scaleFactor")
        self.scaleFactor.setSingleStep(.05)
        gridLayout.addWidget(self.scaleFactor, 1, 4, 1, 1)
        self.scaleFactor.valueChanged.connect(self.onExtentsChanged)

        # Add a default pan tool
        self.toolPan = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.toolPan)

        self.scaleFactor.valueChanged.connect(self.onExtentsChanged)
        self.set_iface(self.iface)
 def setPolygonDrawingMapTool(self, checked):
     if checked:
         self.prevMapTool = iface.mapCanvas().mapTool()
         self.mapToolDrawPolygon = DrawPolygonMapTool(iface.mapCanvas())
         self.mapToolDrawPolygon.polygonSelected.connect(
             self.setAreasToAvoidFromPolygon)
         iface.mapCanvas().setMapTool(self.mapToolDrawPolygon)
     else:
         try:
             iface.mapCanvas().setMapTool(self.prevMapTool)
         except Exception as e:
             logging.error(e)
             iface.mapCanvas().setMapTool(QgsMapToolPan(iface.mapCanvas()))
Esempio n. 22
0
 def set_point_coords(self, point, button):
     log("Set point coords")
     #TODO: Show a messagebar while tool is active, and then remove the bar when a point is chosen.
     self.point = point
     # Disable the choose point tool
     self.canvas.setMapTool(QgsMapToolPan(self.canvas))
     # Don't reset_tab_on_show as it would lead to return to first tab after
     # using the point chooser
     self.reset_tab_on_showEvent = False
     self.show()
     self.reset_tab_on_showEvent = True
     self.point = self.canvas.getCoordinateTransform().toMapCoordinates(self.canvas.mouseLastXY())
     log("Chose point: {}, {}.".format(self.point.x(), self.point.y()))
     self.point_widget.point_x.setText("{:.8f}".format(self.point.x()))
     self.point_widget.point_y.setText("{:.8f}".format(self.point.y()))
Esempio n. 23
0
 def activate_mapTool(self):
     if self.picking_mode:
         self.iface.mapCanvas().setMapTool(
             QgsMapToolPan(self.iface.mapCanvas()))
         self.pick_point_button.setText('Pick a Point')
         self.picking_mode = False
     else:
         if (self.input_layers['soil_layer'] is None
                 or self.input_layers['lulc_layer'] is None
                 or self.input_layers['slope_layer'] is None):
             return
         self.pointTool = PointTool(self.iface.mapCanvas(), self)
         self.iface.mapCanvas().setMapTool(self.pointTool)
         self.pick_point_button.setText('Disable picking')
         self.picking_mode = True
Esempio n. 24
0
    def setupUi(self):
        gridLayout = QGridLayout(self)
        gridLayout.setContentsMargins(0, 0, 0, 0)
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(QColor(255, 255, 255))
        self.canvas.setStyleSheet("border: 0px;")
        settings = QSettings()
        self.canvas.enableAntiAliasing(
            settings.value("/qgis/enable_anti_aliasing", False, type=bool))
        self.setMinimumSize(15, 15)
        # action pan and zoom
        self.default_point_tool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.default_point_tool, clean=True)

        gridLayout.addWidget(self.canvas)
Esempio n. 25
0
    def onRightClick(self, position):  # used to quit the current action
        # print "right click", position
        mapPos = self.canvas.getCoordinateTransform().toMapCoordinates(
            position["x"], position["y"])
        newPoints = [[mapPos.x(), mapPos.y()]]
        # if newPoints == self.lastClicked: return # sometimes a strange "double click" is given

        # self.rubberband.reset(self.polygon)
        # self.rubberband.reset(QGis.Point)
        # print "setting rubberband", mapPos.x(),mapPos.y()
        self.rubberband.addPoint(QgsPoint(mapPos.x(), mapPos.y()))
        self.toolPan = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.toolPan)
        # create new vlayer ???
        self.angles(mapPos.x(), mapPos.y())
        self.tool = None
Esempio n. 26
0
 def _radioButtonsPatrolChanged(self):
     self.populatePatrolLayerSelector()
     self.comboPatrolAreaLayers.setEnabled(
         self.radioPatrolAreaLayer.isChecked())
     self.btnPatrolAreaCanvas.setEnabled(
         self.radioPatrolAreaPolygon.isChecked())
     self.btnPatrolAreaClear.setEnabled(
         self.radioPatrolAreaPolygon.isChecked())
     self.btnPatrolAreaSave.setEnabled(
         self.radioPatrolAreaPolygon.isChecked())
     if self.radioPatrolAreaPolygon.isChecked():
         if self.patrolArea is not None:
             self.patrolFootprint.setToGeometry(self.patrolArea)
     else:
         iface.mapCanvas().setMapTool(QgsMapToolPan(iface.mapCanvas()))
         self.patrolFootprint.reset(QgsWkbTypes.PolygonGeometry)
 def _radioButtonsChanged(self):
     self.populateLayerSelector()
     self.comboAreasToAvoidLayers.setEnabled(self.radioAreasToAvoidLayer.isChecked())
     self.btnAreasToAvoidFromCanvas.setEnabled(
         self.radioAreasToAvoidPolygon.isChecked()
     )
     self.btnAreasToAvoidClear.setEnabled(self.radioAreasToAvoidPolygon.isChecked())
     self.btnAreasToAvoidSave.setEnabled(self.radioAreasToAvoidPolygon.isChecked())
     if self.radioAreasToAvoidPolygon.isChecked():
         if self.areasToAvoid:
             for geometry in self.areasToAvoid:
                 footprint = self.createFootprintArea()
                 footprint.setToGeometry(geometry)
                 self.areasToAvoidFootprint.append(footprint)
     else:
         iface.mapCanvas().setMapTool(QgsMapToolPan(iface.mapCanvas()))
         for footprint in self.areasToAvoidFootprint:
             footprint.reset(QgsWkbTypes.PolygonGeometry)
Esempio n. 28
0
    def __init__(self, layerSet):
        QMainWindow.__init__(self)
        self.showFullScreen()
        self._canvas = GMapCanvas()
        self._canvas.setCanvasColor(Qt.white)
        self.setCentralWidget(self._canvas)

        self._layerSet = layerSet
        self._canvas.setLayerSet(layerSet)

        self._extent = self._layerSet.rawLayers[len(self._layerSet.rawLayers) -
                                                1].extent()
        self._canvas.setExtent(self._extent)

        self._toolPan = QgsMapToolPan(self._canvas)
        self.pan()

        self._layerDock = GAppLayerDocker(self.centralWidget(), layerSet,
                                          self._canvas)
        self.addDockWidget(Qt.LeftDockWidgetArea, self._layerDock)
Esempio n. 29
0
    def __init__(self, parent=None, layer_to_edit=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.layer_to_edit = layer_to_edit
        self.aoi_drawn = []
        self.highlight_tile = None

        self.setup_gui()

        # init render widget
        self.render_widget.canvas.setDestinationCrs(
            self.layer_to_edit.qgs_layer.crs())
        self.render_widget.canvas.setLayers([self.layer_to_edit.qgs_layer])
        self.render_widget.canvas.setExtent(self.layer_to_edit.extent())
        self.render_widget.refresh()

        self.map_tool_pan = QgsMapToolPan(self.render_widget.canvas)
        self.render_widget.canvas.setMapTool(self.map_tool_pan, clean=True)

        # flags
        self.setWindowFlags(self.windowFlags() | Qt.WindowMinimizeButtonHint)
Esempio n. 30
0
    def __init__(self, server, user, repo, graph, layername):
        super(LayerExplorer, self).__init__(None)
        self.user = user
        self.server = server
        self.repo = repo
        self.layername = layername
        self.layer = None
        self.extent = None
        self.renderer = None
        self.graph = graph

        self.setupUi(self)

        self.history = HistoryTree(self)
        self.history.updateContent(self.server, self.user, self.repo,
                                   self.graph, self.layername)
        historyTreeWrapper = HistoryTreeWrapper(self.history)
        layout = QVBoxLayout()
        layout.setMargin(0)
        layout.addWidget(historyTreeWrapper)
        self.historyWidget.setLayout(layout)
        layout = QVBoxLayout()
        layout.setMargin(0)
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)
        layout.addWidget(self.canvas)
        self.mapWidget.setLayout(layout)
        self.canvas.extentsChanged.connect(self.refreshLayer)

        self.history.currentItemChanged.connect(self.itemChanged)

        self.resize(900, 500)
        self.setWindowTitle("Layer Explorer [{}]".format(layername))
        self.setWindowFlags(Qt.Window)

        setCurrentWindow(self)

        self.bar = MessageBar(self.canvas)
Esempio n. 31
0
class FeatureOfInterestDefinerConfigurationWidget(StandardModuleConfigurationWidget):
    """A widget to configure the FeatureOfInterestDefiner Module."""

    def __init__(self, module, controller, parent=None):
        StandardModuleConfigurationWidget.__init__(self, module, controller, parent)
        self.foi_type = module.name
        #self.module = module
        self.setObjectName("FeatureOfInterestDefinerWidget")
        self.parent_widget = module
        # FIXME these modules don't exist
        self.path_png_icon = vistrails.packages.eo4vistrails.geoinf.visual.__path__[0]
        self.path_bkgimg = vistrails.packages.eo4vistrails.geoinf.visual.__path__[0]
        self.create_config_window()

    def create_config_window(self):
        """TO DO - add docstring"""
        self.setWindowTitle(self.foi_type)
        self.setMinimumSize(800, 850)
        self.center()
        self.mainLayout = QtGui.QVBoxLayout()
        self.setLayout(self.mainLayout)

        #set up Group Box for organising CRS of FOI
        self.crsGroupBox = QtGui.QGroupBox("Define Projection or Coordinate Reference System")
        self.crsLayout = QtGui.QHBoxLayout()
        self.crsProj4Label = QtGui.QLabel('SRS Proj4: ')
        self.crsTextAsProj4 = QtGui.QLineEdit('4326')
        self.crsChooseButton = QtGui.QPushButton('&Choose SRS')
        self.crsChooseButton.setAutoDefault(False)
        self.crsChooseButton.setToolTip('Choose a Spatial Reference System or Projection')

        self.crsLayout.addWidget(self.crsProj4Label)
        self.crsLayout.addWidget(self.crsTextAsProj4)
        self.crsLayout.addWidget(self.crsChooseButton)

        self.crsGroupBox.setLayout(self.crsLayout)

        #set up Group Box for getting coords of Bounding Box
        self.bbGroupBox = QtGui.QGroupBox("Define Area of Interest via a Bounding Box in units of SRS")
        self.bbLayout = QtGui.QHBoxLayout()

        self.bbMinXLabel = QtGui.QLabel('MinX/Left: ')
        self.bbMinYLabel = QtGui.QLabel('MinY/Bottom: ')
        self.bbMaxXLabel = QtGui.QLabel('MaxX/Right: ')
        self.bbMaxYLabel = QtGui.QLabel('MaxY/Top: ')

        self.bbMinXText = QtGui.QLineEdit('15')
        self.bbMinYText = QtGui.QLineEdit('-35')
        self.bbMaxXText = QtGui.QLineEdit('35')
        self.bbMaxYText = QtGui.QLineEdit('-20')

        self.bbToMapButton = QtGui.QPushButton('&To Map')
        self.bbToMapButton.setAutoDefault(False)
        self.bbToMapButton.setToolTip('Show Bounding Box on Map')

        self.bbLayout.addWidget(self.bbMinXLabel)
        self.bbLayout.addWidget(self.bbMinXText)
        self.bbLayout.addWidget(self.bbMinYLabel)
        self.bbLayout.addWidget(self.bbMinYText)
        self.bbLayout.addWidget(self.bbMaxXLabel)
        self.bbLayout.addWidget(self.bbMaxXText)
        self.bbLayout.addWidget(self.bbMaxYLabel)
        self.bbLayout.addWidget(self.bbMaxYText)
        self.bbLayout.addWidget(self.bbToMapButton)

        self.bbGroupBox.setLayout(self.bbLayout)

        #set up Group Box for getting text representation of a geometry
        self.asTxtGroupBox = QtGui.QGroupBox("Define Area of Interest via a WKT string in units of SRS")
        self.asTxtLayout = QtGui.QVBoxLayout()

        self.asTxtLabel = QtGui.QLabel('WKT String: ')
        self.asTxtText = QtGui.QTextEdit('')
        self.asTxtToMapButton = QtGui.QPushButton('&To Map')
        self.asTxtToMapButton.setAutoDefault(False)
        self.asTxtToMapButton.setToolTip('Show Bounding Box on Map')

        self.asTxtLayout.addWidget(self.asTxtLabel)
        self.asTxtLayout.addWidget(self.asTxtText)
        self.asTxtLayout.addWidget(self.asTxtToMapButton)

        self.asTxtGroupBox.setLayout(self.asTxtLayout)

        #set up Group Box for Map
        self.MapGroupBox = QtGui.QGroupBox("Map Viewer")
        self.MapLayout = QtGui.QHBoxLayout()
        #sz = QtCore.QSize(200, 300)
        #self.MapLayout.setGeometry(QtCore.QRect(300, 700, 780, 680))
        self.MapGroupBox.setLayout(self.MapLayout)

        ## create canvas
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(QtGui.QColor(200, 200, 255))
        #self.mainLayout.addWidget(self.canvas)

        # icons
        actionAddLayer = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionAddLayer.png"), "Add Layer", self)
        actionZoomIn = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionZoomIn.png"), "Zoom In", self)
        actionZoomOut = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionZoomOut.png"), "Zoom Out", self)
        actionPan = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionPan.png"), "Pan", self)
        actionIdentify = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionIdentify.png"), "Feature Information", self)

        # create toolbar
        self.toolbar = QtGui.QToolBar()  # "Canvas actions"
        self.toolbar.addAction(actionAddLayer)
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionPan)
        self.toolbar.addAction(actionIdentify)

        # create layer explorer pane
        self.explorer = QtGui.QDockWidget("Layers")
        self.explorer.resize(60, 100)
        #~self.explorerListWidget = QtGui.QListWidget()
        #~self.explorerListWidget.setObjectName("listWidget")
        #~self.explorer.setWidget(self.explorerListWidget)

        # create map tools
        self.toolPan = QgsMapToolPan(self.canvas,)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false == in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true == out
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolAOI = QgsMapTool(self.canvas)
        self.toolIdentify = GetFeatureInfoTool(self.canvas, self.gotFeatureForIdentification)
        self.toolIdentify.setAction(actionIdentify)

        # layerList explorer
        self.GroupBoxLyrExplorer = QtGui.QGroupBox("")
        self.vboxLyrExplorer = QtGui.QVBoxLayout()
        self.GroupBoxLyrExplorer.setLayout(self.vboxLyrExplorer)
        self.MapLayout.addWidget(self.GroupBoxLyrExplorer)
        self.label = QtGui.QLabel("")
        self.vboxLyrExplorer.addWidget(self.label)
        self.vboxLyrExplorer.addWidget(self.explorer)

        # toolbar and canvas layout
        self.GroupBoxToolBarMapCanvas = QtGui.QGroupBox("")
        self.vboxToolBarMapCanvas = QtGui.QVBoxLayout()
        self.vboxToolBarMapCanvas.setGeometry(QtCore.QRect(300, 700, 780, 680))
        self.GroupBoxToolBarMapCanvas.setLayout(self.vboxToolBarMapCanvas)
        self.MapLayout.addWidget(self.GroupBoxToolBarMapCanvas)
        self.vboxToolBarMapCanvas.addWidget(self.toolbar)
        self.vboxToolBarMapCanvas.addWidget(self.canvas)

        #global list to hold inputlayers list -> accessible for toggleLayer
        self.mylist = []

        #finalise/cancel buttons
        self.finishGroupBox = QtGui.QGroupBox("Finish")
        self.buttonLayout = QtGui.QHBoxLayout()
        self.finishGroupBox.setLayout(self.buttonLayout)
        self.buttonLayout.setGeometry(QtCore.QRect(300, 500, 780, 680))
        self.buttonLayout.setMargin(5)
        self.cancelButton = QtGui.QPushButton('&Cancel', self)
        self.cancelButton.setAutoDefault(False)
        self.cancelButton.setShortcut('Esc')
        self.buttonLayout.addStretch(1)  # force buttons to the right
        self.buttonLayout.addWidget(self.cancelButton)
        self.okButton = QtGui.QPushButton('&OK', self)
        self.okButton.setAutoDefault(False)
        self.buttonLayout.addWidget(self.okButton)
        self.connect(self.okButton,
                     QtCore.SIGNAL('clicked(bool)'),
                     self.okTriggered)
        self.connect(self.cancelButton,
                     QtCore.SIGNAL('clicked(bool)'),
                     self.close)

        self.mainLayout.addWidget(self.crsGroupBox)
        self.mainLayout.addWidget(self.bbGroupBox)
        self.mainLayout.addWidget(self.asTxtGroupBox)
        self.mainLayout.addWidget(self.MapGroupBox)
        self.mainLayout.addWidget(self.finishGroupBox)

        # set signals
        self.connect(self.crsChooseButton, QtCore.SIGNAL('clicked(bool)'), self.getSRS)
        self.connect(self.bbToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapBB)
        self.connect(self.asTxtToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapTxt)
        self.connect(actionAddLayer, QtCore.SIGNAL("activated()"), self.addLayer)
        self.connect(actionZoomIn, QtCore.SIGNAL("activated()"), self.zoomIn)
        self.connect(actionZoomOut, QtCore.SIGNAL("activated()"), self.zoomOut)
        self.connect(actionPan, QtCore.SIGNAL("activated()"), self.pan)
        self.connect(actionIdentify, QtCore.SIGNAL("triggered()"), self.identifyFeature)

        #load a backdrop layer
        self.mapCanvasLayers = []
        fname = self.path_bkgimg + '/bluemarblemerged.img'
        fileInfo = QtCore.QFileInfo(fname)
        baseName = fileInfo.baseName()
        self.bmLayer = QgsRasterLayer(fname,  baseName)
        QgsMapLayerRegistry.instance().addMapLayer(self.bmLayer)
        self.cl = QgsMapCanvasLayer(self.bmLayer)
        self.mapCanvasLayers.append(self.cl)
        # Set extent to the extent of our layer
        self.canvas.setExtent(self.bmLayer.extent())
        self.canvas.enableAntiAliasing(True)
        self.canvas.freeze(False)
        self.canvas.setLayerSet(self.mapCanvasLayers)
        self.canvas.refresh()

        #now, add a container layer for our text based/ digitised or selected geoms
        self.addMemoryLayer()

        #self.update()

    def center(self):
        """TO DO - add docstring"""
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)

    def getSRS(self):
        # retruns the description and proj4 string of the chosen SRS, from the SRSDialog
        srsdlg = SRSChooserDialog("Choose SRS")
        if srsdlg.exec_():
            self.crsTextAsProj4.setText(srsdlg.getProjection())

    def bbToMapBB(self):
        self.bbToMap(fullWkt=False)

    def bbToMapTxt(self):
        self.bbToMap(fullWkt=True)

    def bbToMap(self, fullWkt=False):
        '''takes bounding box coords and puts them on the map'''
        #if self.foi_type == "AreaOfInterestDefiner":
        if not fullWkt:
            ix = self.bbMinXText.text()
            iy = self.bbMinYText.text()
            ax = self.bbMaxXText.text()
            ay = self.bbMaxYText.text()

            wkt = "POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))" % \
                  (ix,  iy,  ix,  ay,  ax,  ay,  ax,  iy,  ix,  iy)
        else:
            wkt = self.asTxtText.toPlainText()
        try:
            errnum = 0
            geom = QgsGeometry().fromWkt(wkt)
            print "gotGeom"
            if self.foi_type == "AreaOfInterestDefiner" and geom.type() != 2:
                errnum = 1
            elif self.foi_type == "LineOfInterestDefiner" and geom.type() != 1:
                errnum = 1
            elif self.foi_type == "PointOfInterestDefiner" and geom.type() != 0:
                errnum = 1
            else:
                print "attempting to add geometry to mem layer"
                self.addGeomToMemoryLayer(geom)

            if errnum == 1:
                raise ModuleError(self, "Incorrect Geometry Type chosen")
        except:
            raise ModuleError(self, "Could not generate Geometry from text provided")
        #else:
            #print "Cannot create a Bounding box feature on a line or point layer"
        #add to map

    #map tool functions
    def addLayer(self):
        """TO DO: Add doc string"""
        fileName = QtGui.QFileDialog.getOpenFileName(
            parent=None,
            caption="Select Vector Overlay Layer",
            filter="Vector Files (*.shp *.geojson *.gml)")

        print fileName
        info = QtCore.QFileInfo(fileName)
        print info.filePath()
        print info.completeBaseName()
        # create layer
        layer = QgsVectorLayer(info.filePath(), info.completeBaseName(),  "ogr")

        if not layer.isValid():
            print "invalid layer"
            return

        # add layer to the registry
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        # set extent to the extent of our layer
        #self.canvas.setExtent(layer.extent())

        # set the map canvas layer set
        cl = QgsMapCanvasLayer(layer)
        self.mapCanvasLayers.insert(len(self.mapCanvasLayers) - 2, cl)
        #layers = [cl]
        self.canvas.setLayerSet(self.mapCanvasLayers)
        print "added Layer"

    def addMemoryLayer(self):
        '''Adds a layer to contain the feature defined by a bounding box, wkt,
        digitised poly|line|point or selection from other layer.
        '''
        foi_type = self.foi_type.lower()
        if foi_type == 'areaofinterestdefiner':
            layer = QgsVectorLayer("Polygon", "Area of Interest",  "memory")
        if foi_type == 'lineofinterestdefiner':
            layer = QgsVectorLayer("Linestring", "Line of Interest",  "memory")
        if foi_type == 'pointofinterestdefiner':
            layer = QgsVectorLayer("Point", "Point of Interest",  "memory")

        if foi_type == 'areaofinterestdefiner':
            sym = QgsSymbol(QGis.Polygon)
            sym.setColor(QtCore.Qt.black)
            sym.setFillColor(QtCore.Qt.green)
            sym.setFillStyle(QtCore.Qt.Dense6Pattern)
            sym.setLineWidth(0.5)
            sr = QgsSingleSymbolRenderer(QGis.Polygon)
        if foi_type == 'lineofinterestdefiner':
            sym = QgsSymbol(QGis.Line)
            sym.setColor(QtCore.Qt.black)
            sym.setFillColor(QtCore.Qt.green)
            sym.setFillStyle(QtCore.Qt.SolidPattern)
            sym.setLineWidth(0.5)
            sr = QgsSingleSymbolRenderer(QGis.Line)
        if foi_type == 'pointofinterestdefiner':
            sym = QgsSymbol(QGis.Point)
            sym.setColor(QtCore.Qt.black)
            sym.setFillColor(QtCore.Qt.green)
            sym.setFillStyle(QtCore.Qt.SolidPattern)
            sym.setLineWidth(0.3)
            sym.setPointSize(4)
            sym.setNamedPointSymbol("hard:triangle")
            sr = QgsSingleSymbolRenderer(QGis.Point)

        sr.addSymbol(sym)
        layer.setRenderer(sr)
        if not layer.isValid():
            print "invalid layer"
            return
        ml_dp = layer.dataProvider()
        ml_dp.addAttributes([QgsField("gid", QtCore.QVariant.String)])
        # add layer to the registry
        self.mem_layer_obj = QgsMapLayerRegistry.instance().addMapLayer(layer)

        # set extent to the extent of our layer
        #self.canvas.setExtent(layer.extent())

        # set the map canvas layer set
        cl = QgsMapCanvasLayer(layer)
        self.mapCanvasLayers.insert(0, cl)
        #layers = [cl]
        self.canvas.setLayerSet(self.mapCanvasLayers)
        print "added Layer"

    def addGeomToMemoryLayer(self, the_geom, origin=0, delete_when_done=False):
        """TO DO: Add doc string"""
        foi_type = self.foi_type.lower()
        print "got foi_type"
        if self.mem_layer_obj.featureCount() > 0:
            if origin == 1:  # is added by identify operation
                pass
            else:
                print self.mem_layer_obj.featureCount()
                print "there exists a feature, kill it!"
                self.mem_layer_obj.select()
                print "Feature count selcted for deletion:"
                print self.mem_layer_obj.selectedFeatureCount()
                self.mem_layer_obj.deleteSelectedFeatures()
                #self.mem_layer_obj.deleteFeature(0)
                self.mem_layer_obj.commitChanges()
                self.mem_layer_obj.triggerRepaint()

        ml_dp = self.mem_layer_obj.dataProvider()
        print "got DP"
        uuid_gid = QtCore.QUuid().createUuid().toString()
        print "got uuid"
        fet = QgsFeature()
        print "got feature with id"
        fet.setGeometry(the_geom)
        print "set geometry"
        fet.addAttribute(0, uuid_gid)
        print "set attr "
        ml_dp.addFeatures([fet])
        self.mem_layer_obj.commitChanges()
        print "added layers"
        #self.mem_layer_obj.updateFeatureAttributes(fet)
        #self.mem_layer_obj.updateFeatureGeometry(fet)
        self.mem_layer_obj.updateExtents()
        print "updated extents"
        #self.mem_layer_obj.drawFeature(fet)
        self.mem_layer_obj.triggerRepaint()
        print "trp"
        return fet.id()

    def zoomIn(self):
        """TO DO: Add doc string"""
        self.canvas.setMapTool(self.toolZoomIn)

    def zoomOut(self):
        """TO DO: Add doc string"""
        self.canvas.setMapTool(self.toolZoomOut)

    def pan(self):
        """TO DO: Add doc string"""
        self.canvas.setMapTool(self.toolPan)

    def identifyFeature(self):
        '''getFeatureInfo functionality'''
        self.canvas.setMapTool(self.toolIdentify)
        #print "GFI not yet implemented"

    def gotFeatureForIdentification(self, pos):
        """Show a dialog with road information """
        #pos is a rectangle
        self.mem_layer_obj.select()
        ftr = QgsFeature()
        ftr_ids = []
        while self.mem_layer_obj.nextFeature(ftr):
            if ftr.geometry().intersects(pos):
                ftr_ids.append(ftr.id())
        self.chosenFOIGeoms = []
        self.info = QgsMessageViewer()
        if ftr_ids != []:
            f = QgsFeature()
            foi_type = self.foi_type.lower()
            if foi_type == 'areaofinterestdefiner':
                ftrData = "You have selected the following feature(s) for use as an Area of Interest:\n\n"
            if foi_type == 'lineofinterestdefiner':
                ftrData = "You have selected the following feature(s) for use as a Line of Interest:\n\n"
            if foi_type == 'pointofinterestdefiner':
                ftrData = "You have selected the following feature(s) for use as a Point of Interest:\n\n"
            for fid in ftr_ids:
                self.mem_layer_obj.dataProvider().featureAtId(fid, f,  True)
                ftrData += f.attributeMap()[0].toString()
                ftrData += "\n_____________________________\n"
                self.chosenFOIGeoms.append(f.geometry())
                id_fid = self.addGeomToMemoryLayer(f.geometry())
            self.info.setMessageAsPlainText(ftrData)
        else:
            self.info.setMessageAsPlainText("no data to show")
        self.info.show()
        return

    def makeAOI(self):
        pass

    def makeLOI(self):
        pass

    def makePOI(self):
        pass

    def okTriggered(self):
        the_fet = QgsFeature()
        the_geoms = []
        print self.mem_layer_obj.featureCount()
        self.mem_layer_obj.select()
        while self.mem_layer_obj.nextFeature(the_fet):
            #self.mem_layer_obj.featureAtId(0, the_fet)

            the_geoms.append(str(the_fet.geometry().exportToWkt()))
        print the_geoms
        wktstr = WKTString()
        print wktstr

        wktstr.setValue(the_geoms[0])

        self.controller.update_ports_and_functions(
                self.module.id, [], [], [("WKTGeometry", the_geoms),
                    ("SRS", [self.crsTextAsProj4.text()])])
        self.close()
class ViewerWnd(QMainWindow):
    def __init__(self, app, dictOpts):
        QMainWindow.__init__(self)

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.useImageToRender(True)
        self.canvas.enableAntiAliasing(True)
        self.setCentralWidget(self.canvas)

        actionZoomIn = QAction(QIcon(imgs_dir + "mActionZoomIn.png"), QString("Zoom in"), self)
        actionZoomOut = QAction(QIcon(imgs_dir + "mActionZoomOut.png"), QString("Zoom out"), self)
        actionPan = QAction(QIcon(imgs_dir + "mActionPan.png"), QString("Pan"), self)

        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionPan.setCheckable(True)

        self.connect(actionZoomIn, SIGNAL("triggered()"), self.zoomIn)
        self.connect(actionZoomOut, SIGNAL("triggered()"), self.zoomOut)
        self.connect(actionPan, SIGNAL("triggered()"), self.pan)

        # Create the toolbar
        self.toolbar = self.addToolBar("Map tools")
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionPan)

        # Create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)

        # Create the statusbar
        self.statusbar = QStatusBar(self)
        self.statusbar.setObjectName("statusbar")
        self.setStatusBar(self.statusbar)

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle(QFrame.Box)
        self.lblXY.setMinimumWidth(170)
        self.lblXY.setAlignment(Qt.AlignCenter)
        self.statusbar.setSizeGripEnabled(False)
        self.statusbar.addPermanentWidget(self.lblXY, 0)

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle(QFrame.StyledPanel)
        self.lblScale.setMinimumWidth(140)
        self.statusbar.addPermanentWidget(self.lblScale, 0)

        self.createLegendWidget()  # Create the legend widget

        self.connect(app, SIGNAL("loadPgLayer"), self.loadLayer)
        self.connect(self.canvas, SIGNAL("scaleChanged(double)"), self.changeScale)
        self.connect(self.canvas, SIGNAL("xyCoordinates(const QgsPoint&)"), self.updateXY)

        self.pan()

        self.layerSRID = ""
        self.loadLayer(dictOpts)

    def zoomIn(self):
        self.canvas.setMapTool(self.toolZoomIn)

    def zoomOut(self):
        self.canvas.setMapTool(self.toolZoomOut)

    def pan(self):
        self.canvas.setMapTool(self.toolPan)

    def createLegendWidget(self):
        """ Create the map legend widget and associate to the canvas """
        self.legend = Legend(self)
        self.legend.setCanvas(self.canvas)
        self.legend.setObjectName("theMapLegend")

        self.LegendDock = QDockWidget("Layers", self)
        self.LegendDock.setObjectName("legend")
        # self.LegendDock.setAllowedAreas( Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea )
        self.LegendDock.setWidget(self.legend)
        self.LegendDock.setContentsMargins(0, 0, 0, 0)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.LegendDock)

    def loadLayer(self, dictOpts):
        print "I: Loading the layer..."
        self.layerSRID = dictOpts["srid"]  # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()
            self.raise_()

        if dictOpts["type"] == "vector":
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection(dictOpts["-h"], dictOpts["-p"], dictOpts["-d"], dictOpts["-U"], dictOpts["-W"])
            uri.setDataSource(dictOpts["-s"], dictOpts["-t"], dictOpts["-g"])
            layer = QgsVectorLayer(uri.uri(), dictOpts["-s"] + "." + dictOpts["-t"], "postgres")
        elif dictOpts["type"] == "raster":
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s schema=%s table=%s" % (
                dictOpts["-d"],
                dictOpts["-h"],
                dictOpts["-U"],
                dictOpts["-W"],
                dictOpts["-p"],
                dictOpts["-s"],
                dictOpts["-t"],
            )
            layer = QgsRasterLayer(connString, dictOpts["-s"] + "." + dictOpts["-t"])
            layer.setNoDataValue(-32768)
            layer.rasterTransparency().initializeTransparentPixelList(-32768)

        if layer.isValid():
            if self.canvas.layerCount() == 0:
                self.canvas.setExtent(layer.extent())

                if dictOpts["srid"] != "-1":
                    print "I: Map SRS (EPSG): %s" % dictOpts["srid"]
                    self.canvas.setMapUnits(layer.srs().mapUnits())
                else:
                    print "I: Unknown Reference System"
                    self.canvas.setMapUnits(0)  # 0: QGis.Meters

            QgsMapLayerRegistry.instance().addMapLayer(layer)

    def getLayerProperties(self, l):
        """ Create a layer-properties string (l:layer)"""
        print "I: Generating layer properties..."
        if l.type() == 0:  # Vector
            wkbType = [
                "WKBUnknown",
                "WKBPoint",
                "WKBLineString",
                "WKBPolygon",
                "WKBMultiPoint",
                "WKBMultiLineString",
                "WKBMultiPolygon",
                "WKBNoGeometry",
                "WKBPoint25D",
                "WKBLineString25D",
                "WKBPolygon25D",
                "WKBMultiPoint25D",
                "WKBMultiLineString25D",
                "WKBMultiPolygon25D",
            ]
            properties = (
                "Source: %s\n"
                "Geometry type: %s\n"
                "Number of features: %s\n"
                "Number of fields: %s\n"
                "SRS (EPSG): %s\n"
                "Extent: %s "
                % (
                    l.source(),
                    wkbType[l.wkbType()],
                    l.featureCount(),
                    l.dataProvider().fieldCount(),
                    self.layerSRID,
                    l.extent().toString(),
                )
            )
        elif l.type() == 1:  # Raster
            rType = ["GrayOrUndefined (single band)", "Palette (single band)", "Multiband"]
            properties = (
                "Source: %s\n"
                "Raster type: %s\n"
                "Width-Height (pixels): %sx%s\n"
                "Bands: %s\n"
                "SRS (EPSG): %s\n"
                "Extent: %s"
                % (
                    l.source(),
                    rType[l.rasterType()],
                    l.width(),
                    l.height(),
                    l.bandCount(),
                    self.layerSRID,
                    l.extent().toString(),
                )
            )
        return properties

    def changeScale(self, scale):
        self.lblScale.setText("Scale 1:" + formatNumber(scale))

    def updateXY(self, p):
        if self.canvas.mapUnits() == 2:  # Degrees
            self.lblXY.setText(formatToDegrees(p.x()) + " | " + formatToDegrees(p.y()))
        else:  # Unidad lineal
            self.lblXY.setText(formatNumber(p.x()) + " | " + formatNumber(p.y()) + "")
class ViewerWnd( QMainWindow ):
    def __init__( self, app, dictOpts ):
        QMainWindow.__init__( self )
        self.setWindowTitle( "PostGIS Layer Viewer - v.1.6.1" )
        self.setTabPosition( Qt.BottomDockWidgetArea, QTabWidget.North )

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor( Qt.white )
        self.canvas.useImageToRender( True )
        self.canvas.enableAntiAliasing( True )
        self.setCentralWidget( self.canvas )

        actionZoomIn = QAction( QIcon( imgs_dir + "mActionZoomIn.png" ), QString( "Zoom in" ), self )
        actionZoomOut = QAction( QIcon( imgs_dir + "mActionZoomOut.png" ), QString( "Zoom out" ), self )
        actionPan = QAction( QIcon( imgs_dir + "mActionPan.png" ), QString( "Pan" ), self )
        actionZoomFullExtent = QAction( QIcon( imgs_dir + "mActionZoomFullExtent.png" ), QString( "Zoom full" ), self )

        actionZoomIn.setCheckable( True )
        actionZoomOut.setCheckable( True )
        actionPan.setCheckable( True )

        self.connect(actionZoomIn, SIGNAL( "triggered()" ), self.zoomIn )
        self.connect(actionZoomOut, SIGNAL( "triggered()" ), self.zoomOut )
        self.connect(actionPan, SIGNAL( "triggered()" ), self.pan )
        self.connect(actionZoomFullExtent, SIGNAL( "triggered()" ), self.zoomFullExtent )

        self.actionGroup = QActionGroup( self )
        self.actionGroup.addAction( actionPan )
        self.actionGroup.addAction( actionZoomIn )
        self.actionGroup.addAction( actionZoomOut )        

        # Create the toolbar
        self.toolbar = self.addToolBar( "Map tools" )
        self.toolbar.addAction( actionPan )
        self.toolbar.addAction( actionZoomIn )
        self.toolbar.addAction( actionZoomOut )
        self.toolbar.addAction( actionZoomFullExtent )

        # Create the map tools
        self.toolPan = QgsMapToolPan( self.canvas )
        self.toolPan.setAction( actionPan )
        self.toolZoomIn = QgsMapToolZoom( self.canvas, False ) # false = in
        self.toolZoomIn.setAction( actionZoomIn )
        self.toolZoomOut = QgsMapToolZoom( self.canvas, True ) # true = out
        self.toolZoomOut.setAction( actionZoomOut )
        
        # Create the statusbar
        self.statusbar = QStatusBar( self )
        self.statusbar.setObjectName( "statusbar" )
        self.setStatusBar( self.statusbar )

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle( QFrame.Box )
        self.lblXY.setMinimumWidth( 170 )
        self.lblXY.setAlignment( Qt.AlignCenter )
        self.statusbar.setSizeGripEnabled( False )
        self.statusbar.addPermanentWidget( self.lblXY, 0 )

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle( QFrame.StyledPanel )
        self.lblScale.setMinimumWidth( 140 )
        self.statusbar.addPermanentWidget( self.lblScale, 0 )

        self.createLegendWidget()   # Create the legend widget

        self.connect( app, SIGNAL( "loadPgLayer" ), self.loadLayer )
        self.connect( self.canvas, SIGNAL( "scaleChanged(double)" ),
            self.changeScale )
        self.connect( self.canvas, SIGNAL( "xyCoordinates(const QgsPoint&)" ),
            self.updateXY )

        self.pan() # Default

        self.plugins = Plugins( self, self.canvas, dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], dictOpts['-U'], dictOpts['-W'] )

        self.createAboutWidget()
        self.layerSRID = '-1'
        self.loadLayer( dictOpts )
    
    def zoomIn( self ):
        self.canvas.setMapTool( self.toolZoomIn )

    def zoomOut( self ):
        self.canvas.setMapTool( self.toolZoomOut )

    def pan( self ):
        self.canvas.setMapTool( self.toolPan )

    def zoomFullExtent( self ):
        self.canvas.zoomToFullExtent()
    
    def about( self ):
        pass

    def createLegendWidget( self ):
        """ Create the map legend widget and associate it to the canvas """
        self.legend = Legend( self )
        self.legend.setCanvas( self.canvas )
        self.legend.setObjectName( "theMapLegend" )

        self.LegendDock = QDockWidget( "Layers", self )
        self.LegendDock.setObjectName( "legend" )
        self.LegendDock.setTitleBarWidget( QWidget() )
        self.LegendDock.setWidget( self.legend )
        self.LegendDock.setContentsMargins ( 0, 0, 0, 0 )
        self.addDockWidget( Qt.BottomDockWidgetArea, self.LegendDock )

    def createAboutWidget( self ):
        self.AboutDock = QDockWidget( "About", self )
        self.AboutDock.setObjectName( "about" )
        self.AboutDock.setTitleBarWidget( QWidget() )
        self.AboutDock.setContentsMargins( 0, 0, 0, 0 )
        self.tabifyDockWidget( self.LegendDock, self.AboutDock )
        self.LegendDock.raise_() # legendDock at the top

        from PyQt4.QtCore import QRect
        from PyQt4.QtGui import QSizePolicy, QGridLayout, QFont
        font = QFont()
        font.setFamily("Sans Serif")
        font.setPointSize(8.7)
        self.AboutWidget = QWidget()
        self.AboutWidget.setFont( font )
        self.AboutWidget.setObjectName("AboutWidget") 
        self.AboutDock.setWidget( self.AboutWidget )
        self.labelAbout = QLabel( self.AboutWidget )
        self.labelAbout.setAlignment(Qt.AlignCenter)
        self.labelAbout.setWordWrap(True)
        self.gridLayout = QGridLayout(self.AboutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout.addWidget(self.labelAbout, 0, 1, 1, 1)
        self.labelAbout.setTextInteractionFlags(Qt.LinksAccessibleByMouse|Qt.LinksAccessibleByKeyboard|Qt.TextSelectableByKeyboard|Qt.TextSelectableByMouse) 
        self.labelAbout.setOpenExternalLinks( True )
        self.labelAbout.setText("<html><head/><body><a href=\"http://geotux.tuxfamily.org/index.php/en/geo-blogs/item/293-consola-sql-para-plugin-pgadmin-postgis-viewer\">PostGIS Layer Viewer</a> v.1.6.1 (2015.02.24)<br \><br \>" \
            "Copyright (c) 2010 Ivan Mincik,<br \>[email protected]<br \>" \
            u"Copyright (c) 2011-2015 Germán Carrillo,<br \>[email protected]<br \><br \>" \
            "<i>Licensed under the terms of GNU GPL v.2.0</i><br \><br \>" \
            "Based on PyQGIS. Plugin Fast SQL Layer by Pablo T. Carreira.</body></html>" )

    def loadLayer( self, dictOpts ):
        print 'I: Loading the layer...'
        self.layerSRID = dictOpts[ 'srid' ] # To access the SRID when querying layer properties

        if not self.isActiveWindow():
            self.activateWindow()            
            self.raise_() 

        if dictOpts['type'] == 'vector':
            # QGIS connection
            uri = QgsDataSourceURI()
            uri.setConnection( dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], 
                dictOpts['-U'], dictOpts['-W'] )
            uri.setDataSource( dictOpts['-s'], dictOpts['-t'], dictOpts['-g'] )
            layer = QgsVectorLayer( uri.uri(), dictOpts['-s'] + '.' + dictOpts['-t'],
                "postgres" )        
        elif dictOpts['type'] == 'raster':          
            connString = "PG: dbname=%s host=%s user=%s password=%s port=%s mode=2 " \
                "schema=%s column=%s table=%s" % ( dictOpts['-d'], dictOpts['-h'], 
                dictOpts['-U'], dictOpts['-W'], dictOpts['-p'], dictOpts['-s'], 
                dictOpts['col'], dictOpts['-t'] )
            layer = QgsRasterLayer( connString, dictOpts['-s'] + '.' + dictOpts['-t'] )
            
            if layer.isValid():
                layer.setContrastEnhancement( QgsContrastEnhancement.StretchToMinimumMaximum )

        self.addLayer( layer, self.layerSRID )

    def addLayer( self, layer, srid='-1' ):
        if layer.isValid():
            # Only in case that srid != -1, read the layer SRS properties, otherwise don't since it will return 4326
            if srid != '-1': 
               self.layerSRID = layer.crs().description() + ' (' + str( layer.crs().postgisSrid() ) + ')'
            else:
               self.layerSRID = 'Unknown SRS (-1)'

            if self.canvas.layerCount() == 0:
                self.canvas.setExtent( layer.extent() )

                if srid != '-1':
                    print 'I: Map SRS (EPSG): %s' % self.layerSRID                    
                    self.canvas.setMapUnits( layer.crs().mapUnits() )
                else:
                    print 'I: Unknown Reference System'
                    self.canvas.setMapUnits( 0 ) # 0: QGis.Meters

            return QgsMapLayerRegistry.instance().addMapLayer( layer )
        return False

    def activeLayer( self ):
        """ Returns the active layer in the layer list widget """
        return self.legend.activeLayer()

    def getLayerProperties( self, l ):
        """ Create a layer-properties string (l:layer)"""
        print 'I: Generating layer properties...'
        if l.type() == 0: # Vector
            wkbType = ["WKBUnknown","WKBPoint","WKBLineString","WKBPolygon",
                       "WKBMultiPoint","WKBMultiLineString","WKBMultiPolygon",
                       "WKBNoGeometry","WKBPoint25D","WKBLineString25D","WKBPolygon25D",
                       "WKBMultiPoint25D","WKBMultiLineString25D","WKBMultiPolygon25D"]
            properties = "Source: %s\n" \
                         "Geometry type: %s\n" \
                         "Number of features: %s\n" \
                         "Number of fields: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s " \
                          % ( l.source(), wkbType[l.wkbType()], l.featureCount(), 
                              l.dataProvider().fields().count(), self.layerSRID, 
                              l.extent().toString() )
        elif l.type() == 1: # Raster
            rType = [ "GrayOrUndefined (single band)", "Palette (single band)", "Multiband", "ColorLayer" ]
            properties = "Source: %s\n" \
                         "Raster type: %s\n" \
                         "Width-Height (pixels): %sx%s\n" \
                         "Bands: %s\n" \
                         "SRS (EPSG): %s\n" \
                         "Extent: %s" \
                         % ( l.source(), rType[l.rasterType()], l.width(), l.height(),
                             l.bandCount(), self.layerSRID, l.extent().toString() )

        self.layerSRID = '-1' # Initialize the srid 
        return properties

    def changeScale( self, scale ):
        self.lblScale.setText( "Scale 1:" + formatNumber( scale ) )

    def updateXY( self, p ):
        if self.canvas.mapUnits() == 2: # Degrees
            self.lblXY.setText( formatToDegrees( p.x() ) + " | " \
                + formatToDegrees( p.y() ) )
        else: # Unidad lineal
            self.lblXY.setText( formatNumber( p.x() ) + " | " \
                + formatNumber( p.y() ) + "" )
    def __init__( self, app, dictOpts ):
        QMainWindow.__init__( self )
        self.setWindowTitle( "PostGIS Layer Viewer - v.1.6.1" )
        self.setTabPosition( Qt.BottomDockWidgetArea, QTabWidget.North )

        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor( Qt.white )
        self.canvas.useImageToRender( True )
        self.canvas.enableAntiAliasing( True )
        self.setCentralWidget( self.canvas )

        actionZoomIn = QAction( QIcon( imgs_dir + "mActionZoomIn.png" ), QString( "Zoom in" ), self )
        actionZoomOut = QAction( QIcon( imgs_dir + "mActionZoomOut.png" ), QString( "Zoom out" ), self )
        actionPan = QAction( QIcon( imgs_dir + "mActionPan.png" ), QString( "Pan" ), self )
        actionZoomFullExtent = QAction( QIcon( imgs_dir + "mActionZoomFullExtent.png" ), QString( "Zoom full" ), self )

        actionZoomIn.setCheckable( True )
        actionZoomOut.setCheckable( True )
        actionPan.setCheckable( True )

        self.connect(actionZoomIn, SIGNAL( "triggered()" ), self.zoomIn )
        self.connect(actionZoomOut, SIGNAL( "triggered()" ), self.zoomOut )
        self.connect(actionPan, SIGNAL( "triggered()" ), self.pan )
        self.connect(actionZoomFullExtent, SIGNAL( "triggered()" ), self.zoomFullExtent )

        self.actionGroup = QActionGroup( self )
        self.actionGroup.addAction( actionPan )
        self.actionGroup.addAction( actionZoomIn )
        self.actionGroup.addAction( actionZoomOut )        

        # Create the toolbar
        self.toolbar = self.addToolBar( "Map tools" )
        self.toolbar.addAction( actionPan )
        self.toolbar.addAction( actionZoomIn )
        self.toolbar.addAction( actionZoomOut )
        self.toolbar.addAction( actionZoomFullExtent )

        # Create the map tools
        self.toolPan = QgsMapToolPan( self.canvas )
        self.toolPan.setAction( actionPan )
        self.toolZoomIn = QgsMapToolZoom( self.canvas, False ) # false = in
        self.toolZoomIn.setAction( actionZoomIn )
        self.toolZoomOut = QgsMapToolZoom( self.canvas, True ) # true = out
        self.toolZoomOut.setAction( actionZoomOut )
        
        # Create the statusbar
        self.statusbar = QStatusBar( self )
        self.statusbar.setObjectName( "statusbar" )
        self.setStatusBar( self.statusbar )

        self.lblXY = QLabel()
        self.lblXY.setFrameStyle( QFrame.Box )
        self.lblXY.setMinimumWidth( 170 )
        self.lblXY.setAlignment( Qt.AlignCenter )
        self.statusbar.setSizeGripEnabled( False )
        self.statusbar.addPermanentWidget( self.lblXY, 0 )

        self.lblScale = QLabel()
        self.lblScale.setFrameStyle( QFrame.StyledPanel )
        self.lblScale.setMinimumWidth( 140 )
        self.statusbar.addPermanentWidget( self.lblScale, 0 )

        self.createLegendWidget()   # Create the legend widget

        self.connect( app, SIGNAL( "loadPgLayer" ), self.loadLayer )
        self.connect( self.canvas, SIGNAL( "scaleChanged(double)" ),
            self.changeScale )
        self.connect( self.canvas, SIGNAL( "xyCoordinates(const QgsPoint&)" ),
            self.updateXY )

        self.pan() # Default

        self.plugins = Plugins( self, self.canvas, dictOpts['-h'], dictOpts['-p'], dictOpts['-d'], dictOpts['-U'], dictOpts['-W'] )

        self.createAboutWidget()
        self.layerSRID = '-1'
        self.loadLayer( dictOpts )
Esempio n. 35
0
    def create_config_window(self):
        """TO DO - add docstring"""
        self.setWindowTitle(self.foi_type)
        self.setMinimumSize(800, 850)
        self.center()
        self.mainLayout = QtGui.QVBoxLayout()
        self.setLayout(self.mainLayout)

        #set up Group Box for organising CRS of FOI
        self.crsGroupBox = QtGui.QGroupBox("Define Projection or Coordinate Reference System")
        self.crsLayout = QtGui.QHBoxLayout()
        self.crsProj4Label = QtGui.QLabel('SRS Proj4: ')
        self.crsTextAsProj4 = QtGui.QLineEdit('4326')
        self.crsChooseButton = QtGui.QPushButton('&Choose SRS')
        self.crsChooseButton.setAutoDefault(False)
        self.crsChooseButton.setToolTip('Choose a Spatial Reference System or Projection')

        self.crsLayout.addWidget(self.crsProj4Label)
        self.crsLayout.addWidget(self.crsTextAsProj4)
        self.crsLayout.addWidget(self.crsChooseButton)

        self.crsGroupBox.setLayout(self.crsLayout)

        #set up Group Box for getting coords of Bounding Box
        self.bbGroupBox = QtGui.QGroupBox("Define Area of Interest via a Bounding Box in units of SRS")
        self.bbLayout = QtGui.QHBoxLayout()

        self.bbMinXLabel = QtGui.QLabel('MinX/Left: ')
        self.bbMinYLabel = QtGui.QLabel('MinY/Bottom: ')
        self.bbMaxXLabel = QtGui.QLabel('MaxX/Right: ')
        self.bbMaxYLabel = QtGui.QLabel('MaxY/Top: ')

        self.bbMinXText = QtGui.QLineEdit('15')
        self.bbMinYText = QtGui.QLineEdit('-35')
        self.bbMaxXText = QtGui.QLineEdit('35')
        self.bbMaxYText = QtGui.QLineEdit('-20')

        self.bbToMapButton = QtGui.QPushButton('&To Map')
        self.bbToMapButton.setAutoDefault(False)
        self.bbToMapButton.setToolTip('Show Bounding Box on Map')

        self.bbLayout.addWidget(self.bbMinXLabel)
        self.bbLayout.addWidget(self.bbMinXText)
        self.bbLayout.addWidget(self.bbMinYLabel)
        self.bbLayout.addWidget(self.bbMinYText)
        self.bbLayout.addWidget(self.bbMaxXLabel)
        self.bbLayout.addWidget(self.bbMaxXText)
        self.bbLayout.addWidget(self.bbMaxYLabel)
        self.bbLayout.addWidget(self.bbMaxYText)
        self.bbLayout.addWidget(self.bbToMapButton)

        self.bbGroupBox.setLayout(self.bbLayout)

        #set up Group Box for getting text representation of a geometry
        self.asTxtGroupBox = QtGui.QGroupBox("Define Area of Interest via a WKT string in units of SRS")
        self.asTxtLayout = QtGui.QVBoxLayout()

        self.asTxtLabel = QtGui.QLabel('WKT String: ')
        self.asTxtText = QtGui.QTextEdit('')
        self.asTxtToMapButton = QtGui.QPushButton('&To Map')
        self.asTxtToMapButton.setAutoDefault(False)
        self.asTxtToMapButton.setToolTip('Show Bounding Box on Map')

        self.asTxtLayout.addWidget(self.asTxtLabel)
        self.asTxtLayout.addWidget(self.asTxtText)
        self.asTxtLayout.addWidget(self.asTxtToMapButton)

        self.asTxtGroupBox.setLayout(self.asTxtLayout)

        #set up Group Box for Map
        self.MapGroupBox = QtGui.QGroupBox("Map Viewer")
        self.MapLayout = QtGui.QHBoxLayout()
        #sz = QtCore.QSize(200, 300)
        #self.MapLayout.setGeometry(QtCore.QRect(300, 700, 780, 680))
        self.MapGroupBox.setLayout(self.MapLayout)

        ## create canvas
        self.canvas = QgsMapCanvas()
        self.canvas.setCanvasColor(QtGui.QColor(200, 200, 255))
        #self.mainLayout.addWidget(self.canvas)

        # icons
        actionAddLayer = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionAddLayer.png"), "Add Layer", self)
        actionZoomIn = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionZoomIn.png"), "Zoom In", self)
        actionZoomOut = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionZoomOut.png"), "Zoom Out", self)
        actionPan = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionPan.png"), "Pan", self)
        actionIdentify = QtGui.QAction(QtGui.QIcon(self.path_png_icon + \
                        "/mActionIdentify.png"), "Feature Information", self)

        # create toolbar
        self.toolbar = QtGui.QToolBar()  # "Canvas actions"
        self.toolbar.addAction(actionAddLayer)
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionPan)
        self.toolbar.addAction(actionIdentify)

        # create layer explorer pane
        self.explorer = QtGui.QDockWidget("Layers")
        self.explorer.resize(60, 100)
        #~self.explorerListWidget = QtGui.QListWidget()
        #~self.explorerListWidget.setObjectName("listWidget")
        #~self.explorer.setWidget(self.explorerListWidget)

        # create map tools
        self.toolPan = QgsMapToolPan(self.canvas,)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false == in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true == out
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolAOI = QgsMapTool(self.canvas)
        self.toolIdentify = GetFeatureInfoTool(self.canvas, self.gotFeatureForIdentification)
        self.toolIdentify.setAction(actionIdentify)

        # layerList explorer
        self.GroupBoxLyrExplorer = QtGui.QGroupBox("")
        self.vboxLyrExplorer = QtGui.QVBoxLayout()
        self.GroupBoxLyrExplorer.setLayout(self.vboxLyrExplorer)
        self.MapLayout.addWidget(self.GroupBoxLyrExplorer)
        self.label = QtGui.QLabel("")
        self.vboxLyrExplorer.addWidget(self.label)
        self.vboxLyrExplorer.addWidget(self.explorer)

        # toolbar and canvas layout
        self.GroupBoxToolBarMapCanvas = QtGui.QGroupBox("")
        self.vboxToolBarMapCanvas = QtGui.QVBoxLayout()
        self.vboxToolBarMapCanvas.setGeometry(QtCore.QRect(300, 700, 780, 680))
        self.GroupBoxToolBarMapCanvas.setLayout(self.vboxToolBarMapCanvas)
        self.MapLayout.addWidget(self.GroupBoxToolBarMapCanvas)
        self.vboxToolBarMapCanvas.addWidget(self.toolbar)
        self.vboxToolBarMapCanvas.addWidget(self.canvas)

        #global list to hold inputlayers list -> accessible for toggleLayer
        self.mylist = []

        #finalise/cancel buttons
        self.finishGroupBox = QtGui.QGroupBox("Finish")
        self.buttonLayout = QtGui.QHBoxLayout()
        self.finishGroupBox.setLayout(self.buttonLayout)
        self.buttonLayout.setGeometry(QtCore.QRect(300, 500, 780, 680))
        self.buttonLayout.setMargin(5)
        self.cancelButton = QtGui.QPushButton('&Cancel', self)
        self.cancelButton.setAutoDefault(False)
        self.cancelButton.setShortcut('Esc')
        self.buttonLayout.addStretch(1)  # force buttons to the right
        self.buttonLayout.addWidget(self.cancelButton)
        self.okButton = QtGui.QPushButton('&OK', self)
        self.okButton.setAutoDefault(False)
        self.buttonLayout.addWidget(self.okButton)
        self.connect(self.okButton,
                     QtCore.SIGNAL('clicked(bool)'),
                     self.okTriggered)
        self.connect(self.cancelButton,
                     QtCore.SIGNAL('clicked(bool)'),
                     self.close)

        self.mainLayout.addWidget(self.crsGroupBox)
        self.mainLayout.addWidget(self.bbGroupBox)
        self.mainLayout.addWidget(self.asTxtGroupBox)
        self.mainLayout.addWidget(self.MapGroupBox)
        self.mainLayout.addWidget(self.finishGroupBox)

        # set signals
        self.connect(self.crsChooseButton, QtCore.SIGNAL('clicked(bool)'), self.getSRS)
        self.connect(self.bbToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapBB)
        self.connect(self.asTxtToMapButton, QtCore.SIGNAL('clicked(bool)'), self.bbToMapTxt)
        self.connect(actionAddLayer, QtCore.SIGNAL("activated()"), self.addLayer)
        self.connect(actionZoomIn, QtCore.SIGNAL("activated()"), self.zoomIn)
        self.connect(actionZoomOut, QtCore.SIGNAL("activated()"), self.zoomOut)
        self.connect(actionPan, QtCore.SIGNAL("activated()"), self.pan)
        self.connect(actionIdentify, QtCore.SIGNAL("triggered()"), self.identifyFeature)

        #load a backdrop layer
        self.mapCanvasLayers = []
        fname = self.path_bkgimg + '/bluemarblemerged.img'
        fileInfo = QtCore.QFileInfo(fname)
        baseName = fileInfo.baseName()
        self.bmLayer = QgsRasterLayer(fname,  baseName)
        QgsMapLayerRegistry.instance().addMapLayer(self.bmLayer)
        self.cl = QgsMapCanvasLayer(self.bmLayer)
        self.mapCanvasLayers.append(self.cl)
        # Set extent to the extent of our layer
        self.canvas.setExtent(self.bmLayer.extent())
        self.canvas.enableAntiAliasing(True)
        self.canvas.freeze(False)
        self.canvas.setLayerSet(self.mapCanvasLayers)
        self.canvas.refresh()

        #now, add a container layer for our text based/ digitised or selected geoms
        self.addMemoryLayer()
Esempio n. 36
0
    def setupUi(self, _):
        """
        Add to the UI the following elements:

        1) the selection editor
        2) the tabs with the dynamic forms
        3) the map
        4) the toolbar with the map tools
        """
        super(MainWindow, self).setupUi(self)

        self.selection_editor = SelectionDialog(self)
        self.actionUndo.setDisabled(True)

        # setup dynamic forms
        self.tabs = (
            Tab("declustering",
                self.declusteringFormLayout,
                DECLUSTERER_METHODS,
                [self.declusterButton, self.declusteringPurgeButton]),
            Tab("completeness",
                self.completenessFormLayout,
                COMPLETENESS_METHODS,
                [self.completenessButton, self.completenessPurgeButton]),
            Tab("recurrence_model",
                self.recurrenceModelFormLayout,
                OCCURRENCE_METHODS,
                [self.recurrenceModelButton]),
            Tab("max_magnitude",
                self.maxMagnitudeFormLayout,
                MAX_MAGNITUDE_METHODS,
                [self.maxMagnitudeButton]),
            Tab("smoothed_seismicity",
                self.smoothedSeismicityFormLayout,
                SMOOTHED_SEISMICITY_METHODS,
                [self.smoothedSeismicityButton]),
            Tab("histogram",
                self.catalogueAnalysisFormLayout,
                CATALOGUE_ANALYSIS_METHODS,
                [self.catalogueAnalysisButton]))

        for tab in self.tabs:
            tab.setup_form(self.on_algorithm_select)
        self.stackedFormWidget.currentChanged.connect(self.change_tab)

        # setup Map
        self.mapWidget.setCanvasColor(Qt.white)
        self.mapWidget.enableAntiAliasing(True)
        self.mapWidget.show()
        #self.message_bar = QgsMessageBar(self.centralWidget)
        #self.outputVerticalLayout.insertWidget(0, self.message_bar)

        # setup toolbar
        group = QtGui.QActionGroup(self)
        group.addAction(self.actionZoomIn)
        group.addAction(self.actionZoomOut)
        group.addAction(self.actionPan)
        group.addAction(self.actionIdentify)

        # create the map tools
        toolPan = QgsMapToolPan(self.mapWidget)
        toolPan.setAction(self.actionPan)
        # false = in
        toolZoomIn = QgsMapToolZoom(self.mapWidget, False)
        toolZoomIn.setAction(self.actionZoomIn)
        # true = out
        toolZoomOut = QgsMapToolZoom(self.mapWidget, True)
        toolZoomOut.setAction(self.actionZoomOut)

        toolIdentify = QgsMapToolEmitPoint(self.mapWidget)
        toolIdentify.setAction(self.actionIdentify)
        toolIdentify.canvasClicked.connect(
            lambda point, button: self.catalogue_map.show_tip(point))

        self.actionZoomIn.triggered.connect(
            lambda: self.mapWidget.setMapTool(toolZoomIn))
        self.actionZoomOut.triggered.connect(
            lambda: self.mapWidget.setMapTool(toolZoomOut))
        self.actionPan.triggered.connect(
            lambda: self.mapWidget.setMapTool(toolPan))
        self.actionIdentify.triggered.connect(
            lambda: self.mapWidget.setMapTool(toolIdentify))

        self.mapWidget.setMapTool(toolPan)

        self.stackedFormWidget.setCurrentIndex(0)