我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gi.repository.GObject.idle_add()。
def move_box_selection(self): if gv.jcchess.get_stopped(): (treemodel, treeiter) = gv.gui.move_view.get_selection().get_selected() if treeiter is not None: k = gv.gui.movestore.get_value(treeiter,0).find(".") nmove = int(gv.gui.movestore.get_value(treeiter,0)[0:k]) self.comments.set_moveno(nmove) # now call a method in jcchess.py to position it at the move # clicked on gv.jcchess.goto_move(nmove) path = str(nmove) self.treeview.set_cursor(path, None,False) GObject.idle_add(self.treeview.scroll_to_cell,path,None, False, 0,0) #arguments must be in list else: GObject.idle_add(gv.gui.move_view.unselect_all)
def command(self, cmd): e = self.side + "(" + self.get_running_engine().strip() + "):" if gv.verbose or gv.verbose_uci: print("->" + e + cmd.strip()) GObject.idle_add(self.engine_debug.add_to_log, "->" + e + cmd.strip()) try: # write as string (not bytes) since universal_newlines=True self.p.stdin.write(cmd) except AttributeError: GObject.idle_add( self.engine_debug.add_to_log, "# engine process is not running") except IOError: GObject.idle_add( self.engine_debug.add_to_log, "# engine process is not running")
def __init__(self, n, front, back, step): from gi.repository import Gtk from gi.repository import GObject Render.__init__(self, n, front, back) window = Gtk.Window() self.window = window window.resize(self.n, self.n) self.step = step window.connect("destroy", self.__destroy) darea = Gtk.DrawingArea() # darea.connect("expose-event", self.expose) self.darea = darea window.add(darea) window.show_all() #self.cr = self.darea.window.cairo_create() self.steps = 0 GObject.idle_add(self.step_wrap)
def _on_config_change(self): self._last_graph_update = 0 market_ids = set([get_market_id(mc) for mc in config['markets']]) removed_market_ids = self._last_ticer.keys() - market_ids [self._last_ticer.pop(market_id, None) for market_id in removed_market_ids] market_ids = set([get_market_id(mc) for mc in config['markets'] if mc['graph']]) removed_graph_market_ids = self._graph_data_dict.keys() - market_ids [self._graph_data_dict.pop(market_id, None) for market_id in removed_graph_market_ids] self._main_win.remove_graph_markets(removed_graph_market_ids) for market_id in self._last_ticer: last_price = self._last_ticer[market_id]['close'] market_config, _ = config.get_market_by_id(market_id) price_str = btcwidget.currency.service.format_price(last_price, market_config['market'][3:]) GObject.idle_add(self._main_win.set_current_price, market_id, price_str) for market_id in self._graph_data_dict: self._update_market_graph(market_id)
def on_mcg_connect(self, connected): if connected: GObject.idle_add(self._connect_connected) self._mcg.load_playlist() self._mcg.load_albums() self._mcg.get_status() self._connect_action.set_state(GLib.Variant.new_boolean(True)) self._play_action.set_enabled(True) self._clear_playlist_action.set_enabled(True) self._panel_action.set_enabled(True) else: GObject.idle_add(self._connect_disconnected) self._connect_action.set_state(GLib.Variant.new_boolean(False)) self._play_action.set_enabled(False) self._clear_playlist_action.set_enabled(False) self._panel_action.set_enabled(False)
def on_mcg_status(self, state, album, pos, time, volume, error): # Album GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_album, album) # State if state == 'play': GObject.idle_add(self._header_bar.set_play) GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_play, pos, time) self._play_action.set_state(GLib.Variant.new_boolean(True)) elif state == 'pause' or state == 'stop': GObject.idle_add(self._header_bar.set_pause) GObject.idle_add(self._panels[Window._PANEL_INDEX_COVER].set_pause) self._play_action.set_state(GLib.Variant.new_boolean(False)) # Volume GObject.idle_add(self._header_bar.set_volume, volume) # Error if error is None: self._infobar.hide() else: self._show_error(error)
def _change_tracklist_size(self, size, notify=True, store=True): # Set tracklist size if size == TracklistSize.LARGE: self._panel.set_homogeneous(True) self._info_revealer.set_reveal_child(True) elif size == TracklistSize.SMALL: self._panel.set_homogeneous(False) self._info_revealer.set_reveal_child(True) else: self._panel.set_homogeneous(False) self._info_revealer.set_reveal_child(False) # Store size if store: self._tracklist_size = size # Notify signals if notify: self.emit('tracklist-size-changed', size) # Resize image GObject.idle_add(self._resize_image)
def parse_all_files(self, when_idle): """ Parse all standard lesson files and the user_lessonfiles. Will not check if reparse is necessary. """ logging.debug("parse_all_files(when_idle=%s)", when_idle) if when_idle: self._lessonfiles_iterator = self.iter_parse_all_files() def on_idle_parse(): try: filename = self._lessonfiles_iterator.next() return True except StopIteration: logging.debug("parse_all_files(...) done.") import time print "all files parsed:", time.time() - start_time pt.Identifier.check_ns = True return False GObject.idle_add(on_idle_parse) else: list(self.iter_parse_all_files())
def __create_model(self): self.logger.info('Creating ListStore') start = time.perf_counter() model = AdapterSong.create_store() order = AbstractPlaylist.OrderBy[self.userconfig['grid']['sort']['field']] desc = self.userconfig['grid']['sort']['desc'] songs = self.current_playlist.collections(order, desc) for row in songs: model.insert_with_valuesv(-1, AdapterSong.create_col_number(), AdapterSong.create_row(row)) GObject.idle_add(lambda: self.__create_model_finished(model)) end = time.perf_counter() self.logger.info('ListStore created in {:.3f} seconds'.format(end - start))
def download(self, path): text = '' tab_type = self.model[path][0] name = self.model[path][1] url = self.model[path][3] if tab_type == 'tab': text = tabs_fetcher.fetch_ascii_tab(url) elif tab_type == 'guitar pro': path = tabs_fetcher.download_guitar_pro_tab(url, '/tmp/') if path is not None: text = f'{name} downloaded at "{path}"' file_helper.open_file(path) else: text = f'Error while downloading {name}' GObject.idle_add(lambda: self.on_download_finished(text))
def update_menu_item(self): """Update the menu item. :return: """ GObject.idle_add( self.menu_item.set_label, "Ping: " + self.address + self.print_name() + self.state, priority=GObject.PRIORITY_HIGH ) GObject.idle_add( self.menu_item.set_image, self.image, priority=GObject.PRIORITY_HIGH ) GObject.idle_add( self.menu_item.show, priority=GObject.PRIORITY_HIGH )
def set_subcategory(self, root_category, num_items=0, block=False): # nothing to do if (root_category is None or self.categories == root_category.subcategories): return self.current_category = root_category self.header = root_category.name self.categories = root_category.subcategories if not self._built: self._build_subcat_view() self._update_subcat_view(root_category, num_items) GObject.idle_add(self.queue_draw) return
def refresh_apps(self): supported_only = get_global_filter().supported_only if (self.current_category is None or self._supported_only == supported_only): return self._supported_only = supported_only if not self._built: self._build_subcat_view() self._update_subcat_view(self.current_category) GObject.idle_add(self.queue_draw) return #def build(self, desktopdir): #self.in_subsection = True #self.set_subcategory(self.root_category) #return
def mark_changes(self, checkbutton): LOG.debug("mark_changes") addon = checkbutton.pkgname installed = self.view.cache[addon].installed if checkbutton.get_active(): if addon not in self.addons_to_install and not installed: self.addons_to_install.append(addon) if addon in self.addons_to_remove: self.addons_to_remove.remove(addon) else: if addon not in self.addons_to_remove and installed: self.addons_to_remove.append(addon) if addon in self.addons_to_install: self.addons_to_install.remove(addon) self.status_bar.configure() GObject.idle_add(self.view.update_totalsize, priority=GObject.PRIORITY_LOW)
def on_channel_selected(self, item, event, channel, view_id): vm = self.view_manager def config_view(): # set active pane pane = vm.set_active_view(view_id) # configure DisplayState state = pane.state.copy() state.category = None state.subcategory = None state.channel = channel # decide which page we want to display if hasattr(pane, "Pages"): if channel.origin == "all": page = pane.Pages.HOME else: page = pane.Pages.LIST else: page = None # request page change vm.display_page(pane, page, state) return False GObject.idle_add(config_view)
def __init__(self, oneconfviewpickler): '''Controller of the installed pane''' LOG.debug("OneConf Handler init") super(OneConfHandler, self).__init__() # OneConf stuff self.oneconf = DbusConnect() self.oneconf.hosts_dbus_object.connect_to_signal('hostlist_changed', self.refresh_hosts) self.oneconf.hosts_dbus_object.connect_to_signal('packagelist_changed', self._on_store_packagelist_changed) self.oneconf.hosts_dbus_object.connect_to_signal('latestsync_changed', self.on_new_latest_oneconf_sync_timestamp) self.already_registered_hostids = [] self.is_current_registered = False self.oneconfviewpickler = oneconfviewpickler # refresh host list self._refreshing_hosts = False GObject.timeout_add_seconds(MIN_TIME_WITHOUT_ACTIVITY, self.get_latest_oneconf_sync) GObject.idle_add(self.refresh_hosts)
def change_the_title_of_note_in_menu(self,old_title,new_title): print "|||||||||||||||"*20 print "tile cchanged" + new_title for i in self.menu.get_children(): logger.debug("in loop") logger.debug(i.get_label()) if (i.get_submenu()): logger.debug("Submenu is here") for j in i.get_submenu().get_children(): logger.debug("---->" + j.get_label()) for i in self.menu.get_children()[7].get_submenu().get_children(): if old_title == i.get_label(): GObject.idle_add(i.set_label,new_title)
def change_item_icon(self,title,icon): for i in self.menu.get_children(): logger.debug("in loop") logger.debug(i.get_label()) if (i.get_submenu()): logger.debug("Submenu is here") for j in i.get_submenu().get_children(): logger.debug("---->" + j.get_label()) for i in self.menu.get_children()[7].get_submenu().get_children(): if title == i.get_label(): GObject.idle_add(i.set_image,Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.LARGE_TOOLBAR)) logger.debug("Icon changed to: ", str(icon))
def run_pygame(self, main_fn): # Run the main loop after a short delay. The reason for the delay is that the # Sugar activity is not properly created until after its constructor returns. # If the Pygame main loop is called from the activity constructor, the # constructor never returns and the activity freezes. GObject.idle_add(self._run_pygame_cb, main_fn)
def evt_eos(self, event): self.end_time = time.time() self.unregister_event("eos") self.pipeline.stop() render_duration = self.end_time - self.start_time fps = self.settings['framerate']*self.settings['duration']/render_duration logger.info("Rendering of %s took %.2fs (%i fps)" % (self.output_file, render_duration, fps)) GObject.idle_add(self.mainloop.quit)
def set_move(self, move_idx): path = (move_idx,) #self.tree_selection.select_path(path) to be bypasses if cursor_changed as event in moves_clicked self.comments.set_moveno(move_idx) if gv.show_moves == True: if move_idx > 0: path = str(move_idx-1) #gv.gui.move_view.set_cursor(path, None,False) if path[0]!=0 and path!='0': GObject.idle_add(gv.gui.move_view.scroll_to_cell,path,None, False, 0,0) #arguments must be in list return
def treeview_button_press(self, treeview, event): if gv.jcchess.get_stopped(): GObject.idle_add(self.process_tree_selection) else: GObject.idle_add(self.tree_selection.unselect_all) # set the board position at the move the user clicked on
def engine1_button_clicked(self, b): player = gv.jcchess.get_player(WHITE) if player == "Human" or player == "jcchess": GObject.idle_add( self.add_to_log, "# command not sent - player 1 (white) is not a USI engine") return cmd = self.cmd_entry.get_text() + "\n" gv.usiw.command(cmd) # send command to engine2 (black)
def add_to_log(self, msg): msg = msg + "\n" try: # append to end of buffer end_iter = self.tb.get_end_iter() self.tb.insert(end_iter, msg) # scroll to end GObject.idle_add(self.scroll_to_end) except AttributeError: # engine debug window has not been opened. Append the debug # messages until it is opened self.debug_text += msg
def show_debug_window(self, b): # window already exists and is hidden so just show it if self.window is not None: # "present" will show the window if it is hidden # if not hidden it will raise it to the top self.window.present() return # This is the first time the user has opened the engine debug # window so need to create it. self.builder = Gtk.Builder() self.builder.set_translation_domain(gv.domain) self.builder.add_from_file(self.glade_file) self.builder.connect_signals(self) self.window = self.builder.get_object("engine_debug_window") self.tv = self.builder.get_object("engine_debug_textview") self.tv.set_editable(False) self.tb = self.tv.get_buffer() self.tb.set_text(self.debug_text) self.debug_text = "" # used to type commands and send them to the engine self.cmd_entry = self.builder.get_object("engine_debug_entry") self.window.show_all() # scroll to end GObject.idle_add(self.scroll_to_end)
def read_stdout(self): while True: try: e = ("<-" + self.side + "(" + self.get_running_engine().strip() + "):") line= "" # python2 line = unicode(self.p.stdout.readline(), errors ='ignore') # or: 'your iso 8859-15 text'.decode('iso8859-15') # python3 (doesn't work) lineb = self.p.stdout.readline().encode("utf-8", "ignore") #print(lineb) #line = str(lineb) #print(line, "line") line = self.p.stdout.readline() if line == "": if gv.verbose: print(e + "eof reached") if gv.verbose: print(e + "stderr:", self.p.stderr.read()) break #line = line[2:-3] #print(line) line = line.strip() if gv.verbose or gv.verbose_uci: print(e + line) GObject.idle_add(self.engine_debug.add_to_log, e+line) if line.startswith("info"): GObject.idle_add( self.engine_output.add_to_log, self.side, self.get_running_engine().strip(), line) self.op.append(line) except Exception as e: # line = e + "error" print("subprocess error in uci.py read_stdout:", e, "at:", line)
def build_board(self): GObject.idle_add(self.update) # convert jcchess co-ordinates for square into # standard notation (e.g. (1, 0) -> b1)
def set_square_as_unoccupied(self, x, y): self.dnd = (x, y) # redraw square GLib.idle_add(gv.gui.get_event_box(x, y).queue_draw) # called from gui.py when editing the board position to set the piece # on a square.
def set_piece_at_square(self, x, y, piece, colour): self.chessboard.set_piece_at(chess.square(x, y), chess.Piece(piece, colour)) GLib.idle_add(gv.gui.get_event_box(x, y).queue_draw) # called from gui.py to remove piece during promotion dialog
def remove_piece_at_square(self, x, y): piece=self.chessboard.remove_piece_at(chess.square(x, y)) GLib.idle_add(gv.gui.get_event_box(x, y).queue_draw) return piece # called when user does a "clear board" in board edit
def emit(self, *args): GObject.idle_add(GObject.GObject.emit, self, *args)
def quit(self): """Exit the UI event loop.""" GObject.idle_add(Gtk.main_quit)
def schedule_screen_update(self, apply_updates): """Schedule screen updates to run in the UI event loop.""" def wrapper(): apply_updates() self._flush() self._start_blinking() self._screen_invalid() GObject.idle_add(wrapper)
def _fetch_market_ticker(self, market_id): market_config, _ = config.get_market_by_id(market_id) exchange, market = market_config['exchange'], market_config['market'] provider = btcwidget.exchanges.factory.get(exchange) try: price = provider.ticker(market) except Exception as e: print('Failed to update ticker data for {}: {}'.format(market_id, e), file=sys.stderr) price = None if price: price_str = btcwidget.currency.service.format_price(price, market[3:]) print('{} {} ticker: {}'.format(provider.get_name(), market, price_str)) GObject.idle_add(self._main_win.set_current_price, market_id, price_str) self._check_alarms(exchange, market, price) self._last_ticer[market_id] = { 'time': time.time(), 'open': price, 'close': price, } if market_id in self._graph_data_dict: graph_data = self._graph_data_dict[market_id] graph_data.append(self._last_ticer[market_id]) self._update_market_graph(market_id) self._ticker_threads.pop(market_id, None)
def _update_market_graph(self, market_id): now = time.time() graph_data = self._graph_data_dict[market_id] graph_data = [t for t in graph_data if t['time'] > now - config['graph_period_sec']] GObject.idle_add(self._main_win.set_graph_data, market_id, graph_data)
def _trigger_alarm(self, alarm, price): if alarm['type'] == 'A': GObject.idle_add(btcwidget.alarmmessage.alarm_above_message, alarm, price) else: GObject.idle_add(btcwidget.alarmmessage.alarm_below_message, alarm, price) config['alarms'].remove(alarm) config.save()
def watch_yourlanguage(self): # fill exceptions (gui) list with data self.update_exceptions_gui() # fetch set initial data wmclass1 = self.get_activeclass() activelang1 = self.get_currlangname() while True: time.sleep(1) # if language is changed during lockstate, revert afterwards if self.lockscreen_check(): self.lock_state(activelang1) wmclass2 = self.get_activeclass() activelang2 = self.get_currlangname() # first set a few conditions to act *at all* if all( [wmclass2, wmclass2 != "raven", wmclass2 != "Wprviews_window", activelang2]): classchange = wmclass2 != wmclass1 langchange = activelang2 != activelang1 if classchange: self.set_lang_onclasschange(wmclass2, activelang2) activelang2 = self.get_currlangname() elif langchange: self.set_exception(activelang2, wmclass2) GObject.idle_add( self.update_exceptions_gui, priority=GObject.PRIORITY_DEFAULT, ) open(lang_datafile, "wt").write(str(self.langdata)) wmclass1 = wmclass2 activelang1 = activelang2
def set_label(self, newlabel): GObject.idle_add( self.timer.set_text, newlabel, priority=GObject.PRIORITY_DEFAULT )
def set_newicon(self, newicon): GObject.idle_add( self.seticon.set_from_pixbuf, newicon, priority=GObject.PRIORITY_DEFAULT )
def set_state(self, state, *args): for widget in [ self.hoursbutton, self.minsbutton, self.secsbutton, self.sleep, self.nf_bell, self.runcomm, self.nf_icon, self.nf_message, self.command_entry, self.hrs_label, self.secs_label, self.mins_label, ]: widget.set_sensitive(state) if state is True: self.context_start.remove_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION) self.context_start.add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION) self.applybutton.set_label("Run") GObject.idle_add( self.panelgrid.remove, self.timer, priority=GObject.PRIORITY_DEFAULT, ) GObject.idle_add( self.panelgrid.set_row_spacing, 10, priority=GObject.PRIORITY_DEFAULT, ) else: self.applybutton.set_label("Stop") self.context_start.remove_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION) self.context_start.add_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION) GObject.idle_add( self.panelgrid.attach, self.timer, 1, 1, 1, 1, priority=GObject.PRIORITY_DEFAULT, ) GObject.idle_add( self.panelgrid.set_row_spacing, 6, priority=GObject.PRIORITY_DEFAULT, ) active = self.runcomm.get_active() active = False if not all([active, state]) else True GObject.idle_add( self.command_entry.set_sensitive, active, priority=GObject.PRIORITY_DEFAULT, )
def on_mcg_error(self, error): GObject.idle_add(self._show_error, str(error)) # Settings callbacks
def __init__(self, builder): GObject.GObject.__init__(self) self._current_album = None self._cover_pixbuf = None self._timer = None self._properties = {} self._tracklist_size = TracklistSize.LARGE self._icon_theme = Gtk.IconTheme.get_default() # Widgets self._appwindow = builder.get_object('appwindow') self._panel = builder.get_object('cover-panel') self._toolbar = builder.get_object('cover-toolbar') # Toolbar menu self._toolbar_tracklist = builder.get_object('cover-toolbar-tracklist') self._toolbar_tracklist_buttons = { TracklistSize.LARGE: builder.get_object('cover-toolbar-tracklist-large'), TracklistSize.SMALL: builder.get_object('cover-toolbar-tracklist-small'), TracklistSize.HIDDEN: builder.get_object('cover-toolbar-tracklist-hidden') } # Cover self._cover_stack = builder.get_object('cover-stack') self._cover_spinner = builder.get_object('cover-spinner') self._cover_scroll = builder.get_object('cover-scroll') self._cover_box = builder.get_object('cover-box') self._cover_image = builder.get_object('cover-image') self._cover_stack.set_visible_child(self._cover_scroll) self._cover_pixbuf = self._get_default_image() # Album Infos self._info_revealer = builder.get_object('cover-info-revealer') self._info_box = builder.get_object('cover-info-box') self._album_title_label = builder.get_object('cover-album') self._album_date_label = builder.get_object('cover-date') self._album_artist_label = builder.get_object('cover-artist') # Songs self._songs_scale = builder.get_object('cover-songs') self._songs_scale.override_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1)) # Initial actions GObject.idle_add(self._enable_tracklist)
def on_cover_size_allocate(self, widget, allocation): GObject.idle_add(self._resize_image)
def on_grid_scale_change(self, widget, scroll, value): size = round(value) range = self._grid_scale.get_adjustment() if size < range.get_lower() or size > range.get_upper(): return self._item_size = size GObject.idle_add(self._set_widget_grid_size, self._library_grid, size, True) GObject.idle_add(self._library_grid.set_item_padding, size / 100)
def on_filter_entry_changed(self, widget): self._filter_string = self._filter_entry.get_text() GObject.idle_add(self._library_grid_filter.refilter)