Example #1
0
    def load_html(self, mode, html):
        """Load HTML to this class with the mode specified.

        There are two modes that can be used:
            * HTML_FILE_MODE: Directly from a local HTML file.
            * HTML_STR_MODE: From a valid HTML string.

        :param mode: The mode.
        :type mode: int

        :param html: The html that will be loaded. If the mode is a file,
            then it should be a path to the htm lfile. If the mode is a string,
            then it should be a valid HTML string.
        :type html: str
        """
        # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
        self._html_loaded_flag = False

        if mode == HTML_FILE_MODE:
            self.setUrl(QtCore.QUrl.fromLocalFile(html))
        elif mode == HTML_STR_MODE:
            self.setHtml(html)
        else:
            raise InvalidParameterError('The mode is not supported.')

        counter = 0
        sleep_period = 0.1  # sec
        timeout = 20  # it's generous enough!
        while not self._html_loaded_flag and counter < timeout:
            # Block until the event loop is done
            counter += sleep_period
            time.sleep(sleep_period)
            # noinspection PyArgumentList
            QgsApplication.processEvents()
Example #2
0
    def _updateLayer(self, layer):
        if not (self.iface and self.previewEnabled):
            return False

        if layer.properties.get("comboBox_ObjectType") == "Model File":
            self.iface.loadModelLoaders()

        ts0 = time.time()
        tss = []
        for exporter in self.exporter.builders(layer):
            if self.aborted:
                return False
            ts1 = time.time()
            obj = exporter.build()
            ts2 = time.time()
            self.iface.loadJSONObject(obj)
            ts3 = time.time()
            tss.append([ts2 - ts1, ts3 - ts2])
            QgsApplication.processEvents(
            )  # NOTE: process events only for the calling thread
        layer.updated = False
        if DEBUG_MODE:
            logMessage("updating {0} costed {1:.3f}s:\n{2}".format(
                layer.name,
                time.time() - ts0,
                "\n".join(["{:.3f} {:.3f}".format(ts[0], ts[1])
                           for ts in tss])))
        return True
Example #3
0
    def _buildLayer(self, layer):
        if not (self.iface and self.enabled) or self.aborted:
            return False

        self.iface.runScript('loadStart("L{}");  // {}'.format(
            layer.jsLayerId, layer.name))

        if layer.properties.get("comboBox_ObjectType") == "Model File":
            self.iface.loadModelLoaders()

        ts0 = time.time()
        tss = []
        for builder in self.builder.builders(layer):
            if self.aborted or not self.iface:
                return False
            ts1 = time.time()
            obj = builder.build()
            ts2 = time.time()
            self.iface.loadJSONObject(obj)
            ts3 = time.time()
            tss.append([ts2 - ts1, ts3 - ts2])
            QgsApplication.processEvents(
            )  # NOTE: process events only for the calling thread

        layer.updated = False
        self.iface.runScript('loadEnd("L{}");'.format(layer.jsLayerId))

        if DEBUG_MODE:
            msg = "updating {0} costed {1:.3f}s:\n{2}".format(
                layer.name,
                time.time() - ts0,
                "\n".join(["{:.3f} {:.3f}".format(ts[0], ts[1])
                           for ts in tss]))
            logMessage(msg, False)
        return True
Example #4
0
def certificate_preprocess(plot, plots):
    """
    Utility function that loads and renders plots that belong to a specific
    scheme.
    """
    scheme_plot_layer = lht_plot_layer(plot.scheme_id, CERTIFICATE_PLOT)
    QgsMapLayerRegistry.instance().addMapLayer(scheme_plot_layer)
    # Get the EPSG code of the plot
    epsg_code = plot.cb_check_lht_plot_crs.value
    # Setting the project CRS variable
    QgsExpressionContextUtils.setProjectVariable('flts_source_crs', epsg_code)

    # Styling reference plot using primary key
    filter_exp = '"id" = ' + str(plot.id)
    scheme_symbol = QgsSymbolV2.defaultSymbol(scheme_plot_layer.geometryType())
    # Rule-based rendering
    rule_renderer = QgsRuleBasedRendererV2(scheme_symbol)
    root_rule = rule_renderer.rootRule()

    # Rule for highlighting reference plot
    scheme_rule = root_rule.children()[0].clone()
    scheme_rule.setLabel('Reference Plot')
    scheme_rule.setFilterExpression(filter_exp)
    scheme_symbol_layer = scheme_rule.symbol().symbolLayer(0)
    scheme_symbol_layer.setFillColor(Qt.yellow)
    scheme_symbol_layer.setOutlineColor(Qt.black)
    scheme_symbol_layer.setBorderWidth(0.5)
    root_rule.appendChild(scheme_rule)

    # Rule for other plots
    def_rule = root_rule.children()[0].clone()
    def_rule.setLabel('Plots')
    def_rule.setIsElse(True)
    def_symbol_layer = def_rule.symbol().symbolLayer(0)
    def_symbol_layer.setFillColor(Qt.transparent)
    def_symbol_layer.setOutlineColor(Qt.black)
    root_rule.appendChild(def_rule)

    # Remove default rule
    root_rule.removeChildAt(0)

    # Set renderer
    scheme_plot_layer.setRendererV2(rule_renderer)

    # Enable labeling
    scheme_plot_layer.setCustomProperty("labeling", "pal")
    scheme_plot_layer.setCustomProperty("labeling/enabled", "true")
    scheme_plot_layer.setCustomProperty("labeling/fontFamily", "Arial")
    scheme_plot_layer.setCustomProperty("labeling/fontSize", "5.5")
    scheme_plot_layer.setCustomProperty("labeling/fieldName", "plot_number")
    scheme_plot_layer.setCustomProperty("labeling/placement", "1")
    scheme_plot_layer.setCustomProperty("labeling/centroidInside", "true")
    scheme_plot_layer.setCustomProperty("labeling/centroidWhole", "false")

    scheme_plot_layer.triggerRepaint()

    iface.mapCanvas().setExtent(scheme_plot_layer.extent())
    QgsApplication.processEvents()

    return True
Example #5
0
    def progress_callback(self, current_value, maximum_value, message=None):
        """GUI based callback implementation for showing progress.

        :param current_value: Current progress.
        :type current_value: int

        :param maximum_value: Maximum range (point at which task is complete.
        :type maximum_value: int

        :param message: Optional message dictionary to containing content
            we can display to the user. See safe.definitions.analysis_steps
            for an example of the expected format
        :type message: dict
        """
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(tr('Analysis status'), **INFO_STYLE))
        if message is not None:
            report.add(m.ImportantText(message['name']))
            report.add(m.Paragraph(message['description']))
        report.add(self.impact_function.performance_log_message())
        send_static_message(self, report)
        self.progress_bar.setMaximum(maximum_value)
        self.progress_bar.setValue(current_value)
        QgsApplication.processEvents()
Example #6
0
 def project_check(self):
     """Sprawdzenie struktury warstw projektu."""
     if len(dlg.proj.mapLayers()) == 0:
         # QGIS nie ma otwartego projektu, tworzy nowy:
         self.project_create()
         return True
     else:
         QgsApplication.processEvents()
         # QGIS ma otwarty projekt - sprawdzanie jego struktury:
         valid = self.structure_check()
         QgsApplication.processEvents()
         if valid:
             return True
         else:
             m_text = f"Brak wymaganych warstw lub grup warstw w otwartym projekcie. Naciśnięcie Tak spowoduje przebudowanie struktury projektu, naciśnięcie Nie przerwie proces uruchamiania wtyczki."
             reply = QMessageBox.question(dlg.app, "Moek_Editor", m_text, QMessageBox.Yes, QMessageBox.No)
             if reply == QMessageBox.No:
                 return False
             else:
                 lyr_missing = self.structure_check(rebuild=True)
                 if len(lyr_missing) > 0:
                     result = self.layers_create(lyr_missing)
                     return result
                 else:
                     return True
Example #7
0
    def _clean_removed_profiles(self):
        #Delete removed profiles
        for p in self.config.removed_profiles:
            p.deleteLater()
            QgsApplication.processEvents()

        self.config.reset_removed_profiles()
Example #8
0
 def updateProgressBar(self, progressValue):
     QgsApplication.processEvents()
     if self.progressBar and not self.lockProgressBar:
         self.lockProgressBar = True
         self.progressBar.setValue(progressValue)
         self.progressValue = progressValue
         self.lockProgressBar = False
Example #9
0
    def update_entity_relations(self, profile):
        """
        Update entity relations in the profile by creating the corresponding
        foreign key references.
        :param profile: Profile whose foreign key references are to be updated.
        :type profile: Profile
        """
        fks = profile_foreign_keys(profile)

        for er in profile.relations.values():
            #Assert if the EntityRelation object is valid
            if er.valid()[0]:
                #Assert if the entity relation already exists
                if er.autoname in fks:
                    LOGGER.debug('{0} foreign key already exists.'.format(
                        er.autoname))

                    continue

                status = er.create_foreign_key_constraint()
                if not status:
                    msg = self.tr(u'Error in creating {0} foreign key '
                                  'constraint.'.format(er.name))

                else:
                    msg = self.tr(u'{0} foreign key constraint successfully '
                                  'created.'.format(er.name))

                LOGGER.debug(msg)

            QgsApplication.processEvents()
Example #10
0
    def progress_callback(self, current_value, maximum_value, message=None):
        """GUI based callback implementation for showing progress.

        :param current_value: Current progress.
        :type current_value: int

        :param maximum_value: Maximum range (point at which task is complete.
        :type maximum_value: int

        :param message: Optional message dictionary to containing content
            we can display to the user. See safe.definitions.analysis_steps
            for an example of the expected format
        :type message: dict
        """
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(
            tr('Analysis status'), **INFO_STYLE))
        if message is not None:
            report.add(m.ImportantText(message['name']))
            report.add(m.Paragraph(message['description']))
        report.add(self.impact_function.performance_log_message())
        send_static_message(self, report)
        self.progress_bar.setMaximum(maximum_value)
        self.progress_bar.setValue(current_value)
        QgsApplication.processEvents()
Example #11
0
    def _drop_entity_relations(self, profile):
        trans_msg = self.tr('Removing redundant foreign key constraints...')
        self.update_progress.emit(ConfigurationSchemaUpdater.INFORMATION,
                                  trans_msg)

        #Get existing foreign key names
        fks = profile_foreign_keys(profile)

        #Drop removed relations
        for er in profile.removed_relations:
            #Assert if the foreign key exists and skip drop if it exists
            if er.autoname in fks:
                continue

            status = er.drop_foreign_key_constraint()

            if not status:
                msg = self.tr(u'Error in removing {0} foreign key '
                              'constraint.'.format(er.autoname))
                #self.update_progress.emit(ConfigurationSchemaUpdater.WARNING, msg)

            else:
                del profile.relations[er.name]

                msg = self.tr(u'{0} foreign key constraint successfully '
                              'removed.'.format(er.autoname))
                #self.update_progress.emit(ConfigurationSchemaUpdater.INFORMATION, msg)

            QgsApplication.processEvents()

            LOGGER.debug(msg)
Example #12
0
 def layers_create(self, missing=None):
     """Utworzenie warstw w projekcie. Podanie atrybutu 'missing' spowoduje, że tylko wybrane warstwy będą dodane."""
     # Ustalenie ilości dodawanych warstw:
     i_max = len(missing) if missing else self.lyr_cnt
     # Utworzenie listy ze słownikami warstw do dodania:
     lyrs = []
     if missing:
         for l_dict in self.lyrs:
             if l_dict["name"] in missing:
                 lyrs.append(l_dict)
     else:
         lyrs = self.lyrs
     i = 0
     # Dodanie warstw:
     for l_dict in lyrs:
         QgsApplication.processEvents()
         i += 1
         dlg.splash_screen.p_bar.setValue(i * 100 / self.lyr_cnt)
         QgsApplication.processEvents()
         raw_uri = l_dict["uri"]
         uri = eval("f'{}'".format(raw_uri))
         if l_dict["source"] == "wms" or l_dict["source"] == "gdal":
             lyr = QgsRasterLayer(uri, l_dict["name"], l_dict["source"])
             lyr_required = False
         else:
             lyr = QgsVectorLayer(uri, l_dict["name"], l_dict["source"])
             lyr_required = True
         if not lyr.isValid() and not lyr_required:
             m_text = f'Nie udało się poprawnie wczytać podkładu mapowego: {l_dict["name"]}. Naciśnięcie Tak spowoduje kontynuowanie uruchamiania wtyczki (podkład mapowy nie będzie wyświetlany), naciśnięcie Nie przerwie proces uruchamiania wtyczki. Jeśli problem będzie się powtarzał, zaleca się powiadomienie administratora systemu.'
             reply = QMessageBox.question(dlg.app, "Moek_Editor", m_text, QMessageBox.Yes, QMessageBox.No)
             if reply == QMessageBox.No:
                 return False
         elif not lyr.isValid() and lyr_required:
             m_text = f'Nie udało się poprawnie wczytać warstwy: {l_dict["name"]}. Jeśli problem będzie się powtarzał, proszę o powiadomienie administratora systemu.'
             QMessageBox.critical(dlg.app, "Moek_Editor", m_text)
             return False
         if l_dict["source"] == "memory":
             lyr.setCustomProperty("skipMemoryLayersCheck", 1)
             pr = lyr.dataProvider()
             pr.addAttributes(l_dict["attrib"])
             lyr.updateFields()
         if "crs" in l_dict:
             lyr.setCrs(CRS_1992)
         dlg.proj.addMapLayer(lyr, False)
         if l_dict["root"]:
             parent_grp = self.root
             parent_grp.insertChildNode(l_dict["pos"], QgsLayerTreeLayer(lyr))
             parent_grp.findLayer(lyr).setItemVisibilityChecked(l_dict["visible"])
         else:
             if "pos" in l_dict:
                 parent_grp = self.root.findGroup(l_dict["parent"])
                 parent_grp.insertChildNode(l_dict["pos"], QgsLayerTreeLayer(lyr))
                 parent_grp.findLayer(lyr).setItemVisibilityChecked(False)
             else:
                 parent_grp = self.root.findGroup(l_dict["parent"])
                 node = parent_grp.addLayer(lyr)
                 node.setItemVisibilityChecked(l_dict["visible"])
         lyr.loadNamedStyle(f'{STYLE_PATH}{l_dict["name"].lower()}.qml')
     return True
def main(args=None):

    # supply path to qgis install location
    QgsApplication.setPrefixPath("/usr", True)

    # create a reference to the QgsApplication
    # setting the second argument to True enables the IquaView GUI,
    # which we need to do since this is a custom application
    qgs = QgsApplication([], True)

    # init splash screen
    splash_pix = QPixmap(':/resources/iquaview.png')
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())

    light_blue = QColor(165, 197, 192)
    dark_blue = QColor(11, 52, 70)
    # adding progress bar
    progress_bar = QProgressBar(splash)
    p = progress_bar.palette()
    p.setColor(QPalette.Highlight, light_blue)
    p.setColor(QPalette.HighlightedText, dark_blue)
    progress_bar.setPalette(p)
    progress_bar.setMaximum(10)
    progress_bar.setGeometry(0,
                             splash_pix.height() - 50, splash_pix.width(), 20)

    splash.show()
    splash.showMessage("Initializing interface...",
                       Qt.AlignBottom | Qt.AlignCenter, light_blue)

    # progress bar...
    for i in range(1, 11):
        progress_bar.setValue(i)
        t = time()
        if i == 5:
            splash.showMessage("Loading providers...",
                               Qt.AlignBottom | Qt.AlignCenter, light_blue)
            # load providers
            qgs.initQgis()
            LOGGER.info(qgs.showSettings())
        if i == 10:
            # exec iquaview window
            window = MainWindow()
            window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg"))
            splash.showMessage("IQUAview ready!",
                               Qt.AlignBottom | Qt.AlignCenter, light_blue)

        while time() < t + 0.1:
            qgs.processEvents()

    window.showMaximized()
    splash.finish(window)

    qgs.exec_()
    window.deleteLater()
    # when app terminates, call exitQgis() to remove the provider and layer registries from memory
    qgs.exitQgis()
Example #14
0
 def show_busy(self):
     """Lock buttons and enable the busy cursor."""
     self.progress_bar.show()
     self.parent.pbnNext.setEnabled(False)
     self.parent.pbnBack.setEnabled(False)
     self.parent.pbnCancel.setEnabled(False)
     self.parent.repaint()
     enable_busy_cursor()
     QgsApplication.processEvents()
Example #15
0
 def show_busy(self):
     """Lock buttons and enable the busy cursor."""
     self.progress_bar.show()
     self.parent.pbnNext.setEnabled(False)
     self.parent.pbnBack.setEnabled(False)
     self.parent.pbnCancel.setEnabled(False)
     self.parent.repaint()
     enable_busy_cursor()
     QgsApplication.processEvents()
Example #16
0
def vn_zoom(player=False):
    """Zbliżenie mapy do wybranego vn'a."""
    layer = dlg.proj.mapLayersByName("vn_sel")[0]
    layer.selectAll()
    canvas = iface.mapCanvas()
    canvas.zoomToSelected(layer)
    QgsApplication.processEvents()
    layer.removeSelection()
    canvas.refresh()
Example #17
0
    def save_scheme(self):
        """
        Save scheme information, move supporting documents, save holders
        table and create appropriate notifications.
        """
        sch_number = None
        pg_dlg = QProgressDialog(parent=self)
        pg_dlg.setWindowModality(Qt.WindowModal)
        pg_dlg.setMinimum(0)
        pg_dlg.setMaximum(4)
        pg_dlg.setCancelButton(None)
        pg_dlg.setWindowTitle(self.tr('Saving Scheme Information...'))

        pg_dlg.setLabelText(self.tr('Retrieving scheme attribute data...'))
        pg_dlg.setValue(1)
        # Get scheme db object for manual saving to database.
        self.submit(True)
        scheme_obj = self.model()
        scheme_obj.plot_status = 2
        QgsApplication.processEvents()

        pg_dlg.setLabelText(
            self.tr('Saving supporting documents, please wait...'))
        pg_dlg.setValue(2)

        # Format scheme number for saving in document repository
        if not sch_number:
            sch_number = scheme_obj.scheme_number.replace(" / ", "_")
            sch_number = sch_number.replace(" ", "_")

        # Attach documents
        doc_objs = self._cmis_doc_mapper.persist_documents(sch_number)
        scheme_obj.documents = doc_objs
        QgsApplication.processEvents()

        pg_dlg.setLabelText(self.tr('Saving scheme data...'))
        pg_dlg.setValue(3)
        scheme_obj.save()

        # Update last value for generating scheme number
        self._save_ra_last_value(scheme_obj.scheme_number)
        QgsApplication.processEvents()

        pg_dlg.setLabelText(self.tr('Saving holders data...'))
        pg_dlg.setValue(4)
        QgsApplication.processEvents()
        # Attach the scheme object to the holders
        self._holder_importer.set_extra_attribute_value(
            'cb_scheme_collection', [scheme_obj])
        # Save holders data
        self._holder_importer.start()
        QgsApplication.processEvents()

        msg = self.tr(
            u'A new scheme (No. {0}) has been successfully lodged.'.format(
                scheme_obj.scheme_number))
        QMessageBox.information(self, self.tr('New Scheme'), msg)
Example #18
0
 def _updateLayer(self, layer):
     if self.iface and self.previewEnabled:
         for exporter in self.exporter.exporters(layer):
             if self.aborted:
                 return False
             self.iface.loadJSONObject(exporter.build())
             QgsApplication.processEvents()
             # NOTE: process events only for the calling thread
         layer.updated = False
         return True
Example #19
0
    def run(self):
        """Run method that loads and starts the plugin"""
        self.start = time.perf_counter()
        if self.plugin_is_active: # Sprawdzenie, czy plugin jest już uruchomiony
            QMessageBox.information(None, "Informacja", "Wtyczka jest już uruchomiona")
            return  # Uniemożliwienie uruchomienia drugiej instancji pluginu

        # Logowanie użytkownika do bazy danych i pobranie wartości podstawowych zmiennych:
        user_id, user_name, team_i = db_login()
        if not user_id:
            return  # Użytkownik nie zalogował się poprawnie, przerwanie ładowania pluginu

        if not self.plugin_is_active:
            self.plugin_is_active = True

            #print "** STARTING MoekEditor"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = MoekEditorDockWidget(user_id, user_name, team_i)

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # Załadowanie team'ów:
            if not teams_load():  # Nie udało się załadować team'ów użytkownika, przerwanie ładowania pluginu
                self.iface.removeDockWidget(self.dockwidget)
                return
        project_check = self.dockwidget.lyr.project_check()  # Utworzenie nowego projektu QGIS i załadowanie do niego warstw
        if not project_check:
            try:
                self.dockwidget.close()
            except Exception as err:
                print(f"moek_editor/run: {err}")
            return
        self.title_change()  # Zmiana tytułu okna QGIS
        self.dockwidget.splash_screen.p_bar.setMaximum(0)
        QgsApplication.processEvents()
        self.dockwidget.ge = GESync()  # Integracja z Google Earth Pro
        teams_cb_changed()  # Załadowanie powiatów
        # show the dockwidget
        # TODO: fix to allow choice of dock location
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
        self.dockwidget.obj.init_void = False  # Odblokowanie ObjectManager'a
        self.dockwidget.button_conn()  # Podłączenie akcji przycisków
        self.dockwidget.mt.init("multi_tool")  # Aktywacja multi_tool'a
        self.dockwidget.splash_screen.hide()
        self.dockwidget.show()
        self.dockwidget.side_dock.show()

        finish = time.perf_counter()
        print(f"Proces ładowania pluginu trwał {round(finish - self.start, 2)} sek.")
Example #20
0
 def project_create(self):
     """Utworzenie nowego projektu QGIS."""
     iface.newProject(promptToSaveFlag=False)
     # Zmiana tytułu okna QGIS'a:
     dlg.proj.setCrs(CRS_1992)
     # iface.mainWindow().setWindowTitle(new_title)
     QgsApplication.processEvents()
     self.groups_create()
     QgsApplication.processEvents()
     self.layers_create()
     return True
        def _test(is_sidecar):

            QgsProject.instance().removeAllMapLayers()

            tmp_dir = QTemporaryDir()
            shutil.copy(os.path.join(os.path.dirname(
                __file__), 'data', 'raster-palette.tif'), tmp_dir.path())

            rat_path = os.path.join(
                tmp_dir.path(), 'raster-palette.tif' + ('.vat.dbf' if is_sidecar else '.aux.xml'))
            self.assertFalse(os.path.exists(rat_path))

            raster_layer = QgsRasterLayer(os.path.join(tmp_dir.path(), 'raster-palette.tif'), 'rat_test', 'gdal')
            QgsProject.instance().addMapLayer(raster_layer)

            self.assertTrue(raster_layer.isValid())
            self.assertFalse(can_create_rat(raster_layer))
            self.assertFalse(has_rat(raster_layer))

            band = 1

            # Set renderer
            ramp = QgsRandomColorRamp()
            renderer = QgsPalettedRasterRenderer(
                raster_layer.dataProvider(), 1, QgsPalettedRasterRenderer.classDataFromRaster(raster_layer.dataProvider(), band, ramp))
            raster_layer.setRenderer(renderer)
            self.assertTrue(can_create_rat(raster_layer))

            rat = create_rat_from_raster(raster_layer, is_sidecar, rat_path)
            self.assertTrue(rat.isValid())

            self.assertEqual(rat.data['Count'], [78, 176, 52])
            self.assertEqual(rat.data['Value'], [
                            2.257495271713565, 7.037407804695962, 270.4551067154352])
            self.assertEqual(rat.data['A'], [255, 255, 255])
            self.assertNotEqual(rat.data['R'], [0, 0, 0])

            self.assertTrue(rat.save(band))
            self.assertTrue(os.path.exists(rat_path))

            QgsProject.instance().removeMapLayers([raster_layer.id()])
            del (raster_layer)

            self.assertTrue(os.path.exists(rat_path))
            QgsApplication.processEvents()

            # Reload and check
            raster_layer = QgsRasterLayer(os.path.join(
                tmp_dir.path(), 'raster-palette.tif'), 'rat_test', 'gdal')
            self.assertTrue(raster_layer.isValid())
            self.assertFalse(can_create_rat(raster_layer))
            self.assertTrue(has_rat(raster_layer), rat_path)

            os.unlink(rat_path)
Example #22
0
    def redraw(self):
        # If caching is enabled, a simple canvas refresh might not be
        # sufficient to trigger a redraw and you must clear the cached image
        # for the layer
        if self.iface.mapCanvas().isCachingEnabled():
            vlayer = self.get_current_vector_layer()
            if vlayer is None:
                return
            vlayer.triggerRepaint()

        self.iface.mapCanvas().refresh()
        QgsApplication.processEvents()
Example #23
0
    def _buildLayer(self, layer):
        self.iface.runScript('loadStart("L{}");  // {}'.format(
            layer.jsLayerId, layer.name))
        pmsg = "Building {0}...".format(layer.name)
        self.iface.progress(0, pmsg)

        if layer.geomType == q3dconst.TYPE_POINT and layer.properties.get(
                "comboBox_ObjectType") == "Model File":
            self.iface.loadScriptFiles(
                [q3dconst.SCRIPT_COLLADALOADER, q3dconst.SCRIPT_GLTFLOADER])
        elif layer.geomType == q3dconst.TYPE_POINTCLOUD:
            self.iface.loadScriptFiles([
                q3dconst.SCRIPT_FETCH, q3dconst.SCRIPT_POTREE,
                q3dconst.SCRIPT_PCLAYER
            ])

        t0 = t4 = time.time()
        dlist = []
        i = 0
        for builder in self.builder.builders(layer):
            self.iface.progress(i / (i + 4) * 100, pmsg)
            if self.aborted:
                self.iface.runScript("loadAborted();")
                logMessage("***** layer building aborted *****", False)
                return False

            t1 = time.time()
            obj = builder.build()
            t2 = time.time()

            self.iface.loadJSONObject(obj)
            QgsApplication.processEvents(
            )  # NOTE: process events only for the calling thread
            i += 1

            t3 = time.time()
            dlist.append([t1 - t4, t2 - t1, t3 - t2])
            t4 = t3

        layer.updated = False

        self.iface.runScript('loadEnd("L{}");'.format(layer.jsLayerId))

        if DEBUG_MODE:
            dlist = "\n".join([
                " {:.3f} {:.3f} {:.3f}".format(d[0], d[1], d[2]) for d in dlist
            ])
            qDebug("{0} layer updated: {1:.3f}s\n{2}\n".format(
                layer.name,
                time.time() - t0, dlist).encode("utf-8"))
        return True
Example #24
0
    def progress(self, percentage=None, statusMsg=None):
        ui = self.ui
        if percentage is not None:
            ui.progressBar.setValue(percentage)
            if percentage == 100:
                ui.progressBar.setVisible(False)
                ui.label_Status.setText("")
            else:
                ui.progressBar.setVisible(True)

        if statusMsg is not None:
            ui.label_Status.setText(statusMsg)
            ui.label_Status.repaint()
        QgsApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
Example #25
0
  def progress(self, percentage=None, statusMsg=None):
    ui = self.ui
    if percentage is not None:
      ui.progressBar.setValue(percentage)
      if percentage == 100:
        ui.progressBar.setVisible(False)
        ui.label_Status.setText("")
      else:
        ui.progressBar.setVisible(True)

    if statusMsg is not None:
      ui.label_Status.setText(statusMsg)
      ui.label_Status.repaint()
    QgsApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
Example #26
0
    def progress(self, percentage=None, msg=None):
        pbar = self.ui.progressBar

        if percentage is not None:
            pbar.setValue(percentage)
            if percentage == 100:
                pbar.setVisible(False)
                pbar.setFormat("")
            else:
                pbar.setVisible(True)

        if msg is not None:
            pbar.setFormat(msg)

        QgsApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
Example #27
0
    def progress(self, percentage=None, msg=None, numbered=False):
        if percentage is not None:
            self.ui.progressBar.setValue(percentage)

            v = bool(percentage != 100)
            self.ui.progressBar.setEnabled(v)
            self.ui.pushButton_Cancel.setEnabled(v)

        if msg:
            if numbered:
                msg = "{}. {}".format(self.logNextIndex, msg)
                self.logNextIndex += 1
            self.logHtml += "<div class='progress'>{}</div>".format(msg)
            self.ui.textBrowser.setHtml(self.logHtml)

        QgsApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
Example #28
0
    def _update_entities(self, entities):
        for e in entities:
            action = e.action

            if action != DbItem.NONE:
                action_txt = unicode(self._action_text(action))
                trans_msg = u'{0} {1} entity...'.format(
                    action_txt.capitalize(), e.short_name)

                msg = self.tr(trans_msg)

                LOGGER.debug(trans_msg)

                self.update_progress.emit(
                    ConfigurationSchemaUpdater.INFORMATION, msg)

                e.update(self.engine, self.metadata)

            QgsApplication.processEvents()
Example #29
0
    def exportLayer(self, layer):
        if self.iface and self.enabled:
            if layer.geomType == q3dconst.TYPE_DEM:
                for exporter in self.exporter.demExporters(layer):
                    self.iface.loadJSONObject(exporter.build())
                    QgsApplication.processEvents(
                        QEventLoop.ExcludeUserInputEvents)
                    # NOTE: process events only for the calling thread

            elif layer.geomType in [
                    q3dconst.TYPE_POINT, q3dconst.TYPE_LINESTRING,
                    q3dconst.TYPE_POLYGON
            ]:
                for exporter in self.exporter.vectorExporters(layer):
                    self.iface.loadJSONObject(exporter.build())
                    QgsApplication.processEvents(
                        QEventLoop.ExcludeUserInputEvents)

            layer.updated = False
Example #30
0
    def _test_con(self):
        """
        Tests a connection.
        """

        msg_dur = 5000

        try:
            self._enable_wdgs(False)
            if self.ok_btn.isEnabled():
                self.ok_btn.setEnabled(False)

            QgsApplication.processEvents()

            con_info = self._con_info
            self._save_con_info(con_info)

            QgsApplication.processEvents()

            self.mc.con = db.get_con(con_info)

            if db.chck_nofa_tbls(self.mc.con):
                QMessageBox.information(
                    self, u'Success',
                    u'Connection to NOFA database succeeded.')
                self.ok_btn.setEnabled(True)
            else:
                QMessageBox.warning(
                    self, u'Success - not NOFA',
                    u'Connection succeeded but the database is not NOFA.')
                self.ok_btn.setEnabled(False)

                self.mc.con.close()
                self.mc.con = None
        except psycopg2.OperationalError:
            self.mc.con = None
            self.ok_btn.setEnabled(False)
            QMessageBox.warning(self, u'Fail', u'Connection failed.')
        except:
            self.mc.disp_err()
        finally:
            self._enable_wdgs(True)
Example #31
0
 def project_create(self):
     """Utworzenie nowego projektu QGIS."""
     iface.newProject(False)
     try:
         bmap = self.get_google_layer()
         bmap.renderer().setOpacity(0.75)
     except:
         bmap = None
     if bmap:
         dlg.proj.addMapLayer(bmap)
     else:
         print("Błąd przy załadowaniu WMS!")
     QgsApplication.processEvents()
     dlg.proj.setCrs(CRS_1992)
     canvas = iface.mapCanvas()
     canvas.setExtent(init_extent())
     self.groups_create()
     self.layers_create()
     self.layer_to_group_move(lyr_name="Google Map")
     return True
Example #32
0
    def _buildLayer(self, layer):
        self.iface.runScript('loadStart("L{}");  // {}'.format(
            layer.jsLayerId, layer.name))
        pmsg = "Building {0}...".format(layer.name)
        self.iface.progress(0, pmsg)

        if layer.properties.get("comboBox_ObjectType") == "Model File":
            self.iface.loadModelLoaders()

        ts0 = time.time()
        tss = []
        i = 0
        for builder in self.builder.builders(layer):
            self.iface.progress(i / (i + 4) * 100, pmsg)
            if self.aborted:
                self.iface.runScript("loadAborted();")
                logMessage("***** layer building aborted *****", False)
                return False
            ts1 = time.time()
            obj = builder.build()
            ts2 = time.time()
            self.iface.loadJSONObject(obj)
            ts3 = time.time()
            tss.append([ts2 - ts1, ts3 - ts2])
            QgsApplication.processEvents(
            )  # NOTE: process events only for the calling thread
            i += 1

        layer.updated = False

        self.iface.runScript('loadEnd("L{}");'.format(layer.jsLayerId))
        self.iface.progress()

        if DEBUG_MODE:
            msg = "updating {0} costed {1:.3f}s:\n{2}".format(
                layer.name,
                time.time() - ts0,
                "\n".join(["{:.3f} {:.3f}".format(ts[0], ts[1])
                           for ts in tss]))
            logMessage(msg, False)
        return True
Example #33
0
            def progress_event(received, total):
                """Update progress.

                :param received: Data received so far.
                :type received: int

                :param total: Total expected data.
                :type total: int
                """
                # noinspection PyArgumentList
                QgsApplication.processEvents()

                self.progress_dialog.adjustSize()

                human_received = humanize_file_size(received)
                human_total = humanize_file_size(total)

                label_text = tr("%s : %s of %s" % (
                    self.prefix_text, human_received, human_total))

                self.progress_dialog.setLabelText(label_text)
                self.progress_dialog.setMaximum(total)
                self.progress_dialog.setValue(received)
Example #34
0
    def testExecuteSqlCancel(self):
        """Test that feedback can cancel an executeSql query"""

        if hasattr(self, 'slowQuery'):

            md = QgsProviderRegistry.instance().providerMetadata(self.providerKey)
            conn = md.createConnection(self.uri, {})
            feedback = QgsFeedback()

            def _run(task):
                conn.executeSql(self.slowQuery, feedback=feedback)

            def _cancel():
                feedback.cancel()

            start = time.time()
            QtCore.QTimer.singleShot(500, _cancel)
            task = QgsTask.fromFunction('test long running query', _run)
            QgsApplication.taskManager().addTask(task)
            while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
                QgsApplication.processEvents()
            end = time.time()
            self.assertTrue(end - start < 1)
Example #35
0
            def progress_event(received, total):
                """Update progress.

                :param received: Data received so far.
                :type received: int

                :param total: Total expected data.
                :type total: int
                """
                # noinspection PyArgumentList
                QgsApplication.processEvents()

                self.progress_dialog.adjustSize()

                human_received = humanize_file_size(received)
                human_total = humanize_file_size(total)

                label_text = tr(
                    "%s : %s of %s" %
                    (self.prefix_text, human_received, human_total))

                self.progress_dialog.setLabelText(label_text)
                self.progress_dialog.setMaximum(total)
                self.progress_dialog.setValue(received)
Example #36
0
    def download(self):
        """Downloading the file.

        :returns: True if success, otherwise returns a tuple with format like
            this (QNetworkReply.NetworkError, error_message)

        :raises: IOError - when cannot create output_path
        """
        # Prepare output path
        self.output_file = QFile(self.output_path)
        if not self.output_file.open(QFile.WriteOnly):
            raise IOError(self.output_file.errorString())

        # Prepare downloaded buffer
        self.downloaded_file_buffer = QByteArray()

        # Request the url
        request = QNetworkRequest(self.url)
        self.reply = self.manager.get(request)
        self.reply.readyRead.connect(self.get_buffer)
        self.reply.finished.connect(self.write_data)
        self.manager.requestTimedOut.connect(self.request_timeout)

        if self.progress_dialog:
            # progress bar
            def progress_event(received, total):
                """Update progress.

                :param received: Data received so far.
                :type received: int

                :param total: Total expected data.
                :type total: int
                """
                # noinspection PyArgumentList
                QgsApplication.processEvents()

                self.progress_dialog.adjustSize()

                human_received = humanize_file_size(received)
                human_total = humanize_file_size(total)

                label_text = tr("%s : %s of %s" % (
                    self.prefix_text, human_received, human_total))

                self.progress_dialog.setLabelText(label_text)
                self.progress_dialog.setMaximum(total)
                self.progress_dialog.setValue(received)

            # cancel
            def cancel_action():
                """Cancel download."""
                self.reply.abort()
                self.reply.deleteLater()

            self.reply.downloadProgress.connect(progress_event)
            self.progress_dialog.canceled.connect(cancel_action)

        # Wait until finished
        # On Windows 32bit AND QGIS 2.2, self.reply.isFinished() always
        # returns False even after finished slot is called. So, that's why we
        # are adding self.finished_flag (see #864)
        while not self.reply.isFinished() and not self.finished_flag:
            # noinspection PyArgumentList
            QgsApplication.processEvents()

        result = self.reply.error()
        try:
            http_code = int(self.reply.attribute(
                QNetworkRequest.HttpStatusCodeAttribute))
        except TypeError:
            # If the user cancels the request, the HTTP response will be None.
            http_code = None

        self.reply.abort()
        self.reply.deleteLater()

        if result == QNetworkReply.NoError:
            return True, None

        elif result == QNetworkReply.UnknownNetworkError:
            return False, tr(
                'The network is unreachable. Please check your internet '
                'connection.')

        elif http_code == 408:
            msg = tr(
                'Sorry, the server aborted your request. '
                'Please try a smaller area.')
            LOGGER.debug(msg)
            return False, msg

        elif http_code == 509:
            msg = tr(
                'Sorry, the server is currently busy with another request. '
                'Please try again in a few minutes.')
            LOGGER.debug(msg)
            return False, msg

        elif result == QNetworkReply.ProtocolUnknownError or \
                result == QNetworkReply.HostNotFoundError:
            # See http://doc.qt.io/qt-5/qurl-obsolete.html#encodedHost
            encoded_host = self.url.toAce(self.url.host())
            LOGGER.exception('Host not found : %s' % encoded_host)
            return False, tr(
                'Sorry, the server is unreachable. Please try again later.')

        elif result == QNetworkReply.ContentNotFoundError:
            LOGGER.exception('Path not found : %s' % self.url.path())
            return False, tr('Sorry, the layer was not found on the server.')

        else:
            return result, self.reply.errorString()
Example #37
0
 def removeProgressBar(self, msgBarItem):
     self.progressBar = None
     if self.progressValue != 100:  # To recognize an abortement by user of import.
         QgsApplication.processEvents()
         self.worker.stop = True
 def translate_callback(self, pct, msg, user_data):
     self.progress_dlg.setValue(int(100*pct))
     QgsApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
     if self.progress_dlg.wasCanceled():
         return 0
     return 1
 def addFeatures(self, layerid, features, fields, points=None, lines=None, polygons=None, permissions={}, add_empty=False, addToMap=True):
     """ Add DIVI layer to QGIS """
     qgis_fields = [ QgsField(field['key'], self.TYPES_MAP.get(field['type'], QVariant.String)) for field in fields ]
     #print (qgis_fields)
     #print (points, lines, polygons)
     if points is not None:
         points_pr = points.dataProvider()
         if points_pr.fields():
             points_pr.deleteAttributes(list(range(len(points_pr.fields()))))
         points_pr.addAttributes(qgis_fields)
         points.updateFields()
     if lines is not None:
         lines_pr = lines.dataProvider()
         if lines_pr.fields():
             lines_pr.deleteAttributes(list(range(len(lines_pr.fields()))))
         lines_pr.addAttributes(qgis_fields)
         lines.updateFields()
     if polygons is not None:
         polygons_pr = polygons.dataProvider()
         if polygons_pr.fields():
             polygons_pr.deleteAttributes(list(range(len(polygons_pr.fields()))))
         x = polygons_pr.addAttributes(qgis_fields)
         polygons.updateFields()
     #Lists of QGIS features
     points_list = []
     lines_list = []
     polygons_list = []
     count = float(len(features))
     points_ids = []
     lines_ids = []
     polygons_ids = []
     for i, feature in enumerate(features, start=1):
         #Geometria w formacie WKB zakodowanym przez base64
         geom = QgsGeometry()
         geom.fromWkb(b64decode(feature['geometry']))
         f = QgsFeature()
         f.setGeometry(geom)
         f.setAttributes([ feature['properties'].get(field['key']) for field in fields ])
         #Add feature to list by geometry type
         if geom.type() == QgsWkbTypes.PointGeometry:
             points_list.append(f)
             points_ids.append(feature['id'])
         elif geom.type() == QgsWkbTypes.LineGeometry:
             lines_list.append(f)
             lines_ids.append(feature['id'])
         elif geom.type() == QgsWkbTypes.PolygonGeometry:
             polygons_list.append(f)
             polygons_ids.append(feature['id'])
         else:
             continue
         if self.msgBar is not None:
             #self.msgBar.setProgress(i/count)
             pass
             QgsApplication.processEvents()
             if self.msgBar.aborted:
                 #Użytkownik anulował operację
                 return []
     #Add only layers that have features
     result = []
     register = partial(self.registerLayer, layerid=layerid, permissions=permissions,
         addToMap=addToMap, fields=fields)
     if points is not None and (points_list or add_empty):
         lyr, added = register(layer=points, features=points_list)
         result.append(lyr)
         self.ids_map[points.id()] = dict(list(zip(added, points_ids)))
     if lines is not None and (lines_list or add_empty):
         lyr, added = register(layer=lines, features=lines_list)
         result.append(lyr)
         self.ids_map[lines.id()] = dict(list(zip(added, lines_ids)))
     if polygons is not None and (polygons_list or add_empty):
         lyr, added = register(layer=polygons, features=polygons_list)
         result.append(lyr)
         self.ids_map[polygons.id()] = dict(list(zip(added, polygons_ids)))
     return result
Example #40
0
    def insert_line(self):
        layer = self.iface.activeLayer()
        if not isinstance(layer, QgsVectorLayer) or layer.geometryType() != QGis.Line:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Select lines layer for inserting new geom!"),
                                    level=QgsMessageBar.WARNING,
                                    duration=5)
            return

        if not layer.isEditable():
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                    self.tr("Line can\'t be inserted! Layer is not editable!"),
                                    level=QgsMessageBar.WARNING,
                                    duration=5)
            return

        if not self._geom_buffer:
            self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                        self.tr("Line can\'t be inserted! Copy points first!"),
                        level=QgsMessageBar.WARNING,
                        duration=5)
            return

        #show message
        self.iface.messageBar().clearWidgets()
        self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                            self.tr("Processing points. Please wait..."),
                                            level=QgsMessageBar.INFO
                                            )
        QgsApplication.setOverrideCursor(Qt.WaitCursor)
        QgsApplication.processEvents()
        QgsApplication.processEvents()
        QgsApplication.processEvents()

        try:
            # Create line

            # QGS geoms to np
            points = [(in_geom.x(), in_geom.y()) for in_geom in self._geom_buffer]
            data = np.array(points)

            # Make line
            som = SOM1d(data)
            result = som.connect()

            #np to QGS
            self._geom_buffer = [QgsPoint(out_geom[0], out_geom[1]) for out_geom in result]

            if layer.wkbType() == QGis.WKBMultiLineString:
                geom = QgsGeometry.fromMultiPolyline([self._geom_buffer])
            else:
                geom = QgsGeometry.fromPolyline(self._geom_buffer)

            # Check crs and reproject
            target_crs = layer.crs()
            if target_crs.srsid() != self._srid.srsid():
                transf = QgsCoordinateTransform(self._srid, target_crs)
                geom.transform(transf)

            # Insert feature
            feat = QgsFeature()
            feat.setFields(layer.dataProvider().fields())
            feat.setGeometry(geom)

            suppressForm = QSettings().value("/qgis/digitizing/disable_enter_attribute_values_dialog", type=bool, defaultValue=False)

            if suppressForm:
                # quite insert feature
                result = layer.addFeatures([feat])
            else:
                # show dialog
                QgsApplication.restoreOverrideCursor()
                attrDialog = QgsAttributeDialog(layer, feat, False)
                attrDialog.setIsAddDialog(True)
                result = attrDialog.exec_()

            # show message
            self.iface.messageBar().clearWidgets()
            if result:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("One line was sucesfull added"),
                                                level=QgsMessageBar.INFO)
            else:
                self.iface.messageBar().pushMessage(self.tr("ReconstructLine"),
                                                self.tr("Line was not added"),
                                                level=QgsMessageBar.CRITICAL)

            self.iface.mapCanvas().refresh()
        finally:
            QgsApplication.restoreOverrideCursor()