def thread(self): ''' Поток ''' now = [] while self.exit_flag: now_old = now now = self.ACPI.read() if not now: pixb = gtk.icon_theme_get_default().load_icon(\ 'gpm-battery-missing', 22, gtk.ICON_LOOKUP_USE_BUILTIN) self.set_from_pixbuf(pixb) self.set_tooltip('Батарея отсутствует') else: if now != now_old: gtk.gdk.threads_enter() thm = gtk.icon_theme_get_default() pixb = thm.load_icon(self.make_icon_file_name(now), 22, gtk.ICON_LOOKUP_USE_BUILTIN) self.set_from_pixbuf(pixb) if now['Status'] == 1: self.set_tooltip('Зарядка %s осталось %s ресурс %s' % (now['Stat'], now['Time'], now['Diff_design'])) else: self.set_tooltip('Емкость %s осталось %s ресурс %s' % (now['Stat'], now['Time'], now['Diff_design'])) gtk.gdk.threads_leave() for i in xrange(4): if self.exit_flag: time.sleep(1) else: break
def generate_file_list(self, parent, lsfl): """Populate the file list treestore. This method is called when a directory is selected on the left treeview. It populates the right treestore with the contents of the selected directory. Has a built-in check for the filter text entry. """ lsfl.clear() for dirchild in parent.dirs: lsfl.append([gtk.icon_theme_get_default().\ load_icon(ICONS[MIMES[dirchild.mimetype]], SETTINGS.iconlistsize, gtk.ICON_LOOKUP_FORCE_SVG), dirchild.name, dirchild.strsize, dirchild.__str__()]) for filechild in parent.files: if isinstance(filechild, Photo) \ and filechild.hasthumb is True: lsfl.append([filechild.icon, filechild.name, filechild.strsize, filechild.__str__()]) else: lsfl.append([gtk.icon_theme_get_default().\ load_icon(ICONS[MIMES[filechild.mimetype]], SETTINGS.iconlistsize, gtk.ICON_LOOKUP_FORCE_SVG), filechild.name, filechild.strsize, filechild.__str__()])
def load_stock_image(name='stock_calendar',size = gtk.ICON_SIZE_SMALL_TOOLBAR ): dir = gtk.TEXT_DIR_NONE state =gtk.STATE_NORMAL try: pixbuf = gtk.icon_theme_get_default().load_icon(name, gtk.icon_size_lookup(size)[0], gtk.ICON_LOOKUP_USE_BUILTIN) except gobject.GError, exc: return gtk.icon_theme_get_default().load_icon(gtk.STOCK_MISSING_IMAGE, gtk.icon_size_lookup(size)[0], gtk.ICON_LOOKUP_USE_BUILTIN)
def get_icon(self, size=16): """ Returns the icon for the module contained in this wrapper. In the case of a sink or source this is easy as the module contains the icon. Wrappers derived from this class (such as the CategoryWrapper) may override this function """ import gtk if not self.icon.has_key(size) or self.icon[size] is None: if self.module_type in ["source", "sink", "twoway", "category"]: try: info = gtk.icon_theme_get_default().lookup_icon(self.icon_name, size, gtk.ICON_LOOKUP_GENERIC_FALLBACK) self.icon[size] = info.load_icon() self.icon_path = info.get_filename() except: self.icon[size] = None log.warn("Could not load icon %s for %s" % (self.icon_name, self.name)) #Last resort: Try the non icon-naming-spec compliant icon self.icon_name = "conduit" info = gtk.icon_theme_get_default().lookup_icon(self.icon_name, size, 0) self.icon[size] = info.load_icon() self.icon_path = info.get_filename() return self.icon[size]
def get_icon_pixbuf(name=None, stock=None, size=gtk.ICON_SIZE_DIALOG): ok = True if name: #use png icons on windows if gs.IS_WINDOWS: name = os.path.splitext(name)[0] + ".png" filename = os.path.join(gs.ICON_DIR, name) try: pb = gtk.gdk.pixbuf_new_from_file_at_size( os.path.abspath(filename), *gtk.icon_size_lookup(size) ) except Exception: LOG.warn("Error loading icon: %s" % filename, exc_info=True) ok = False elif stock: try: pb = gtk.icon_theme_get_default().load_icon( stock, gtk.icon_size_lookup(size)[0], 0) except Exception: ok = False LOG.warn("Error loading stock icon: %s" % stock, exc_info=True) else: raise ValueError("Must pass and icon name or a stock name") if not ok: pb = gtk.icon_theme_get_default().load_icon( gtk.STOCK_MISSING_IMAGE, gtk.icon_size_lookup(size)[0], 0) return pb
def __init__(self, image_size=gtk.ICON_SIZE_MENU): super(SpinnerIcon, self).__init__() self._frames = [] icon_theme = gtk.icon_theme_get_default() icon_info = icon_theme.lookup_icon('process-working', image_size, gtk.ICON_LOOKUP_USE_BUILTIN) if icon_info: icon = icon_info.load_icon() size = icon_info.get_base_size() width = icon.get_width() height = icon.get_height() for y in xrange(0, height, size): for x in xrange(0, width, size): self._frames.append(icon.subpixbuf(x, y, size, size)) self._current_frame = 0 self._num_frames = len(self._frames) -1 icon_theme = gtk.icon_theme_get_default() self._default_icon = icon_theme.load_icon('text-html', gtk.ICON_SIZE_MENU, gtk.ICON_LOOKUP_USE_BUILTIN) self._default_icon = self._default_icon.scale_simple(16, 16, gtk.gdk.INTERP_BILINEAR) self.set_from_pixbuf(self._default_icon) self._is_spinning = False
def get_folder_list_callback(self, results): if results[3]: showMessage(None, results[3]) return if self.RootDirectoryDisableTraverse: if self.RootDirectory and not results[0].startswith(self.RootDirectory): log.debug("Browse Folder: disable=" + str(self.RootDirectoryDisableTraverse) + " matched start with rootDir '" + results[0] + "'") return self.liststore.clear() self.selectedfolder = results[0] log.debug("RBB:callback selectedfolder="+self.selectedfolder) self.label.handler_block(self.handler_id) self.recentliststore.clear() for folder in self.recent: self.recentliststore.append([folder]) self.recentliststore.prepend([self.selectedfolder]) self.label.set_active(0) self.label.handler_unblock(self.handler_id) if not results[1]: pixbuf = gtk.icon_theme_get_default().load_icon("go-up", 24, 0) self.liststore.append([pixbuf, ".."]) subfolders = [] for folder in results[2]: subfolders.append(folder) subfolders.sort(key=caseInsensitive) for folder in subfolders: pixbuf = gtk.icon_theme_get_default().load_icon("folder", 24, 0) self.liststore.append([pixbuf, folder])
def set_thumbnail(self, filename): try: filetype = gnomevfs.get_mime_type(filename) except: filetype = "unknown" if filetype.startswith("image") or filetype.startswith("sketch"): im = Image.open(filename) im.thumbnail((256, 256), Image.NEAREST) pixbuf = self.cont.image2pixbuf(im) image = gtk.Image() image.set_from_pixbuf(pixbuf) elif filetype.startswith("audio"): icon_theme = gtk.icon_theme_get_default() pixbuf = icon_theme.load_icon("mediaplayer_default_album", 128, 0) image = gtk.Image() image.set_from_pixbuf(pixbuf) elif filetype.startswith("video"): icon_theme = gtk.icon_theme_get_default() pixbuf = icon_theme.load_icon("general_video", 128, 0) image = gtk.Image() image.set_from_pixbuf(pixbuf) else: icon_theme = gtk.icon_theme_get_default() pixbuf = icon_theme.load_icon("tasklaunch_file_manager", 128, 0) image = gtk.Image() image.set_from_pixbuf(pixbuf) self.imageBox.remove(self.imageBoxContent) self.imageBoxContent = image self.imageBox.add(self.imageBoxContent) self.imageBox.show_all() return
def init(): from blamainwindow import BlaMainWindow gtk.icon_theme_get_default().append_search_path(blaconst.ICONS_PATH) theme = gtk.icon_theme_get_default() gtk.window_set_default_icon_name(blaconst.APPNAME) return BlaMainWindow()
def __init__(self, frame): self.dragging = False self.lastPos = (0, 0) self.tool = FITSCanvas.CONTRAST self.frame = frame gtk.icon_theme_get_default().append_search_path( os.path.abspath(os.path.dirname(__file__))) self.window = gtk.ScrolledWindow() self.window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.canvas = goocanvas.Canvas() self.canvas.set_property("automatic-bounds", True) self.builder = gtk.Builder() self.builder.add_from_file( os.path.join(os.path.dirname(__file__), "canvas.xml")) self.builder.connect_signals({"contrast_activate_cb": self.contrast_activate_cb, "zoom_activate_cb": self.zoom_activate_cb, "pan_activate_cb": self.pan_activate_cb, "_98_activate_cb": self._98_activate_cb, "minmax_activate_cb": self.minmax_activate_cb, "linear_activate_cb": self.linear_activate_cb, "log_activate_cb": self.log_activate_cb, "invert_activate_cb": self.invert_activate_cb, "reset_contrast_activate_cb": self.reset_contrast_activate_cb}) w, h = self.frame.get_image().get_width( ), self.frame.get_image().get_height() self.canvas.set_bounds(0, 0, w, h) canvasItem = goocanvas.Image(pixbuf=frame.get_pixbuf(), x=0, y=0) self.canvas.get_root_item().add_child(canvasItem) self.canvasImage = self.canvas.get_root_item().get_child(0) # connect canvas events self.canvas.connect("button-press-event", self.button_press_callback) self.canvas.connect( "button-release-event", self.button_release_callback) self.canvas.connect("motion-notify-event", self.motion_notify_callback) # create our accelerator maps #gtk.accel_map_add_entry("<canvas>/Zoom", ord('z'), 0) # connect accelerator #accel_group = self.builder.get_object("canvasAcceleratorGroup") #accel_group.connect_by_path("<canvas>/Zoom", self.zoom_activate_cb) # self.window.get_parent().add_accel_group(accel_group) # go! self.window.add(self.canvas) self.window.show_all()
def file_pixbuf(self, column, cell, model, iter): filename = os.path.join(self.dirname, model.get_value(iter, 0)) filestat = os.stat(filename) if stat.S_ISDIR(filestat.st_mode): pb = gtk.icon_theme_get_default().load_icon("folder", 24, 0) elif filename.endswith(tuple(self.audioFormats)): pb = gtk.icon_theme_get_default().load_icon("audio-volume-medium", 24, 0) else: pb = gtk.icon_theme_get_default().load_icon("edit-copy", 24, 0) cell.set_property('pixbuf', pb) return
def _create_gui(self): #load themed or fallback app icon try: icon = os.path.join(os.path.dirname(__file__),'uclogo.svg') if os.path.exists(icon): #not installed self.icon = gtk.gdk.pixbuf_new_from_file(icon) else: #installed self.icon = gtk.icon_theme_get_default().load_icon("uclogo", 24, gtk.ICON_LOOKUP_FORCE_SVG) except gobject.GError: self.icon = gtk.icon_theme_get_default().load_icon(gtk.STOCK_NETWORK, 24, gtk.ICON_LOOKUP_FORCE_SVG) #build tray icon self.tray = gtk.StatusIcon() self.tray.set_from_pixbuf(self.icon) self.tray.set_tooltip('IEnabler Connecting..') self.tray.connect('popup-menu', self._on_popup_menu) self.tray.set_visible(True) #attach the libnotification bubble to the tray self.notification = pynotify.Notification(CONFIGURATION.get("name")) try: self.notification.attach_to_status_icon(self.tray) except: pass self.notification.set_timeout(pynotify.EXPIRES_DEFAULT) #create popup menu self.menu = gtk.Menu() enable = gtk.ImageMenuItem(stock_id=gtk.STOCK_YES, accel_group=None) enable.get_children()[0].set_text("Enable Internet") enable.connect("activate", lambda x: self.authenticate("Enable")) disable = gtk.ImageMenuItem(stock_id=gtk.STOCK_NO, accel_group=None) disable.get_children()[0].set_text("Disable Internet") disable.connect("activate", lambda x: self.authenticate("Disable")) topup = gtk.ImageMenuItem(stock_id=gtk.STOCK_HOME, accel_group=None) topup.get_children()[0].set_text("Add Funds") topup.connect("activate", lambda x: webbrowser.open(CONFIGURATION.get("add_funds_url"))) configure = gtk.ImageMenuItem(stock_id=gtk.STOCK_PREFERENCES, accel_group=None) configure.connect("activate", self._on_configure_clicked) about = gtk.ImageMenuItem(stock_id=gtk.STOCK_ABOUT, accel_group=None) about.connect("activate", self._on_about_clicked) quit = gtk.ImageMenuItem(stock_id=gtk.STOCK_QUIT, accel_group=None) quit.connect("activate", self._on_exit_clicked) self.menu.add(enable) self.menu.add(disable) self.menu.add(topup) self.menu.add(gtk.SeparatorMenuItem()) self.menu.add(configure) self.menu.add(gtk.SeparatorMenuItem()) self.menu.add(about) self.menu.add(quit) self.menu.show_all()
def set_app_display_from_data(self, data): self.ui.get_object('application_name').props.label = data['name'] icon = self.ui.get_object('application_icon') try: if data['icon'].startswith('/'): pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(data['icon'], 32, 32) else: pixbuf = gtk.icon_theme_get_default().load_icon( data['icon'], 32, gtk.ICON_LOOKUP_USE_BUILTIN) except glib.GError: pixbuf = gtk.icon_theme_get_default().load_icon( 'gnome-panel-launcher', 32, gtk.ICON_LOOKUP_USE_BUILTIN) icon.set_from_pixbuf(pixbuf)
def set_direction(self, direction): if direction == Conflict.CONFLICT_COPY_SINK_TO_SOURCE: self.image = gtk.icon_theme_get_default().load_icon("conduit-conflict-left",16,0) elif direction == Conflict.CONFLICT_COPY_SOURCE_TO_SINK: self.image = gtk.icon_theme_get_default().load_icon("conduit-conflict-right",16,0) elif direction == Conflict.CONFLICT_SKIP: self.image = gtk.icon_theme_get_default().load_icon("conduit-conflict-skip",16,0) elif direction == Conflict.CONFLICT_DELETE: self.image = gtk.icon_theme_get_default().load_icon("conduit-conflict-delete",16,0) elif direction == Conflict.CONFLICT_ASK: self.image = gtk.icon_theme_get_default().load_icon("conduit-conflict-ask",16,0) else: self.image = None
def parse_icon(self): """Method used when reading from binary file.""" try: self._icon = gtk.icon_theme_get_default().\ load_icon(ICONS[MIMES[self._mimetype]], SETTINGS.iconlistsize, gtk.ICON_LOOKUP_FORCE_SVG) except Exception as exc: if SETTINGS.missingicon is True: MANAGER.append_event("Error loading icon for mimetype: " + self._mimetype, self.__str__(), exc, 4) if self._icon == None: self._icon = gtk.icon_theme_get_default().\ load_icon(ICONS["file"], SETTINGS.iconlistsize, gtk.ICON_LOOKUP_FORCE_SVG)
def main(): class Unbuffered(object): def __init__(self, file): self.file = file def write(self, arg): self.file.write(arg) self.file.flush() def __getattr__(self, attr): return getattr(self.file, attr) sys.stdout = Unbuffered(sys.stdout) gtk.icon_theme_get_default().append_search_path(paths.icon_dir()) app = MeldApp() app.parse_args(sys.argv[1:]) gtk.main()
def on_name_change(self, treeview): """ Called when the user selects a movie or a show from the 'name list'. """ selected_text = self.get_selected_name() self.file_model.clear() if self.get_mode() == MODE_SHOWS: self.seassons_model.clear() seassons = self.pycavane.seasson_by_show(selected_text) for i in range(1, len(seassons) + 1): # Here we're assuming that the server has the # seassons 1 to length(seassons) that could not be true. TODO #self.seassons_model.append([i]) gobject.idle_add(append_item_to_store, self.seassons_model, [i]) else: self.file_model.clear() theme = gtk.icon_theme_get_default() file_icon = theme.load_icon(gtk.STOCK_FILE, 48, 0) letter = selected_text for movie in self.pycavane.get_movies(letter): #self.file_model.append([file_icon, movie[1]]) gobject.idle_add(append_item_to_store, self.file_model, (file_icon, movie[1]))
def get_image_from_name(name, size, fit_size = "both"): assert isinstance(name, str), "Image name must be a string" icon = None if gtk.stock_lookup(name): icon = gtk.image_new_from_stock(name, size) elif gtk.icon_theme_get_default().has_icon(name): icon = gtk.image_new_from_icon_name(name, size) else: path = os.path.join('..', os.path.dirname(os.path.dirname(__file__)), 'data', 'gfx', name+'.png') if os.path.exists(path): try: _size = gtk.icon_size_lookup(size) pixbuf = gtk.gdk.pixbuf_new_from_file(path) heightS = max(float(_size[1])/float(pixbuf.get_height()), 1.0) widthS = max(float(_size[0])/float(pixbuf.get_width()), 1.0) if fit_size == 'both': if heightS < widthS: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, _size[1]*pixbuf.get_width()/pixbuf.get_height(), _size[1]) else: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, _size[0], _size[0]*pixbuf.get_height()/pixbuf.get_width()) elif fit_size == 'width': pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, _size[0], _size[0]*pixbuf.get_height()/pixbuf.get_widtht()) else: pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(path, _size[1]*pixbuf.get_width()/pixbuf.get_height(), _size[1]) icon = gtk.image_new_from_pixbuf(pixbuf) except Exception as e: print e icon = gtk.image_new_from_stock(gtk.STOCK_MISSING_IMAGE, size) else: icon = gtk.image_new_from_stock(gtk.STOCK_MISSING_IMAGE, size) return icon
def get_pixbuf(self, size): '''Get the application icon as a C{gtk.gdk.Pixbuf}. @param size: the icon size as gtk constant @returns: a pixbuf object or C{None} ''' icon = self['Desktop Entry'].get('Icon', None) if not icon: return None if isinstance(icon, File): icon = icon.path w, h = gtk.icon_size_lookup(size) if '/' in icon or '\\' in icon: if zim.fs.isfile(icon): return gtk.gdk.pixbuf_new_from_file_at_size(icon, w, h) else: return None else: theme = gtk.icon_theme_get_default() try: pixbuf = theme.load_icon(icon.encode('utf-8'), w, 0) except Exception, error: #~ logger.exception('Foo') return None return pixbuf
def make_icons_model(): import os, glob stock_icon_ls = gtk.stock_list_ids() # coot icons pixbuf_dir = os.getenv("COOT_PIXMAPS_DIR") if not pixbuf_dir: pixbuf_dir = os.path.join(get_pkgdatadir(), "pixmaps") patt = os.path.normpath(pixbuf_dir + "/*.svg") coot_icon_filename_ls = glob.glob(patt) model = gtk.ListStore(gtk.gdk.Pixbuf, str, str) for icon_filename in coot_icon_filename_ls: if os.path.isfile(icon_filename): icon = os.path.basename(icon_filename) pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icon_filename, 16, 16) model.append([pixbuf, icon, icon_filename]) # build in default gtk icons icon_theme = gtk.icon_theme_get_default() for icon in stock_icon_ls: try: pixbuf = icon_theme.load_icon(icon, 16, gtk.ICON_LOOKUP_USE_BUILTIN) model.append([pixbuf, icon, None]) except: pass return model
def on_seasson_change(self, combo): """ Called when the 'seasson' combobox changes value. This will only be fired if the 'mode' combobox is setted to 'Shows'. """ # Precondition if self.get_mode() != MODE_SHOWS: return seasson = combobox_get_active_text(combo) show = self.get_selected_name() if not seasson: return self.file_model.clear() theme = gtk.icon_theme_get_default() file_icon = theme.load_icon(gtk.STOCK_FILE, 48, 0) seasson = "Temporada " + seasson # Hopfully temporary fix for episode in self.pycavane.episodes_by_season(show, seasson): episode_name = "%.2d - %s" % (int(episode[1]), episode[2]) #self.file_model.append([file_icon, episode_name]) gobject.idle_add(append_item_to_store, self.file_model, (file_icon, episode_name))
def __init__(self, message="", default_text='', modal=True): gtk.Dialog.__init__(self) self.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CLOSE, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) #self.set_title("Icon search") if modal: self.set_modal(True) self.set_border_width(5) self.set_size_request(400, 300) self.combobox=gtk.combo_box_new_text() self.combobox.set_size_request(200, 20) hbox=gtk.HBox(False,2) #format: actual icon, name, context self.model=gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING) self.modelfilter=self.model.filter_new() self.modelfilter.set_visible_func(self.search_icons) self.iconview=gtk.IconView() self.iconview.set_model(self.modelfilter) self.iconview.set_pixbuf_column(0) self.iconview.set_text_column(1) self.iconview.set_selection_mode(gtk.SELECTION_SINGLE) self.iconview.set_item_width(72) self.iconview.set_size_request(200, 220) defaulttheme=gtk.icon_theme_get_default() self.combobox.connect('changed', self.category_changed) self.refine=gtk.Entry() self.refine.connect('changed', self.category_changed) self.refine.set_icon_from_stock(gtk.ENTRY_ICON_SECONDARY, gtk.STOCK_FIND) self.refine.set_size_request(200, 30) list2=[] for c in defaulttheme.list_contexts(): current=defaulttheme.list_icons(context=c) list2+=set(current) self.combobox.append_text(c) for i in current: try: self.model.append([defaulttheme.load_icon(i, 32, gtk.ICON_LOOKUP_USE_BUILTIN), i,c]) except GError as err: stderr.write('Error loading "%s": %s\n' % (i, err.args[0])) other=list(set(defaulttheme.list_icons())-(set(list2))) for i in other: self.model.append([defaulttheme.load_icon(i, 32, gtk.ICON_LOOKUP_USE_BUILTIN), i,"Other"]) self.combobox.prepend_text("Other") scrolled = gtk.ScrolledWindow() scrolled.add(self.iconview) scrolled.props.hscrollbar_policy = gtk.POLICY_NEVER scrolled.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC hbox.add(self.combobox) hbox.add(self.refine) self.vbox.add(hbox) self.vbox.add(scrolled) self.combobox.set_active(0) self.iconview.connect('selection-changed', self.get_icon_name) self.vbox.show_all()
def append_update(self, status, pkgname, summary): model = self.get_model() icontheme = gtk.icon_theme_get_default() for icon_name in ['application-x-deb', 'package-x-generic', 'package']: icon_theme = icontheme.lookup_icon(icon_name, size=32, flags=gtk.ICON_LOOKUP_NO_SVG) if icon_theme: break if icon_theme: pixbuf = icon_theme.load_icon() else: pixbuf = icontheme.load_icon(gtk.STOCK_MISSING_IMAGE, 32, 0) iter = model.append() model.set(iter, self.COLUMN_INSTALLED, status, self.COLUMN_ICON, pixbuf, self.COLUMN_PKG, pkgname, self.COLUMN_NAME, pkgname, self.COLUMN_DESC, summary, self.COLUMN_DISPLAY, '<b>%s</b>\n%s' % (pkgname, summary), self.COLUMN_TYPE, 'update')
def __init__(self, parent, version, date): gtk.MessageDialog.__init__(self, parent, gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_NONE, 'VMNetX update available') theme = gtk.icon_theme_get_default() try: icon = theme.load_icon('vmnetx', 256, 0) icon = icon.scale_simple(self.ICON_SIZE, self.ICON_SIZE, gtk.gdk.INTERP_BILINEAR) except glib.GError: # VMNetX icon not installed in search path icon = theme.load_icon('software-update-available', self.ICON_SIZE, 0) self.set_image(gtk.image_new_from_pixbuf(icon)) self.set_title('Update Available') datestr = '%s %s, %s' % ( date.strftime('%B'), date.strftime('%d').lstrip('0'), date.strftime('%Y') ) self.format_secondary_markup( 'VMNetX <b>%s</b> was released on <b>%s</b>.' % ( urllib.quote(version), datestr)) self.add_buttons('Skip this version', gtk.RESPONSE_REJECT, 'Remind me later', gtk.RESPONSE_CLOSE, 'Download update', gtk.RESPONSE_ACCEPT) self.set_default_response(gtk.RESPONSE_ACCEPT) self.connect('response', self._response)
def __download_album(self, audio_dl_uri, sku): def download_progress(current, total): self.__downloads[str_uri] = (current, total) self.__notify_status_changed() def download_finished(uri, result): del self.__cancellables[str_uri] del self.__downloads[str_uri] try: success = uri.copy_finish(result) except Exception, e: success = False print "Download not completed: " + str(e) if success: threading.Thread(target=unzip_album).start() else: remove_download_files() if len(self.__downloads) == 0: # All downloads are complete shell = self.get_property('shell') manager = shell.get_player().get_property('ui-manager') manager.get_action("/MagnatuneSourceViewPopup/MagnatuneCancelDownload").set_sensitive(False) if success: width, height = gtk.icon_size_lookup(gtk.ICON_SIZE_LARGE_TOOLBAR) icon = rb.try_load_icon(gtk.icon_theme_get_default(), "magnatune", width, 0) shell.notify_custom(4000, _("Finished Downloading"), _("All Magnatune downloads have been completed."), icon, True) self.__notify_status_changed()
def __init__(self, viewer, is_remote=False): gtk.HBox.__init__(self, spacing=3) self._theme = gtk.icon_theme_get_default() self._warnings = gtk.HBox() self.pack_start(self._warnings, expand=False) self.pack_start(gtk.Label()) # filler def add_icon(name, sensitive): icon = self._get_icon(name) icon.set_sensitive(sensitive) self.pack_start(icon, expand=False) return icon escape_label = gtk.Label('Ctrl-Alt') escape_label.set_padding(3, 0) self.pack_start(escape_label, expand=False) keyboard_icon = add_icon('input-keyboard', viewer.keyboard_grabbed) mouse_icon = add_icon('input-mouse', viewer.mouse_grabbed) if is_remote: add_icon('network-idle', True) else: add_icon('computer', True) viewer.connect('viewer-keyboard-grab', self._grabbed, keyboard_icon) viewer.connect('viewer-mouse-grab', self._grabbed, mouse_icon)
def _get_icon_info(self): icon_info = _IconInfo() if self.file_name: icon_info.file_name = self.file_name elif self.icon_name: theme = gtk.icon_theme_get_default() size = 50 if self.width != None: size = self.width info = theme.lookup_icon(self.icon_name, int(size), 0) if info: attach_x, attach_y = self._get_attach_points(info, size) icon_info.file_name = info.get_filename() icon_info.attach_x = attach_x icon_info.attach_y = attach_y del info else: logging.warning('No icon with the name %s was found in the ' 'theme.', self.icon_name) return icon_info
def _draw_badge(self, context, size, sensitive, widget): theme = gtk.icon_theme_get_default() badge_info = theme.lookup_icon(self.badge_name, int(size), 0) if badge_info: badge_file_name = badge_info.get_filename() if badge_file_name.endswith('.svg'): handle = self._loader.load(badge_file_name, {}, self.cache) dimensions = handle.get_dimension_data() icon_width = int(dimensions[0]) icon_height = int(dimensions[1]) pixbuf = handle.get_pixbuf() else: pixbuf = gtk.gdk.pixbuf_new_from_file(badge_file_name) icon_width = pixbuf.get_width() icon_height = pixbuf.get_height() context.scale(float(size) / icon_width, float(size) / icon_height) if not sensitive: pixbuf = self._get_insensitive_pixbuf(pixbuf, widget) surface = hippo.cairo_surface_from_gdk_pixbuf(pixbuf) context.set_source_surface(surface, 0, 0) context.paint()
def on_get_value(self, rowref, column): if column == 0: # Object return rowref elif column == 1: # IsNew pixmap if rowref['unseen']: icon_theme = gtk.icon_theme_get_default() return icon_theme.load_icon('emblem-new', 10, gtk.ICON_LOOKUP_USE_BUILTIN) else: return None elif column == 2: # Title title = rowref['title'] if rowref['unread']: title = '<b>%s</b>' % title return title elif column == 3: # Date return self.date_to_str(rowref['updated_parsed']) elif column == 4: # DateNum entry_id = rowref['id'] if entry_id not in self.data_weights: weight = time.mktime(rowref['updated_parsed']) if rowref['unread']: weight = weight * 100 if rowref['unseen']: weight = weight * 100 self.data_weights[entry_id] = weight return self.data_weights[entry_id] elif column == 5: # Size length = int(rowref['links'][0]['length']) return format_to_maximun_unit(length, "GB", "MB", "KB", "Bytes") return
def __init__( self ): gobject.GObject.__init__( self ) self.icons = { } self.count = 0 # Some apps don't put a default icon in the default theme folder, so we will search all themes def createTheme( d ): theme = gtk.IconTheme() theme.set_custom_theme( d ) return theme # This takes to much time and there are only a very few applications that use icons from different themes #self.themes = map( createTheme, [ d for d in os.listdir( "/usr/share/icons" ) if os.path.isdir( os.path.join( "/usr/share/icons", d ) ) ] ) defaultTheme = gtk.icon_theme_get_default() defaultKdeTheme = createTheme( "kde.default" ) # Themes with the same content as the default them aren't needed #self.themes = [ theme for theme in self.themes if theme.list_icons() != defaultTheme.list_icons() ] self.themes = [ defaultTheme, defaultKdeTheme ] self.cache = {} # Listen for changes in the themes for theme in self.themes: theme.connect("changed", self.themeChanged )
def __init__(self, image_dir): global_settings.client_name = gui_misc.get_wi_name() self.image_dir = image_dir try: self.application_dir = os.environ["PACKAGE_MANAGER_ROOT"] except KeyError: self.application_dir = "/" misc.setlocale(locale.LC_ALL, "") for module in (gettext, gtk.glade): module.bindtextdomain( "pkg", os.path.join(self.application_dir, "usr/share/locale")) module.textdomain("pkg") gui_misc.init_for_help(self.application_dir) self.pub_pkg_list = None self.pr = progress.NullProgressTracker() self.pub_new_tasks = [] self.pkg_install_tasks = [] self.icon_theme = gtk.icon_theme_get_default() icon_location = os.path.join(self.application_dir, ICON_LOCATION) self.icon_theme.append_search_path(icon_location) self.param = None self.disabled_pubs = {} self.repo_gui = None self.first_run = True # Webinstall Dialog builder = gtk.Builder() self.gladefile = os.path.join( self.application_dir, "usr/share/package-manager/packagemanager.ui") builder.add_from_file(self.gladefile) self.w_webinstall_dialog = \ builder.get_object("webinstalldialog") self.w_webinstall_proceed = \ builder.get_object("proceed_button") self.w_webinstall_cancel = \ builder.get_object("cancel_button") self.w_webinstall_help = \ builder.get_object("help_button") self.w_webinstall_close = \ builder.get_object("close_button") self.w_webinstall_proceed_label = \ builder.get_object("proceed_new_repo_label") self.w_webinstall_toplabel = \ builder.get_object("webinstall_toplabel") self.w_webinstall_frame = \ builder.get_object("webinstall_frame") self.w_webinstall_image = \ builder.get_object("pkgimage") self.window_icon = gui_misc.get_icon(self.icon_theme, 'packagemanager', 48) self.w_webinstall_image.set_from_pixbuf(self.window_icon) self.w_webinstall_info_label = \ builder.get_object("label19") self.w_webinstall_textview = \ builder.get_object("webinstall_textview") infobuffer = self.w_webinstall_textview.get_buffer() infobuffer.create_tag("bold", weight=pango.WEIGHT_BOLD) infobuffer.create_tag("disabled", foreground="#757575") #Close to DimGrey self.__setup_signals() self.w_webinstall_dialog.set_icon(self.window_icon) self.api_o = gui_misc.get_api_object(self.image_dir, self.pr, self.w_webinstall_dialog) gui_misc.setup_logging()
class AddFeed(gtk.Window): prefs = None icon_theme = gtk.icon_theme_get_default() got_results = False num = 0 def __init__(self, prefs=None, applet=None): gtk.Window.__init__(self) if prefs is not None: self.prefs = prefs self.applet = prefs.applet self.set_transient_for(prefs) elif applet is not None: self.applet = applet self.google_source = None for source in self.applet.feeds.values(): if isinstance(source, classes.GoogleFeed): self.google_source = source break self.site_images = {} self.set_border_width(12) self.set_title(_("Add Feed")) self.set_icon_from_file(icon_path) #Source: label and radio buttons source_label = gtk.Label(_("Source:")) source_label.set_alignment(1.0, 0.0) source_vbox = gtk.VBox(False, 3) #Search via Google Reader pb = self.icon_theme.load_icon("system-search", 16, 0) pb = classes.get_16x16(pb) search_radio = gtk.RadioButton(None) search_radio.add(self.get_radio_hbox(pb, _("Search"))) if not self.google_source: search_radio.set_sensitive(False) search_radio.set_tooltip_text( _("You must sign in to a Google service to search for feeds.")) #Regular RSS/Atom feed try: pb = self.icon_theme.load_icon('application-rss+xml', 16, 0) pb = classes.get_16x16(pb) except: pb = gtk.gdk.pixbuf_new_from_file_at_size(icon_path, 16, 16) webfeed_radio = gtk.RadioButton(search_radio, None) webfeed_radio.add(self.get_radio_hbox(pb, _("RSS/Atom"))) #Google (Reader and Wave) pb = self.applet.get_favicon('www.google.com', True) google_radio = gtk.RadioButton(search_radio, None) google_radio.add( self.get_radio_hbox(pb, classes.GoogleFeed.title, 'www.google.com')) #Google Reader (CheckButton) pb = get_greader_icon() self.greader_check = gtk.CheckButton() self.greader_check.add( self.get_radio_hbox(pb, classes.GoogleReader.title, 'google-reader')) self.greader_check.set_active(True) self.greader_check.connect('toggled', self.check_toggled) #Google Wave pb = self.applet.get_favicon('wave.google.com', True) self.gwave_check = gtk.CheckButton() self.gwave_check.add( self.get_radio_hbox(pb, classes.GoogleWave.title, 'wave.google.com')) self.gwave_check.connect('toggled', self.check_toggled) google_vbox = gtk.VBox(False, 3) google_vbox.pack_start(self.greader_check, False) google_vbox.pack_start(self.gwave_check, False) google_vbox.show_all() self.google_align = gtk.Alignment(0.0, 0.0, 1.0, 0.0) self.google_align.set_padding(0, 0, 12, 0) self.google_align.add(google_vbox) self.google_align.set_no_show_all(True) #Reddit Inbox pb = self.applet.get_favicon('www.reddit.com', True) reddit_radio = gtk.RadioButton(search_radio, None) reddit_radio.add( self.get_radio_hbox(pb, classes.Reddit.title, 'www.reddit.com')) #Twitter Timeline and/or Replies pb = gtk.gdk.pixbuf_new_from_file_at_size(twitter_path, 16, 16) twitter_radio = gtk.RadioButton(search_radio, None) twitter_radio.add(self.get_radio_hbox(pb, _("Twitter"))) self.twitter_timeline_check = gtk.CheckButton(_("Timeline")) self.twitter_timeline_check.set_active(True) self.twitter_timeline_check.connect('toggled', self.check_toggled) self.twitter_timeline_check.show() self.twitter_replies_check = gtk.CheckButton(_("Replies")) self.twitter_replies_check.connect('toggled', self.check_toggled) self.twitter_replies_check.show() twitter_vbox = gtk.VBox(False, 3) twitter_vbox.pack_start(self.twitter_timeline_check, False) twitter_vbox.pack_start(self.twitter_replies_check, False) twitter_vbox.show_all() self.twitter_align = gtk.Alignment(0.0, 0.0, 1.0, 0.0) self.twitter_align.set_padding(0, 0, 12, 0) self.twitter_align.add(twitter_vbox) self.twitter_align.set_no_show_all(True) num = 0 for widget in (search_radio, webfeed_radio, google_radio, self.google_align, reddit_radio, twitter_radio, self.twitter_align): if isinstance(widget, gtk.RadioButton): widget.connect('toggled', self.radio_toggled) widget.num = num num += 1 source_vbox.pack_start(widget, False, False, 0) source_hbox = gtk.HBox(False, 6) source_hbox.pack_start(source_label, False, False) source_hbox.pack_start(source_vbox) #"Search for" label and entry search_label = gtk.Label(_("Search for")) search_label.set_alignment(1.0, 0.5) search_label.show() self.search_entry = gtk.Entry() self.search_entry.show() self.search_entry.connect('changed', self.entry_changed) self.search_hbox = gtk.HBox(False, 6) self.search_hbox.pack_start(search_label, False) self.search_hbox.pack_start(self.search_entry) self.search_hbox.set_no_show_all(True) #URL: label and entry url_label = gtk.Label(_("URL:")) url_label.set_alignment(1.0, 0.5) url_label.show() self.url_entry = gtk.Entry() self.url_entry.show() self.url_entry.connect('changed', self.entry_changed) self.url_hbox = gtk.HBox(False, 6) self.url_hbox.pack_start(url_label, False, False) self.url_hbox.pack_start(self.url_entry) self.url_hbox.set_no_show_all(True) #Username: label and entry user_label = gtk.Label(_("Username:"******"Password:"******"Feed search by ")) button = gtk.LinkButton(reader_url, _("Google Reader")) image.show() image_align.show() label.show() button.show() hbox = gtk.HBox() hbox.pack_start(image_align, False, False, 6) hbox.pack_start(label, False) hbox.pack_start(button, False) hbox.show() self.search_msg = gtk.HBox() self.search_msg.pack_start(hbox, True, False) self.search_msg.set_no_show_all(True) #Results VBox and ScrolledWindow for Feed Search self.results_vbox = gtk.VBox(False, 3) self.results_vbox.show() self.results_sw = gtk.ScrolledWindow() self.results_sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.results_sw.add_with_viewport(self.results_vbox) self.results_sw.set_no_show_all(True) #Cancel and Add buttons cancel = gtk.Button(stock=gtk.STOCK_CLOSE) cancel.connect('clicked', self.close) self.add_button = gtk.Button(stock=gtk.STOCK_ADD) self.add_button.set_flags(gtk.CAN_DEFAULT) self.add_button.set_sensitive(False) self.add_button.set_no_show_all(True) self.add_button.connect('clicked', self.almost_add_feed) #If signed in to Google Reader self.search_button = gtk.Button(_("_Search")) image = gtk.image_new_from_icon_name('search', gtk.ICON_SIZE_BUTTON) self.search_button.set_image(image) self.search_button.set_flags(gtk.CAN_DEFAULT) self.search_button.set_sensitive(False) self.search_button.set_no_show_all(True) self.search_button.connect('clicked', self.do_search) if self.google_source is not None: self.search_button.show() self.search_hbox.show() self.search_msg.show() else: self.add_button.show() self.url_hbox.show() webfeed_radio.set_active(True) button_hbox = gtk.HBox(False, 6) button_hbox.pack_end(self.add_button, False, False) button_hbox.pack_end(self.search_button, False, False) button_hbox.pack_end(cancel, False, False) main_vbox = gtk.VBox(False, 6) main_vbox.pack_start(source_hbox, False, False) main_vbox.pack_start(self.search_hbox, False, False) main_vbox.pack_start(self.url_hbox, False, False) main_vbox.pack_start(self.user_hbox, False, False) main_vbox.pack_start(self.pass_hbox, False, False) main_vbox.pack_start(self.search_msg, False, False) main_vbox.pack_start(self.results_sw) main_vbox.pack_end(button_hbox, False, False) main_vbox.show_all() self.add(main_vbox) self.add_button.grab_default() #Make the labels the same size sg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL) sg.add_widget(source_label) sg.add_widget(search_label) sg.add_widget(url_label) sg.add_widget(user_label) sg.add_widget(pass_label) #Make the buttons the same size sg = gtk.SizeGroup(gtk.SIZE_GROUP_HORIZONTAL) sg.add_widget(cancel) sg.add_widget(self.add_button) sg.add_widget(self.search_button) self.show_all() #Update any downloaded favicons if necessary for siteid in ('www.google.com', 'google-reader', 'wave.google.com', 'www.reddit.com'): self.applet.fetch_favicon(self.fetched_favicon, siteid, siteid) #The favicon was fetched def fetched_favicon(self, siteid, data): self.applet.favicons[siteid] = long(time.time()) fp = open(os.path.join(cache_dir, siteid + '.ico'), 'w+') fp.write(data) fp.close() pb = self.applet.get_favicon(siteid, True) if siteid in self.site_images: self.site_images[siteid].set_from_pixbuf(pb) #Add button clicked def almost_add_feed(self, button): #URL for RSS/Atom if self.num == 1: url = self.url_entry.get_text() self.applet.add_feed(url) #Signing in to Google Reader or Reddit else: username = self.user_entry.get_text() password = self.pass_entry.get_text() #Google if self.num == 2: if self.greader_check.get_active(): self.applet.add_feed('google-reader-' + username, None, username, password) if self.gwave_check.get_active(): self.applet.add_feed('google-wave-' + username, None, username, password) #Reddit if self.num == 3: self.applet.add_feed('reddit-' + username, None, username, password) elif self.num == 4: timeline = self.twitter_timeline_check.get_active() replies = self.twitter_replies_check.get_active() if timeline and replies: self.applet.add_feed('twitter-both-' + username, None, username, password) elif timeline: self.applet.add_feed('twitter-timeline-' + username, None, username, password) elif replies: self.applet.add_feed('twitter-replies-' + username, None, username, password) if self.prefs: self.prefs.update_liststore() self.destroy() def entry_changed(self, entry): #RSS/Atom or Search if entry == self.search_entry: self.do_sensitive(self.search_button, (entry, )) elif entry == self.url_entry: self.do_sensitive(self.add_button, (entry, )) elif self.num == 2: self.do_sensitive(self.add_button, (self.user_entry, self.pass_entry), (self.greader_check, self.gwave_check)) elif self.num == 4: self.do_sensitive( self.add_button, (self.user_entry, self.pass_entry), (self.twitter_timeline_check, self.twitter_replies_check)) else: self.do_sensitive(self.add_button, (self.user_entry, self.pass_entry)) def radio_toggled(self, radio): if not radio.get_active(): return False self.num = radio.num if self.num == 0: self.hide_widgets() self.search_button.show() self.search_hbox.show() self.search_msg.show() self.do_sensitive(self.search_button, (self.search_entry, )) if self.got_results: self.results_sw.show() elif self.num == 1: self.hide_widgets() self.add_button.show() self.url_hbox.show() self.do_sensitive(self.add_button, (self.url_entry, )) elif self.num in (2, 3, 4): self.hide_widgets() self.add_button.show() self.user_hbox.show() self.pass_hbox.show() if self.num == 2: self.google_align.show() self.do_sensitive(self.add_button, (self.user_entry, self.pass_entry), (self.greader_check, self.gwave_check)) elif self.num == 4: self.twitter_align.show() self.do_sensitive( self.add_button, (self.user_entry, self.pass_entry), (self.twitter_timeline_check, self.twitter_replies_check)) else: self.do_sensitive(self.add_button, (self.user_entry, self.pass_entry)) def check_toggled(self, check): if check in (self.greader_check, self.gwave_check): self.do_sensitive(self.add_button, (self.user_entry, self.pass_entry), (self.greader_check, self.gwave_check)) elif check in (self.twitter_timeline_check, self.twitter_replies_check): self.do_sensitive( self.add_button, (self.user_entry, self.pass_entry), (self.twitter_timeline_check, self.twitter_replies_check)) def close(self, button): self.destroy() def do_search(self, button): #Clear the results vbox for child in self.results_vbox.get_children(): child.destroy() query = self.search_entry.get_text() self.search_throbber.props.active = True self.google_source.get_search_results(query, self.got_search, self.search_error) def search_error(self, *args): self.got_results = False self.search_throbber.props.active = False image = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_MENU) label = gtk.Label( _("There was an error while searching.\nPlease try again later.")) hbox = gtk.HBox(False, 6) hbox.set_border_width(6) hbox.pack_start(image, False) hbox.pack_start(label, False) #Center the box hboxbox = gtk.HBox(False, 0) hboxbox.pack_start(hbox, True, False) self.results_vbox.pack_start(hboxbox, False) self.results_sw.show() self.results_vbox.show_all() def got_search(self, results): hsep = None self.got_results = True self.search_throbber.props.active = False for result in results: if result['url'] not in self.applet.urls: add = gtk.Button(stock=gtk.STOCK_ADD) add.url = result['url'] add.connect('clicked', self.add_search_result) add_vbox = gtk.VBox(False, 0) add_vbox.pack_start(add, True, False) label = gtk.Label(result['title']) label.set_line_wrap(True) hbox = gtk.HBox(False, 6) hbox.set_border_width(6) hbox.pack_start(add_vbox, False) hbox.pack_start(label, False) self.results_vbox.pack_start(hbox, False) hsep = gtk.HSeparator() self.results_vbox.pack_start(hsep, False) #Destroy the last hseparator if hsep: hsep.destroy() #No results at all else: image = gtk.image_new_from_stock(gtk.STOCK_DIALOG_ERROR, gtk.ICON_SIZE_MENU) label = gtk.Label( _("No results found.\nTry checking your spelling or using different search terms." )) label.set_line_wrap(True) hbox = gtk.HBox(False, 6) hbox.pack_start(image, False) hbox.pack_start(label, False) #Center the box hboxbox = gtk.HBox(False, 0) hboxbox.pack_start(hbox, True, False) self.results_vbox.pack_start(hboxbox, False) self.results_sw.set_size_request(300, 200) self.results_sw.show() self.results_vbox.show_all() def add_search_result(self, button): button.parent.set_sensitive(False) self.applet.add_feed(button.url) if self.prefs is not None: self.prefs.update_liststore() def hide_widgets(self): self.search_button.hide() self.search_hbox.hide() self.search_msg.hide() self.add_button.hide() self.url_hbox.hide() self.user_hbox.hide() self.pass_hbox.hide() self.results_sw.hide() self.google_align.hide() self.twitter_align.hide() #All entries need to have non-empty text #At least one check needs to be active def do_sensitive(self, button, entries=[], checks=[]): button.set_sensitive(True) for entry in entries: if entry.get_text().strip() == '': button.set_sensitive(False) return if len(checks) == 0: return for check in checks: if check.get_active(): return button.set_sensitive(False) def get_radio_hbox(self, pb, text, siteid=None): image = gtk.image_new_from_pixbuf(pb) if siteid is not None: self.site_images[siteid] = image label = gtk.Label(text) hbox = gtk.HBox(False, 3) hbox.pack_start(image, False) hbox.pack_start(label, False) return hbox
import gtk theme = gtk.icon_theme_get_default() part_icon = theme.load_icon(gtk.STOCK_PREFERENCES, 16, 0) mount_icon = theme.load_icon(gtk.STOCK_GOTO_TOP, 16, 0) unmount_icon = theme.load_icon(gtk.STOCK_COPY, 16, 0) buff_icons = { 1000: theme.load_icon(gtk.STOCK_HOME, 16, 0), 2000: unmount_icon, 2001: mount_icon, 10: theme.load_icon(gtk.STOCK_ADD, 16, 0), -1: theme.load_icon(gtk.STOCK_DELETE, 16, 0) } task_queue_icons = {0: mount_icon, 1: unmount_icon}
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import os import gtk import gnomevfs ICONS_CACHE = {} ICON_THEME = gtk.icon_theme_get_default() ICON_LIST = ICON_THEME.list_icons() FOLDER_ICON = gtk.Image().render_icon(gtk.STOCK_DIRECTORY, gtk.ICON_SIZE_MENU) FILE_ICON = gtk.Image().render_icon(gtk.STOCK_FILE, gtk.ICON_SIZE_MENU) def get_imagename(mime): if mime in ICON_LIST: return mime mime1 = mime.replace('/', '-') if mime1 in ICON_LIST: return mime1 mime2 = mime.replace('/', '-x-') if mime2 in ICON_LIST: return mime2 return gtk.STOCK_FILE
def lookupIcon(icon_name): icon_theme = gtk.icon_theme_get_default() return icon_theme.lookup_icon(icon_name, 48, 0).get_filename()
def __init__(self, uid, panel_id): self.network_handler = self.NetworkHandler() self.tokens = classes.Tokens() self.favicons = classes.Tokens(cache_index) #AWN Applet Configuration awn.AppletSimple.__init__(self, 'feeds', uid, panel_id) self.set_tooltip_text(_("Loading feeds...")) self.dialog = awn.Dialog(self) self.main_vbox = gtk.VBox(False, False) self.dialog.add(self.main_vbox) self.main_vbox.show() #Need icon theme self.icon_theme = gtk.icon_theme_get_default() self.icon_theme.connect('changed', self.icon_theme_changed) #Get a 16x16 icon representing the Internet/web self.web_image = self.icon_theme.load_icon('applications-internet', 16, 0) #Force a size of 16x16 if self.web_image.get_width() != 16 or self.web_image.get_height() != 16: self.web_image = self.web_image.scale_simple(16, 16, gtk.gdk.INTERP_BILINEAR) #Throbber overlay self.throbber = awn.OverlayThrobber() self.throbber.props.gravity = gtk.gdk.GRAVITY_SOUTH_WEST #Error icon overlay self.error_icon = awn.OverlayThemedIcon("gtk-dialog-error") self.error_icon.props.gravity = gtk.gdk.GRAVITY_SOUTH_WEST #First updated feed favicon (bottom right) self.favicon1 = awn.OverlayPixbuf(self.web_image) self.favicon1.props.gravity = gtk.gdk.GRAVITY_SOUTH_EAST #Second updated feed favicon (bottom) self.favicon2 = awn.OverlayPixbuf(self.web_image) self.favicon2.props.gravity = gtk.gdk.GRAVITY_SOUTH #Third updated feed favicon (right) self.favicon3 = awn.OverlayPixbuf(self.web_image) self.favicon3.props.gravity = gtk.gdk.GRAVITY_EAST for overlay in (self.throbber, self.error_icon, self.favicon1, self.favicon2, self.favicon3): if self.get_size() > 48: overlay.props.scale = 16.0 / self.get_size() else: overlay.props.scale = 0.33 overlay.props.apply_effects = True overlay.props.active = False self.add_overlay(overlay) #Magic at work. Position the 2nd and 3rd favicons adjacent to the icon if self.get_size() > 48: self.favicon2.props.x_adj = 0.5 - 24.0 / self.get_size() self.favicon3.props.y_adj = 0.5 - 24.0 / self.get_size() else: self.favicon2.props.x_adj = 0.0 self.favicon3.props.y_adj = 0.0 #"Loading feeds..." label self.loading_feeds = gtk.Label(_("Loading feeds...")) self.loading_feeds.modify_font(pango.FontDescription('bold')) self.main_vbox.pack_start(self.loading_feeds, False, False, 3) self.loading_feeds.show() self.loading_feeds.set_no_show_all(True) #No feeds label self.no_feeds = gtk.Label(_("You don't have any feeds.")) self.main_vbox.pack_start(self.no_feeds) self.no_feeds.set_no_show_all(True) #AwnConfigClient instance self.client = awn.config_get_default_for_applet(self) #Connect to signals self.connect('button-press-event', self.button_press) self.dialog.props.hide_on_unfocus = True self.get_urls() #TODO: put this and the similar code in add_feed() into a single, better place for url in self.urls: _base_url = '-'.join(url.split('-')[:-1]) username = url.split('-')[-1] if _base_url == 'google-reader': self.feeds[url] = classes.GoogleReader(self, username) elif _base_url == 'google-wave': self.feeds[url] = classes.GoogleWave(self, username) elif _base_url == 'reddit': self.feeds[url] = classes.Reddit(self, username) elif _base_url in ('twitter-timeline', 'twitter-both', 'twitter-replies'): self.feeds[url] = classes.Twitter(self, username, None, base_url=_base_url) else: self.feeds[url] = classes.WebFeed(self, url) #Set the icon only_greader = bool(len(self.urls)) for feed in self.feeds.values(): if not isinstance(feed, classes.GoogleReader): only_greader = False break self.set_icon_name(['awn-feeds', 'awn-feeds-greader'][only_greader]) self.setup_dialog() #Allow user to drag and drop feed URLs onto the applet icon #E.g. In a browser, user drags and drops a link to an Atom feed onto the applet self.get_icon().drag_dest_set(gtk.DEST_DEFAULT_DROP | gtk.DEST_DEFAULT_MOTION, \ [("STRING", 0, 0), ("text/plain", 0, 0), ("text/uri-list", 0, 0)], \ gtk.gdk.ACTION_COPY) self.get_icon().connect('drag_data_received', self.applet_drag_data_received) self.get_icon().connect('drag-motion', self.applet_drag_motion) self.get_icon().connect('drag-leave', self.applet_drag_leave) self.dialog.connect('scroll-event', self.scroll) self.connect('size-changed', self.size_changed) #Set up the D-Bus service self.service = classes.DBusService(self) self.update_feeds()
def __init__(self, handle, create_jobject=True): """Initialise the Activity handle -- sugar.activity.activityhandle.ActivityHandle instance providing the activity id and access to the presence service which *may* provide sharing for this application create_jobject -- boolean define if it should create a journal object if we are not resuming Side effects: Sets the gdk screen DPI setting (resolution) to the Sugar screen resolution. Connects our "destroy" message to our _destroy_cb method. Creates a base gtk.Window within this window. Creates an ActivityService (self._bus) servicing this application. Usage: If your Activity implements __init__(), it should call the base class __init()__ before doing Activity specific things. """ # Stuff that needs to be done early icons_path = os.path.join(get_bundle_path(), 'icons') gtk.icon_theme_get_default().append_search_path(icons_path) sugar_theme = 'sugar-72' if 'SUGAR_SCALING' in os.environ: if os.environ['SUGAR_SCALING'] == '100': sugar_theme = 'sugar-100' # This code can be removed when we grow an xsettings daemon (the GTK+ # init routines will then automatically figure out the font settings) settings = gtk.settings_get_default() settings.set_property('gtk-font-name', '%s %f' % (style.FONT_FACE, style.FONT_SIZE)) settings.set_property('gtk-theme-name', sugar_theme) settings.set_property('gtk-icon-theme-name', 'sugar') settings.set_property( 'gtk-icon-sizes', 'gtk-large-toolbar=%s,%s' % (style.STANDARD_ICON_SIZE, style.STANDARD_ICON_SIZE)) Window.__init__(self) if 'SUGAR_ACTIVITY_ROOT' in os.environ: # If this activity runs inside Sugar, we want it to take all the # screen. Would be better if it was the shell to do this, but we # haven't found yet a good way to do it there. See #1263. self.connect('window-state-event', self.__window_state_event_cb) screen = gtk.gdk.screen_get_default() screen.connect('size-changed', self.__screen_size_changed_cb) self._adapt_window_to_screen() # process titles will only show 15 characters # but they get truncated anyway so if more characters # are supported in the future we will get a better view # of the processes proc_title = '%s <%s>' % (get_bundle_name(), handle.activity_id) util.set_proc_title(proc_title) self.connect('realize', self.__realize_cb) self.connect('delete-event', self.__delete_event_cb) self._active = False self._activity_id = handle.activity_id self.shared_activity = None self._join_id = None self._updating_jobject = False self._closing = False self._quit_requested = False self._deleting = False self._max_participants = 0 self._invites_queue = [] self._jobject = None self._read_file_called = False self._session = _get_session() self._session.register(self) self._session.connect('quit-requested', self.__session_quit_requested_cb) self._session.connect('quit', self.__session_quit_cb) accel_group = gtk.AccelGroup() self.set_data('sugar-accel-group', accel_group) self.add_accel_group(accel_group) self._bus = ActivityService(self) self._owns_file = False share_scope = SCOPE_PRIVATE if handle.object_id: self._jobject = datastore.get(handle.object_id) if 'share-scope' in self._jobject.metadata: share_scope = self._jobject.metadata['share-scope'] if 'launch-times' in self._jobject.metadata: self._jobject.metadata['launch-times'] += ', %d' % \ int(time.time()) else: self._jobject.metadata['launch-times'] = \ str(int(time.time())) self.shared_activity = None self._join_id = None if handle.object_id is None and create_jobject: logging.debug('Creating a jobject.') self._jobject = self._initialize_journal_object() if handle.invited: wait_loop = gobject.MainLoop() self._client_handler = _ClientHandler( self.get_bundle_id(), partial(self.__got_channel_cb, wait_loop)) # FIXME: The current API requires that self.shared_activity is set # before exiting from __init__, so we wait until we have got the # shared activity. http://bugs.sugarlabs.org/ticket/2168 wait_loop.run() else: pservice = presenceservice.get_instance() mesh_instance = pservice.get_activity(self._activity_id, warn_if_none=False) self._set_up_sharing(mesh_instance, share_scope) if not create_jobject: self.set_title(get_bundle_name()) return if self.shared_activity is not None: self._jobject.metadata['title'] = self.shared_activity.props.name self._jobject.metadata['icon-color'] = \ self.shared_activity.props.color else: self._jobject.metadata.connect('updated', self.__jobject_updated_cb) self.set_title(self._jobject.metadata['title']) bundle = get_bundle_instance(get_bundle_path()) self.set_icon_from_file(bundle.get_icon())
def __init__(self): #gtk entry self.entry1 = gtk.Entry() self.entry2 = gtk.Entry() self.entry3 = gtk.Entry() self.entry4 = gtk.Entry() self.entry5 = gtk.Entry() #gtk label self.out1 = gtk.Label() self.out2 = gtk.Label() self.out3 = gtk.Label() self.out4 = gtk.Label() self.out5 = gtk.Label() self.out6 = gtk.Label() self.out7 = gtk.Label() self.out8 = gtk.Label() self.out9 = gtk.Label() self.out10 = gtk.Label() self.out11 = gtk.Label() self.out12 = gtk.Label() labelA = gtk.Label('') labelA.set_markup('<b>PENDAPATAN</b>') labelB = gtk.Label('') labelB.set_markup('<b>ZAKAT PENGHASILAN</b>') labelC = gtk.Label('') labelC.set_markup('<b>ZAKAT SIMPANAN</b>') label1 = gtk.Label("Pendapatan / gaji (per bulan)") label2 = gtk.Label("Pendapatan lain (per bulan)") label3 = gtk.Label("Pendapatan total (per tahun)") label4 = gtk.Label("Kebutuhan (per bulan)") label5 = gtk.Label("Kebutuhan total (per tahun)") label6 = gtk.Label("Sisa pendapatan") label7 = gtk.Label("Harga beras saat ini (per Kg)") label8 = gtk.Label("Besarnya nishab") label9 = gtk.Label("Wajib zakat penghasilan ?") label10 = gtk.Label("Besarnya zakat penghasilan yang harus dibayarkan") label11 = gtk.Label("Zakat Per tahun") label12 = gtk.Label("Zakat Per bulan") label13 = gtk.Label("Harga emas saat ini (per gram)") label14 = gtk.Label("Besarnya nishab") label15 = gtk.Label("Wajib zakat simpanan ?") label16 = gtk.Label("Besarnya zakat simpanan yang harus dibayarkan") label17 = gtk.Label("Zakat Per tahun") label18 = gtk.Label("Zakat Per bulan") #gtk button button1 = gtk.Button(stock='gtk-about') button2 = gtk.Button("_Hitung Zakat") button3 = gtk.Button(stock='gtk-clear') button4 = gtk.Button(stock='gtk-close') #vbox vbox1 = gtk.VBox(False, 5) vbox2 = gtk.VBox(False, 5) #buttonbox buttonbox = gtk.HButtonBox() buttonbox.set_spacing(15) buttonbox.set_layout(gtk.BUTTONBOX_CENTER) buttonbox.add(button1) buttonbox.add(button2) buttonbox.add(button3) buttonbox.add(button4) #image pixbuf = gtk.gdk.pixbuf_new_from_file( "/usr/share/zacalc/image/logo.png") image = gtk.Image() image.set_from_pixbuf(pixbuf) image.show() #table table1 = gtk.Table(1, 6, True) table2 = gtk.Table(1, 6, True) #frame frame = gtk.Frame() frame.set_shadow_type(gtk.SHADOW_ETCHED_IN) #align align1 = gtk.Alignment(0.5, 0.3, 0, 0) align2 = gtk.Alignment(0.5, 0.1, 0, 0) align3 = gtk.Alignment(0.5, 0.5, 0, 0) #layout inserting vbox1.add(frame) vbox1.add(buttonbox) frame.add(align1) align1.add(table1) align3.add(vbox2) align2.add(table2) table1.attach(image, 3, 6, 0, 10) table1.attach(labelA, 0, 3, 0, 1) table1.attach(label1, 0, 2, 1, 2) table1.attach(label2, 0, 2, 2, 3) table1.attach(label3, 0, 2, 3, 4) table1.attach(label4, 0, 2, 4, 5) table1.attach(label5, 0, 2, 5, 6) table1.attach(label6, 0, 2, 6, 7) table1.attach(self.entry1, 2, 3, 1, 2) table1.attach(self.entry2, 2, 3, 2, 3) table1.attach(self.out1, 2, 3, 3, 4) table1.attach(self.entry3, 2, 3, 4, 5) table1.attach(self.out2, 2, 3, 5, 6) table1.attach(self.out3, 2, 3, 6, 7) table1.attach(labelB, 0, 3, 8, 9) table1.attach(label7, 0, 2, 9, 10) table1.attach(label8, 0, 2, 10, 11) table1.attach(label9, 0, 2, 11, 12) table1.attach(label10, 0, 3, 12, 13) table1.attach(self.entry4, 2, 3, 9, 10) table1.attach(self.out4, 2, 3, 10, 11) table1.attach(self.out5, 2, 3, 11, 12) table1.attach(label11, 0, 2, 13, 14) table1.attach(label12, 0, 2, 14, 15) table1.attach(self.out6, 2, 3, 13, 14) table1.attach(self.out7, 2, 3, 14, 15) table1.attach(labelC, 3, 5, 8, 9) table1.attach(label13, 3, 5, 9, 10) table1.attach(label14, 3, 5, 10, 11) table1.attach(label15, 3, 5, 11, 12) table1.attach(label16, 3, 6, 12, 13) table1.attach(self.entry5, 5, 6, 9, 10) table1.attach(self.out8, 5, 6, 10, 11) table1.attach(self.out9, 5, 6, 11, 12) table1.attach(label17, 3, 5, 13, 14) table1.attach(label18, 3, 5, 14, 15) table1.attach(self.out10, 5, 6, 13, 14) table1.attach(self.out11, 5, 6, 14, 15) #property frame.set_label('') self.clear_value(self) self.out1.set_alignment(xalign=0.95, yalign=0.5) self.out2.set_alignment(xalign=0.95, yalign=0.5) self.out3.set_alignment(xalign=0.95, yalign=0.5) self.out4.set_alignment(xalign=0.95, yalign=0.5) self.out5.set_alignment(xalign=0.05, yalign=0.5) self.out6.set_alignment(xalign=0.95, yalign=0.5) self.out7.set_alignment(xalign=0.95, yalign=0.5) self.out8.set_alignment(xalign=0.95, yalign=0.5) self.out9.set_alignment(xalign=0.05, yalign=0.5) self.out10.set_alignment(xalign=0.95, yalign=0.5) self.out11.set_alignment(xalign=0.95, yalign=0.5) labelA.set_alignment(xalign=0, yalign=0.5) labelB.set_alignment(xalign=0, yalign=0.5) labelC.set_alignment(xalign=0, yalign=0.5) label1.set_alignment(xalign=0, yalign=0.5) label2.set_alignment(xalign=0, yalign=0.5) label3.set_alignment(xalign=0, yalign=0.5) label4.set_alignment(xalign=0, yalign=0.5) label5.set_alignment(xalign=0, yalign=0.5) label6.set_alignment(xalign=0, yalign=0.5) label7.set_alignment(xalign=0, yalign=0.5) label8.set_alignment(xalign=0, yalign=0.5) label9.set_alignment(xalign=0, yalign=0.5) label10.set_alignment(xalign=0, yalign=0.5) label11.set_alignment(xalign=0, yalign=0.5) label12.set_alignment(xalign=0, yalign=0.5) label13.set_alignment(xalign=0, yalign=0.5) label14.set_alignment(xalign=0, yalign=0.5) label15.set_alignment(xalign=0, yalign=0.5) label16.set_alignment(xalign=0, yalign=0.5) label17.set_alignment(xalign=-0, yalign=0.5) label18.set_alignment(xalign=-0, yalign=0.5) image.set_alignment(xalign=0, yalign=0.5) table1.set_col_spacings(30) align1.set_padding(5, 5, 15, 15) table2.set_col_spacings(0) align2.set_padding(0, 0, 0, 0) #signal self.entry1.connect("changed", self.valid_number) self.entry2.connect("changed", self.valid_number) self.entry3.connect("changed", self.valid_number) self.entry4.connect("changed", self.valid_number) self.entry5.connect("changed", self.valid_number) button1.connect("clicked", self.show_about) button2.connect("clicked", self.calculate) button3.connect("clicked", self.clear_value) button4.connect("clicked", gtk.main_quit) icon_theme = gtk.icon_theme_get_default() try: self.icon = icon_theme.load_icon("zacalc", 48, 0) except Exception, e: print "can't load icon", e
def __init__(self): GetSettings() self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_resizable(True) self.window.connect("destroy", self.destroy_equalizer) self.window.set_title(windowtitle + " [" + realstatus + "]") self.window.set_border_width(0) icon_theme = gtk.icon_theme_get_default() icon_theme = gtk.icon_theme_get_default() if icon_theme.has_icon("multimedia-volume-control"): icon = icon_theme.load_icon("multimedia-volume-control", 16, 0) self.window.set_icon(icon) elif icon_theme.has_icon("gnome-volume-control"): icon = icon_theme.load_icon("gnome-volume-control", 16, 0) self.window.set_icon(icon) elif icon_theme.has_icon("stock_volume"): icon = icon_theme.load_icon("stock_volume", 16, 0) self.window.set_icon(icon) else: print("No icon found, window will be iconless") menu = gtk.Menu() menu_item = gtk.MenuItem('Reset to defaults') menu_item.connect("activate", self.on_resetsettings) menu.append(menu_item) menu_item.show() menu_item = gtk.MenuItem('Remove user preset...') menu_item.connect("activate", self.on_removepreset) menu.append(menu_item) menu_item.show() root_menu = gtk.MenuItem("Advanced") root_menu.show() root_menu.set_submenu(menu) vbox1 = gtk.VBox(False, 0) self.window.add(vbox1) vbox1.show() menu_bar = gtk.MenuBar() vbox1.pack_start(menu_bar, False, False, 2) menu_bar.show() menu_bar.append(root_menu) hbox1 = gtk.HBox(False, 1) #hbox1.set_border_width(10) vbox1.add(hbox1) hbox1.show() table = gtk.Table(3, 17, False) table.set_border_width(5) hbox1.add(table) # Preamp widget global preampscale global preampscalevalue preampscale = gtk.VScale() preampscale.set_draw_value(0) preampscale.set_inverted(1) preampscale.set_value_pos(gtk.POS_BOTTOM) preampscale.set_range(0.0, 2.0) preampscale.set_increments(1, 0.1) preampscale.set_digits(1) preampscale.set_size_request(35, 200) preampscale.set_value(float(preamp)) preampscale.connect("value-changed", self.on_preampscale) label = gtk.Label() label.set_markup("<small>Preamp</small>") preampscalevalue = gtk.Label() preampscalevalue.set_markup(str(preampscale.get_value()) + "x") table.attach(label, 1, 2, 0, 1) table.attach(preampscale, 1, 2, 1, 2) table.attach(preampscalevalue, 1, 2, 2, 3) #label.show() #preampscale.show() #preampscalevalue.show() # Separator between preamp and bands separator = gtk.VSeparator() table.attach(separator, 2, 3, 1, 2) #separator.show() # Equalizer bands global scale self.scales = {} self.labels = {} self.scalevalues = {} for x in range(1, num_ladspa_controls + 1): scale = gtk.VScale() self.scales[x] = scale scale.set_draw_value(0) scale.set_inverted(1) scale.set_value_pos(gtk.POS_BOTTOM) scale.set_range(float(ranges[0]), float(ranges[1])) scale.set_increments(1, 0.1) scale.set_digits(1) scale.set_size_request(35, 200) scale.set_value(float(ladspa_controls[x - 1])) scale.connect("value-changed", self.on_scale, x) FormatLabels(x) label = gtk.Label() self.labels[x] = label label.set_markup("<small>" + whitespace1 + c + "\n" + whitespace2 + suffix + "</small>") scalevalue = gtk.Label() self.scalevalues[x] = scalevalue scalevalue.set_markup("<small>" + str(scale.get_value()) + "\ndB</small>") table.attach(label, x + 2, x + 3, 0, 1) table.attach(scale, x + 2, x + 3, 1, 2) table.attach(scalevalue, x + 2, x + 3, 2, 3) label.show() scale.show() scalevalue.show() table.show() vbox2 = gtk.VBox(True, 1) vbox2.set_border_width(10) hbox1.add(vbox2) vbox2.show() presetslabel = gtk.Label() presetslabel.set_markup("<small>Preset:</small>") vbox2.pack_start(presetslabel, False, False, 0) presetslabel.show() global presetsbox presetsbox = gtk.combo_box_entry_new_text() vbox2.pack_start(presetsbox, False, False, 0) presetsbox.get_child().set_text(preset) for i in range(len(rawpresets)): presetsbox.append_text(rawpresets[i]) presetsbox.connect("changed", self.on_presetsbox, x) presetsbox.show() savepreset = gtk.Button('Save Preset') vbox2.pack_start(savepreset, False, False, 0) savepreset.connect("clicked", self.on_savepreset) savepreset.show() global eqenabled eqenabled = gtk.CheckButton("EQ Enabled") eqenabled.set_active(status) eqenabled.unset_flags(gtk.CAN_FOCUS) eqenabled.connect("clicked", self.on_eqenabled) vbox2.pack_start(eqenabled, False, False, 0) eqenabled.show() global keepsettings keepsettings = gtk.CheckButton('Keep Settings') keepsettings.set_active(persistence) keepsettings.unset_flags(gtk.CAN_FOCUS) keepsettings.connect("clicked", self.on_keepsettings) vbox2.pack_start(keepsettings, False, False, 0) keepsettings.show() applysettings = gtk.Button('Apply Settings') vbox2.pack_start(applysettings, False, False, 0) applysettings.connect("clicked", self.on_applysettings) applysettings.show() quitbutton = gtk.Button('Quit') vbox2.pack_start(quitbutton, False, False, 0) quitbutton.connect("clicked", lambda w: gtk.main_quit()) quitbutton.show() separator = gtk.HSeparator() vbox2.pack_start(separator, False, False, 0) separator.set_size_request(100, 10) #separator.show() self.window.show()
def __init__(self): self.DEBUG = DEBUG self.util = util self.PATH = self.util.get_path() self.LOGO_PATH = os.path.join(self.PATH, "icons/specto.svg") self.SRC_PATH = self.util.get_path("src") self.SPECTO_DIR = self.util.get_path("specto") self.CACHE_DIR = self.util.get_path("tmp") self.FILE = self.util.get_file() self.logger = Logger(self) self.VERSION = VERSION # The Specto version number self.GTK = GTK if not self.check_instance(): #see if specto is already running self.specto_gconf = specto_gconf self.check_default_settings() self.connection_manager = conmgr.get_net_listener() self.use_keyring = self.specto_gconf.get_entry("use_keyring") #create the watch collection and add the watches self.watch_db = Watch_collection(self) self.watch_io = Watch_io(self, self.FILE) if (sys.argv[1:] and "--console" in sys.argv[1:][0]) or not self.GTK: self.logger.log(_("Console mode enabled."), "debug", "specto") self.GTK = False self.CONSOLE = True try: args = sys.argv[1:][1] except: args = "" self.console = Console(self, args) elif self.GTK: self.GTK = True self.CONSOLE = False self.icon_theme = gtk.icon_theme_get_default() #allow users to hide the window on startup if sys.argv[1:] and "--no-window" in sys.argv[1:][0]: self.notifier_hide = True #always show if there's no icon and no indicator support elif self.specto_gconf.get_entry( "always_show_icon") == False and not INDICATOR: self.notifier_hide = False elif self.specto_gconf.get_entry("show_notifier") == True: self.notifier_hide = False elif self.specto_gconf.get_entry("show_notifier") == False: self.notifier_hide = True else: #just in case the entry was never created in gconf self.notifier_keep_hidden = False self.notifier = Notifier(self) else: sys.exit(0) #listen for gconf keys self.specto_gconf.notify_entry("debug_mode", self.key_changed, "debug") values = self.watch_io.read_all_watches(True) try: self.watch_db.create(values) except AttributeError as error_fields: self.logger.log(_("Could not create a watch, because it is corrupt."), \ "critical", "specto") if self.GTK: for watch in self.watch_db: self.notifier.add_notifier_entry(watch.id) # Listen for USR1. If received, answer and show the window def listen_for_USR1(signum, frame): f = open(self.SPECTO_DIR + "/" + "specto.pid.boot") pid = int(f.readline()) f.close() os.kill(pid, signal.SIGUSR1) # If window was not shown, make it appear if not self.notifier.get_state(): self.logger.log( "Showing window, the user ran another instance of specto", "debug", "specto") self.toggle_notifier() else: # Based on http://www.pygtk.org/docs/pygtk/class-gtkwindow.html#method-gtkwindow--present self.logger.log( "Window is already visible! Raising it to the front.", "debug", "specto") self.notifier.notifier.present() signal.signal(signal.SIGUSR1, listen_for_USR1) self.notifier.refresh_all_watches() else: self.console.start_watches() if self.GTK: gtk.main() else: try: self.go = gobject.MainLoop() self.go.run() except (KeyboardInterrupt, SystemExit): sys.exit(0)
def __init__(self, message="", default_text='', modal=True): gtk.Dialog.__init__(self) self.add_buttons(gtk.STOCK_CANCEL, gtk.RESPONSE_CLOSE, gtk.STOCK_OK, gtk.RESPONSE_ACCEPT) #self.set_title("Icon search") if modal: self.set_modal(True) self.set_border_width(5) self.set_size_request(400, 300) self.combobox=gtk.combo_box_new_text() self.combobox.set_size_request(200, 20) hbox=gtk.HBox(False,2) #format: actual icon, name, context #self.model=gtk.ListStore(gtk.gdk.Pixbuf, gobject.TYPE_STRING, gobject.TYPE_STRING) #self.modelfilter=self.model.filter_new() self.modelfilter=ICON_STORE.filter_new() self.iconview=gtk.IconView() self.iconview.set_model(self.modelfilter) self.iconview.set_pixbuf_column(0) self.iconview.set_text_column(1) self.iconview.set_selection_mode(gtk.SELECTION_SINGLE) self.iconview.set_item_width(72) self.iconview.set_size_request(200, 220) defaulttheme=gtk.icon_theme_get_default() self.combobox.connect('changed', self.category_changed) self.refine=gtk.Entry() self.refine.connect('changed', self.category_changed) self.refine.set_icon_from_stock(gtk.ENTRY_ICON_SECONDARY, gtk.STOCK_FIND) self.refine.set_size_request(200, 30) self.modelfilter.set_visible_func(self.search_icons) #catted_icons=[] for c in defaulttheme.list_contexts(): #current=defaulttheme.list_icons(context=c) #catted_icons+=set(current) self.combobox.append_text(c) #for i in current: # try: # self.model.append([defaulttheme.load_icon(i, 32, # gtk.ICON_LOOKUP_USE_BUILTIN), # i,c]) # except GError as err: stderr.write('Error loading "%s": %s\n' % (i, err.args[0])) #other=list(set(defaulttheme.list_icons())-(set(catted_icons))) #for i in other: # self.model.append([defaulttheme.load_icon(i, 32, # gtk.ICON_LOOKUP_USE_BUILTIN), # i,"Other"]) self.combobox.prepend_text("Other") scrolled = gtk.ScrolledWindow() scrolled.add(self.iconview) scrolled.props.hscrollbar_policy = gtk.POLICY_NEVER scrolled.props.vscrollbar_policy = gtk.POLICY_AUTOMATIC hbox.add(self.combobox) hbox.add(self.refine) self.vbox.add(hbox) self.vbox.add(scrolled) self.combobox.set_active(0) self.iconview.connect('selection-changed', self.get_icon_name) self.vbox.show_all()
def __init__(self): self.icon_theme = gtk.icon_theme_get_default() self.icon_theme.append_search_path(Config.icon_file_directory)
class Prefs(gtk.Window): icon_theme = gtk.icon_theme_get_default() show_only_new_check = None def __init__(self, applet): self.applet = applet gtk.Window.__init__(self) self.set_title(_("Feeds Applet Preferences")) self.set_icon_from_file(icon_path) self.set_border_width(12) vbox = gtk.VBox(False, 12) tab_feeds_vbox = gtk.VBox(False, 6) tab_updating_vbox = gtk.VBox(False, 6) self.notebook = gtk.Notebook() self.notebook.append_page(tab_feeds_vbox, gtk.Label(_("Feeds"))) self.notebook.append_page(tab_updating_vbox, gtk.Label(_("Updating"))) vbox.pack_start(self.notebook, True, True, 0) #Feeds: Add/Remove, with a TreeView for displaying self.liststore = gtk.ListStore(gtk.gdk.Pixbuf, str, str) pb_renderer = gtk.CellRendererPixbuf() text_renderer = gtk.CellRendererText() column = gtk.TreeViewColumn(' ') column.pack_start(pb_renderer, False) column.pack_start(text_renderer, True) column.add_attribute(pb_renderer, 'pixbuf', 0) column.add_attribute(text_renderer, 'markup', 1) self.treeview = gtk.TreeView(self.liststore) self.treeview.append_column(column) self.treeview.set_headers_visible(False) self.treeview.get_selection().connect('changed', self.selection_changed) sw = gtk.ScrolledWindow() sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.add_with_viewport(self.treeview) sw.set_size_request(225, 200) #Remove and add buttons self.remove_button = gtk.Button(stock=gtk.STOCK_REMOVE) self.remove_button.set_sensitive(False) self.remove_button.connect('clicked', self.remove_feed) add_button = gtk.Button(stock=gtk.STOCK_ADD) add_button.connect('clicked', self.show_add) buttons_hbox = gtk.HButtonBox() buttons_hbox.set_layout(gtk.BUTTONBOX_EDGE) buttons_hbox.pack_end(add_button, False) buttons_hbox.pack_end(self.remove_button, False) show_favicons_check = gtk.CheckButton(_("_Show website icons")) if self.applet.client.get_bool(GROUP_DEFAULT, 'show_favicons'): show_favicons_check.set_active(True) show_favicons_check.connect('toggled', self.check_toggled, 'show_favicons') self.show_only_new_check = gtk.CheckButton(_("Show _only new feeds")) if self.applet.client.get_bool(GROUP_DEFAULT, 'show_only_new'): self.show_only_new_check.set_active(True) self.show_only_new_check.connect('toggled', self.check_toggled, 'show_only_new') #TODO: this position is a little ugly, but I don't know how to do it better. #Import and export buttons (OPML) import_button = gtk.Button(_("Import")) import_button.connect('clicked', self.do_import) self.export_button = gtk.Button(_("Export")) self.export_button.connect('clicked', self.do_export) sensitive = False for url, feed in self.applet.feeds.items(): if isinstance(feed, classes.WebFeed): sensitive = True break self.export_button.set_sensitive(sensitive) buttons_hbox2 = gtk.HButtonBox() buttons_hbox2.set_layout(gtk.BUTTONBOX_EDGE) buttons_hbox2.pack_end(import_button, False) buttons_hbox2.pack_end(self.export_button, False) feeds_vbox = gtk.VBox(False, 6) feeds_vbox.pack_start(sw) feeds_vbox.pack_start(buttons_hbox, False) feeds_vbox.pack_start(show_favicons_check, False) feeds_vbox.pack_start(self.show_only_new_check, False) feeds_vbox.pack_start(buttons_hbox2, False) feeds_vbox.set_border_width(12) tab_feeds_vbox.pack_start(feeds_vbox) #Updating section (enable/disable automatically updating and change how often) #Checkbox: Notify for updated feeds check_notify = gtk.CheckButton(_("_Notify for updated feeds")) if self.applet.client.get_bool(GROUP_DEFAULT, 'notify'): check_notify.set_active(True) check_notify.connect('toggled', self.check_toggled, 'notify') #Checkbox: Update automatically check_auto = gtk.CheckButton(_("_Update automatically")) if self.applet.client.get_bool(GROUP_DEFAULT, 'auto_update'): check_auto.set_active(True) check_auto.connect('toggled', self.check_toggled, 'auto_update') #Update every [SpinButton] minutes label_auto1 = gtk.Label(_("Update every ")) label_auto2 = gtk.Label(_(" minutes")) interval = self.applet.client.get_int(GROUP_DEFAULT, 'update_interval') auto_adj = gtk.Adjustment(interval, 3, 60, 1, 5, 0) auto_spin = gtk.SpinButton(auto_adj, 1) auto_spin.connect('focus-out-event', self.spin_focusout) hbox_auto = gtk.HBox(False, 0) hbox_auto.pack_start(label_auto1, False) hbox_auto.pack_start(auto_spin, False) hbox_auto.pack_start(label_auto2, False) keep_unread_check = gtk.CheckButton( _("Keep items unread when updating")) if self.applet.client.get_bool(GROUP_DEFAULT, 'keep_unread'): keep_unread_check.set_active(True) keep_unread_check.connect('toggled', self.check_toggled, 'keep_unread') auto_vbox = gtk.VBox(False, 6) auto_vbox.pack_start(check_notify, False) auto_vbox.pack_start(check_auto, False) auto_vbox.pack_start(hbox_auto, False) auto_vbox.pack_start(keep_unread_check, False) auto_vbox.set_border_width(12) tab_updating_vbox.pack_start(auto_vbox) #Close button in the bottom right corner close = gtk.Button(stock=gtk.STOCK_CLOSE) close.connect('clicked', self.deleted) close_hbox = gtk.HBox(False, 0) close_hbox.pack_end(close, False) vbox.pack_end(close_hbox, False) self.add(vbox) self.update_liststore() self.show_all() self.connect('delete-event', self.deleted) def deleted(self, widget, event=None): self.hide() self.notebook.set_current_page(0) return True #Feeds section def show_add(self, button): AddFeed(self) def remove_feed(self, button): sel = self.treeview.get_selection() url = self.liststore[sel.get_selected()[1]][2] self.applet.remove_feed(url) #This returns True if the iter is still valid #(i.e. the removed feed wasn't the bottom one) if not self.liststore.remove(sel.get_selected()[1]): self.remove_button.set_sensitive(False) sensitive = False for url, feed in self.applet.feeds.items(): if isinstance(feed, classes.WebFeed): sensitive = True break self.export_button.set_sensitive(sensitive) def selection_changed(self, sel): self.remove_button.set_sensitive(bool(sel.get_selected())) #Updating section def check_toggled(self, check, key): self.applet.client.set_value(GROUP_DEFAULT, key, check.get_active()) #If user had disabled automatically updating and just turned it on now, #start the timeout to update if key == 'auto_update': self.applet.do_timer() elif key == 'show_favicons': if check.get_active(): self.applet.show_favicons() else: self.applet.hide_favicons() elif key == 'show_only_new': self.applet.show_only_new() if self.applet.show_only_new_check is not None: self.applet.show_only_new_check.set_active(check.get_active()) def spin_focusout(self, spin, event): self.applet.client.set_value(GROUP_DEFAULT, 'update_interval', int(spin.get_value())) def update_liststore(self): self.liststore.clear() sensitive = False for url in self.applet.urls: feed = self.applet.feeds[url] if isinstance(feed, classes.WebFeed): sensitive = True pb = self.applet.get_favicon(feed.icon) if pb == self.applet.web_image: pb = None title = [feed.title, _("Loading...")][feed.title == ''] self.liststore.append([pb, title, url]) self.export_button.set_sensitive(sensitive) def do_import(self, button): file_chooser = gtk.FileChooserDialog(_("Open OPML File"), \ buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK), \ action=gtk.FILE_CHOOSER_ACTION_OPEN) file_chooser.set_icon_from_file(icon_path) response = file_chooser.run() filename = file_chooser.get_filename() file_chooser.destroy() if response != gtk.RESPONSE_OK: return False self.applet.load_opml(filename) def do_export(self, button): file_chooser = gtk.FileChooserDialog(_("Save OPML File"), \ buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK), \ action=gtk.FILE_CHOOSER_ACTION_SAVE) file_chooser.set_icon_from_file(icon_path) file_chooser.set_do_overwrite_confirmation(True) #Note: the following string is used as an exmaple filename file_chooser.set_current_name(_("feeds.opml")) response = file_chooser.run() filename = file_chooser.get_filename() file_chooser.destroy() if response != gtk.RESPONSE_OK: return False initial_text = [ '<?xml version="1.0" encoding="UTF-8"?>', '<opml version="1.0">', ' <head>', ' <title>%s</title>' % _("Awn Feeds Applet Items"), ' </head>', ' <body>' ] each_text = ' <outline title="%s" text="%s" htmlUrl="%s" type="rss" xmlUrl="%s" />' end_text = [' </body>', '</opml>'] feeds_text = [] for url, feed in self.applet.feeds.items(): if isinstance(feed, classes.WebFeed): title = html_safe(feed.title) web_url = html_safe(feed.web_url) url = html_safe(feed.url) feeds_text.append(each_text % (title, title, web_url, url)) try: with open(filename, 'w+') as fp: fp.write('\n'.join(initial_text + feeds_text + end_text)) except IOError, e: dialog = classes.ErrorDialog(self, _("Could not save '%s'") % filename, e) dialog.run() dialog.destroy()
def __init__(self, datadir=None, logdir=None): DistUpgradeView.__init__(self) self.logdir = logdir if not datadir or datadir == '.': localedir = os.path.join(os.getcwd(), "mo") gladedir = os.getcwd() else: localedir = "/usr/share/locale/" gladedir = os.path.join(datadir, "gtkbuilder") # check if we have a display etc gtk.init_check() try: locale.bindtextdomain("ubuntu-release-upgrader", localedir) gettext.textdomain("ubuntu-release-upgrader") except Exception as e: logging.warning("Error setting locales (%s)" % e) icons = gtk.icon_theme_get_default() try: gtk.window_set_default_icon( icons.load_icon("system-software-update", 32, 0)) except gobject.GError as e: logging.debug("error setting default icon, ignoring (%s)" % e) pass SimpleGtkbuilderApp.__init__(self, gladedir + "/DistUpgrade.ui", "ubuntu-release-upgrader") # terminal stuff self.create_terminal() self.prev_step = 0 # keep a record of the latest step # we don't use this currently #self.window_main.set_keep_above(True) self.icontheme = gtk.icon_theme_get_default() # we keep a reference pngloader around so that its in memory # -> this avoid the issue that during the dapper->edgy upgrade # the loaders move from /usr/lib/gtk/2.4.0/loaders to 2.10.0 self.pngloader = gtk.gdk.PixbufLoader("png") try: self.svgloader = gtk.gdk.PixbufLoader("svg") self.svgloader.close() except gobject.GError as e: logging.debug("svg pixbuf loader failed (%s)" % e) pass try: import webkit self._webkit_view = webkit.WebView() self.vbox_main.pack_end(self._webkit_view) except: logging.exception("html widget") self._webkit_view = None self.window_main.realize() self.window_main.window.set_functions(gtk.gdk.FUNC_MOVE) self._opCacheProgress = GtkOpProgress(self.progressbar_cache) self._acquireProgress = GtkAcquireProgressAdapter(self) self._cdromProgress = GtkCdromProgressAdapter(self) self._installProgress = GtkInstallProgressAdapter(self) # details dialog self.details_list = gtk.TreeStore(gobject.TYPE_STRING) column = gtk.TreeViewColumn("") render = gtk.CellRendererText() column.pack_start(render, True) column.add_attribute(render, "markup", 0) self.treeview_details.append_column(column) self.details_list.set_sort_column_id(0, gtk.SORT_ASCENDING) self.treeview_details.set_model(self.details_list) # Use italic style in the status labels attrlist = pango.AttrList() #attr = pango.AttrStyle(pango.STYLE_ITALIC, 0, -1) attr = pango.AttrScale(pango.SCALE_SMALL, 0, -1) attrlist.insert(attr) self.label_status.set_property("attributes", attrlist) # reasonable fault handler sys.excepthook = self._handleException
def lookup_icon(name): icons = gtk.icon_theme_get_default() logo = icons.lookup_icon(name, -1, 0) if logo: return logo.get_filename()
def _get_icon(self, name): theme = gtk.icon_theme_get_default() return theme.load_icon(name, self.icon_size, 0)
def __init__(self, treestore, find_params, callback, substitution=None): self.treestore = treestore self.find_params = find_params self.callback = callback self.substitution = substitution self.theme = Gtk.icon_theme_get_default()
def __init__(self, conduitApplication, moduleManager, typeConverter, syncManager): """ Constructs the mainwindow. Throws up a splash screen to cover the most time consuming pieces """ #add some additional dirs to the icon theme search path so that #modules can provider their own icons icon_dirs = [ conduit.SHARED_DATA_DIR, conduit.SHARED_MODULE_DIR, os.path.join(conduit.SHARED_DATA_DIR, "icons"), os.path.join(conduit.USER_DIR, "modules") ] for i in icon_dirs: gtk.icon_theme_get_default().prepend_search_path(i) gtk.window_set_default_icon_name("conduit") signals = { "on_mainwindow_delete": self.on_window_closed, "on_mainwindow_state_event": self.on_window_state_event, "on_synchronize_activate": self.on_synchronize_all_clicked, "on_cancel_activate": self.on_cancel_all_clicked, "on_quit_activate": self.on_window_closed, "on_clear_canvas_activate": self.on_clear_canvas, "on_preferences_activate": self.on_conduit_preferences, "on_about_activate": self.on_about_conduit, "on_contents_activate": self.on_help, "on_save1_activate": self.save_settings, } self.conduitApplication = conduitApplication self.builder = _GtkBuilderWrapper(conduit.SHARED_DATA_DIR, "conduit.ui") self.builder.connect_signals(signals) #type converter and sync manager self.type_converter = typeConverter self.sync_manager = syncManager #Initialize the mainWindow self.mainWindow = self.builder.get_object("MainWindow") #Enable RGBA colormap if conduit.GLOBALS.settings.get("gui_use_rgba_colormap") == True: screen = self.mainWindow.get_screen() colormap = screen.get_rgba_colormap() if colormap: gtk.widget_set_default_colormap(colormap) self.mainWindow.set_position(gtk.WIN_POS_CENTER) title = "Conduit" if conduit.IS_DEVELOPMENT_VERSION: title = title + _(" - %s (Development Version)") % conduit.VERSION if not conduit.IS_INSTALLED: title = title + _(" - Running Uninstalled") self.mainWindow.set_title(title) #Configure canvas self.canvasSW = self.builder.get_object("canvasScrolledWindow") self.hpane = self.builder.get_object("hpaned1") #start up the canvas msg = MsgArea.MsgAreaController() self.builder.get_object("mainVbox").pack_start(msg, False, False) self.canvas = Canvas.Canvas(parentWindow=self.mainWindow, typeConverter=self.type_converter, syncManager=self.sync_manager, gtkbuilder=self.builder, msg=msg) self.canvasSW.add(self.canvas) self.canvas.connect('drag-drop', self.drop_cb) self.canvas.connect("drag-data-received", self.drag_data_received_data) # Populate the tree model self.dataproviderTreeModel = Tree.DataProviderTreeModel() dataproviderScrolledWindow = self.builder.get_object("scrolledwindow2") self.dataproviderTreeView = Tree.DataProviderTreeView( self.dataproviderTreeModel) dataproviderScrolledWindow.add(self.dataproviderTreeView) #Set up the expander used for resolving sync conflicts self.conflictResolver = ConflictResolver.ConflictResolver(self.builder) #Preferences manager self.preferences = PreferencesWindow(self.builder) #add the preconfigured Conduit menu if conduit.GLOBALS.settings.get("gui_show_hints"): self.preconfiguredConduitsMenu = _PreconfiguredConduitMenu() self.builder.get_object("file_menu").insert( self.preconfiguredConduitsMenu.item, 3) else: self.preconfiguredConduitsMenu = None #if running a development version, add some developer specific links #to the help menu if conduit.IS_DEVELOPMENT_VERSION: helpMenu = self.builder.get_object("help_menu") developersMenuItem = gtk.ImageMenuItem(_("Developers")) developersMenuItem.set_image( gtk.image_new_from_icon_name("applications-development", gtk.ICON_SIZE_MENU)) developersMenu = gtk.Menu() developersMenuItem.set_submenu(developersMenu) helpMenu.prepend(developersMenuItem) for name, url in DEVELOPER_WEB_LINKS: item = gtk.ImageMenuItem(_(name)) item.set_image( gtk.image_new_from_icon_name("applications-internet", gtk.ICON_SIZE_MENU)) item.connect("activate", self.on_developer_menu_item_clicked, _(name), url) developersMenu.append(item) #final GUI setup self.cancelSyncButton = self.builder.get_object('cancel') self.hpane.set_position( conduit.GLOBALS.settings.get("gui_hpane_postion")) self.dataproviderTreeView.set_expand_rows() self.window_state = 0 log.info("Main window constructed (thread: %s)" % thread.get_ident())
def on_get_value(self, rowref, column): if rowref >= len(self._episodes): return None episode = self._episodes[rowref] downloading = self._downloading if column == self.C_URL: return episode.url elif column == self.C_TITLE: return episode.title elif column == self.C_FILESIZE_TEXT: return self._format_filesize(episode) elif column == self.C_EPISODE: return episode elif column == self.C_STATUS_ICON: if downloading(episode): return self.ICON_DOWNLOADING elif episode.state == gpodder.STATE_DELETED: return self.ICON_DELETED elif episode.state == gpodder.STATE_NORMAL and \ not episode.is_played and \ not downloading(episode): return None # self.ICON_NEW elif episode.state == gpodder.STATE_DOWNLOADED: filename = episode.local_filename(create=False, \ check_only=True) file_type = episode.file_type() if file_type == 'audio': status_icon = self.ICON_AUDIO_FILE if episode.is_locked: status_icon += '-locked' elif file_type == 'video': status_icon = self.ICON_VIDEO_FILE if episode.is_locked: status_icon += '-locked' elif file_type == 'image': status_icon = self.ICON_IMAGE_FILE else: status_icon = self.ICON_GENERIC_FILE if gpodder.ui.maemo: return status_icon icon_theme = gtk.icon_theme_get_default() if filename is not None and have_gio: file = gio.File(filename) if file.query_exists(): file_info = file.query_info('*') icon = file_info.get_icon() for icon_name in icon.get_names(): if icon_theme.has_icon(icon_name): return icon_name return status_icon return None elif column == self.C_PUBLISHED_TEXT: return episode.cute_pubdate() elif column == self.C_DESCRIPTION: return self._format_description(episode) elif column == self.C_TOOLTIP: return '' elif column == self.C_VIEW_SHOW_UNDELETED: return episode.state != gpodder.STATE_DELETED or downloading( episode) elif column == self.C_VIEW_SHOW_DOWNLOADED: return episode.state == gpodder.STATE_DOWNLOADED or \ (episode.state == gpodder.STATE_NORMAL and \ not episode.is_played) or \ downloading(episode) elif column == self.C_VIEW_SHOW_UNPLAYED: return (not episode.is_played and (episode.state in \ (gpodder.STATE_DOWNLOADED, gpodder.STATE_NORMAL))) or \ downloading(episode) elif column == self.C_FILESIZE: return episode.length elif column == self.C_PUBLISHED: return episode.pubDate elif column == self.C_TIME: return episode.get_play_info_string() elif column == self.C_TIME_VISIBLE: return episode.total_time elif column == self.C_LOCKED: return episode.is_locked and \ episode.state == gpodder.STATE_DOWNLOADED and \ episode.file_exists() raise Exception('could not find column index: ' + str(column))
def initGUI(self): theme = gtk.icon_theme_get_default() if theme.has_icon("terminal"): icon = theme.lookup_icon("terminal", 128, flags=gtk.ICON_LOOKUP_USE_BUILTIN) if icon is not None: gtk.window_set_default_icon(icon.load_icon()) self.MainWin.set_title("crussh: " + ' '.join(self.Terminals.keys())) self.MainWin.set_role(role="crussh_main_win") self.MainWin.connect("delete-event", lambda window, event: gtk.main_quit()) MainVBox = gtk.VBox() self.MainWin.add(MainVBox) MainMenuBar = gtk.MenuBar() MainVBox.pack_start(MainMenuBar, fill=True, expand=False) def add_host_handler(self, base): diag = EntryDialog(buttons=gtk.BUTTONS_OK, type=gtk.MESSAGE_QUESTION, message_format="Hostname to add:") print "test" host = diag.run() if len(host) > 0: base.addHost(host) diag.destroy() base.reflow(force=True) FileItem = gtk.MenuItem(label="File") FileMenu = gtk.Menu() FileItem.set_submenu(FileMenu) AddHostItem = gtk.MenuItem(label="Add Host") AddHostItem.connect("activate", add_host_handler, self) FileMenu.append(AddHostItem) FileMenu.append(gtk.SeparatorMenuItem()) QuitItem = gtk.ImageMenuItem(gtk.STOCK_QUIT) QuitItem.connect("activate", lambda discard: gtk.main_quit()) FileMenu.append(QuitItem) MainMenuBar.append(FileItem) EditItem = gtk.MenuItem(label="Edit") EditMenu = gtk.Menu() EditItem.set_submenu(EditMenu) ActiveHostsItem = gtk.MenuItem(label="Active Hosts") ActiveHostsItem.connect("activate", lambda discard: HostsMask(self.Terminals)) EditMenu.append(ActiveHostsItem) PrefsItem = gtk.MenuItem(label="Preferences") def save_func(new_config): self.Config = new_config self.reflow(force=True) # save to file last, so it doesn't hold up other GUI actions conf_json = json.dumps(self.Config, sort_keys=True, indent=4) try: conf_file = open(os.path.expanduser("~/.crusshrc"), 'w') conf_file.write(conf_json) conf_file.close() except: pass PrefsItem.connect("activate", lambda discard: CruSSHConf(self.Config, save_func)) EditMenu.append(PrefsItem) MainMenuBar.append(EditItem) self.ScrollWin.props.hscrollbar_policy = gtk.POLICY_NEVER self.ScrollWin.props.vscrollbar_policy = gtk.POLICY_ALWAYS self.ScrollWin.props.shadow_type = gtk.SHADOW_ETCHED_IN MainVBox.pack_start(self.ScrollWin) self.LayoutTable.set_homogeneous(True) self.LayoutTable.set_row_spacings(1) self.LayoutTable.set_col_spacings(1) self.ScrollWin.add_with_viewport(self.LayoutTable) self.ScrollWin.set_size_request(self.TermMinWidth, self.TermMinHeight) # don't display chars while typing. self.EntryBox.set_visibility(False) self.EntryBox.set_invisible_char(' ') # feed GNOME clipboard to all active terminals def feed_paste(widget): for host in self.Terminals: if self.Terminals[host].copy_input: self.Terminals[host].paste_clipboard() self.EntryBox.props.buffer.delete_text(0, -1) # forward key events to all terminals with copy_input set def feed_input(widget, event): self.EntryBox.props.buffer.delete_text(0, -1) # check for paste key shortcut (ctl-shift-v) if (event.type == gtk.gdk.KEY_PRESS) \ and (event.state & gtk.gdk.CONTROL_MASK == gtk.gdk.CONTROL_MASK) \ and (event.state & gtk.gdk.SHIFT_MASK == gtk.gdk.SHIFT_MASK) \ and (event.keyval == gtk.gdk.keyval_from_name('V')): feed_paste(widget) else: # propagate to every terminal for host in self.Terminals: t_event = event.copy() if self.Terminals[host].copy_input: self.Terminals[host].event(t_event) # this stops regular handler from firing, switching focus. return True def click_handler(widget, event): # if middle click if event.button == 2: feed_input(widget, event) self.EntryBox.connect("key_press_event", feed_input) self.EntryBox.connect("key_release_event", feed_input) self.EntryBox.connect("paste_clipboard", feed_paste) self.EntryBox.connect("button_press_event", click_handler) MainVBox.pack_start(self.EntryBox, False, False) # reflow layout on size change. self.MainWin.connect("size-allocate", lambda widget, allocation: self.reflow()) # give EntryBox default focus on init self.EntryBox.props.has_focus = True
def init_vhost_properties(self): # Get glade file XML f = open(os.path.join(self.path, "ssl.glade"), "r") self.glade_vhost_xml = f.read() f.close() # Remember you will need to recreate tree everytime the window loads wtree = gtk.glade.xml_new_from_buffer(self.glade_vhost_xml, len(self.glade_vhost_xml), "table_ssl") table_ssl = wtree.get_widget("table_ssl") #self.entry_admin_email = wtree.get_widget("entry_admin_email") #self.entry_log_location = wtree.get_widget("entry_log_location") self.treeview_requests = wtree.get_widget("treeview_requests") self.linkbutton_active_cert = wtree.get_widget( "linkbutton_active_cert") self.filechooserbutton_ssl_cert = wtree.get_widget( "filechooserbutton_ssl_cert") self.spinbutton_port = wtree.get_widget("spinbutton_port") self.entry_ssl_key_location = wtree.get_widget( "entry_ssl_key_location") self.filechooserbutton_ssl_key = wtree.get_widget( "filechooserbutton_ssl_key") signals = { "on_button_csr_clicked": self.on_button_csr_clicked, "on_treeview_requests_row_activated": self.on_treeview_requests_row_activated, "on_button_import_clicked": self.on_button_import_clicked, "on_button_import_key_clicked": self.on_button_import_key_clicked, "on_button_key_reset_clicked": self.on_button_key_reset_clicked } wtree.signal_autoconnect(signals) # Setup tree column = gtk.TreeViewColumn(('')) column.set_spacing(4) cell = gtk.CellRendererToggle() cell.set_radio(True) cell.connect('toggled', self.treeview_requests_toggled) column.pack_start(cell, False) column.set_attributes(cell, active=0) self.treeview_requests.append_column(column) column = gtk.TreeViewColumn(('')) column.set_spacing(4) cell = gtk.CellRendererPixbuf() column.pack_start(cell, False) column.set_attributes(cell, pixbuf=1) self.treeview_requests.append_column(column) column = gtk.TreeViewColumn(('Type')) cell = gtk.CellRendererText() column.pack_start(cell, True) column.set_attributes(cell, markup=2) self.treeview_requests.append_column(column) column = gtk.TreeViewColumn(('Domain')) cell = gtk.CellRendererText() column.pack_start(cell, True) column.set_attributes(cell, markup=3) self.treeview_requests.append_column(column) column = gtk.TreeViewColumn(('Expires')) cell = gtk.CellRendererText() column.pack_start(cell, True) column.set_attributes(cell, markup=4) self.treeview_requests.append_column(column) self.spinbutton_port.set_value(443) icon_theme = gtk.icon_theme_get_default() pixbuf = icon_theme.lookup_icon("application-certificate", 24, 0).load_icon() return table_ssl, "SSL", pixbuf
# connect to the bus bus = dbus.SessionBus() dbus_names = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus') dbus_names.connect_to_signal( 'NameOwnerChanged', NameOwnerChanged, dbus_interface='org.freedesktop.DBus') # to detect new Media Players dbus_o = bus.get_object('org.freedesktop.DBus', '/') dbus_intf = dbus.Interface(dbus_o, 'org.freedesktop.DBus') # connect to the first Media Player found for n in dbus_intf.ListNames(): if mpris in n: Connect(n) vol.set_value(PropGet('Volume') * 100.0) update(0) break # run a timer to update position timeout_add(1000, timeset) window.set_icon_name('audio-x-generic') window.show() window.set_icon(gtk.icon_theme_get_default().load_icon('audio-x-generic', 24, 0)) win_position = window.get_position() gtk.main() # execute the main loop
def _get_tree_icon(self, icon_name, add_bullet=False, \ add_padlock=False, add_missing=False, icon_size=32, \ build_icon_from_file = False): """ Loads an icon from the current icon theme at the specified size, suitable for display in a gtk.TreeView. Additional emblems can be added on top of the icon. Caching is used to speed up the icon lookup. The `build_icon_from_file` argument indicates (when True) that the icon has to be created on the fly from a given image file. The `icon_name` argument is then interpreted as the path to this file. Those specific icons will *not be cached*. """ # Add all variables that modify the appearance of the icon, so # our cache does not return the same icons for different requests cache_id = (icon_name, add_bullet, add_padlock, add_missing, icon_size) if cache_id in self._icon_cache: return self._icon_cache[cache_id] icon_theme = gtk.icon_theme_get_default() try: if build_icon_from_file: icon = self._get_icon_from_image(icon_name, icon_size) else: icon = icon_theme.load_icon(icon_name, icon_size, 0) except: try: log('Missing icon in theme: %s', icon_name, sender=self) icon = icon_theme.load_icon(gtk.STOCK_DIALOG_QUESTION, \ icon_size, 0) except: log('Please install the GNOME icon theme.', sender=self) icon = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, \ True, 8, icon_size, icon_size) if icon and (add_bullet or add_padlock or add_missing): # We'll modify the icon, so use .copy() if add_missing: try: icon = icon.copy() # Desaturate the icon so it looks even more "missing" icon.saturate_and_pixelate(icon, 0.0, False) emblem = icon_theme.load_icon(self.ICON_MISSING, icon_size / 2, 0) (width, height) = (emblem.get_width(), emblem.get_height()) xpos = icon.get_width() - width ypos = icon.get_height() - height emblem.composite(icon, xpos, ypos, width, height, xpos, ypos, 1, 1, gtk.gdk.INTERP_BILINEAR, 255) except: pass elif add_bullet: try: icon = icon.copy() emblem = icon_theme.load_icon(self.ICON_UNPLAYED, icon_size / 2, 0) (width, height) = (emblem.get_width(), emblem.get_height()) xpos = icon.get_width() - width ypos = icon.get_height() - height emblem.composite(icon, xpos, ypos, width, height, xpos, ypos, 1, 1, gtk.gdk.INTERP_BILINEAR, 255) except: pass if add_padlock: try: icon = icon.copy() emblem = icon_theme.load_icon(self.ICON_LOCKED, icon_size / 2, 0) (width, height) = (emblem.get_width(), emblem.get_height()) emblem.composite(icon, 0, 0, width, height, 0, 0, 1, 1, gtk.gdk.INTERP_BILINEAR, 255) except: pass self._icon_cache[cache_id] = icon return icon
def update_treeview(self): icon_theme = gtk.icon_theme_get_default() cert_icon = icon_theme.lookup_icon("application-certificate", 24, 0).load_icon() cert_icon_self = icon_theme.lookup_icon("application-certificate", 24, 0).load_icon() self.treeview_requests_store = gtk.ListStore(bool, gtk.gdk.Pixbuf, str, str, str, str) self.treeview_requests.set_model(self.treeview_requests_store) files = Shell.command.listdir("/etc/apache2/ssl/") files.sort() domains = list(self.vhost.get_server_alias()) if self.vhost.config.ServerName: domains = [self.vhost.get_server_name()] + domains if not self.active_cert: self.treeview_requests_store.append( (True, None, "<b><i>No Certificate</i></b>", "", "", None)) else: self.treeview_requests_store.append( (False, None, "<i>No Certificate</i>", "", "", None)) for path in files: full_path = os.path.join("/etc/apache2/ssl/", path) if path.endswith(".crt"): cert = crypto.load_certificate( crypto.FILETYPE_PEM, Shell.command.read_file(full_path)) domain = cert.get_subject().commonName domain_match = False # find domains that are relevent for d in domains: if d == domain or (domain[0] == "*" and (d.endswith(domain[1:]) or d == domain[2:])): domain_match = True if domain_match: expired = self.get_expiry_date_hack( cert, full_path) icon = cert_icon if domain == cert.get_issuer().commonName: icon = cert_icon_self if cert.has_expired(): expired = "<b>Expired " + expired + "</b>" if full_path == self.active_cert: self.treeview_requests_store.append( (True, icon, "<b>Certificate</b>", "<b>" + domain + "</b>", "<b>" + expired + "</b>", full_path)) select = self.treeview_requests.get_selection() select.select_path( len(self.treeview_requests_store) - 1) self.treeview_requests.scroll_to_cell( len(self.treeview_requests_store) - 1) else: self.treeview_requests_store.append( (False, icon, "Certificate", domain, expired, full_path)) break
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA import gconf import gtk from sugar.activity import activity from sugar.graphics import style from sugar.graphics.icon import Icon from sugar.graphics.xocolor import XoColor from sugar.graphics.xocolor import _parse_string from sugar.graphics.toolbutton import ToolButton names = gtk.icon_theme_get_default().list_icons() if "gtk-ok" in names: icon = "gtk-ok" else: icon = "dialog-ok" class AboutMeActivity(activity.Activity): def colour_changed_callback(self, widget, type): colour = widget.get_current_color() red = "%x" % int(colour.red / 65535.0 * 255) if len(red) == 1: red = "0%s" % red green = "%x" % int(colour.green / 65535.0 * 255) if len(green) == 1: green = "0%s" % green
def __init__(self, settings): self.settings = settings #Make the main window self.win = gtk.Window() self.win.set_title(_('To-Do List Preferences')) #Get the default icon [theme] self.icon_theme = gtk.icon_theme_get_default() self.icon_theme.connect('changed', self.icon_theme_changed) icon = self.icon_theme.load_icon('view-sort-descending', 48, 48) #Get the window's icon self.win.set_icon(icon) #Make the main GtkNotebook along with three main widgets and two Labels notebook = gtk.Notebook() general_align = gtk.Alignment(xscale=1.0) priority_align = gtk.Alignment(xscale=1.0) icon_align = gtk.Alignment(xscale=1.0) general_label = gtk.Label(_('General')) priority_label = gtk.Label(_('Priority')) icon_label = gtk.Label(_('Icon')) notebook.append_page(general_align, general_label) notebook.append_page(priority_align, priority_label) notebook.append_page(icon_align, icon_label) main_vbox = gtk.VBox(False, 6) main_vbox.pack_start(notebook) #Label: Title (bold) title_label = gtk.Label(_('Title')) title_label.modify_font(pango.FontDescription('bold')) title_label.set_alignment(0.0, 0.5) #GtkAlignment for the entry title_align = gtk.Alignment(xscale=1.0) title_align.set_padding(0, 0, 10, 0) #Entry for Title title_entry = gtk.Entry() title_entry.set_text(self.settings['title']) title_entry.connect('focus-out-event', self.update) #Label: Confirm when removing... (bold) confirm_label = gtk.Label(_('Confirm when removing...')) confirm_label.modify_font(pango.FontDescription('bold')) confirm_label.set_alignment(0.0, 0.5) #GtkAlignment for the checkbuttons confirm_align = gtk.Alignment() confirm_align.set_padding(0, 0, 10, 0) #CheckButton: Items confirm_items = gtk.CheckButton(_('_Items')) confirm_items.key = 'confirm_items' if self.settings['confirm_items']: confirm_items.set_active(True) confirm_items.connect('toggled', self.check_toggled) #CheckButton: Categories confirm_cats = gtk.CheckButton(_('C_ategories')) confirm_cats.key = 'confirm_categories' if self.settings['confirm_categories']: confirm_cats.set_active(True) confirm_cats.connect('toggled', self.check_toggled) #Label: Width (bold) width_label = gtk.Label(_('Width')) width_label.modify_font(pango.FontDescription('bold')) width_label.set_alignment(0.0, 0.5) #GtkAlignment for the widgets width_align = gtk.Alignment(xscale=1.0) width_align.set_padding(0, 0, 10, 0) #CheckButton: Use Custom Width width_check = gtk.CheckButton(_('_Use Custom Width')) if self.settings['use_custom_width'] == True: width_check.set_active(True) width_check.key = 'use_custom_width' width_check.connect('toggled', self.check_toggled) #Label: Width (pixels) width_label2 = gtk.Label(_('Width (pixels)')) width_label2.set_alignment(0.0, 0.5) #SpinButton for custom width in pixels width_adj = gtk.Adjustment(float(self.settings['custom_width']), 25, 500, \ 1, 5, 0) width_spin = gtk.SpinButton(width_adj, 1, 0) width_spin.key = 'custom_width' width_spin.connect('focus-out-event', self.spin_focusout) #Put the General tab together title_align.add(title_entry) title_vbox = gtk.VBox() title_vbox.pack_start(title_label, False) title_vbox.pack_start(title_align, False) confirm_align_vbox = gtk.VBox() confirm_align_vbox.pack_start(confirm_items, False) confirm_align_vbox.pack_start(confirm_cats, False) confirm_align.add(confirm_align_vbox) confirm_vbox = gtk.VBox() confirm_vbox.pack_start(confirm_label, False) confirm_vbox.pack_start(confirm_align, False) width_hbox = gtk.HBox() width_hbox.pack_start(width_label2) width_hbox.pack_end(width_spin, False) width_align_vbox = gtk.VBox() width_align_vbox.pack_start(width_check) width_align_vbox.pack_start(width_hbox) width_align.add(width_align_vbox) width_vbox = gtk.VBox() width_vbox.pack_start(width_label, False) width_vbox.pack_start(width_align, False) general_vbox = gtk.VBox() general_vbox.pack_start(title_vbox, False, False, 6) general_vbox.pack_start(confirm_vbox, False, False, 6) general_vbox.pack_start(width_vbox, False, False, 6) general_align.set_padding(0, 0, 12, 12) general_align.add(general_vbox) #Label: Low Priority (bold) priority_low_label = gtk.Label(_('Low Priority')) priority_low_label.modify_font(pango.FontDescription('bold')) priority_low_label.set_alignment(0.0, 0.5) #GtkAlignment priority_low_align = gtk.Alignment(xscale=1.0) priority_low_align.set_padding(0, 0, 10, 0) #Low Priority Colors priority_low_background = self.color2('low') priority_low_text = self.color2('low', True) #Label: Medium Priority (bold) priority_med_label = gtk.Label(_('Medium Priority')) priority_med_label.modify_font(pango.FontDescription('bold')) priority_med_label.set_alignment(0.0, 0.5) #GtkAlignment priority_med_align = gtk.Alignment(xscale=1.0) priority_med_align.set_padding(0, 0, 10, 0) #Medium Priority Colors priority_med_background = self.color2('med') priority_med_text = self.color2('med', True) #Label: High Priority (bold) priority_high_label = gtk.Label(_('High Priority')) priority_high_label.modify_font(pango.FontDescription('bold')) priority_high_label.set_alignment(0.0, 0.5) #GtkAlignment priority_high_align = gtk.Alignment(xscale=1.0) priority_high_align.set_padding(0, 0, 10, 0) #High Priority Colors priority_high_background = self.color2('high') priority_high_text = self.color2('high', True) #Put the Priority tab together low_align_vbox = gtk.VBox() low_align_vbox.pack_start(priority_low_background, False) low_align_vbox.pack_start(priority_low_text, False) priority_low_align.add(low_align_vbox) low_vbox = gtk.VBox() low_vbox.pack_start(priority_low_label, False) low_vbox.pack_start(priority_low_align, False) med_align_vbox = gtk.VBox() med_align_vbox.pack_start(priority_med_background, False) med_align_vbox.pack_start(priority_med_text, False) priority_med_align.add(med_align_vbox) med_vbox = gtk.VBox() med_vbox.pack_start(priority_med_label, False) med_vbox.pack_start(priority_med_align, False) high_align_vbox = gtk.VBox() high_align_vbox.pack_start(priority_high_background, False) high_align_vbox.pack_start(priority_high_text, False) priority_high_align.add(high_align_vbox) high_vbox = gtk.VBox() high_vbox.pack_start(priority_high_label, False) high_vbox.pack_start(priority_high_align, False) priority_vbox = gtk.VBox() priority_vbox.pack_start(low_vbox, False, False, 6) priority_vbox.pack_start(med_vbox, False, False, 6) priority_vbox.pack_start(high_vbox, False, False, 6) priority_align.set_padding(0, 0, 12, 12) priority_align.add(priority_vbox) #Set up the GtkAlignment for this tab icon_align.set_padding(0, 0, 12, 12) #Label: Icon Color (bold) icon_color_label = gtk.Label(_('Icon Color')) icon_color_label.modify_font(pango.FontDescription('bold')) icon_color_label.set_alignment(0.0, 0.5) #GtkAlignment icon_color_align = gtk.Alignment(xscale=1.0) icon_color_align.set_padding(0, 0, 10, 0) #ComboBox for Icon Color liststore = gtk.ListStore(str) for color in icon_colors_human: liststore.append([color]) index = icon_colors_real.index(self.settings['color']) color_cb = gtk.ComboBox(liststore) color_cb.set_active(index) cell = gtk.CellRendererText() color_cb.pack_start(cell, True) color_cb.add_attribute(cell, 'text', 0) color_cb.key = 'color' color_cb.connect('changed', self.cb_changed) #Label: Custom Colors (bold) custom_colors_label = gtk.Label(_('Custom Colors')) custom_colors_label.modify_font(pango.FontDescription('bold')) custom_colors_label.set_alignment(0.0, 0.5) #GtkAlignment custom_colors_align = gtk.Alignment(xscale=1.0) custom_colors_align.set_padding(0, 0, 10, 0) #Colors: Outer Border, Inner Border, Main Color, Text Color outer_border = self.color(_('Outer Border'), 0) inner_border = self.color(_('Inner Border'), 3) main_color = self.color(_('Main'), 6) text_color = self.color(_('Text'), 9) #Label: Icon Type (bold) icon_type_label = gtk.Label(_('Icon Type')) icon_type_label.modify_font(pango.FontDescription('bold')) icon_type_label.set_alignment(0.0, 0.5) #GtkAlignment icon_type_align = gtk.Alignment(xscale=1.0) icon_type_align.set_padding(0, 0, 10, 0) #ComboBox: Icon Type: Number of Items, Progress, Both liststore = gtk.ListStore(str) for _type in icon_types_human: liststore.append([_type]) index = icon_types_real.index(self.settings['icon_type']) _type_cb = gtk.ComboBox(liststore) _type_cb.set_active(index) cell = gtk.CellRendererText() _type_cb.pack_start(cell, True) _type_cb.add_attribute(cell, 'text', 0) _type_cb.key = 'icon_type' _type_cb.connect('changed', self.cb_changed) #Put the Icon tab together icon_color_align.add(color_cb) icon_color_vbox = gtk.VBox() icon_color_vbox.pack_start(icon_color_label, False) icon_color_vbox.pack_start(icon_color_align, False) custom_colors_align_vbox = gtk.VBox() custom_colors_align_vbox.pack_start(outer_border, False) custom_colors_align_vbox.pack_start(inner_border, False) custom_colors_align_vbox.pack_start(main_color, False) custom_colors_align_vbox.pack_start(text_color, False) custom_colors_align.add(custom_colors_align_vbox) custom_colors_vbox = gtk.VBox() custom_colors_vbox.pack_start(custom_colors_label, False) custom_colors_vbox.pack_start(custom_colors_align, False) icon_type_align.add(_type_cb) icon_type_vbox = gtk.VBox() icon_type_vbox.pack_start(icon_type_label, False) icon_type_vbox.pack_start(icon_type_align, False) icon_vbox = gtk.VBox() icon_vbox.pack_start(icon_color_vbox, False, False, 6) icon_vbox.pack_start(custom_colors_vbox, False, False, 6) icon_vbox.pack_start(icon_type_vbox, False, False, 6) icon_align.add(icon_vbox) #Close button close_button = gtk.Button(stock=gtk.STOCK_CLOSE) close_button.connect('clicked', self.close) #HButtonBox so the close button doesn't take the entire width close_hbbox = gtk.HButtonBox() close_hbbox.set_layout(gtk.BUTTONBOX_END) close_hbbox.pack_end(close_button, False) #Show the window main_vbox.pack_start(close_hbbox) self.win.add(main_vbox) self.win.set_border_width(6) self.win.show_all()
def __init__(self): """ The constructor """ gnotero_base.gnotero_base.__init__(self) gtk.StatusIcon.__init__(self) if self.os != "windows": actions = [ ('Menu', None, 'Menu'), ('Quit', gtk.STOCK_QUIT, None, None, 'Quit', self.quit), ('Settings', gtk.STOCK_PREFERENCES, None, None, 'Gnoteroconf', self.start_gnoteroconf), ('Copy', None, None, None, 'Gnoterobrowse', self.start_gnoterobrowse), ('Zotero', None, None, None, 'Zotero', self.start_zotero), ('About', gtk.STOCK_ABOUT, None, None, 'About', self.about) ] menu = """ <ui> <menubar name="Menubar"> <menu action="Menu"> <menuitem action="Settings"/> <menuitem action="Copy"/> <menuitem action="Zotero"/> <menuitem action="About"/> <menuitem action="Quit"/> </menu> </menubar> </ui> """ else: actions = [ ('Menu', None, 'Menu'), ('Quit', gtk.STOCK_QUIT, None, None, 'Quit', self.quit), ('Zotero', None, None, None, 'Zotero', self.start_zotero), ('About', gtk.STOCK_ABOUT, None, None, 'About', self.about) ] menu = """ <ui> <menubar name="Menubar"> <menu action="Menu"> <menuitem action="Zotero"/> <menuitem action="About"/> <menuitem action="Quit"/> </menu> </menubar> </ui> """ self.first_result = None self.clipboard = gtk.Clipboard() ag = gtk.ActionGroup('Actions') ag.add_actions(actions) self.manager = gtk.UIManager() self.manager.insert_action_group(ag, 0) self.manager.add_ui_from_string(menu) self.menu = self.manager.get_widget('/Menubar/Menu/Quit').props.parent quit = self.manager.get_widget('/Menubar/Menu/Quit') quit.get_children()[0].set_markup('Quit') if self.os != "windows": preferences = self.manager.get_widget('/Menubar/Menu/Settings') preferences.get_children()[0].set_markup('Gnoteroconf') copy = self.manager.get_widget('/Menubar/Menu/Copy') copy.get_children()[0].set_markup('Gnoterobrowse ') zotero = self.manager.get_widget('/Menubar/Menu/Zotero') zotero.get_children()[0].set_markup('Fullscreen Zotero ') self.icon_theme = gtk.icon_theme_get_default() if self.os == "windows": self.set_from_file("data\\icons\\gnotero.png") else: pixbuf = self.icon_theme.load_icon(self.systray_icon, 22, 0) self.set_from_pixbuf(pixbuf) self.set_tooltip('Quick access to your Zotero references') self.set_visible(True) self.connect('popup-menu', self.on_popup_menu) self.connect('activate', self.on_activate) self.shown = False self.create_window() # Start the listener self.listener = listener.Listener(self) self.listener.start()
def __init__(self, app): self.app = app self.theme = gtk.icon_theme_get_default()
class catfish: def __init__(self): """Create the main window.""" # Check for a desktop environment desktop = os.environ.get('DESKTOP_SESSION', os.environ.get('GDMSESSION', '')) if desktop[:4] == 'xfce': # We assume this is Xfce4 default_fileman = 'Thunar' self.open_wrapper = 'exo-open' elif desktop[:5] == 'gnome': # We assume this is Gnome default_fileman = 'Nautilus' self.open_wrapper = 'gnome-open' else: # Unknown desktop? Just see what we have then # Guess suitable fileman commands = ['Nautilus', 'Thunar', 'konqueror', 'pcmanfm'] default_fileman = '' for path in os.environ.get('PATH', '/usr/bin').split(os.pathsep): for command in commands: if os.path.exists(os.path.join(path, command)): default_fileman = command break commands = ['gnome-open', 'exo-open', 'xdg-open'] self.open_wrapper = '' # Guess suitable file open wrapper for path in os.environ.get('PATH', '/usr/bin').split(os.pathsep): for command in commands: if os.path.exists(os.path.join(path, command)): self.open_wrapper = command break # Parse command line options parser = optparse.OptionParser(usage='usage: ' + app_name + ' [options] keywords', version=app_name + ' v' + app_version) parser.add_option('', '--large-icons', action='store_true' , dest='icons_large', help='Use large icons') parser.add_option('', '--thumbnails', action='store_true' , dest='thumbnails', help='Use thumbnails') parser.add_option('', '--iso-time', action='store_true' , dest='time_iso', help='Display time in iso format') parser.add_option('', '--limit', type='int', metavar='LIMIT' , dest='limit_results', help='Limit number of results') parser.add_option('', '--path', help='Search in folder PATH') parser.add_option('', '--fileman', help='Use FILEMAN as filemanager') parser.add_option('', '--wrapper', metavar='WRAPPER' , dest='open_wrapper', help='Use WRAPPER to open files') parser.add_option('', '--method', help='Use METHOD to search') parser.add_option('', '--exact', action='store_true' , help='Perform exact match') parser.add_option('', '--hidden', action='store_true' , help='Include hidden files') parser.add_option('', '--fulltext', action='store_true' , help='Perform fulltext search') parser.add_option('', '--file-action', metavar='ACTION' , dest='file_action', help='File action: "open" or "folder"') parser.add_option('', '--debug', action='store_true' , help='Show debugging messages.') parser.set_defaults(icons_large=0, thumbnails=0, time_iso=0, method='find' , limit_results=0, path='~', fileman=default_fileman, exact=0 , hidden=0, fulltext=0, file_action='open', debug=0, open_wrapper=self.open_wrapper) self.options, args = parser.parse_args() keywords = ' '.join(args) if not self.options.file_action in ('open', 'folder'): print 'Error: Invalid value for "file-action".\n' print 'Use either "open" to open files by default or' print 'use "folder" to open the containing folder.' print '(The default is "open".)' sys.exit(1) if not self.options.fileman: print 'Warning: No file manager was found or specified.' # Prepare i18n using gettext try: locale.setlocale(locale.LC_ALL, '') gettext.bindtextdomain(app_name, 'locale') gettext.textdomain(app_name) gtk.glade.bindtextdomain(app_name, 'locale') gtk.glade.textdomain(app_name) except Exception, msg: if self.options.debug: print 'Debug:', msg print 'Warning: Invalid locale, i18n is disabled.' # Guess location of glade file glade_file = app_name + '.glade' glade_path = os.getcwd() if not os.path.exists(os.path.join(glade_path, glade_file)): glade_path = os.path.dirname(sys.argv[0]) if not os.path.exists(os.path.join(glade_path, glade_file)): print 'Error: The glade file could not be found.' sys.exit() # Load interface from glade file and retrieve widgets self.load_interface(os.path.join(glade_path, glade_file)) # Fetch stock labels for the menu items manually # Note that this is needed to workaround a bug in glade for menu in self.menu_file.get_children(): if menu.child: label = menu.child.get_label() if label[:4] == 'gtk-': stock = gtk.stock_lookup(label) menu.child.set_label(stock[1]) # Add markup to labels for label in (self.label_find_type, self.label_find_method, self.label_find_folder): label.set_markup('<i>%s</i>' % label.get_text()) # Set some initial values self.icon_cache = {} self.icon_theme = gtk.icon_theme_get_default() self.tooltips = gtk.Tooltips() self.checkbox_find_exact.set_active(self.options.exact) self.checkbox_find_hidden.set_active(self.options.hidden) self.checkbox_find_fulltext.set_active(self.options.fulltext) if self.options.limit_results: self.checkbox_find_limit.set_active(1) self.checkbox_find_limit.toggled() self.spin_find_limit.set_value(self.options.limit_results) self.folder_thumbnails = os.path.expanduser('~/.thumbnails/normal/') self.options.path = os.path.abspath(self.options.path) self.button_find_folder.set_filename(os.path.expanduser(self.options.path)) try: self.link_color = self.treeview_files.style_get_property('link-color') except: self.link_color = None if self.link_color == None: self.link_color = 'blue' # Set up keywords completion completion = gtk.EntryCompletion() self.entry_find_text.set_completion(completion) listmodel = gtk.ListStore(str) completion.set_model(listmodel) completion.set_text_column(0) # Retrieve available search methods methods = ['find', 'locate', 'slocate', 'tracker', 'doodle', 'beagle'] # DBus allows us to have two more methods if 'dbus' in globals(): for method in ('strigi', 'pinot'): methods.append(method) bin_dirs = os.environ.get('PATH', '/usr/bin').split(os.pathsep) listmodel = gtk.ListStore(gtk.gdk.Pixbuf, str) method_default = -1 icon = self.get_icon_pixbuf(gtk.STOCK_EXECUTE) for method_name in methods: method_binary = self.get_find_options(method_name)[0] for path in bin_dirs: if os.path.exists(os.path.join(path, method_binary)): listmodel.append([icon, method_name]) if self.options.method == method_name: method_default = len(listmodel) - 1 break if method_default < 0: print 'Warning:', ('Method "%s" is not available.' % self.options.method) method_default = 0 self.combobox_find_method.set_sensitive(len(listmodel) > 1) # Prepare method combobox cell = gtk.CellRendererPixbuf() cell.set_property('xalign', 0) self.combobox_find_method.pack_start(cell, True) self.combobox_find_method.add_attribute(cell, 'pixbuf', 0) cell = gtk.CellRendererText() self.combobox_find_method.pack_start(cell, True) self.combobox_find_method.add_attribute(cell, 'text', 1) self.combobox_find_method.set_model(listmodel) self.combobox_find_method.set_active(method_default) # Prepare type toolbar if 'xdg' in globals(): # This feature requires xdg for label, mime in ((_('Documents'), 'text'), (_('Images'), 'image'), (_('Music'), 'audio'), (_('Videos'), 'video')): self.toolbar_find_type.insert(self.new_toggle_button(label, mime), -1) self.toolbar_find_type.show_all() else: # If xdg is unavailable we hide the type toolbar self.label_find_type.hide() self.toolbar_find_type.hide() if self.options.icons_large or self.options.thumbnails: self.treeview_files.append_column(gtk.TreeViewColumn(_('Preview'), gtk.CellRendererPixbuf(), pixbuf=0)) self.treeview_files.append_column(self.new_column(_('Filename'), 1, markup=1)) else: self.treeview_files.append_column(self.new_column(_('Filename'), 1, 'icon', 1)) self.treeview_files.append_column(self.new_column(_('Size'), 2, 'filesize')) self.treeview_files.append_column(self.new_column(_('Location'), 3, 'ellipsize')) self.treeview_files.append_column(self.new_column(_('Last modified'), 4, markup=1)) self.entry_find_text.set_text(keywords) self.button_find.activate()
def add(self, vfs_uris, action=None): retval = None for vfs_uri in vfs_uris: uri = vfs_uri.as_uri() path = vfs_uri.as_string() name = uri.get_basename() mime_type = "" pixbuf = None # check for existence: if not uri.query_exists(): continue # check for duplicates duplicate = False iter = self.store.get_iter_first() while iter: store_uri = self.store.get_value(iter, COL_URI) if vfs_uri.equals(store_uri): duplicate = True break iter = self.store.iter_next(iter) if duplicate: continue # check for desktop item if name.endswith(".desktop"): file = vfs.File.for_uri(path) if file is None or not file.exists(): continue entry = fdo.DesktopEntry.for_file(file) name = entry.get_name() icon_name = entry.get_icon() if entry.key_exists( "Icon") else "application-x-executable" mime_type = "" type = gio.FILE_TYPE_REGULAR if icon_name: icon_info = gtk.icon_theme_get_default().lookup_icon( icon_name, self.icon_size, 0) icon_uri = icon_info.get_filename( ) if icon_info else icon_name pixbuf = IconFactory().load_icon(icon_uri, self.icon_size) if pixbuf: pixbuf.add_alpha(True, '\0', '\0', '\0') else: # get file info try: fileinfo = uri.query_info(','.join([ gio.FILE_ATTRIBUTE_STANDARD_TYPE, gio.FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE, gio.FILE_ATTRIBUTE_STANDARD_IS_HIDDEN, gio.FILE_ATTRIBUTE_STANDARD_IS_BACKUP ])) if fileinfo.get_is_hidden() or fileinfo.get_is_backup(): continue type = fileinfo.get_file_type() mime_type = fileinfo.get_content_type() except: continue # get pixbuf for icon pixbuf = Thumbnailer(path, mime_type).get_icon(self.icon_size) if pixbuf: pixbuf.add_alpha(True, '\0', '\0', '\0') # create monitor try: monitor = Monitor(vfs_uri) monitor.connect("deleted", self._deleted_cb) except: monitor = None # add to store iter = self.store.append( [vfs_uri, monitor, type, name, mime_type, pixbuf, None]) if self.store.iter_is_valid(iter): self.emit("item-created", iter) else: print "ERROR in STACK: iter is NOK (stacks_backend.py)" # return pixbuf later? if pixbuf: retval = pixbuf # restructure of dialog needed return (retval is not None)