def do_set_property(self, property, value):
     if property.name == 'name':
         raise AttributeError, "Property 'name' cannot be changed."
     elif property.name == 'label':
         self.label = value
         self.__lset = self.label != ''
         if not self.__lset and self.stock_id != '':
             _item = gtk.stock_lookup(self.stock_id)
             if _item is not None:
                 self.label = _item[2]
         if not self.__slset:
             self.short_label = self.label
             self.notify('short-label')
     elif property.name == 'tooltip':
         self.tooltip = value
     elif property.name == 'stock-id':
         self.stock_id = value
         if not self.__lset:
             _item = gtk.stock_lookup(self.stock_id)
             if _item is not None:
                 self.label = _item[2]
             else:
                 self.label = ''
             self.notify('label')
         if not self.__slset:
             self.short_label = self.label
             self.notify('short-label')
     elif property.name == 'action-group':
         self.action_group = value
     elif property.name == 'hide-if-empty':
         self.hide_if_empty = value
     elif property.name == 'is-important':
         self.is_important = value
     elif property.name == 'sensitive':
         self.set_sensitive(value)
     elif property.name == 'short-label':
         self.short_label = value
         self.__slset = self.short_label != ''
         if not self.__slset:
             self.__slset = self.label
     elif property.name == 'visible':
         self.set_visible(value)
     elif property.name == 'visible-horizontal':
         self.visible_horizontal = value
     elif property.name == 'visible-overflow':
         self.visible_overflown = value
     elif property.name == 'visible-vertical':
         self.visible_vertical = value
     else:
         raise AttributeError, "Unknown property '%s'" % property
Пример #2
0
def run_command_arg_dialog(cmd_name, help_text, run_hook):
    """Launch a dialog to get extra arguments for a command."""
    checker_function = lambda t: True
    dialog, container, name_entry = get_naming_dialog(cmd_name,
                                                      checker_function)
    dialog.set_title(cmd_name)
    help_label = gtk.stock_lookup(gtk.STOCK_HELP)[1].strip("_")
    help_button = rose.gtk.util.CustomButton(
            stock_id=gtk.STOCK_HELP,
            label=help_label,
            size=gtk.ICON_SIZE_LARGE_TOOLBAR)
    help_button.connect(
                "clicked",
                lambda b: rose.gtk.util.run_scrolled_dialog(
                                help_text,
                                title=help_label))
    help_hbox = gtk.HBox()
    help_hbox.pack_start(help_button, expand=False, fill=False)
    help_hbox.show()
    container.pack_end(help_hbox, expand=False, fill=False)
    name_entry.grab_focus()
    dialog.connect("response", _handle_command_arg_response, run_hook,
                   name_entry)
    dialog.set_modal(False)
    dialog.show()
Пример #3
0
    def show_toast(self, body, icon=None, urgency="low", summary=_notifyRealm, name=None):
        tray_x = 0
        tray_y = 0

        if notifyInitialized:
            sleep(0.5)  # FIXME: issue #43, associate the balloon with the notification icon properly. Currently, this is a hack to leave time for the tray icon to appear before getting its coordinates
            if self.notifier.tray:
                tray_x = self.notifier.tray.get_x()
                tray_y = self.notifier.tray.get_y()
            else:
                tray_x = 0
                tray_y = 0
            self.toast = pynotify.Notification(summary, body)
            if name:
                # If name is not None and exists in specto.watch_db, a button is added to the notification
                w = self.specto.watch_db.find_watch(name)
                if w != -1 and self.capabilities["actions"]:  # Don't request action buttons if the notification daemon (ex: notify-osd) rejects them
                    self.toast.add_action("clicked", gtk.stock_lookup(gtk.STOCK_JUMP_TO)[1].replace('_', ''), self.__open_watch, w)
            self.toast.set_urgency(self._Urgencies[urgency])
            if icon:
                #self.toast.set_property('icon-name', icon)  # We now use a pixbuf in the line below to allow themable icons
                self.toast.set_icon_from_pixbuf(icon)

            if tray_x != 0 and tray_y != 0:  # grab the x and y position of the tray icon and make the balloon emerge from it
                self.toast.set_hint("x", tray_x)
                self.toast.set_hint("y", tray_y)

            try:
                self.toast.show()
            except:
                self.specto.logger.log(_("Cannot display notification message. Make sure that libnotify and D-Bus are available on your system."), "error", self.specto)
Пример #4
0
 def setup_actions(self, keymap=None):
     self.main_actg = G.ActionGroup('Main')
     for entry in self.main_act_table:
         self.action_states[entry[0]] = None
         n, lab, cb = entry[:3]
         if G.stock_lookup(lab) is not None:
             a = G.Action(n, None, None, lab)
         else:
             a = G.Action(n, lab, None, None)
         if cb is not None:
             a.connect('activate', partial(cb, self))
         if keymap is not None and n in keymap and keymap[n]:
             self.main_actg.add_action_with_accel(a, keymap[n])
         else:
             self.main_actg.add_action(a)
     self.zoom_actg = G.ActionGroup('Zoom')
     first_zoom_action = None
     for n, lab, v in self.zoom_act_table:
         a = G.RadioAction(n, lab, None, None, v)
         if first_zoom_action is None:
             first_zoom_action = a
             a.connect('changed', self.on_zoom_changed)
         else:
             a.set_group(first_zoom_action)
         self.zoom_actg.add_action(a)
     self.rotate_actg = G.ActionGroup('Rotate')
     first_rotate_action = None
     for n, lab, v in self.rotate_act_table:
         a = G.RadioAction(n, lab, None, None, v)
         if first_rotate_action is None:
             first_rotate_action = a
             a.connect('changed', self.on_rotate_changed)
         else:
             a.set_group(first_rotate_action)
         self.rotate_actg.add_action(a)
Пример #5
0
    def __init__(self, specto, body, icon=None, x=0, y=0, urgency="low", summary=_notifyRealm, name=None):
        global notifyInitialized

        if not notifyInitialized:
           pynotify.init(self._notifyRealm)
           notifyInitialized = True

        self.specto=specto
        self.toast = pynotify.Notification(summary, body)
        self.timeout = specto.specto_gconf.get_entry("pop_toast_duration")*1000
        if self.timeout:
            self.toast.set_timeout(self.timeout)
        if name:
            #If name is not None and exists in specto.watch_db, a button is added to the notification
            w = self.specto.find_watch(name)
            if w != -1:
                self.toast.add_action("clicked", gtk.stock_lookup(gtk.STOCK_JUMP_TO)[1].replace('_', ''), self.__open_watch, w)
        self.toast.set_urgency(self._Urgencies[urgency])
        if icon:
            #self.toast.set_property('icon-name', icon)#we now use a pixbuf in the line below to allow themable icons
            self.toast.set_icon_from_pixbuf(icon)
            
        if x!=0 and y!=0:#grab the x and y position of the tray icon and make the balloon emerge from it
            self.toast.set_hint("x", x)
            self.toast.set_hint("y", y)
        
        if not self.toast.show():
            specto.logger.log("Can't send Notification message. Check your DBUS!", "error", self.__class__)
Пример #6
0
	def add_buttons(self, *args):
		""" add_buttons(Label0, ResponseID0, StockID1, ResponseID1, ...) """

		if len(args) % 2 != 0:
			raise ValueError, "Not enough arguments supplied, (Button, Response,...)"

		i = 0
		while i < len(args)-1:

			try:
				stock_info = gtk.stock_lookup(args[i])
			except TypeError:
				stock_info = None

			if stock_info != None:
				# Stock item
				button = gtk.Button(stock = args[i])

			else:
				# Label
				button = gtk.Button(label = args[i])

			button.connect("clicked", lambda w,id: self.response(id), args[i+1])
			self.buttonbox.add(button)

			i += 2
Пример #7
0
    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
Пример #8
0
    def open_menu(self, menu):

        # always work on a copy
        menu = menu[:]

        if (menu): menu.append(MenuItem("/__separator"))
        menu += self.__DISPLAY_MENU

        mainmenu = gtk.Menu()
        tree = {}
        for entry in menu:
            if (not entry.label):
                item = gtk.SeparatorMenuItem()

            elif (entry.icon):
                if (gtk.stock_lookup(entry.icon)):
                    item = gtk.ImageMenuItem(entry.icon)
                    if (entry.label):
                        item.get_children()[0].set_text_with_mnemonic(entry.label)

                else:
                    item = gtk.ImageMenuItem(entry.label)
                    try:
                        img = Tiling()
                        data = vfs.read_entire_file(self.get_full_path(entry.icon))
                        img.set_from_data(data)
                        img.render(16, 16, 1, 1)
                        img.show()
                        item.set_image(img)
                    except:
                        import traceback; traceback.print_exc()

            else:
                item = gtk.MenuItem(entry.label)

            if (entry.callback):
                item.connect("activate",
                             lambda src, cb, args: cb(*args),
                             entry.callback, entry.args)

            item.show()
            if (not entry.active): item.set_sensitive(False)

            menupath = "/".join(entry.path.split("/")[:-1])
            if (menupath):
                parentitem = tree.get(menupath)

                if (not parentitem.get_submenu()):
                    m = gtk.Menu()
                    parentitem.set_submenu(m)
                else:
                    m = parentitem.get_submenu()

            else:
                m = mainmenu

            m.append(item)
            tree["/".join(entry.path.split("/"))] = item

        mainmenu.popup(None, None, None, 0, 0)
Пример #9
0
    def _load_stock_items(self):
        groups = {
            "a": gtk.ToolItemGroup("Stock Icons (A-F)"),
            "g": gtk.ToolItemGroup("Stock Icons (G-N)"),
            "o": gtk.ToolItemGroup("Stock Icons (O-R)"),
            "s": gtk.ToolItemGroup("Stock Icons (S-Z)")
        }
        group = groups["a"]
        for g in groups.values():
            self.palette.add(g)

        items = gtk.stock_list_ids()
        items.sort()
        for i in items:
            #stock id names are in form gtk-foo, sort into one of the groups above
            try:
                group = groups[i[4]]
            except KeyError:
                pass

            b = gtk.ToolButton(i)
            b.set_tooltip_text(i)
            b.set_is_important(True)
            info = gtk.stock_lookup(i)
            if info:
                b.set_label(info[1].replace("_", ""))
            else:
                b.set_label(i)

            group.insert(b, -1)
Пример #10
0
    def __init__(self, box):
        title = gtk.stock_lookup(gtk.STOCK_HELP)[1]
        stock.register('sweetener-help-contents', title, '<Ctrl>H',
                       'toolbar-help')
        SettingsItem.__init__(self, None, 'sweetener-help-contents')

        sw = gtk.ScrolledWindow()
        sw.set_size_request(int(gtk.gdk.screen_width() / 2.8),
                            gtk.gdk.screen_height() - style.GRID_CELL_SIZE * 3)
        sw.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        self._max_text_width = int(gtk.gdk.screen_width() / 3) - 20
        self._vbox = gtk.VBox()
        self._vbox.set_homogeneous(False)
        hbox = gtk.HBox()
        hbox.pack_start(self._vbox, False, True, 0)
        sw.add_with_viewport(hbox)
        sw.show()
        self.content = sw
        item = self.get_tool_item()
        item.show_all()
        separator = gtk.SeparatorToolItem()
        separator.show()
        box.toolbar.insert(separator, len(box.toolbar.get_children()[:-2]))
        box.toolbar.insert(item, len(box.toolbar.get_children()[:-2]))
        for i in helpcontent.help:
            self.add_section(i[0])
            for text, icon in i[1:]:
                self.add_paragraph(text, icon)
Пример #11
0
    def __init__(self, label, stock=None):
        """An menu item with an (option) icon.

        you can use this in three different ways:

        ContextMenuItem('foo')
        ContextMenuItem('foo', gtk.STOCK_PASTE)
        ContextMenuItem(gtk.STOCK_PASTE)

        The first will display an label 'foo'. The second will display the same label with the
        paste icon, and the last will display the paste icon with the default paste label
        """
        gtk.ImageMenuItem.__init__(self)

        if not stock:
            stock = label
            info = gtk.stock_lookup(label)
            if info:
                try:
                    label = info.label
                # For PyGTk
                except AttributeError:
                    label = info[1]

        lbl = gtk.AccelLabel(label)
        lbl.set_alignment(0, 0.5)
        lbl.set_use_underline(True)
        lbl.set_use_markup(True)
        self.add(lbl)

        image = gtk.Image()
        image.set_from_stock(stock, gtk.ICON_SIZE_MENU)
        self.set_image(image)
Пример #12
0
def get_stock_icons():
    """
    Get a sorted list of all available stock icons
    @returns: a list of tuples; (stock_label, stock_id)
    """

    global _stock_icons
    if _stock_icons:
        return _stock_icons

    icons = []

    for stock_id in gtk.stock_list_ids():
        # Do not list stock ids starting with gazpacho-, they
        # are considered private
        if stock_id.startswith('gazpacho-'):
            continue

        stock_info = gtk.stock_lookup(stock_id)
        if not stock_info:
            # gtk-new -> New
            if stock_id.startswith('gtk-'):
                stock_label = stock_id[4:].replace('-', ' ')
            else:
                stock_label = stock_id
            stock_label = stock_label.capitalize()
        else:
            stock_label = stock_info[1].replace('_', '')

        icons.append((stock_label, stock_id))

    icons.sort()
    _stock_icons = icons

    return icons
Пример #13
0
    def __init__(self, label, stock=None):
        """An menu item with an (option) icon.

        you can use this in three different ways:

        ContextMenuItem('foo')
        ContextMenuItem('foo', gtk.STOCK_PASTE)
        ContextMenuItem(gtk.STOCK_PASTE)

        The first will display an label 'foo'. The second will display the same label with the
        paste icon, and the last will display the paste icon with the default paste label
        """
        # For some reason I don't know, gtk.ImageMenuItem.__init__(...) does not work. It
        # complains I should use __gobject_init__ instead.
        self.__gobject_init__()

        if not stock:
            stock = label
            info = gtk.stock_lookup(label)
            if info:
                label = info[1]

        lbl = gtk.AccelLabel(label)
        lbl.set_alignment(0, 0.5)
        lbl.set_use_underline(True)
        lbl.set_use_markup(True)
        self.add(lbl)

        image = gtk.Image()
        image.set_from_stock(stock, gtk.ICON_SIZE_MENU)
        self.set_image(image)
Пример #14
0
 def setup_tooltip(self):
     if self.tooltip:
         self.toolitem.set_title(self.tooltip)
     else:
         text = gtk.stock_lookup(self.stock_id)[1]
         self.toolitem.set_title(text.replace('_', ''))
     self.setup_accelerator()
Пример #15
0
    def __init__(self, label, stock=None):
        """An menu item with an (option) icon.

        you can use this in three different ways:

        ContextMenuItem('foo')
        ContextMenuItem('foo', gtk.STOCK_PASTE)
        ContextMenuItem(gtk.STOCK_PASTE)

        The first will display an label 'foo'. The second will display the same label with the
        paste icon, and the last will display the paste icon with the default paste label
        """
        # For some reason I don't know, gtk.ImageMenuItem.__init__(...) does not work. It
        # complains I should use __gobject_init__ instead.
        self.__gobject_init__()

        if not stock:
            stock = label
            info = gtk.stock_lookup(label)
            if info:
                label = info[1]

        lbl = gtk.AccelLabel(label)
        lbl.set_alignment(0, 0.5)
        lbl.set_use_underline(True)
        lbl.set_use_markup(True)
        self.add(lbl)

        image = gtk.Image()
        image.set_from_stock(stock, gtk.ICON_SIZE_MENU)
        self.set_image(image)
Пример #16
0
    def _load_stock_items(self):
        groups = {
            "a": gtk.ToolItemGroup("Stock Icons (A-F)"),
            "g": gtk.ToolItemGroup("Stock Icons (G-N)"),
            "o": gtk.ToolItemGroup("Stock Icons (O-R)"),
            "s": gtk.ToolItemGroup("Stock Icons (S-Z)"),
        }
        group = groups["a"]
        for g in groups.values():
            self.palette.add(g)

        items = gtk.stock_list_ids()
        items.sort()
        for i in items:
            # stock id names are in form gtk-foo, sort into one of the groups above
            try:
                group = groups[i[4]]
            except KeyError:
                pass

            b = gtk.ToolButton(i)
            b.set_tooltip_text(i)
            b.set_is_important(True)
            info = gtk.stock_lookup(i)
            if info:
                b.set_label(info[1].replace("_", ""))
            else:
                b.set_label(i)

            group.insert(b, -1)
Пример #17
0
def overwrite_stock(stock_id, new_accelerator):
    info = list(gtk.stock_lookup(stock_id))
    keyval, mask = gtk.accelerator_parse(new_accelerator)
    info[2] = mask
    info[3] = keyval
    logger.debug(str(info))
    gtk.stock_add([(info[0], info[1], info[2], info[3], info[4])])
Пример #18
0
    def __init__(self, label, stock=None):
        """An menu item with an (option) icon.

        you can use this in three different ways:

        ContextMenuItem('foo')
        ContextMenuItem('foo', gtk.STOCK_PASTE)
        ContextMenuItem(gtk.STOCK_PASTE)

        The first will display an label 'foo'. The second will display the same label with the
        paste icon, and the last will display the paste icon with the default paste label
        """
        gtk.ImageMenuItem.__init__(self)

        if not stock:
            stock = label
            info = gtk.stock_lookup(label)
            if info:
                try:
                    label = info.label
                # For PyGTk
                except AttributeError:
                    label = info[1]

        lbl = gtk.AccelLabel(label)
        lbl.set_alignment(0, 0.5)
        lbl.set_use_underline(True)
        lbl.set_use_markup(True)
        self.add(lbl)

        image = gtk.Image()
        image.set_from_stock(stock, gtk.ICON_SIZE_MENU)
        self.set_image(image)
Пример #19
0
    def add_buttons(self, *args):
        """ add_buttons(Label0, ResponseID0, StockID1, ResponseID1, ...) """

        if len(args) % 2 != 0:
            raise ValueError, "Not enough arguments supplied, (Button, Response,...)"

        i = 0
        while i < len(args) - 1:

            try:
                stock_info = gtk.stock_lookup(args[i])
            except TypeError:
                stock_info = None

            if stock_info != None:
                # Stock item
                button = gtk.Button(stock=args[i])

            else:
                # Label
                button = gtk.Button(label=args[i])

            button.connect("clicked", lambda w, id: self.response(id),
                           args[i + 1])
            self.buttonbox.add(button)

            i += 2
 def add_action_with_accel(self, action, accel):
     # print "add_action_with_accel"
     _keyval = None
     _mods = None
     _name = action.get_name()
     _path = "/".join(['<Actions>', self.name, _name])
     if accel is None:
         # print "accel is None"
         _sid = action.get_property('stock-id')
         if _sid != '':
             # print "sid = '%s'" % _sid
             _data = gtk.stock_lookup(_sid)
             if _data is not None and _data[3] != 0:
                 # print "data: " + str(_data)
                 _mods = _data[2]
                 _keyval = _data[3]
     else:
         _k, _m = gtk.accelerator_parse(accel)
         if gtk.accelerator_valid(_k, _m):
             _keyval = _k
             _mods = _m
     if _keyval is not None:
         # print "calling gtk.accel_map_change_entry()"
         # print "Path: " + _path
         # print "Key: " + str(_keyval)
         # print "Mods: " + str(_mods)
         if not gtk.accel_map_change_entry(_path, _keyval, _mods, True):
             print "Failed to change accel_map for '%s'" % _path
     action.set_accel_path(_path)
     self.add_action(action)
Пример #21
0
    def __update_paused(self, player, paused):
        menu = self.ui.get_widget("/Menu/Control/PlayPause")

        if paused: key = gtk.STOCK_MEDIA_PLAY
        else: key = gtk.STOCK_MEDIA_PAUSE
        text = gtk.stock_lookup(key)[1]
        menu.get_image().set_from_stock(key, gtk.ICON_SIZE_MENU)
        menu.set_label(text)
        menu.set_use_underline(True)
Пример #22
0
    def __create_model(self):
        store = gtk.ListStore(
            gobject.TYPE_PYOBJECT,
            gobject.TYPE_STRING)

        ids = gtk.stock_list_ids()
        ids.sort()

        for data in ids:
            info = StockItemInfo(stock_id=data)
            stock_item = gtk.stock_lookup(data)

            if stock_item:
                info.stock_item = stock_item
            else:
                # stock_id, label, modifier, keyval, translation_domain
                info.stock_item =('', '', 0, 0, '')

            # only show icons for stock IDs that have default icons
            icon_set = gtk.icon_factory_lookup_default(info.stock_id)
            if icon_set is None:
                info.small_icon = None
            else:
                # See what sizes this stock icon really exists at
                sizes = icon_set.get_sizes()
                n_sizes = len(sizes)

                # Use menu size if it exists, otherwise first size found
                size = sizes[0];
                i = 0;
                while(i < n_sizes):
                    if(sizes[i] == gtk.ICON_SIZE_MENU):
                        size = gtk.ICON_SIZE_MENU
                        break
                    i += 1

                info.small_icon = self.render_icon(info.stock_id, size)

                if(size != gtk.ICON_SIZE_MENU):
                    # Make the result the proper size for our thumbnail
                    w, h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)

                    scaled = info.small_icon.scale_simple(w, h, 'bilinear')
                    info.small_icon = scaled

            if info.stock_item[3] == 0:
                info.accel_str = ""
            else:
                info.accel_str = \
                    gtk.accelerator_name(info.stock_item[3], info.stock_item[2])

            iter = store.append()
            store.set(iter, 0, info, 1, info.stock_id)

        return store
Пример #23
0
 def append_toggle(self, stock, signal, accelerator = None, toggled = True):
     info = gtk.stock_lookup(stock)
     label = info[1] if info else stock
     menuitem = gtk.CheckMenuItem(label)
     menuitem.set_active(toggled)
     self.submenu.append(menuitem)
     menuitem.connect("toggled", self.activate, signal)
     self.install_signal(signal)
     if accelerator:
         key, mask = gtk.accelerator_parse(accelerator)
         menuitem.add_accelerator("toggled", self.application.bindings, key, mask, gtk.ACCEL_VISIBLE)
Пример #24
0
 def autobuild_tooltips(self, toolbar):
     """Scan GTK Toolbar recursively and set the Buttons tooltip."""
     for c in toolbar.get_children():
         if hasattr(c, 'get_stock_id'):
             stock = c.get_stock_id()
             if stock is not None and not c.get_property('has-tooltip'):
                 infos = gtk.stock_lookup(stock)
                 if infos is not None:
                     txt = infos[1].replace('_','')
                     c.set_tooltip_text(txt)
     return
Пример #25
0
 def append_toggle(self, stock, signal, accelerator=None, toggled=True):
     info = gtk.stock_lookup(stock)
     label = info[1] if info else stock
     menuitem = gtk.CheckMenuItem(label)
     menuitem.set_active(toggled)
     self.submenu.append(menuitem)
     menuitem.connect("toggled", self.activate, signal)
     self.install_signal(signal)
     if accelerator:
         key, mask = gtk.accelerator_parse(accelerator)
         menuitem.add_accelerator("toggled", self.application.bindings, key,
                                  mask, gtk.ACCEL_VISIBLE)
Пример #26
0
    def __create_model(self):
        store = gtk.ListStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING)

        ids = gtk.stock_list_ids()
        ids.sort()

        for data in ids:
            info = StockItemInfo(stock_id=data)
            stock_item = gtk.stock_lookup(data)

            if stock_item:
                info.stock_item = stock_item
            else:
                # stock_id, label, modifier, keyval, translation_domain
                info.stock_item = ('', '', 0, 0, '')

            # only show icons for stock IDs that have default icons
            icon_set = gtk.icon_factory_lookup_default(info.stock_id)
            if icon_set is None:
                info.small_icon = None
            else:
                # See what sizes this stock icon really exists at
                sizes = icon_set.get_sizes()
                n_sizes = len(sizes)

                # Use menu size if it exists, otherwise first size found
                size = sizes[0]
                i = 0
                while (i < n_sizes):
                    if (sizes[i] == gtk.ICON_SIZE_MENU):
                        size = gtk.ICON_SIZE_MENU
                        break
                    i += 1

                info.small_icon = self.render_icon(info.stock_id, size)

                if (size != gtk.ICON_SIZE_MENU):
                    # Make the result the proper size for our thumbnail
                    w, h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)

                    scaled = info.small_icon.scale_simple(w, h, 'bilinear')
                    info.small_icon = scaled

            if info.stock_item[3] == 0:
                info.accel_str = ""
            else:
                info.accel_str = \
                    gtk.accelerator_name(info.stock_item[3], info.stock_item[2])

            iter = store.append()
            store.set(iter, 0, info, 1, info.stock_id)

        return store
Пример #27
0
    def prop_set_stock_id(self, action, value):
        action.set_property('stock-id', value)

        # Set the accelerator from the stock item, but only if it's
        # not set already
        if action.get_data('accel_key'):
            return

        # FIXME: Should we print a warning if it cannot be found
        stock_item = gtk.stock_lookup(value)
        if stock_item:
            self._set_accel(action, stock_item[3], stock_item[2])
Пример #28
0
	def create_stock_item(self, id, name, icon = None):
		"Creates a stock item"

		gtk.stock_add(((id, name, 0, 0, None), ))

		if icon is None:
			pass

		elif gtk.stock_lookup(icon) is not None:
			self.add(id, self.parent.get_style().lookup_icon_set(icon))

		else:
			self.create_stock_icon(id, icon, ( gtk.ICON_SIZE_SMALL_TOOLBAR, gtk.ICON_SIZE_LARGE_TOOLBAR, gtk.ICON_SIZE_MENU, gtk.ICON_SIZE_BUTTON, gtk.ICON_SIZE_DIALOG, ICON_SIZE_LABEL, ICON_SIZE_HEADLINE ))
Пример #29
0
    def create_item(self, p_type, p_text=None, p_stock=None, p_accel=None):
        """
            p_type:  una cadena que representa el tipo de elemento de menu a
                     crear. 'p_type' puede ser "normal", "image", "check",
                     "radio" o "separator".
            p_text:  una cadena a mostrar por el elemento de menu.
            p_stock: una cadena que represente un 'stock de gtk' o una
                     direccion de una imagen a mostrar por el elemento de menu.
            p_accel: una cadena que representa la combinacion de teclas que
                     activa a dicho elemento de menu. 'p_accel' es lo ultimo
                     que se muestra en el elemento de menu.

            Retorna: un 'gtk.MenuItem' en dependencia de los parametros dados.

            Crea y retorna un elemento de menu segun los parametros dados.
        """
        if p_type == "normal":
            item = gtk.MenuItem()

        elif p_type == "image":
            item = gtk.ImageMenuItem()
            img = gtk.Image()
            if gtk.stock_lookup(p_stock):
                img.set_from_stock(p_stock, gtk.ICON_SIZE_MENU)
            else:
                img.set_from_file(p_stock)
            item.set_image(img)

        elif p_type == "check":
            item = gtk.CheckMenuItem()

        elif p_type == "radio":
            pass

        else:
            return gtk.SeparatorMenuItem()

        hbox = gtk.HBox(False, 15)

        label = gtk.Label(p_text)
        label.set_use_underline(True)
        label.set_alignment(0.0, 0.5)
        self.__size_group.add_widget(label)
        hbox.pack_start(label, False)

        if p_accel:
            hbox.pack_end(gtk.Label(p_accel), False)

        item.add(hbox)
        return item
Пример #30
0
    def __init__(self, header, text, icon, buttons, parent=None):
        """
        :param header: str, the header portion of the dialog
        :param text: str, the text body of the dialog
        :param icon: gtk Stock ID, a stock id for the gtk icon to display
        :param buttons: tuple, of gtk stock ids and responses
        :param parent: gtkWindow, the parent window, if None it will default to the
            MainWindow
        """
        super(BaseDialog, self).__init__(
            title=header,
            parent=parent if parent else component.get('MainWindow').window,
            flags=gtk.DIALOG_MODAL
            | gtk.DIALOG_DESTROY_WITH_PARENT
            | gtk.DIALOG_NO_SEPARATOR,
            buttons=buttons,
        )

        self.set_icon(get_deluge_icon())

        self.connect('delete-event', self._on_delete_event)
        self.connect('response', self._on_response)

        # Setup all the formatting and such to make our dialog look pretty
        self.set_border_width(5)
        self.set_default_size(200, 100)
        hbox = gtk.HBox(spacing=5)
        image = gtk.Image()
        if not gtk.stock_lookup(icon) and (
            icon.endswith('.svg') or icon.endswith('.png')
        ):
            # Hack for Windows since it doesn't support svg
            if icon.endswith('.svg') and windows_check():
                icon = icon.rpartition('.svg')[0] + '16.png'
            image.set_from_pixbuf(get_pixbuf_at_size(icon, 32))
        else:
            image.set_from_stock(icon, gtk.ICON_SIZE_DIALOG)
        image.set_alignment(0.5, 0.0)
        hbox.pack_start(image, False, False, 0)
        vbox = gtk.VBox(spacing=5)
        tlabel = gtk.Label(text)
        tlabel.set_use_markup(True)
        tlabel.set_line_wrap(True)
        tlabel.set_alignment(0.0, 0.5)
        vbox.pack_start(tlabel, False, False, 0)
        hbox.pack_start(vbox, False, False, 0)
        self.vbox.pack_start(hbox, False, False, 0)
        self.vbox.set_spacing(5)
        self.vbox.show_all()
Пример #31
0
    def show_toast(self,
                   body,
                   icon=None,
                   urgency="low",
                   summary=_notifyRealm,
                   name=None):
        tray_x = 0
        tray_y = 0

        if notifyInitialized:
            sleep(
                0.5
            )  # FIXME: issue #43, associate the balloon with the notification icon properly. Currently, this is a hack to leave time for the tray icon to appear before getting its coordinates
            if self.notifier.tray:
                tray_x = self.notifier.tray.get_x()
                tray_y = self.notifier.tray.get_y()
            else:
                tray_x = 0
                tray_y = 0
            self.toast = pynotify.Notification(summary, body)
            if name:
                # If name is not None and exists in specto.watch_db, a button is added to the notification
                w = self.specto.watch_db.find_watch(name)
                if w != -1 and self.capabilities[
                        "actions"]:  # Don't request action buttons if the notification daemon (ex: notify-osd) rejects them
                    self.toast.add_action(
                        "clicked",
                        gtk.stock_lookup(gtk.STOCK_JUMP_TO)[1].replace(
                            '_', ''), self.__open_watch, w)
            self.toast.set_urgency(self._Urgencies[urgency])
            if icon:
                #self.toast.set_property('icon-name', icon)  # We now use a pixbuf in the line below to allow themable icons
                self.toast.set_icon_from_pixbuf(icon)

            if tray_x != 0 and tray_y != 0:  # grab the x and y position of the tray icon and make the balloon emerge from it
                self.toast.set_hint("x", tray_x)
                self.toast.set_hint("y", tray_y)

            try:
                self.toast.show()
            except:
                self.specto.logger.log(
                    _("Cannot display notification message. Make sure that libnotify and D-Bus are available on your system."
                      ), "error", self.specto)
Пример #32
0
    def __init__(self,
                 specto,
                 body,
                 icon=None,
                 x=0,
                 y=0,
                 urgency="low",
                 summary=_notifyRealm,
                 name=None):
        global notifyInitialized

        if not notifyInitialized:
            pynotify.init(self._notifyRealm)
            notifyInitialized = True

        self.specto = specto
        self.toast = pynotify.Notification(summary, body)
        self.timeout = specto.specto_gconf.get_entry(
            "pop_toast_duration") * 1000
        if self.timeout:
            self.toast.set_timeout(self.timeout)
        if name:
            #If name is not None and exists in specto.watch_db, a button is added to the notification
            w = self.specto.find_watch(name)
            if w != -1:
                self.toast.add_action(
                    "clicked",
                    gtk.stock_lookup(gtk.STOCK_JUMP_TO)[1].replace('_', ''),
                    self.__open_watch, w)
        self.toast.set_urgency(self._Urgencies[urgency])
        if icon:
            #self.toast.set_property('icon-name', icon)#we now use a pixbuf in the line below to allow themable icons
            self.toast.set_icon_from_pixbuf(icon)

        if x != 0 and y != 0:  #grab the x and y position of the tray icon and make the balloon emerge from it
            self.toast.set_hint("x", x)
            self.toast.set_hint("y", y)

        if not self.toast.show():
            specto.logger.log(
                "Can't send Notification message. Check your DBUS!", "error",
                self.__class__)
Пример #33
0
def getPixbufFromStock(iconName, size=gtk.ICON_SIZE_MENU):
    """
    @summary: Gets a pixbuf from stock.
    @param iconName: Name of the icon, if it is in current theme.
    @param size: Size of the icon.
    @return: Pixbuf with the icon.
    @raise TypeError: raise when any parameter type is not correct
    """
    if (not isinstance(iconName, str)):
        __log__.error("iconName is not str")
        raise TypeError("iconName is not str")
    if (not isinstance(size, (int, int))):
        __log__.error("size is not (int, int)")
        raise TypeError("size is not (int, int)")
    
    icon = None
    theme = gtk.icon_theme_get_default()
    
    if (iconName != None):
        if (theme.has_icon(iconName)):
            pixelSize = gtk.icon_size_lookup(size)
            icon = theme.load_icon(iconName, pixelSize[0], 0)
        else:
        	if (icon == None):
	        	lk = gtk.stock_lookup(iconName)
    	    	if (lk != None):
        			ctrl = gtk.MenuItem()
        			icon = ctrl.render_icon(lk[0], size)
	        		ctrl = None
		elif (iconName == gtk.STOCK_FILE):
			icon = None
		elif (iconName != gtk.STOCK_MISSING_IMAGE):
			icon = getPixbufFromStock(gtk.STOCK_FILE)
    	    	else:
			__log__.warning("There is not an icon with name %s" % iconName)
            		icon = None
    else:
        __log__.warning("iconName is None.")
        icon = None
        
    return icon
Пример #34
0
def run_command_arg_dialog(cmd_name, help_text, run_hook):
    """Launch a dialog to get extra arguments for a command."""
    checker_function = lambda t: True
    dialog, container, name_entry = get_naming_dialog(cmd_name,
                                                      checker_function)
    dialog.set_title(cmd_name)
    help_label = gtk.stock_lookup(gtk.STOCK_HELP)[1].strip("_")
    help_button = rose.gtk.util.CustomButton(stock_id=gtk.STOCK_HELP,
                                             label=help_label,
                                             size=gtk.ICON_SIZE_LARGE_TOOLBAR)
    help_button.connect(
        "clicked", lambda b: run_scrolled_dialog(help_text, title=help_label))
    help_hbox = gtk.HBox()
    help_hbox.pack_start(help_button, expand=False, fill=False)
    help_hbox.show()
    container.pack_end(help_hbox, expand=False, fill=False)
    name_entry.grab_focus()
    dialog.connect("response", _handle_command_arg_response, run_hook,
                   name_entry)
    dialog.set_modal(False)
    dialog.show()
Пример #35
0
    def prop_set_use_stock(self, menuitem, value):
        child = menuitem.child

        if not child:
            child = gtk.AccelLabel("")
            child.set_alignment(0.0, 0.5)
            menuitem.add(child)
            child.set_accel_widget(menuitem)
            child.show()

        value = str2bool(value)
        if not isinstance(child, gtk.Label) or not value:
            return

        stock_id = child.get_label()

        retval = gtk.stock_lookup(stock_id)
        if retval:
            _, label, modifier, keyval, _ = retval
            # put in the stock image next to the text.  Done before
            # messing with the label child, so that stock_id doesn't
            # become invalid.
            if isinstance(menuitem, gtk.ImageMenuItem):
                image = gtk.image_new_from_stock(stock_id, gtk.ICON_SIZE_MENU)
                menuitem.set_image(image)
                image.show()

            child.set_text(label)
            child.set_use_underline(True)

            if keyval:
                # This triggers a segfault on exit (pachi.glade), weird
                menuitem.add_accelerator('activate',
                                         self._build.ensure_accel(),
                                         keyval, modifier,
                                         gtk.ACCEL_VISIBLE)
        else:
            print "warning: could not look up stock id '%s'" % stock_id
Пример #36
0
    def _load_plugin_pages(self):
        self._clear_children(self.plug_root)
        plugin_pages = []
        plugin_manager = self.main.exaile.plugins

        for name in plugin_manager.enabled_plugins:
            plugin = plugin_manager.enabled_plugins[name]
            if hasattr(plugin, 'get_preferences_pane'):
                try:
                    plugin_pages.append(plugin.get_preferences_pane())
                except Exception:
                    logger.warning('Error loading preferences pane')
                    traceback.print_exc()

        import locale
        plugin_pages.sort(key=lambda x: locale.strxfrm(x.name))

        for page in plugin_pages:
            icon = self.default_icon

            if hasattr(page, 'icon'):
                if isinstance(page.icon, gtk.gdk.Pixbuf):
                    icon = page.icon
                else:
                    stock_id = gtk.stock_lookup(page.icon)

                    if stock_id is not None:
                        icon = icons.MANAGER.pixbuf_from_stock(
                            stock_id[0], gtk.ICON_SIZE_MENU)
                    else:
                        icon = icons.MANAGER.pixbuf_from_icon_name(
                            page.icon, gtk.ICON_SIZE_MENU)

            self.model.append(self.plug_root, [page, page.name, icon])

        glib.idle_add(self.tree.expand_row,
            self.model.get_path(self.plug_root), False)
Пример #37
0
    def _load_plugin_pages(self):
        self._clear_children(self.plug_root)
        plugin_pages = []
        plugin_manager = self.main.exaile.plugins

        for name in plugin_manager.enabled_plugins:
            plugin = plugin_manager.enabled_plugins[name]
            if hasattr(plugin, 'get_preferences_pane'):
                try:
                    plugin_pages.append(plugin.get_preferences_pane())
                except Exception:
                    logger.warning('Error loading preferences pane')
                    traceback.print_exc()

        import locale
        plugin_pages.sort(key=lambda x: locale.strxfrm(x.name))

        for page in plugin_pages:
            icon = self.default_icon

            if hasattr(page, 'icon'):
                if isinstance(page.icon, gtk.gdk.Pixbuf):
                    icon = page.icon
                else:
                    stock_id = gtk.stock_lookup(page.icon)

                    if stock_id is not None:
                        icon = icons.MANAGER.pixbuf_from_stock(
                            stock_id[0], gtk.ICON_SIZE_MENU)
                    else:
                        icon = icons.MANAGER.pixbuf_from_icon_name(
                            page.icon, gtk.ICON_SIZE_MENU)

            self.model.append(self.plug_root, [page, page.name, icon])

        glib.idle_add(self.tree.expand_row,
                      self.model.get_path(self.plug_root), False)
Пример #38
0
        return '<b>%s</b>' % self._name


icons = ObjectList([
    Column(title='Stock Data',
           cells=[
               Cell('stock_name', gtk.Pixmap, use_stock=True),
               Cell('stock_name', str),
           ],
           sorted=False),
    Column('name', str, 'Name', use_markup=True),
],
                   sortable=True)

for id in gtk.stock_list_ids():
    lookup = gtk.stock_lookup(id)
    if lookup is None:
        continue
    stock_name, name = gtk.stock_lookup(id)[:2]
    name = name.replace('_', '')
    icons.append(IconInfo(stock_name, name))

scroll = gtk.ScrolledWindow()
scroll.add(icons)

win = gtk.Window()
win.add(scroll)
win.set_size_request(600, 400)

win.show_all()
win.connect('destroy', gtk.main_quit)
Пример #39
0
def get_label(stock, underline):
    text = gtk.stock_lookup(stock)[1]
    if underline:
        text = text.replace('_', '')
    return text
Пример #40
0
    def __init__(self, parent, main):
        """
            Initializes the preferences dialog
        """
        self.main = main
        self.last_child = None
        self.last_page = None
        self.parent = parent
        self.settings = MANAGER
        self.fields = {}
        self.panes = {}
        self.builders = {}
        self.popup = None

        self.builder = gtk.Builder()
        self.builder.set_translation_domain('exaile')
        self.builder.add_from_file(
            xdg.get_data_path('ui', 'preferences', 'preferences_dialog.ui'))
        self.builder.connect_signals(self)

        self.window = self.builder.get_object('PreferencesDialog')
        self.window.set_transient_for(parent)
        self.window.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.window.connect('delete-event', lambda *e: self.close())

        self.box = self.builder.get_object('preferences_box')

        self.tree = self.builder.get_object('preferences_tree')
        self.model = self.builder.get_object('model')

        title_cellrenderer = self.builder.get_object('title_cellrenderer')
        title_cellrenderer.props.ypad = 3

        self.default_icon = icons.MANAGER.pixbuf_from_stock(
            gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_MENU)

        # sets up the default panes
        for page in self.PAGES:
            icon = self.default_icon

            if hasattr(page, 'icon'):
                if isinstance(page.icon, gtk.gdk.Pixbuf):
                    icon = page.icon
                else:
                    stock_id = gtk.stock_lookup(page.icon)

                    if stock_id is not None:
                        icon = icons.MANAGER.pixbuf_from_stock(
                            stock_id[0], gtk.ICON_SIZE_MENU)
                    else:
                        icon = icons.MANAGER.pixbuf_from_icon_name(
                            page.icon, gtk.ICON_SIZE_MENU)

            self.model.append(None, [page, page.name, icon])

        # Use icon name to allow overrides
        plugin_icon = icons.MANAGER.pixbuf_from_icon_name(
            'extension', gtk.ICON_SIZE_MENU)
        self.plug_root = self.model.append(None,
            [plugin, _('Plugins'), plugin_icon])

        self._load_plugin_pages()

        selection = self.tree.get_selection()
        selection.connect('changed', self.switch_pane)
        # Disallow selection on rows with no widget to show
        selection.set_select_function(lambda path:
            self.model[path][0] is not None)

        glib.idle_add(selection.select_path, (0,))
Пример #41
0
 def isStock(self, button):
     return button.get_use_stock() and gtk.stock_lookup(button.get_label()) is not None
Пример #42
0
def get_accelerator(stock):
    return gtk.stock_lookup(stock)[2:-1]
Пример #43
0
 def cell_data2(col, render, model, iter):
     icon = getattr(model[iter][0], 'PLUGIN_ICON', gtk.STOCK_EXECUTE)
     if gtk.stock_lookup(icon):
         render.set_property('stock-id', icon)
     else:
         render.set_property('icon-name', icon)
Пример #44
0
    def _do_layout(self):
        'Builds the GUI'
        main_h = gtk.HBox()
        main_v = gtk.VBox()
        
        # Title entry
        title_table = gui.ESTable(1)
        self._title_entry = title_table.attach_entry(_("New Theme"),
                                                     label=_("Theme Name"))
        main_v.pack_start(title_table, False, False)
        
        self._notebook = gtk.Notebook()
        self._notebook.connect('switch-page', self._nb_page_changed)
        main_v.pack_start(self._notebook, True, True, 5)
        
        ######################
        # Page 1: Background #
        ######################
        self._treeview_bgs = gtk.TreeView()
        self._treeview_bgs.set_reorderable(True)
        
        gtk.stock_add([('add-background-gradient',_('Add Gradient'), gtk.gdk.MOD1_MASK, 0,
                'pymserv'),
                ('add-background-solid',_('Add Solid Color'), gtk.gdk.MOD1_MASK, 0,
                'pymserv'),
                ('add-background-radial',_('Add Radial Gradient'), gtk.gdk.MOD1_MASK, 0,
                'pymserv'),
               ("add-background-image",_('Add Image'), gtk.gdk.MOD1_MASK, 0,
                'pymserv')])
        
        #Background Toolbar
        toolbar = gtk.Toolbar()
        btn = gtk.ToolButton(gtk.stock_lookup('add-background-image')[0])
        btn.set_tooltip_markup(_("Add a new Image Background"))
        btn.connect('clicked', self._on_bg_image_new)
        toolbar.insert(btn, -1)
        btn = gtk.ToolButton(gtk.stock_lookup('add-background-solid')[0])
        btn.set_tooltip_markup(_("Add a new Solid Color Background"))
        btn.connect('clicked', self._on_bg_solid_new)
        toolbar.insert(btn, -1)
        btn = gtk.ToolButton(gtk.stock_lookup('add-background-gradient')[0])
        btn.set_tooltip_markup(_("Add a new Gradient Background"))
        btn.connect('clicked', self._on_bg_gradient_new)
        toolbar.insert(btn, -1)
        btn = gtk.ToolButton(gtk.stock_lookup('add-background-radial')[0])
        btn.set_tooltip_markup(_("Add a new Radial Gradient Background"))
        btn.connect('clicked', self._on_bg_radial_new)
        toolbar.insert(btn, -1)
        button = gtk.ToolButton(gtk.STOCK_DELETE)
        button.connect('clicked', self._on_delete_bg)
        toolbar.insert(button, -1)
        
        # Background Treeview Columns
        self._bg_model = gtk.ListStore(gobject.TYPE_PYOBJECT)
        self._column_bgs = gtk.TreeViewColumn(_("Backgrounds"))
        textrend = gtk.CellRendererText()
        self._column_bgs.pack_start(textrend)
        self._column_bgs.set_cell_data_func(textrend, self._bg_get_row_text)
        colorrend = gtk.CellRendererText()
        self._column_bgs.pack_start(colorrend)
        self._column_bgs.set_cell_data_func(colorrend, self._bg_get_row_color)
        self._treeview_bgs.append_column(self._column_bgs)
        self._treeview_bgs.set_size_request(90,200)
        self._treeview_bgs.set_model(self._bg_model)
        self._bg_model.connect("rows-reordered", self._on_bgs_reordered)
        self._bg_model.connect("row-changed", self._on_bgs_reordered)
        self._treeview_bgs.get_selection().connect("changed", self._on_bg_changed)
        
        bg_left = gtk.VBox()
        gui.append_comment(bg_left, _("Backgrounds will be drawn starting with \
the first element in this list moving to the last one."), 0)
        bg_left.pack_start(toolbar, False, True, gui.WIDGET_SPACING)
        scroll = gtk.ScrolledWindow()
        scroll.add(self._treeview_bgs)
        scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        bg_left.pack_start(scroll, True, True, gui.WIDGET_SPACING)
        
        self._bg_edit_table = gui.ESTable(15, row_spacing=10, auto_inc_y=True)
        scroll_bg_edit = gtk.ScrolledWindow()
        scroll_bg_edit.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        scroll_bg_edit.add_with_viewport(self._bg_edit_table)

        bgbox = gtk.HBox()
        bgbox.pack_start(bg_left, False, True, 0)
        bgbox.pack_start(gtk.VSeparator(), False, False, 15)
        bgbox.pack_start(scroll_bg_edit)
        self._notebook.append_page(bgbox, gtk.Label(_("Background")))
        

        ########### Notebook Page 2: Body Text #################################
        self.body_widgets = {}
        body_h = gtk.HBox()
        body_h.pack_start(self._get_section_left(self._on_body_changed,
                                                 self.body_widgets))
        body_h.pack_start(gtk.VSeparator())
        body_h.pack_start(self._get_section_right(self._on_body_changed,
                                                  self.body_widgets))
        self._notebook.append_page(body_h, gtk.Label(_("Body Text")))
       
        ############ Notebook Page 3: Footer Text ##############################
        self.footer_widgets = {}
        footer_h = gtk.HBox()
        footer_h.pack_start(self._get_section_left(self._on_footer_changed,
                                                   self.footer_widgets))
        footer_h.pack_start(gtk.VSeparator())
        footer_h.pack_start(self._get_section_right(self._on_footer_changed,
                                                    self.footer_widgets))
        self._notebook.append_page(footer_h, gtk.Label(_("Footer Text")))
        
        table_meta = gui.ESTable(4, auto_inc_y=True)
        #Key names for meta must comply with the keys in the <meta> tag in the theme file
        self._meta = {}
        self._meta['author'] = table_meta.attach_entry("", label=_("Author"))
        self._meta['themeurl'] = table_meta.attach_entry("", label=_("Theme URL"))
        self._meta['copyright'] = table_meta.attach_entry("", label=_("Copyright"))
        self._meta['description'] = table_meta.attach_entry("", label=_("Description"))
        self._meta['tags'] = table_meta.attach_entry("", label=_("Tags"))
        table_meta.attach_comment(_("Separate tags with commas"))
        self._notebook.append_page(table_meta, gtk.Label(_("Metadata")))
        
        main_h.pack_start(main_v)
        
        ############  Preview  ########################
        table_right = gui.ESTable(3, auto_inc_y=True)
        table_right.attach_section_title(_("Preview"))
        self._preview = gtk.DrawingArea()
        self._preview.set_size_request(300, int(300*0.75))
        self._preview.connect('expose-event', self._expose)
        table_right.attach_widget(self._preview)
        self._pos_expander = table_right.attach_widget(self._get_position())
        self._pos_expander.set_sensitive(False)
        h = gtk.HBox()
        btn_revert = gtk.Button("", gtk.STOCK_REVERT_TO_SAVED)
        btn_revert.connect('clicked', self._revert_changes)
        btn_save = gtk.Button("", gtk.STOCK_SAVE)
        btn_save.connect('clicked', self._save_changes)
        h.pack_start(btn_revert)
        h.pack_start(btn_save)
        table_right.attach_hseparator()
        table_right.attach_widget(h)

        main_h.pack_end(table_right)
        self.add(main_h)
        self.show_all()
        self._set_changed(False)
Пример #45
0
 def __init__(self, parent, slide):
     gtk.Dialog.__init__(self, _("Editing Slide"), parent,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
     
     # Slide Elements
     lstore = gtk.ListStore(gobject.TYPE_PYOBJECT)
     self._tree = gtk.TreeView(lstore)
     for e in slide._content:
         lstore.append((e,))
     col = gtk.TreeViewColumn( _("Slide Element") )
     text = gtk.CellRendererText()
     text.set_property("ellipsize", pango.ELLIPSIZE_END)
     col.pack_start(text, True)
     col.set_cell_data_func(text, self._set_slide_row_text)
     self._tree.append_column(col)
     self._tree.set_headers_clickable(False)
     self._tree.get_selection().select_path((0,))
     
     self.set_border_width(4)
     self.vbox.set_spacing(7)
     
     cancelbutton = self.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT)
     cancelbutton.connect("clicked", self._quit_without_save)
     newbutton = self.add_button(_("Save and New"), gtk.RESPONSE_APPLY)
     newimg = gtk.Image()
     newimg.set_from_stock(gtk.STOCK_NEW, gtk.ICON_SIZE_BUTTON)
     newbutton.set_image(newimg)
     newbutton.connect("clicked", self._quit_with_save)
     okbutton = self.add_button(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
     okbutton.connect("clicked", self._quit_with_save)
     
     hbox = gtk.HBox()
     hbox.set_spacing(7)
     vbox = gtk.VBox()
     vbox.set_spacing(7)
     
     self.connect("delete-event", self._quit_without_save)
     
     self.slide_title = slide.title
     self.slide_content = slide._content
     self.changed = False
     
     # Title
     vbox.pack_start(self._get_title_box(), False, True)
     
     # Toolbar
     gtk.stock_add([('add-text',_('Add Text'), gtk.gdk.MOD1_MASK, 0,
                     'pymserv'),
                    ("add-image",_('Add Image'), gtk.gdk.MOD1_MASK, 0,
                     'pymserv')])
     toolbar = gtk.Toolbar()
     button = gtk.ToolButton(gtk.stock_lookup('add-text')[0])
     button.set_tooltip_markup(_('Add a new text element.'))
     button.connect('clicked', self._add_text, self._tree)
     toolbar.insert(button, -1)
     button = gtk.ToolButton(gtk.stock_lookup('add-image')[0])
     button.set_tooltip_markup(_('Add a new image element.'))
     button.connect('clicked', self._add_image, self._tree)
     toolbar.insert(button, -1)
     button = gtk.ToolButton(gtk.STOCK_DELETE)
     button.connect('clicked', self._delete_row, self._tree)
     self._tree.get_selection().connect('changed',
                                        gui.treesel_disable_widget, button)
     toolbar.insert(button, -1)
     vbox.pack_start(toolbar, False, True)
     
     
     self._tree.get_selection().connect("changed", self._element_changed)
     
     scroll = gtk.ScrolledWindow()
     scroll.add(self._tree)
     scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
     scroll.set_size_request(280, 250)
     scroll.set_shadow_type(gtk.SHADOW_IN)
     vbox.pack_start(scroll, True, True)
     hbox.pack_start(vbox, False, True)
     
     # This will contain an editor for a `theme._RenderableSection`
     # It will load when an item is selected from the left.
     self._ctbl = gui.ESTable(4,1)
     
     hbox.pack_start(self._ctbl, True, True)
     
     self.vbox.pack_start(hbox, True, True)
     self.vbox.show_all()
     self._tree.get_selection().emit("changed")
Пример #46
0
    def __init__(self, parent, main):
        """
            Initializes the preferences dialog
        """
        self.main = main
        self.last_child = None
        self.last_page = None
        self.parent = parent
        self.settings = MANAGER
        self.fields = {}
        self.panes = {}
        self.builders = {}
        self.popup = None

        self.builder = gtk.Builder()
        self.builder.set_translation_domain('exaile')
        self.builder.add_from_file(
            xdg.get_data_path('ui', 'preferences', 'preferences_dialog.ui'))
        self.builder.connect_signals(self)

        self.window = self.builder.get_object('PreferencesDialog')
        self.window.set_transient_for(parent)
        self.window.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.window.connect('delete-event', lambda *e: self.close())

        self.box = self.builder.get_object('preferences_box')

        self.tree = self.builder.get_object('preferences_tree')
        self.model = self.builder.get_object('model')

        title_cellrenderer = self.builder.get_object('title_cellrenderer')
        title_cellrenderer.props.ypad = 3

        self.default_icon = icons.MANAGER.pixbuf_from_stock(
            gtk.STOCK_PROPERTIES, gtk.ICON_SIZE_MENU)

        # sets up the default panes
        for page in self.PAGES:
            icon = self.default_icon

            if hasattr(page, 'icon'):
                if isinstance(page.icon, gtk.gdk.Pixbuf):
                    icon = page.icon
                else:
                    stock_id = gtk.stock_lookup(page.icon)

                    if stock_id is not None:
                        icon = icons.MANAGER.pixbuf_from_stock(
                            stock_id[0], gtk.ICON_SIZE_MENU)
                    else:
                        icon = icons.MANAGER.pixbuf_from_icon_name(
                            page.icon, gtk.ICON_SIZE_MENU)

            self.model.append(None, [page, page.name, icon])

        # Use icon name to allow overrides
        plugin_icon = icons.MANAGER.pixbuf_from_icon_name(
            'extension', gtk.ICON_SIZE_MENU)
        self.plug_root = self.model.append(
            None, [plugin, _('Plugins'), plugin_icon])

        self._load_plugin_pages()

        selection = self.tree.get_selection()
        selection.connect('changed', self.switch_pane)
        # Disallow selection on rows with no widget to show
        selection.set_select_function(
            lambda path: self.model[path][0] is not None)

        glib.idle_add(selection.select_path, (0, ))
Пример #47
0
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()
Пример #48
0
    def __init__(self, mailbox, label):
        super(Folder, self).__init__(mailbox, label)

        self.updating = False

        if label in self._labels:
            self.label = gtk.stock_lookup(label)[1]
            self.pixbuf = \
                 gtk.Window().render_icon(label, gtk.ICON_SIZE_SMALL_TOOLBAR)
        else:
            self.label = label
            self.pixbuf = \
                gtk.Window().render_icon("folder", gtk.ICON_SIZE_SMALL_TOOLBAR)

        self.widget = gtk.VBox()
        self.widget.filter = self.filter

        self.progress = gtk.ProgressBar()

        self.scrolled = gtk.ScrolledWindow()
        self.scrolled.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
        self.widget.add(self.scrolled)

        self.list_store = gtk.ListStore(object)
        self.list_view = gtk.TreeView(self.list_store)
        self.list_view.connect("button-press-event", self._button_press)
        self.list_model = self.list_view.get_model()

        self.list_view.set_headers_visible(False)
        self.list_view.set_rules_hint(True)
        self.scrolled.add(self.list_view)

        self.status_renderer = gtk.CellRendererPixbuf()
        self.status_renderer.set_property("stock-size", gtk.ICON_SIZE_MENU)
        self.status_column = gtk.TreeViewColumn(None, self.status_renderer)
        self.status_column.set_expand(False)
        self.list_view.append_column(self.status_column)
        self.status_column.set_cell_data_func(self.status_renderer,
                                              self._render_status)

        self.text_renderer = gtk.CellRendererText()
        self.text_renderer.props.ellipsize = pango.ELLIPSIZE_END
        self.text_column = gtk.TreeViewColumn(None, self.text_renderer)
        self.text_column.set_expand(True)
        self.list_view.append_column(self.text_column)
        self.text_column.set_cell_data_func(self.text_renderer,
                                            self._render_text,
                                            self._address)

        self.date_renderer = gtk.CellRendererText()
        self.date_column = gtk.TreeViewColumn(None, self.date_renderer)
        self.date_column.set_expand(False)
        self.list_view.append_column(self.date_column)
        self.date_column.set_cell_data_func(self.date_renderer,
                                            self._render_date)
        self.date_renderer.set_property("alignment", pango.ALIGN_RIGHT)
        self.date_renderer.set_property("xalign", 1)

        self.trash_renderer = gtk.CellRendererPixbuf()
        self.trash_renderer.set_property("stock-id", "delete")
        self.trash_renderer.set_property("stock-size", gtk.ICON_SIZE_MENU)
        self.trash_column = gtk.TreeViewColumn(None, self.trash_renderer)
        self.trash_column.set_expand(False)
        self.list_view.append_column(self.trash_column)

        self.pretty_label = gtk.HBox()
        self.pretty_label.set_spacing(3)
        self.pretty_label.pack_start(
            gtk.image_new_from_pixbuf(self.pixbuf), False, False)
        self.pretty_label.pack_start(gtk.Label(self.label))
Пример #49
0
        self._name = name

    @property
    def name(self):
        return '<b>%s</b>'%self._name

icons = ObjectList([
    Column(title='Stock Data', cells=[
        Cell('stock_name', gtk.Pixmap, use_stock=True),
        Cell('stock_name', str),
        ], sorted=False),
    Column('name', str, 'Name', use_markup=True),
], sortable=True)

for id in gtk.stock_list_ids():
    lookup = gtk.stock_lookup(id)
    if lookup is None:
        continue
    stock_name, name = gtk.stock_lookup(id)[:2]
    name = name.replace('_', '')
    icons.append(IconInfo(stock_name, name))

scroll = gtk.ScrolledWindow()
scroll.add(icons)

win = gtk.Window()
win.add(scroll)
win.set_size_request(600, 400)

win.show_all()
win.connect('destroy', gtk.main_quit)