# This file is part of Gajim. # # Gajim 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. # # Gajim 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 Gajim. If not, see . from gi.repository import Gio, GObject ''' https://discourse.gnome.org/t/gtk-threading-problem-with-glib-idle-add/13597/5 https://github.com/gdm-settings/gdm-settings/blob/f245d3000200fa6be2a35c7f6ac45b131dadb5d6/src/utils.py#L116..L162 ''' class BackgroundTask(GObject.Object): __gtype_name__ = 'BackgroundTask' def __init__(self, function, finish_callback, **kwargs): super().__init__(**kwargs) self.function = function self.finish_callback = finish_callback self._current = None def start(self): if self._current: AlreadyRunningError('Task is already running') finish_callback = lambda self, task, nothing: self.finish_callback() task = Gio.Task.new(self, None, finish_callback, None) task.run_in_thread(self._thread_cb) self._current = task @staticmethod def _thread_cb(task, self, task_data, cancellable): try: retval = self.function() task.return_value(retval) except Exception as e: task.return_value(e) def finish(self): task = self._current self._current = None if not Gio.Task.is_valid(task, self): raise InvalidGioTaskError() value = task.propagate_value().value if isinstance(value, Exception): raise value return value