Пример #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)
Пример #2
0
    def testTaskFromFunctionWithFlags(self):
        """ test creating task from function with flags"""

        task = QgsTask.fromFunction('test task', run, 20, flags=QgsTask.Flags())
        self.assertFalse(task.canCancel())
        task2 = QgsTask.fromFunction('test task', run, 20, flags=QgsTask.CanCancel)
        self.assertTrue(task2.canCancel())
Пример #3
0
    def __init__(self, settings):
        QgsTask.__init__(self, 'QConsolidate')

        self.settings = settings

        self.project = None
        self.projectFile = None

        self.baseDirectory = self.settings['output']
        self.dataDirectory = os.path.join(self.baseDirectory, LAYERS_DIRECTORY)

        self.error = ''
Пример #4
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)
Пример #5
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)
Пример #6
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)
Пример #7
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)
Пример #8
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)
Пример #9
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)
Пример #10
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)
Пример #11
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 runTask(self, dataRun):
    def finished(exception, dataResult):
      def endEditable():
        self.layerPolygon.commitChanges()
        self.layerPolygon.updateExtents()
        if self.isIniEditable:
          self.layerPolygon.startEditing()

      def setRenderLayer():
        fileStyle = os.path.join( os.path.dirname( __file__ ), "gimpselectionfeature_with_expression.qml" )
        self.layerPolygon.loadNamedStyle( fileStyle )
        self.mapCanvasEffects.zoom( self.layerPolygon, dataResult['geomBBox'] )
      
      self.msgBar.clearWidgets()
      if exception:
        self.msgBar.pushMessage( self.nameModulus, str( exception ), Qgis.Critical )
        return
      self.msgBar.pushMessage( self.nameModulus, dataResult['message'], dataResult['level'] )
      if 'getFeatures' == dataResult['process']:
        endEditable()
        imgs =  filter( lambda f: os.path.exists( f ), ( self.pathfileImage, self.pathfileImageSelect ) )
        [ os.remove( item ) for item in imgs ]
        if dataResult['isOk']:
          setRenderLayer()
          self.setEnabledWidgetTransfer( True, True )
        else:
          self.setEnabledWidgetTransfer( True )
      else:
        self.setEnabledWidgetTransfer( True )

    def run(task, data):
      self.worker.setData( task, data )
      return self.worker.run()

    self.setEnabledWidgetTransfer( False )
    task = QgsTask.fromFunction('GimpSelectionFeature Task', run, dataRun, on_finished=finished )
    if not self.layerPolygon is None:
      task.setDependentLayers( [ self.layerPolygon ] )
    self.taskManager.addTask( task )
Пример #13
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')
Пример #14
0
 def report_per_field(self):
     """Creates a QgsTask in order to collect data then on finish it runs
     simple_field."""
     if self.path is None:
         QMessageBox.information(
             None, self.tr('Error'),
             self.tr('A directory to save the report must be selected.'))
         return
     year = self.dw.DEReportYear.text()
     if self.dw.RBReportWithoutDetails.isChecked():
         self.report_name = '{p}\\{t}_{y}.pdf'.format(
             p=self.path, t=self.tr('GeoDataFarm_Limited_report'), y=year)
         if self.dw.RBAllYear.isChecked():
             year = None
         else:
             year = self.dw.DEReportYear.text()
         task = QgsTask.fromFunction('Run import text data',
                                     self.collect_data,
                                     year,
                                     on_finished=self.simple_field)
         self.tsk_mngr.addTask(task)
     else:
         report_name = '{p}\\{t}_{y}.pdf'.format(
             p=self.path, t=self.tr('GeoDataFarm_Limited_report'), y=year)
Пример #15
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')
Пример #16
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
Пример #17
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)
Пример #18
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)
Пример #19
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
 def __init__(self, desc, observer):
     QgsTask.__init__(self, desc, QgsTask.CanCancel)
     self.observer = observer
     self._continue = True
     self._interval = 2.5
Пример #21
0
 def call_import_temps_task(self):
     self.taskWeather = QgsTask.fromFunction(u'QWeather',
                                             self.import_temps_task,
                                             on_finished=self.completed,
                                             wait_time=4)
     QgsApplication.taskManager().addTask(self.taskWeather)
Пример #22
0
    def update_pic(self):
        """Collects the data that the user gave as input and starts the QgsTask
        that runs the SQL query. On finish plot_data is called"""
        if self.canvas is not None:
            self.dlg.mplvl.removeWidget(self.canvas)
        if self.dlg.CBLimitArea.isChecked() and self.search_area == '':
            try:
                self.iface.actionSaveActiveLayerEdits().trigger()
                self.iface.actionToggleEditing().trigger()
                feature = self.add_field.field.getFeature(1)
                QgsProject.instance().removeMapLayer(self.add_field.field.id())
                self.add_field.field = None
            except:
                QMessageBox.information(
                    None, self.tr("Error:"),
                    self.
                    tr('No coordinates where found, did you mark the field on the canvas?'
                       ))
                return
            limiting_polygon = feature.geometry().asWkt()
            self.search_area = limiting_polygon
        elif self.dlg.CBLimitArea.isChecked(
        ) and self.add_field.field is not None:
            self.iface.actionSaveActiveLayerEdits().trigger()
            self.iface.actionToggleEditing().trigger()
            feature = self.add_field.field.getFeature(1)
            QgsProject.instance().removeMapLayer(self.add_field.field.id())
            self.add_field.field = None
            limiting_polygon = feature.geometry().asWkt()
            self.search_area = limiting_polygon
        elif self.dlg.CBLimitArea.isChecked():
            limiting_polygon = self.search_area
        else:
            limiting_polygon = None
            self.search_area = ''
        other_parameters = {}
        investigating_param = {}
        investigating_param['values'] = []
        prefixes = {}
        prefix_count = 0
        for nbr, col in enumerate(self.layout_dict.keys()):
            self.update_top_panel(nbr, col)
            for tbl_nr in range(len(self.layout_dict[col]['tbl'])):
                table = self.layout_dict[col]['tbl'][tbl_nr]
                schema = self.layout_dict[col]['schema'][tbl_nr]
                data_type = self.layout_dict[col]['type']
                ha = self.layout_dict[col]['harvest'][tbl_nr]['tbl_name']
                s_t = '{schema}.{table}'.format(schema=schema, table=table)
                if s_t not in prefixes.keys():
                    prefix_count += 1
                    prefixes[s_t] = 'a{prefix_count}'.format(
                        prefix_count=prefix_count)
                if self.cb[nbr].isChecked():
                    column_investigated = col
                    if ha not in investigating_param.keys():
                        investigating_param[ha] = {}
                        investigating_param[ha]['ha_col'] = \
                        self.layout_dict[col]['harvest'][tbl_nr]['index_col']
                    if s_t not in investigating_param[ha].keys():
                        investigating_param[ha][s_t] = {}
                    investigating_param[ha][s_t] = {}
                    investigating_param[ha][s_t]['prefix'] = prefixes[s_t]
                    investigating_param[ha][s_t]['col'] = col
                    i_col = col
                    analyse_params = self.get_initial_distinct_values(
                        col, table, schema)
                    investigating_param['values'].extend(
                        analyse_params['distinct_values'])
                    # Can happens multiple times, hence shouldn't be a problem.
                    if data_type == 'checked':
                        investigating_param['checked'] = True
                    else:
                        investigating_param['checked'] = False
                else:
                    if ha not in other_parameters.keys():
                        other_parameters[ha] = {}
                    if s_t not in other_parameters[ha].keys():
                        other_parameters[ha][s_t] = {}

                    other_parameters[ha][s_t]['prefix'] = prefixes[s_t]
                    other_parameters[ha][s_t][col] = {}
                    if self.layout_dict[col]['type'] == 'max_min':
                        other_parameters[ha][s_t][col]['type'] = 'max_min'
                        other_parameters[ha][s_t][col][
                            'min'] = self.layout_dict[col]['min']
                        other_parameters[ha][s_t][col][
                            'max'] = self.layout_dict[col]['max']
                    else:
                        other_parameters[ha][s_t][col]['type'] = 'checked'
                        other_parameters[ha][s_t][col]['check_text'] = "'"
        if not investigating_param['checked']:
            minvalue = float(self.layout_dict[i_col]['min'])
            maxvalue = float(self.layout_dict[i_col]['max'])
            values = copy.deepcopy(investigating_param['values'])
            for value in investigating_param['values']:
                if value is None:
                    values.remove(value)
                elif round(value, 3) < minvalue:
                    values.remove(value)
                elif round(value, 3) > maxvalue:
                    values.remove(value)
            investigating_param['values'] = values
        if not investigating_param['checked'] and len(
                investigating_param['values']) > 20:
            investigating_param['hist'] = True
            investigating_param['values'].sort()
            temp = []
            for val in range(
                    0, len(investigating_param['values']),
                    int(round(len(investigating_param['values']) / 20))):
                temp.append(investigating_param['values'][val])
            temp.append(investigating_param['values'][-1])
            investigating_param['values'] = temp
        elif not investigating_param['checked']:
            investigating_param['hist'] = False
            investigating_param['values'].sort()
        else:
            investigating_param['hist'] = False
            investigating_param['values'] = "'"
        other_parameters, investigating_param = self.update_checked_field(
            other_parameters, investigating_param)
        min_counts = self.dlg.minNumber.text()
        self.column_investigated = column_investigated
        self.investigating_param = investigating_param
        task1 = QgsTask.fromFunction('running script',
                                     sql_query,
                                     investigating_param,
                                     other_parameters,
                                     self.db,
                                     min_counts,
                                     limiting_polygon,
                                     on_finished=self.plot_data)
        self.tsk_mngr.addTask(task1)
Пример #23
0
 def run_waiting(self):
     waiting_msg = WaitingMsg()
     task = QgsTask.fromFunction('waiting', waiting_msg.run)
     self.tsk_mngr.addTask(task)
 def createTaskCalcIntersects(self):
     taskManager = QgsApplication.taskManager()
     self.task1 = QgsTask.fromFunction(self.MESSAGE_CATEGORY,
                                       self.calcIntersects,
                                       on_finished=self.completed)
     taskManager.addTask(self.task1)
Пример #25
0
    def call_import_photos(self):
        self.taskPhotos = QgsTask.fromFunction(u'ImportPhotos', self.import_photos_task,
                                 on_finished=self.completed, wait_time=4)

        QgsApplication.taskManager().addTask(self.taskPhotos)
Пример #26
0
    def updateFeatures(self):
        def addExpField(expField):
            field = QgsField(expField, QVariant.String)
            sq, iniBraces, endBraces = "'{}"
            value = self._frm_url
            for c in 'xyzq':
                src = f"{iniBraces}{c}{endBraces}"
                dest = f"{sq} || {c} || {sq}"
                value = value.replace(src, dest)
            end_sq = f" || {sq}"
            if value.endswith(end_sq):
                total = -1 * (len(end_sq))
                value = f"{sq}" + value[:total]
            else:
                value = f"{sq}{value}{sq}"
            self._layer.addExpressionField(value, field)

        def run(task, prov):
            totalTiles = self.getTotalTiles()
            c_tiles = 0
            for tile in self._tilesCanvas(self._zoom):
                if task.isCanceled():
                    return {'canceled': True, 'total': c_tiles}
                feat = QgsFeature()
                geom = QgsGeometry.fromRect(tile.rect)
                feat.setGeometry(geom)
                feat.setAttributes([tile.x, tile.y, tile.z, tile.q])
                prov.addFeature(feat)
                progress = c_tiles / totalTiles * 100
                task.setProgress(progress)
                c_tiles += 1
            return {'canceled': False, 'total': c_tiles}

        def finished(exception, result=None):
            self.selectedFeatures.emit(0)
            self._layer.updateExtents()
            self._layer.triggerRepaint()
            self._currentTask = None
            r = {'name': 'update'}
            if exception:
                r['error'] = f"Exception, {exception}"
            r.update(result)
            self.finishProcess.emit(r)

        if self._currentTask:
            self._currentTask.cancel()
            return
        prov = self._layer.dataProvider()
        prov.truncate()  # Delete all
        expField = 'url'
        idExpField = self._layer.fields().indexOf(expField)
        if idExpField > -1:
            self._layer.removeExpressionField(idExpField)
        if self._frm_url:
            addExpField(expField)
        # Task
        self.finishedTask = False
        args = {
            'description': f"{self.__class__.__name__}.populate",
            'function': run,
            'prov': prov,
            'on_finished': finished
        }
        self._currentTask = QgsTask.fromFunction(**args)
        self._currentTask.setDependentLayers([self._layer])
        self.taskManager.addTask(self._currentTask)
Пример #27
0
    def CreateBitratePlot(self):
        ''' Create video Plot Bitrate Thread '''
        sender = self.sender().objectName()

        if sender == "actionAudio":
            taskactionAudio = QgsTask.fromFunction(
                'Show Audio Bitrate',
                self.BitratePlot.CreatePlot,
                fileName=self.fileName,
                output=None,
                t='audio',
                on_finished=self.finishedTask,
                flags=QgsTask.CanCancel)

            QgsApplication.taskManager().addTask(taskactionAudio)

        elif sender == "actionVideo":
            taskactionVideo = QgsTask.fromFunction(
                'Show Video Bitrate',
                self.BitratePlot.CreatePlot,
                fileName=self.fileName,
                output=None,
                t='video',
                on_finished=self.finishedTask,
                flags=QgsTask.CanCancel)

            QgsApplication.taskManager().addTask(taskactionVideo)

        elif sender == "actionSave_Audio":
            fileaudio, _ = askForFiles(self,
                                       QCoreApplication.translate(
                                           "QgsFmvPlayer",
                                           "Save Audio Bitrate Plot"),
                                       isSave=True,
                                       exts=[
                                           "png", "pdf", "pgf", "eps", "ps",
                                           "raw", "rgba", "svg", "svgz"
                                       ])

            if not fileaudio:
                return

            taskactionSave_Audio = QgsTask.fromFunction(
                'Save Action Audio Bitrate',
                self.BitratePlot.CreatePlot,
                fileName=self.fileName,
                output=fileaudio,
                t='audio',
                on_finished=self.finishedTask,
                flags=QgsTask.CanCancel)

            QgsApplication.taskManager().addTask(taskactionSave_Audio)

        elif sender == "actionSave_Video":
            filevideo, _ = askForFiles(self,
                                       QCoreApplication.translate(
                                           "QgsFmvPlayer",
                                           "Save Video Bitrate Plot"),
                                       isSave=True,
                                       exts=[
                                           "png", "pdf", "pgf", "eps", "ps",
                                           "raw", "rgba", "svg", "svgz"
                                       ])

            if not filevideo:
                return

            taskactionSave_Video = QgsTask.fromFunction(
                'Save Action Video Bitrate',
                self.BitratePlot.CreatePlot,
                fileName=self.fileName,
                output=filevideo,
                t='video',
                on_finished=self.finishedTask,
                flags=QgsTask.CanCancel)

            QgsApplication.taskManager().addTask(taskactionSave_Video)
Пример #28
0
    def convertVideo(self):
        '''Convert Video To Other Format '''
        out, _ = askForFiles(self,
                             QCoreApplication.translate(
                                 "QgsFmvPlayer", "Save Video as..."),
                             isSave=True,
                             exts=[
                                 "mp4", "ogg", "avi", "mkv", "webm", "flv",
                                 "mov", "mpg", "mp3"
                             ])

        if not out:
            return

        # TODO : Make Correct format Conversion and embebed metadata
        info = self.converter.probeInfo(self.fileName)
        if info is not None:
            if self.HasFileAudio:
                audio_codec = info.audio.codec
                audio_samplerate = info.audio.audio_samplerate
                audio_channels = info.audio.audio_channels

            video_codec = info.video.codec
            video_width = info.video.video_width
            video_height = info.video.video_height
            video_fps = info.video.video_fps

        _, out_ext = os.path.splitext(out)

        if self.HasFileAudio:
            options = {
                'format': out_ext[1:],
                'audio': {
                    'codec': audio_codec,
                    'samplerate': audio_samplerate,
                    'channels': audio_channels
                },
                'video': {
                    'codec': video_codec,
                    'width': video_width,
                    'height': video_height,
                    'fps': video_fps
                }
            }
        else:
            options = {
                'format': out_ext[1:],
                'video': {
                    'codec': video_codec,
                    'width': video_width,
                    'height': video_height,
                    'fps': video_fps
                }
            }

        taskConvertVideo = QgsTask.fromFunction('Converting Video Task',
                                                self.converter.convert,
                                                infile=self.fileName,
                                                outfile=out,
                                                options=options,
                                                twopass=False,
                                                on_finished=self.finishedTask,
                                                flags=QgsTask.CanCancel)

        QgsApplication.taskManager().addTask(taskConvertVideo)
Пример #29
0
 def cancel(self):
     self.con.cancel(
     )  #psycopg2 conection can be cancelled from any thread.
     QgsTask.cancel(self)
Пример #30
0
 def __init__(self, desc, sourcePath, destGroup):
     QgsTask.__init__(self, desc)
     self.sourcePath = sourcePath
     self.destGroup = destGroup
Пример #31
0
 def trigger_insection(self):
     """Preparing the data, by setting the correct type (including the date and
     time format), creating a shp file and finally ensure that the
     coordinates is in EPSG:4326
     """
     params = {}
     params['schema'] = self.data_type
     params['column_types'] = self.col_types
     params['heading_row'] = []
     for col in self.heading_row:
         params['heading_row'].append(check_text(col))
     params['encoding'] = self.encoding
     params['file_name_with_path'] = self.file_name_with_path
     params['field'] = self.ITD.CBField.currentText()
     params['longitude_col'] = self.longitude_col
     params['latitude_col'] = self.latitude_col
     params['focus_col'] = []
     if self.ITD.RBDateOnly.isChecked():
         is_ok, first_date = check_date_format(
             self.sample_data, check_text(self.ITD.ComBDate.currentText()),
             self.ITD.ComBDate_2.currentText())
         if not is_ok:
             QMessageBox.information(
                 None, self.tr('Error'),
                 self.
                 tr("The date format didn't match the selected format, please change"
                    ))
             return
         params['date_row'] = check_text(self.ITD.ComBDate.currentText())
         params['date_format'] = self.ITD.ComBDate_2.currentText()
         params['all_same_date'] = ''
         manual_date = 'date_'
         table_date = first_date
     else:
         params['all_same_date'] = self.ITD.DE.text()
         manual_date = 'c_' + self.ITD.DE.text()
         table_date = self.ITD.DE.text()
         params['date_row'] = ''
     self.tbl_name = check_text(self.ITD.CBField.currentText() + '_' +
                                self.data_type + '_' + table_date)
     params['tbl_name'] = self.tbl_name
     if self.db.check_table_exists(self.tbl_name, self.data_type):
         return
     for i in range(self.add_to_param_row_count):
         params['focus_col'].append(
             check_text(self.ITD.TWtoParam.item(i, 0).text()))
     self.focus_cols = params['focus_col']
     if params['schema'] == 'harvest':
         params['yield_row'] = params['focus_col'][0]
         params['max_yield'] = float(self.ITD.LEMaximumYield.text())
         params['min_yield'] = float(self.ITD.LEMinimumYield.text())
     self.mff.insert_manual_data(manual_date,
                                 self.ITD.CBField.currentText(),
                                 self.tbl_name, self.data_type)
     params['sep'] = self.sep
     params['tr'] = self.tr
     params['epsg'] = self.ITD.LEEPSG.text()
     if float(self.ITD.LEMoveX.text()) != 0.0 or float(
             self.ITD.LEMoveY.text()) != 0.0:
         params['move'] = True
         params['move_x'] = float(self.ITD.LEMoveX.text())
         params['move_y'] = float(self.ITD.LEMoveY.text())
     else:
         params['move'] = False
     #a = insert_data_to_database('debug', self.db, params)
     #print(a)
     task = QgsTask.fromFunction('Run import text data',
                                 insert_data_to_database,
                                 self.db,
                                 params,
                                 on_finished=self.finish)
     self.tsk_mngr.addTask(task)
Пример #32
0
 def __init__(self, desc):
     QgsTask.__init__(self, desc)
Пример #33
0
    def test_flags(self):
        """
        Test task flags
        """
        thread_safe_alg = QgsApplication.processingRegistry().algorithmById(
            'native:buffer')
        nonthread_safe_alg = QgsApplication.processingRegistry().algorithmById(
            'native:setprojectvariable')
        context = QgsProcessingContext()
        context.setProject(QgsProject.instance())
        feedback = ConsoleFeedBack()

        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback)
        self.assertEqual(task.flags(), QgsTask.CanCancel)
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Flags())
        self.assertEqual(task.flags(), QgsTask.Flags())
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.CanCancel)
        self.assertEqual(task.flags(), QgsTask.CanCancel)
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.CancelWithoutPrompt)
        self.assertEqual(task.flags(), QgsTask.CancelWithoutPrompt)
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.CancelWithoutPrompt
                                          | QgsTask.CanCancel)
        self.assertEqual(task.flags(),
                         QgsTask.CancelWithoutPrompt | QgsTask.CanCancel)

        # alg which can't be canceled
        task = QgsProcessingAlgRunnerTask(nonthread_safe_alg, {},
                                          context=context,
                                          feedback=feedback)
        self.assertEqual(task.flags(), QgsTask.Flags())
        # we clear the CanCancel flag automatically, since the algorithm itself cannot be canceled
        task = QgsProcessingAlgRunnerTask(nonthread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.CanCancel)
        self.assertEqual(task.flags(), QgsTask.Flags())

        # hidden task
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Hidden)
        self.assertEqual(task.flags(), QgsTask.Hidden)
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Hidden
                                          | QgsTask.CanCancel)
        self.assertEqual(task.flags(), QgsTask.Hidden | QgsTask.CanCancel)
        task = QgsProcessingAlgRunnerTask(thread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Hidden
                                          | QgsTask.CanCancel
                                          | QgsTask.CancelWithoutPrompt)
        self.assertEqual(
            task.flags(),
            QgsTask.Hidden | QgsTask.CanCancel | QgsTask.CancelWithoutPrompt)

        task = QgsProcessingAlgRunnerTask(nonthread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Hidden)
        self.assertEqual(task.flags(), QgsTask.Hidden)
        task = QgsProcessingAlgRunnerTask(nonthread_safe_alg, {},
                                          context=context,
                                          feedback=feedback,
                                          flags=QgsTask.Hidden
                                          | QgsTask.CanCancel)
        self.assertEqual(task.flags(), QgsTask.Hidden)
 def prepareXsdForMetadata(self):
     task = QgsTask.fromFunction('Wczytywanie schematu XSD dla metadanych', self.createMetadataValidator)
     if task.description() not in [task.description() for task in QgsApplication.taskManager().activeTasks()]:
         QgsApplication.taskManager().addTask(task)
         QgsMessageLog.logMessage('starting XSD reading task')