Python gi.repository.GLib.idle_add() Examples

The following are 30 code examples of gi.repository.GLib.idle_add(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module gi.repository.GLib , or try the search function .
Example #1
Source File: fsync.py    From daily-wallpaper with MIT License 8 votes vote down vote up
def _async_call(f, args, kwargs, on_done):
    def run(data):
        f, args, kwargs, on_done = data
        error = None
        result = None
        try:
            result = f(*args, **kwargs)
        except Exception as e:
            e.traceback = traceback.format_exc()
            error = 'Unhandled exception in asyn call:\n{}'.format(e.traceback)
        GLib.idle_add(lambda: on_done(result, error))

    data = f, args, kwargs, on_done
    thread = threading.Thread(target=run, args=(data,))
    thread.daemon = True
    thread.start() 
Example #2
Source File: dbus_ctrl.py    From simLAB with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        logging.info('D-Bus process started')
        GLib.threads_init()  # allow threads in GLib
        GLib.idle_add(self._idleQueueSync)

        DBusGMainLoop(set_as_default=True)
        dbusService = SessionDBus(self.taskQueue, self.resultQueue)

        try:
            GLib.MainLoop().run()
        except KeyboardInterrupt:
            logging.debug("\nThe MainLoop will close...")
            GLib.MainLoop().quit()
        return 
Example #3
Source File: script.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def execute(self, inputs, outputs, gvm):
    self.logger.debug("Delete state")
    state_id = inputs["generated_state_id"]
    # the target state is the hierarchy state, which holds this library state as child state
    target_state = self.parent.parent
    
    call_gui_callback(target_state.remove_state, state_id)
    # do not call this with idle_add, otherwise the oberserver will be triggered asynchronously
    # i.e. the before notification will be handled after the whole operation already happend
    #GLib.idle_add(target_state.remove_state, state_id)
    
    while state_id in target_state.states.keys():
        time.sleep(0.1)
    
    wait_for_gui()
    
    #call_gui_callback(wait_for_gui)
    
    #time.sleep(2.0)
    return 0 
Example #4
Source File: logging_console.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def print_message(self, message, log_level):
        with self._lock:
            if log_level <= log.logging.VERBOSE and self._enables.get('VERBOSE', False):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "debug",
                              priority=GLib.PRIORITY_LOW)
            if log.logging.VERBOSE < log_level <= log.logging.DEBUG and self._enables.get('DEBUG', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "debug",
                              priority=self.logging_priority)
            elif log.logging.DEBUG < log_level <= log.logging.INFO and self._enables.get('INFO', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "info",
                              priority=self.logging_priority)
            elif log.logging.INFO < log_level <= log.logging.WARNING and self._enables.get('WARNING', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "warning",
                              priority=self.logging_priority)
            elif log.logging.WARNING < log_level and self._enables.get('ERROR', True):
                GLib.idle_add(self.print_to_text_view, message, self.filtered_buffer, "error",
                              priority=self.logging_priority) 
Example #5
Source File: panctl.py    From pantalaimon with Apache License 2.0 6 votes vote down vote up
def main():
    loop = asyncio.get_event_loop()
    glib_loop = GLib.MainLoop()

    try:
        panctl = PanCtl()
    except GLib.Error as e:
        print(f"Error, {e}")
        sys.exit(-1)

    fut = loop.run_in_executor(None, glib_loop.run)

    try:
        loop.run_until_complete(panctl.loop())
    except KeyboardInterrupt:
        pass

    GLib.idle_add(glib_loop.quit)
    loop.run_until_complete(fut) 
Example #6
Source File: start.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def register_signal_handlers(callback):
    # When using plain signal.signal to install a signal handler, the GUI will not shutdown until it receives the
    # focus again. The following logic (inspired from https://stackoverflow.com/a/26457317) fixes this
    def install_glib_handler(sig):
        unix_signal_add = None

        if hasattr(GLib, "unix_signal_add"):
            unix_signal_add = GLib.unix_signal_add
        elif hasattr(GLib, "unix_signal_add_full"):
            unix_signal_add = GLib.unix_signal_add_full

        if unix_signal_add:
            unix_signal_add(GLib.PRIORITY_HIGH, sig, callback, sig)

    def idle_handler(*args):
        GLib.idle_add(callback, *args, priority=GLib.PRIORITY_HIGH)

    for signal_code in [signal.SIGHUP, signal.SIGINT, signal.SIGTERM]:
        signal.signal(signal_code, idle_handler)
        GLib.idle_add(install_glib_handler, signal_code, priority=GLib.PRIORITY_HIGH) 
Example #7
Source File: canvas.py    From RAFCON with Eclipse Public License 1.0 6 votes vote down vote up
def wait_for_update(self, trigger_update=False):
        """Update canvas and handle all events in the gtk queue

        :param bool trigger_update: Whether to call update_now() or not
        """
        if trigger_update:
            self.update_now()

        from gi.repository import Gtk
        from gi.repository import GLib
        from threading import Event
        event = Event()

        # Handle all events from gaphas, but not from gtkmvc3
        # Make use of the priority, which is higher for gaphas then for gtkmvc3
        def priority_handled(event):
            event.set()
        priority = (GLib.PRIORITY_HIGH_IDLE + GLib.PRIORITY_DEFAULT_IDLE) / 2
        # idle_add is necessary here, as we do not want to block the user from interacting with the GUI
        # while gaphas is redrawing
        GLib.idle_add(priority_handled, event, priority=priority)
        while not event.is_set():
            Gtk.main_iteration() 
Example #8
Source File: image.py    From vimiv with MIT License 6 votes vote down vote up
def _load_thread(self, loader, path):
        # The try ... except wrapper and the _faulty_image attribute are used to
        # catch weird images that break GdkPixbufLoader but work otherwise
        # See https://github.com/karlch/vimiv/issues/49 for more information
        try:
            self._faulty_image = True
            with open(path, "rb") as f:
                image_bytes = f.read()
                loader.write(image_bytes)
            self._faulty_image = False
            loader.close()
        except GLib.GError:
            self._pixbuf_original = GdkPixbuf.Pixbuf.new_from_file(path)
            self._faulty_image = False
            self._set_image_pixbuf()
            GLib.idle_add(self._update) 
Example #9
Source File: helpers.py    From brave with Apache License 2.0 6 votes vote down vote up
def run_on_master_thread_when_idle(func, **func_args):
    '''
    This function allows other threads (runing the API) to call a function
    on the master thread (running GStreamer) at a moment when it is idle.
    '''
    def function_runner(args):
        if args['func'] is None:
            raise RuntimeError('Missing function to run on master thread (within run function)!')

        try:
            f = args['func']
            func_args = args['func_args']
            f(**func_args)
        except Exception as e:
            print('------------ UNCAUGHT EXCEPTION ON MASTER THREAD: %s ------------' % e, file=sys.stderr)
            print(traceback.format_exc(), file=sys.stderr)

        return False

    if func is None:
        raise RuntimeError('Missing function to run on master thread!')
    GLib.idle_add(function_runner, {'func': func, 'func_args': func_args}) 
Example #10
Source File: gui_utilities.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def glib_idle_add_store_extend(store, things, clear=False, wait=False):
	"""
	Extend a GTK store object (either :py:class:`Gtk.ListStore` or
	:py:class:`Gtk.TreeStore`) object using :py:func:`GLib.idle_add`. This
	function is suitable for use in non-main GUI threads for synchronizing data.

	:param store: The GTK storage object to add *things* to.
	:type store: :py:class:`Gtk.ListStore`, :py:class:`Gtk.TreeStore`
	:param tuple things: The array of things to add to *store*.
	:param bool clear: Whether or not to clear the storage object before adding *things* to it.
	:param bool wait: Whether or not to wait for the operation to complete before returning.
	:return: Regardless of the *wait* parameter, ``None`` is returned.
	:rtype: None
	"""
	if not isinstance(store, Gtk.ListStore):
		raise TypeError('store must be a Gtk.ListStore instance')
	idle_add = glib_idle_add_wait if wait else glib_idle_add_once
	idle_add(_store_extend, store, things, clear) 
Example #11
Source File: gui_utilities.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def glib_idle_add_wait(function, *args, **kwargs):
	"""
	Execute *function* in the main GTK loop using :py:func:`GLib.idle_add`
	and block until it has completed. This is useful for threads that need
	to update GUI data.

	:param function function: The function to call.
	:param args: The positional arguments to *function*.
	:param kwargs: The key word arguments to *function*.
	:return: The result of the function call.
	"""
	gsource_completed = threading.Event()
	results = []

	@functools.wraps(function)
	def wrapper():
		results.append(function(*args, **kwargs))
		gsource_completed.set()
		return False
	GLib.idle_add(wrapper)
	gsource_completed.wait()
	return results.pop() 
Example #12
Source File: commandline.py    From vimiv with MIT License 6 votes vote down vote up
def _thread_for_external(self, cmd, p, from_pipe):
        """Start a new thread for external commands.

        Args:
            cmd: The command to run.
            directory: Directory which is affected by command.
        """
        # Get output and error and run the command
        out, err = p.communicate()
        if p.returncode:
            message = "Command exited with status " + str(p.returncode) + "\n"
            message += err.decode()
            GLib.idle_add(self._app["statusbar"].message, message, "error")
        else:
            # Run pipe if we have output
            if from_pipe:
                GLib.idle_add(self._run_pipe, out)
            # We do not know what might have changed concerning paths
            else:
                GLib.idle_add(self._app.emit, "paths-changed", self)
        self.running_processes.pop() 
Example #13
Source File: sniffer.py    From btle-sniffer with MIT License 6 votes vote down vote up
def _connect(self, device):
        def cb_connect():
            try:
                bus = pydbus.SystemBus()
                proxy = bus.get(SERVICE_NAME, device.path)
                proxy.Connect()
            except KeyError:
                self._log.debug("The device has likely disappeared.", exc_info=True)
            except GLib.Error:
                self._log.debug("Connect() failed:", exc_info=True)
            else:
                self._log.info("Connection successful.")

            self.queued_connections -= 1

        if self.queued_connections == 0:
            print_device(device, "Connecting")
            GLib.idle_add(cb_connect)
            device.connected = True
            self.queued_connections += 1 
Example #14
Source File: wattman.py    From WattmanGTK with GNU General Public License v2.0 5 votes vote down vote up
def refresh(refreshtime,Handler,Plot):
    # Used in thread to update the values in the gui and plot
    while True:
        GLib.idle_add(Handler.update_gui)
        GLib.idle_add(Plot.refresh)
        time.sleep(refreshtime) 
Example #15
Source File: image.py    From vimiv with MIT License 5 votes vote down vote up
def _play_gif(self):
        """Run the animation of a gif."""
        self._pixbuf_original = self._pixbuf_iter.get_pixbuf()
        GLib.idle_add(self._update)
        if self._pixbuf_iter.advance():
            # Clear old timer
            if self._timer_id:
                GLib.source_remove(self._timer_id)
            # Add new timer if the gif is not static
            delay = self._pixbuf_iter.get_delay_time()
            self._timer_id = GLib.timeout_add(delay, self._play_gif) \
                if delay >= 0 else 0 
Example #16
Source File: __init__.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def on_save_as_clicked(self, widget):
        dialog = Gtk.FileChooserDialog(
            _("Save as"), mainwindow(), Gtk.FileChooserAction.SAVE,
            (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_SAVE,
             Gtk.ResponseType.ACCEPT))
        dialog.set_current_folder(os.path.expanduser("~"))

        response = dialog.run()
        if response == Gtk.ResponseType.ACCEPT:
            filename = dialog.get_filename()
        else:
            filename = None

        dialog.destroy()

        if filename is None:
            return

        self.progress_dialog.set_title(_("Save as"))

        def save_as(cancel_event):
            with open(filename, "w") as to_file:
                self.process_records(self.save_records, cancel_event, to_file)

            GLib.idle_add(self.progress_dialog.hide)

        cancel_event = threading.Event()
        loop = asyncio.get_event_loop()
        loop.run_in_executor(None, save_as, cancel_event)

        response = self.progress_dialog.run()
        if response == Gtk.ResponseType.CANCEL:
            cancel_event.set()
        self.progress_dialog.hide() 
Example #17
Source File: thumbnail_manager.py    From vimiv with MIT License 5 votes vote down vote up
def _do_callback(result):
        GLib.idle_add(*result) 
Example #18
Source File: image.py    From vimiv with MIT License 5 votes vote down vote up
def _finish_image_pixbuf(self, loader, image_id):
        if self._identifier == image_id:
            GLib.idle_add(self._update) 
Example #19
Source File: __init__.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def importing(self, filenames):
        drop_indexes(self.chessfile.engine)

        self.importer = PgnImport(self.chessfile, append_pgn=True)
        self.importer.initialize()
        for i, filename in enumerate(filenames):
            if len(filenames) > 1:
                GLib.idle_add(self.progressbar0.set_fraction, i / float(len(filenames)))
            if self.importer.cancel:
                break
            if isinstance(filename, tuple):
                info_link, pgn_link = filename
                self.importer.do_import(pgn_link, info=info_link, progressbar=self.progressbar)
            else:
                self.importer.do_import(filename, progressbar=self.progressbar)

        GLib.idle_add(self.progressbar.set_text, _("Recreating indexes..."))

        # .sqlite
        create_indexes(self.chessfile.engine)

        # .scout
        self.chessfile.init_scoutfish()

        # .bin
        self.chessfile.init_chess_db()

        self.chessfile.set_tag_filter(None)
        self.chessfile.set_fen_filter(None)
        self.chessfile.set_scout_filter(None)
        GLib.idle_add(self.gamelist.load_games)
        GLib.idle_add(self.emit, "chessfile_imported", self.chessfile)
        GLib.idle_add(self.progressbar0.hide)
        GLib.idle_add(self.progress_dialog.hide) 
Example #20
Source File: script.py    From RAFCON with Eclipse Public License 1.0 5 votes vote down vote up
def execute(self, inputs, outputs, gvm):
    warnings.warn("Please substitute MessageDialog with 'generic/dialog/Dialog [Info]'. "
                  "See the library description for details on the new API.", RAFCONDeprecationWarning)
    self.logger.debug("Creating message dialog")
    markup_text = inputs['message_text']
    abort = inputs['abort_on_quit']

    def run_dialog(event, result, logger):
        dialog_window = RAFCONMessageDialog(markup_text=markup_text,
                                            message_type=Gtk.MessageType.INFO, flags=Gtk.DialogFlags.MODAL,
                                            parent=get_root_window())
        result[1] = dialog_window
        result[0] = dialog_window.run()
        dialog_window.destroy()

        event.set()

    event = self._preempted
    result = [None, None]  # first entry is the dialog return value, second one is the dialog object
    GLib.idle_add(run_dialog, event, result, self.logger)

    # Event is either set by the dialog or by an external preemption request
    event.wait()

    response_id, dialog = result

    # The dialog was not closed by the user, but we got a preemption request
    if response_id is None:
        GLib.idle_add(dialog.destroy)
        return "preempted"

    event.clear()

    if response_id == -5:
        return 0
    
    if abort:
        return 'aborted'
    else:
        return 0 
Example #21
Source File: widgets.py    From nautilus-folder-icons with GNU General Public License v3.0 5 votes vote down vote up
def emit(self, *args):
        # Use idle_add to make it possible to use emit within a Thread
        GLib.idle_add(GObject.GObject.emit, self, *args) 
Example #22
Source File: trayicon.py    From networkmgr with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def updateinfo(self):
        if self.ifruning is False:
            self.ifruning = True
            self.cardinfo = networkdictionary()
            defaultcard = self.cardinfo['default']
            default_type = self.network_type(defaultcard)
            sleep(1)
            GLib.idle_add(self.updatetray, defaultcard, default_type) 
Example #23
Source File: GameListPanel.py    From pychess with GNU General Public License v3.0 5 votes vote down vote up
def onGameAdd(self, games, new_games):
        game_store = {}
        for game in new_games:
            game_store[game] = (game, self.clearpix,
                                game.wplayer.name + game.wplayer.display_titles(),
                                game.wplayer.getRatingForCurrentGame(),
                                game.bplayer.name + game.bplayer.display_titles(),
                                game.bplayer.getRatingForCurrentGame(),
                                game.display_text, game.display_rated)

        def do_onGameAdd(games, new_games, game_store):
            for game in new_games:
                # game removed before we finish processing "games /bslwBzSLx"
                if game not in game_store:
                    continue
                # log.debug("%s" % game,
                # extra={"task": (self.connection.username, "GTS.onGameAdd")})
                ti = self.store.append(game_store[game])
                self.games[game] = {"ti": ti}
                self.games[game]["private_cid"] = game.connect(
                    "notify::private", self.private_changed)
                self._update_gamesrunning_label()

        GLib.idle_add(do_onGameAdd,
                      games,
                      new_games,
                      game_store,
                      priority=GLib.PRIORITY_LOW) 
Example #24
Source File: channel.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app):
    self.app    = app
    self.stack  = app.channels_stack
    self.filter = None

    self.channels = Gtk.Builder()
    self.channels.add_from_file(relative_path('ui/channels.ui'))
    self.channels.connect_signals(self)

    self.channels_box = self.channels.get_object('box_channels')
    self.stack.add_named(self.channels_box, 'channels_container')

    self.channels_filters = self.channels.get_object('list_box_channels_filters')
    self.channels_list    = self.channels.get_object('flow_box_channels_list')
    self.channels_list.set_filter_func(self.on_channels_list_row_changed)

    GLib.idle_add(self.do_initial_setup) 
Example #25
Source File: player.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def on_toolbar_player_enter_notify_event(self, _widget, _event):
    self.toolbar_stick = True
    GLib.idle_add(self.toggle_toolbar, False) 
Example #26
Source File: backend_gtk3.py    From neural-network-animation with MIT License 5 votes vote down vote up
def draw_idle(self):
        def idle_draw(*args):
            try:
                self.draw()
            finally:
                self._idle_draw_id = 0
            return False
        if self._idle_draw_id == 0:
            self._idle_draw_id = GLib.idle_add(idle_draw) 
Example #27
Source File: backend_gtk3.py    From neural-network-animation with MIT License 5 votes vote down vote up
def __init__(self, figure):
        if _debug: print('FigureCanvasGTK3.%s' % fn_name())
        FigureCanvasBase.__init__(self, figure)
        GObject.GObject.__init__(self)

        self._idle_draw_id  = 0
        self._need_redraw   = True
        self._lastCursor    = None

        self.connect('scroll_event',         self.scroll_event)
        self.connect('button_press_event',   self.button_press_event)
        self.connect('button_release_event', self.button_release_event)
        self.connect('configure_event',      self.configure_event)
        self.connect('draw',                 self.on_draw_event)
        self.connect('key_press_event',      self.key_press_event)
        self.connect('key_release_event',    self.key_release_event)
        self.connect('motion_notify_event',  self.motion_notify_event)
        self.connect('leave_notify_event',   self.leave_notify_event)
        self.connect('enter_notify_event',   self.enter_notify_event)
        self.connect('size_allocate',        self.size_allocate)

        self.set_events(self.__class__.event_mask)

        self.set_double_buffered(True)
        self.set_can_focus(True)
        self._renderer_init()
        self._idle_event_id = GLib.idle_add(self.idle_event) 
Example #28
Source File: channel.py    From kickoff-player with GNU General Public License v3.0 5 votes vote down vote up
def do_update_channels_data(self):
    GLib.idle_add(self.app.toggle_reload, False)

    self.app.streams_api.save_channels()
    time.sleep(5)

    GLib.idle_add(self.do_channels_widgets)
    GLib.idle_add(self.update_channels_widgets)
    GLib.idle_add(self.app.toggle_reload, True) 
Example #29
Source File: search_widget.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def apply_search(self, panel, add_list):
        """
        Add persons to specified panel by self.queue.
        """
        thread_event = Event()
        context = GLib.main_context_default()
        while True:
            item = self.queue.get()

            if item == 'stop':
                self.queue.task_done()
                return

            add_list.append(item.handle)
            task_id = GLib.idle_add(self.do_this, thread_event,
                                    self.add_to_result,
                                    item.handle, panel)
            task = context.find_source_by_id(task_id)
            # wait until person is added to list
            while not thread_event.wait(timeout=0.01):
                if not self.in_search:
                    if task and not task.is_destroyed():
                        GLib.source_remove(task.get_id())
                    self.queue.task_done()
                    return
            thread_event.clear()
            self.queue.task_done() 
Example #30
Source File: search_widget.py    From addons-source with GNU General Public License v2.0 5 votes vote down vote up
def do_this(self, event, func, *args):
        """
        Do some function (and wait "event" in the thread).
        It should be called by "GLib.idle_add".
        In the end "event" will be set.
        """
        func(*args)
        event.set()