def update_text(self): markup = "" recent = False for i, key in enumerate(self.data): if i != 0: last = self.data[i - 1] if len(key.repl) > 1 or len(last.repl) > 1: markup += ' ' elif key.bk_stop or last.bk_stop: markup += '<span font_family="sans">\u2009</span>' if not recent and (datetime.now() - key.stamp).total_seconds() < self.recent_thr: recent = True markup += '<u>' escaped_key_repl = glib.markup_escape_text(key.repl) self.logger.debug("escaped_key_repl is: " + key.repl) codepoints = map(ord, key.repl) self.logger.debug("codepoints are: " + str(codepoints)) # for some reason, in my system it screws formatting when running # this, so yeah, quick dirty hack to make it work if codepoints == [65107]: escaped_key_repl = '~' elif codepoints == [65106]: escaped_key_repl = '^' markup += '\u200c' + escaped_key_repl if recent: markup += '</u>' self.logger.debug("Label updated: %s." % markup) glib.idle_add(lambda: self.listener(markup))
def __init__(self): '''class constructor''' self.window = None self.tray_icon = None self.conversations = [] self.single_instance = None self.config = e3.common.Config() self.config_dir = e3.common.ConfigDir('emesene2') self.config_path = self.config_dir.join('config') self.config.load(self.config_path) if self.config.d_accounts is None: self.config.d_accounts = {} if self.config.d_remembers is None: self.config.d_remembers = {} self.session = None self.logged_in = False self.timeout_id = None self.cur_service = None self._parse_commandline() self._setup() signal.signal(signal.SIGINT, lambda *args: glib.idle_add(self.close_session())) signal.signal(signal.SIGTERM, lambda *args: glib.idle_add(self.close_session()))
def __init__(self, snapshots = None): self.xml = gtk.glade.XML("%s/../../glade/time-slider-delete.glade" \ % (os.path.dirname(__file__))) self.backuptodelete = [] self.shortcircuit = [] maindialog = self.xml.get_widget("time-slider-delete") self.pulsedialog = self.xml.get_widget("pulsedialog") self.pulsedialog.set_transient_for(maindialog) self.datasets = zfs.Datasets() if snapshots: maindialog.hide() self.shortcircuit = snapshots else: glib.idle_add(self.__init_scan) self.progressdialog = self.xml.get_widget("deletingdialog") self.progressdialog.set_transient_for(maindialog) self.progressbar = self.xml.get_widget("deletingprogress") # signal dictionary dic = {"on_closebutton_clicked" : gtk.main_quit, "on_window_delete_event" : gtk.main_quit, "on_snapshotmanager_delete_event" : gtk.main_quit, "on_fsfilterentry_changed" : self.__on_filterentry_changed, "on_schedfilterentry_changed" : self.__on_filterentry_changed, "on_typefiltercombo_changed" : self.__on_filterentry_changed, "on_selectbutton_clicked" : self.__on_selectbutton_clicked, "on_deselectbutton_clicked" : self.__on_deselectbutton_clicked, "on_deletebutton_clicked" : self.__on_deletebutton_clicked, "on_confirmcancel_clicked" : self.__on_confirmcancel_clicked, "on_confirmdelete_clicked" : self.__on_confirmdelete_clicked, "on_errordialog_response" : self.__on_errordialog_response} self.xml.signal_autoconnect(dic)
def execute(self, async_conn): """Executes a query within an asyncronous psycopg2 connection """ if self.status == self.STATUS_CANCELLED: return self.status = self.STATUS_EXECUTING # Async variant of Connection.execute() in storm/database.py state = State() statement = compile(self.expr, state) stmt = convert_param_marks(statement, "?", "%s") self._async_cursor = async_conn.cursor() self._async_conn = async_conn # This is postgres specific, see storm/databases/postgres.py self._statement = stmt.encode('utf-8') self._parameters = tuple(Connection.to_database(state.parameters)) trace("connection_raw_execute", self._conn, self._async_cursor, self._statement, self._parameters) self._async_cursor.execute(self._statement, self._parameters) # This can happen if another thread cancelled this while the cursor was # executing. In that case, it is not interested in the retval anymore if self.status == self.STATUS_CANCELLED: return self.status = self.STATUS_FINISHED glib.idle_add(self._on_finish)
def exposeBegin(self, imageRequest): startTime = time.time() timeout = startTime + self.exptime self.currentFrame += 1 def ui(): self.exposureLabel.set_label( "<b>%-2d/%-2d</b>" % (self.currentFrame, self.frames)) self.exposureProgress.set_fraction(0.0) def exposeTimer(startTime, timeout): now = time.time() if now >= timeout: return False counter = now - startTime self.exposureProgress.set_fraction(counter / self.exptime) self.exposureProgress.set_text( "%.2f" % (self.exptime - counter)) return True self.exposeTimer = glib.timeout_add( 100, exposeTimer, startTime, timeout) glib.idle_add(ui)
def _button_press(self, _wid, ev): cursor = self.get_cursor() if cursor is not None: cursor, _renderer = cursor assert len(cursor) == 1 old = cursor[0] else: old = None new = self.get_path_at_pos(int(ev.x), int(ev.y)) if new is not None: assert len(new) == 1 new = new[0] if new is not None: self.set_cursor((new,)) if old is not None and (ev.state & gtk.gdk.SHIFT_MASK): self._change_selection(old, new) elif ev.state & gtk.gdk.CONTROL_MASK: if self.path_is_selected((new,)): self.unselect_path((new,)) else: self.select_path((new,)) self._selection_anchor = new else: if not self.path_is_selected((new,)): self.unselect_all() self.select_path((new,)) self._selection_anchor = new # We need to let the default handler run to prepare for a possible # drag, but then we need to fix up its selection breakage afterward. glib.idle_add(self._button_press_fixup, self.get_selected_items(), priority=glib.PRIORITY_HIGH) return False
def on_option_set(self, event, settings, option): """ Reflects external volume changes """ if option == 'player/volume': glib.idle_add(self.set_value, float(settings.get_option(option)))
def send_chat(self, text): """Send a chat message over the network""" if text == "": return # don't send an empty message if text[0] == '[' or text[0] == '\\': text = '\\' + text glib.idle_add(self.send_message, text)
def _delete_cb(self, widget): """Properties dialog delete callback""" self._dialog.hide() name = brushmanager.translate_group_name(self._group) msg = C_( "brush group delete", u"Really delete group \u201C{group_name}\u201D?", ).format( group_name = name, ) bm = self._app.brushmanager if not dialogs.confirm(self, msg): return bm.delete_group(self._group) if self._group not in bm.groups: remover = lambda t, q: ( self._app.workspace.remove_tool_widget(t, q) or False ) glib.idle_add(remover, self.__gtype_name__, (self._group,)) return # Special groups like "Deleted" cannot be deleted, # but the error message is very confusing in that case... msg = C_( "brush group delete", u"Could not delete group \u201C{group_name}\u201D.\n" u"Some special groups cannot be deleted.", ).format( group_name = name, ) dialogs.error(self, msg)
def add_device_panel(self, type, obj, device): from xl.collection import CollectionScanThread from xlgui.panel.device import DevicePanel, FlatPlaylistDevicePanel import xlgui.panel paneltype = DevicePanel if hasattr(device, 'panel_type'): if device.panel_type == 'flatplaylist': paneltype = FlatPlaylistDevicePanel elif issubclass(device.panel_type, xlgui.panel.Panel): paneltype = device.panel_type panel = paneltype(self.main.window, self.main, device, device.get_name()) sort = True panel.connect('append-items', lambda panel, items, sort=sort: self.main.on_append_items(items, sort=sort)) panel.connect('queue-items', lambda panel, items, sort=sort: self.main.on_append_items(items, queue=True, sort=sort)) panel.connect('replace-items', lambda panel, items, sort=sort: self.main.on_append_items(items, replace=True, sort=sort)) self.device_panels[device.get_name()] = panel glib.idle_add(self.add_panel, *panel.get_panel()) thread = CollectionScanThread(device.get_collection()) thread.connect('done', panel.load_tree) self.progress_manager.add_monitor(thread, _("Scanning %s..." % device.name), gtk.STOCK_REFRESH)
def race_info_time_edit_activate_cb(self, button): """Display race timing edit dialog.""" ostx = '' oftx = '' if self.start is not None: ostx = self.start.rawtime(4) if self.finish is not None: oftx = self.finish.rawtime(4) (ret, stxt, ftxt) = uiutil.edit_times_dlg(self.meet.window, ostx, oftx) if ret == 1: try: stod = None if stxt: stod = tod.tod(stxt, 'MANU', 'C0i') self.meet.timer.printline(' ' + str(stod)) ftod = None if ftxt: ftod = tod.tod(ftxt, 'MANU', 'C1i') self.meet.timer.printline(' ' + str(ftod)) self.set_start(stod) self.set_finish(ftod) self.set_elapsed() if self.start is not None and self.finish is not None: self.log_elapsed() self.log.info('Updated race times.') except (decimal.InvalidOperation, ValueError), v: self.log.error('Error updating times: ' + str(v)) glib.idle_add(self.delayed_announce)
def toggle_package(self, path, model, image=False): inc = model[path][self.model.COL_INC] # Warn user before removing included packages if inc: pn = model[path][self.model.COL_NAME] revdeps = self.model.find_reverse_depends(pn) if len(revdeps): lbl = "<b>Remove %s?</b>\n\nThis action cannot be undone and all packages which depend on this will be removed\nPackages which depend on %s include %s." % (pn, pn, ", ".join(revdeps).rstrip(",")) else: lbl = "<b>Remove %s?</b>\n\nThis action cannot be undone." % pn dialog = CrumbsDialog(self, lbl, gtk.STOCK_DIALOG_WARNING) dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL) dialog.add_button("Remove", gtk.RESPONSE_OK) response = dialog.run() dialog.destroy() if response == gtk.RESPONSE_CANCEL: return self.set_busy_cursor() # Convert path to path in original model opath = model.convert_path_to_child_path(path) # This is a potentially length call which can block the # main loop, therefore do the work in an idle func to keep # the UI responsive glib.idle_add(self.toggle_package_idle_cb, opath, image) self.dirty = True
def on_table_progress(self): script_dir = sys.path[0] save_path = os.path.join(script_dir, 'gxtubes') myfile='%s/%s.cc' % (save_path,self.tube.get_active_text()) self.progressbar.show() if self.progressbar.get_fraction() >= 1.0: value = 0.0 else: value = self.progressbar.get_fraction() + 0.1 self.progressbar.set_fraction(value) if os.path.isfile(myfile): sleep(1) infile = open(myfile, "r") if infile: self.sw.set_size_request (-1, 480) textbuffer = self.textview.get_buffer() string = infile.read() infile.close() textbuffer.set_text(string) self.image.hide() self.textview.show() glib.idle_add(self.on_plot_finish) self.progressbar.hide() return False return True
def run(self): # Update widget in main thread try: if self.pageContent: # Loop through all pages lastIndex = len(self.pageContent) - 1 runLoop = True i = 0 while runLoop: # Get the full path of the content page if os.path.isfile(self.pageContent[i][0]): #print 'Load page: ' + self.pageContent[i][0] # Load html into browser object # Use glib to schedule an update of the parent browser object # If you do this directly the objects won't refresh glib.idle_add(self.browser.load_html_string, self.pageContent[i][1], 'file:///') # Wait interval time.sleep(self.interval) # Reset counter when you need to loop the pages if i == lastIndex: if self.loop: i = 0 else: runLoop = False else: i = i + 1 else: # You can only get here if you delete a file while in the loop print 'Page not found: ' + self.pageContent[i][0] else: print 'No pages found to load' except Exception, detail: print detail
def image_combo_changed_cb(self, combo): self.builder.window_sensitive(False) selected_image = self.image_combo.get_active_text() if not selected_image or (selected_image == self.__dummy_image__): return # remove __dummy_image__ item from the store list after first user selection # because it is no longer valid combo_store = combo.get_model() if len(combo_store) and (combo_store[0][0] == self.__dummy_image__): combo.remove_text(0) self.builder.customized = False selected_recipes = [] image_path = self.builder.recipe_model.pn_path[selected_image] image_iter = self.builder.recipe_model.get_iter(image_path) selected_packages = self.builder.recipe_model.get_value(image_iter, self.builder.recipe_model.COL_INSTALL).split() self.update_image_desc() self.builder.recipe_model.reset() self.builder.package_model.reset() self.show_baseimg_selected() if selected_image == self.builder.recipe_model.__custom_image__: self.just_bake_button.hide() glib.idle_add(self.image_combo_changed_idle_cb, selected_image, selected_recipes, selected_packages)
def machine_combo_changed_cb(self, machine_combo): self.builder.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.WATCH)) self.builder.wait(0.1) #wait for combo and cursor to update self.stopping = False self.builder.parsing_warnings = [] combo_item = machine_combo.get_active_text() if not combo_item or combo_item == self.__dummy_machine__: return # remove __dummy_machine__ item from the store list after first user selection # because it is no longer valid combo_store = machine_combo.get_model() if len(combo_store) and (combo_store[0][0] == self.__dummy_machine__): machine_combo.remove_text(0) self.builder.configuration.curr_mach = combo_item if self.machine_combo_changed_by_manual: self.builder.configuration.clear_selection() # reset machine_combo_changed_by_manual self.machine_combo_changed_by_manual = True self.builder.configuration.selected_image = None # Do reparse recipes self.builder.populate_recipe_package_info_async() glib.idle_add(self.machine_combo_changed_idle_cb)
def on_option_set(self, event, settings, option): """ Updates appearance on setting change """ if option == 'plugin/osd/format': self.info_area.set_info_format(settings.get_option(option, _('<span font_desc="Sans 11" foreground="#fff"><b>$title</b></span>\n' 'by $artist\n' 'from $album') )) if option == 'plugin/osd/background': self.__options['background'] = alphacolor_parse(settings.get_option(option, '#333333cc')) glib.idle_add(self.queue_draw) elif option == 'plugin/osd/display_duration': self.__options['display_duration'] = int(settings.get_option(option, 4)) elif option == 'plugin/osd/show_progress': self.info_area.set_display_progress(settings.get_option(option, True)) elif option == 'plugin/osd/position': position = Point._make(settings.get_option(option, [20, 20])) glib.idle_add(self.move, position.x, position.y) elif option == 'plugin/osd/border_radius': value = settings.get_option(option, 10) self.set_border_width(max(6, int(value / 2))) self.__options['border_radius'] = value self.emit('size-allocate', self.get_allocation())
def start(self, e): # self.skip is a list of paths user wishes to not copy/check buffer_content = self.textbuffer.get_text(self.textbuffer.get_start_iter(), self.textbuffer.get_end_iter()) self.skip = buffer_content.split("\n") # Paths cannot end with / for index, element in enumerate(self.skip): if element: if element[-1] == '/': self.skip[index] = element[:-1] self.p.set_text('Scanning...') # each waker is in format ( path, [dirs] [files] ) self.src_walker = os.walk(self.src_dir_dialog.get_current_folder()) self.dst_walker = os.walk(self.dst_dir_dialog.get_current_folder()) print print self.src_dir_dialog.get_uri() print self.dst_dir_dialog.get_current_folder(); print # bug - if it's not a device (hdd, /), it returns home dir import sys sys.exit() glib.idle_add(self.scan)
def __init__(self): """class constructor""" self.window = None self.tray_icon = None self.conversations = [] self.minimize = False self.single_instance = None self.config = e3.common.Config() self.config_dir = e3.common.ConfigDir("emesene2") self.config_path = self.config_dir.join("config") self.config.load(self.config_path) if self.config.d_accounts is None: self.config.d_accounts = {} if self.config.d_remembers is None: self.config.d_remembers = {} self.session = None self.logged_in = False self.timeout_id = None self.cur_service = None self.notification = None self.conv_manager_available = False self.last_session_account = None self.last_session_service = None self._parse_commandline() self._setup() signal.signal(signal.SIGINT, lambda *args: glib.idle_add(self.close_session())) signal.signal(signal.SIGTERM, lambda *args: glib.idle_add(self.close_session()))
def main(): target = sys.argv[1] opts = make_defaults_struct() MAX_CLIENTS = 10 clients = [] def start_try(): sock = socket.socket(socket.AF_UNIX) sock.connect(target) conn = SocketConnection(sock, sock.getsockname(), sock.getpeername(), target, "trylogin") def stop_cb(client): try: clients.remove(client) except: pass if len(clients)<MAX_CLIENTS: start_try() def cracked_cb(password): sys.exit(0) tl = TryLogin(conn, opts, gen_password(), stop_cb, cracked_cb) clients.append(tl) tl.run() for _ in range(MAX_CLIENTS): glib.idle_add(start_try) glib_mainloop = glib.MainLoop() glib_mainloop.run()
def set_from_np(self, img): '''Sets the contents of the image from a numpy array''' if img is None: w, h = self._fixed_size cv2.rectangle(self.buffer, (0,0), (w, h), (0,0,0,0)) else: # if resize needed, then do it h, w, c = img.shape if w != self._fixed_size[0] or h != self._fixed_size[1]: self.zoom = float(w) / self._fixed_size[0] cv2.resize(img, self._fixed_size, self.resize_buffer) src = self.resize_buffer else: self.zoom = 1 src = img # now copy it to the buffer and convert to the right format if c == 1: cv2.cvtColor(src, cv2.COLOR_GRAY2BGRA, self.buffer) else: cv2.cvtColor(src, cv2.COLOR_BGR2BGRA, self.buffer) # .. and invalidate? Make sure to use idle_add to dispatch it on the UI # thread, otherwise you will get random crashes glib.idle_add(self.queue_draw)
def execute_to_gtk(gen): """ Execute the given generator until it requests to switch to the GTK thread. Returns a generator to be run from the GTK thread or None if not required. """ # Flag indicating if the adjustment value has been set (and thus the # adjustment will need setting on completion) adjustment_set = False while gen is not None: gen, progress = self.generator_step(gen) if progress is None: # Requested to continue in GTK thread or the function crashed break else: # Progress update value, max_value = progress adjustment_set = True glib.idle_add(self.update_adjustment, adjustment, value, max_value) # Clear/Reset the adjustment if it was set if adjustment_set: glib.idle_add(self.update_adjustment, adjustment, 0, 0) return gen
def set_cover_from_track(self, track): """ Updates the cover image and triggers cross-fading """ cover_data = covers.MANAGER.get_cover(track, set_only=True) if cover_data is None: self.hide() return if not self.props.visible: self.show() size = settings.get_option('plugin/desktopcover/size', 200) upscale = settings.get_option('plugin/desktopcover/override_size', False) pixbuf = self.image.get_pixbuf() next_pixbuf = icons.MANAGER.pixbuf_from_data( cover_data, size=(size, size), upscale=upscale) fading = settings.get_option('plugin/desktopcover/fading', False) if fading and pixbuf is not None and self._cross_fade_id is None: # Prescale to allow for proper crossfading width, height = next_pixbuf.get_width(), next_pixbuf.get_height() pixbuf = pixbuf.scale_simple(width, height, gtk.gdk.INTERP_BILINEAR) glib.idle_add(self.image.set_from_pixbuf, pixbuf) duration = settings.get_option( 'plugin/desktopcover/fading_duration', 50) self._cross_fade_id = glib.timeout_add(int(duration), self.cross_fade, pixbuf, next_pixbuf, duration) else: glib.idle_add(self.image.set_from_pixbuf, next_pixbuf)
def quit(self, *e): """ Quits Exaile """ self.window.hide() glib.idle_add(self.controller.exaile.quit) return True
def run(self): me = self.schema.getMySelf() fsrv = self.schema.getFileSrv(False) fsrvstr = "%s:%s" % (fsrv[COL_HOST], fsrv[COL_IP]) others = self.schema.servers[:] others.remove(me) srvlst = ["%s:%s" % (srv[COL_HOST],srv[COL_IP]) for srv in others] curdir = os.path.abspath(os.curdir) absscript = "/bin/bash \"%s/cluster.sh\"" % curdir if me[COL_COMBO_KEY] == 'filesrv': cmd = "%s -m filesvr -d %s -s %s" % (absscript, me[COL_PATH], ','.join(srvlst)) self.__exec(cmd) elif me[COL_COMBO_KEY] == 'master': if me is fsrv: cmd = "%s -m filesvr -d %s -s %s" % (absscript, me[COL_PATH], ','.join(srvlst)) self.__exec(cmd) else: cmd = "%s -m backbone -d %s -s %s" % (absscript, me[COL_PATH], fsrvstr) self.__execWithPswd(cmd) elif me[COL_COMBO_KEY] == 'slave': mstr = self.schema.getMasterSrv() cmd = "%s -m slave -d %s -s %s -b %s" % (absscript, me[COL_PATH], fsrvstr, mstr[COL_IP]) self.__execWithPswd(cmd) else: pass glib.idle_add(self.pwin.spinner.destroy)
def main(): mainloop = glib.MainLoop() def cb(): test_clipboard() mainloop.quit() glib.idle_add(cb) mainloop.run()
def add_prompt_later(): global prompt_needed prompt_needed = True # add in idle loop so that we first process all queued signals glib.idle_add(add_prompt)
def set_location(self, width=0, height=0, posx=None, posy=None, single_window=False): """place the window on the given coordinates """ if single_window: w, h = self.get_size() def this_is_an_hax(*args): # Really, it is! And an ugly one! if self.is_maximized(): self.box.set_position(w-width) else: self.resize(self.set_or_get_width(width+w), self.set_or_get_height(height)) self.box.set_position(w) return False glib.idle_add(this_is_an_hax) else: self.set_default_size(self.set_or_get_width(width), self.set_or_get_height(height)) #if window isn't visible center on screen screen = self.get_screen() pwidth, pheight = screen.get_width(), screen.get_height() if posx > pwidth: posx = (pwidth - width) // 2 if posy > pheight: posy = (pheight - height) // 2 self.move(self.set_or_get_posx(posx), self.set_or_get_posy(posy))
def _shutdown_dialog_callback(dialog, response_id): dialog.destroy() if response_id == gtk.RESPONSE_CLOSE:# "Don't Save" pass elif response_id == gtk.RESPONSE_YES:# "Save" if editorstate.PROJECT().last_save_path != None: persistance.save_project(editorstate.PROJECT(), editorstate.PROJECT().last_save_path) else: dialogutils.warning_message(_("Project has not been saved previously"), _("Save project with File -> Save As before closing."), gui.editor_window.window) return else: # "Cancel" return # --- APP SHUT DOWN --- # print "Exiting app..." # No more auto saving stop_autosave() # Save window dimensions on exit x, y, w, h = gui.editor_window.window.get_allocation() editorpersistance.prefs.exit_allocation = (w, h) editorpersistance.prefs.app_v_paned_position = gui.editor_window.app_v_paned.get_position() editorpersistance.prefs.top_paned_position = gui.editor_window.top_paned.get_position() editorpersistance.prefs.mm_paned_position = gui.editor_window.mm_paned.get_position() editorpersistance.save() # Block reconnecting consumer before setting window not visible updater.player_refresh_enabled = False gui.editor_window.window.set_visible(False) # Close and destroy app when gtk finds time to do it after hiding window glib.idle_add(_app_destroy)
def on_mark_set(self, sb, it, mark): if mark is sb.get_insert(): if (it.compare(sb.get_iter_at_mark(self.start_mark)) < 0 or it.compare(sb.get_iter_at_mark(self.end_mark)) > 0): self.hide() else: idle_add(self.place_window)
def tray_click(button, pressed, time=0): log.info("tray_click(%s, %s, %s)", button, pressed, time) if button == 1 and pressed: glib.idle_add(tray.activate, button, time) elif button == 3 and not pressed: glib.idle_add(tray.popup, button, time)
def close_titler(): global _titler, _titler_data _titler.set_visible(False) glib.idle_add(titler_destroy)
def os_signal(signum, _frame): glib.idle_add(handle_signal, signum)
view.set_cursor(cursor) else: view.set_cursor(0) if view.flags() & gtk.REALIZED: view.scroll_to_point(0, 0) self.entry.set_text(directory.get_parse_name()) if history: self.back.set_sensitive(True) self.history = self.history[:self.i + 1] self.history.append(self.current) self.i = len(self.history) - 1 self.forward.set_sensitive(False) self.up.set_sensitive(bool(directory.get_parent())) glib.idle_add(idle) def drag_data_received(self, *e): """ stub """ pass def drag_data_delete(self, *e): """ stub """ pass def drag_get_data(self, treeview, context, selection, target_id, etime): """
def __select_path(self, path): self.get_selection().select_path(path) glib.idle_add(self.scroll_to_cell, path) self.set_cursor_on_cell(path)
def on_option_set(self, typ, obj, data): if data in ("gui/resizable_cols", self.settings_width_name): glib.idle_add(self._setup_sizing)
def run(self): '''convert Event object on the queue to gui.Signal''' while not self._stop: event = self.event_queue.get() glib.idle_add(self.process, event)
def on_option_set(self, event, settings, option): """ Updates the internal format on setting change """ if option == 'gui/progress_bar_text_format': glib.idle_add(self.set_property, 'format', self.get_option_value())
def on_queue_tracks_removed(self, event, queue, tracks): """ Updates the list on queue changes """ glib.idle_add(self.remove_tracks, tracks)
def apply(self, value=None): return_value = widgets.ScalePreference.apply(self, value) glib.idle_add(self.preferences.parent.queue_draw) return return_value
def __load(self): def load_station_details(station): response, content = self.__fetch(station.uri) if 200 == response.status: pattern = re.compile(r'href="([^"]+\.pls)"') for uri in pattern.findall(content): if uri.startswith('/'): uri = urljoin(station.uri, uri) if station.accept_stream(uri): pending_channels.append([station, uri]) print '%d stations found...' % len(pending_channels) else: print 'Bad response: %s %s' % (response.reason, response.status) def find_config_file(basename): filename = get_config_filename(basename) if os.path.isfile(filename): return filename for libdir in sys.path: prefix = os.path.commonprefix([__file__, libdir]) if not prefix or prefix != libdir: continue libdir_parent, libdir_name = os.path.split(libdir) if 'site-packages' == libdir_name: prefix = os.path.join(libdir_parent, '..', '..') filename = os.path.join(prefix, 'share', 'webradio', basename) if os.path.isfile(filename): return filename for filename in [ os.path.join(libdir, 'data', basename), os.path.join(libdir_parent, 'data', basename) ]: if os.path.isfile(filename): return filename return None def load_station_list(): filename = find_config_file('stations') if filename is None: raise RuntimeError, 'Cannot find station list' print 'reading stations from %r' % filename parser = SafeConfigParser() parser.read(filename) for station_id in parser.sections(): uri = parser.get(station_id, 'uri') title = parser.get(station_id, 'title') stream_uri = parser.get(station_id, 'streams') station = Station(station_id, title, uri) if stream_uri: station.stream_uri = stream_uri i = 1 while True: key = 'noise%d' % i i += 1 if not parser.has_option(station_id, key): break noise = parser.get(station_id, key) station.add_noise_filter(noise) for key in parser.options(station_id): if key.startswith('alias.'): name = key[len('alias.'):] value = parser.get(station_id, key) station.add_alias(name, value) continue load_station_details(station) self.StationAdded(station) def load_streams(channel, content): parser = SafeConfigParser() parser.readfp(StringIO(content)) playlist = dict(parser.items('playlist')) length = int(playlist['numberofentries']) for i in range(1, length + 1): uri = playlist['file%d' % i] title = playlist.get('title%d' % i) length = int(playlist.get('length%d' % i, -1)) if title: title = channel.station.filter_noise(title) stream = Stream(uri, title, length) channel.streams.append(stream) def load_pending_channels(): for station, uri in pending_channels: response, content = self.__fetch(uri) if 200 == response.status: channel = Channel(station, uri) station.channels.append(channel) load_streams(channel, content) self.ChannelAdded(station.id, channel) pending_channels = [] load_station_list() idle_add(self.DataReady, 1) load_pending_channels() idle_add(self.DataReady, 2)
def on_queue_current_playlist_changed(self, event, queue, playlist): """ Updates the list on queue changes """ glib.idle_add(self.update_playlist, playlist)
def slewComplete (self, az): def ui(): self.startUpdateTimer() self.slewButton.set_sensitive(True) self.updateTrackingStatus() glib.idle_add(ui)
def reset(self): """ Resets the progress bar appearance """ glib.idle_add(self.set_fraction, 0) glib.idle_add(self.set_text, _('Not Playing'))
def slitChangeBegin (self): def ui(): self.openButton.set_sensitive(False) self.closeButton.set_sensitive(False) glib.idle_add(ui)
def tod_context_clear_activate_cb(self, menuitem, data=None): """Clear times for selected rider.""" # clear has no real meaning in omnium glib.idle_add(self.delayed_announce)
def slewBegin (self, az): def ui(): self.pauseUpdateTimer() self.slewButton.set_sensitive(False) glib.idle_add(ui)
def on_continue(self): self.continued = True #self.draw_queue=[] glib.idle_add(self.next)
def tod_context_edit_activate_cb(self, menuitem, data=None): """Run edit time dialog.""" # no edit time for now in omnium glib.idle_add(self.delayed_announce)
def run(self): # control connection self.control_dpy = xlib.XOpenDisplay(None) xlib.XSynchronize(self.control_dpy, True) # unmapped replay window self.replay_dpy = xlib.XOpenDisplay(None) self.custom_atom = xlib.XInternAtom(self.replay_dpy, b"SCREENKEY", False) replay_fd = xlib.XConnectionNumber(self.replay_dpy) self.replay_win = create_replay_window(self.replay_dpy) # bail during initialization errors try: if self.input_types & InputType.keyboard: self._kbd_init() except Exception as e: self.error = e xlib.XCloseDisplay(self.control_dpy) xlib.XDestroyWindow(self.replay_dpy, self.replay_win) xlib.XCloseDisplay(self.replay_dpy) # cheap wakeup() equivalent for compatibility glib.idle_add(self._event_callback, None) self._stop = True self.lock.release() return # initialize recording context ev_ranges = [] dev_ranges = [] if self.input_types & InputType.keyboard: ev_ranges.append([xlib.FocusIn, xlib.FocusOut]) dev_ranges.append([xlib.KeyPress, xlib.KeyRelease]) if self.input_types & InputType.button: dev_ranges.append([xlib.ButtonPress, xlib.ButtonRelease]) if self.input_types & InputType.movement: dev_ranges.append([xlib.MotionNotify, xlib.MotionNotify]) self.record_ctx = record_context(self.control_dpy, ev_ranges, dev_ranges); record_dpy = xlib.XOpenDisplay(None) record_fd = xlib.XConnectionNumber(record_dpy) # we need to keep the record_ref alive(!) record_ref = record_enable(record_dpy, self.record_ctx, self._event_received) # event loop self.lock.release() while True: with self.lock: if self._stop: break r_fd = [] if xlib.XPending(record_dpy): r_fd.append(record_fd) if xlib.XPending(self.replay_dpy): r_fd.append(replay_fd) if not r_fd: r_fd, _, _ = select.select([record_fd, replay_fd], [], []) if not r_fd: break if record_fd in r_fd: xlib.XRecordProcessReplies(record_dpy) xlib.XFlush(self.replay_dpy) if replay_fd in r_fd: ev = xlib.XEvent() xlib.XNextEvent(self.replay_dpy, xlib.byref(ev)) if self.input_types & InputType.keyboard: self._kbd_process(ev) # finalize self.lock.acquire() xlib.XRecordFreeContext(self.control_dpy, self.record_ctx) xlib.XCloseDisplay(self.control_dpy) xlib.XCloseDisplay(record_dpy) del record_ref if self.input_types & InputType.keyboard: self._kbd_del() xlib.XDestroyWindow(self.replay_dpy, self.replay_win) xlib.XCloseDisplay(self.replay_dpy) self._stop = True self.lock.release()
def editcol_db(self, cell, path, new_text, col): """Cell update with writeback to meet.""" new_text = new_text.strip() self.riders[path][col] = new_text.strip() glib.idle_add(self.meet.rider_edit, self.riders[path][COL_BIB], self.series, col, new_text)
def __enb(eventname, exaile, nothing): glib.idle_add(_enable, exaile)
def run(self): glib.idle_add(self.task_ctrl.use(self.idle))
def Propagate(self, widget=None, data=None): glib.idle_add(self.network.Propagate, self.pattern_spin_button.get_value_as_int())
def _event_processed(self, data): data.symbol = xlib.XKeysymToString(data.keysym) if data.string is None: data.string = keysym_to_unicode(data.keysym) glib.idle_add(self._event_callback, data)
def stop_collecting_data(self, callback): """Stop data collection on all sensors and run callback.""" for sensor in self.sensors: sensor.stop_recording() if callback is not None: glib.idle_add(callback)
def __init__(self): # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # When the window is given the "delete_event" signal (this is given # by the window manager, usually by the "close" option, or on the # titlebar), we ask it to call the delete_event () function # as defined above. The data passed to the callback # function is NULL and is ignored in the callback function. self.window.connect("delete_event", self.delete_event) # Here we connect the "destroy" event to a signal handler. # This event occurs when we call gtk_widget_destroy() on the window, # or if we return FALSE in the "delete_event" callback. self.window.connect("destroy", self.destroy) self.window.set_title("Network") self.window.set_default_size( 0, 0) #this is to ensure the window is always the smallest it can be self.window.set_resizable(False) self.patterns = Patterns self.targets = Targets # Args are: homogeneous, spacing, expand, fill, padding homogeneous = False spacing = 0 expand = False fill = False padding = 10 self.hbox = gtk.HBox(homogeneous, spacing) self.hbox2 = gtk.HBox(homogeneous, spacing) self.vbox = gtk.VBox(homogeneous, spacing) self.window.add(self.vbox) adjustment = gtk.Adjustment(value=1, lower=1, upper=100000000, step_incr=1000, page_incr=10000) self.iterations_spin_button = gtk.SpinButton(adjustment, climb_rate=0, digits=0) adjustment = gtk.Adjustment(value=2, lower=1, upper=100, step_incr=5, page_incr=5) self.width_spin_button = gtk.SpinButton(adjustment, climb_rate=0, digits=0) self.layer_combobox = gtk.combo_box_new_text() self.layer_combobox.append_text("2") self.layer_combobox.append_text("3") self.layer_combobox.set_active(1) adjustment = gtk.Adjustment(value=2, lower=1, upper=100, step_incr=5, page_incr=5) self.height_spin_button = gtk.SpinButton(adjustment, climb_rate=0, digits=0) adjustment = gtk.Adjustment(value=100, lower=1, upper=100, step_incr=5, page_incr=5) self.unit_width_spin_button = gtk.SpinButton(adjustment, climb_rate=0, digits=0) adjustment = gtk.Adjustment(value=0, lower=0, upper=len(self.patterns) - 1, step_incr=1, page_incr=1) self.pattern_spin_button = gtk.SpinButton(adjustment, climb_rate=0, digits=0) self.pattern_spin_button.set_wrap(True) # Create a series of buttons with the appropriate settings self.play = gtk.Button("Train") self.pause = gtk.Button("Pause") self.reset = gtk.Button("Reset") self.step = gtk.Button("Step") self.view_learning_graph = gtk.Button("Learning Graph") self.play.connect("clicked", self.Run, None) self.pause.connect("clicked", self.Pause, None) self.reset.connect("clicked", self.Reset, None) self.step.connect("clicked", self.Step, None) self.width_spin_button.connect("value_changed", self.Reset) self.height_spin_button.connect("value_changed", self.Reset) self.unit_width_spin_button.connect("value_changed", self.Reset) self.pattern_spin_button.connect("value_changed", self.Propagate) self.layer_combobox.connect('changed', self.Reset) self.network = Network( width=self.width_spin_button.get_value_as_int(), height=int(self.layer_combobox.get_active_text()), unit_width=self.unit_width_spin_button.get_value_as_int(), patterns=self.patterns, targets=self.targets, hidden_width=self.width_spin_button.get_value_as_int()) self.network.show() self.pause.set_sensitive(self.network.paused) self.vbox.pack_start(self.network, True, True, 0) self.vbox.pack_start(self.hbox, expand, fill, 3) self.vbox.pack_start(self.hbox2, expand, fill, 3) self.status_bar = gtk.Statusbar() self.vbox.pack_start(self.status_bar, expand, fill, 0) self.status_bar.show() glib.idle_add(self.Status_update) self.hbox.show() self.hbox2.show() self.vbox.show() self.play.show() self.pause.show() self.reset.show() self.step.show() self.view_learning_graph.show() self.iterations_spin_button.show() self.width_spin_button.show() self.height_spin_button.show() self.unit_width_spin_button.show() self.pattern_spin_button.show() self.layer_combobox.show() self.hbox.pack_start(self.play, expand, fill, padding) self.hbox.pack_start(self.pause, expand, fill, 0) self.hbox.pack_start(self.reset, expand, fill, padding) label = gtk.Label("Epochs:") label.show() self.hbox.pack_start(label, expand, fill, 0) self.hbox.pack_start(self.iterations_spin_button, expand, fill, padding) label = gtk.Label("Hidden units:") label.show() self.hbox.pack_start(label, expand, fill, padding) self.hbox.pack_start(self.width_spin_button, expand, fill, padding) # label = gtk.Label("Unit size:") # label.show() # self.hbox.pack_start(label, expand, fill, 0) # self.hbox.pack_start(self.unit_width_spin_button, expand, fill, padding) self.hbox2.pack_start(self.step, expand, fill, padding) label = gtk.Label("Pattern:") label.show() self.hbox2.pack_start(label, expand, fill, 0) self.hbox2.pack_start(self.pattern_spin_button, expand, fill, padding) label = gtk.Label("Layers:") label.show() self.hbox2.pack_start(label, expand, fill, padding) self.hbox2.pack_start(self.layer_combobox, expand, fill, 0) self.quit = gtk.Button("Quit") self.quit.connect("clicked", self.destroy, None) self.hbox2.pack_end(self.quit, expand, fill, padding) self.quit.show() #print window.get_size() self.window.show() self.window.present() return None
def play(self): """Start the experiment.""" # TODO: possibly change the "pipeline" of the drop-involvement in exp if self.play_callback is not None: glib.idle_add(self.play_callback)
def run(self): glib.idle_add(_idle) self._mainloop = gobject.MainLoop() self._mainloop.run()