Ejemplo n.º 1
0
    def testTaskFromFunctionWithSubTaskCompletedIsCalledOnce(self):  # spellok
        """ test that when a parent task has subtasks it does emit taskCompleted only once"""

        self.finished = 0
        self.completed = 0

        def _on_finished(e):
            self.finished += 1

        def _on_completed():
            self.completed += 1

        task = QgsTask.fromFunction('test task', run_no_result, on_finished=_on_finished)
        task.taskCompleted.connect(_on_completed)
        spy = QSignalSpy(task.taskCompleted)
        sub_task_1 = QgsTask.fromFunction('test subtask 1', run_no_result, on_finished=_on_finished)
        sub_task_2 = QgsTask.fromFunction('test subtask 2', run_no_result, on_finished=_on_finished)
        task.addSubTask(sub_task_1, [], QgsTask.ParentDependsOnSubTask)
        task.addSubTask(sub_task_2, [], QgsTask.ParentDependsOnSubTask)

        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            QCoreApplication.processEvents()
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        self.assertEqual(self.completed, 1)
        self.assertEqual(self.finished, 3)
        self.assertEqual(len(spy), 1)
Ejemplo n.º 2
0
    def testLayerRemovalBeforeRun(self):
        """test behavior when layer is removed before task begins"""
        path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif')
        raster_layer = QgsRasterLayer(path, "test")
        self.assertTrue(raster_layer.isValid())

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(raster_layer.dataProvider().clone()))

        tmp = create_temp_filename('remove_layer.tif')
        writer = QgsRasterFileWriter(tmp)

        task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs())

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        # remove layer
        raster_layer = None

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        # in this case will still get a positive result - since the pipe is cloned before the task
        # begins the task is no longer dependent on the original layer
        self.assertTrue(self.success)
        self.assertFalse(self.fail)
        self.assertTrue(os.path.exists(tmp))
Ejemplo n.º 3
0
    def testTaskFromFunctionWithKwargs(self):
        """ test creating task from function using kwargs """

        task = QgsTask.fromFunction('test task3', run_with_kwargs, result=5, password=1)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass

        self.assertEqual(task.returned_values, 5)
        self.assertFalse(task.exception)
        self.assertEqual(task.status(), QgsTask.Complete)
    def testFetchBadUrl(self):
        fetcher = QgsNetworkContentFetcherTask(QUrl('http://x'))
        self.loaded = False

        def check_reply():
            r = fetcher.reply()
            assert r.error() != QNetworkReply.NoError
            self.loaded = True

        fetcher.fetched.connect(check_reply)
        QgsApplication.taskManager().addTask(fetcher)
        while not self.loaded:
            app.processEvents()
Ejemplo n.º 5
0
    def testTaskFromFunctionFinished(self):
        """ test that task from function can have callback finished function"""
        task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_no_val)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertFalse(task.returned_values)
        self.assertFalse(task.exception)
        self.assertTrue(finished_no_val.called)
Ejemplo n.º 6
0
    def testTaskFromFunctionFinishedWithVal(self):
        """ test that task from function can have callback finished function and is passed result values"""
        task = QgsTask.fromFunction('test task', run_single_val_result, on_finished=finished_single_value_result)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertEqual(task.returned_values, (5))
        self.assertFalse(task.exception)
        self.assertEqual(finished_single_value_result.value, 5)
Ejemplo n.º 7
0
    def testTaskFromFunctionFinishedFail(self):
        """ test that task from function which fails calls finished with exception"""
        task = QgsTask.fromFunction('test task', run_fail, on_finished=finished_fail)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertTrue(task.exception)
        self.assertTrue(finished_fail.finished_exception)
        self.assertEqual(task.exception, finished_fail.finished_exception)
Ejemplo n.º 8
0
    def testTaskFromFunctionCanceledWhileQueued(self):
        """ test that task from finished is called with exception when task is terminated while queued"""
        task = QgsTask.fromFunction('test task', run_no_result, on_finished=finished_fail)
        task.hold()
        QgsApplication.taskManager().addTask(task)
        task.cancel()
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertTrue(task.exception)
        self.assertTrue(finished_fail.finished_exception)
        self.assertEqual(task.exception, finished_fail.finished_exception)
Ejemplo n.º 9
0
    def testTaskFromFunctionIsCancellable(self):
        """ test that task from function can check canceled status """
        bad_task = QgsTask.fromFunction('test task4', cancellable)
        QgsApplication.taskManager().addTask(bad_task)
        while bad_task.status() != QgsTask.Running:
            pass

        bad_task.cancel()
        while bad_task.status() == QgsTask.Running:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        self.assertEqual(bad_task.status(), QgsTask.Terminated)
        self.assertTrue(bad_task.exception)
Ejemplo n.º 10
0
    def testNoLayer(self):
        """test that failure (and not crash) occurs when no layer set"""

        options = QgsVectorFileWriter.SaveVectorOptions()
        tmp = create_temp_filename('fail.shp')
        task = QgsVectorFileWriterTask(None, tmp, options)
        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertFalse(self.success)
        self.assertTrue(self.fail)
Ejemplo n.º 11
0
    def testFetchUrlContent(self):
        fetcher = QgsNetworkContentFetcherTask(
            QUrl('http://localhost:' + str(self.port) + '/qgis_local_server/index.html'))
        self.loaded = False

        def check_reply():
            r = fetcher.reply()
            assert r.error() == QNetworkReply.NoError, r.error()

            assert b'QGIS' in r.readAll()
            self.loaded = True

        fetcher.fetched.connect(check_reply)
        QgsApplication.taskManager().addTask(fetcher)
        while not self.loaded:
            app.processEvents()
Ejemplo n.º 12
0
    def testSuccess(self):
        """test successfully writing a layer"""
        self.layer = self.createLayer()
        options = QgsVectorFileWriter.SaveVectorOptions()
        tmp = create_temp_filename('successlayer.shp')
        task = QgsVectorFileWriterTask(self.layer, tmp, options)

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)
Ejemplo n.º 13
0
    def testTaskFromFunctionCanSetProgress(self):
        """ test that task from function can set progress """
        task = QgsTask.fromFunction('test task5', progress_function)
        QgsApplication.taskManager().addTask(task)
        while task.status() != QgsTask.Running:
            pass

        # wait a fraction so that setProgress gets a chance to be called
        sleep(0.001)
        self.assertEqual(task.progress(), 50)
        self.assertFalse(task.exception)

        task.cancel()
        while task.status() == QgsTask.Running:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()
  def __init__(self, iface, dockWidgetGui):
    def createDirectories():
      dirPlugin = os.path.dirname(__file__)
      dirImage = os.path.join( dirPlugin, 'img' )
      if not os.path.isdir( dirImage ):
        os.mkdir( dirImage )
      dirLayer = os.path.join( dirPlugin, 'db' )
      if not os.path.isdir( dirLayer ):
        os.mkdir( dirLayer )
      return { 'image': dirImage, 'gpkg': dirLayer }

    def getDefinitionLayerPolygon(dirLayer):
      def getFields():
        atts = [
          { 'name': 'id_add', 'type': QVariant.Int },
          { 'name': 'total_imgs', 'type':QVariant.Int },
          { 'name': 'images', 'type': QVariant.String, 'len': 254 },
          { 'name': 'user', 'type': QVariant.String, 'len': 20 },
          { 'name': 'date_add', 'type': QVariant.String, 'len': 20 },
          { 'name': 'crs_map', 'type': QVariant.String, 'len': 50 },
          { 'name': 'extent_map', 'type': QVariant.String, 'len': 200 },
          { 'name': 'annotation', 'type': QVariant.String, 'len': 100 }
        ]
        fields = QgsFields()
        for att in atts:
          f = QgsField( att['name'], att['type'] )
          if 'len' in att:
            f.setLength( att['len'])
          fields.append( f )
        return fields

      return {
        'fileName': os.path.join( dirLayer, 'gimp_selection.gpkg' ),
        'fields': getFields(),
        'geometryType': QgsWkbTypes.PolygonGeometry,
        'crs': QgsCoordinateReferenceSystem('EPSG:4326')
      }

    super().__init__()
    self.dockWidgetGui = dockWidgetGui
    self.layerPolygon, self.isIniEditable =  None, None
    self.worker = WorkerTaskGimpSelectionFeature()
    self.layerImages = []
    self.socket, self.hasConnect = None, None
    self.canvas, self.msgBar = iface.mapCanvas(), iface.messageBar()
    self.project = QgsProject.instance()
    self.mapCanvasEffects = MapCanvasEffects()
    self.taskManager = QgsApplication.taskManager()
    self.root = self.project.layerTreeRoot()
    dirs = createDirectories()
    self.pathfileImage = os.path.join( dirs['image'], 'tmp_gimp-plugin.tif' )
    self.pathfileImageSelect = os.path.join( dirs['image'], 'tmp_gimp-plugin_sel.tif' )
    self.defLayerPolygon = getDefinitionLayerPolygon( dirs['gpkg'] )
    self.featureAdd = None
    
    self._connect()
    self.setEnabledWidgetTransfer( False )
Ejemplo n.º 15
0
    def testSuccessWithLayer(self):
        """test successfully writing to a layer-enabled format"""
        self.layer = self.createLayer()
        options = QgsVectorFileWriter.SaveVectorOptions()
        options.driverName = "KML"
        options.layerName = "test-dashes"
        tmp = create_temp_filename('successlayer.kml')
        task = QgsVectorFileWriterTask(self.layer, tmp, options)

        task.completed.connect(self.onComplete)
        task.errorOccurred.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertEqual(self.new_layer, "test_dashes")
        self.assertTrue(self.success)
        self.assertFalse(self.fail)
Ejemplo n.º 16
0
    def testLayerRemovalBeforeRun(self):
        """test behavior when layer is removed before task begins"""
        self.layer = self.createLayer()
        options = QgsVectorFileWriter.SaveVectorOptions()
        tmp = create_temp_filename('fail.shp')
        task = QgsVectorFileWriterTask(self.layer, tmp, options)

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        # remove layer
        self.layer = None

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)
Ejemplo n.º 17
0
    def testFieldValueConverter(self):
        """test no crash when fieldValueConverter is used"""
        self.layer = self.createLayer()
        options = QgsVectorFileWriter.SaveVectorOptions()
        converter = QgsVectorFileWriter.FieldValueConverter()
        options.fieldValueConverter = converter
        tmp = create_temp_filename('converter.shp')
        task = QgsVectorFileWriterTask(self.layer, tmp, options)

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        del converter

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)
Ejemplo n.º 18
0
    def testTaskFromFunction(self):
        """ test creating task from function """

        task = QgsTask.fromFunction('test task', run, 20)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass

        self.assertEqual(task.returned_values, 20)
        self.assertFalse(task.exception)
        self.assertEqual(task.status(), QgsTask.Complete)

        # try a task which cancels itself
        bad_task = QgsTask.fromFunction('test task2', run, None)
        QgsApplication.taskManager().addTask(bad_task)
        while bad_task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass

        self.assertFalse(bad_task.returned_values)
        self.assertTrue(bad_task.exception)
        self.assertEqual(bad_task.status(), QgsTask.Terminated)
Ejemplo n.º 19
0
    def executeSql(self):

        sql = self._getSqlQuery()
        if sql == "":
            return

        # delete the old model
        old_model = self.viewResult.model()
        self.viewResult.setModel(None)
        if old_model:
            old_model.deleteLater()

        try:
            self.modelAsync = self.db.sqlResultModelAsync(sql, self)
            self.modelAsync.done.connect(self.executeSqlCompleted)
            self.updateUiWhileSqlExecution(True)
            QgsApplication.taskManager().addTask(self.modelAsync.task)
        except Exception as e:
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return
Ejemplo n.º 20
0
    def test(self):
        l1 = QgsVectorLayer(os.path.join(self.testDataDir, "france_parts.shp"), "françéà", "ogr", QgsVectorLayer.LayerOptions(False))
        self.assertEqual(l1.isValid(), True)
        QgsProject.instance().addMapLayer(l1)

        df = QgsVirtualLayerDefinition()
        df.setQuery('select * from "françéà"')
        self.task = QgsVirtualLayerTask(df)

        ids = [f.id() for f in self.task.layer().getFeatures()]
        self.assertEqual(len(ids), 0)

        self.task.taskCompleted.connect(self.onSuccess)
        self.task.taskTerminated.connect(self.onFail)

        QgsApplication.taskManager().addTask(self.task)
        while not self._success and not self._fail:
            QCoreApplication.processEvents()

        self.assertTrue(self._success)
        self.assertFalse(self._fail)

        self.assertEqual(len(self.ids), 4)

        # Test exception
        self._success = False
        self._fail = False
        df.setQuery('select *')
        self.task = QgsVirtualLayerTask(df)
        self.task.taskCompleted.connect(self.onSuccess)
        self.task.taskTerminated.connect(self.onFail)
        QgsApplication.taskManager().addTask(self.task)
        while not self._success and not self._fail:
            QCoreApplication.processEvents()

        self.assertFalse(self._success)
        self.assertTrue(self._fail)
        self.assertEqual(self._exceptionText, 'Query preparation error on PRAGMA table_info(_tview): no tables specified', self._exceptionText)
Ejemplo n.º 21
0
    def test(self):
        l1 = QgsVectorLayer(os.path.join(self.testDataDir, "france_parts.shp"), "françéà", "ogr", QgsVectorLayer.LayerOptions(False))
        self.assertEqual(l1.isValid(), True)
        QgsProject.instance().addMapLayer(l1)

        df = QgsVirtualLayerDefinition()
        df.setQuery('select * from "françéà"')
        self.task = QgsVirtualLayerTask(df)

        ids = [f.id() for f in self.task.layer().getFeatures()]
        self.assertEqual(len(ids), 0)

        self.task.taskCompleted.connect(self.onSuccess)
        self.task.taskTerminated.connect(self.onFail)

        QgsApplication.taskManager().addTask(self.task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)

        self.assertEqual(len(self.ids), 4)
Ejemplo n.º 22
0
    def go2epa_accept(self):
        """ Save INP, RPT and result name into GSW file """

        # Save user values
        self.save_user_values()

        self.dlg_go2epa.txt_infolog.clear()
        self.dlg_go2epa.txt_file_rpt.setStyleSheet(None)
        status = self.check_fields()
        if status is False:
            return

        # Get widgets values
        self.result_name = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_result_name, False, False)
        self.net_geom = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_only_check)
        self.export_inp = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_export)
        self.export_subcatch = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_export_subcatch)
        self.file_inp = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_file_inp)
        self.exec_epa = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_exec)
        self.file_rpt = utils_giswater.getWidgetText(self.dlg_go2epa, self.dlg_go2epa.txt_file_rpt)
        self.import_result = utils_giswater.isChecked(self.dlg_go2epa, self.dlg_go2epa.chk_import_result)

        # Check for sector selector
        if self.export_inp:
            sql = "SELECT sector_id FROM selector_sector LIMIT 1"
            row = self.controller.get_row(sql)
            if row is None:
                msg = "You need to select some sector"
                self.controller.show_info_box(msg)
                return

        # Set background task 'Go2Epa'
        description = f"Go2Epa"
        self.task_go2epa = TaskGo2Epa(description, self.controller, self)
        QgsApplication.taskManager().addTask(self.task_go2epa)
        QgsApplication.taskManager().triggerTask(self.task_go2epa)
    def run_task(self, args):
        """Sets up a QgsTask to do the heavy lifting in a background process of QGIS.
        
        Sets up the ProevenVerzamelingTask, which inherits from QgsTask, to handle the
        processor heavy queries and calculations in a background process, QGIS will stay
        stay responsive in the meantime. The ProevenVerzamelingTask is added to the QGIS
        taskmanager to handle it.

        Parameters
        ----------
        args : arguments dict
            Dictionary of arguments that will be passed to a QgsTask class.
        """
        progressDialog = QProgressDialog('Initializing Task: BIS Bevraging...',
                                         'Cancel', 0, 100)
        progressDialog.show()
        task = ProevenVerzamelingTask('Proeven Verzameling Bevraging', self,
                                      **args)
        task.progressChanged.connect(
            lambda: progressDialog.setValue(task.progress()))
        progressDialog.canceled.connect(task.cancel)
        task.begun.connect(lambda: progressDialog.setLabelText(
            'Task Running: BIS Bevraging...'))
        QgsApplication.taskManager().addTask(task)
Ejemplo n.º 24
0
    def testTaskFromFunctionFinishedWithMultipleValues(self):
        """ test that task from function can have callback finished function and is passed multiple result values"""
        result_value = None
        result_statement = None

        def finished_multiple_value_result(e, results):
            nonlocal result_value
            nonlocal result_statement
            assert e is None
            result_value = results[0]
            result_statement = results[1]

        task = QgsTask.fromFunction('test task', run_multiple_val_result, on_finished=finished_multiple_value_result)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertEqual(task.returned_values, (5, 'whoo'))
        self.assertFalse(task.exception)
        self.assertEqual(result_value, 5)
        self.assertEqual(result_statement, 'whoo')
Ejemplo n.º 25
0
    def test(self):
        l1 = QgsVectorLayer(os.path.join(self.testDataDir, "france_parts.shp"), "françéà", "ogr", QgsVectorLayer.LayerOptions(False))
        self.assertEqual(l1.isValid(), True)
        QgsProject.instance().addMapLayer(l1)

        df = QgsVirtualLayerDefinition()
        df.setQuery('select * from "françéà"')
        task = QgsVirtualLayerTask(df)

        ids = [f.id() for f in task.layer().getFeatures()]
        self.assertEqual(len(ids), 0)

        task.taskCompleted.connect(self.onSuccess)
        task.taskTerminated.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)

        ids = [f.id() for f in task.layer().getFeatures()]
        self.assertEqual(len(ids), 4)
Ejemplo n.º 26
0
    def testSuccess(self):
        """test successfully writing a layer"""
        path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif')
        raster_layer = QgsRasterLayer(path, "test")
        self.assertTrue(raster_layer.isValid())

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(raster_layer.dataProvider().clone()))

        tmp = create_temp_filename('success.tif')
        writer = QgsRasterFileWriter(tmp)

        task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs())

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)
        self.assertTrue(os.path.exists(tmp))
Ejemplo n.º 27
0
    def testTaskFromFunctionCanceledWhileQueued(self):
        """ test that task from finished is called with exception when task is terminated while queued"""
        finished_exception = None

        def finished_fail(e):
            nonlocal finished_exception
            assert e
            finished_exception = e

        task = QgsTask.fromFunction('test task',
                                    run_no_result,
                                    on_finished=finished_fail)
        task.hold()
        QgsApplication.taskManager().addTask(task)
        task.cancel()
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertTrue(task.exception)
        self.assertTrue(finished_exception)
        self.assertEqual(task.exception, finished_exception)
    def run_base_query_handler(self):
        QgsMessageLog.logMessage('Running base query', 'BigQuery Layers',
                                 Qgis.Info)
        project_name = self.project_edit.text()
        query = self.query_edit.toPlainText()
        self.client = bigquery.Client(project_name)

        self.base_query_job = Queue()
        self.base_query_job.put(self.client.query(query))

        for elm in self.base_query_elements + self.layer_import_elements:
            elm.setEnabled(False)
        self.run_query_button.setText('Running...')
        self.run_query_button.repaint()

        self.base_query_task = BaseQueryTask(
            'Background Query', self.iface, self.base_query_job,
            self.query_progress_field, self.geometry_column_combo_box,
            self.base_query_elements, self.layer_import_elements,
            self.run_query_button)
        QgsApplication.taskManager().addTask(self.base_query_task)

        QgsMessageLog.logMessage('After task manager', 'BigQuery Layers',
                                 Qgis.Info)
Ejemplo n.º 29
0
    def testSuccess(self):
        """test successfully writing a layer"""
        path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif')
        raster_layer = QgsRasterLayer(path, "test")
        self.assertTrue(raster_layer.isValid())

        pipe = QgsRasterPipe()
        self.assertTrue(pipe.set(raster_layer.dataProvider().clone()))

        tmp = create_temp_filename('success.tif')
        writer = QgsRasterFileWriter(tmp)

        task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs())

        task.writeComplete.connect(self.onSuccess)
        task.errorOccurred.connect(self.onFail)

        QgsApplication.taskManager().addTask(task)
        while not self.success and not self.fail:
            QCoreApplication.processEvents()

        self.assertTrue(self.success)
        self.assertFalse(self.fail)
        self.assertTrue(os.path.exists(tmp))
Ejemplo n.º 30
0
    def SaveACSV(self):
        """ Save Table as CSV  """
        data = self.player.GetPacketData()
        out, _ = askForFiles(
            self,
            QCoreApplication.translate("QgsFmvMetadata", "Save CSV"),
            isSave=True,
            exts="csv",
        )
        if not out:
            return

        task = QgsTask.fromFunction(
            "Save CSV Report Task",
            self.CreateCSV,
            out=out,
            data=data,
            VManager=self.VManager,
            on_finished=self.finishedTask,
            flags=QgsTask.CanCancel,
        )

        QgsApplication.taskManager().addTask(task)
        return
Ejemplo n.º 31
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)
Ejemplo n.º 32
0
def georeferencingVideo(parent):
    """Extract Current Frame Thread
    :param packet: Parent class
    """
    image = parent.videoWidget.currentFrame()

    folder = getVideoFolder(parent.fileName)
    qgsu.createFolderByName(folder, "mosaic")
    out = os.path.join(folder, "mosaic")

    position = str(parent.player.position())

    taskGeoreferencingVideo = QgsTask.fromFunction(
        "Georeferencing Current Frame Task",
        GeoreferenceFrame,
        image=image,
        output=out,
        p=position,
        on_finished=parent.finishedTask,
        flags=QgsTask.CanCancel,
    )

    QgsApplication.taskManager().addTask(taskGeoreferencingVideo)
    return
Ejemplo n.º 33
0
    def testTaskFromFunctionFinishedWithMultipleValues(self):
        """ test that task from function can have callback finished function and is passed multiple result values"""
        result_value = None
        result_statement = None

        def finished_multiple_value_result(e, results):
            nonlocal result_value
            nonlocal result_statement
            assert e is None
            result_value = results[0]
            result_statement = results[1]

        task = QgsTask.fromFunction('test task', run_multiple_val_result, on_finished=finished_multiple_value_result)
        QgsApplication.taskManager().addTask(task)
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()

        # check that the finished function was called
        self.assertEqual(task.returned_values, (5, 'whoo'))
        self.assertFalse(task.exception)
        self.assertEqual(result_value, 5)
        self.assertEqual(result_statement, 'whoo')
Ejemplo n.º 34
0
    def SaveAsPDF(self):
        """ Save Table as pdf """
        timestamp = str(self.player.player.position()) + " seconds"
        frame = self.player.videoWidget.GetCurrentFrame()
        data = self.player.GetPacketData()
        rows = self.VManager.rowCount()
        columns = self.VManager.columnCount()
        fileName = self.player.fileName

        out, _ = askForFiles(self, QCoreApplication.translate(
            "QgsFmvMetadata", "Save PDF"),
            isSave=True,
            exts='pdf')
        if out == "":
            return

        def finished(e):
            QApplication.restoreOverrideCursor()
            if e is None:
                qgsu.showUserAndLogMessage(QCoreApplication.translate(
                    "QgsFmvMetadata", "Succesfully creating PDF"))
            else:
                qgsu.showUserAndLogMessage(QCoreApplication.translate(
                    "QgsFmvMetadata", "Failed creating PDF : "), str(e), level=QGis.Warning)
            return

        task = QgsTask.fromFunction('Save PDF Report Task',
                                    QgsFmvMetadata.CreatePDF,
                                    out=out,
                                    timestamp=timestamp,
                                    data=data,
                                    frame=frame,
                                    rows=rows,
                                    columns=columns,
                                    fileName=fileName,
                                    VManager=self.VManager,
                                    on_finished=finished,
                                    flags=QgsTask.CanCancel)

        QCoreApplication.processEvents()
        tm.addTask(task)
        QCoreApplication.processEvents()
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            QCoreApplication.processEvents()
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()
        return
Ejemplo n.º 35
0
 def testMembers(self):
     self.assertTrue(QgsApplication.actionScopeRegistry())
     # self.assertTrue(QgsApplication.annotationRegistry()) NOT AVAILABLE IN BINDINGS
     self.assertTrue(QgsApplication.colorSchemeRegistry())
     self.assertTrue(QgsApplication.fieldFormatterRegistry())
     self.assertTrue(QgsApplication.gpsConnectionRegistry())
     self.assertTrue(QgsApplication.messageLog())
     self.assertTrue(QgsApplication.paintEffectRegistry())
     self.assertTrue(QgsApplication.pluginLayerRegistry())
     self.assertTrue(QgsApplication.processingRegistry())
     self.assertTrue(QgsApplication.profiler())
     # self.assertTrue(QgsApplication.rasterRendererRegistry()) NOT AVAILABLE IN BINDINGS
     self.assertTrue(QgsApplication.rendererRegistry())
     self.assertTrue(QgsApplication.svgCache())
     self.assertTrue(QgsApplication.symbolLayerRegistry())
     self.assertTrue(QgsApplication.taskManager())
Ejemplo n.º 36
0
 def __init__(self, layer):
     super().__init__()
     self._layer = layer
     self.totalAddTiles = 100
     self._frm_url, self.getUrl = None, None
     self._tilesCanvas = TilesMapCanvas()
     self.mapCanvas = QgsUtils.iface.mapCanvas()
     self.project = QgsProject.instance()
     self.taskManager = QgsApplication.taskManager()
     self._currentTask = None
     self.root = self.project.layerTreeRoot()
     self._nameGroupTiles = 'Tile images'
     self._ltgTiles = self.root.findGroup(self._nameGroupTiles)
     self._ltl = self.root.findLayer(layer)
     self._zoom = self._getZoom()
     self._connect()
Ejemplo n.º 37
0
 def testMembers(self):
     self.assertTrue(QgsApplication.actionScopeRegistry())
     # self.assertTrue(QgsApplication.annotationRegistry()) NOT AVAILABLE IN BINDINGS
     self.assertTrue(QgsApplication.colorSchemeRegistry())
     self.assertTrue(QgsApplication.fieldFormatterRegistry())
     self.assertTrue(QgsApplication.gpsConnectionRegistry())
     self.assertTrue(QgsApplication.messageLog())
     self.assertTrue(QgsApplication.paintEffectRegistry())
     self.assertTrue(QgsApplication.pluginLayerRegistry())
     self.assertTrue(QgsApplication.processingRegistry())
     self.assertTrue(QgsApplication.profiler())
     # self.assertTrue(QgsApplication.rasterRendererRegistry()) NOT AVAILABLE IN BINDINGS
     self.assertTrue(QgsApplication.rendererRegistry())
     self.assertTrue(QgsApplication.svgCache())
     self.assertTrue(QgsApplication.symbolLayerRegistry())
     self.assertTrue(QgsApplication.taskManager())
Ejemplo n.º 38
0
    def __init__(self, iface):
        QObject.__init__(self)

        self.iface = iface
        self.settings = Settings()
        self.settings_dialog = SettingsDialog()
        self.layers = Layers()
        self.chart_dock = ChartDock(self.iface, self.layers)
        self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.chart_dock)
        self.filter_start_date = None
        self.filter_end_date = None
        self.filter_installation = None
        self.filter_sensor = None
        self.filter_tjm = None
        self.filter_axe = None
        self.filter_sector = None
        self.tm = QgsApplication.taskManager()
Ejemplo n.º 39
0
    def initGui(self):
        self.actionRun = QAction(self.tr('QConsolidate'), self.iface.mainWindow())
        self.actionRun.setIcon(QIcon(os.path.join(pluginPath, 'icons', 'qconsolidate.svg')))
        self.actionRun.setObjectName('runQConsolidate')

        self.actionAbout = QAction(self.tr('About QConsolidate…'), self.iface.mainWindow())
        self.actionAbout.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.actionRun.setObjectName('aboutQConsolidate')

        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionRun)
        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionAbout)
        self.iface.addToolBarIcon(self.actionRun)

        self.actionRun.triggered.connect(self.run)
        self.actionAbout.triggered.connect(self.about)

        self.taskManager = QgsApplication.taskManager()
Ejemplo n.º 40
0
    def __init__(self, iface):
        def getConfig():
            def readUrlJson(locale):
                f_name = 'http://azure.solved.eco.br:90/mapbiomascollection_{locale}.json'
                isOk = True
                try:
                    name = f_name.format( locale=locale )
                    with urllib.request.urlopen(name) as url:
                        data = json.loads( url.read().decode() )
                except:
                    isOk = False
                
                r = { 'isOk': isOk }
                ( key, value ) = ( 'data', data )  if isOk else ( 'message', f"Missing file '{name}'" )
                r[ key ] = value
                return r

            overrideLocale = QSettings().value('locale/overrideFlag', False, type=bool)
            locale = QLocale.system().name() if not overrideLocale else QSettings().value('locale/userLocale', '')
            r = readUrlJson( locale )
            if r['isOk']:
                return r['data']

            if not r['isOk'] and locale == 'en_US':
                self.messageError = r['message']
                return None

            r = readUrlJson('en_US')
            if r['isOk']:
                return r['data']

            self.messageError = r['message']
            return None

        super().__init__()        
        self.msgBar = iface.messageBar()
        self.root = QgsProject.instance().layerTreeRoot()
        self.taskManager = QgsApplication.taskManager()
        self.messageError = ''
        self.data = getConfig() # If error, return None and set self.messageError
        self.widgetProvider = None
Ejemplo n.º 41
0
    def SaveACSV(self):
        """ Save Table as CSV  """
        data = self.player.GetPacketData()
        out, _ = askForFiles(self,
                             QCoreApplication.translate(
                                 "QgsFmvMetadata", "Save CSV"),
                             isSave=True,
                             exts='csv')
        if out == "":
            return

        def finished(e):
            QApplication.restoreOverrideCursor()
            if e is None:
                qgsu.showUserAndLogMessage(
                    QCoreApplication.translate("QgsFmvMetadata",
                                               "Succesfully creating CSV"))
            else:
                qgsu.showUserAndLogMessage(QCoreApplication.translate(
                    "QgsFmvMetadata", "Failed creating CSV : "),
                                           str(e),
                                           level=QGis.Warning)
            return

        task = QgsTask.fromFunction('Save CSV Report Task',
                                    QgsFmvMetadata.CreateCSV,
                                    out=out,
                                    data=data,
                                    VManager=self.VManager,
                                    on_finished=finished,
                                    flags=QgsTask.CanCancel)

        QCoreApplication.processEvents()
        tm.addTask(task)
        QCoreApplication.processEvents()
        while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
            QCoreApplication.processEvents()
            pass
        while QgsApplication.taskManager().countActiveTasks() > 0:
            QCoreApplication.processEvents()
        return
Ejemplo n.º 42
0
    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: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        self.tm = QgsApplication.taskManager()
        self.qproject = QgsProject.instance()

        self.pluginIsActive = False

        self.dockwidget = None
        self.metawidget = None

        # Populated on load from a URL
        self.acknowledgements = None

        # 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',
                                   'QRAVE_{}.qm'.format(locale))
        self.settings = Settings(iface=self.iface)

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

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Riverscapes Plugin (QRAVE)')

        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QRAVE')
        self.toolbar.setObjectName(u'QRAVE')
Ejemplo n.º 43
0
    def initGui(self):
        self.actionRun = QAction(self.tr('QConsolidate'),
                                 self.iface.mainWindow())
        self.actionRun.setIcon(
            QIcon(os.path.join(pluginPath, 'icons', 'qconsolidate.svg')))
        self.actionRun.setObjectName('runQConsolidate')

        self.actionAbout = QAction(self.tr('About QConsolidate...'),
                                   self.iface.mainWindow())
        self.actionAbout.setIcon(
            QgsApplication.getThemeIcon('/mActionHelpContents.svg'))
        self.actionRun.setObjectName('aboutQConsolidate')

        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionRun)
        self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionAbout)
        self.iface.addToolBarIcon(self.actionRun)

        self.actionRun.triggered.connect(self.run)
        self.actionAbout.triggered.connect(self.about)

        self.taskManager = QgsApplication.taskManager()
Ejemplo n.º 44
0
def georeferencingVideo(parent):
    """ Extract Current Frame Thread """
    image = parent.videoWidget.GetCurrentFrame()
    root, _ = os.path.splitext(os.path.basename(parent.fileName))
    out = os.path.join(os.path.expanduser("~"), "QGIS_FMV", root)
    position = str(parent.player.position())

    if position == "0":
        return

    task = QgsTask.fromFunction('Georeferencing Current Frame Task',
                                GeoreferenceFrame,
                                image=image, output=out, p=position,
                                flags=QgsTask.CanCancel)

    tm.addTask(task)
    while task.status() not in [QgsTask.Complete, QgsTask.Terminated]:
        QCoreApplication.processEvents()
    while QgsApplication.taskManager().countActiveTasks() > 0:
        QCoreApplication.processEvents()
    return
Ejemplo n.º 45
0
    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: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # 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',
                                   'Qgis3Test_{}.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)

        # Create the dialog (after translation) and keep reference
        self.dlg = Qgis3TestDialog()
        self.dlg.PBRunWait.clicked.connect(self.run_waiting)
        self.dlg.PBStopWait.clicked.connect(self.stop_waiting)
        self.dlg.PBRunCounter.clicked.connect(self.run_counting)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Qgis3Test')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'Qgis3Test')
        self.toolbar.setObjectName(u'Qgis3Test')
        self.tsk_mngr = QgsApplication.taskManager()
Ejemplo n.º 46
0
    def runAlgorithm(self):
        self.feedback = self.createFeedback()
        self.context = dataobjects.createContext(self.feedback)

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParameterValues()

            if checkCRS and not self.algorithm().validateInputCrs(
                    parameters, self.context):
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Parameters do not all use the same CRS. This can '
                            'cause unexpected results.\nDo you want to '
                            'continue?'), QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.algorithm().checkParameterValues(
                parameters, self.context)
            if not ok:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return
            self.runButton().setEnabled(False)
            self.cancelButton().setEnabled(False)
            buttons = self.mainWidget().iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.clearProgress()
            self.setProgressText(
                QCoreApplication.translate('AlgorithmDialog',
                                           'Processing algorithm…'))

            self.setInfo(QCoreApplication.translate(
                'AlgorithmDialog',
                '<b>Algorithm \'{0}\' starting&hellip;</b>').format(
                    self.algorithm().displayName()),
                         escapeHtml=False)

            self.feedback.pushInfo(self.tr('Input parameters:'))
            display_params = []
            for k, v in parameters.items():
                display_params.append("'" + k + "' : " + self.algorithm(
                ).parameterDefinition(k).valueAsPythonString(v, self.context))
            self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) +
                                          ' }')
            self.feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                # Make sure the Log tab is visible before executing the algorithm
                try:
                    self.showLog()
                    self.repaint()
                except:
                    pass

                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.algorithm(), parameters,
                                    self.iterateParam, self.context,
                                    self.feedback):
                    self.feedback.pushInfo(
                        self.tr('Execution completed in {0:0.2f} seconds').
                        format(time.time() - start_time))
                    self.cancelButton().setEnabled(False)
                    self.finish(True, parameters, self.context, self.feedback)
                else:
                    self.cancelButton().setEnabled(False)
                    self.resetGui()
            else:
                command = self.algorithm().asPythonCommand(
                    parameters, self.context)
                if command:
                    ProcessingLog.addToLog(command)
                QgsGui.instance().processingRecentAlgorithmLog().push(
                    self.algorithm().id())
                self.cancelButton().setEnabled(
                    self.algorithm().flags()
                    & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        self.feedback.pushInfo(
                            self.tr('Execution completed in {0:0.2f} seconds').
                            format(time.time() - start_time))
                        self.feedback.pushInfo(self.tr('Results:'))
                        self.feedback.pushCommandInfo(pformat(results))
                    else:
                        self.feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds').
                            format(time.time() - start_time))
                    self.feedback.pushInfo('')

                    if self.feedback_dialog is not None:
                        self.feedback_dialog.close()
                        self.feedback_dialog.deleteLater()
                        self.feedback_dialog = None

                    self.cancelButton().setEnabled(False)

                    if not self.in_place:
                        self.finish(ok, results, self.context, self.feedback)
                    elif ok:
                        self.close()

                    self.feedback = None
                    self.context = None

                if not self.in_place and not (
                        self.algorithm().flags()
                        & QgsProcessingAlgorithm.FlagNoThreading):
                    # Make sure the Log tab is visible before executing the algorithm
                    self.showLog()

                    task = QgsProcessingAlgRunnerTask(self.algorithm(),
                                                      parameters, self.context,
                                                      self.feedback)
                    if task.isCanceled():
                        on_complete(False, {})
                    else:
                        task.executed.connect(on_complete)
                        self.setCurrentTask(task)
                else:
                    self.proxy_progress = QgsProxyProgressTask(
                        QCoreApplication.translate(
                            "AlgorithmDialog", "Executing “{}”").format(
                                self.algorithm().displayName()))
                    QgsApplication.taskManager().addTask(self.proxy_progress)
                    self.feedback.progressChanged.connect(
                        self.proxy_progress.setProxyProgress)
                    self.feedback_dialog = self.createProgressDialog()
                    self.feedback_dialog.show()
                    if self.in_place:
                        ok, results = execute_in_place(self.algorithm(),
                                                       parameters,
                                                       self.context,
                                                       self.feedback)
                    else:
                        ok, results = execute(self.algorithm(), parameters,
                                              self.context, self.feedback)
                    self.feedback.progressChanged.disconnect()
                    self.proxy_progress.finalize(ok)
                    on_complete(ok, results)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox().accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=Qgis.Warning,
                duration=5)
        except AlgorithmDialogBase.InvalidOutputExtension as e:
            try:
                self.buttonBox().accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage("",
                                          e.message,
                                          level=Qgis.Warning,
                                          duration=5)
Ejemplo n.º 47
0
    def run(self):
        """Run method that performs all the real work"""

        # Control variables for possible rerun of algorithm
        reRun = True
        reRunProj = None

        while reRun:
    
            
            
            # Create seperate threa for calculations so that QGIS stays
            # responsive
            workerThread = ProcessingTask()
            
            # Initialize dialog window
            self.dlg = SeilaplanPluginDialog(self.iface, workerThread)
            # Get available raster from table of content in QGIS
            self.dlg.updateRasterList()
            # Load initial values of dialog
            self.dlg.loadInitialVals()

            # If this is a rerun of the algorithm the previous user values are
            #   loaded into the GUI
            if reRunProj:
                self.dlg.loadProj(reRunProj)

            self.dlg.show()
            # Start event loop
            self.dlg.exec_()

            reRun = False
            reRunProj = None

            
            # The algorithm is executed in a separate thread. To see progress,
            # a new gui shows a progress bar.
            
            # If all needed data has been input in the gui and the user has
            # clicked 'ok'
            if workerThread.state is True:
                # Initialize gui to show progress
                self.progressDialog = ProgressDialog(self.iface)
                self.progressDialog.setThread(workerThread)

                # Add task to taskmanager of QGIS and start the calculations
                QgsApplication.taskManager().addTask(workerThread)

                # Show progress bar
                self.progressDialog.run()

                # After calculations have finished and progress gui has been
                # closed: Check if user wants a rerun
                if self.progressDialog.reRun:
                    reRun = True
                    reRunProj = workerThread.projInfo['projFile']

                del self.progressDialog
            
            del workerThread
            del self.dlg

        return
Ejemplo n.º 48
0
    def runAlgorithm(self):
        self.feedback = self.createFeedback()
        self.context = dataobjects.createContext(self.feedback)

        checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParameterValues()

            if checkCRS and not self.algorithm().validateInputCrs(parameters, self.context):
                reply = QMessageBox.question(self, self.tr("Unmatching CRS's"),
                                             self.tr('Parameters do not all use the same CRS. This can '
                                                     'cause unexpected results.\nDo you want to '
                                                     'continue?'),
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.algorithm().checkParameterValues(parameters, self.context)
            if not ok:
                QMessageBox.warning(
                    self, self.tr('Unable to execute algorithm'), msg)
                return
            self.runButton().setEnabled(False)
            self.cancelButton().setEnabled(False)
            buttons = self.mainWidget().iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.clearProgress()
            self.setProgressText(QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…'))

            self.setInfo(
                QCoreApplication.translate('AlgorithmDialog', '<b>Algorithm \'{0}\' starting&hellip;</b>').format(self.algorithm().displayName()), escapeHtml=False)

            self.feedback.pushInfo(self.tr('Input parameters:'))
            display_params = []
            for k, v in parameters.items():
                display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition(k).valueAsPythonString(v, self.context))
            self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }')
            self.feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                # Make sure the Log tab is visible before executing the algorithm
                try:
                    self.showLog()
                    self.repaint()
                except:
                    pass

                self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback):
                    self.feedback.pushInfo(
                        self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
                    self.cancelButton().setEnabled(False)
                    self.finish(True, parameters, self.context, self.feedback)
                else:
                    self.cancelButton().setEnabled(False)
                    self.resetGui()
            else:
                command = self.algorithm().asPythonCommand(parameters, self.context)
                if command:
                    ProcessingLog.addToLog(command)
                QgsGui.instance().processingRecentAlgorithmLog().push(self.algorithm().id())
                self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        self.feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time))
                        self.feedback.pushInfo(self.tr('Results:'))
                        self.feedback.pushCommandInfo(pformat(results))
                    else:
                        self.feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds').format(time.time() - start_time))
                    self.feedback.pushInfo('')

                    if self.feedback_dialog is not None:
                        self.feedback_dialog.close()
                        self.feedback_dialog.deleteLater()
                        self.feedback_dialog = None

                    self.cancelButton().setEnabled(False)

                    if not self.in_place:
                        self.finish(ok, results, self.context, self.feedback)
                    elif ok:
                        self.close()

                    self.feedback = None
                    self.context = None

                if not self.in_place and not (self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading):
                    # Make sure the Log tab is visible before executing the algorithm
                    self.showLog()

                    task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback)
                    if task.isCanceled():
                        on_complete(False, {})
                    else:
                        task.executed.connect(on_complete)
                        self.setCurrentTask(task)
                else:
                    self.proxy_progress = QgsProxyProgressTask(QCoreApplication.translate("AlgorithmDialog", "Executing “{}”").format(self.algorithm().displayName()))
                    QgsApplication.taskManager().addTask(self.proxy_progress)
                    self.feedback.progressChanged.connect(self.proxy_progress.setProxyProgress)
                    self.feedback_dialog = self.createProgressDialog()
                    self.feedback_dialog.show()
                    if self.in_place:
                        ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback)
                    else:
                        ok, results = execute(self.algorithm(), parameters, self.context, self.feedback)
                    self.feedback.progressChanged.disconnect()
                    self.proxy_progress.finalize(ok)
                    on_complete(ok, results)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox().accepted.connect(lambda e=e:
                                                  e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
                                          level=Qgis.Warning, duration=5)
        except AlgorithmDialogBase.InvalidOutputExtension as e:
            try:
                self.buttonBox().accepted.connect(lambda e=e:
                                                  e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.messageBar().clearWidgets()
            self.messageBar().pushMessage("", e.message,
                                          level=Qgis.Warning, duration=5)
Ejemplo n.º 49
0
    def accept(self):
        super(AlgorithmDialog, self)._saveGeometry()

        feedback = self.createFeedback()
        context = dataobjects.createContext(feedback)

        checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParamValues()

            if checkCRS and not self.alg.validateInputCrs(parameters, context):
                reply = QMessageBox.question(self, self.tr("Unmatching CRS's"),
                                             self.tr('Layers do not all use the same CRS. This can '
                                                     'cause unexpected results.\nDo you want to '
                                                     'continue?'),
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            checkExtentCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            # TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(self, self.tr("Extent CRS"),
                                             self.tr('Extent parameters must use the same CRS as the input layers.\n'
                                                     'Your input layers do not have the same extent as the project, '
                                                     'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                                                     'Do you want to continue?'),
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.alg.checkParameterValues(parameters, context)
            if msg:
                QMessageBox.warning(
                    self, self.tr('Unable to execute algorithm'), msg)
                return
            self.btnRun.setEnabled(False)
            self.btnClose.setEnabled(False)
            buttons = self.mainWidget.iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.progressBar.setMaximum(0)
            self.lblProgress.setText(self.tr('Processing algorithm...'))
            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.tabWidget.setCurrentIndex(1)
                self.repaint()
            except:
                pass

            self.setInfo(
                self.tr('<b>Algorithm \'{0}\' starting...</b>').format(self.alg.displayName()), escape_html=False)

            feedback.pushInfo(self.tr('Input parameters:'))
            feedback.pushCommandInfo(pformat(parameters))
            feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                self.buttonCancel.setEnabled(self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.alg, parameters, self.iterateParam, context, feedback):
                    feedback.pushInfo(
                        self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
                    self.buttonCancel.setEnabled(False)
                    self.finish(True, parameters, context, feedback)
                else:
                    self.buttonCancel.setEnabled(False)
                    self.resetGUI()
            else:
                command = self.alg.asPythonCommand(parameters, context)
                if command:
                    ProcessingLog.addToLog(command)
                self.buttonCancel.setEnabled(self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds'.format(time.time() - start_time)))
                        feedback.pushInfo(self.tr('Results:'))
                        feedback.pushCommandInfo(pformat(results))
                    else:
                        feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds'.format(time.time() - start_time)))
                    feedback.pushInfo('')

                    self.buttonCancel.setEnabled(False)
                    self.finish(ok, results, context, feedback)

                task = QgsProcessingAlgRunnerTask(self.alg, parameters, context, feedback)
                task.executed.connect(on_complete)
                QgsApplication.taskManager().addTask(task)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(lambda e=e:
                                                e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()),
                                 level=QgsMessageBar.WARNING, duration=5)
 def createTaskCalcIntersects(self):
     taskManager = QgsApplication.taskManager()
     self.task1 = QgsTask.fromFunction(self.MESSAGE_CATEGORY,
                                       self.calcIntersects,
                                       on_finished=self.completed)
     taskManager.addTask(self.task1)
Ejemplo n.º 51
0
    def startWorker(self):
        """Initialises and starts."""
        self.inputbuffers = {}
        self.referencebuffers = {}
        self.polycount = {}
        self.completeness = {}
        self.miscodings = {}
        self.statistics = {}
        self.testcounter = 0

        try:
            layerindex = self.inputLayer.currentIndex()
            layerId = self.inputLayer.itemData(layerindex)
            self.inputlayer = QgsProject.instance().mapLayer(layerId)
            if self.inputlayer is None:
                self.showError(self.tr('No input layer defined'))
                return
            refindex = self.referenceLayer.currentIndex()
            reflayerId = self.referenceLayer.itemData(refindex)
            self.reflayer = QgsProject.instance().mapLayer(reflayerId)
            if layerId == reflayerId:
                self.showInfo('The reference layer must be different'
                              ' from the input layer!')
                return
            if self.reflayer is None:
                self.showError(self.tr('No reference layer defined'))
                return
            if self.inputlayer.sourceCrs().authid() != self.reflayer.sourceCrs(
            ).authid():
                self.showWarning('Layers must have the same CRS - Input: ' +
                                 str(self.inputlayer.sourceCrs().authid()) +
                                 ' Reference: ' +
                                 str(self.reflayer.sourceCrs().authid()))
                return
            if self.reflayer.sourceCrs().isGeographic():
                self.showWarning('Geographic CRS used -' +
                                 ' computations will be in decimal degrees!')
            # Algorithms
            self.bufferalg = QgsApplication.processingRegistry().algorithmById(
                'native:buffer')
            #self.bufferalg=QgsApplication.processingRegistry().algorithmById('qgis:buffer')
            self.unionalg = QgsApplication.processingRegistry().algorithmById(
                'qgis:union')
            self.intersectionalg = QgsApplication.processingRegistry(
            ).algorithmById('qgis:intersection')
            self.differencealg = QgsApplication.processingRegistry(
            ).algorithmById('qgis:difference')
            self.multitosinglealg = QgsApplication.processingRegistry(
            ).algorithmById('qgis:multiparttosingleparts')
            self.statalg = QgsApplication.processingRegistry().algorithmById(
                'qgis:statisticsbycategories')

            # Calculate the total length of lines in the layers
            self.inpgeomlength = 0
            for f in self.inputlayer.getFeatures():
                self.inpgeomlength = self.inpgeomlength + f.geometry().length()
            self.refgeomlength = 0
            for f in self.reflayer.getFeatures():
                self.refgeomlength = self.refgeomlength + f.geometry().length()

            # Number of steps and radii
            steps = self.stepsSB.value()
            startradius = self.startRadiusSB.value()
            endradius = self.endRadiusSB.value()
            delta = (endradius - startradius) / (steps - 1)
            self.radiuses = []
            for step in range(steps):
                self.radiuses.append(startradius + step * delta)
            #self.radiuses = [10,20,50]
            #self.showInfo(str(self.radiuses))
            feedback = QgsProcessingFeedback()
            selectedinputonly = self.selectedFeaturesCheckBox.isChecked()
            selectedrefonly = self.selectedRefFeaturesCheckBox.isChecked()
            #plugincontext = dataobjects.createContext(feedback)
            #self.showInfo('Plugin context: ' + str(plugincontext))
            #self.showInfo('GUI thread: ' + str(QThread.currentThread()) + ' ID: ' + str(QThread.currentThreadId()))

            ###### Testing QgsTask!!!
            # I følge oppskrifta på opengis.ch
            context = QgsProcessingContext()
            #context = plugincontext
            #self.showInfo('Normal context: ' + str(context))
            #context.setProject(QgsProject.instance())
            for radius in self.radiuses:
                # Buffer input  # Works!
                inlayercopy = QgsVectorLayer(self.inputlayer.source(),
                                             'in' + str(radius),
                                             self.inputlayer.providerType())
                ##inlayercopy = self.copylayer(self.inputlayer, 'in' + str(radius))
                params = {
                    'INPUT': inlayercopy,
                    #'INPUT': self.inputlayer,
                    'DISTANCE': radius,
                    #'OUTPUT':'/home/havatv/test.shp'
                    'OUTPUT': 'memory:InputBuffer'
                }
                task = QgsProcessingAlgRunnerTask(self.bufferalg, params,
                                                  context)
                ##task = QgsProcessingAlgRunnerTask(self.bufferalg,params,context,feedback)
                # Add a few extra parameters (context, radius and "input") using "partial"
                task.executed.connect(
                    partial(self.buffer_executed, context, radius, self.INPUT))
                QgsApplication.taskManager().addTask(task)
                self.showInfo('Start Input buffer: ' + str(radius))
                # Buffer reference  # Works!
                reflayercopy = QgsVectorLayer(self.reflayer.source(),
                                              'ref' + str(radius),
                                              self.reflayer.providerType())
                #reflayercopy = self.copylayer(self.reflayer, 'ref' + str(radius))
                params = {
                    'INPUT': reflayercopy,
                    #'INPUT': self.reflayer,
                    'DISTANCE': radius,
                    #'OUTPUT':'/home/havatv/test.shp'
                    'OUTPUT': 'memory:ReferenceBuffer'
                }
                task = QgsProcessingAlgRunnerTask(self.bufferalg, params,
                                                  context)
                #task = QgsProcessingAlgRunnerTask(self.bufferalg,params,context,feedback)
                # Add a few extra parameters (context, radius and "reference") using "partial"
                task.executed.connect(
                    partial(self.buffer_executed, context, radius, self.REF))
                QgsApplication.taskManager().addTask(task)
                self.showInfo('Start Ref buffer: ' + str(radius))

            ##task.begun.connect(self.task_begun)
            ##task.taskCompleted.connect(self.task_completed)
            ##task.progressChanged.connect(self.task_progress)
            ##task.taskTerminated.connect(self.task_stopped)

            #iteration = 5   # Identifiserer hvilken iterasjon det er snakk om

            ## I følge oppskrifta på opengis.ch (partial legger inn context som første parameter):
            ## context ser ut til å være helt nødvendig!
            #task.executed.connect(partial(self.task_executed, context, iteration))
            #self.button_box.button(QDialogButtonBox.Ok).setEnabled(False)
            #self.button_box.button(QDialogButtonBox.Close).setEnabled(False)
            #self.button_box.button(QDialogButtonBox.Cancel).setEnabled(True)
        except:
            import traceback
            self.showError(traceback.format_exc())
        else:
            pass
Ejemplo n.º 52
0
    def buffer_executed(self, context, iteration, kind, ok, result):
        #self.showInfo("Buffer executed (" + str(kind) + '): ' +
        #              str(iteration) + ', OK: ' + str(ok) +
        #              ', Res: ' + str(result))
        self.tcmutex.acquire()
        try:
            self.testcounter = self.testcounter + 1
            self.showInfo("Buffer finished: " + str(iteration) + ' - ' +
                          str(kind) + ' ' + str(self.testcounter) + ' ' +
                          str(QgsApplication.taskManager().count()))
        finally:
            self.tcmutex.release()
        #return

        if not ok:
            self.showInfo("Buffer failed - " + str(iteration) + ' ' +
                          str(kind))
            return
        #blayer = result['OUTPUT'] ## blayer blir string!
        # Get the result (line) dataset from the buffer algorithm
        blayer = QgsProcessingUtils.mapLayerFromString(result['OUTPUT'],
                                                       context)
        # Add attribute
        provider = blayer.dataProvider()
        newfield = QgsField('InputB', QVariant.String, len=5)
        if kind == self.REF:
            newfield = QgsField('RefB', QVariant.String, len=5)
        provider.addAttributes([newfield])
        blayer.updateFields()
        # Update the attribute
        blayer.startEditing()
        field_index = blayer.fields().lookupField('InputB')
        if kind == self.REF:
            field_index = blayer.fields().lookupField('RefB')
        #self.showInfo('refb, field index: ' + str(field_index))
        for f in provider.getFeatures():
            #self.showInfo('Feature (refb): ' + str(f))
            if kind == self.REF:
                # Set the attribute value to 'R'
                blayer.changeAttributeValue(f.id(), field_index, 'R')
            else:
                # Set the attribute value to 'I'
                blayer.changeAttributeValue(f.id(), field_index, 'I')
        blayer.commitChanges()

        if kind == self.INPUT:
            self.ibmutex.acquire(
            )  # Important to acquire ibmutex first (deadlock)
            try:
                self.inputbuffers[iteration] = result['OUTPUT']
            finally:
                self.ibmutex.release()
        elif kind == self.REF:
            self.rbmutex.acquire()
            try:
                self.referencebuffers[iteration] = result['OUTPUT']
            finally:
                self.rbmutex.release()
        else:
            self.showInfo("Strange kind of buffer: " + str(kind))
        # Do line overlay:  # Works!
        if kind == self.INPUT:
            reflayercopy = QgsVectorLayer(self.reflayer.source(),
                                          'refint' + str(iteration),
                                          self.reflayer.providerType())
            #reflayercopy = self.copylayer(self.reflayer, 'refint' + str(iteration))
            params = {
                'INPUT': reflayercopy,
                #'INPUT': self.reflayer,
                #'OVERLAY': result['OUTPUT'],
                'OVERLAY': blayer,
                #'OVERLAY': QgsProcessingUtils.mapLayerFromString(result['OUTPUT'], context),
                'OUTPUT': 'memory:Intersection'
            }
            task = QgsProcessingAlgRunnerTask(self.intersectionalg, params,
                                              context)
            # Add a few extra parameters (context, radius) using "partial"
            task.executed.connect(
                partial(self.intersection_executed, context, iteration))
            QgsApplication.taskManager().addTask(task)
            #self.showInfo('Start Intersection: ' + str(iteration))
        elif kind == self.REF:
            # The reference buffer is used to remove parts of the input layer
            inlayercopy = QgsVectorLayer(self.inputlayer.source(),
                                         'indiff' + str(iteration),
                                         self.inputlayer.providerType())
            #inlayercopy = self.copylayer(self.inputlayer, 'indiff' + str(iteration))
            params = {
                'INPUT': inlayercopy,
                #'INPUT': self.inputlayer,
                'OVERLAY': blayer,
                'OUTPUT': 'memory:Difference'
            }
            task = QgsProcessingAlgRunnerTask(self.differencealg, params,
                                              context)
            # Add a few extra parameters (context, radius) using "partial"
            task.executed.connect(
                partial(self.difference_executed, context, iteration))
            QgsApplication.taskManager().addTask(task)
            #self.showInfo('Start Difference: ' + str(iteration))

        todelete = []  # buffer sizes to remove (after handling)
        # Do union, if possible
        # Check if both buffers are available:
        self.ibmutex.acquire()  # Important to acquire ibmutex first (deadlock)
        try:
            self.rbmutex.acquire()
            try:
                for key in self.inputbuffers:
                    if key in self.referencebuffers:
                        # Union input  # Does not work!
                        params = {
                            #'INPUT': self.inputbuffers[key],
                            'INPUT':
                            QgsProcessingUtils.mapLayerFromString(
                                self.inputbuffers[key], context),
                            #'OVERLAY': self.referencebuffers[key],
                            'OVERLAY':
                            QgsProcessingUtils.mapLayerFromString(
                                self.referencebuffers[key], context),
                            'OUTPUT':
                            'memory:Union'
                        }
                        task = QgsProcessingAlgRunnerTask(
                            self.unionalg, params, context)
                        # Add a few extra parameters (context, radius) using "partial"
                        task.executed.connect(
                            partial(self.union_executed, context, iteration))
                        QgsApplication.taskManager().addTask(task)
                        #self.showInfo('Start Union: ' + str(iteration))
                        todelete.append(key)
                        #del self.inputbuffers[key]
                        #del self.referencebuffers[key]
                for key in todelete:
                    del self.inputbuffers[key]
                    del self.referencebuffers[key]
                    #self.showInfo('Removed key: ' + str(key))
            finally:
                self.rbmutex.release()
        finally:
            self.ibmutex.release()
Ejemplo n.º 53
0
    def union_executed(self, context, iteration, ok, result):
        #self.showInfo("Union executed: " + str(iteration) + ', OK: ' + str(ok) + ', Res: ' + str(result))
        if not ok:
            self.showInfo("Union failed - " + str(iteration))
            return
        # Get the result (polygon) dataset from the union algorithm
        unionlayer = QgsProcessingUtils.mapLayerFromString(
            result['OUTPUT'], context)
        # Add attributes
        provider = unionlayer.dataProvider()
        provider.addAttributes([QgsField('Area', QVariant.Double)])
        provider.addAttributes([QgsField('Combined', QVariant.String, len=40)])
        unionlayer.updateFields()
        unionlayer.startEditing()
        area_field_index = unionlayer.fields().lookupField('Area')  # OK
        #self.showInfo('union, area field index: ' + str(area_field_index))
        combined_field_index = unionlayer.fields().lookupField(
            'Combined')  # OK
        #self.showInfo('union, combined field index: ' + str(combined_field_index))
        # Update the attributes
        for f in provider.getFeatures():
            #self.showInfo('Feature: ' + str(f))
            area = f.geometry().area()
            unionlayer.changeAttributeValue(f.id(), area_field_index, area)
            iidx = unionlayer.fields().lookupField('InputB')
            ridx = unionlayer.fields().lookupField('RefB')
            i = f.attributes()[iidx]
            r = f.attributes()[ridx]
            # Set the 'Combined' attribute value to show the combination
            comb = ''
            if i is not None:
                if r is not None:
                    comb = str(i) + str(r)
                else:
                    comb = str(i)
            else:
                if r is not None:
                    comb = str(r)
                else:
                    comb = None
            #self.showInfo('Combination: ' + str(comb))
            unionlayer.changeAttributeValue(f.id(), combined_field_index, comb)
        unionlayer.commitChanges()

        # Do multipart to singlepart: # OK
        params = {
            #'INPUT': QgsProcessingUtils.mapLayerFromString(result['OUTPUT'], context),
            'INPUT': unionlayer,
            #'INPUT': result['OUTPUT'],
            'OUTPUT': 'memory:Singlepart'
        }
        task = QgsProcessingAlgRunnerTask(self.multitosinglealg, params,
                                          context)
        # Add extra parameters (context, iteration) using "partial"
        task.executed.connect(
            partial(self.tosingle_executed, context, iteration))
        QgsApplication.taskManager().addTask(task)
        #self.showInfo('Start MultipartToSinglepart: ' + str(iteration))

        # Do the statistics
        params = {
            'INPUT': unionlayer,
            'VALUES_FIELD_NAME': 'Area',
            'CATEGORIES_FIELD_NAME': 'Combined',
            #'OUTPUT':'/home/havatv/stats.csv'
            'OUTPUT': 'memory:Statistics'
        }
        task = QgsProcessingAlgRunnerTask(self.statalg, params, context)
        # Add extra parameters (context, iteration) using "partial"
        task.executed.connect(partial(self.stats_executed, context, iteration))
        QgsApplication.taskManager().addTask(task)
Ejemplo n.º 54
0
    def __init__(self, iface, parent=None):
        """Constructor."""
        self.iface = iface
        super(BOSDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)

        # Some constants for translated text
        self.BOS = self.tr('BOS')
        self.BROWSE = self.tr('Browse')
        self.CANCEL = self.tr('Cancel')
        self.HELP = self.tr('Help')
        self.CLOSE = self.tr('Close')
        self.OK = self.tr('OK')
        #self.NUMBEROFSTEPS = 10  # Number of steps

        self.labelTextSize = 8
        self.titleTextSize = 10

        self.INPUT = 'input'
        self.REF = 'reference'

        okButton = self.button_box.button(QDialogButtonBox.Ok)
        okButton.setText(self.OK)
        cancelButton = self.button_box.button(QDialogButtonBox.Cancel)
        cancelButton.setText(self.CANCEL)
        helpButton = self.helpButton
        helpButton.setText(self.HELP)
        self.BOSscene = QGraphicsScene(self)
        self.BOSGraphicsView.setScene(self.BOSscene)

        # Connect signals
        okButton.clicked.connect(self.startWorker)
        #self.displacementButton.clicked.connect(self.showPlots)
        #self.avgdispButton.clicked.connect(self.showAverageDisplacement)
        #self.oscillationButton.clicked.connect(self.showOscillation)
        #self.complmiscButton.clicked.connect(self.showComplenessMiscoding)
        #self.saveSvgButton.clicked.connect(self.saveAsSVG)
        #self.saveAsPdfButton.clicked.connect(self.saveAsPDF)
        # Global variables with mutexes
        # Dictionary variable for input buffers
        self.inputbuffers = {}
        self.ibmutex = Lock()
        # Dictionary variable for reference buffers
        self.referencebuffers = {}
        self.rbmutex = Lock()
        # Variables for statistics
        # Number of polygons:
        self.polycount = {}
        self.pcmutex = Lock()
        # Complenetess values:
        self.completeness = {}
        self.comutex = Lock()
        # Miscoding values:
        self.miscodings = {}
        self.mimutex = Lock()
        # Other statistics
        self.statistics = {}
        self.stmutex = Lock()

        self.testcounter = 0
        self.tcmutex = Lock()

        self.radiuses = []

        # This one fires "immediately"?
        QgsApplication.taskManager().allTasksFinished.connect(
            self.all_tasks_completed)
 def enrichLayerProcess(self):
     layers = QgsProject.instance().layerTreeRoot().children()
     selectedLayerIndex = self.dlg.chooseLayerEnrich.currentIndex()
     self.enrichLayer = layers[selectedLayerIndex].layer().clone()
     attlist = {}
     itemlist = []
     propertylist = []
     excludelist = []
     resultmap = {}
     self.dlg.enrichTableResult.clear()
     self.dlg.enrichTableResult.setRowCount(0)
     self.dlg.enrichTableResult.setColumnCount(
         self.dlg.enrichTable.rowCount())
     fieldnames = []
     for row in range(self.dlg.enrichTable.rowCount()):
         fieldnames.append(self.dlg.enrichTable.item(row, 0).text())
     self.dlg.enrichTableResult.setHorizontalHeaderLabels(fieldnames)
     self.enrichLayer.startEditing()
     for row in range(self.dlg.enrichTable.rowCount()):
         idfield = self.dlg.enrichTable.cellWidget(row, 5).currentText()
         idprop = self.dlg.enrichTable.item(row, 6).text()
         if idprop == None or idprop == "":
             msgBox = QMessageBox()
             msgBox.setText(
                 "ID Property has not been specified for column " +
                 str(self.dlg.enrichTable.item(row, 0).text()))
             msgBox.exec()
             return
         item = self.dlg.enrichTable.item(row, 0).text()
         propertyy = self.dlg.enrichTable.item(row, 1)
         triplestoreurl = ""
         if self.dlg.enrichTable.item(row, 2) != None:
             triplestoreurl = self.dlg.enrichTable.item(row, 2).text()
             print(self.dlg.enrichTable.item(row, 2).text())
         strategy = self.dlg.enrichTable.cellWidget(row, 3).currentText()
         content = ""
         if self.dlg.enrichTable.cellWidget(row, 4) != None:
             content = self.dlg.enrichTable.cellWidget(row, 4).currentText()
         if item != idfield:
             propertylist.append(self.dlg.enrichTable.item(row, 1))
         if strategy == "Exclude":
             excludelist.append(row)
         if strategy != "No Enrichment" and propertyy != None:
             progress = QProgressDialog(
                 "Enriching column " +
                 self.dlg.enrichTable.item(row, 0).text(), "Abort", 0, 0,
                 self.dlg)
             progress.setWindowModality(Qt.WindowModal)
             progress.setCancelButton(None)
             self.qtask = EnrichmentQueryTask(
                 "Enriching column: " +
                 self.dlg.enrichTable.item(row, 0).text(), triplestoreurl,
                 self.enrichLayer, strategy,
                 self.dlg.enrichTable.item(row, 8).text(), row,
                 len(self.enrichLayer.fields()),
                 self.dlg.enrichTable.item(row,
                                           0).text(), self.dlg.enrichTable,
                 self.dlg.enrichTableResult, idfield, idprop,
                 self.dlg.enrichTable.item(row, 1), content, progress)
             QgsApplication.taskManager().addTask(self.qtask)
         else:
             rowww = 0
             for f in self.enrichLayer.getFeatures():
                 if rowww >= self.dlg.enrichTableResult.rowCount():
                     self.dlg.enrichTableResult.insertRow(rowww)
                 #if item in f:
                 newitem = QTableWidgetItem(str(f[item]))
                 self.dlg.enrichTableResult.setItem(rowww, row, newitem)
                 #if ";" in str(newitem):
                 #    newitem.setBackground(QColor.red)
                 print(str(newitem))
                 rowww += 1
         self.enrichLayer.commitChanges()
         row += 1
     iface.vectorLayerTools().stopEditing(self.enrichLayer)
     self.enrichLayer.dataProvider().deleteAttributes(excludelist)
     self.enrichLayer.updateFields()
     self.dlg.enrichTable.hide()
     self.dlg.enrichTableResult.show()
     self.dlg.startEnrichment.setText("Enrichment Configuration")
     self.dlg.startEnrichment.clicked.disconnect()
     self.dlg.startEnrichment.clicked.connect(self.dlg.showConfigTable)
     self.dlg.addEnrichedLayerRowButton.setEnabled(False)
     return self.enrichLayer
Ejemplo n.º 56
0
except ImportError:
    None

try:
    from cv2 import (COLOR_BGR2RGB, cvtColor, COLOR_GRAY2RGB)
    import numpy as np
except ImportError:
    None

try:
    from pydevd import *
except ImportError:
    None

settings = QSettings()
tm = QgsApplication.taskManager()

windows = platform.system() == 'Windows'

xSize = 0
ySize = 0

defaultTargetWidth = 200.0

iface, \
geotransform , \
geotransform_affine, \
gcornerPointUL, \
gcornerPointUR, \
gcornerPointLR, \
gcornerPointLL, \
Ejemplo n.º 57
0
    def accept(self):
        super(AlgorithmDialog, self)._saveGeometry()

        feedback = self.createFeedback()
        context = dataobjects.createContext(feedback)

        checkCRS = ProcessingConfig.getSetting(
            ProcessingConfig.WARN_UNMATCHING_CRS)
        try:
            parameters = self.getParamValues()

            if checkCRS and not self.alg.validateInputCrs(parameters, context):
                reply = QMessageBox.question(
                    self, self.tr("Unmatching CRS's"),
                    self.tr('Layers do not all use the same CRS. This can '
                            'cause unexpected results.\nDo you want to '
                            'continue?'), QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            checkExtentCRS = ProcessingConfig.getSetting(
                ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS)
            # TODO
            if False and checkExtentCRS and self.checkExtentCRS():
                reply = QMessageBox.question(
                    self, self.tr("Extent CRS"),
                    self.
                    tr('Extent parameters must use the same CRS as the input layers.\n'
                       'Your input layers do not have the same extent as the project, '
                       'so the extent might be in a wrong CRS if you have selected it from the canvas.\n'
                       'Do you want to continue?'),
                    QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
                if reply == QMessageBox.No:
                    return
            ok, msg = self.alg.checkParameterValues(parameters, context)
            if msg:
                QMessageBox.warning(self,
                                    self.tr('Unable to execute algorithm'),
                                    msg)
                return
            self.btnRun.setEnabled(False)
            self.btnClose.setEnabled(False)
            buttons = self.mainWidget.iterateButtons
            self.iterateParam = None

            for i in range(len(list(buttons.values()))):
                button = list(buttons.values())[i]
                if button.isChecked():
                    self.iterateParam = list(buttons.keys())[i]
                    break

            self.progressBar.setMaximum(0)
            self.lblProgress.setText(self.tr('Processing algorithm...'))
            # Make sure the Log tab is visible before executing the algorithm
            try:
                self.tabWidget.setCurrentIndex(1)
                self.repaint()
            except:
                pass

            self.setInfo(
                self.tr('<b>Algorithm \'{0}\' starting...</b>').format(
                    self.alg.displayName()),
                escape_html=False)

            feedback.pushInfo(self.tr('Input parameters:'))
            feedback.pushCommandInfo(pformat(parameters))
            feedback.pushInfo('')
            start_time = time.time()

            if self.iterateParam:
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)
                if executeIterating(self.alg, parameters, self.iterateParam,
                                    context, feedback):
                    feedback.pushInfo(
                        self.tr(
                            'Execution completed in {0:0.2f} seconds'.format(
                                time.time() - start_time)))
                    self.buttonCancel.setEnabled(False)
                    self.finish(True, parameters, context, feedback)
                else:
                    self.buttonCancel.setEnabled(False)
                    self.resetGUI()
            else:
                command = self.alg.asPythonCommand(parameters, context)
                if command:
                    ProcessingLog.addToLog(command)
                self.buttonCancel.setEnabled(
                    self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel)

                def on_complete(ok, results):
                    if ok:
                        feedback.pushInfo(
                            self.tr('Execution completed in {0:0.2f} seconds'.
                                    format(time.time() - start_time)))
                        feedback.pushInfo(self.tr('Results:'))
                        feedback.pushCommandInfo(pformat(results))
                    else:
                        feedback.reportError(
                            self.tr('Execution failed after {0:0.2f} seconds'.
                                    format(time.time() - start_time)))
                    feedback.pushInfo('')

                    self.buttonCancel.setEnabled(False)
                    self.finish(ok, results, context, feedback)

                task = QgsProcessingAlgRunnerTask(self.alg, parameters,
                                                  context, feedback)
                task.executed.connect(on_complete)
                QgsApplication.taskManager().addTask(task)

        except AlgorithmDialogBase.InvalidParameterValue as e:
            try:
                self.buttonBox.accepted.connect(
                    lambda e=e: e.widget.setPalette(QPalette()))
                palette = e.widget.palette()
                palette.setColor(QPalette.Base, QColor(255, 255, 0))
                e.widget.setPalette(palette)
            except:
                pass
            self.bar.clearWidgets()
            self.bar.pushMessage(
                "",
                self.tr("Wrong or missing parameter value: {0}").format(
                    e.parameter.description()),
                level=QgsMessageBar.WARNING,
                duration=5)
Ejemplo n.º 58
-1
    def openAllResults(self):
        resultPath = os.path.join(
            os.path.join(self.ProjectDirectory, "Results"),
            self.NetworkName + "_" + self.Scenario)
        if not os.path.exists(resultPath):
            self.iface.messageBar().pushMessage(
                "Warning",
                "No scenario results are available",
                level=1,
                duration=5)
            return

        if not self.setVariables():
            return

        # Process
        self.setLayersNames(True)
        # Task is necessary because after remove layers, DBF files are in use. With the task,
        # the remove process finishs and filer are not in use
        task1 = QgsTask.fromFunction("",
                                     self.removeResults,
                                     on_finished=self.openAllResultsProcess)
        task1.run()
        QgsApplication.taskManager().addTask(task1)