1# -*- coding: utf-8 -*-

2

3"""

4***************************************************************************

5 qgstaskwrapper.py

6 ---------------------

7 Date : May 2018

8 Copyright : (C) 2018 by Denis Rouzaud

9 Email : denis@opengis.ch

10***************************************************************************

11* *

12* This program is free software; you can redistribute it and/or modify *

13* it under the terms of the GNU General Public License as published by *

14* the Free Software Foundation; either version 2 of the License, or *

15* (at your option) any later version. *

16* *

17***************************************************************************

18"""

19

20

21 from qgis._core import QgsTask

22

23

24 class QgsTaskWrapper(QgsTask):

25

26 def __init__(self, description, flags, function, on_finished, *args, **kwargs):

27 QgsTask.__init__(self, description, flags)

28 self.args = args

29 self.kwargs = kwargs

30 self.function = function

31 self.on_finished = on_finished

32 self.returned_values = None

33 self.exception = None

34

35 def run(self):

36 try:

37 self.returned_values = self.function(self, *self.args, **self.kwargs)

38 except Exception as ex:

39 # report error

40 self.exception = ex

41 return False

42

43 return True

44

45 def finished(self, result):

46 if not self.on_finished:

47 return

48

49 if not result and self.exception is None:

50 self.exception = Exception('Task canceled')

51

52 try:

53 if self.returned_values:

54 self.on_finished(self.exception, self.returned_values)

55 else:

56 self.on_finished(self.exception)

57 except Exception as ex:

58 self.exception = ex