コード例 #1
0
 def showUI(self):
     """ shows the ui and starts it so user interaction can begin """
     self.builder = Builder()
     self.builder.add_from_file("ui.xml")
     self.mainWindow = self.builder.get_object("mainWin")
     self.mainWindow.set_title(self.currentFLC.label)
     self.mainWindow.maximize()
     self.mainWindow.connect("delete-event", main_quit)
     self.fssEntry = self.builder.get_object("fssEntry")
     self.bssEntry = self.builder.get_object("bssEntry")
     self.inputsBox = self.builder.get_object("inputsBox")
     self.outputsBox = self.builder.get_object("outputsBox")
     self.rulesBox = self.builder.get_object("rulesBox")
     self.andCombo = self.builder.get_object("andCombo")
     self.implicationCombo = self.builder.get_object("implicationCombo")
     self.inputPlots = []
     self.outputPlots = []
     for i in self.currentFLC.inputs:
         self.inputPlots.append(PlotWidget([i]))
     for i in self.currentFLC.outputs:
         self.outputPlots.append(PlotWidget([i]))
     for k, i in enumerate(self.inputPlots):
         self.inputsBox.pack_start(self.inputPlots[k].get_canvas_widget())
     for k, i in enumerate(self.outputPlots):
         self.outputsBox.pack_start(self.outputPlots[k].get_canvas_widget())
     self.rbList = RuleBaseWidget(
         self.currentFLC.rulebase).get_list_widget()
     self.rulesBox.pack_start(self.rbList)
     self.discSpin = self.builder.get_object("discretizationSteps")
     self.closeButton = self.builder.get_object("closeBtn")
     self.closeButton.connect("clicked", main_quit)
     self.executeButton = self.builder.get_object("execBtn")
     self.executeButton.connect("clicked", self.execute_clicked)
     self.mainWindow.show_all()
     main()
コード例 #2
0
ファイル: utils.py プロジェクト: rbemmanuel/openlanhouse
def get_gtk_builder(name):
    filename = "%s/%s.ui" % (UI_PATH, name)
    assert ospath.exists(filename)
    b = Builder()
    b.set_property("translation-domain", I18N_APP)
    b.add_from_file(filename)
    return b
コード例 #3
0
ファイル: queuedtorrents.py プロジェクト: newfyle/deluge
    def __init__(self):
        component.Component.__init__(self,
                                     'QueuedTorrents',
                                     depend=['StatusBar', 'AddTorrentDialog'])
        self.queue = []
        self.status_item = None

        self.config = ConfigManager('gtkui.conf')
        self.builder = Builder()
        self.builder.add_from_file(
            deluge.common.resource_filename(
                'deluge.ui.gtkui', os.path.join('glade', 'queuedtorrents.ui')))
        self.builder.get_object('chk_autoadd').set_active(
            self.config['autoadd_queued'])
        self.dialog = self.builder.get_object('queued_torrents_dialog')
        self.dialog.set_icon(get_logo(32))

        self.builder.connect_signals(self)

        self.treeview = self.builder.get_object('treeview')
        self.treeview.append_column(
            TreeViewColumn(_('Torrent'), CellRendererText(), text=0))

        self.liststore = ListStore(str, str)
        self.treeview.set_model(self.liststore)
        self.treeview.set_tooltip_column(1)
コード例 #4
0
ファイル: builder.py プロジェクト: atoun/python-cream
class GtkBuilderInterface(object):
    """
    Integrates GTKBuilder interfaces into a class so that you can access
    widgets defined in the UI file as if they were attributes of the class.

    Example::

        class MyGreatWindow(GtkBuilderInterface):
            def __init__(self):
                GtkBuilderInterface.__init__(self, '/path/to/ui.glade')
                self.window.show_all()

    where ``window`` is a window defined in the UI file.

    :param builder_file: Path to the UI file
    """

    def __init__(self, builder_file):
        self._builder_file = builder_file
        self._builder_tree = Builder()
        self._builder_tree.add_from_file(builder_file)

    def __getattr__(self, attr):
        obj = self._builder_tree.get_object(attr)
        if obj is None:
            raise AttributeError(attr)
        return obj

    def connect_signals(self, *a):
        self._builder_tree.connect_signals(*a)
コード例 #5
0
ファイル: peers_tab.py プロジェクト: deluge-torrent/deluge
 def on_menuitem_add_peer_activate(self, menuitem):
     """This is a callback for manually adding a peer"""
     log.debug('on_menuitem_add_peer')
     builder = Builder()
     builder.add_from_file(deluge.common.resource_filename(
         'deluge.ui.gtkui', os.path.join('glade', 'connect_peer_dialog.ui')
     ))
     peer_dialog = builder.get_object('connect_peer_dialog')
     txt_ip = builder.get_object('txt_ip')
     response = peer_dialog.run()
     if response:
         value = txt_ip.get_text()
         if value and ':' in value:
             if ']' in value:
                 # ipv6
                 ip = value.split(']')[0][1:]
                 port = value.split(']')[1][1:]
             else:
                 # ipv4
                 ip = value.split(':')[0]
                 port = value.split(':')[1]
             if deluge.common.is_ip(ip):
                 log.debug('adding peer %s to %s', value, self.torrent_id)
                 client.core.connect_peer(self.torrent_id, ip, port)
     peer_dialog.destroy()
     return True
コード例 #6
0
ファイル: Utils.py プロジェクト: mystilleef/scribes
def get_gui_object(globals_, basepath):
	from os.path import join
	folder = get_current_folder(globals_)
	file_ = join(folder, basepath)
	from gtk import Builder
	gui = Builder()
	gui.add_from_file(file_)
	return gui
コード例 #7
0
ファイル: baseview.py プロジェクト: Ailick/virtaal
 def load_builder_file(cls, path_parts, root=None, domain=''):
     _id = "/".join(path_parts)
     if _id in _builders:
         return _builders[_id]
     buildername = pan_app.get_abs_data_filename(path_parts)
     builder = Builder()
     builder.add_from_file(buildername)
     builder.set_translation_domain(domain)
     _builders[_id] = builder
     return builder
コード例 #8
0
ファイル: label_config.py プロジェクト: deluge-torrent/deluge
    def load(self):
        log.debug('Adding Label Preferences page')
        builder = Builder()
        builder.add_from_file(get_resource('label_pref.ui'))

        self.plugin.add_preferences_page(_('Label'), builder.get_object('label_prefs_box'))
        self.plugin.register_hook('on_show_prefs', self.load_settings)
        self.plugin.register_hook('on_apply_prefs', self.on_apply_prefs)

        self.load_settings()
コード例 #9
0
ファイル: label_config.py プロジェクト: newfyle/deluge
    def load(self):
        log.debug('Adding Label Preferences page')
        builder = Builder()
        builder.add_from_file(get_resource('label_pref.ui'))

        self.plugin.add_preferences_page(_('Label'),
                                         builder.get_object('label_prefs_box'))
        self.plugin.register_hook('on_show_prefs', self.load_settings)
        self.plugin.register_hook('on_apply_prefs', self.on_apply_prefs)

        self.load_settings()
コード例 #10
0
 def __init__(self, fname, root=None, domain="", typedict={}):
     self.builder = Builder()
     if domain:
         self.builder.set_translation_domain(domain)
     conv = GtkBuilderConverter(root=root, skip_windows=False)
     conv.parse_file(fname)
     cwd = os.getcwd()
     os.chdir(os.path.dirname(fname))
     xml = conv.to_xml()
     self.builder.add_from_string(xml, len(xml))
     os.chdir(cwd)
コード例 #11
0
ファイル: baseview.py プロジェクト: denji/virtaal
 def load_builder_file(cls, path_parts, root=None, domain=''):
     buildername = pan_app.get_abs_data_filename(path_parts)
     if os.name == 'nt' and getattr(sys, 'frozen', False):
         try:
             basedirs = [os.getcwd()]
             # FIXME
             #glade.bindtextdomain(domain, pan_app.get_abs_data_filename('locale', basedirs=basedirs))
         except Exception:
             logging.exception('bindtextdomain()')
     builder = Builder()
     builder.add_from_file(buildername)
     builder.set_translation_domain(domain)
     return buildername, builder
コード例 #12
0
ファイル: gui.py プロジェクト: wodny/pendrive-frenzy-2
    def __init__(self, updates_out, events_in):
        self.updates_out = updates_out
        self.events_in = events_in

        self.builder = Builder()
        self.builder.add_from_file(sys.path[0] + "/lib/pendrive-frenzy.glade")

        self.window = self.builder.get_object("main_window")
        self.pendrive_list = PendriveListWrapper(
            self.builder.get_object("pendrive_list"))
        self.writing_enabled = self.builder.get_object("writing_enabled")
        self.infobar = self.builder.get_object("infobar")
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_contextid = self.statusbar.get_context_id("default")

        self.builder.connect_signals(self)
        self.window.show()
コード例 #13
0
ファイル: glade_compat.py プロジェクト: ecell/spatiocyte
 def __init__(self, fname, root=None, domain="", typedict={}):
     self.builder = Builder()
     if domain:
         self.builder.set_translation_domain(domain)
     conv = GtkBuilderConverter(root=root, skip_windows=False)
     conv.parse_file(fname)
     cwd = os.getcwd()
     os.chdir(os.path.dirname(fname))
     xml = conv.to_xml()
     self.builder.add_from_string(xml, len(xml))
     os.chdir(cwd)
コード例 #14
0
ファイル: systemtray.py プロジェクト: deluge-torrent/deluge
    def enable(self):
        """Enables the system tray icon."""
        self.builder = Builder()
        self.builder.add_from_file(resource_filename('deluge.ui.gtkui', os.path.join(
            'glade', 'tray_menu.ui')))

        self.builder.connect_signals(self)

        self.tray_menu = self.builder.get_object('tray_menu')

        if appindicator and self.config['enable_appindicator']:
            log.debug('Enabling the Application Indicator...')
            self.indicator = appindicator.Indicator('deluge', 'deluge',
                                                    appindicator.CATEGORY_APPLICATION_STATUS)
            try:
                self.indicator.set_property('title', _('Deluge'))
            except TypeError:
                # Catch 'title' property error for previous appindicator versions
                pass
            # Pass the menu to the Application Indicator
            self.indicator.set_menu(self.tray_menu)

            # Make sure the status of the Show Window MenuItem is correct
            self._sig_win_hide = self.mainwindow.window.connect('hide', self._on_window_hide)
            self._sig_win_show = self.mainwindow.window.connect('show', self._on_window_show)
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(False)

            # Show the Application Indicator
            self.indicator.set_status(appindicator.STATUS_ACTIVE)

        else:
            log.debug('Enabling the system tray icon..')
            if windows_check():
                self.tray = status_icon_new_from_pixbuf(get_logo(32))
            else:
                self.tray = status_icon_new_from_icon_name('deluge')

            self.tray.connect('activate', self.on_tray_clicked)
            self.tray.connect('popup-menu', self.on_tray_popup)

        self.builder.get_object('download-limit-image').set_from_file(get_pixmap('downloading16.png'))
        self.builder.get_object('upload-limit-image').set_from_file(get_pixmap('seeding16.png'))

        client.register_event_handler('ConfigValueChangedEvent', self.config_value_changed)
        if client.connected():
            # We're connected so we need to get some values from the core
            self.__start()
        else:
            # Hide menu widgets because we're not connected to a host.
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).hide()
コード例 #15
0
def get_gtk_builder(name):
    filename = "%s/%s.ui" % (UI_PATH, name)
    assert ospath.exists(filename)
    b = Builder()
    b.set_property("translation-domain", I18N_APP)
    b.add_from_file(filename)
    return b
コード例 #16
0
 def on_menuitem_add_peer_activate(self, menuitem):
     """This is a callback for manually adding a peer"""
     log.debug('on_menuitem_add_peer')
     builder = Builder()
     builder.add_from_file(
         deluge.common.resource_filename(
             'deluge.ui.gtkui',
             os.path.join('glade', 'connect_peer_dialog.ui')))
     peer_dialog = builder.get_object('connect_peer_dialog')
     txt_ip = builder.get_object('txt_ip')
     response = peer_dialog.run()
     if response:
         value = txt_ip.get_text()
         if value and ':' in value:
             if ']' in value:
                 # ipv6
                 ip = value.split(']')[0][1:]
                 port = value.split(']')[1][1:]
             else:
                 # ipv4
                 ip = value.split(':')[0]
                 port = value.split(':')[1]
             if deluge.common.is_ip(ip):
                 log.debug('adding peer %s to %s', value, self.torrent_id)
                 client.core.connect_peer(self.torrent_id, ip, port)
     peer_dialog.destroy()
     return True
コード例 #17
0
ファイル: baseview.py プロジェクト: yarons/virtaal
 def load_builder_file(cls, path_parts, root=None, domain=''):
     _id = "/".join(path_parts)
     if _id in _builders:
         return _builders[_id]
     buildername = pan_app.get_abs_data_filename(path_parts)
     builder = Builder()
     builder.add_from_file(buildername)
     builder.set_translation_domain(domain)
     _builders[_id] = builder
     return builder
コード例 #18
0
	def start_builder(self):
		self.resourceman = resourceman("rainbow_shooter.share")
		#self.configuration = confmanager()
		self.configuration = confmanager(True) # Debug version
		self.parman = paramanager(self.configuration)


		#gladefile = "share/rainbow_shooter.xml"
		gladefile = self.resourceman.get_xml_file_path("rainbow_shooter")
		self.builder = Builder()
		self.builder.add_from_file(gladefile)

		# Add row dialog UI elements
		self.color_list = self.builder.get_object("color_lst")
		self.time = self.builder.get_object("time")
		self.color_btn = self.builder.get_object("color_btn")

		# Preference dialog objects
		self.preference_dialog = self.builder.get_object("preference_dialog")
		self.timer_adjustment = self.builder.get_object("timer_adjustment")
		self.default_adjustment = self.builder.get_object("default_adjustment")
		self.minimum_adjustment = self.builder.get_object("minimum_adjustment")
		self.maximum_adjustment = self.builder.get_object("maximum_adjustment")
		self.pd_libpath = self.builder.get_object("pd_libpath")
		# The table UI controls.
		self.pt_model = periodictable(self.color_list)
		# New row appender UI controls.
		newrowuictrl = new_row_UIcontrol(self.pt_model, self.color_list, self.color_btn, self.time, self.timer_adjustment, self.configuration)
		# Preference dialog UI controls.
		prefuictrl = pref_UIcontrol(self.preference_dialog, self.configuration,
		self.default_adjustment, self.minimum_adjustment, self.maximum_adjustment,
		self.update_defaults)
		# Playback dialog UI controls.
		playback_ui = playerui(self.pt_model, self.resourceman)
		# Builder signals
		dic = {
		"options_clicked_cb" : prefuictrl.options_clicked_cb,
		"cancel_clicked_cb" : prefuictrl.cancel_clicked_cb,
		"pd_ok_clicked_cb" : prefuictrl.pd_ok_clicked_cb,
		"pd_cancel_clicked_cb" : prefuictrl.pd_cancel_clicked_cb,
		"time_icon_press_cb" : newrowuictrl.time_icon_press_cb,
		"add_clicked_cb"	: newrowuictrl.add_clicked_cb,
		"remove_clicked_cb"	: self.pt_model.remove_clicked_cb,
		"play_clicked_cb"	: playback_ui.play_clicked_cb,
		"destroy"			: self.destroy
		}
		self.builder.connect_signals(dic)
		self.start_defaults()
コード例 #19
0
ファイル: glade_compat.py プロジェクト: ecell/spatiocyte
    class XML(object):
        def __init__(self, fname, root=None, domain="", typedict={}):
            self.builder = Builder()
            if domain:
                self.builder.set_translation_domain(domain)
            conv = GtkBuilderConverter(root=root, skip_windows=False)
            conv.parse_file(fname)
            cwd = os.getcwd()
            os.chdir(os.path.dirname(fname))
            xml = conv.to_xml()
            self.builder.add_from_string(xml, len(xml))
            os.chdir(cwd)

        def signal_connect(self, handler_name, func):
            self.builder.connect(handler_name, func)

        def signal_autoconnect(self, dict):
            self.builder.connect_signals(dict)

        def get_widget(self, name):
            obj = self.builder.get_object(name)
            if isinstance(obj, Action):
                obj = obj.get_proxies()[0]
            return obj
コード例 #20
0
    class XML(object):
        def __init__(self, fname, root=None, domain="", typedict={}):
            self.builder = Builder()
            if domain:
                self.builder.set_translation_domain(domain)
            conv = GtkBuilderConverter(root=root, skip_windows=False)
            conv.parse_file(fname)
            cwd = os.getcwd()
            os.chdir(os.path.dirname(fname))
            xml = conv.to_xml()
            self.builder.add_from_string(xml, len(xml))
            os.chdir(cwd)

        def signal_connect(self, handler_name, func):
            self.builder.connect(handler_name, func)

        def signal_autoconnect(self, dict):
            self.builder.connect_signals(dict)

        def get_widget(self, name):
            obj = self.builder.get_object(name)
            if isinstance(obj, Action):
                obj = obj.get_proxies()[0]
            return obj
コード例 #21
0
class QueuedTorrents(component.Component):
    def __init__(self):
        component.Component.__init__(self, 'QueuedTorrents', depend=['StatusBar', 'AddTorrentDialog'])
        self.queue = []
        self.status_item = None

        self.config = ConfigManager('gtkui.conf')
        self.builder = Builder()
        self.builder.add_from_file(deluge.common.resource_filename(
            'deluge.ui.gtkui', os.path.join('glade', 'queuedtorrents.ui')))
        self.builder.get_object('chk_autoadd').set_active(self.config['autoadd_queued'])
        self.dialog = self.builder.get_object('queued_torrents_dialog')
        self.dialog.set_icon(get_logo(32))

        self.builder.connect_signals(self)

        self.treeview = self.builder.get_object('treeview')
        self.treeview.append_column(TreeViewColumn(_('Torrent'), CellRendererText(), text=0))

        self.liststore = ListStore(str, str)
        self.treeview.set_model(self.liststore)
        self.treeview.set_tooltip_column(1)

    def run(self):
        self.dialog.set_transient_for(component.get('MainWindow').window)
        self.dialog.show()

    def start(self):
        if len(self.queue) == 0:
            return

        # Make sure status bar info is showing
        self.update_status_bar()

        # We only want the add button sensitive if we're connected to a host
        self.builder.get_object('button_add').set_sensitive(True)

        if self.config['autoadd_queued'] or self.config['standalone']:
            self.on_button_add_clicked(None)
        else:
            self.run()

    def stop(self):
        # We only want the add button sensitive if we're connected to a host
        self.builder.get_object('button_add').set_sensitive(False)
        self.update_status_bar()

    def add_to_queue(self, torrents):
        """Adds the list of torrents to the queue"""
        # Add to the queue while removing duplicates
        self.queue = list(set(self.queue + torrents))

        # Update the liststore
        self.liststore.clear()
        for torrent in self.queue:
            if deluge.common.is_magnet(torrent):
                magnet = deluge.common.get_magnet_info(torrent)
                self.liststore.append([magnet['name'], torrent])
            else:
                self.liststore.append([os.path.split(torrent)[1], torrent])

        # Update the status bar
        self.update_status_bar()

    def update_status_bar(self):
        """Attempts to update status bar"""
        # If there are no queued torrents.. remove statusbar widgets and return
        if len(self.queue) == 0:
            if self.status_item is not None:
                component.get('StatusBar').remove_item(self.status_item)
                self.status_item = None
            return False

        try:
            component.get('StatusBar')
        except Exception:
            # The statusbar hasn't been loaded yet, so we'll add a timer to
            # update it later.
            timeout_add(100, self.update_status_bar)
            return False

        # Set the label text for statusbar
        if len(self.queue) > 1:
            label = str(len(self.queue)) + _(' Torrents Queued')
        else:
            label = str(len(self.queue)) + _(' Torrent Queued')

        # Add the statusbar items if needed, or just modify the label if they
        # have already been added.
        if self.status_item is None:
            self.status_item = component.get('StatusBar').add_item(
                stock=STOCK_SORT_DESCENDING,
                text=label,
                callback=self.on_statusbar_click)
        else:
            self.status_item.set_text(label)

        # We return False so the timer stops
        return False

    def on_statusbar_click(self, widget, event):
        log.debug('on_statusbar_click')
        self.run()

    def on_button_remove_clicked(self, widget):
        selected = self.treeview.get_selection().get_selected()[1]
        if selected is not None:
            path = self.liststore.get_value(selected, 1)
            self.liststore.remove(selected)
            self.queue.remove(path)
            self.update_status_bar()

    def on_button_clear_clicked(self, widget):
        self.liststore.clear()
        del self.queue[:]
        self.update_status_bar()

    def on_button_close_clicked(self, widget):
        self.dialog.hide()

    def on_button_add_clicked(self, widget):
        # Add all the torrents in the liststore
        def add_torrent(model, path, _iter, data):
            torrent_path = model.get_value(_iter, 1).decode('utf-8')
            process_args([torrent_path])

        self.liststore.foreach(add_torrent, None)
        del self.queue[:]
        self.dialog.hide()
        self.update_status_bar()

    def on_chk_autoadd_toggled(self, widget):
        self.config['autoadd_queued'] = widget.get_active()
コード例 #22
0
ファイル: builder.py プロジェクト: atoun/python-cream
 def __init__(self, builder_file):
     self._builder_file = builder_file
     self._builder_tree = Builder()
     self._builder_tree.add_from_file(builder_file)
コード例 #23
0
	def __init__(self, exaile):
		self.exaile = exaile
		self.playlist = exaile.playlists.get_playlist(_pl_name)
		self.num_songs = min(_def_num_songs, len(self.playlist))
		b = Builder()
		basedir = os.path.dirname(os.path.realpath(__file__))
		b.add_from_file(os.path.join(basedir, 'musicquiz.ui'))
		self.window = b.get_object('QuizWindow')

		# When closed, don't prompt the user, just close the window.
		self.window.connect("delete_event", lambda x,y: False)
		self.window.connect_object("destroy", Window.destroy,
			self.window)

		# Connect buttons to move through the notebook.
		self.start_button = b.get_object('start_button')
		self.submit_button = b.get_object('submit_button')
		self.restart_button = b.get_object('restart_button')
		self.notebook = b.get_object('notebook1')
		self.start_button.connect_object("clicked", Quizzer.quiz, self)
		self.submit_button.connect_object("clicked", Quizzer.finish, self)
		self.restart_button.connect_object("clicked", Notebook.set_current_page,
				self.notebook, 0)

		# Connect spinner to self.num_songs
		temp = Adjustment(value=_def_num_songs, lower=1,
				upper=len(self.playlist), step_incr=1)
		self.num_songs_spinner = b.get_object('num_songs_spinner')
		temp.connect("value_changed", self.change_num_songs,
				self.num_songs_spinner)
		self.num_songs_spinner.set_adjustment(temp)

		self.quiz_vbox = b.get_object('quiz_vbox')
		self.results_textview = b.get_object('results_textview')

		# Done! Show the window!
		self.window.show()

		log.debug("Quizzer plugin loaded.")
コード例 #24
0
ファイル: sumadora.py プロジェクト: ivziete/ponencias
import gtk
from gtk import Builder

def gtk_main_quit(widget):
	gtk.main_quit()

def plus_clicked(widget):
	entry1 = builder.get_object("entry1")
	entry2 = builder.get_object("entry2")
	entry3 = builder.get_object("entry3")
	label1 = builder.get_object("label1")

	label1.set_text(str(int(entry1.get_text())+int(entry2.get_text())+int(entry3.get_text())))

builder = Builder()
builder.add_from_file("sumadora.glade")
builder.connect_signals(locals())
window = builder.get_object("window1")
window.show()

gtk.main()
コード例 #25
0
class rshooterGui (Window):
	"""Constructs each widget and loads any managers."""
	def start_builder(self):
		self.resourceman = resourceman("rainbow_shooter.share")
		#self.configuration = confmanager()
		self.configuration = confmanager(True) # Debug version
		self.parman = paramanager(self.configuration)


		#gladefile = "share/rainbow_shooter.xml"
		gladefile = self.resourceman.get_xml_file_path("rainbow_shooter")
		self.builder = Builder()
		self.builder.add_from_file(gladefile)

		# Add row dialog UI elements
		self.color_list = self.builder.get_object("color_lst")
		self.time = self.builder.get_object("time")
		self.color_btn = self.builder.get_object("color_btn")

		# Preference dialog objects
		self.preference_dialog = self.builder.get_object("preference_dialog")
		self.timer_adjustment = self.builder.get_object("timer_adjustment")
		self.default_adjustment = self.builder.get_object("default_adjustment")
		self.minimum_adjustment = self.builder.get_object("minimum_adjustment")
		self.maximum_adjustment = self.builder.get_object("maximum_adjustment")
		self.pd_libpath = self.builder.get_object("pd_libpath")
		# The table UI controls.
		self.pt_model = periodictable(self.color_list)
		# New row appender UI controls.
		newrowuictrl = new_row_UIcontrol(self.pt_model, self.color_list, self.color_btn, self.time, self.timer_adjustment, self.configuration)
		# Preference dialog UI controls.
		prefuictrl = pref_UIcontrol(self.preference_dialog, self.configuration,
		self.default_adjustment, self.minimum_adjustment, self.maximum_adjustment,
		self.update_defaults)
		# Playback dialog UI controls.
		playback_ui = playerui(self.pt_model, self.resourceman)
		# Builder signals
		dic = {
		"options_clicked_cb" : prefuictrl.options_clicked_cb,
		"cancel_clicked_cb" : prefuictrl.cancel_clicked_cb,
		"pd_ok_clicked_cb" : prefuictrl.pd_ok_clicked_cb,
		"pd_cancel_clicked_cb" : prefuictrl.pd_cancel_clicked_cb,
		"time_icon_press_cb" : newrowuictrl.time_icon_press_cb,
		"add_clicked_cb"	: newrowuictrl.add_clicked_cb,
		"remove_clicked_cb"	: self.pt_model.remove_clicked_cb,
		"play_clicked_cb"	: playback_ui.play_clicked_cb,
		"destroy"			: self.destroy
		}
		self.builder.connect_signals(dic)
		self.start_defaults()
	"""Based on the loaded configuration set the values in the UI widgets
	This action is made only once per start."""
	def start_defaults(self):
		self.default_adjustment.set_value(self.configuration.get_default_timer())
		print(type(self.configuration.get_min_range()))
		self.minimum_adjustment.set_value(self.configuration.get_min_range())
		self.maximum_adjustment.set_value(self.configuration.get_max_range())
		self.update_defaults()
	"""Sets new values in the UI widgets."""
	def update_defaults(self):
		self.timer_adjustment.set_value(self.default_adjustment.get_value())
		self.timer_adjustment.set_lower(self.minimum_adjustment.get_value())
		self.timer_adjustment.set_upper(self.maximum_adjustment.get_value())
	#"""Sets dynamically the default values of the widgets."""
#	def update_live_conf(self):
#		self.default_adjustment.set_value(self.configuration.get_default_timer())
#		self.minimum_adjustment.set_value(self.configuration.get_min_range())
#		self.maximum_adjustment.set_value(self.configuration.get_max_range())
	def __init__(self):
		super(rshooterGui, self).__init__()
		self.start_builder()
		# Preparing the artwork
		win_icon = pixbuf_new_from_file("/home/gnu_d/Desktop/active_programs/olivers_colors/rainbow-shooter/rainbow_shooter/share/icons/rainbow_shooter.svg")
		win_icon = pixbuf_new_from_file(self.resourceman.get_images_file_path("rainbow_shooter", "svg"))

		self = self.builder.get_object("window1")
		# Setting the window icon.
		self.set_icon(win_icon)

		self.show_all()
	"""Exits from the program."""
	def destroy(self, widget):
		main_quit()
コード例 #26
0
ファイル: systemtray.py プロジェクト: deluge-torrent/deluge
class SystemTray(component.Component):
    def __init__(self):
        component.Component.__init__(self, 'SystemTray', interval=4)
        self.mainwindow = component.get('MainWindow')
        self.config = ConfigManager('gtkui.conf')
        # List of widgets that need to be hidden when not connected to a host
        self.hide_widget_list = [
            'menuitem_add_torrent',
            'menuitem_pause_session',
            'menuitem_resume_session',
            'menuitem_download_limit',
            'menuitem_upload_limit',
            'menuitem_quitdaemon',
            'separatormenuitem1',
            'separatormenuitem2',
            'separatormenuitem3',
            'separatormenuitem4'
        ]
        self.config.register_set_function('enable_system_tray', self.on_enable_system_tray_set)
        # bit of a hack to prevent function from doing something on startup
        self.__enabled_set_once = False
        self.config.register_set_function('enable_appindicator', self.on_enable_appindicator_set)

        self.max_download_speed = -1.0
        self.download_rate = 0.0
        self.max_upload_speed = -1.0
        self.upload_rate = 0.0

        self.config_value_changed_dict = {
            'max_download_speed': self._on_max_download_speed,
            'max_upload_speed': self._on_max_upload_speed
        }

    def enable(self):
        """Enables the system tray icon."""
        self.builder = Builder()
        self.builder.add_from_file(resource_filename('deluge.ui.gtkui', os.path.join(
            'glade', 'tray_menu.ui')))

        self.builder.connect_signals(self)

        self.tray_menu = self.builder.get_object('tray_menu')

        if appindicator and self.config['enable_appindicator']:
            log.debug('Enabling the Application Indicator...')
            self.indicator = appindicator.Indicator('deluge', 'deluge',
                                                    appindicator.CATEGORY_APPLICATION_STATUS)
            try:
                self.indicator.set_property('title', _('Deluge'))
            except TypeError:
                # Catch 'title' property error for previous appindicator versions
                pass
            # Pass the menu to the Application Indicator
            self.indicator.set_menu(self.tray_menu)

            # Make sure the status of the Show Window MenuItem is correct
            self._sig_win_hide = self.mainwindow.window.connect('hide', self._on_window_hide)
            self._sig_win_show = self.mainwindow.window.connect('show', self._on_window_show)
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(False)

            # Show the Application Indicator
            self.indicator.set_status(appindicator.STATUS_ACTIVE)

        else:
            log.debug('Enabling the system tray icon..')
            if windows_check():
                self.tray = status_icon_new_from_pixbuf(get_logo(32))
            else:
                self.tray = status_icon_new_from_icon_name('deluge')

            self.tray.connect('activate', self.on_tray_clicked)
            self.tray.connect('popup-menu', self.on_tray_popup)

        self.builder.get_object('download-limit-image').set_from_file(get_pixmap('downloading16.png'))
        self.builder.get_object('upload-limit-image').set_from_file(get_pixmap('seeding16.png'))

        client.register_event_handler('ConfigValueChangedEvent', self.config_value_changed)
        if client.connected():
            # We're connected so we need to get some values from the core
            self.__start()
        else:
            # Hide menu widgets because we're not connected to a host.
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).hide()

    def __start(self):
        if self.config['enable_system_tray']:

            if self.config['standalone']:
                try:
                    self.hide_widget_list.remove('menuitem_quitdaemon')
                    self.hide_widget_list.remove('separatormenuitem4')
                except ValueError:
                    pass
                self.builder.get_object('menuitem_quitdaemon').hide()
                self.builder.get_object('separatormenuitem4').hide()

            # Show widgets in the hide list because we've connected to a host
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).show()

            # Build the bandwidth speed limit menus
            self.build_tray_bwsetsubmenu()

            # Get some config values
            def update_config_values(configs):
                self._on_max_download_speed(configs['max_download_speed'])
                self._on_max_upload_speed(configs['max_upload_speed'])
            client.core.get_config_values(['max_download_speed', 'max_upload_speed']).addCallback(update_config_values)

    def start(self):
        self.__start()

    def stop(self):
        if self.config['enable_system_tray'] and not self.config['enable_appindicator']:
            try:
                # Hide widgets in hide list because we're not connected to a host
                for widget in self.hide_widget_list:
                    self.builder.get_object(widget).hide()
            except Exception as ex:
                log.debug('Unable to hide system tray menu widgets: %s', ex)

            self.tray.set_tooltip_text(_('Deluge') + '\n' + _('Not Connected...'))

    def shutdown(self):
        if self.config['enable_system_tray']:
            if appindicator and self.config['enable_appindicator']:
                self.indicator.set_status(appindicator.STATUS_PASSIVE)
            else:
                self.tray.set_visible(False)

    def send_status_request(self):
        client.core.get_session_status([
            'payload_upload_rate',
            'payload_download_rate']).addCallback(self._on_get_session_status)

    def config_value_changed(self, key, value):
        """This is called when we received a config_value_changed signal from
        the core."""
        if key in self.config_value_changed_dict:
            self.config_value_changed_dict[key](value)

    def _on_max_download_speed(self, max_download_speed):
        if self.max_download_speed != max_download_speed:
            self.max_download_speed = max_download_speed
            self.build_tray_bwsetsubmenu()

    def _on_max_upload_speed(self, max_upload_speed):
        if self.max_upload_speed != max_upload_speed:
            self.max_upload_speed = max_upload_speed
            self.build_tray_bwsetsubmenu()

    def _on_get_session_status(self, status):
        self.download_rate = fspeed(status['payload_download_rate'], shortform=True)
        self.upload_rate = fspeed(status['payload_upload_rate'], shortform=True)

    def update(self):
        if not self.config['enable_system_tray']:
            return

        # Tool tip text not available for appindicator
        if appindicator and self.config['enable_appindicator']:
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(False)
            return

        # Set the tool tip text
        max_download_speed = self.max_download_speed
        max_upload_speed = self.max_upload_speed

        if max_download_speed == -1:
            max_download_speed = _('Unlimited')
        else:
            max_download_speed = '%s %s' % (max_download_speed, _('K/s'))
        if max_upload_speed == -1:
            max_upload_speed = _('Unlimited')
        else:
            max_upload_speed = '%s %s' % (max_upload_speed, _('K/s'))

        msg = '%s\n%s: %s (%s)\n%s: %s (%s)' % (
            _('Deluge'), _('Down'), self.download_rate,
            max_download_speed, _('Up'), self.upload_rate, max_upload_speed
        )

        # Set the tooltip
        self.tray.set_tooltip_text(msg)

        self.send_status_request()

    def build_tray_bwsetsubmenu(self):
        # Create the Download speed list sub-menu
        submenu_bwdownset = build_menu_radio_list(
            self.config['tray_download_speed_list'], self.on_tray_setbwdown,
            self.max_download_speed,
            _('K/s'), show_notset=True, show_other=True
        )

        # Create the Upload speed list sub-menu
        submenu_bwupset = build_menu_radio_list(
            self.config['tray_upload_speed_list'], self.on_tray_setbwup,
            self.max_upload_speed,
            _('K/s'), show_notset=True, show_other=True
        )
        # Add the sub-menus to the tray menu
        self.builder.get_object('menuitem_download_limit').set_submenu(
            submenu_bwdownset)
        self.builder.get_object('menuitem_upload_limit').set_submenu(
            submenu_bwupset)

        # Show the sub-menus for all to see
        submenu_bwdownset.show_all()
        submenu_bwupset.show_all()

    def disable(self, invert_app_ind_conf=False):
        """Disables the system tray icon or appindicator."""
        try:
            if invert_app_ind_conf:
                app_ind_conf = not self.config['enable_appindicator']
            else:
                app_ind_conf = self.config['enable_appindicator']
            if appindicator and app_ind_conf:
                if hasattr(self, '_sig_win_hide'):
                    self.mainwindow.window.disconnect(self._sig_win_hide)
                    self.mainwindow.window.disconnect(self._sig_win_show)
                    log.debug('Disabling the application indicator..')

                self.indicator.set_status(appindicator.STATUS_PASSIVE)
                del self.indicator
            else:
                log.debug('Disabling the system tray icon..')
                self.tray.set_visible(False)
                del self.tray
            del self.builder
            del self.tray_menu
        except Exception as ex:
            log.debug('Unable to disable system tray: %s', ex)

    def blink(self, value):
        try:
            self.tray.set_blinking(value)
        except AttributeError:
            # If self.tray is not defined then ignore. This happens when the
            # tray icon is not being used.
            pass

    def on_enable_system_tray_set(self, key, value):
        """Called whenever the 'enable_system_tray' config key is modified"""
        if value:
            self.enable()
        else:
            self.disable()

    def on_enable_appindicator_set(self, key, value):
        """Called whenever the 'enable_appindicator' config key is modified"""
        if self.__enabled_set_once:
            self.disable(True)
            self.enable()
        self.__enabled_set_once = True

    def on_tray_clicked(self, icon):
        """Called when the tray icon is left clicked."""
        self.blink(False)

        if self.mainwindow.active():
            self.mainwindow.hide()
        else:
            self.mainwindow.present()

    def on_tray_popup(self, status_icon, button, activate_time):
        """Called when the tray icon is right clicked."""
        self.blink(False)

        if self.mainwindow.visible():
            self.builder.get_object('menuitem_show_deluge').set_active(True)
        else:
            self.builder.get_object('menuitem_show_deluge').set_active(False)

        popup_function = status_icon_position_menu
        if windows_check() or osx_check():
            popup_function = None
            button = 0
        self.tray_menu.popup(None, None, popup_function, button, activate_time, status_icon)

    def on_menuitem_show_deluge_activate(self, menuitem):
        log.debug('on_menuitem_show_deluge_activate')
        if menuitem.get_active() and not self.mainwindow.visible():
            self.mainwindow.present()
        elif not menuitem.get_active() and self.mainwindow.visible():
            self.mainwindow.hide()

    def on_menuitem_add_torrent_activate(self, menuitem):
        log.debug('on_menuitem_add_torrent_activate')
        component.get('AddTorrentDialog').show()

    def on_menuitem_pause_session_activate(self, menuitem):
        log.debug('on_menuitem_pause_session_activate')
        client.core.pause_session()

    def on_menuitem_resume_session_activate(self, menuitem):
        log.debug('on_menuitem_resume_session_activate')
        client.core.resume_session()

    def on_menuitem_quit_activate(self, menuitem):
        log.debug('on_menuitem_quit_activate')
        self.mainwindow.quit()

    def on_menuitem_quitdaemon_activate(self, menuitem):
        log.debug('on_menuitem_quitdaemon_activate')
        self.mainwindow.quit(shutdown=True)

    def on_tray_setbwdown(self, widget, data=None):
        if isinstance(widget, RadioMenuItem):
            # ignore previous radiomenuitem value
            if not widget.get_active():
                return
        self.setbwlimit(widget, _('Download Speed Limit'), _('Set the maximum download speed'),
                        'max_download_speed', 'tray_download_speed_list', self.max_download_speed,
                        'downloading.svg')

    def on_tray_setbwup(self, widget, data=None):
        if isinstance(widget, RadioMenuItem):
            # ignore previous radiomenuitem value
            if not widget.get_active():
                return
        self.setbwlimit(widget, _('Upload Speed Limit'), _('Set the maximum upload speed'),
                        'max_upload_speed', 'tray_upload_speed_list', self.max_upload_speed,
                        'seeding.svg')

    def _on_window_hide(self, widget, data=None):
        """_on_window_hide - update the menuitem's status"""
        log.debug('_on_window_hide')
        self.builder.get_object('menuitem_show_deluge').set_active(False)

    def _on_window_show(self, widget, data=None):
        """_on_window_show - update the menuitem's status"""
        log.debug('_on_window_show')
        self.builder.get_object('menuitem_show_deluge').set_active(True)

    def setbwlimit(self, widget, header, text, core_key, ui_key, default, image):
        """Sets the bandwidth limit based on the user selection."""
        def set_value(value):
            log.debug('setbwlimit: %s', value)
            if value is None:
                return
            elif value == 0:
                value = -1
            # Set the config in the core
            client.core.set_config({core_key: value})

        if widget.get_name() == 'unlimited':
            set_value(-1)
        elif widget.get_name() == 'other':
            dialog = dialogs.OtherDialog(header, text, _('K/s'), image, default)
            dialog.run().addCallback(set_value)
        else:
            set_value(widget.get_children()[0].get_text().split(' ')[0])
コード例 #27
0
class SystemTray(component.Component):
    def __init__(self):
        component.Component.__init__(self, 'SystemTray', interval=4)
        self.mainwindow = component.get('MainWindow')
        self.config = ConfigManager('gtkui.conf')
        # List of widgets that need to be hidden when not connected to a host
        self.hide_widget_list = [
            'menuitem_add_torrent',
            'menuitem_pause_session',
            'menuitem_resume_session',
            'menuitem_download_limit',
            'menuitem_upload_limit',
            'menuitem_quitdaemon',
            'separatormenuitem1',
            'separatormenuitem2',
            'separatormenuitem3',
            'separatormenuitem4',
        ]
        self.config.register_set_function('enable_system_tray',
                                          self.on_enable_system_tray_set)
        # bit of a hack to prevent function from doing something on startup
        self.__enabled_set_once = False
        self.config.register_set_function('enable_appindicator',
                                          self.on_enable_appindicator_set)

        self.max_download_speed = -1.0
        self.download_rate = 0.0
        self.max_upload_speed = -1.0
        self.upload_rate = 0.0

        self.config_value_changed_dict = {
            'max_download_speed': self._on_max_download_speed,
            'max_upload_speed': self._on_max_upload_speed,
        }

    def enable(self):
        """Enables the system tray icon."""
        self.builder = Builder()
        self.builder.add_from_file(
            resource_filename('deluge.ui.gtkui',
                              os.path.join('glade', 'tray_menu.ui')))

        self.builder.connect_signals(self)

        self.tray_menu = self.builder.get_object('tray_menu')

        if appindicator and self.config['enable_appindicator']:
            log.debug('Enabling the Application Indicator...')
            self.indicator = appindicator.Indicator(
                'deluge', 'deluge', appindicator.CATEGORY_APPLICATION_STATUS)
            try:
                self.indicator.set_property('title', _('Deluge'))
            except TypeError:
                # Catch 'title' property error for previous appindicator versions
                pass
            # Pass the menu to the Application Indicator
            self.indicator.set_menu(self.tray_menu)

            # Make sure the status of the Show Window MenuItem is correct
            self._sig_win_hide = self.mainwindow.window.connect(
                'hide', self._on_window_hide)
            self._sig_win_show = self.mainwindow.window.connect(
                'show', self._on_window_show)
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(
                    True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(
                    False)

            # Show the Application Indicator
            self.indicator.set_status(appindicator.STATUS_ACTIVE)

        else:
            log.debug('Enabling the system tray icon..')
            if windows_check() or osx_check():
                self.tray = status_icon_new_from_pixbuf(get_logo(32))
            else:
                self.tray = status_icon_new_from_icon_name('deluge-panel')

            self.tray.connect('activate', self.on_tray_clicked)
            self.tray.connect('popup-menu', self.on_tray_popup)

        self.builder.get_object('download-limit-image').set_from_file(
            get_pixmap('downloading16.png'))
        self.builder.get_object('upload-limit-image').set_from_file(
            get_pixmap('seeding16.png'))

        client.register_event_handler('ConfigValueChangedEvent',
                                      self.config_value_changed)
        if client.connected():
            # We're connected so we need to get some values from the core
            self.__start()
        else:
            # Hide menu widgets because we're not connected to a host.
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).hide()

    def __start(self):
        if self.config['enable_system_tray']:

            if self.config['standalone']:
                try:
                    self.hide_widget_list.remove('menuitem_quitdaemon')
                    self.hide_widget_list.remove('separatormenuitem4')
                except ValueError:
                    pass
                self.builder.get_object('menuitem_quitdaemon').hide()
                self.builder.get_object('separatormenuitem4').hide()

            # Show widgets in the hide list because we've connected to a host
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).show()

            # Build the bandwidth speed limit menus
            self.build_tray_bwsetsubmenu()

            # Get some config values
            def update_config_values(configs):
                self._on_max_download_speed(configs['max_download_speed'])
                self._on_max_upload_speed(configs['max_upload_speed'])

            client.core.get_config_values(
                ['max_download_speed',
                 'max_upload_speed']).addCallback(update_config_values)

    def start(self):
        self.__start()

    def stop(self):
        if self.config['enable_system_tray'] and not self.config[
                'enable_appindicator']:
            try:
                # Hide widgets in hide list because we're not connected to a host
                for widget in self.hide_widget_list:
                    self.builder.get_object(widget).hide()
            except Exception as ex:
                log.debug('Unable to hide system tray menu widgets: %s', ex)

            self.tray.set_tooltip_text(
                _('Deluge') + '\n' + _('Not Connected...'))

    def shutdown(self):
        if self.config['enable_system_tray']:
            if appindicator and self.config['enable_appindicator']:
                self.indicator.set_status(appindicator.STATUS_PASSIVE)
            else:
                self.tray.set_visible(False)

    def send_status_request(self):
        client.core.get_session_status(
            ['payload_upload_rate',
             'payload_download_rate']).addCallback(self._on_get_session_status)

    def config_value_changed(self, key, value):
        """This is called when we received a config_value_changed signal from
        the core."""
        if key in self.config_value_changed_dict:
            self.config_value_changed_dict[key](value)

    def _on_max_download_speed(self, max_download_speed):
        if self.max_download_speed != max_download_speed:
            self.max_download_speed = max_download_speed
            self.build_tray_bwsetsubmenu()

    def _on_max_upload_speed(self, max_upload_speed):
        if self.max_upload_speed != max_upload_speed:
            self.max_upload_speed = max_upload_speed
            self.build_tray_bwsetsubmenu()

    def _on_get_session_status(self, status):
        self.download_rate = fspeed(status['payload_download_rate'],
                                    shortform=True)
        self.upload_rate = fspeed(status['payload_upload_rate'],
                                  shortform=True)

    def update(self):
        if not self.config['enable_system_tray']:
            return

        # Tool tip text not available for appindicator
        if appindicator and self.config['enable_appindicator']:
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(
                    True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(
                    False)
            return

        # Set the tool tip text
        max_download_speed = self.max_download_speed
        max_upload_speed = self.max_upload_speed

        if max_download_speed == -1:
            max_download_speed = _('Unlimited')
        else:
            max_download_speed = '%s %s' % (max_download_speed, _('K/s'))
        if max_upload_speed == -1:
            max_upload_speed = _('Unlimited')
        else:
            max_upload_speed = '%s %s' % (max_upload_speed, _('K/s'))

        msg = '%s\n%s: %s (%s)\n%s: %s (%s)' % (
            _('Deluge'),
            _('Down'),
            self.download_rate,
            max_download_speed,
            _('Up'),
            self.upload_rate,
            max_upload_speed,
        )

        # Set the tooltip
        self.tray.set_tooltip_text(msg)

        self.send_status_request()

    def build_tray_bwsetsubmenu(self):
        # Create the Download speed list sub-menu
        submenu_bwdownset = build_menu_radio_list(
            self.config['tray_download_speed_list'],
            self.on_tray_setbwdown,
            self.max_download_speed,
            _('K/s'),
            show_notset=True,
            show_other=True,
        )

        # Create the Upload speed list sub-menu
        submenu_bwupset = build_menu_radio_list(
            self.config['tray_upload_speed_list'],
            self.on_tray_setbwup,
            self.max_upload_speed,
            _('K/s'),
            show_notset=True,
            show_other=True,
        )
        # Add the sub-menus to the tray menu
        self.builder.get_object('menuitem_download_limit').set_submenu(
            submenu_bwdownset)
        self.builder.get_object('menuitem_upload_limit').set_submenu(
            submenu_bwupset)

        # Show the sub-menus for all to see
        submenu_bwdownset.show_all()
        submenu_bwupset.show_all()

    def disable(self, invert_app_ind_conf=False):
        """Disables the system tray icon or appindicator."""
        try:
            if invert_app_ind_conf:
                app_ind_conf = not self.config['enable_appindicator']
            else:
                app_ind_conf = self.config['enable_appindicator']
            if appindicator and app_ind_conf:
                if hasattr(self, '_sig_win_hide'):
                    self.mainwindow.window.disconnect(self._sig_win_hide)
                    self.mainwindow.window.disconnect(self._sig_win_show)
                    log.debug('Disabling the application indicator..')

                self.indicator.set_status(appindicator.STATUS_PASSIVE)
                del self.indicator
            else:
                log.debug('Disabling the system tray icon..')
                self.tray.set_visible(False)
                del self.tray
            del self.builder
            del self.tray_menu
        except Exception as ex:
            log.debug('Unable to disable system tray: %s', ex)

    def blink(self, value):
        try:
            self.tray.set_blinking(value)
        except AttributeError:
            # If self.tray is not defined then ignore. This happens when the
            # tray icon is not being used.
            pass

    def on_enable_system_tray_set(self, key, value):
        """Called whenever the 'enable_system_tray' config key is modified"""
        if value:
            self.enable()
        else:
            self.disable()

    def on_enable_appindicator_set(self, key, value):
        """Called whenever the 'enable_appindicator' config key is modified"""
        if self.__enabled_set_once:
            self.disable(True)
            self.enable()
        self.__enabled_set_once = True

    def on_tray_clicked(self, icon):
        """Called when the tray icon is left clicked."""
        self.blink(False)

        if self.mainwindow.active():
            self.mainwindow.hide()
        else:
            self.mainwindow.present()

    def on_tray_popup(self, status_icon, button, activate_time):
        """Called when the tray icon is right clicked."""
        self.blink(False)

        if self.mainwindow.visible():
            self.builder.get_object('menuitem_show_deluge').set_active(True)
        else:
            self.builder.get_object('menuitem_show_deluge').set_active(False)

        popup_function = status_icon_position_menu
        if windows_check() or osx_check():
            popup_function = None
            button = 0
        self.tray_menu.popup(None, None, popup_function, button, activate_time,
                             status_icon)

    def on_menuitem_show_deluge_activate(self, menuitem):
        log.debug('on_menuitem_show_deluge_activate')
        if menuitem.get_active() and not self.mainwindow.visible():
            self.mainwindow.present()
        elif not menuitem.get_active() and self.mainwindow.visible():
            self.mainwindow.hide()

    def on_menuitem_add_torrent_activate(self, menuitem):
        log.debug('on_menuitem_add_torrent_activate')
        component.get('AddTorrentDialog').show()

    def on_menuitem_pause_session_activate(self, menuitem):
        log.debug('on_menuitem_pause_session_activate')
        client.core.pause_session()

    def on_menuitem_resume_session_activate(self, menuitem):
        log.debug('on_menuitem_resume_session_activate')
        client.core.resume_session()

    def on_menuitem_quit_activate(self, menuitem):
        log.debug('on_menuitem_quit_activate')
        self.mainwindow.quit()

    def on_menuitem_quitdaemon_activate(self, menuitem):
        log.debug('on_menuitem_quitdaemon_activate')
        self.mainwindow.quit(shutdown=True)

    def on_tray_setbwdown(self, widget, data=None):
        if isinstance(widget, RadioMenuItem):
            # ignore previous radiomenuitem value
            if not widget.get_active():
                return
        self.setbwlimit(
            widget,
            _('Download Speed Limit'),
            _('Set the maximum download speed'),
            'max_download_speed',
            'tray_download_speed_list',
            self.max_download_speed,
            'downloading.svg',
        )

    def on_tray_setbwup(self, widget, data=None):
        if isinstance(widget, RadioMenuItem):
            # ignore previous radiomenuitem value
            if not widget.get_active():
                return
        self.setbwlimit(
            widget,
            _('Upload Speed Limit'),
            _('Set the maximum upload speed'),
            'max_upload_speed',
            'tray_upload_speed_list',
            self.max_upload_speed,
            'seeding.svg',
        )

    def _on_window_hide(self, widget, data=None):
        """_on_window_hide - update the menuitem's status"""
        log.debug('_on_window_hide')
        self.builder.get_object('menuitem_show_deluge').set_active(False)

    def _on_window_show(self, widget, data=None):
        """_on_window_show - update the menuitem's status"""
        log.debug('_on_window_show')
        self.builder.get_object('menuitem_show_deluge').set_active(True)

    def setbwlimit(self, widget, header, text, core_key, ui_key, default,
                   image):
        """Sets the bandwidth limit based on the user selection."""
        def set_value(value):
            log.debug('setbwlimit: %s', value)
            if value is None:
                return
            elif value == 0:
                value = -1
            # Set the config in the core
            client.core.set_config({core_key: value})

        if widget.get_name() == 'unlimited':
            set_value(-1)
        elif widget.get_name() == 'other':
            dialog = dialogs.OtherDialog(header, text, _('K/s'), image,
                                         default)
            dialog.run().addCallback(set_value)
        else:
            set_value(widget.get_children()[0].get_text().split(' ')[0])
コード例 #28
0
    def enable(self):
        """Enables the system tray icon."""
        self.builder = Builder()
        self.builder.add_from_file(
            resource_filename('deluge.ui.gtkui',
                              os.path.join('glade', 'tray_menu.ui')))

        self.builder.connect_signals(self)

        self.tray_menu = self.builder.get_object('tray_menu')

        if appindicator and self.config['enable_appindicator']:
            log.debug('Enabling the Application Indicator...')
            self.indicator = appindicator.Indicator(
                'deluge', 'deluge', appindicator.CATEGORY_APPLICATION_STATUS)
            try:
                self.indicator.set_property('title', _('Deluge'))
            except TypeError:
                # Catch 'title' property error for previous appindicator versions
                pass
            # Pass the menu to the Application Indicator
            self.indicator.set_menu(self.tray_menu)

            # Make sure the status of the Show Window MenuItem is correct
            self._sig_win_hide = self.mainwindow.window.connect(
                'hide', self._on_window_hide)
            self._sig_win_show = self.mainwindow.window.connect(
                'show', self._on_window_show)
            if self.mainwindow.visible():
                self.builder.get_object('menuitem_show_deluge').set_active(
                    True)
            else:
                self.builder.get_object('menuitem_show_deluge').set_active(
                    False)

            # Show the Application Indicator
            self.indicator.set_status(appindicator.STATUS_ACTIVE)

        else:
            log.debug('Enabling the system tray icon..')
            if windows_check() or osx_check():
                self.tray = status_icon_new_from_pixbuf(get_logo(32))
            else:
                self.tray = status_icon_new_from_icon_name('deluge-panel')

            self.tray.connect('activate', self.on_tray_clicked)
            self.tray.connect('popup-menu', self.on_tray_popup)

        self.builder.get_object('download-limit-image').set_from_file(
            get_pixmap('downloading16.png'))
        self.builder.get_object('upload-limit-image').set_from_file(
            get_pixmap('seeding16.png'))

        client.register_event_handler('ConfigValueChangedEvent',
                                      self.config_value_changed)
        if client.connected():
            # We're connected so we need to get some values from the core
            self.__start()
        else:
            # Hide menu widgets because we're not connected to a host.
            for widget in self.hide_widget_list:
                self.builder.get_object(widget).hide()
コード例 #29
0
ファイル: gui.py プロジェクト: wodny/pendrive-frenzy-2
class GUI:
    def __init__(self, updates_out, events_in):
        self.updates_out = updates_out
        self.events_in = events_in

        self.builder = Builder()
        self.builder.add_from_file(sys.path[0] + "/lib/pendrive-frenzy.glade")

        self.window = self.builder.get_object("main_window")
        self.pendrive_list = PendriveListWrapper(
            self.builder.get_object("pendrive_list"))
        self.writing_enabled = self.builder.get_object("writing_enabled")
        self.infobar = self.builder.get_object("infobar")
        self.statusbar = self.builder.get_object("statusbar")
        self.statusbar_contextid = self.statusbar.get_context_id("default")

        self.builder.connect_signals(self)
        self.window.show()

    def loop(self):
        updater = Updater(self.updates_out, self)
        updater.start()

        logging.debug(_("Entering GTK loop..."))
        gtk.main()
        logging.debug(_("Exited GTK loop."))
        self.events_in.put(Quit())
        self.events_in.close()
        self.events_in.join_thread()
        self.updates_out.close()
        self.updates_out.join_thread()
        logging.debug(_("GUI end."))

    def on_main_window_destroy(self, widget, data=None):
        gtk.main_quit()

    def on_select_source_dir_pressed(self, widget, data=None):
        chooser = gtk.FileChooserDialog(
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))

        chooser.set_default_response(gtk.RESPONSE_OK)
        response = chooser.run()
        if response == gtk.RESPONSE_OK:
            source = chooser.get_filename()
            self.infobar.set_text(_("Loading config: {0}...".format(source)))
            self.events_in.put(ReadConfig(source))
        chooser.destroy()

    def on_writing_pressed(self, widget, data=None):
        active = self.writing_active()
        self.events_in.put(WritingChanged(active))

    def writing_active(self):
        return self.writing_enabled.get_active()

    def infobar_update(self, info):
        gobject.idle_add(self.__infobar_update, info)

    def __infobar_update(self, info):
        self.infobar.set_text(info)

    def statusbar_update(self, status):
        gobject.idle_add(self.__statusbar_update, status)

    def __statusbar_update(self, status):
        self.statusbar.pop(self.statusbar_contextid)
        self.statusbar.push(self.statusbar_contextid, status)

    def status_update(self, pendrive, status_code, status_text):
        gobject.idle_add(self.__status_update_idle, pendrive, status_code,
                         status_text)

    def __status_update_idle(self, pendrive, status_code, status_text):
        pendrive = self.pendrive_list.pendrive_store.find(pendrive)
        if pendrive is None:
            return
        self.pendrive_list.pendrive_store.set_status(pendrive, status_code,
                                                     status_text)

    def quit(self):
        gobject.idle_add(self.__quit)

    def __quit(self):
        gtk.main_quit()

    def pendrive_add(self, pendrive, port):
        gobject.idle_add(self.__pendrive_add_idle, pendrive, port)

    def __pendrive_add_idle(self, pendrive, port):
        self.pendrive_list.pendrive_store.store.append([
            pendrive, port,
            _("New"), DriveStatus.DRIVE_NEW, PendriveStore.COLOR_NEW
        ])

    def pendrive_remove(self, pendrive):
        gobject.idle_add(self.__pendrive_remove_idle, pendrive)

    def __pendrive_remove_idle(self, pendrive):
        pendrive_iter = self.pendrive_list.pendrive_store.find(pendrive)
        if pendrive_iter is None:
            return
        self.pendrive_list.pendrive_store.store.remove(pendrive_iter)
コード例 #30
0
class UI:
    """ the complete user interface of the program """
    def __init__(self, flc):
        """ constructor """
        self.builder = None
        self.mainWindow = None
        self.fssEntry = None
        self.bssEntry = None
        self.andCombo = None
        self.implicationCombo = None
        self.rbList = None
        self.rulesBox = None
        self.inputsBox = None
        self.outputsBox = None
        self.closeButton = None
        self.executeButton = None
        self.discSpin = None
        self.outputLabels = None
        self.inputPlots = None
        self.outputPlots = None
        self.currentFLC = flc

    def showUI(self):
        """ shows the ui and starts it so user interaction can begin """
        self.builder = Builder()
        self.builder.add_from_file("ui.xml")
        self.mainWindow = self.builder.get_object("mainWin")
        self.mainWindow.set_title(self.currentFLC.label)
        self.mainWindow.maximize()
        self.mainWindow.connect("delete-event", main_quit)
        self.fssEntry = self.builder.get_object("fssEntry")
        self.bssEntry = self.builder.get_object("bssEntry")
        self.inputsBox = self.builder.get_object("inputsBox")
        self.outputsBox = self.builder.get_object("outputsBox")
        self.rulesBox = self.builder.get_object("rulesBox")
        self.andCombo = self.builder.get_object("andCombo")
        self.implicationCombo = self.builder.get_object("implicationCombo")
        self.inputPlots = []
        self.outputPlots = []
        for i in self.currentFLC.inputs:
            self.inputPlots.append(PlotWidget([i]))
        for i in self.currentFLC.outputs:
            self.outputPlots.append(PlotWidget([i]))
        for k, i in enumerate(self.inputPlots):
            self.inputsBox.pack_start(self.inputPlots[k].get_canvas_widget())
        for k, i in enumerate(self.outputPlots):
            self.outputsBox.pack_start(self.outputPlots[k].get_canvas_widget())
        self.rbList = RuleBaseWidget(
            self.currentFLC.rulebase).get_list_widget()
        self.rulesBox.pack_start(self.rbList)
        self.discSpin = self.builder.get_object("discretizationSteps")
        self.closeButton = self.builder.get_object("closeBtn")
        self.closeButton.connect("clicked", main_quit)
        self.executeButton = self.builder.get_object("execBtn")
        self.executeButton.connect("clicked", self.execute_clicked)
        self.mainWindow.show_all()
        main()

    def execute_clicked(self, widget):
        """ called when the user clicks on the execute button """
        if self.outputLabels != None:
            """ clears the output label widgets """
            for l in self.outputLabels:
                l.destroy()
        self.outputLabels = []
        """ clears the output plots """
        for op in self.outputPlots:
            op.clear()

        try:
            """ calibrates the rule base of the controller """
            self.currentFLC.rulebase.calibrate()
        except:
            error(
                "Incomplete rule base",
                "Please fill in the missing items in the Rule Base and try again."
            )
            return

        try:
            """ sets the input variable values from the text boxes """
            input_vars = [
                float(self.fssEntry.get_text()),
                float(self.bssEntry.get_text())
            ]
        except:
            error(
                "Incorrect sensor input values",
                "Please input correct integer or floating-point values and try again."
            )
            return
        """ sets the function pointer to the AND and implication operators, either
        to the python built-in function min() or the product() function
    """
        if (self.andCombo.get_active_text() == "Minimum"):
            andOp = min
        else:
            andOp = product

        if (self.implicationCombo.get_active_text() == "Minimum"):
            implOp = min
        else:
            implOp = product
        """ sets the number of discretization steps from the spin text box """
        disc_steps = self.discSpin.get_value_as_int()
        """ runs the controller """
        output = self.currentFLC.run(input_vars, andOp, implOp, disc_steps)
        """ refreshes the view from the model """
        self.rbList.refresh()
        """ sets the output label widgets to their values and puts them into the
        gtk box
    """
        for o in output:
            tmp = Label("<b>" + o[0] + "</b>" + "\t" + str(o[1]))
            tmp.set_use_markup(True)
            self.outputLabels.append(tmp)
        for w in self.outputLabels:
            self.rulesBox.pack_start(w, False, False, 5)
        """ clears the plotting widgets, creates the new plots of the outputs
        (adding the defuzzified outputs) and adds the widgets back with the
        new plots
    """
        for k, v in enumerate(self.currentFLC.outputs):
            self.outputPlots[k].add_var(v.get_defuz_var(implOp, disc_steps))
        self.outputsBox.foreach(self.outputsBox.remove)
        for k, i in enumerate(self.outputPlots):
            self.outputsBox.pack_start(self.outputPlots[k].get_canvas_widget())
        self.mainWindow.show_all()