2022-08-16 11:12:28 +00:00
|
|
|
# run_async.py
|
|
|
|
#
|
|
|
|
# Change the look of Adwaita, with ease
|
|
|
|
# Copyright (C) 2022 Gradience Team
|
|
|
|
#
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
|
2022-08-14 18:14:38 +00:00
|
|
|
import sys
|
|
|
|
import threading
|
|
|
|
import traceback
|
|
|
|
|
|
|
|
from gi.repository import GLib
|
|
|
|
|
2022-10-10 19:45:47 +00:00
|
|
|
from gradience.utils.utils import buglog
|
2022-08-23 17:38:09 +00:00
|
|
|
|
2022-08-17 21:35:59 +00:00
|
|
|
|
2022-08-14 18:14:38 +00:00
|
|
|
class RunAsync(threading.Thread):
|
|
|
|
def __init__(self, task_func, callback=None, *args, **kwargs):
|
|
|
|
self.source_id = None
|
2022-09-07 16:01:32 +00:00
|
|
|
if threading.current_thread() is not threading.main_thread():
|
|
|
|
raise AssertionError
|
2022-08-14 18:14:38 +00:00
|
|
|
|
|
|
|
super(RunAsync, self).__init__(
|
|
|
|
target=self.target, args=args, kwargs=kwargs)
|
|
|
|
|
|
|
|
self.task_func = task_func
|
|
|
|
|
|
|
|
self.callback = callback if callback else lambda r, e: None
|
|
|
|
self.daemon = kwargs.pop("daemon", True)
|
|
|
|
|
|
|
|
self.start()
|
|
|
|
|
|
|
|
def target(self, *args, **kwargs):
|
|
|
|
result = None
|
|
|
|
error = None
|
|
|
|
|
2022-08-23 17:38:09 +00:00
|
|
|
buglog(f"Running async job [{self.task_func}].")
|
2022-08-14 18:14:38 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
result = self.task_func(*args, **kwargs)
|
|
|
|
except Exception as exception:
|
2022-09-07 15:51:36 +00:00
|
|
|
buglog(
|
|
|
|
"Error while running async job: "
|
|
|
|
f"{self.task_func}\nException: {exception}"
|
|
|
|
)
|
2022-08-14 18:14:38 +00:00
|
|
|
|
|
|
|
error = exception
|
|
|
|
_ex_type, _ex_value, trace = sys.exc_info()
|
|
|
|
traceback.print_tb(trace)
|
2022-09-07 15:51:36 +00:00
|
|
|
traceback_info = "\n".join(traceback.format_tb(trace))
|
2022-08-14 18:14:38 +00:00
|
|
|
|
2022-08-23 17:38:09 +00:00
|
|
|
buglog([str(exception), traceback_info])
|
2022-08-14 18:14:38 +00:00
|
|
|
self.source_id = GLib.idle_add(self.callback, result, error)
|
|
|
|
return self.source_id
|