def __init__(self, oneconfviewpickler): '''Controller of the installed pane''' LOG.debug("OneConf Handler init") super(OneConfHandler, self).__init__() # FIXME: should be an enum common to OneConf and here self.appname = "Ubuntu Software Center" # 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 start_capturing(self, widget): """" Start capturing the thermal image """ global date_format, extension, database_folder,\ xpixel, ypixel self.filename = database_folder + "/" + strftime(date_format, gmtime()) + db_ext self.window.start_button.set_sensitive(False) self.window.connect_button.set_sensitive(False) self.window.progressbar.set_no_show_all(False) self.window.progressbar.show() self.xpixel, self.ypixel = 0, 0 self.arduino.write("start".encode()) fig = plt.figure() plt.autoscale(True) plt.clf() cmap = get_cmap('jet') self.img = plt.imshow(self.data, interpolation="nearest", cmap=cmap, aspect='auto') plt.axis('off') self.cb = fig.colorbar(self.img) self.cb.set_label("Temperature (°" + unit_temperature.upper() + ") ") thread = Thread(target=plt.show) thread.setDaemon(True) thread.start() GObject.timeout_add_seconds(1, self.update_progressbar) self.thread = Thread(target=self.get_temperatures) self.thread.setDaemon(True) self.thread.start()
def __player_ended_cb(self, game): self.draw_pieces() self.drawingarea.queue_draw() if len(self.game.pieces) > 0: # si hay piezas puede pedir pero no pasar self.btnNew.props.sensitive = True self.btnPass.props.sensitive = False else: # si no hay piezas no puede pedir pero si pasar self.btnNew.props.sensitive = False self.btnPass.props.sensitive = True if not self.game.player_automatic_playing(): self.btnNew.props.sensitive = False self.btnPass.props.sensitive = False if not self.game.is_finished(): if self.game.ENABLE_AUTO_MODE: GObject.timeout_add(300, game.start_next_player) else: GObject.timeout_add_seconds(2, game.start_next_player) else: win = (self.game.winner == self.game.ui_player) self._finish_game(win)
def startup_init_update_timer(self): """ start the update timer with a delayed startup """ if AUTOCHECK_UPDATE: logger.debug('Starting delayed update timer') GObject.timeout_add_seconds( TIMER_STARTUP_DELAY, self.start_update_timer)
def update_timeout(self): if AUTOCHECK_UPDATE: self.next_update = self.next_update - 1 self.update_timer_id = -1 if self.next_update < 0: if self.yumex_running: # do not check for updates now: retry in a minute logger.debug('Yumex is running, try again in 1 minut') self.update_timer_id = GObject.timeout_add_seconds( 60, self.update_timeout) else: # check for updates: this will automatically restart the # timer self.get_updates() else: cur_timestamp = int(time.time()) if cur_timestamp - self.last_timestamp > 60 * 2: # this can happen on hibernation/suspend # or when the system time changes logger.debug('Time changed: restarting update timer') self.start_update_timer() else: self.update_timer_id = GObject.timeout_add_seconds( 60, self.update_timeout) self.last_timestamp = cur_timestamp return False
def initiate_purchase(self, app, iconname, url=None, html=None): """ initiates the purchase workflow inside the embedded webkit window for the item specified """ if not self._ask_for_tos_acceptance_if_needed(): self.emit("terms-of-service-declined") return False self.init_view() self.app = app self.iconname = iconname self.wk.webkit.load_html_string(self.LOADING_HTML, "file:///") self.wk.show() while Gtk.events_pending(): Gtk.main_iteration() if url: self.wk.webkit.load_uri(url) elif html: self.wk.webkit.load_html_string(html, "file:///") else: self.wk.webkit.load_html_string(DUMMY_HTML, "file:///") self.pack_start(self.wk, True, True, 0) # only for debugging if os.environ.get("SOFTWARE_CENTER_DEBUG_BUY"): GObject.timeout_add_seconds(1, _generate_events, self) return True
def __init__(self, pipeline_string='videotestsrc pattern=18 ! tee name=t ! queue ! autovideosink t. ! queue ! videoconvert ! videorate ! video/x-raw,width=(int)320,height=(int)240,format=(string)RGB16,framerate=(fraction)30/1 ! appsink name=sink'): self.data = None# this will contain the data passed between self.source_id = None self.lock = Lock() self.isWhite = True self.isStream = True self.timestamp = 0 self.pipeline = Gst.parse_launch(pipeline_string) self.appsink = self.pipeline.get_by_name('sink') assert self.appsink, 'appsink element named \'sink\' not found' self.appsink.connect('new-sample', self.on_new_buffer) self.appsink.set_property('emit-signals', True) self.pipeline.set_state(Gst.State.PLAYING) # OUTPUT pipeline self.pipeline_out = Gst.parse_launch('appsrc name=source ! videoconvert ! autovideosink') self.appsrc = self.pipeline_out.get_by_name('source') assert self.appsrc, 'appsrc element named \'source\' not found' self.appsrc.set_property('caps', Gst.Caps.from_string('video/x-raw,format=(string)RGB16,width=(int)320,height=(int)240,framerate=(fraction)30/1')) self.appsrc.connect('need-data', self.on_need_data) self.appsrc.connect('enough-data', self.on_enough_data) self.pipeline_out.set_state(Gst.State.PLAYING) GObject.timeout_add_seconds(2, self._switch_data_type)
def clear_token_from_ubuntu_sso_sync(appname): """ send a dbus signal to the com.ubuntu.sso service to clear the credentials for the given appname, e.g. _("Ubuntu Software Center") and wait for it to finish (or 2s) """ from ubuntu_sso import ( DBUS_BUS_NAME, DBUS_CREDENTIALS_IFACE, DBUS_CREDENTIALS_PATH, ) # clean loop = GObject.MainLoop() bus = dbus.SessionBus() obj = bus.get_object(bus_name=DBUS_BUS_NAME, object_path=DBUS_CREDENTIALS_PATH, follow_name_owner_changes=True) proxy = dbus.Interface(object=obj, dbus_interface=DBUS_CREDENTIALS_IFACE) proxy.connect_to_signal("CredentialsCleared", loop.quit) proxy.connect_to_signal("CredentialsNotFound", loop.quit) proxy.connect_to_signal("CredentialsError", loop.quit) proxy.clear_credentials(appname, {}) # ensure we don't hang forever here GObject.timeout_add_seconds(2, loop.quit) # run the mainloop until the credentials are clear loop.run()
def __init__(self): self._ind = AppIndicator3.Indicator.new_with_path( "mspanotify", "logo", AppIndicator3.IndicatorCategory.APPLICATION_STATUS, os.path.dirname(os.path.realpath(__file__)), ) self._ind.set_attention_icon_full("logo2", ":o") self._ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) menu = Gtk.Menu() self._prefs = PrefsWindow() goto_page_item = Gtk.MenuItem("Open MSPA in browser") check_now_item = Gtk.MenuItem("Check now") fake_check_item = Gtk.MenuItem("Fake check") prefs_item = Gtk.MenuItem("Preferences") quit_item = Gtk.MenuItem("Quit") goto_page_item.connect("activate", self._goto_page_activate) check_now_item.connect("activate", self._manual_check) fake_check_item.connect("activate", self._fake_check) sep1 = Gtk.SeparatorMenuItem() prefs_item.connect("activate", lambda w: self._prefs.show()) sep2 = Gtk.SeparatorMenuItem() quit_item.connect("activate", self._quit_activate) menu.append(goto_page_item) menu.append(check_now_item) menu.append(fake_check_item) menu.append(sep1) menu.append(prefs_item) menu.append(sep2) menu.append(quit_item) menu.show_all() self._ind.set_menu(menu) self._read_update_file() self._check() GObject.timeout_add_seconds(self._prefs.prefs["freq"], self._check)
def __init__ (self, run_selector = True): """run_selector means that we start our regular game. For testing purposes, it will be convenient to hand a run_selector=False to this method to avoid running the dialog and allow a tester to set up a game programmatically. """ self.settings = Gio.Settings("org.gnome.gnome-sudoku") self.setup_gui() self.timer = timer.ActiveTimer(self.w) self.gsd.set_timer(self.timer) self.won = False # add the accelerator group to our toplevel window self.worker_connections = [] self.is_fullscreen = False # setup sudoku maker... self.sudoku_maker = sudoku_maker.SudokuMaker() self.sudoku_tracker = saver.SudokuTracker() # generate puzzles while our use is working... self.show() if run_selector: self.do_stop() if self.select_game(): # If this return True, the user closed... self.quit = True else: self.quit = False # Generate puzzles in background... GObject.timeout_add_seconds(1, lambda *args: self.start_worker_thread() and True)
def get_test_window(): w = OneConfViews(Gtk.IconTheme.get_default()) w.show() win = Gtk.Window() win.set_data("pane", w) win.add(w) win.set_size_request(400, 600) win.connect("destroy", lambda x: Gtk.main_quit()) # init the view w.register_computer("AAAAA", "NameA") w.register_computer("ZZZZZ", "NameZ") w.register_computer("CCCCC", "NameC") w.register_computer(None, "This computer should be first") w.select_first() GObject.timeout_add_seconds(5, w.register_computer, "EEEEE", "NameE") def print_selected_hostid(widget, hostid, hostname): print "%s selected for %s" % (hostid, hostname) w.connect("computer-changed", print_selected_hostid) win.show_all() return win
def __init__(self): self.builder = Gtk.Builder() self.builder.set_translation_domain(LANG_DOM) self.builder.add_from_file(UI_FILE) self.builder.connect_signals(self) self.win=self.builder.get_object('window1') self.graf_box=self.builder.get_object('graf_box') self.statusbar = self.builder.get_object('statusbar') self.statusbar.push(1,_('Last access: ')) self.ui_label={} for label in labels: self.ui_label[label]=self.builder.get_object(label) fig = Figure() self.plot1 = fig.add_subplot(111) self.plot2 = fig.add_subplot(212) self.plot3 = fig.add_subplot(313) self.plot3.set_position([0.055,0.06,0.93,0.24]) self.plot2.set_position([0.055,0.38,0.93,0.24]) self.plot1.set_position([0.055,0.69,0.93,0.24]) self.canvas = FigureCanvas(fig) self.graf_box.pack_start(self.canvas,True,True,0) self.win.show_all() if self.get_params(): self.update_ui() GObject.timeout_add_seconds(180,self.update_ui)
def _on_take_picture(self, *args): sink = self.pipeline_launcher.pipeline.get_by_name('dumpsink') if sink: sample = sink.get_property('last-sample') buf = sample.get_buffer() diff = (buf.pts/Gst.SECOND - self.position) if abs(diff) > 1: logger.warning('Timestamp between pipeline position and dump differ by more than 1 second, you may be capturing a late buffer') cap = sample.get_caps() data = buf.extract_dup(0, buf.get_size()) logger.info("Got picture: %s" %cap) if self.pic_textbuffer.get_modified(): s, e = self.pic_textbuffer.get_bounds() fname = self.pic_textbuffer.get_text(s, e, include_hidden_chars=True) else: fname = "%s.jpg" %int(time.time()) self.pic_textbuffer.set_text(fname) self.pic_textbuffer.set_modified(False) abs_fname = os.path.join(self.folder, fname) if os.path.isfile(abs_fname): overwrite = self.yesno("Are you sure you want to overwrite file %s ?" %abs_fname) if not overwrite: return f = open(abs_fname, "wb") f.write(data) f.close() logger.info('Wrote file %s (%i kbytes)' %(abs_fname, round(buf.get_size()/1024))) size = int(round(os.path.getsize(abs_fname)/1024)) self.take_picture_btn.set_label('Picture saved (%s kB)' %size) GObject.timeout_add_seconds(3, self._reset_take_picture_btn) else: logger.error('dumpsink element not found')
def __init__(self): # Pretend to be an actual program for the sake of the example self.launcher = Unity.LauncherEntry.get_for_desktop_id ("test.desktop") # Initially show a count of 0 on the icon self.launcher.set_property("count", 0) self.launcher.set_property("count_visible", True) # Set progress to 42% done self.launcher.set_property("progress", 0.42) self.launcher.set_property("progress_visible", True) # We also want a quicklist ql = Dbusmenu.Menuitem.new () item1 = Dbusmenu.Menuitem.new () item1.property_set (Dbusmenu.MENUITEM_PROP_LABEL, "Item 1") item1.property_set_bool (Dbusmenu.MENUITEM_PROP_VISIBLE, True) item1.connect("item-activated", self.itemhandler) item2 = Dbusmenu.Menuitem.new () item2.property_set (Dbusmenu.MENUITEM_PROP_LABEL, "Item 2") item2.property_set_bool (Dbusmenu.MENUITEM_PROP_VISIBLE, True) item2.connect("item-activated", self.itemhandler) ql.child_append (item1) ql.child_append (item2) self.launcher.set_property("quicklist", ql) # init a counter self.counter = 0 # start a loop to update the icon every 2 seconds GObject.timeout_add_seconds(2, self.update_launcher)
def run(self): self.success = False self._timeout_count = 1 try: self.poll() except: pass if self.success or self.timeout == 0: # Return the current state on success # or timeout is 0 return self.success try: gobject.timeout_add_seconds(self.timeout_seconds, self._timeout_cb) if self.events: pyatspi.Registry.registerEventListener( self._event_cb, *self.events) if _main_loop: _main_loop.run() else: gtk.main() if self.events: pyatspi.Registry.deregisterEventListener( self._event_cb, *self.events) except: if self._ldtp_debug: print(traceback.format_exc()) return self.success
def set_run_buttons(self): for c in self.box.get_children(): self.box.remove(c) bbox = Gtk.Box(homogeneous=True) wbox = Gtk.Box(homogeneous=True) stopb = Gtk.Button(label="Stop") stopb.connect("clicked", self.on_stop) bbox.pack_start(stopb, False, False, 0) self.scorel = Gtk.Label(label="0") bbox.pack_start(self.scorel, False, False, 0) self.wordl = Gtk.Label(label="") wbox.pack_start(self.wordl, True, True, 0) timer = self.sm.get_timer() timel = Gtk.Label(label="%s:%s" %(str(timer/60).zfill(2), str(timer%60).zfill(2))) timel.timer = timer def on_timer(timel): timel.timer -= 1 m = timel.timer / 60 s = timel.timer % 60 timel.set_label("%s:%s" %(str(m).zfill(2), str(s).zfill(2))) if m == 0 and s == 0: self.on_timeout() return False else: return True GObject.timeout_add_seconds(1, on_timer, timel) bbox.pack_start(timel, True, True, 0) self.box.pack_start(bbox, False, False, 0) self.box.pack_start(wbox, False, False, 0)
def test_queries_while_batch_insert (self): self.assertTrue (os.path.exists ('ttl')) for root, dirs, files in os.walk('ttl'): for ttl_file in filter (lambda f: f.endswith (".ttl"), files): full_path = os.path.abspath(os.path.join (root, ttl_file)) print full_path counter = 0 current_batch = "" for line in open(full_path): if (line.startswith ("@prefix")): continue current_batch += line if len(line) > 1 and line[:-1].endswith ('.'): counter += 1 if counter == BATCH_SIZE: query = "INSERT {" + current_batch + "}" self.tracker.get_tracker_iface ().BatchSparqlUpdate (query, timeout=20000, reply_handler=self.batch_success_cb, error_handler=self.batch_failed_cb) self.run_a_query () counter = 0 current_batch = "" self.batch_counter += 1 gobject.timeout_add_seconds (2, self.run_a_query) # Safeguard of 60 seconds. The last reply should quit the loop gobject.timeout_add_seconds (60, self.timeout_cb) self.main_loop.run ()
def clip_password(self, item): pwname = item.password_name load_clipboard(self.cfg, pwname) from gi.repository import GObject GObject.timeout_add_seconds( self.cfg["clip_clear_time"], clear_clipboard)
def _update(self): try: element = self.ingredient_orders.popleft() if element.delete_time > datetime.datetime.now(): self.ingredient_orders.appendleft(element) except IndexError: pass if not len(self.ingredient_orders) == self.ingredient_orders.maxlen \ and not self.ingredient_orders_buffer.empty() and not self.ingredient_order_new: ingredient_id = self.ingredient_orders_buffer.get() try: element = ingredientorder.IngredientOrder(self.ingredients[ingredient_id]) element.delete_time = datetime.datetime.now() + datetime.timedelta(seconds=int(self.seconds_to_show)) self.ingredient_orders.append(element) self.ingredient_order_new = element print('Added new ingredient order to show with deletion time ' + element.delete_time.strftime('%H:%M:%S') + ' and ingredient ' + element.ingredient.ingredient_name) self.overlay.add_overlay(self.ingredient_order_new.ingredient.image) self.overlay.show_all() os.system("mpg321 {0} &".format(self.alert_sound_file)) GObject.timeout_add_seconds(int(self.seconds_to_show_big), self._remove_overlay) except KeyError: print('Cannot find id ' + str(ingredient_id) + ' in dictionary') for box in self.boxes: box.clear() i = 0 while True: try: self.boxes[i].set_from_pixbuf(self.ingredient_orders[i].ingredient.image_thumbnail.get_pixbuf()) except IndexError: break i += 1 return True
def send_command(self, command): if not self.skype_out: self.attach(command.Timeout) self.push_command(command) self.notifier.sending_command(command) cmd = '#%d %s' % (command.Id, command.Command) self.logger.debug('sending %s', repr(cmd)) if command.Blocking: if self.run_main_loop: command._event = event = threading.Event() else: command._loop = loop = gobject.MainLoop() command._set = False else: command._timer = timer = threading.Timer(command.timeout2float(), self.pop_command, (command.Id,)) try: result = self.skype_out.Invoke(cmd) except dbus.DBusException as err: raise SkypeAPIError(str(err)) if result.startswith('#%d ' % command.Id): self.notify(result) if command.Blocking: if self.run_main_loop: event.wait(command.timeout2float()) if not event.isSet(): raise SkypeAPIError('Skype command timeout') elif not command._set: gobject.timeout_add_seconds(int(command.timeout2float()), loop.quit) loop.run() if not command._set: raise SkypeAPIError('Skype command timeout') else: timer.start()
def test_add_license_key_backend(self): self._finished = False # add repo deb_line = "deb https://mvo:[email protected]/canonical-isd-hackers/internal-qa/ubuntu oneiric main" signing_key_id = "F5410BE0" app = Application("Test app1", self.PKGNAME) # install only when runnig as root, as we require polkit promtps # otherwise # FIXME: provide InstallBackendSimulate() if os.getuid() == 0: backend = get_install_backend() backend.ui = Mock() backend.connect("transaction-finished", self._on_transaction_finished) # simulate repos becomes available for the public 20 s later GObject.timeout_add_seconds(20, self._add_pw_to_commercial_repo) # run it backend.add_repo_add_key_and_install_app(deb_line, signing_key_id, app, "icon", self.LICENSE_KEY) # wait until the pkg is installed while not self._finished: while Gtk.events_pending(): Gtk.main_iteration() time.sleep(0.1) if os.getuid() == 0: self.assertTrue(os.path.exists(self.LICENSE_KEY_PATH)) self.assertEqual(open(self.LICENSE_KEY_PATH).read(), self.LICENSE_KEY)
def main(): #Setup logging level = logging.DEBUG logging.basicConfig(level=level) try: #Launches recording pipeline. I need to hook up into the Gst #messages. recorder = Recorder(logger=logging) except GObject.GError as excp: logging.critical("Unable to initialize GStreamer pipelines: %s", excp) sys.exit(127) #I need to tell the recorder which method will handle messages. recorder.register_message_handler(bus_message_handler) #recorder.register_buffer_handler(buffer_handler) #Create the loop and add a few triggers GObject.threads_init() loop = GObject.MainLoop() GObject.timeout_add_seconds(0, recorder.start) GObject.timeout_add_seconds(5, loop.quit) loop.run() #When the loop ends, set things back to reasonable states recorder.stop()
def main(argv): global mainloop, provider, options parser = optparse.OptionParser() parser.add_option("--provider", "-p", dest="provider", help="Provider to use", default="de-db") parser.add_option("--format", dest="format", help="Format to use (terse or full)", default="terse") parser.add_option("--when", dest="when", help="When to start the trip", default=None) options, args = parser.parse_args(argv) if len(args) == 3: start = args[1] end = args[2] else: print("Usage: %s <from> <to>" % argv[0]) return 1 manager = Lpf.Manager() provider = manager.activate_provider(options.provider) print("Loaded provider %s" % provider.props.name) when = parse_datetime(options.when) provider.get_locs(start, 0, locs_cb, (end, when)) mainloop = GObject.MainLoop() GObject.timeout_add_seconds(20, quit, "timed out") mainloop.run() return 0
def run(self): CgfwUtil.mkDirAndClear(self.param.tmpDir) try: sys.stdout = StdoutRedirector(os.path.join(self.param.tmpDir, "fpemud-cgfw.out")) sys.stderr = sys.stdout logging.getLogger().addHandler(logging.StreamHandler(sys.stderr)) logging.getLogger().setLevel(logging.INFO) # check configuration if len(CgfwCommon.getCgfwCfgList(self.param.etcDir)) == 0: raise Exception("no cgfw config file") # create main loop DBusGMainLoop(set_as_default=True) self.param.mainloop = GLib.MainLoop() self.param.dbusMainObject = DbusMainObject(self.param, self) # write pid file with open(os.path.join(self.param.tmpDir, "fpemud-cgfw.pid"), "w") as f: f.write(str(os.getpid())) # modify dns server configuration with open("/etc/resolv.conf", "r") as f: self.resloveFileContent = f.read() self.dnsmasqProc = self._runDnsmasq() with open("/etc/resolv.conf", "w") as f: f.write("# Generated by fpemud-cgfw\n") f.write("nameserver 127.0.0.1\n") logging.info("DNS resolution path modified.") # run vpn client GObject.timeout_add_seconds(0, self._timeoutCallback) # start main loop logging.info("Mainloop begins.") GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self._sigHandlerINT, None) GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self._sigHandlerTERM, None) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, self._sigHandlerHUP, None) GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1, self._sigHandlerUSR1, None) self.param.mainloop.run() logging.info("Mainloop exits.") finally: if self.vpnClientPidWatch is not None: GLib.source_remove(self.vpnClientPidWatch) if self.vpnClientProc is not None: self.vpnClientProc.terminate() self.vpnClientProc.wait() # revert dns resolution path if self.resloveFileContent is not None: with open("/etc/resolv.conf", "w") as f: f.write(self.resloveFileContent) if self.dnsmasqProc is not None: self.dnsmasqProc.terminate() self.dnsmasqProc.wait() logging.shutdown() shutil.rmtree(self.param.tmpDir)
def _childWatchCallback(self, pid, condition, user_data=None): assert pid == self.vpnClientProc.pid logging.info("CGFW VPN %s disconnected, re-connect in %d seconds." % (self.curCgfwCfg.name, self.param.reconnectTimeout)) self.vpnClientProc = None self.vpnClientPidWatch = None self.curCgfwCfg = None GObject.timeout_add_seconds(self.param.reconnectTimeout, self._timeoutCallback)
def play(self): if not self.playing: self.playing = True self.player.set_state(Gst.State.PLAYING) GObject.timeout_add_seconds(1, self.update_song_row) self.playpause_button.set_stock_id(Gtk.STOCK_MEDIA_PAUSE) self.update_song_row() self.emit('play-state-changed', True)
def _first_check(self): def _do_check(): self.send_check_updates_signal(startup_check = True) return False if self._dbus_service_available: # after 10 seconds, let the system fully start GObject.timeout_add_seconds(10, _do_check)
def __init__(self, score, title, commentary): WebKit.WebView.__init__(self) self.set_transparent(False) self.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0,0,0,0)) score = ParseScore.split_scores(score) self.load_html_string(ParseScore.generate_html(score, title, commentary), '') print("Webview loaded") GObject.timeout_add_seconds(10, self.callback)
def start_search(self, button, entry): self.show_cancel_button() self.search_progress_id = GObject.timeout_add_seconds(1, self.start_search_feedback, entry) self.finish_search_id = GObject.timeout_add_seconds(15, self.finish_search, button)
def __notify_timer_daily(self): seg = self.get_seg_until_next() self.dispatcher.emit('timer-nightly') if self.logger: self.logger.debug('timer-nightly in %s', seg) GObject.timeout_add_seconds(seg, self.__notify_timer_daily) return False
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.known_drawings = [] self.last_sync_time = 0 self._sync_label_timer = GObject.timeout_add_seconds( 60, self._update_sync_label) self._update_sync_label() Config.instance().connect('notify::orientation', self._on_orientation_changed)
def __response_cb(self, alert, response_id): self.remove_alert(alert) self._section_toolbar.accept_button.set_sensitive(True) self._section_toolbar.cancel_button.set_sensitive(True) if response_id is Gtk.ResponseType.CANCEL: self._section_view.undo() self._section_view.setup() self._options[self._current_option]['alerts'] = [] elif response_id is Gtk.ResponseType.ACCEPT: self._options[self._current_option]['alerts'] = \ self._section_view.restart_alerts self._show_main_view() elif response_id is Gtk.ResponseType.APPLY: self.busy() self._section_toolbar.accept_button.set_sensitive(False) self._section_toolbar.cancel_button.set_sensitive(False) get_session_manager().logout() GObject.timeout_add_seconds(4, self.__quit_timeout_cb)
def on_button1_clicked(self, widget): # Check size if not self.checksigsize(): # Submit to forum dialogreply = self.dialog.run() if dialogreply == Gtk.ResponseType.APPLY: self.statusmsg("Επικοινωνία...") timeid = GObject.timeout_add_seconds(1, self.webwrapper) self.dialog.hide()
def set_active(self, active): if active and not self.get_active(): self.timeout_id = GObject.timeout_add_seconds(self.interval, self.update_accounts, None) logger.debug("activated source: "+str(self.timeout_id)) elif not active and self.get_active(): GObject.source_remove(self.timeout_id) logger.debug("deactivated source "+str(self.timeout_id)) self.timeout_id = -1
def __init__(self, **kwargs): self._icon = NotificationPulsingIcon() self._icon.props.pixel_size = style.STANDARD_ICON_SIZE Gtk.EventBox.__init__(self, **kwargs) self.props.visible_window = False self._icon.props.pulse_color = \ XoColor('%s,%s' % (style.COLOR_BUTTON_GREY.get_svg(), style.COLOR_TRANSPARENT.get_svg())) self._icon.props.pulsing = True self.add(self._icon) self._icon.show() GObject.timeout_add_seconds(self._PULSE_TIMEOUT, self.__stop_pulsing_cb) self.set_size_request(style.GRID_CELL_SIZE, style.GRID_CELL_SIZE)
def on_dialog_shown(self, dialog): """ Fired when the dialog has been shown. """ # Start the timeout if self.countdown > 0: self.timeout_id = GObject.timeout_add_seconds( 1, self.process_countdown)
def __start_record(self, key): """Sets the timer for the duration of the scheduled recording that is about to start. If any connectivity errors occur, logger prints it properly. Args: key (str): the new mediapackage identifier. """ mp = self.repo.get(key) # FIXME what if the mp doesnt exist? if mp.status == mediapackage.SCHEDULED: self.mp_rec = key mp = self.repo.get(key) self.logger.info('Start time for recording %s, duration %s ms', mp.getIdentifier(), mp.getDuration()) GObject.timeout_add_seconds(mp.getDuration()/1000, self.__stop_record, mp.getIdentifier()) self.recorder.record(mp) del self.start_timers[mp.getIdentifier()]
def update_file_info_full(self, provider, handle, closure, file_): if (self.is_drive_root(file_)): # print "Detected Nuxeo Drive folder: " + file_.get_uri() file_.add_emblem("drive_sync") else: if (self.is_drive_managed_file(file_)): uri = file_.get_uri()[7:] if (self.runAsync): GObject.timeout_add_seconds(1, self.do_update_cb, provider, handle, closure, file_, uri) return Nautilus.OperationResult.IN_PROGRESS else: uri = file_.get_uri()[7:] self.get_drive_managed_file_status(file_, uri) self.callCounter = self.callCounter + 1 # print "Counter => " + str(self.callCounter) return Nautilus.OperationResult.COMPLETE
def time_changed(self): refresh_time = datetime.datetime.combine(datetime.date.today(), self.get_configuration()) secs_to_refresh = self.seconds_until(refresh_time) if self.timeout_source: GObject.source_remove(self.timeout_source) self.timeout_source = GObject.timeout_add_seconds( secs_to_refresh, self.emit_refresh)
def execute_after_process_exit(self, proc, func=None): def is_process_still_alive(): log.debug("is_process_still_alive() for pid: %i" % proc.pid) # First we need to see if the commit process is still running retval = proc.poll() log.debug("%s" % retval) still_going = (retval is None) if not still_going and callable(func): func() return still_going # Add our callback function on a 1 second timeout GObject.timeout_add_seconds(1, is_process_still_alive)
def dbus_targetnotfound_signal_hdl(self): self._exit = False # eventually interrupt termination self.set_status_to_attention() msg = self._indicator_hdl.prepare_targetnotfound_handling() assert self._targetnotfound_dialog is None self._targetnotfound_dialog = misc.msgdialog_standalone( message_str="", msgtype=Gtk.MessageType.ERROR, boxtitle=Infos.NAME, buttons=Gtk.ButtonsType.NONE, sticky=True) self._targetnotfound_dialog.add_buttons(Gtk.STOCK_CANCEL, Gtk.RESPONSE_CANCEL, _("Try again"), Gtk.RESPONSE_OK) _ttimer = GObject.timeout_add_seconds( constants.TIMEOUT_RETRY_TARGET_CHECK_SECONDS, self._targetnotfound_dialog_destroy) _ctimer = GObject.timeout_add_seconds(constants.ONE_SECOND, self._targetnotfound_timer, msg, constants.ONE_SECOND) msg = msg % self._indicator_hdl.get_targetnotfound_clock() self._targetnotfound_dialog.set_markup(msg) self._add_dialog_to_showlist(dialog=self._targetnotfound_dialog) result = self._targetnotfound_dialog.run() self._targetnotfound_dialog.destroy() self._remove_dialog_from_showlist(dialog=self._targetnotfound_dialog) self._targetnotfound_dialog = None if result == Gtk.RESPONSE_OK: retry = constants.RETRY_TRUE elif result == Gtk.RESPONSE_NONE: retry = constants.RETRY_TRUE else: retry = constants.RETRY_FALSE GObject.source_remove(_ttimer) GObject.source_remove(_ctimer) self._indicator_hdl.finish_targetnotfound_handling(retry) self.set_status_to_normal()
def refresh(self): uptodateText = _("Your system is up to date") updavText = _("There are updates available") noConText = _("No internet connection") errText = _("Unable to retrieve sources information") self.counter += 1 print(("UmRefresh refresh count #: %d" % self.counter)) self.statusIcon.set_from_pixbuf(self.pbExec) self.statusIcon.set_tooltip_text(_("Refreshing...")) if not self.umglobal.isSrciptRunning("updatemanager.py"): for fle in glob(join(self.scriptDir, "files/.um*")): remove(fle) self.umglobal.getLocalInfo() if self.umglobal.repos: if self.counter > 1: self.umglobal.getServerInfo() if self.umglobal.hasInternet: # Check update status if self.checkForUpdates(): if self.umglobal.newUpd: self.statusIcon.set_from_pixbuf(self.pbInfo) self.statusIcon.set_tooltip_text( _("New update: %s" % self.umglobal.serverUpdVersion)) else: self.statusIcon.set_from_pixbuf(self.pbInfo) self.statusIcon.set_tooltip_text(updavText) else: self.statusIcon.set_from_pixbuf(self.pbApply) self.statusIcon.set_tooltip_text(uptodateText) else: self.statusIcon.set_from_pixbuf(self.pbDisconnected) self.statusIcon.set_tooltip_text(noConText) # Check every 60 seconds if there is a connection GObject.timeout_add_seconds(60, self.refresh) return True else: self.statusIcon.set_from_pixbuf(self.pbError) self.statusIcon.set_tooltip_text(errText) print("Done refreshing")
def refresh(self): # Don't refresh if the apt cache is being refreshed if not self.isAptExecuting(): if not self.umglobal.isProcessRunning("updatemanager.py"): for fle in glob(join(self.umglobal.filesDir, ".um*")): remove(fle) self.umglobal.getLocalInfo() if self.umglobal.repos: if self.umglobal.hasInternet: # Check update status if self.checkForUpdates(): if self.umglobal.newUpd: self.umglobal.updatesText = _( "New update: %s" % self.umglobal.serverUpdVersion) print((self.umglobal.updatesText)) self.changeIcon("icon-updates", self.umglobal.updatesText) else: self.umglobal.updatesText = _( "There are updates available") print((self.umglobal.updatesText)) self.changeIcon("icon-updates", self.umglobal.updatesText) else: print((self.umglobal.connectedText)) self.changeIcon("icon-connected", self.umglobal.connectedText) else: print((self.umglobal.disconnectedText)) self.changeIcon("icon-disconnected", self.umglobal.disconnectedText) # Check every 30 seconds if there is a connection GObject.timeout_add_seconds(30, self.refresh) self.umglobal.getServerInfo() return True else: self.umglobal.errorText = _( "Unable to retrieve sources information") print((self.umglobal.errorText)) self.changeIcon("icon-error", self.umglobal.errorText) print("Done refreshing")
def __set_schedule(self): """Schedule our own "save" events (we won't see any from gEdit since we're not named). """ wait_s = self.__run_interval_s * 60 self.__debug("Scheduling save for (%d) second intervals." % (wait_s)) i = GObject.timeout_add_seconds(wait_s, self.__store_unsaved_cb) self.__save_timer_id = i
def run_subprocess(self): if self.state == STATE_RUNNING: return self.set_state(STATE_RUNNING) cmd_check = 'pgrep chef-client' self.log('Checking for an already running chef-client instance...') args = shlex.split(cmd_check) while True: if subprocess.Popen(args) == 0: time.sleep(1) else: break cmd = '/usr/bin/env chef-client' self.log('Calling subprocess: ' + cmd) args = shlex.split(cmd) self.process = subprocess.Popen(args) GObject.timeout_add_seconds(1, self.check_state)
def notify_launch(self, activity_id, service_name): registry = get_registry() activity_info = registry.get_bundle(service_name) if not activity_info: raise ValueError("Activity service name '%s'" " was not found in the bundle registry." % service_name) color = self._shared_activities.get(activity_id, None) home_activity = Activity(activity_info, activity_id, color) self._add_activity(home_activity) self._set_active_activity(home_activity) self.emit('launch-started', home_activity) # FIXME: better learn about finishing processes by receiving a signal. # Now just check whether an activity has a window after ~90sec GObject.timeout_add_seconds(90, self._check_activity_launched, activity_id)
def _start_probing(self): self.__watchdog_id = None self.__probe_id = None self.__watchdog_notice = False self.__pid = 0 self.__frozen = False self.__main = self.__output = self.__controls = None if not self.__shutdown: self.__probe_id = GObject.timeout_add_seconds( 2, self._idjc_started_probe)
def __init__(self): Gtk.Window.__init__(self, title="PiHole Panel") grid = Gtk.Grid(margin=4) grid.set_column_homogeneous(True) self.add(grid) self.grid = grid # Create the various elements of the window self.status_label, self.status_button = self.draw_status_elements() self.statistics_frame = self.draw_statistics_frame() self.top_queries_frame = self.draw_top_queries_frame() self.top_ads_frame = self.draw_top_ads_frame() self.fetch_data_and_update_display() # Initial data fetch-and-display # Create a timer --> self.on_timer will be called periodically GObject.timeout_add_seconds(update_interval_seconds, self.on_timer)
def test_queries_while_import(self): assert os.path.isdir(cfg.generated_ttl_dir()) for root, dirs, files in os.walk(cfg.generated_ttl_dir()): for ttl_file in filter(lambda f: f.endswith(".ttl"), files): full_path = os.path.abspath(os.path.join(root, ttl_file)) self.files_counter += 1 self.tracker.load("file://" + full_path, timeout=30000, result_handler=self.loaded_success_cb, error_handler=self.loaded_failed_cb, user_data=full_path) GObject.timeout_add_seconds(2, self.run_a_query) # Safeguard of 60 seconds. The last reply should quit the loop # It doesn't matter if we didn't import all of the files yet. GObject.timeout_add_seconds(60, self.timeout_cb) self.main_loop.run()
def scan(self, timeout=10): """Scan for BT devices visible to all adapters.'""" self._bus.add_signal_receiver( interfaces_added, dbus_interface="org.freedesktop.DBus.ObjectManager", signal_name="InterfacesAdded") self._bus.add_signal_receiver( properties_changed, dbus_interface="org.freedesktop.DBus.Properties", signal_name="PropertiesChanged", arg0="org.bluez.Device1", path_keyword="path") for adapter in self._get_objects_by_iface(ADAPTER_IFACE): try: dbus.Interface(adapter, ADAPTER_IFACE).StopDiscovery() except dbus.exceptions.DBusException: pass dbus.Interface(adapter, ADAPTER_IFACE).StartDiscovery() GObject.timeout_add_seconds(timeout, self._scan_timeout) self._main_loop.run()
def play(self): if self.game.is_finished(): return False # "Jugando automatico" if self.game.start is None: # si no hay ninguna pieza en el tablero ponemos la primera piece = self._pieces[0] n, p = self.game.cantX / 2 - 1, self.game.cantY / 2 self.game.put_piece(self, piece, n, p) # seteamos comienzo y fin del domino startTile = Tile(n, p) startTile.value = piece.a startTile.direction = Tile.LEFT self.game.start = startTile endTile = Tile(n + 1, p) endTile.value = piece.b endTile.direction = Tile.RIGHT self.game.end = endTile else: # "automatica siguiente" # buscamos si tenemos alguna ficha que corresponda # en el comienzo if not self.check_put_piece(): # pido una hasta que sea valida o no hayan mas disponibles # si no encontramos pedimos hasta que alguna sirva # "Pido pieza" if self.game.request_one_piece(self): if self.game.ENABLE_AUTO_MODE: GObject.timeout_add(300, self.play) else: GObject.timeout_add_seconds(1, self.play) return False else: self.has_passed = True # juega el siguiente jugador GObject.idle_add(self.end_play) return False
def autoconnect(self): """Start a timer which basically looks for 30 seconds of inactivity on the device, then does autoconnect to an Ad-hoc network. This function may be called early on (e.g. when the device is still in NM_DEVICE_STATE_UNMANAGED). It is assumed that initialisation will complete quickly, and long before the timeout ticks. """ if self._idle_source != 0: GObject.source_remove(self._idle_source) self._idle_source = GObject.timeout_add_seconds( self._AUTOCONNECT_TIMEOUT, self.__idle_check_cb)
def __init__(self): Gtk.HBox.__init__(self, False, 1) imagenes = [ Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image(), Gtk.Image() ] cantidad = 0 for x in imagenes: self.add(x) self.show_all() GObject.timeout_add_seconds(1, self.actualizar, imagenes, cantidad)
def create_timer(self, mp): """Creates a timer for a future mediapackage recording if there are less than 30 minutes to the scheduled event. Args: mp (Mediapackage): the mediapackage whose timer is going to be created. """ diff = (mp.getDate() - datetime.datetime.utcnow()) if diff < datetime.timedelta(minutes=30) and mp.getIdentifier() != self.mp_rec and not self.start_timers.has_key(mp.getIdentifier()): self.logger.info('Create timer for MP {}, it starts at {}'.format(mp.getIdentifier(), mp.getStartDateAsString())) self.dispatcher.emit('recorder-scheduled-event', mp.getIdentifier()) timeout_id = GObject.timeout_add_seconds(diff.seconds, self.__start_record, mp.getIdentifier()) self.start_timers[mp.getIdentifier()] = timeout_id
def __slideshow_timeout_cb(self, *args): if self._current_box + 1 > len(self._boxes) - 1: return False self._current_box += 1 self._area.queue_draw() box = self._boxes[self._current_box] duration = box.slideshow_duration self._timeout_id = \ GObject.timeout_add_seconds(duration, self.__slideshow_timeout_cb) return False
def time_changed(self): refresh_hour, refresh_mins = self.get_configuration() now = datetime.datetime.now() refresh_time = datetime.datetime(now.year, now.month, now.day, int(refresh_hour), int(refresh_mins), 0) secs_to_refresh = self.seconds_until(refresh_time) if self.timeout_source: GObject.source_remove(self.timeout_source) self.timeout_source = GObject.timeout_add_seconds( secs_to_refresh, self.emit_refresh)
def __init__(self): filename = "popup.glade" self.builder = Gtk.Builder() self.builder.add_from_file(filename) self.builder.connect_signals(self) self.window = self.builder.get_object("window1") self.title = self.builder.get_object("lblTitle") self.message = self.builder.get_object("lblMessage") self.titleBox = self.builder.get_object("labelbox") self.titleBox.connect("button-release-event", self.on_clicked) self.exit = self.builder.get_object("exitbox") self.exit.connect("button-release-event", self.close_notify) self.icon = self.builder.get_object("imgIcon") self.window.set_gravity(gdk.Gravity.NORTH_WEST) self.display = False self.window.set_keep_above(True) color = gdk.color_parse('#F7A900') for wid in [self.window, self.exit, self.titleBox]: wid.modify_bg(Gtk.StateFlags.NORMAL, color) self.counter = 0 self.counter2 = 0 self.counting = False self.queue = [] gobject.timeout_add_seconds(1, self.timer) gobject.timeout_add_seconds(0.2, self.display_notify) gobject.timeout_add_seconds(30, self.message_system) while gtk.events_pending(): gtk.main_iteration_do(True) self.message_system()
def start(self, use_timings): if not use_timings: self._prev_icon.show() self._next_icon.show() return self._prev_icon.hide() self._next_icon.hide() box = self._boxes[self._current_box] duration = box.slideshow_duration self._timeout_id = \ GObject.timeout_add_seconds(duration, self.__slideshow_timeout_cb)
def __check_capacity(self): if self._state != UPowerGlib.DeviceState.DISCHARGING: return if self._level > self.warning_capacity: return if self._level > self._minimum_capacity: logging.error('battery under warning, %d%%' % self._level) return elapsed = time.time() - self._grace if elapsed < self._grace_time: logging.error('battery under minimum, %d%%, grace %d%%' % (self._level, elapsed * 100 / self._grace)) return logging.error('battery under minimum, %d%%, forced shutdown' % self._level) sm = get_session_manager() sm.shutdown() GObject.timeout_add_seconds(10, sm.shutdown_completed)
def __init__(self, **properties): super().__init__(**properties) self.pool_warned = False self.vms_warned = set() self.qubes_app = Qubes() self.set_application_id("org.qubes.qui.tray.DiskSpace") self.register() prefs_action = Gio.SimpleAction.new("prefs", GLib.VariantType.new("s")) prefs_action.connect("activate", launch_preferences_dialog) self.add_action(prefs_action) self.icon = Gtk.StatusIcon() self.icon.connect('button-press-event', self.make_menu) self.refresh_icon() GObject.timeout_add_seconds(120, self.refresh_icon) Gtk.main()