Fixed "PluginEnabledEvent" and "PluginDisabledEvent" the argument cannot be called name since that should contain the event name.

Ported plugins on deluge's git to this new event dispatching style.
This commit is contained in:
Pedro Algarvio 2010-12-11 05:42:45 +00:00
parent 67ea05921c
commit 078ed6ba71
15 changed files with 120 additions and 115 deletions

View File

@ -273,24 +273,24 @@ class PluginEnabledEvent(DelugeEvent):
""" """
Emitted when a plugin is enabled in the Core. Emitted when a plugin is enabled in the Core.
""" """
__slots__ = ('name',) __slots__ = ('plugin_name',)
def __init__(self, name): def __init__(self, plugin_name):
""" """
:param name: the plugin name :param plugin_name: the plugin name
:type name: string :type plugin_name: string
""" """
self.name = name self.plugin_name = plugin_name
class PluginDisabledEvent(DelugeEvent): class PluginDisabledEvent(DelugeEvent):
""" """
Emitted when a plugin is disabled in the Core. Emitted when a plugin is disabled in the Core.
""" """
__slots__ = ('name',) __slots__ = ('plugin_name',)
def __init__(self, name): def __init__(self, plugin_name):
""" """
:param name: the plugin name :param plugin_name: the plugin name
:type name: string :type plugin_name: string
""" """
self.name = name self.plugin_name = plugin_name

View File

@ -57,7 +57,7 @@ OPTIONS_AVAILABLE = { #option: builtin
"enabled":False, "enabled":False,
"path":False, "path":False,
"append_extension":False, "append_extension":False,
"abspath":False, "abspath":False,
"download_location":True, "download_location":True,
"max_download_speed":True, "max_download_speed":True,
"max_upload_speed":True, "max_upload_speed":True,
@ -79,8 +79,6 @@ MAX_NUM_ATTEMPTS = 10
class AutoaddOptionsChangedEvent(DelugeEvent): class AutoaddOptionsChangedEvent(DelugeEvent):
"""Emitted when the options for the plugin are changed.""" """Emitted when the options for the plugin are changed."""
def __init__(self):
pass
def CheckInput(cond, message): def CheckInput(cond, message):
if not cond: if not cond:
@ -88,7 +86,7 @@ def CheckInput(cond, message):
class Core(CorePluginBase): class Core(CorePluginBase):
def enable(self): def enable(self):
#reduce typing, assigning some values to self... #reduce typing, assigning some values to self...
self.config = deluge.configmanager.ConfigManager("autoadd.conf", DEFAULT_PREFS) self.config = deluge.configmanager.ConfigManager("autoadd.conf", DEFAULT_PREFS)
self.watchdirs = self.config["watchdirs"] self.watchdirs = self.config["watchdirs"]
@ -127,7 +125,7 @@ class Core(CorePluginBase):
def update(self): def update(self):
pass pass
@export() @export()
def set_options(self, watchdir_id, options): def set_options(self, watchdir_id, options):
"""Update the options for a watch folder.""" """Update the options for a watch folder."""
@ -147,14 +145,14 @@ class Core(CorePluginBase):
#disable the watch loop if it was active #disable the watch loop if it was active
if watchdir_id in self.update_timers: if watchdir_id in self.update_timers:
self.disable_watchdir(watchdir_id) self.disable_watchdir(watchdir_id)
self.watchdirs[watchdir_id].update(options) self.watchdirs[watchdir_id].update(options)
#re-enable watch loop if appropriate #re-enable watch loop if appropriate
if self.watchdirs[watchdir_id]['enabled']: if self.watchdirs[watchdir_id]['enabled']:
self.enable_watchdir(watchdir_id) self.enable_watchdir(watchdir_id)
self.config.save() self.config.save()
component.get("EventManager").emit(AutoaddOptionsChangedEvent()) component.get("EventManager").emit(AutoaddOptionsChangedEvent())
def load_torrent(self, filename): def load_torrent(self, filename):
try: try:
log.debug("Attempting to open %s for add.", filename) log.debug("Attempting to open %s for add.", filename)
@ -171,7 +169,7 @@ class Core(CorePluginBase):
info = lt.torrent_info(lt.bdecode(filedump)) info = lt.torrent_info(lt.bdecode(filedump))
return filedump return filedump
def update_watchdir(self, watchdir_id): def update_watchdir(self, watchdir_id):
"""Check the watch folder for new torrents to add.""" """Check the watch folder for new torrents to add."""
watchdir_id = str(watchdir_id) watchdir_id = str(watchdir_id)
@ -185,7 +183,7 @@ class Core(CorePluginBase):
log.warning("Invalid AutoAdd folder: %s", watchdir["abspath"]) log.warning("Invalid AutoAdd folder: %s", watchdir["abspath"])
self.disable_watchdir(watchdir_id) self.disable_watchdir(watchdir_id)
return return
# Generate options dict for watchdir # Generate options dict for watchdir
opts = {} opts = {}
if 'stop_at_ratio_toggle' in watchdir: if 'stop_at_ratio_toggle' in watchdir:
@ -246,7 +244,7 @@ class Core(CorePluginBase):
"""Disables any watch folders with unhandled exceptions.""" """Disables any watch folders with unhandled exceptions."""
self.disable_watchdir(watchdir_id) self.disable_watchdir(watchdir_id)
log.error("Disabling '%s', error during update: %s" % (self.watchdirs[watchdir_id]["path"], failure)) log.error("Disabling '%s', error during update: %s" % (self.watchdirs[watchdir_id]["path"], failure))
@export @export
def enable_watchdir(self, watchdir_id): def enable_watchdir(self, watchdir_id):
watchdir_id = str(watchdir_id) watchdir_id = str(watchdir_id)
@ -259,7 +257,7 @@ class Core(CorePluginBase):
self.watchdirs[watchdir_id]['enabled'] = True self.watchdirs[watchdir_id]['enabled'] = True
self.config.save() self.config.save()
component.get("EventManager").emit(AutoaddOptionsChangedEvent()) component.get("EventManager").emit(AutoaddOptionsChangedEvent())
@export @export
def disable_watchdir(self, watchdir_id): def disable_watchdir(self, watchdir_id):
watchdir_id = str(watchdir_id) watchdir_id = str(watchdir_id)
@ -287,7 +285,7 @@ class Core(CorePluginBase):
def get_config(self): def get_config(self):
"""Returns the config dictionary.""" """Returns the config dictionary."""
return self.config.config return self.config.config
@export() @export()
def get_watchdirs(self): def get_watchdirs(self):
return self.watchdirs.keys() return self.watchdirs.keys()
@ -319,7 +317,7 @@ class Core(CorePluginBase):
self.config.save() self.config.save()
component.get("EventManager").emit(AutoaddOptionsChangedEvent()) component.get("EventManager").emit(AutoaddOptionsChangedEvent())
return watchdir_id return watchdir_id
@export @export
def remove(self, watchdir_id): def remove(self, watchdir_id):
"""Remove a watch folder.""" """Remove a watch folder."""

View File

@ -113,22 +113,22 @@ class OptionsDialog():
self.glade.get_widget(field+"_entry").show() self.glade.get_widget(field+"_entry").show()
self.glade.get_widget(field+"_chooser").hide() self.glade.get_widget(field+"_chooser").hide()
self.set_sensitive() self.set_sensitive()
def on_get_enabled_plugins(result): def on_get_enabled_plugins(result):
if 'Label' in result: if 'Label' in result:
self.glade.get_widget('label_frame').show() self.glade.get_widget('label_frame').show()
else: else:
self.glade.get_widget('label_frame').hide() self.glade.get_widget('label_frame').hide()
self.glade.get_widget('label_toggle').set_active(False) self.glade.get_widget('label_toggle').set_active(False)
client.core.get_enabled_plugins().addCallback(on_get_enabled_plugins) client.core.get_enabled_plugins().addCallback(on_get_enabled_plugins)
def set_sensitive(self): def set_sensitive(self):
maintoggles = ['download_location', 'append_extension', 'move_completed', 'label', \ maintoggles = ['download_location', 'append_extension', 'move_completed', 'label', \
'max_download_speed', 'max_upload_speed', 'max_connections', \ 'max_download_speed', 'max_upload_speed', 'max_connections', \
'max_upload_slots', 'add_paused', 'auto_managed', 'stop_at_ratio', 'queue_to_top'] 'max_upload_slots', 'add_paused', 'auto_managed', 'stop_at_ratio', 'queue_to_top']
[self.on_toggle_toggled(self.glade.get_widget(x+'_toggle')) for x in maintoggles] [self.on_toggle_toggled(self.glade.get_widget(x+'_toggle')) for x in maintoggles]
def on_toggle_toggled(self, tb): def on_toggle_toggled(self, tb):
toggle = str(tb.name).replace("_toggle", "") toggle = str(tb.name).replace("_toggle", "")
isactive = tb.get_active() isactive = tb.get_active()
@ -166,29 +166,29 @@ class OptionsDialog():
self.glade.get_widget('stop_at_ratio').set_active(isactive) self.glade.get_widget('stop_at_ratio').set_active(isactive)
self.glade.get_widget('stop_ratio').set_sensitive(isactive) self.glade.get_widget('stop_ratio').set_sensitive(isactive)
self.glade.get_widget('remove_at_ratio').set_sensitive(isactive) self.glade.get_widget('remove_at_ratio').set_sensitive(isactive)
def on_apply(self, Event=None): def on_apply(self, Event=None):
client.autoadd.set_options(str(self.watchdir_id), self.generate_opts()).addCallbacks(self.on_added, self.on_error_show) client.autoadd.set_options(str(self.watchdir_id), self.generate_opts()).addCallbacks(self.on_added, self.on_error_show)
def on_error_show(self, result): def on_error_show(self, result):
self.glade.get_widget('error_label').set_text(result.value.exception_msg) self.glade.get_widget('error_label').set_text(result.value.exception_msg)
self.err_dialog = self.glade.get_widget('error_dialog') self.err_dialog = self.glade.get_widget('error_dialog')
self.err_dialog.set_transient_for(self.dialog) self.err_dialog.set_transient_for(self.dialog)
result.cleanFailure() result.cleanFailure()
self.err_dialog.show() self.err_dialog.show()
def on_added(self, result): def on_added(self, result):
self.dialog.destroy() self.dialog.destroy()
def on_error_ok(self, Event=None): def on_error_ok(self, Event=None):
self.err_dialog.hide() self.err_dialog.hide()
def on_add(self, Event=None): def on_add(self, Event=None):
client.autoadd.add(self.generate_opts()).addCallbacks(self.on_added, self.on_error_show) client.autoadd.add(self.generate_opts()).addCallbacks(self.on_added, self.on_error_show)
def on_cancel(self, Event=None): def on_cancel(self, Event=None):
self.dialog.destroy() self.dialog.destroy()
def generate_opts(self): def generate_opts(self):
# generate options dict based on gtk objects # generate options dict based on gtk objects
options = {} options = {}
@ -217,11 +217,11 @@ class OptionsDialog():
options[id] = self.glade.get_widget(id).get_active() options[id] = self.glade.get_widget(id).get_active()
options[id+'_toggle'] = self.glade.get_widget(id+'_toggle').get_active() options[id+'_toggle'] = self.glade.get_widget(id+'_toggle').get_active()
return options return options
class GtkUI(GtkPluginBase): class GtkUI(GtkPluginBase):
def enable(self): def enable(self):
self.glade = gtk.glade.XML(get_resource("config.glade")) self.glade = gtk.glade.XML(get_resource("config.glade"))
self.glade.signal_autoconnect({ self.glade.signal_autoconnect({
"on_add_button_clicked": self.on_add_button_clicked, "on_add_button_clicked": self.on_add_button_clicked,
@ -229,18 +229,18 @@ class GtkUI(GtkPluginBase):
"on_remove_button_clicked": self.on_remove_button_clicked "on_remove_button_clicked": self.on_remove_button_clicked
}) })
self.opts_dialog = OptionsDialog() self.opts_dialog = OptionsDialog()
component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs) component.get("PluginManager").register_hook("on_apply_prefs", self.on_apply_prefs)
component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs) component.get("PluginManager").register_hook("on_show_prefs", self.on_show_prefs)
client.register_event_handler("AutoaddOptionsChangedEvent", self.on_options_changed_event) client.register_event_handler("AutoaddOptionsChangedEvent", self.on_options_changed_event)
self.watchdirs = {} self.watchdirs = {}
vbox = self.glade.get_widget("watchdirs_vbox") vbox = self.glade.get_widget("watchdirs_vbox")
sw = gtk.ScrolledWindow() sw = gtk.ScrolledWindow()
sw.set_shadow_type(gtk.SHADOW_ETCHED_IN) sw.set_shadow_type(gtk.SHADOW_ETCHED_IN)
sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
vbox.pack_start(sw, True, True, 0) vbox.pack_start(sw, True, True, 0)
self.store = self.create_model() self.store = self.create_model()
@ -256,28 +256,28 @@ class GtkUI(GtkPluginBase):
component.get("Preferences").add_page("AutoAdd", self.glade.get_widget("prefs_box")) component.get("Preferences").add_page("AutoAdd", self.glade.get_widget("prefs_box"))
self.on_show_prefs() self.on_show_prefs()
def disable(self): def disable(self):
component.get("Preferences").remove_page("AutoAdd") component.get("Preferences").remove_page("AutoAdd")
component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_prefs) component.get("PluginManager").deregister_hook("on_apply_prefs", self.on_apply_prefs)
component.get("PluginManager").deregister_hook("on_show_prefs", self.on_show_prefs) component.get("PluginManager").deregister_hook("on_show_prefs", self.on_show_prefs)
def create_model(self): def create_model(self):
store = gtk.ListStore(str, bool, str) store = gtk.ListStore(str, bool, str)
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.iteritems():
store.append([watchdir_id, watchdir['enabled'], watchdir['path']]) store.append([watchdir_id, watchdir['enabled'], watchdir['path']])
return store return store
def create_columns(self, treeView): def create_columns(self, treeView):
rendererToggle = gtk.CellRendererToggle() rendererToggle = gtk.CellRendererToggle()
column = gtk.TreeViewColumn("On", rendererToggle, activatable=True, active=1) column = gtk.TreeViewColumn("On", rendererToggle, activatable=True, active=1)
column.set_sort_column_id(1) column.set_sort_column_id(1)
treeView.append_column(column) treeView.append_column(column)
tt = gtk.Tooltip() tt = gtk.Tooltip()
tt.set_text('Double-click to toggle') tt.set_text('Double-click to toggle')
treeView.set_tooltip_cell(tt, None, None, rendererToggle) treeView.set_tooltip_cell(tt, None, None, rendererToggle)
rendererText = gtk.CellRendererText() rendererText = gtk.CellRendererText()
column = gtk.TreeViewColumn("Path", rendererText, text=2) column = gtk.TreeViewColumn("Path", rendererText, text=2)
column.set_sort_column_id(2) column.set_sort_column_id(2)
@ -289,20 +289,20 @@ class GtkUI(GtkPluginBase):
def load_watchdir_list(self): def load_watchdir_list(self):
pass pass
def add_watchdir_entry(self): def add_watchdir_entry(self):
pass pass
def on_add_button_clicked(self, Event=None): def on_add_button_clicked(self, Event=None):
#display options_window #display options_window
self.opts_dialog.show() self.opts_dialog.show()
def on_remove_button_clicked(self, Event=None): def on_remove_button_clicked(self, Event=None):
tree, tree_id = self.treeView.get_selection().get_selected() tree, tree_id = self.treeView.get_selection().get_selected()
watchdir_id = str(self.store.get_value(tree_id, 0)) watchdir_id = str(self.store.get_value(tree_id, 0))
if watchdir_id: if watchdir_id:
client.autoadd.remove(watchdir_id) client.autoadd.remove(watchdir_id)
def on_edit_button_clicked(self, Event=None, a=None, col=None): def on_edit_button_clicked(self, Event=None, a=None, col=None):
tree, tree_id = self.treeView.get_selection().get_selected() tree, tree_id = self.treeView.get_selection().get_selected()
watchdir_id = str(self.store.get_value(tree_id, 0)) watchdir_id = str(self.store.get_value(tree_id, 0))
@ -314,7 +314,7 @@ class GtkUI(GtkPluginBase):
client.autoadd.enable_watchdir(watchdir_id) client.autoadd.enable_watchdir(watchdir_id)
else: else:
self.opts_dialog.show(self.watchdirs[watchdir_id], watchdir_id) self.opts_dialog.show(self.watchdirs[watchdir_id], watchdir_id)
def on_listitem_activated(self, treeview): def on_listitem_activated(self, treeview):
tree, tree_id = self.treeView.get_selection().get_selected() tree, tree_id = self.treeView.get_selection().get_selected()
if tree_id: if tree_id:
@ -323,7 +323,7 @@ class GtkUI(GtkPluginBase):
else: else:
self.glade.get_widget('edit_button').set_sensitive(False) self.glade.get_widget('edit_button').set_sensitive(False)
self.glade.get_widget('remove_button').set_sensitive(False) self.glade.get_widget('remove_button').set_sensitive(False)
def on_apply_prefs(self): def on_apply_prefs(self):
log.debug("applying prefs for AutoAdd") log.debug("applying prefs for AutoAdd")
for watchdir_id, watchdir in self.watchdirs.iteritems(): for watchdir_id, watchdir in self.watchdirs.iteritems():
@ -331,8 +331,8 @@ class GtkUI(GtkPluginBase):
def on_show_prefs(self): def on_show_prefs(self):
client.autoadd.get_config().addCallback(self.cb_get_config) client.autoadd.get_config().addCallback(self.cb_get_config)
def on_options_changed_event(self): def on_options_changed_event(self, event):
client.autoadd.get_config().addCallback(self.cb_get_config) client.autoadd.get_config().addCallback(self.cb_get_config)
def cb_get_config(self, config): def cb_get_config(self, config):
@ -344,4 +344,4 @@ class GtkUI(GtkPluginBase):
# Disable the remove and edit buttons, because nothing in the store is selected # Disable the remove and edit buttons, because nothing in the store is selected
self.glade.get_widget('remove_button').set_sensitive(False) self.glade.get_widget('remove_button').set_sensitive(False)
self.glade.get_widget('edit_button').set_sensitive(False) self.glade.get_widget('edit_button').set_sensitive(False)

View File

@ -62,15 +62,19 @@ class ExecuteCommandAddedEvent(DelugeEvent):
""" """
Emitted when a new command is added. Emitted when a new command is added.
""" """
__slots__ = ('command_id', 'event', 'command')
def __init__(self, command_id, event, command): def __init__(self, command_id, event, command):
self._args = [command_id, event, command] self.command_id = command_id
self.event = event
self.command = command
class ExecuteCommandRemovedEvent(DelugeEvent): class ExecuteCommandRemovedEvent(DelugeEvent):
""" """
Emitted when a command is removed. Emitted when a command is removed.
""" """
__slots__ = ('command_id',)
def __init__(self, command_id): def __init__(self, command_id):
self._args = [command_id] self.command_id = command_id
class Core(CorePluginBase): class Core(CorePluginBase):
def enable(self): def enable(self):
@ -80,17 +84,17 @@ class Core(CorePluginBase):
# Go through the commands list and register event handlers # Go through the commands list and register event handlers
for command in self.config["commands"]: for command in self.config["commands"]:
event = command[EXECUTE_EVENT] event_name = command[EXECUTE_EVENT]
if event in self.registered_events: if event_name in self.registered_events:
continue continue
def create_event_handler(event): def create_event_handler(event_name):
def event_handler(torrent_id): def event_handler(event):
self.execute_commands(torrent_id, event) self.execute_commands(event.torrent_id, event_name)
return event_handler return event_handler
event_handler = create_event_handler(event) event_handler = create_event_handler(event_name)
event_manager.register_event_handler(EVENT_MAP[event], event_handler) event_manager.register_event_handler(EVENT_MAP[event_name], event_handler)
self.registered_events[event] = event_handler self.registered_events[event_name] = event_handler
log.debug("Execute core plugin enabled!") log.debug("Execute core plugin enabled!")

View File

@ -159,13 +159,13 @@ class ExecutePreferences(object):
command = widget.get_text() command = widget.get_text()
client.execute.save_command(command_id, event, command) client.execute.save_command(command_id, event, command)
def on_command_added_event(self, command_id, event, command): def on_command_added_event(self, event):
log.debug("Adding command %s: %s", event, command) log.debug("Adding command %s: %s", event.event, event.command)
self.add_command(command_id, event, command) self.add_command(event.command_id, event.event, event.command)
def on_command_removed_event(self, command_id): def on_command_removed_event(self, event):
log.debug("Removing command %s", command_id) log.debug("Removing command %s", event.command_id)
self.remove_command(command_id) self.remove_command(event.command_id)
class GtkUI(GtkPluginBase): class GtkUI(GtkPluginBase):

View File

@ -75,14 +75,14 @@ class Core(CorePluginBase):
def update(self): def update(self):
pass pass
def _on_torrent_finished(self, torrent_id): def _on_torrent_finished(self, event):
""" """
This is called when a torrent finishes. We need to check to see if there This is called when a torrent finishes. We need to check to see if there
are any files to extract. are any files to extract.
""" """
# Get the save path # Get the save path
save_path = component.get("TorrentManager")[torrent_id].get_status(["save_path"])["save_path"] save_path = component.get("TorrentManager")[event.torrent_id].get_status(["save_path"])["save_path"]
files = component.get("TorrentManager")[torrent_id].get_files() files = component.get("TorrentManager")[event.torrent_id].get_files()
for f in files: for f in files:
ext = os.path.splitext(f["path"]) ext = os.path.splitext(f["path"])
if ext[1] in (".gz", ".bz2", ".lzma"): if ext[1] in (".gz", ".bz2", ".lzma"):
@ -98,22 +98,22 @@ class Core(CorePluginBase):
# Now that we have the cmd, lets run it to extract the files # Now that we have the cmd, lets run it to extract the files
fp = os.path.join(save_path, f["path"]) fp = os.path.join(save_path, f["path"])
# Get the destination path # Get the destination path
dest = self.config["extract_path"] dest = self.config["extract_path"]
if self.config["use_name_folder"]: if self.config["use_name_folder"]:
name = component.get("TorrentManager")[torrent_id].get_status(["name"])["name"] name = component.get("TorrentManager")[event.torrent_id].get_status(["name"])["name"]
dest = os.path.join(dest, name) dest = os.path.join(dest, name)
# Create the destination folder if it doesn't exist # Create the destination folder if it doesn't exist
if not os.path.exists(dest): if not os.path.exists(dest):
try: try:
os.makedirs(dest) os.makedirs(dest)
except Exception, e: except Exception, e:
log.error("Error creating destination folder: %s", e) log.error("Error creating destination folder: %s", e)
return return
log.debug("Extracting to %s", dest) log.debug("Extracting to %s", dest)
def on_extract_success(result, torrent_id): def on_extract_success(result, torrent_id):
# XXX: Emit an event # XXX: Emit an event
log.debug("Extract was successful for %s", torrent_id) log.debug("Extract was successful for %s", torrent_id)
@ -124,8 +124,8 @@ class Core(CorePluginBase):
# Run the command and add some callbacks # Run the command and add some callbacks
d = getProcessValue(cmd[0], cmd[1].split() + [str(fp)], {}, str(dest)) d = getProcessValue(cmd[0], cmd[1].split() + [str(fp)], {}, str(dest))
d.addCallback(on_extract_success, torrent_id) d.addCallback(on_extract_success, event.torrent_id)
d.addErrback(on_extract_failed, torrent_id) d.addErrback(on_extract_failed, event.torrent_id)
@export @export
def set_config(self, config): def set_config(self, config):

View File

@ -53,12 +53,14 @@ class LowDiskSpaceEvent(DelugeEvent):
"""Triggered when the available space for a specific path is getting """Triggered when the available space for a specific path is getting
too low. too low.
""" """
__slots__ = ('percents_dict',)
def __init__(self, percents_dict): def __init__(self, percents_dict):
""" """
:param percents: dictionary of path keys with their respecive :param percents: dictionary of path keys with their respecive
occupation percentages. occupation percentages.
""" """
self._args = [percents_dict] self.percents_dict = percents_dict
DEFAULT_PREFS = { DEFAULT_PREFS = {
"enabled": False, "enabled": False,
@ -170,25 +172,25 @@ class Core(CorePluginBase):
free_percent = free_blocks * 100 / total_blocks free_percent = free_blocks * 100 / total_blocks
return free_percent return free_percent
def __custom_email_notification(self, ocupied_percents): def __custom_email_notification(self, event):
subject = _("Low Disk Space Warning") subject = _("Low Disk Space Warning")
message = _("You're running low on disk space:\n") message = _("You're running low on disk space:\n")
for path, ocupied_percent in ocupied_percents.iteritems(): for path, ocupied_percent in event.percents_dict.iteritems():
message += _(' %s%% ocupation in %s\n') % (ocupied_percent, path) message += _(' %s%% ocupation in %s\n') % (ocupied_percent, path)
# "\"%s\"%% space occupation on %s") % (ocupied_percent, path) # "\"%s\"%% space occupation on %s") % (ocupied_percent, path)
return subject, message return subject, message
def __on_plugin_enabled(self, plugin_name): def __on_plugin_enabled(self, event):
if plugin_name == 'Notifications': if event.plugin_name == 'Notifications':
component.get("CorePlugin.Notifications"). \ component.get("CorePlugin.Notifications"). \
register_custom_email_notification( register_custom_email_notification(
"LowDiskSpaceEvent", self.__custom_email_notification "LowDiskSpaceEvent", self.__custom_email_notification
) )
def __on_plugin_disabled(self, plugin_name): def __on_plugin_disabled(self, event):
if plugin_name == 'Notifications': if event.plugin_name == 'Notifications':
component.get("CorePlugin.Notifications"). \ component.get("CorePlugin.Notifications"). \
deregister_custom_email_notification("LowDiskSpaceEvent") deregister_custom_email_notification("LowDiskSpaceEvent")

View File

@ -132,22 +132,22 @@ class GtkUI(GtkPluginBase):
self.glade.get_widget('enabled').set_active(config['enabled']) self.glade.get_widget('enabled').set_active(config['enabled'])
self.glade.get_widget('percent').set_value(config['percent']) self.glade.get_widget('percent').set_value(config['percent'])
def __custom_popup_notification(self, ocupied_percents): def __custom_popup_notification(self, event):
title = _("Low Free Space") title = _("Low Free Space")
message = '' message = ''
for path, percent in ocupied_percents.iteritems(): for path, percent in event.percents_dict.iteritems():
message += '%s%% %s\n' % (percent, path) message += '%s%% %s\n' % (percent, path)
message += '\n' message += '\n'
return title, message return title, message
def __custom_blink_notification(self, ocupied_percents): def __custom_blink_notification(self, event):
return True # Yes, do blink return True # Yes, do blink
def __custom_sound_notification(self, ocupied_percents): def __custom_sound_notification(self, event):
return '' # Use default sound return '' # Use default sound
def __on_plugin_enabled(self, plugin_name): def __on_plugin_enabled(self, event):
if plugin_name == 'Notifications': if event.plugin_name == 'Notifications':
notifications = component.get("GtkPlugin.Notifications") notifications = component.get("GtkPlugin.Notifications")
notifications.register_custom_popup_notification( notifications.register_custom_popup_notification(
"LowDiskSpaceEvent", self.__custom_popup_notification "LowDiskSpaceEvent", self.__custom_popup_notification
@ -159,7 +159,7 @@ class GtkUI(GtkPluginBase):
"LowDiskSpaceEvent", self.__custom_sound_notification "LowDiskSpaceEvent", self.__custom_sound_notification
) )
def __on_plugin_disabled(self, plugin_name): def __on_plugin_disabled(self, event):
pass pass
# if plugin_name == 'Notifications': # if plugin_name == 'Notifications':
# notifications = component.get("GtkPlugin.Notifications") # notifications = component.get("GtkPlugin.Notifications")

View File

@ -131,20 +131,20 @@ class Core(CorePluginBase):
return dict( [(label, 0) for label in self.labels.keys()]) return dict( [(label, 0) for label in self.labels.keys()])
## Plugin hooks ## ## Plugin hooks ##
def post_torrent_add(self, torrent_id, from_state): def post_torrent_add(self, event):
log.debug("post_torrent_add") log.debug("post_torrent_add")
torrent = self.torrents[torrent_id] torrent = self.torrents[event.torrent_id]
for label_id, options in self.labels.iteritems(): for label_id, options in self.labels.iteritems():
if options["auto_add"]: if options["auto_add"]:
if self._has_auto_match(torrent, options): if self._has_auto_match(torrent, options):
self.set_torrent(torrent_id, label_id) self.set_torrent(event.torrent_id, label_id)
return return
def post_torrent_remove(self, torrent_id): def post_torrent_remove(self, event):
log.debug("post_torrent_remove") log.debug("post_torrent_remove")
if torrent_id in self.torrent_labels: if event.torrent_id in self.torrent_labels:
del self.torrent_labels[torrent_id] del self.torrent_labels[event.torrent_id]
## Utils ## ## Utils ##
def clean_config(self): def clean_config(self):

View File

@ -186,9 +186,9 @@ Subject: %(subject)s
return _("Notification email sent.") return _("Notification email sent.")
def _on_torrent_finished_event(self, torrent_id): def _on_torrent_finished_event(self, event):
log.debug("Handler for TorrentFinishedEvent called for CORE") log.debug("Handler for TorrentFinishedEvent called for CORE")
torrent = component.get("TorrentManager")[torrent_id] torrent = component.get("TorrentManager")[event.torrent_id]
torrent_status = torrent.get_status({}) torrent_status = torrent.get_status({})
# Email # Email
subject = _("Finished Torrent \"%(name)s\"") % torrent_status subject = _("Finished Torrent \"%(name)s\"") % torrent_status

View File

@ -74,11 +74,12 @@ class SchedulerEvent(DelugeEvent):
""" """
Emitted when a schedule state changes. Emitted when a schedule state changes.
""" """
__slots__ = ('colour',)
def __init__(self, colour): def __init__(self, colour):
""" """
:param colour: str, the current scheduler state :param colour: str, the current scheduler state
""" """
self._args = [colour] self.colour = colour
class Core(CorePluginBase): class Core(CorePluginBase):
def enable(self): def enable(self):
@ -117,8 +118,8 @@ class Core(CorePluginBase):
pass pass
def on_config_value_changed(self, key, value): def on_config_value_changed(self, event):
if key in CONTROLLED_SETTINGS: if event.key in CONTROLLED_SETTINGS:
self.do_schedule(False) self.do_schedule(False)
def __apply_set_functions(self): def __apply_set_functions(self):

View File

@ -201,9 +201,9 @@ class GtkUI(GtkPluginBase):
client.scheduler.get_config().addCallback(on_get_config) client.scheduler.get_config().addCallback(on_get_config)
def on_scheduler_event(self, state): def on_scheduler_event(self, event):
def on_state_deferred(s): def on_state_deferred(s):
self.status_item.set_image_from_file(get_resource(state.lower() + ".png")) self.status_item.set_image_from_file(get_resource(event.colour.lower() + ".png"))
self.state_deferred.addCallback(on_state_deferred) self.state_deferred.addCallback(on_state_deferred)

View File

@ -107,7 +107,7 @@ class EventLog(component.Component):
(event.key, color, event.value)) (event.key, color, event.value))
def on_plugin_enabled_event(self, event): def on_plugin_enabled_event(self, event):
self.console.write(self.prefix + "PluginEnabled: {!info!}%s" % event.name) self.console.write(self.prefix + "PluginEnabled: {!info!}%s" % event.plugin_name)
def on_plugin_disabled_event(self, event): def on_plugin_disabled_event(self, event):
self.console.write(self.prefix + "PluginDisabled: {!info!}%s" % event.name) self.console.write(self.prefix + "PluginDisabled: {!info!}%s" % event.plugin_name)

View File

@ -90,10 +90,10 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase,
self.enable_plugin(plugin) self.enable_plugin(plugin)
def _on_plugin_enabled_event(self, event): def _on_plugin_enabled_event(self, event):
self.enable_plugin(event.name) self.enable_plugin(event.plugin_name)
def _on_plugin_disabled_event(self, event): def _on_plugin_disabled_event(self, event):
self.disable_plugin(event.name) self.disable_plugin(event.plugin_name)
## Hook functions ## Hook functions
def run_on_show_prefs(self): def run_on_show_prefs(self):

View File

@ -73,10 +73,10 @@ class PluginManager(PluginManagerBase, component.Component):
self.enable_plugin(plugin) self.enable_plugin(plugin)
def _on_plugin_enabled_event(self, event): def _on_plugin_enabled_event(self, event):
self.enable_plugin(event.name) self.enable_plugin(event.plugin_name)
def _on_plugin_disabled_event(self, event): def _on_plugin_disabled_event(self, event):
self.disable_plugin(event.name) self.disable_plugin(event.plugin_name)
def disable_plugin(self, name): def disable_plugin(self, name):
# Get the plugin instance # Get the plugin instance