Exemple #1
0
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert (schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        user_msg1 = QgsMessageBar(dlg)
        user_msg1.pushInfo(
            "Select:", "one [many] for single [multiple] "
            "revisions.  Fetching may take time.")

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
                     "FROM " + schema + ".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget(dlg)
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(6)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels([
            'Select', 'Revision', 'Commit Message', 'Branch', 'Date', 'Author'
        ])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                chkBoxItem = QTableWidgetItem()
                chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                chkBoxItem.setCheckState(Qt.Unchecked)
                tblw.setItem(i, 0, chkBoxItem)
                tblw.setItem(i, j + 1, QTableWidgetItem(str(item)))

        layout.addWidget(user_msg1)
        layout.addWidget(tblw)
        layout.addWidget(button_box)
        dlg.resize(650, 300)
        if not dlg.exec_():
            return

        rows = set()
        revision_number_list = []
        for i in range(len(revs)):
            if tblw.item(i, 0).checkState():
                print "Revision " + str(i + 1) + " will be fetched"
                revision_number_list.append(i + 1)
                rows.add(tblw.item(i, 0).row())

        progressMessageBar = self.iface.messageBar().createMessage(
            "Querying "
            "the database for revision(s) " + str(revision_number_list))
        progress = QProgressBar()
        progress.setMaximum(len(rows))
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar,
                                           self.iface.messageBar().INFO)
        progress.setValue(0)

        for i, row in enumerate(rows):
            progress.setValue(i + 1)
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(), schema,
                                              branch, rev)
            grp_name = branch + ' revision ' + str(rev)
            grp_idx = self.iface.legendInterface().addGroup(grp_name)
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(
                    schema + '_' + branch + '_rev_' + str(rev),
                    new_uri.table(), new_uri.geometryColumn(), new_uri.sql(),
                    new_uri.keyColumn())
                display_name = QgsMapLayerRegistry.instance().mapLayer(
                    layer_id).name()
                src = new_uri.uri().replace('()', '')
                new_layer = self.iface.addVectorLayer(src, display_name,
                                                      'postgres')
                self.iface.legendInterface().moveLayer(new_layer, grp_idx)
        self.iface.messageBar().clearWidgets()
    def view(self):
        """create view and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(
                self.current_layers[0] )
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        assert(schema)
        dlg = QDialog()
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(
                QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        user_msg1 = QgsMessageBar(dlg)
        user_msg1.pushInfo("Select:", "one [many] for single [multiple] "
        "revisions.  Fetching may take time.")

        pcur = versioning_base.Db( psycopg2.connect(self.pg_conn_info()) )
        pcur.execute("SELECT rev, commit_msg, branch, date, author "
            "FROM "+schema+".revisions")
        revs = pcur.fetchall()
        pcur.close()
        tblw = QTableWidget( dlg )
        tblw.setRowCount(len(revs))
        tblw.setColumnCount(6)
        tblw.setSortingEnabled(True)
        tblw.setHorizontalHeaderLabels(['Select','Revision', 'Commit Message',
                                      'Branch', 'Date', 'Author'])
        tblw.verticalHeader().setVisible(False)
        for i, rev in enumerate(revs):
            for j, item in enumerate(rev):
                chkBoxItem = QTableWidgetItem()
                chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                chkBoxItem.setCheckState(Qt.Unchecked)
                tblw.setItem(i, 0, chkBoxItem)
                tblw.setItem(i, j+1, QTableWidgetItem( str(item) ))

        layout.addWidget( user_msg1 )
        layout.addWidget( tblw )
        layout.addWidget( button_box )
        dlg.resize( 650, 300 )
        if not dlg.exec_() :
            return

        rows = set()
        revision_number_list = []
        for i in range(len(revs)):
            if  tblw.item(i,0).checkState():
                print "Revision "+ str(i + 1) +" will be fetched"
                revision_number_list.append(i + 1)
                rows.add(tblw.item(i,0).row())

        progressMessageBar = self.iface.messageBar().createMessage("Querying "
        "the database for revision(s) "+str(revision_number_list))
        progress = QProgressBar()
        progress.setMaximum(len(rows))
        progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO)
        progress.setValue(0)

        for i, row in enumerate(rows):
            progress.setValue(i+1)
            branch = revs[row][2]
            rev = revs[row][0]
            versioning_base.add_revision_view(uri.connectionInfo(),
                    schema, branch, rev )
            grp_name = branch+' revision '+str(rev)
            grp_idx = self.iface.legendInterface().addGroup( grp_name )
            for layer_id in reversed(self.current_layers):
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                new_uri = QgsDataSourceURI(layer.source())
                new_uri.setDataSource(schema+'_'+branch+'_rev_'+str(rev),
                        new_uri.table(),
                        new_uri.geometryColumn(),
                        new_uri.sql(),
                        new_uri.keyColumn())
                display_name =  QgsMapLayerRegistry.instance().mapLayer(layer_id).name()
                src = new_uri.uri().replace('()','')
                new_layer = self.iface.addVectorLayer( src,
                        display_name, 'postgres')
                self.iface.legendInterface().moveLayer( new_layer, grp_idx)
        self.iface.messageBar().clearWidgets()
Exemple #3
0
class NmapsEngine:
    """QGIS Plugin Implementation."""
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgisInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.visible = False
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir, 'i18n',
                                   'NmapsEngine_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Nmaps Engine')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'NmapsEngine')
        self.toolbar.setObjectName(u'NmapsEngine')

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('NmapsEngine', message)

    def add_action(self,
                   icon_path,
                   text,
                   callback,
                   enabled_flag=True,
                   add_to_menu=True,
                   add_to_toolbar=True,
                   status_tip=None,
                   whats_this=None,
                   parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        # Create the dialog (after translation) and keep reference
        self.dlg = NmapsEngineDialog()

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            self.toolbar.addAction(action)

        if add_to_menu:
            self.iface.addPluginToMenu(self.menu, action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/NmapsEngine/icon.png'
        self.add_action(icon_path,
                        text=self.tr(u'NMap'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        self.dlg.pushButton.clicked.connect(self.create_nmap)
        self.dlg.listWidget.itemDoubleClicked.connect(self.item_click)
        self.bar = QgsMessageBar(self.dlg)
        QObject.connect(self.iface.mapCanvas(), SIGNAL("layersChanged()"),
                        self.nmap_connect)
        QgsMapLayerRegistry.instance(
        ).layersWillBeRemoved["QStringList"].connect(self.remove_layer)
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.bar.move(20, 1)
        self.bar.setFixedSize(692, 40)

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Nmaps Engine'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.iface.mainWindow().statusBar().showMessage("...")
        self.dlg.listWidget.clear()
        self.dlg.show()
        self.visible = True
        # Run the dialog event loop
        self.nmap_connect()
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            self.visible = False
            pass

    def remove_layer(self, lyr_id):
        if len(lyr_id) == 1:
            lyr = QgsMapLayerRegistry.instance().mapLayer(
                lyr_id[0])  # returns QgsMapLayer pointer
            lyr_name = lyr.name()
            tl = pickle_db.load_obj()
            for k, v in tl.items():
                if v == lyr_name:
                    del tl[k]
            pickle_db.save_obj(tl)

    def nmap_connect(self):
        if self.visible:
            self.iface.mainWindow().statusBar().clear()
            self.bar.pushInfo("Serwer NMap",
                              "Łączenie z serwerem NMap".decode("utf-8"))
            try:
                token = Authentication(ApiKey(), 'qgis-plugin').authenticate()
                self.nm_token = Token(token)
            except:
                self.bar.pushCritical("Serwer NMap",
                                      "Nie udało się połączyć".decode("utf-8"))
                tkd = TokenDialog(self)
                tkd.dlg()
                return False

            try:
                tilesets = Tilesets(self.nm_token).list()
            except:
                self.bar.pushCritical("Serwer NMap",
                                      "Nie mogę pobrać danych".decode("utf-8"))
                return False

            self.bar.clearWidgets()
            self.bar.pushSuccess("Serwer NMap", "Połączono".decode('utf-8'))
            self.iface.mainWindow().statusBar().showMessage(
                "Połączono".decode("utf-8"))

            tl = pickle_db.load_obj()

            avialble_layers = [
                layer.name()
                for layer in self.iface.legendInterface().layers()
            ]

            self.dlg.listWidget.clear()
            for tileset in tilesets:
                tileset_list_item = TilesetListItem()
                tileset_list_item.setTextUp(tileset.get('id'))
                tileset_list_item.setTextDown(tileset.get('name'))
                if tileset.get('name') in tl and tl[tileset.get(
                        'name')] in avialble_layers:
                    tileset_list_item.setTextMiddle(tl[tileset.get('name')])
                if tileset.get('id') in tl and tl[tileset.get(
                        'id')] in avialble_layers:
                    tileset_list_item.setTextMiddle(tl[tileset.get('id')])
                tileset_list_item.setIcon(None)
                tileset_list_item_widget = QListWidgetItem(self.dlg.listWidget)
                tileset_list_item_widget.setSizeHint(
                    tileset_list_item.sizeHint())
                self.dlg.listWidget.addItem(tileset_list_item_widget)
                self.dlg.listWidget.setItemWidget(tileset_list_item_widget,
                                                  tileset_list_item)

            self.bar.clearWidgets()
            self.bar.pushSuccess(
                "Serwer NMap",
                "Połączono i pobrano listę zestawów".decode('utf-8'))

            self.timer = QTimer()
            self.timer.timeout.connect(self.add_notif)
            self.timer.start(4000)

    def item_click(self, item):
        current = item.listWidget().itemWidget(item)
        item_id = current.getTextUp()
        item_label = current.getTextDown()
        TilesetCommonDialog(item_id, self).dlg(item_label)

    def create_nmap(self):
        TilesetCreateDialog(self).dlg()

    def add_notif(self):
        tileset_req = Tilesets(self.nm_token)
        notifications = tileset_req.jobs()
        self.bar.clearWidgets()
        for notification in notifications:
            if notification.get('status') == 'waiting':
                self.bar.pushInfo(
                    "Serwer NMap", "Oczekiwanie  %s %d %%".decode('utf-8') %
                    (notification.get('originalname'),
                     notification.get('progress')))
            if notification.get('status') == 'processing':
                self.bar.pushInfo(
                    "Serwer NMap", "Kafelkowanie  %s %d %%".decode('utf-8') %
                    (notification.get('originalname'),
                     notification.get('progress')))
            if notification.get('status') == 'success':
                self.bar.pushSuccess(
                    "Serwer NMap", "Ukończono %s".decode('utf-8') %
                    (notification.get('originalname')))
                self.nmap_connect()
                tileset_req.hide(notification.get('job_id'))
            if notification.get('status') == 'error':
                self.bar.pushCritical(
                    "Serwer NMap", "Błąd %s".decode('utf-8') %
                    (notification.get('originalname')))
                tileset_req.hide(notification.get('job_id'))