Autopep8 E265

This commit is contained in:
Calum Lind 2014-09-22 12:14:53 +01:00
parent 2f68092740
commit 142e96b246
49 changed files with 237 additions and 237 deletions

View File

@ -245,7 +245,7 @@ def open_url_in_browser(url):
import webbrowser import webbrowser
webbrowser.open(url) webbrowser.open(url)
## Formatting text functions # Formatting text functions
# For performance reasons these fsize units are translated outside the function # For performance reasons these fsize units are translated outside the function
byte_txt = "Bytes" byte_txt = "Bytes"
@ -617,7 +617,7 @@ def is_ip(ip):
""" """
import socket import socket
#first we test ipv4 # first we test ipv4
try: try:
if windows_check(): if windows_check():
if socket.inet_aton(ip): if socket.inet_aton(ip):
@ -628,7 +628,7 @@ def is_ip(ip):
except socket.error: except socket.error:
if not socket.has_ipv6: if not socket.has_ipv6:
return False return False
#now test ipv6 # now test ipv6
try: try:
if windows_check(): if windows_check():
log.warning("ipv6 check unavailable on windows") log.warning("ipv6 check unavailable on windows")

View File

@ -771,7 +771,7 @@ class Core(component.Component):
torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids) torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids)
torrent_moved = True torrent_moved = True
prev_queue_position = None prev_queue_position = None
#torrent_ids must be sorted before moving. # torrent_ids must be sorted before moving.
for queue_position, torrent_id in sorted(torrents): for queue_position, torrent_id in sorted(torrents):
# Move the torrent if and only if there is space (by not moving it we preserve the order) # Move the torrent if and only if there is space (by not moving it we preserve the order)
if torrent_moved or queue_position - prev_queue_position > 1: if torrent_moved or queue_position - prev_queue_position > 1:
@ -791,7 +791,7 @@ class Core(component.Component):
torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids) torrents = ((self.torrentmanager.get_queue_position(torrent_id), torrent_id) for torrent_id in torrent_ids)
torrent_moved = True torrent_moved = True
prev_queue_position = None prev_queue_position = None
#torrent_ids must be sorted before moving. # torrent_ids must be sorted before moving.
for queue_position, torrent_id in sorted(torrents, reverse=True): for queue_position, torrent_id in sorted(torrents, reverse=True):
# Move the torrent if and only if there is space (by not moving it we preserve the order) # Move the torrent if and only if there is space (by not moving it we preserve the order)
if torrent_moved or prev_queue_position - queue_position > 1: if torrent_moved or prev_queue_position - queue_position > 1:

View File

@ -1043,7 +1043,7 @@ class Torrent(object):
# If the torrent has already reached it's 'stop_seed_ratio' then do not do anything # If the torrent has already reached it's 'stop_seed_ratio' then do not do anything
if self.options["stop_at_ratio"]: if self.options["stop_at_ratio"]:
if self.get_ratio() >= self.options["stop_ratio"]: if self.get_ratio() >= self.options["stop_ratio"]:
#XXX: This should just be returned in the RPC Response, no event # XXX: This should just be returned in the RPC Response, no event
return return
if self.options["auto_managed"]: if self.options["auto_managed"]:

View File

@ -97,7 +97,7 @@ def make_meta_file(path, url, piece_length, progress=None, title=None, comment=N
info = makeinfo(path, piece_length, progress, name, content_type, private) info = makeinfo(path, piece_length, progress, name, content_type, private)
#check_info(info) # check_info(info)
h = file(f, 'wb') h = file(f, 'wb')
data['info'] = info data['info'] = info

View File

@ -81,7 +81,7 @@ def check_input(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.config.run_converter((0, 1), 2, self.__migrate_config_1_to_2) self.config.run_converter((0, 1), 2, self.__migrate_config_1_to_2)
self.config.save() self.config.save()
@ -104,7 +104,7 @@ class Core(CorePluginBase):
self.enable_watchdir(watchdir_id) self.enable_watchdir(watchdir_id)
def disable(self): def disable(self):
#disable all running looping calls # disable all running looping calls
component.get("EventManager").deregister_event_handler( component.get("EventManager").deregister_event_handler(
"PreTorrentRemovedEvent", self.__on_pre_torrent_removed "PreTorrentRemovedEvent", self.__on_pre_torrent_removed
) )
@ -135,12 +135,12 @@ class Core(CorePluginBase):
if key not in OPTIONS_AVAILABLE: if key not in OPTIONS_AVAILABLE:
if key not in [key2 + "_toggle" for key2 in OPTIONS_AVAILABLE.iterkeys()]: if key not in [key2 + "_toggle" for key2 in OPTIONS_AVAILABLE.iterkeys()]:
raise Exception("autoadd: Invalid options key:%s" % key) raise Exception("autoadd: Invalid options key:%s" % key)
#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()

View File

@ -57,12 +57,12 @@ class OptionsDialog():
self.dialog.set_transient_for(component.get("Preferences").pref_dialog) self.dialog.set_transient_for(component.get("Preferences").pref_dialog)
if watchdir_id: if watchdir_id:
#We have an existing watchdir_id, we are editing # We have an existing watchdir_id, we are editing
self.glade.get_widget('opts_add_button').hide() self.glade.get_widget('opts_add_button').hide()
self.glade.get_widget('opts_apply_button').show() self.glade.get_widget('opts_apply_button').show()
self.watchdir_id = watchdir_id self.watchdir_id = watchdir_id
else: else:
#We don't have an id, adding # We don't have an id, adding
self.glade.get_widget('opts_add_button').show() self.glade.get_widget('opts_add_button').show()
self.glade.get_widget('opts_apply_button').hide() self.glade.get_widget('opts_apply_button').hide()
self.watchdir_id = None self.watchdir_id = None
@ -439,7 +439,7 @@ class GtkUI(GtkPluginBase):
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):

View File

@ -37,8 +37,8 @@ if windows_check():
'C:\\Program Files (x86)\\7-Zip\\7z.exe', 'C:\\Program Files (x86)\\7-Zip\\7z.exe',
] ]
switch_7z = "x -y" switch_7z = "x -y"
## Future suport: # Future suport:
## 7-zip cannot extract tar.* with single command. # 7-zip cannot extract tar.* with single command.
# ".tar.gz", ".tgz", # ".tar.gz", ".tgz",
# ".tar.bz2", ".tbz", # ".tar.bz2", ".tbz",
# ".tar.lzma", ".tlz", # ".tar.lzma", ".tlz",
@ -53,9 +53,9 @@ if windows_check():
break break
else: else:
required_cmds = ["unrar", "unzip", "tar", "unxz", "unlzma", "7zr", "bunzip2"] required_cmds = ["unrar", "unzip", "tar", "unxz", "unlzma", "7zr", "bunzip2"]
## Possible future suport: # Possible future suport:
# gunzip: gz (cmd will delete original archive) # gunzip: gz (cmd will delete original archive)
## the following do not extract to dest dir # the following do not extract to dest dir
# ".xz": ["xz", "-d --keep"], # ".xz": ["xz", "-d --keep"],
# ".lzma": ["xz", "-d --format=lzma --keep"], # ".lzma": ["xz", "-d --format=lzma --keep"],
# ".bz2": ["bzip2", "-d --keep"], # ".bz2": ["bzip2", "-d --keep"],

View File

@ -82,7 +82,7 @@ class Core(CorePluginBase):
self.config = ConfigManager("label.conf", defaults=CONFIG_DEFAULTS) self.config = ConfigManager("label.conf", defaults=CONFIG_DEFAULTS)
self.core_cfg = ConfigManager("core.conf") self.core_cfg = ConfigManager("core.conf")
#reduce typing, assigning some values to self... # reduce typing, assigning some values to self...
self.torrents = core.torrentmanager.torrents self.torrents = core.torrentmanager.torrents
self.labels = self.config["labels"] self.labels = self.config["labels"]
self.torrent_labels = self.config["torrent_labels"] self.torrent_labels = self.config["torrent_labels"]
@ -92,7 +92,7 @@ class Core(CorePluginBase):
component.get("EventManager").register_event_handler("TorrentAddedEvent", self.post_torrent_add) component.get("EventManager").register_event_handler("TorrentAddedEvent", self.post_torrent_add)
component.get("EventManager").register_event_handler("TorrentRemovedEvent", self.post_torrent_remove) component.get("EventManager").register_event_handler("TorrentRemovedEvent", self.post_torrent_remove)
#register tree: # register tree:
component.get("FilterManager").register_tree_field("label", self.init_filter_dict) component.get("FilterManager").register_tree_field("label", self.init_filter_dict)
log.debug("Label plugin enabled..") log.debug("Label plugin enabled..")
@ -161,7 +161,7 @@ class Core(CorePluginBase):
def get_labels(self): def get_labels(self):
return sorted(self.labels.keys()) return sorted(self.labels.keys())
#Labels: # Labels:
@export @export
def add(self, label_id): def add(self, label_id):
"""add a label """add a label
@ -265,12 +265,12 @@ class Core(CorePluginBase):
self.labels[label_id].update(options_dict) self.labels[label_id].update(options_dict)
#apply # apply
for torrent_id, label in self.torrent_labels.iteritems(): for torrent_id, label in self.torrent_labels.iteritems():
if label_id == label and torrent_id in self.torrents: if label_id == label and torrent_id in self.torrents:
self._set_torrent_options(torrent_id, label_id) self._set_torrent_options(torrent_id, label_id)
#auto add # auto add
options = self.labels[label_id] options = self.labels[label_id]
if options["auto_add"]: if options["auto_add"]:
for torrent_id, torrent in self.torrents.iteritems(): for torrent_id, torrent in self.torrents.iteritems():

View File

@ -52,23 +52,23 @@ class GtkUI(GtkPluginBase):
log.debug(ex) log.debug(ex)
def load_interface(self): def load_interface(self):
#sidebar # sidebar
#disabled # disabled
if not self.sidebar_menu: if not self.sidebar_menu:
self.sidebar_menu = sidebar_menu.LabelSidebarMenu() self.sidebar_menu = sidebar_menu.LabelSidebarMenu()
#self.sidebar.load() # self.sidebar.load()
#menu: # menu:
log.debug("add items to torrentview-popup menu.") log.debug("add items to torrentview-popup menu.")
torrentmenu = component.get("MenuBar").torrentmenu torrentmenu = component.get("MenuBar").torrentmenu
self.label_menu = submenu.LabelMenu() self.label_menu = submenu.LabelMenu()
torrentmenu.append(self.label_menu) torrentmenu.append(self.label_menu)
self.label_menu.show_all() self.label_menu.show_all()
#columns: # columns:
self.load_columns() self.load_columns()
#config: # config:
if not self.labelcfg: if not self.labelcfg:
self.labelcfg = label_config.LabelConfig(self.plugin) self.labelcfg = label_config.LabelConfig(self.plugin)
self.labelcfg.load() self.labelcfg.load()

View File

@ -59,5 +59,5 @@ class LabelConfig(object):
def on_apply_prefs(self): def on_apply_prefs(self):
options = {} options = {}
#update options dict here. # update options dict here.
client.label.set_config(options) client.label.set_config(options)

View File

@ -21,7 +21,7 @@ log = logging.getLogger(__name__)
NO_LABEL = "No Label" NO_LABEL = "No Label"
#helpers: # helpers:
def get_resource(filename): def get_resource(filename):
import pkg_resources import pkg_resources
import os import os
@ -30,7 +30,7 @@ def get_resource(filename):
) )
#menu # menu
class LabelSidebarMenu(object): class LabelSidebarMenu(object):
def __init__(self): def __init__(self):
@ -38,7 +38,7 @@ class LabelSidebarMenu(object):
self.menu = self.treeview.menu self.menu = self.treeview.menu
self.items = [] self.items = []
#add items, in reverse order, because they are prepended. # add items, in reverse order, because they are prepended.
sep = gtk.SeparatorMenuItem() sep = gtk.SeparatorMenuItem()
self.items.append(sep) self.items.append(sep)
self.menu.prepend(sep) self.menu.prepend(sep)
@ -47,10 +47,10 @@ class LabelSidebarMenu(object):
self._add_item("add", _("_Add Label"), gtk.STOCK_ADD) self._add_item("add", _("_Add Label"), gtk.STOCK_ADD)
self.menu.show_all() self.menu.show_all()
#dialogs: # dialogs:
self.add_dialog = AddDialog() self.add_dialog = AddDialog()
self.options_dialog = OptionsDialog() self.options_dialog = OptionsDialog()
#hooks: # hooks:
self.menu.connect("show", self.on_show, None) self.menu.connect("show", self.on_show, None)
def _add_item(self, id, label, stock): def _add_item(self, id, label, stock):
@ -82,18 +82,18 @@ class LabelSidebarMenu(object):
cat = self.treeview.cat cat = self.treeview.cat
label = self.treeview.value label = self.treeview.value
if cat == "label" or (cat == "cat" and label == "label"): if cat == "label" or (cat == "cat" and label == "label"):
#is a label : show menu-items # is a label : show menu-items
for item in self.items: for item in self.items:
item.show() item.show()
#default items # default items
sensitive = ((label not in (NO_LABEL, None, "", "All")) and (cat != "cat")) sensitive = ((label not in (NO_LABEL, None, "", "All")) and (cat != "cat"))
for item in self.items: for item in self.items:
item.set_sensitive(sensitive) item.set_sensitive(sensitive)
#add is allways enabled. # add is allways enabled.
self.item_add.set_sensitive(True) self.item_add.set_sensitive(True)
else: else:
#not a label -->hide everything. # not a label -->hide everything.
for item in self.items: for item in self.items:
item.hide() item.hide()
@ -106,7 +106,7 @@ class LabelSidebarMenu(object):
self.items = [] self.items = []
#dialogs: # dialogs:
class AddDialog(object): class AddDialog(object):
def __init__(self): def __init__(self):
pass pass
@ -137,7 +137,7 @@ class OptionsDialog(object):
chk_ids = ["apply_max", "apply_queue", "stop_at_ratio", "apply_queue", "remove_at_ratio", chk_ids = ["apply_max", "apply_queue", "stop_at_ratio", "apply_queue", "remove_at_ratio",
"apply_move_completed", "move_completed", "is_auto_managed", "auto_add"] "apply_move_completed", "move_completed", "is_auto_managed", "auto_add"]
#list of tuples, because order matters when nesting. # list of tuples, because order matters when nesting.
sensitive_groups = [ sensitive_groups = [
("apply_max", ["max_download_speed", "max_upload_speed", "max_upload_slots", "max_connections"]), ("apply_max", ["max_download_speed", "max_upload_speed", "max_upload_slots", "max_connections"]),
("apply_queue", ["is_auto_managed", "stop_at_ratio"]), ("apply_queue", ["is_auto_managed", "stop_at_ratio"]),

View File

@ -33,7 +33,7 @@ class LabelMenu(gtk.MenuItem):
self.set_submenu(self.sub_menu) self.set_submenu(self.sub_menu)
self.items = [] self.items = []
#attach.. # attach..
component.get("MenuBar").torrentmenu component.get("MenuBar").torrentmenu
self.sub_menu.connect("show", self.on_show, None) self.sub_menu.connect("show", self.on_show, None)

View File

@ -18,12 +18,12 @@ sclient.set_core_uri()
print(sclient.get_enabled_plugins()) print(sclient.get_enabled_plugins())
#enable plugin. # enable plugin.
if not "label" in sclient.get_enabled_plugins(): if not "label" in sclient.get_enabled_plugins():
sclient.enable_plugin("label") sclient.enable_plugin("label")
#test labels. # test labels.
print("#init labels") print("#init labels")
try: try:
sclient.label_remove("test") sclient.label_remove("test")

View File

@ -56,7 +56,7 @@ class SchedulerSelectWidget(gtk.DrawingArea):
self.button_state.append(list(s)) self.button_state.append(list(s))
log.debug(self.button_state) log.debug(self.button_state)
#redraw the whole thing # redraw the whole thing
def expose(self, widget, event): def expose(self, widget, event):
self.context = self.window.cairo_create() self.context = self.window.cairo_create()
self.context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) self.context.rectangle(event.area.x, event.area.y, event.area.width, event.area.height)
@ -76,7 +76,7 @@ class SchedulerSelectWidget(gtk.DrawingArea):
self.context.set_source_rgba(0.5, 0.5, 0.5, 0.5) self.context.set_source_rgba(0.5, 0.5, 0.5, 0.5)
self.context.stroke() self.context.stroke()
#coordinates --> which box # coordinates --> which box
def get_point(self, event): def get_point(self, event):
size = self.window.get_size() size = self.window.get_size()
x = int((event.x - size[0] * 0.5 / 145.0) / (6 * size[0] / 145.0)) x = int((event.x - size[0] * 0.5 / 145.0) / (6 * size[0] / 145.0))
@ -93,17 +93,17 @@ class SchedulerSelectWidget(gtk.DrawingArea):
return [x, y] return [x, y]
#mouse down # mouse down
def mouse_down(self, widget, event): def mouse_down(self, widget, event):
self.mouse_press = True self.mouse_press = True
self.start_point = self.get_point(event) self.start_point = self.get_point(event)
#if the same box -> change it # if the same box -> change it
def mouse_up(self, widget, event): def mouse_up(self, widget, event):
self.mouse_press = False self.mouse_press = False
end_point = self.get_point(event) end_point = self.get_point(event)
#change color on mouseclick depending on the button # change color on mouseclick depending on the button
if end_point[0] is self.start_point[0] and end_point[1] is self.start_point[1]: if end_point[0] is self.start_point[0] and end_point[1] is self.start_point[1]:
if event.button == 1: if event.button == 1:
self.button_state[end_point[0]][end_point[1]] += 1 self.button_state[end_point[0]][end_point[1]] += 1
@ -115,8 +115,8 @@ class SchedulerSelectWidget(gtk.DrawingArea):
self.button_state[end_point[0]][end_point[1]] = 2 self.button_state[end_point[0]][end_point[1]] = 2
self.queue_draw() self.queue_draw()
#if box changed and mouse is pressed draw all boxes from start point to end point # if box changed and mouse is pressed draw all boxes from start point to end point
#set hover text etc.. # set hover text etc..
def mouse_hover(self, widget, event): def mouse_hover(self, widget, event):
if self.get_point(event) != self.hover_point: if self.get_point(event) != self.hover_point:
self.hover_point = self.get_point(event) self.hover_point = self.get_point(event)
@ -133,7 +133,7 @@ class SchedulerSelectWidget(gtk.DrawingArea):
self.queue_draw() self.queue_draw()
#clear hover text on mouse leave # clear hover text on mouse leave
def mouse_leave(self, widget, event): def mouse_leave(self, widget, event):
self.hover_label.set_text("") self.hover_label.set_text("")
self.hover_point = [-1, -1] self.hover_point = [-1, -1]
@ -199,9 +199,9 @@ class GtkUI(GtkPluginBase):
def on_status_item_clicked(self, widget, event): def on_status_item_clicked(self, widget, event):
component.get("Preferences").show("Scheduler") component.get("Preferences").show("Scheduler")
#Configuration dialog # Configuration dialog
def create_prefs_page(self): def create_prefs_page(self):
#Select Widget # Select Widget
hover = gtk.Label() hover = gtk.Label()
self.scheduler_select = SchedulerSelectWidget(hover) self.scheduler_select = SchedulerSelectWidget(hover)

View File

@ -113,11 +113,11 @@ class Core(CorePluginBase):
def update_stats(self): def update_stats(self):
try: try:
#Get all possible stats! # Get all possible stats!
stats = {} stats = {}
for key in self.stats_keys: for key in self.stats_keys:
#try all keys we have, very inefficient but saves having to # try all keys we have, very inefficient but saves having to
#work out where a key comes from... # work out where a key comes from...
try: try:
stats.update(self.core.get_session_status([key])) stats.update(self.core.get_session_status([key]))
except AttributeError: except AttributeError:
@ -134,8 +134,8 @@ class Core(CorePluginBase):
update_time = time.time() update_time = time.time()
self.last_update[1] = update_time self.last_update[1] = update_time
#extract the ones we are interested in # extract the ones we are interested in
#adding them to the 1s array # adding them to the 1s array
for stat, stat_list in self.stats[1].iteritems(): for stat, stat_list in self.stats[1].iteritems():
if stat in stats: if stat in stats:
stat_list.insert(0, int(stats[stat])) stat_list.insert(0, int(stats[stat]))

View File

@ -121,7 +121,7 @@ class Graph:
ratio = (right - left) / float(duration) ratio = (right - left) / float(duration)
if duration < 1800 * 10: if duration < 1800 * 10:
#try rounding to nearest 1min, 5mins, 10mins, 30mins # try rounding to nearest 1min, 5mins, 10mins, 30mins
for step in [60, 300, 600, 1800]: for step in [60, 300, 600, 1800]:
if duration / step < 10: if duration / step < 10:
x_step = step x_step = step
@ -130,7 +130,7 @@ class Graph:
# if there wasnt anything useful find a nice fitting hourly divisor # if there wasnt anything useful find a nice fitting hourly divisor
x_step = ((duration / 5) / 3600) * 3600 x_step = ((duration / 5) / 3600) * 3600
#this doesnt allow for dst and timezones... # this doesnt allow for dst and timezones...
seconds_to_step = math.ceil(start / float(x_step)) * x_step - start seconds_to_step = math.ceil(start / float(x_step)) * x_step - start
for i in xrange(0, duration / x_step + 1): for i in xrange(0, duration / x_step + 1):
@ -146,7 +146,7 @@ class Graph:
font_extents = self.ctx.font_extents() font_extents = self.ctx.font_extents()
x_axis_space = font_extents[2] + 2 + self.line_size / 2.0 x_axis_space = font_extents[2] + 2 + self.line_size / 2.0
plot_height = self.height - x_axis_space plot_height = self.height - x_axis_space
#lets say we need 2n-1*font height pixels to plot the y ticks # lets say we need 2n-1*font height pixels to plot the y ticks
tick_limit = (plot_height / font_extents[3]) # / 2.0 tick_limit = (plot_height / font_extents[3]) # / 2.0
max_value = 0 max_value = 0
@ -163,7 +163,7 @@ class Graph:
y_ticks = self.intervalise(max_value, tick_limit) y_ticks = self.intervalise(max_value, tick_limit)
max_value = y_ticks[-1] max_value = y_ticks[-1]
#find the width of the y_ticks # find the width of the y_ticks
y_tick_text = [self.left_axis['formatter'](tick) for tick in y_ticks] y_tick_text = [self.left_axis['formatter'](tick) for tick in y_ticks]
def space_required(text): def space_required(text):
@ -182,8 +182,8 @@ class Graph:
"""Given a value x create an array of tick points to got with the graph """Given a value x create an array of tick points to got with the graph
The number of ticks returned can be constrained by limit, minimum of 3 The number of ticks returned can be constrained by limit, minimum of 3
""" """
#Limit is the number of ticks which is 1 + the number of steps as we # Limit is the number of ticks which is 1 + the number of steps as we
#count the 0 tick in limit # count the 0 tick in limit
if limit is not None: if limit is not None:
if limit < 3: if limit < 3:
limit = 2 limit = 2
@ -194,7 +194,7 @@ class Graph:
scale = self.left_axis['formatter_scale'](x) scale = self.left_axis['formatter_scale'](x)
x = x / float(scale) x = x / float(scale)
#Find the largest power of 10 less than x # Find the largest power of 10 less than x
log = math.log10(x) log = math.log10(x)
intbit = math.floor(log) intbit = math.floor(log)

View File

@ -122,7 +122,7 @@ class GraphsTab(Tab):
self.graph.draw_to_context(context, self.graph.draw_to_context(context,
self.graph_widget.allocation.width, self.graph_widget.allocation.width,
self.graph_widget.allocation.height) self.graph_widget.allocation.height)
#Do not propagate the event # Do not propagate the event
return False return False
def update(self): def update(self):
@ -188,7 +188,7 @@ class GraphsTab(Tab):
current = intervals.index(self.selected_interval) current = intervals.index(self.selected_interval)
except: except:
current = 0 current = 0
#should select the value saved in config # should select the value saved in config
self.intervals_combo.set_active(current) self.intervals_combo.set_active(current)
def _on_selected_interval_changed(self, combobox): def _on_selected_interval_changed(self, combobox):

View File

@ -100,7 +100,7 @@ def test_write():
f.write(data) f.write(data)
f.close() f.close()
#test_sync() # test_sync()
test_async() test_async()
test_dht() test_dht()
#test_write() # test_write()

View File

@ -110,7 +110,7 @@ def create_plugin():
write_file(data_dir, "config.glade", GLADE) write_file(data_dir, "config.glade", GLADE)
write_file(data_dir, "%s.js" % safe_name, DEFAULT_JS) write_file(data_dir, "%s.js" % safe_name, DEFAULT_JS)
#add an input parameter for this? # add an input parameter for this?
print("building dev-link..") print("building dev-link..")
write_file(plugin_base, "create_dev_link.sh", CREATE_DEV_LINK) write_file(plugin_base, "create_dev_link.sh", CREATE_DEV_LINK)
dev_link_path = os.path.join(plugin_base, "create_dev_link.sh") dev_link_path = os.path.join(plugin_base, "create_dev_link.sh")

View File

@ -9,8 +9,8 @@
# #
# #
#generate docs for deluge-wiki # generate docs for deluge-wiki
#client doc's For core. # client doc's For core.
# #
from __future__ import print_function from __future__ import print_function

View File

@ -112,7 +112,7 @@ class TorrentTestCase(unittest.TestCase):
# The length of the list of new priorites is the same as the original # The length of the list of new priorites is the same as the original
self.assertEquals(len(priorities_original), len(new_priorites)) self.assertEquals(len(priorities_original), len(new_priorites))
#self.print_priority_list(priorities) # self.print_priority_list(priorities)
def test_set_prioritize_first_last_pieces_false(self): def test_set_prioritize_first_last_pieces_false(self):
atp = self.get_torrent_atp("dir_with_6_files.torrent") atp = self.get_torrent_atp("dir_with_6_files.torrent")
@ -128,4 +128,4 @@ class TorrentTestCase(unittest.TestCase):
for i in priorities: for i in priorities:
self.assertEquals(priorities[i], 1) self.assertEquals(priorities[i], 1)
#self.print_priority_list(priorities) # self.print_priority_list(priorities)

View File

@ -306,7 +306,7 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
self.assertEquals(rencode.dumps(self.msg2), rencode.dumps(message2)) self.assertEquals(rencode.dumps(self.msg2), rencode.dumps(message2))
# Needs file containing big data structure e.g. like thetorrent list as it is transfered by the daemon # Needs file containing big data structure e.g. like thetorrent list as it is transfered by the daemon
#def test_simulate_big_transfer(self): # def test_simulate_big_transfer(self):
# filename = "../deluge.torrentlist" # filename = "../deluge.torrentlist"
# #
# f = open(filename, "r") # f = open(filename, "r")
@ -314,7 +314,7 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
# message_to_send = eval(data) # message_to_send = eval(data)
# self.transfer.transfer_message(message_to_send) # self.transfer.transfer_message(message_to_send)
# #
# # Get the data as sent to the network by DelugeTransferProtocol # Get the data as sent to the network by DelugeTransferProtocol
# compressed_data = self.transfer.get_messages_out_joined() # compressed_data = self.transfer.get_messages_out_joined()
# packet_size = 16000 # Or something smaller... # packet_size = 16000 # Or something smaller...
# #
@ -324,16 +324,16 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
# self.assertEquals(len(self.transfer.get_messages_in()), 0) # self.assertEquals(len(self.transfer.get_messages_in()), 0)
# else: # else:
# self.assertEquals(len(self.transfer.get_messages_in()), 1) # self.assertEquals(len(self.transfer.get_messages_in()), 1)
# # Get the data as received by DelugeTransferProtocol # Get the data as received by DelugeTransferProtocol
# transfered_message = self.transfer.get_messages_in().pop(0) # transfered_message = self.transfer.get_messages_in().pop(0)
# # Test that the data structures are equal # Test that the data structures are equal
# #self.assertEquals(transfered_message, message_to_send) # self.assertEquals(transfered_message, message_to_send)
# #self.assertTrue(transfered_message == message_to_send) # self.assertTrue(transfered_message == message_to_send)
# #
# #f.close() # f.close()
# #f = open("rencode.torrentlist", "w") # f = open("rencode.torrentlist", "w")
# #f.write(str(transfered_message)) # f.write(str(transfered_message))
# #f.close() # f.close()
def receive_parts_helper(self, data, packet_size, receive_func=None): def receive_parts_helper(self, data, packet_size, receive_func=None):
byte_count = len(data) byte_count = len(data)

View File

@ -84,7 +84,7 @@ class Win32IcoFile(object):
icon_header['color_depth'] = (icon_header['bpp'] or (icon_header['nb_color'] == 16 and 4)) icon_header['color_depth'] = (icon_header['bpp'] or (icon_header['nb_color'] == 16 and 4))
icon_header['dim'] = (icon_header['width'], icon_header['height']) icon_header['dim'] = (icon_header['width'], icon_header['height'])
self.entry.append(icon_header) self.entry.append(icon_header)
#end for (read headers) # end for (read headers)
# order by size and color depth # order by size and color depth
self.entry.sort(lambda x, y: cmp(x['width'], y['width']) self.entry.sort(lambda x, y: cmp(x['width'], y['width'])
@ -144,7 +144,7 @@ class Win32IcoFile(object):
if mode == PIL.BmpImagePlugin.BIT2MODE[k][1]: if mode == PIL.BmpImagePlugin.BIT2MODE[k][1]:
bpp = k bpp = k
break break
#end for # end for
log.debug("o:%s, w:%s, h:%s, bpp:%s", o, im.size[0], im.size[1], bpp) log.debug("o:%s, w:%s, h:%s, bpp:%s", o, im.size[0], im.size[1], bpp)
and_mask_offset = o + (im.size[0] * im.size[1] * (bpp / 8.0)) and_mask_offset = o + (im.size[0] * im.size[1] * (bpp / 8.0))
@ -199,18 +199,18 @@ class Win32IcoFile(object):
im = im.convert('RGBA') im = im.convert('RGBA')
im.putalpha(mask) im.putalpha(mask)
log.debug("image mode: %s", im.mode) log.debug("image mode: %s", im.mode)
#end if !'RGBA' # end if !'RGBA'
#end if (png)/else(bmp) # end if (png)/else(bmp)
return im return im
#end frame # end frame
def __repr__(self): def __repr__(self):
s = 'Microsoft Icon: %d images (max %dx%d %dbpp)' % ( s = 'Microsoft Icon: %d images (max %dx%d %dbpp)' % (
len(self.entry), self.entry[0]['width'], self.entry[0]['height'], len(self.entry), self.entry[0]['width'], self.entry[0]['height'],
self.entry[0]['bpp']) self.entry[0]['bpp'])
return s return s
#end Win32IcoFile # end Win32IcoFile
class Win32IconImageFile (PIL.ImageFile.ImageFile): class Win32IconImageFile (PIL.ImageFile.ImageFile):
@ -242,7 +242,7 @@ class Win32IconImageFile (PIL.ImageFile.ImageFile):
self.im = im.im self.im = im.im
self.mode = im.mode self.mode = im.mode
self.size = im.size self.size = im.size
#end class Win32IconImageFile # end class Win32IconImageFile
def _accept(prefix): def _accept(prefix):
@ -250,7 +250,7 @@ def _accept(prefix):
Quick file test helper for Image.open() Quick file test helper for Image.open()
""" """
return prefix[:4] == _MAGIC return prefix[:4] == _MAGIC
#end _accept # end _accept
# register our decoder with PIL # register our decoder with PIL

View File

@ -206,12 +206,12 @@ class Command(BaseCommand):
col_filename = unicode(col_filename, "utf-8") col_filename = unicode(col_filename, "utf-8")
col_all_info = col_size + col_progress + col_priority col_all_info = col_size + col_progress + col_priority
#Check how much space we've got left after writing all the info # Check how much space we've got left after writing all the info
space_left = cols - tlen(col_all_info) space_left = cols - tlen(col_all_info)
#And how much we will potentially have with the longest possible column # And how much we will potentially have with the longest possible column
maxlen_space_left = cols - tlen(" (1000.0 MiB) 100.00% Priority: Do Not Download") maxlen_space_left = cols - tlen(" (1000.0 MiB) 100.00% Priority: Do Not Download")
if maxlen_space_left > tlen(col_filename) + 1: if maxlen_space_left > tlen(col_filename) + 1:
#If there is enough space, pad it all nicely # If there is enough space, pad it all nicely
col_all_info = "" col_all_info = ""
col_all_info += " (" col_all_info += " ("
spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size) spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size)
@ -223,13 +223,13 @@ class Command(BaseCommand):
spaces_to_add = tlen(" Priority: Do Not Download") - tlen(col_priority) spaces_to_add = tlen(" Priority: Do Not Download") - tlen(col_priority)
col_all_info += col_priority col_all_info += col_priority
col_all_info += " " * spaces_to_add col_all_info += " " * spaces_to_add
#And remember to put it to the left! # And remember to put it to the left!
col_filename = format_utils.pad_string(col_filename, maxlen_space_left - 2, side="right") col_filename = format_utils.pad_string(col_filename, maxlen_space_left - 2, side="right")
elif space_left > tlen(col_filename) + 1: elif space_left > tlen(col_filename) + 1:
#If there is enough space, put the info to the right # If there is enough space, put the info to the right
col_filename = format_utils.pad_string(col_filename, space_left - 2, side="right") col_filename = format_utils.pad_string(col_filename, space_left - 2, side="right")
else: else:
#And if there is not, shorten the name # And if there is not, shorten the name
col_filename = format_utils.trim_string(col_filename, space_left, True) col_filename = format_utils.trim_string(col_filename, space_left, True)
self.console.write(col_filename + col_all_info) self.console.write(col_filename + col_all_info)
@ -348,15 +348,15 @@ class Command(BaseCommand):
s += " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ") s += " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ")
s += " {!input!}%s" % (status["name"]) s += " {!input!}%s" % (status["name"])
#Shorten the ID if it's necessary. Pretty hacky # Shorten the ID if it's necessary. Pretty hacky
#I _REALLY_ should make a nice function for it that can partition and shorten stuff # I _REALLY_ should make a nice function for it that can partition and shorten stuff
space_left = cols - strwidth("[s] 100.00% " + status["name"] + " " * 3) - 2 space_left = cols - strwidth("[s] 100.00% " + status["name"] + " " * 3) - 2
if space_left >= len(torrent_id) - 2: if space_left >= len(torrent_id) - 2:
#There's enough space, print it # There's enough space, print it
s += " {!cyan!}%s" % torrent_id s += " {!cyan!}%s" % torrent_id
else: else:
#Shorten the ID # Shorten the ID
a = int(space_left * 2 / 3.0) a = int(space_left * 2 / 3.0)
b = space_left - a b = space_left - a
if a < 8: if a < 8:
@ -366,10 +366,10 @@ class Command(BaseCommand):
a += b a += b
b = 0 b = 0
if a > 8: if a > 8:
#Print the shortened ID # Print the shortened ID
s += " {!cyan!}%s" % (torrent_id[0:a] + ".." + torrent_id[-b - 1:-1]) s += " {!cyan!}%s" % (torrent_id[0:a] + ".." + torrent_id[-b - 1:-1])
else: else:
#It has wrapped over to the second row anyway # It has wrapped over to the second row anyway
s += " {!cyan!}%s" % torrent_id s += " {!cyan!}%s" % torrent_id
self.console.write(s) self.console.write(s)

View File

@ -54,7 +54,7 @@ class Command(BaseCommand):
# This is a correct path, check to see if it's a directory # This is a correct path, check to see if it's a directory
if os.path.isdir(line): if os.path.isdir(line):
# Directory, so we need to show contents of directory # Directory, so we need to show contents of directory
#ret.extend(os.listdir(line)) # ret.extend(os.listdir(line))
for f in os.listdir(line): for f in os.listdir(line):
# Skip hidden # Skip hidden
if f.startswith("."): if f.startswith("."):

View File

@ -49,7 +49,7 @@ class EventLog(component.Component):
self.write("{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})" % ( self.write("{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})" % (
status["name"], torrent_id) status["name"], torrent_id)
) )
#Write out what state the added torrent took # Write out what state the added torrent took
self.on_torrent_state_changed_event(torrent_id, status["state"]) self.on_torrent_state_changed_event(torrent_id, status["state"])
client.core.get_torrent_status(torrent_id, ["name", "state"]).addCallback(on_torrent_status) client.core.get_torrent_status(torrent_id, ["name", "state"]).addCallback(on_torrent_status)
@ -59,7 +59,7 @@ class EventLog(component.Component):
(self.console.get_torrent_name(torrent_id), torrent_id)) (self.console.get_torrent_name(torrent_id), torrent_id))
def on_torrent_state_changed_event(self, torrent_id, state): def on_torrent_state_changed_event(self, torrent_id, state):
#It's probably a new torrent, ignore it # It's probably a new torrent, ignore it
if not state: if not state:
return return
# Modify the state string color # Modify the state string color
@ -68,7 +68,7 @@ class EventLog(component.Component):
t_name = self.console.get_torrent_name(torrent_id) t_name = self.console.get_torrent_name(torrent_id)
#Again, it's most likely a new torrent # Again, it's most likely a new torrent
if not t_name: if not t_name:
return return

View File

@ -143,7 +143,7 @@ class AddTorrents(BaseMode, component.Component):
self.raw_rows.append(row) self.raw_rows.append(row)
self.raw_rows_dirs.append(row) self.raw_rows_dirs.append(row)
#Highlight the directory we came from # Highlight the directory we came from
if self.path_stack_pos < len(self.path_stack): if self.path_stack_pos < len(self.path_stack):
selected = self.path_stack[self.path_stack_pos] selected = self.path_stack[self.path_stack_pos]
ld = sorted(self.listing_dirs, key=lambda n: n.lower()) ld = sorted(self.listing_dirs, key=lambda n: n.lower())
@ -204,7 +204,7 @@ class AddTorrents(BaseMode, component.Component):
widths = [self.cols - 35, 12, 23] widths = [self.cols - 35, 12, 23]
self.formatted_rows.append(format_utils.format_row(cols, widths)) self.formatted_rows.append(format_utils.format_row(cols, widths))
else: else:
#Size of .torrent file itself couldn't matter less so we'll leave it out # Size of .torrent file itself couldn't matter less so we'll leave it out
try: try:
filename = filename.decode("utf8") filename = filename.decode("utf8")
except: except:
@ -236,7 +236,7 @@ class AddTorrents(BaseMode, component.Component):
def on_resize(self, *args): def on_resize(self, *args):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
#Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out # Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out
legacy = component.get("LegacyUI") legacy = component.get("LegacyUI")
legacy.on_resize(*args) legacy.on_resize(*args)
@ -253,7 +253,7 @@ class AddTorrents(BaseMode, component.Component):
self.stdscr.erase() self.stdscr.erase()
self.add_string(0, self.statusbars.topbar) self.add_string(0, self.statusbars.topbar)
#This will quite likely fail when switching modes # This will quite likely fail when switching modes
try: try:
rf = format_utils.remove_formatting rf = format_utils.remove_formatting
string = self.statusbars.bottombar string = self.statusbars.bottombar
@ -267,7 +267,7 @@ class AddTorrents(BaseMode, component.Component):
off = 1 off = 1
#Render breadcrumbs # Render breadcrumbs
s = "Location: " s = "Location: "
for i, e in enumerate(self.path_stack): for i, e in enumerate(self.path_stack):
if e == "/": if e == "/":
@ -287,7 +287,7 @@ class AddTorrents(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Render header # Render header
cols = ["Name", "Contents", "Modification time"] cols = ["Name", "Contents", "Modification time"]
widths = [self.cols - 35, 12, 23] widths = [self.cols - 35, 12, 23]
s = "" s = ""
@ -309,10 +309,10 @@ class AddTorrents(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Render files and folders # Render files and folders
for i, row in enumerate(self.formatted_rows[self.view_offset:]): for i, row in enumerate(self.formatted_rows[self.view_offset:]):
i += self.view_offset i += self.view_offset
#It's a folder # It's a folder
color_string = "" color_string = ""
if self.raw_rows[i][4]: if self.raw_rows[i][4]:
if self.raw_rows[i][1] == -1: if self.raw_rows[i][1] == -1:
@ -369,7 +369,7 @@ class AddTorrents(BaseMode, component.Component):
self._show_add_dialog() self._show_add_dialog()
def _enter_dir(self): def _enter_dir(self):
#Enter currently selected directory # Enter currently selected directory
dirname = self.raw_rows[self.cursel][0] dirname = self.raw_rows[self.cursel][0]
new_dir = self.path_stack_pos >= len(self.path_stack) new_dir = self.path_stack_pos >= len(self.path_stack)
new_dir = new_dir or (dirname != self.path_stack[self.path_stack_pos]) new_dir = new_dir or (dirname != self.path_stack[self.path_stack_pos])
@ -457,7 +457,7 @@ class AddTorrents(BaseMode, component.Component):
self.popup.add_select_input("Add Paused:", "add_paused", ["Yes", "No"], [True, False], ap) self.popup.add_select_input("Add Paused:", "add_paused", ["Yes", "No"], [True, False], ap)
def _go_up(self): def _go_up(self):
#Go up in directory hierarchy # Go up in directory hierarchy
if self.path_stack_pos > 1: if self.path_stack_pos > 1:
self.path_stack_pos -= 1 self.path_stack_pos -= 1
@ -495,14 +495,14 @@ class AddTorrents(BaseMode, component.Component):
if c == curses.KEY_UP: if c == curses.KEY_UP:
self.scroll_list_up(1) self.scroll_list_up(1)
elif c == curses.KEY_PPAGE: elif c == curses.KEY_PPAGE:
#self.scroll_list_up(self._listing_space-2) # self.scroll_list_up(self._listing_space-2)
self.scroll_list_up(self.rows // 2) self.scroll_list_up(self.rows // 2)
elif c == curses.KEY_HOME: elif c == curses.KEY_HOME:
self.scroll_list_up(len(self.formatted_rows)) self.scroll_list_up(len(self.formatted_rows))
elif c == curses.KEY_DOWN: elif c == curses.KEY_DOWN:
self.scroll_list_down(1) self.scroll_list_down(1)
elif c == curses.KEY_NPAGE: elif c == curses.KEY_NPAGE:
#self.scroll_list_down(self._listing_space-2) # self.scroll_list_down(self._listing_space-2)
self.scroll_list_down(self.rows // 2) self.scroll_list_down(self.rows // 2)
elif c == curses.KEY_END: elif c == curses.KEY_END:
self.scroll_list_down(len(self.formatted_rows)) self.scroll_list_down(len(self.formatted_rows))
@ -514,7 +514,7 @@ class AddTorrents(BaseMode, component.Component):
# Enter Key # Enter Key
elif c == curses.KEY_ENTER or c == 10: elif c == curses.KEY_ENTER or c == 10:
self._perform_action() self._perform_action()
#Escape # Escape
elif c == 27: elif c == 27:
self.back_to_overview() self.back_to_overview()
else: else:

View File

@ -411,7 +411,7 @@ class AllTorrents(BaseMode, component.Component):
ccol = column ccol = column
width = self.column_widths[i] width = self.column_widths[i]
#Trim the column if it's too long to fit # Trim the column if it's too long to fit
if len(ccol) > width: if len(ccol) > width:
ccol = ccol[:width - 1] ccol = ccol[:width - 1]
@ -538,7 +538,7 @@ class AllTorrents(BaseMode, component.Component):
result = state result = state
#Sort first by secondary sort field and then primary sort field # Sort first by secondary sort field and then primary sort field
# so it all works out # so it all works out
cmp_func = self._queue_sort cmp_func = self._queue_sort
@ -551,7 +551,7 @@ class AllTorrents(BaseMode, component.Component):
reverse = field in reverse_sort_fields reverse = field in reverse_sort_fields
#Get first element so we can check if it has given field # Get first element so we can check if it has given field
# and if it's a string # and if it's a string
first_element = state[state.keys()[0]] first_element = state[state.keys()[0]]
if field in first_element: if field in first_element:
@ -560,7 +560,7 @@ class AllTorrents(BaseMode, component.Component):
sort_key = lambda s: sg(s)[field] sort_key = lambda s: sg(s)[field]
sort_key2 = lambda s: sg(s)[field].lower() sort_key2 = lambda s: sg(s)[field].lower()
#If it's a string, sort case-insensitively but preserve A>a order # If it's a string, sort case-insensitively but preserve A>a order
if is_string: if is_string:
result = sorted(result, cmp_func, sort_key, reverse) result = sorted(result, cmp_func, sort_key, reverse)
result = sorted(result, cmp_func, sort_key2, reverse) result = sorted(result, cmp_func, sort_key2, reverse)
@ -572,7 +572,7 @@ class AllTorrents(BaseMode, component.Component):
return result return result
#Just in case primary and secondary fields are empty and/or # Just in case primary and secondary fields are empty and/or
# both are too ambiguous, also sort by queue position first # both are too ambiguous, also sort by queue position first
if "queue" not in [s_secondary, s_primary]: if "queue" not in [s_secondary, s_primary]:
result = sort_by_field(state, result, "queue") result = sort_by_field(state, result, "queue")
@ -809,9 +809,9 @@ class AllTorrents(BaseMode, component.Component):
self.refresh() self.refresh()
def refresh(self, lines=None): def refresh(self, lines=None):
#log.error("ref") # log.error("ref")
#import traceback #import traceback
#traceback.print_stack() # traceback.print_stack()
# Something has requested we scroll to the top of the list # Something has requested we scroll to the top of the list
if self._go_top: if self._go_top:
self.cursel = 1 self.cursel = 1
@ -847,7 +847,7 @@ class AllTorrents(BaseMode, component.Component):
self.add_string(self.rows - 1, string) self.add_string(self.rows - 1, string)
else: else:
#This will quite likely fail when switching modes # This will quite likely fail when switching modes
try: try:
rf = format_utils.remove_formatting rf = format_utils.remove_formatting
string = self.statusbars.bottombar string = self.statusbars.bottombar
@ -867,7 +867,7 @@ class AllTorrents(BaseMode, component.Component):
tidx = self.curoff tidx = self.curoff
currow = 2 currow = 2
#Because dots are slow # Because dots are slow
sorted_ids = self._sorted_ids sorted_ids = self._sorted_ids
curstate = self.curstate curstate = self.curstate
gcv = deluge.ui.console.modes.column.get_column_value gcv = deluge.ui.console.modes.column.get_column_value
@ -956,7 +956,7 @@ class AllTorrents(BaseMode, component.Component):
try: try:
self.add_string(currow, "%s%s" % (colorstr, row[0]), trim=False) self.add_string(currow, "%s%s" % (colorstr, row[0]), trim=False)
except: except:
#Yeah, this should be fixed in some better way # Yeah, this should be fixed in some better way
pass pass
tidx += 1 tidx += 1
currow += 1 currow += 1
@ -965,7 +965,7 @@ class AllTorrents(BaseMode, component.Component):
else: else:
self.add_string(1, "Waiting for torrents from core...") self.add_string(1, "Waiting for torrents from core...")
#self.stdscr.redrawwin() # self.stdscr.redrawwin()
if self.entering_search: if self.entering_search:
curses.curs_set(2) curses.curs_set(2)
self.stdscr.move(self.rows - 1, len(self.search_string) + 17) self.stdscr.move(self.rows - 1, len(self.search_string) + 17)

View File

@ -36,7 +36,7 @@ class EventView(BaseMode):
self.add_string(0, self.statusbars.topbar) self.add_string(0, self.statusbars.topbar)
hstr = "%sPress [h] for help" % (" " * (self.cols - len(self.statusbars.bottombar) - 10)) hstr = "%sPress [h] for help" % (" " * (self.cols - len(self.statusbars.bottombar) - 10))
#This will quite likely fail when switching modes # This will quite likely fail when switching modes
try: try:
rf = format_utils.remove_formatting rf = format_utils.remove_formatting
string = self.statusbars.bottombar string = self.statusbars.bottombar
@ -74,7 +74,7 @@ class EventView(BaseMode):
def on_resize(self, *args): def on_resize(self, *args):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
#Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out # Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out
legacy = component.get("LegacyUI") legacy = component.get("LegacyUI")
legacy.on_resize(*args) legacy.on_resize(*args)
self.stdscr.erase() self.stdscr.erase()

View File

@ -104,7 +104,7 @@ def trim_string(string, w, have_dbls):
def format_column(col, lim): def format_column(col, lim):
dbls = 0 dbls = 0
#Chosen over isinstance(col, unicode) and col.__class__ == unicode # Chosen over isinstance(col, unicode) and col.__class__ == unicode
# for speed - it's ~3 times faster for non-unicode strings and ~1.5 # for speed - it's ~3 times faster for non-unicode strings and ~1.5
# for unicode strings. # for unicode strings.
if col.__class__ is unicode: if col.__class__ is unicode:
@ -199,7 +199,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True):
for i in range(len(ret), min_lines): for i in range(len(ret), min_lines):
ret.append(" ") ret.append(" ")
#Carry colors over to the next line # Carry colors over to the next line
last_color_string = "" last_color_string = ""
for i, line in enumerate(ret): for i, line in enumerate(ret):
if i != 0: if i != 0:

View File

@ -744,7 +744,7 @@ class TextInput(InputField):
# This is a correct path, check to see if it's a directory # This is a correct path, check to see if it's a directory
if os.path.isdir(line): if os.path.isdir(line):
# Directory, so we need to show contents of directory # Directory, so we need to show contents of directory
#ret.extend(os.listdir(line)) # ret.extend(os.listdir(line))
for f in os.listdir(line): for f in os.listdir(line):
# Skip hidden # Skip hidden
if f.startswith("."): if f.startswith("."):
@ -786,7 +786,7 @@ class InputPopup(Popup):
self.additional_formatting = additional_formatting self.additional_formatting = additional_formatting
self.immediate_action = immediate_action self.immediate_action = immediate_action
#We need to replicate some things in order to wrap our inputs # We need to replicate some things in order to wrap our inputs
self.encoding = parent_mode.encoding self.encoding = parent_mode.encoding
def move(self, r, c): def move(self, r, c):
@ -833,7 +833,7 @@ class InputPopup(Popup):
self.inputs.append(CheckedInput(self, message, name, checked, self.inputs.append(CheckedInput(self, message, name, checked,
additional_formatting=self.additional_formatting)) additional_formatting=self.additional_formatting))
#def add_checked_plus_input(self, message, name, child) # def add_checked_plus_input(self, message, name, child)
def add_float_spin_input(self, message, name, value=0.0, inc_amt=1.0, precision=1, min_val=None, max_val=None): def add_float_spin_input(self, message, name, value=0.0, inc_amt=1.0, precision=1, min_val=None, max_val=None):
i = FloatSpinInput(self, message, name, self.move, value, inc_amt, precision, min_val, max_val, i = FloatSpinInput(self, message, name, self.move, value, inc_amt, precision, min_val, max_val,

View File

@ -127,7 +127,7 @@ class Legacy(BaseMode, component.Component):
self.console_config = component.get("AllTorrents").config self.console_config = component.get("AllTorrents").config
#To avoid having to truncate the file every time we're writing # To avoid having to truncate the file every time we're writing
# or doing it on exit(and therefore relying on an error-less # or doing it on exit(and therefore relying on an error-less
# or in other words clean exit, we're going to have two files # or in other words clean exit, we're going to have two files
# that we swap around based on length # that we swap around based on length
@ -153,7 +153,7 @@ class Legacy(BaseMode, component.Component):
lines2 = [] lines2 = []
self._hf_lines[1] = 0 self._hf_lines[1] = 0
#The non-full file is the active one # The non-full file is the active one
if self._hf_lines[0] > self._hf_lines[1]: if self._hf_lines[0] > self._hf_lines[1]:
self.lines = lines1 + lines2 self.lines = lines1 + lines2
else: else:
@ -162,10 +162,10 @@ class Legacy(BaseMode, component.Component):
if len(self.lines) > MAX_HISTFILE_SIZE: if len(self.lines) > MAX_HISTFILE_SIZE:
self.lines = self.lines[-MAX_HISTFILE_SIZE:] self.lines = self.lines[-MAX_HISTFILE_SIZE:]
#Instead of having additional input history file, we can # Instead of having additional input history file, we can
# simply scan for lines beginning with ">>> " # simply scan for lines beginning with ">>> "
for i, line in enumerate(self.lines): for i, line in enumerate(self.lines):
#if not isinstance(line, unicode): # if not isinstance(line, unicode):
#line = line.encode(self.encoding) #line = line.encode(self.encoding)
#self.lines[i] = line #self.lines[i] = line
line = format_utils.remove_formatting(line) line = format_utils.remove_formatting(line)
@ -219,7 +219,7 @@ class Legacy(BaseMode, component.Component):
# Read the character # Read the character
c = self.stdscr.getch() c = self.stdscr.getch()
#An ugly, ugly, UGLY UGLY way to handle alt+backspace # An ugly, ugly, UGLY UGLY way to handle alt+backspace
# deleting more characters than it should, but without a more # deleting more characters than it should, but without a more
# complex input handling system, a more elegant solution # complex input handling system, a more elegant solution
# is not viable # is not viable
@ -385,7 +385,7 @@ class Legacy(BaseMode, component.Component):
def on_resize(self, *args): def on_resize(self, *args):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
#We need to also refresh AllTorrents because otherwise it will # We need to also refresh AllTorrents because otherwise it will
# be only us that get properly resized # be only us that get properly resized
all_torrents = component.get("AllTorrents") all_torrents = component.get("AllTorrents")
all_torrents.on_resize(*args) all_torrents.on_resize(*args)
@ -464,8 +464,8 @@ class Legacy(BaseMode, component.Component):
""" """
if self.console_config["save_legacy_history"]: if self.console_config["save_legacy_history"]:
#Determine which file is the active one # Determine which file is the active one
#If both are under maximum, it's first, otherwise it's the one not full # If both are under maximum, it's first, otherwise it's the one not full
if self._hf_lines[0] < MAX_HISTFILE_SIZE and self._hf_lines[1] < MAX_HISTFILE_SIZE: if self._hf_lines[0] < MAX_HISTFILE_SIZE and self._hf_lines[1] < MAX_HISTFILE_SIZE:
active_file = 0 active_file = 0
elif self._hf_lines[0] == MAX_HISTFILE_SIZE: elif self._hf_lines[0] == MAX_HISTFILE_SIZE:
@ -473,7 +473,7 @@ class Legacy(BaseMode, component.Component):
else: else:
active_file = 0 active_file = 0
#Write the line # Write the line
f = open(self.history_file[active_file], "a") f = open(self.history_file[active_file], "a")
if isinstance(text, unicode): if isinstance(text, unicode):
@ -482,10 +482,10 @@ class Legacy(BaseMode, component.Component):
f.write(os.linesep) f.write(os.linesep)
#And increment line counter # And increment line counter
self._hf_lines[active_file] += 1 self._hf_lines[active_file] += 1
#If the active file reaches max size, we truncate it # If the active file reaches max size, we truncate it
# therefore swapping the currently active file # therefore swapping the currently active file
if self._hf_lines[active_file] == MAX_HISTFILE_SIZE: if self._hf_lines[active_file] == MAX_HISTFILE_SIZE:
self._hf_lines[1 - active_file] = 0 self._hf_lines[1 - active_file] = 0
@ -684,7 +684,7 @@ class Legacy(BaseMode, component.Component):
# First check to see if there is no space, this will mean that it's a # First check to see if there is no space, this will mean that it's a
# command that needs to be completed. # command that needs to be completed.
#We don't want to split by escaped spaces # We don't want to split by escaped spaces
def split(string): def split(string):
return re.split(r"(?<!\\) ", string) return re.split(r"(?<!\\) ", string)
@ -714,11 +714,11 @@ class Legacy(BaseMode, component.Component):
# return it, else we need to print out the matches without modifying # return it, else we need to print out the matches without modifying
# the line. # the line.
elif len(possible_matches) == 1: elif len(possible_matches) == 1:
#Do not append space after directory names # Do not append space after directory names
new_line = line_prefix + possible_matches[0] new_line = line_prefix + possible_matches[0]
if not new_line.endswith("/") and not new_line.endswith(r"\\"): if not new_line.endswith("/") and not new_line.endswith(r"\\"):
new_line += " " new_line += " "
#We only want to print eventual colors or other control characters, not return them # We only want to print eventual colors or other control characters, not return them
new_line = format_utils.remove_formatting(new_line) new_line = format_utils.remove_formatting(new_line)
return (new_line, len(new_line)) return (new_line, len(new_line))
else: else:
@ -746,7 +746,7 @@ class Legacy(BaseMode, component.Component):
if match_count >= 4: if match_count >= 4:
self.write("{!green!}Autocompletion matches:") self.write("{!green!}Autocompletion matches:")
#Only list some of the matching torrents as there can be hundreds of them # Only list some of the matching torrents as there can be hundreds of them
if self.console_config["third_tab_lists_all"]: if self.console_config["third_tab_lists_all"]:
if hits == 2 and left > max_list: if hits == 2 and left > max_list:
for i in range(listed, listed + max_list): for i in range(listed, listed + max_list):
@ -771,7 +771,7 @@ class Legacy(BaseMode, component.Component):
if hits > 2: if hits > 2:
self.write("{!green!}Finished listing %i torrents (%i/%i)" % (match_count, hits - 1, pages)) self.write("{!green!}Finished listing %i torrents (%i/%i)" % (match_count, hits - 1, pages))
#We only want to print eventual colors or other control characters, not return them # We only want to print eventual colors or other control characters, not return them
line = format_utils.remove_formatting(line) line = format_utils.remove_formatting(line)
cursor = len(line) cursor = len(line)
return (line, cursor) return (line, cursor)
@ -786,7 +786,7 @@ class Legacy(BaseMode, component.Component):
# This is a correct path, check to see if it's a directory # This is a correct path, check to see if it's a directory
if os.path.isdir(line): if os.path.isdir(line):
# Directory, so we need to show contents of directory # Directory, so we need to show contents of directory
#ret.extend(os.listdir(line)) # ret.extend(os.listdir(line))
try: try:
for f in os.listdir(line): for f in os.listdir(line):
# Skip hidden # Skip hidden
@ -839,7 +839,7 @@ class Legacy(BaseMode, component.Component):
elif dirs_first == -1: elif dirs_first == -1:
ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=False) ret = sorted(ret, key=lambda p: os.path.isdir(p), reverse=False)
#Highlight directory names # Highlight directory names
for i, filename in enumerate(ret): for i, filename in enumerate(ret):
if os.path.isdir(filename): if os.path.isdir(filename):
ret[i] = "{!cyan!}%s" % filename ret[i] = "{!cyan!}%s" % filename
@ -863,7 +863,7 @@ class Legacy(BaseMode, component.Component):
else: else:
empty = False empty = False
#Remove dangling backslashes to avoid breaking shlex # Remove dangling backslashes to avoid breaking shlex
if line.endswith("\\"): if line.endswith("\\"):
line = line[:-1] line = line[:-1]
@ -903,9 +903,9 @@ class Legacy(BaseMode, component.Component):
else: else:
l = len(raw_line) l = len(raw_line)
#Let's avoid listing all torrents twice if there's no pattern # Let's avoid listing all torrents twice if there's no pattern
if not empty and torrent_id.startswith(line): if not empty and torrent_id.startswith(line):
#Highlight the matching part # Highlight the matching part
text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name) text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name)
possible_matches.append(text) possible_matches.append(text)
if torrent_name.startswith(line): if torrent_name.startswith(line):

View File

@ -95,7 +95,7 @@ class Popup:
log.debug("Resizing(or creating) popup window") log.debug("Resizing(or creating) popup window")
#Height # Height
if hr == 0: if hr == 0:
hr = int(self.parent.rows / 2) hr = int(self.parent.rows / 2)
elif hr == -1: elif hr == -1:
@ -103,7 +103,7 @@ class Popup:
elif hr > self.parent.rows - 2: elif hr > self.parent.rows - 2:
hr = self.parent.rows - 2 hr = self.parent.rows - 2
#Width # Width
if wr == 0: if wr == 0:
wr = int(self.parent.cols / 2) wr = int(self.parent.cols / 2)
elif wr == -1: elif wr == -1:

View File

@ -263,7 +263,7 @@ class ColumnsPane(BasePane):
for cpn in deluge.ui.console.modes.alltorrents.column_pref_names: for cpn in deluge.ui.console.modes.alltorrents.column_pref_names:
pn = "show_%s" % cpn pn = "show_%s" % cpn
#If there is no option for it, it's not togglable # If there is no option for it, it's not togglable
# We check in default_prefs because it might still exist in config files # We check in default_prefs because it might still exist in config files
if pn not in default_prefs: if pn not in default_prefs:
continue continue

View File

@ -143,7 +143,7 @@ class Preferences(BaseMode):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
self.__calc_sizes() self.__calc_sizes()
#Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out # Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out
legacy = component.get("LegacyUI") legacy = component.get("LegacyUI")
legacy.on_resize(*args) legacy.on_resize(*args)
self.stdscr.erase() self.stdscr.erase()

View File

@ -337,7 +337,7 @@ class TorrentDetail(BaseMode, component.Component):
else: else:
color_string = "{!%s,%s!}" % (fg, bg) color_string = "{!%s,%s!}" % (fg, bg)
#actually draw the dir/file string # actually draw the dir/file string
if fl[3] and fl[4]: # this is an expanded directory if fl[3] and fl[4]: # this is an expanded directory
xchar = "v" xchar = "v"
elif fl[3]: # collapsed directory elif fl[3]: # collapsed directory
@ -400,7 +400,7 @@ class TorrentDetail(BaseMode, component.Component):
def on_resize(self, *args): def on_resize(self, *args):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
#Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out # Always refresh Legacy(it will also refresh AllTorrents), otherwise it will bug deluge out
legacy = component.get("LegacyUI") legacy = component.get("LegacyUI")
legacy.on_resize(*args) legacy.on_resize(*args)
@ -417,12 +417,12 @@ class TorrentDetail(BaseMode, component.Component):
up_color = colors.state_color["Seeding"] up_color = colors.state_color["Seeding"]
down_color = colors.state_color["Downloading"] down_color = colors.state_color["Downloading"]
#Name # Name
s = "{!info!}Name: {!input!}%s" % status["name"] s = "{!info!}Name: {!input!}%s" % status["name"]
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Print DL info and ETA # Print DL info and ETA
if status["download_payload_rate"] > 0: if status["download_payload_rate"] > 0:
s = "%sDownloading: {!input!}" % down_color s = "%sDownloading: {!input!}" % down_color
else: else:
@ -436,7 +436,7 @@ class TorrentDetail(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Print UL info and ratio # Print UL info and ratio
if status["upload_payload_rate"] > 0: if status["upload_payload_rate"] > 0:
s = "%sUploading: {!input!}" % up_color s = "%sUploading: {!input!}" % up_color
else: else:
@ -451,7 +451,7 @@ class TorrentDetail(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Seed/peer info # Seed/peer info
s = "{!info!}Seeds:{!green!} %s {!input!}(%s)" % (status["num_seeds"], status["total_seeds"]) s = "{!info!}Seeds:{!green!} %s {!input!}(%s)" % (status["num_seeds"], status["total_seeds"])
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
@ -459,7 +459,7 @@ class TorrentDetail(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Tracker # Tracker
if status["message"] == "OK": if status["message"] == "OK":
color = "{!green!}" color = "{!green!}"
else: else:
@ -477,24 +477,24 @@ class TorrentDetail(BaseMode, component.Component):
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Time added # Time added
s = "{!info!}Added: {!input!}%s" % fdate(status["time_added"]) s = "{!info!}Added: {!input!}%s" % fdate(status["time_added"])
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Time active # Time active
s = "{!info!}Time active: {!input!}%s" % (ftime(status["active_time"])) s = "{!info!}Time active: {!input!}%s" % (ftime(status["active_time"]))
if status["seeding_time"]: if status["seeding_time"]:
s += ", {!cyan!}%s{!input!} seeding" % (ftime(status["seeding_time"])) s += ", {!cyan!}%s{!input!} seeding" % (ftime(status["seeding_time"]))
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Download Folder # Download Folder
s = "{!info!}Download Folder: {!input!}%s" % status["download_location"] s = "{!info!}Download Folder: {!input!}%s" % status["download_location"]
self.add_string(off, s) self.add_string(off, s)
off += 1 off += 1
#Owner # Owner
if status["owner"]: if status["owner"]:
s = "{!info!}Owner: {!input!}%s" % status["owner"] s = "{!info!}Owner: {!input!}%s" % status["owner"]
@ -510,7 +510,7 @@ class TorrentDetail(BaseMode, component.Component):
self.stdscr.erase() self.stdscr.erase()
self.add_string(0, self.statusbars.topbar) self.add_string(0, self.statusbars.topbar)
#This will quite likely fail when switching modes # This will quite likely fail when switching modes
try: try:
rf = format_utils.remove_formatting rf = format_utils.remove_formatting
string = self.statusbars.bottombar string = self.statusbars.bottombar
@ -591,7 +591,7 @@ class TorrentDetail(BaseMode, component.Component):
def build_prio_list(self, files, ret_list, parent_prio, selected_prio): def build_prio_list(self, files, ret_list, parent_prio, selected_prio):
# has a priority been set on my parent (if so, I inherit it) # has a priority been set on my parent (if so, I inherit it)
for f in files: for f in files:
#Do not set priorities for the whole dir, just selected contents # Do not set priorities for the whole dir, just selected contents
if f[3]: if f[3]:
self.build_prio_list(f[3], ret_list, parent_prio, selected_prio) self.build_prio_list(f[3], ret_list, parent_prio, selected_prio)
else: # file, need to add to list else: # file, need to add to list
@ -632,13 +632,13 @@ class TorrentDetail(BaseMode, component.Component):
""" """
fc = self.__get_contained_files_count(idx=idx) fc = self.__get_contained_files_count(idx=idx)
if idx not in self.marked: if idx not in self.marked:
#Not selected, select it # Not selected, select it
self.__mark_tree(self.file_list, idx) self.__mark_tree(self.file_list, idx)
elif self.marked[idx] < fc: elif self.marked[idx] < fc:
#Partially selected, unselect all contents # Partially selected, unselect all contents
self.__unmark_tree(self.file_list, idx) self.__unmark_tree(self.file_list, idx)
else: else:
#Selected, unselect it # Selected, unselect it
self.__unmark_tree(self.file_list, idx) self.__unmark_tree(self.file_list, idx)
def __mark_tree(self, file_list, idx, mark_all=False): def __mark_tree(self, file_list, idx, mark_all=False):
@ -650,10 +650,10 @@ class TorrentDetail(BaseMode, component.Component):
total_marked = 0 total_marked = 0
for element in file_list: for element in file_list:
marked = 0 marked = 0
#Select the file if it's the one we want or # Select the file if it's the one we want or
# if it's inside a directory that got selected # if it's inside a directory that got selected
if (element[1] == idx) or mark_all: if (element[1] == idx) or mark_all:
#If it's a folder then select everything inside # If it's a folder then select everything inside
if element[3]: if element[3]:
marked = self.__mark_tree(element[3], idx, True) marked = self.__mark_tree(element[3], idx, True)
self.marked[element[1]] = marked self.marked[element[1]] = marked
@ -661,17 +661,17 @@ class TorrentDetail(BaseMode, component.Component):
marked = 1 marked = 1
self.marked[element[1]] = 1 self.marked[element[1]] = 1
else: else:
#Does not match but the item to be selected might be inside, recurse # Does not match but the item to be selected might be inside, recurse
if element[3]: if element[3]:
marked = self.__mark_tree(element[3], idx, False) marked = self.__mark_tree(element[3], idx, False)
#Partially select the folder if it contains files that were selected # Partially select the folder if it contains files that were selected
if marked > 0: if marked > 0:
self.marked[element[1]] = marked self.marked[element[1]] = marked
else: else:
if element[1] in self.marked: if element[1] in self.marked:
#It's not the element we want but it's marked so count it # It's not the element we want but it's marked so count it
marked = 1 marked = 1
#Count and then return total amount of files selected in all subdirectories # Count and then return total amount of files selected in all subdirectories
total_marked += marked total_marked += marked
return total_marked return total_marked
@ -717,30 +717,30 @@ class TorrentDetail(BaseMode, component.Component):
total_marked = 0 total_marked = 0
for element in file_list: for element in file_list:
marked = 0 marked = 0
#It's either the item we want to select or # It's either the item we want to select or
# a contained item, deselect it # a contained item, deselect it
if (element[1] == idx) or unmark_all: if (element[1] == idx) or unmark_all:
if element[1] in self.marked: if element[1] in self.marked:
del self.marked[element[1]] del self.marked[element[1]]
#Deselect all contents if it's a catalog # Deselect all contents if it's a catalog
if element[3]: if element[3]:
self.__unmark_tree(element[3], idx, True) self.__unmark_tree(element[3], idx, True)
else: else:
#Not file we wanted but it might be inside this folder, recurse inside # Not file we wanted but it might be inside this folder, recurse inside
if element[3]: if element[3]:
marked = self.__unmark_tree(element[3], idx, False) marked = self.__unmark_tree(element[3], idx, False)
#If none of the contents remain selected, unselect this folder as well # If none of the contents remain selected, unselect this folder as well
if marked == 0: if marked == 0:
if element[1] in self.marked: if element[1] in self.marked:
del self.marked[element[1]] del self.marked[element[1]]
#Otherwise update selection count # Otherwise update selection count
else: else:
self.marked[element[1]] = marked self.marked[element[1]] = marked
else: else:
if element[1] in self.marked: if element[1] in self.marked:
marked = 1 marked = 1
#Count and then return selection count so we can update # Count and then return selection count so we can update
# directories higher up in the hierarchy # directories higher up in the hierarchy
total_marked += marked total_marked += marked
return total_marked return total_marked
@ -753,7 +753,7 @@ class TorrentDetail(BaseMode, component.Component):
if idx == self.current_file_idx: if idx == self.current_file_idx:
return true_idx return true_idx
#It's a folder # It's a folder
if element[3]: if element[3]:
i = self._selection_to_file_idx(element[3], idx + 1, true_idx, closed or not element[4]) i = self._selection_to_file_idx(element[3], idx + 1, true_idx, closed or not element[4])
if isinstance(i, tuple): if isinstance(i, tuple):
@ -804,7 +804,7 @@ class TorrentDetail(BaseMode, component.Component):
client.core.rename_files(torrent_id, [(file_idx, new_filename)]) client.core.rename_files(torrent_id, [(file_idx, new_filename)])
def _show_rename_popup(self): def _show_rename_popup(self):
#Perhaps in the future: Renaming multiple files # Perhaps in the future: Renaming multiple files
if self.marked: if self.marked:
title = "Error (Enter to close)" title = "Error (Enter to close)"
text = "Sorry, you can't rename multiple files, please clear selection with {!info!}'c'{!normal!} key" text = "Sorry, you can't rename multiple files, please clear selection with {!info!}'c'{!normal!} key"

View File

@ -56,25 +56,25 @@ class StatusBars(component.Component):
info = client.connection_info() info = client.connection_info()
connection_info = "" connection_info = ""
#Client name # Client name
if info[2] == "localclient": if info[2] == "localclient":
connection_info += "{!white,blue!}%s" connection_info += "{!white,blue!}%s"
else: else:
connection_info += "{!green,blue,bold!}%s" connection_info += "{!green,blue,bold!}%s"
#Hostname # Hostname
if info[0] == "127.0.0.1": if info[0] == "127.0.0.1":
connection_info += "{!white,blue,bold!}@{!white,blue!}%s" connection_info += "{!white,blue,bold!}@{!white,blue!}%s"
else: else:
connection_info += "{!white,blue,bold!}@{!red,blue,bold!}%s" connection_info += "{!white,blue,bold!}@{!red,blue,bold!}%s"
#Port # Port
if info[1] == DEFAULT_PREFS["daemon_port"]: if info[1] == DEFAULT_PREFS["daemon_port"]:
connection_info += "{!white,blue!}:%s" connection_info += "{!white,blue!}:%s"
else: else:
connection_info += "{!status!}:%s" connection_info += "{!status!}:%s"
#Change color back to normal, just in case # Change color back to normal, just in case
connection_info += "{!status!}" connection_info += "{!status!}"
self.topbar += connection_info % (info[2], info[0], info[1]) self.topbar += connection_info % (info[2], info[0], info[1])

View File

@ -69,7 +69,7 @@ class AddTorrentDialog(component.Component):
}) })
self.torrent_liststore = gtk.ListStore(str, str, str) self.torrent_liststore = gtk.ListStore(str, str, str)
#download?, path, filesize, sequence number, inconsistent? # download?, path, filesize, sequence number, inconsistent?
self.files_treestore = gtk.TreeStore( self.files_treestore = gtk.TreeStore(
bool, str, gobject.TYPE_UINT64, gobject.TYPE_INT64, bool, str) bool, str, gobject.TYPE_UINT64, gobject.TYPE_INT64, bool, str)
self.files_treestore.set_sort_column_id(1, gtk.SORT_ASCENDING) self.files_treestore.set_sort_column_id(1, gtk.SORT_ASCENDING)
@ -516,7 +516,7 @@ class AddTorrentDialog(component.Component):
self.files_treestore.set_value(iter, 4, True) self.files_treestore.set_value(iter, 4, True)
else: else:
self.files_treestore.set_value(iter, 0, toggle) self.files_treestore.set_value(iter, 0, toggle)
#set inconsistent to false # set inconsistent to false
self.files_treestore.set_value(iter, 4, False) self.files_treestore.set_value(iter, 4, False)
else: else:
toggle = self.files_treestore.get_value(iter, 0) toggle = self.files_treestore.get_value(iter, 0)

View File

@ -340,7 +340,7 @@ class FilesTab(Tab):
timestamp = gtk.get_current_event_time() timestamp = gtk.get_current_event_time()
show_file(filepath, timestamp=timestamp) show_file(filepath, timestamp=timestamp)
## The following 3 methods create the folder/file view in the treeview # The following 3 methods create the folder/file view in the treeview
def prepare_file_store(self, files): def prepare_file_store(self, files):
split_files = {} split_files = {}
i = 0 i = 0

View File

@ -57,7 +57,7 @@ class FilterTreeView(component.Component):
self.treeview = gtk.TreeView() self.treeview = gtk.TreeView()
self.sidebar.add_tab(self.treeview, "filters", "Filters") self.sidebar.add_tab(self.treeview, "filters", "Filters")
#set filter to all when hidden: # set filter to all when hidden:
self.sidebar.notebook.connect("hide", self._on_hide) self.sidebar.notebook.connect("hide", self._on_hide)
# Create the treestore # Create the treestore
@ -98,7 +98,7 @@ class FilterTreeView(component.Component):
self.treeview.connect("button-press-event", self.on_button_press_event) self.treeview.connect("button-press-event", self.on_button_press_event)
#colors using current theme. # colors using current theme.
style = self.window.window.get_style() style = self.window.window.get_style()
self.colour_background = style.bg[gtk.STATE_NORMAL] self.colour_background = style.bg[gtk.STATE_NORMAL]
self.colour_foreground = style.fg[gtk.STATE_NORMAL] self.colour_foreground = style.fg[gtk.STATE_NORMAL]
@ -116,11 +116,11 @@ class FilterTreeView(component.Component):
self.default_menu_items = self.menu.get_children() self.default_menu_items = self.menu.get_children()
def start(self): def start(self):
#add Cat nodes: # add Cat nodes:
self.cat_nodes = {} self.cat_nodes = {}
self.filters = {} self.filters = {}
#initial order of state filter: # initial order of state filter:
self.cat_nodes["state"] = self.treestore.append(None, ["cat", "state", _("States"), 0, None, False]) self.cat_nodes["state"] = self.treestore.append(None, ["cat", "state", _("States"), 0, None, False])
for state in ["All", "Active"] + TORRENT_STATE: for state in ["All", "Active"] + TORRENT_STATE:
self.update_row("state", state, 0, _(state)) self.update_row("state", state, 0, _(state))
@ -149,7 +149,7 @@ class FilterTreeView(component.Component):
self.treeview.set_model(self.model_filter) self.treeview.set_model(self.model_filter)
def cb_update_filter_tree(self, filter_items): def cb_update_filter_tree(self, filter_items):
#create missing cat_nodes # create missing cat_nodes
for cat in filter_items: for cat in filter_items:
if not cat in self.cat_nodes: if not cat in self.cat_nodes:
label = _(cat) label = _(cat)
@ -157,7 +157,7 @@ class FilterTreeView(component.Component):
label = _("Labels") label = _("Labels")
self.cat_nodes[cat] = self.treestore.append(None, ["cat", cat, label, 0, None, False]) self.cat_nodes[cat] = self.treestore.append(None, ["cat", cat, label, 0, None, False])
#update rows # update rows
visible_filters = [] visible_filters = []
for cat, filters in filter_items.iteritems(): for cat, filters in filter_items.iteritems():
for value, count in filters: for value, count in filters:
@ -214,7 +214,7 @@ class FilterTreeView(component.Component):
label = model.get_value(row, 2) label = model.get_value(row, 2)
count = model.get_value(row, 3) count = model.get_value(row, 3)
#Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed # Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
original_filters = warnings.filters[:] original_filters = warnings.filters[:]
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
try: try:
@ -324,7 +324,7 @@ class FilterTreeView(component.Component):
return True return True
elif event.button == 3: elif event.button == 3:
#assign current cat, value to self: # assign current cat, value to self:
x, y = event.get_coords() x, y = event.get_coords()
path = self.treeview.get_path_at_pos(int(x), int(y)) path = self.treeview.get_path_at_pos(int(x), int(y))
if not path: if not path:
@ -334,7 +334,7 @@ class FilterTreeView(component.Component):
self.value = self.model_filter.get_value(row, 1) self.value = self.model_filter.get_value(row, 1)
self.count = self.model_filter.get_value(row, 3) self.count = self.model_filter.get_value(row, 3)
#Show the pop-up menu # Show the pop-up menu
self.set_menu_sensitivity() self.set_menu_sensitivity()
self.menu.hide() self.menu.hide()
self.menu.popup(None, None, None, event.button, event.time) self.menu.popup(None, None, None, event.button, event.time)
@ -345,7 +345,7 @@ class FilterTreeView(component.Component):
return True return True
def set_menu_sensitivity(self): def set_menu_sensitivity(self):
#select-all/pause/resume # select-all/pause/resume
sensitive = (self.cat != "cat" and self.count != 0) sensitive = (self.cat != "cat" and self.count != 0)
for item in self.default_menu_items: for item in self.default_menu_items:
item.set_sensitive(sensitive) item.set_sensitive(sensitive)

View File

@ -143,7 +143,7 @@ class GtkUI(object):
import gnome.ui import gnome.ui
import gnome import gnome
#Suppress: Warning: Attempt to add property GnomeProgram::*** after class was initialised # Suppress: Warning: Attempt to add property GnomeProgram::*** after class was initialised
original_filters = warnings.filters[:] original_filters = warnings.filters[:]
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
try: try:

View File

@ -111,22 +111,22 @@ class MenuBar(component.Component):
### Connect main window Signals ### ### Connect main window Signals ###
component.get("MainWindow").connect_signals({ component.get("MainWindow").connect_signals({
## File Menu # File Menu
"on_menuitem_addtorrent_activate": self.on_menuitem_addtorrent_activate, "on_menuitem_addtorrent_activate": self.on_menuitem_addtorrent_activate,
"on_menuitem_createtorrent_activate": self.on_menuitem_createtorrent_activate, "on_menuitem_createtorrent_activate": self.on_menuitem_createtorrent_activate,
"on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate, "on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate,
"on_menuitem_quit_activate": self.on_menuitem_quit_activate, "on_menuitem_quit_activate": self.on_menuitem_quit_activate,
## Edit Menu # Edit Menu
"on_menuitem_preferences_activate": self.on_menuitem_preferences_activate, "on_menuitem_preferences_activate": self.on_menuitem_preferences_activate,
"on_menuitem_connectionmanager_activate": self.on_menuitem_connectionmanager_activate, "on_menuitem_connectionmanager_activate": self.on_menuitem_connectionmanager_activate,
## View Menu # View Menu
"on_menuitem_toolbar_toggled": self.on_menuitem_toolbar_toggled, "on_menuitem_toolbar_toggled": self.on_menuitem_toolbar_toggled,
"on_menuitem_sidebar_toggled": self.on_menuitem_sidebar_toggled, "on_menuitem_sidebar_toggled": self.on_menuitem_sidebar_toggled,
"on_menuitem_statusbar_toggled": self.on_menuitem_statusbar_toggled, "on_menuitem_statusbar_toggled": self.on_menuitem_statusbar_toggled,
## Help Menu # Help Menu
"on_menuitem_homepage_activate": self.on_menuitem_homepage_activate, "on_menuitem_homepage_activate": self.on_menuitem_homepage_activate,
"on_menuitem_faq_activate": self.on_menuitem_faq_activate, "on_menuitem_faq_activate": self.on_menuitem_faq_activate,
"on_menuitem_community_activate": self.on_menuitem_community_activate, "on_menuitem_community_activate": self.on_menuitem_community_activate,
@ -137,7 +137,7 @@ class MenuBar(component.Component):
# Connect menubar signals # Connect menubar signals
self.builder.connect_signals({ self.builder.connect_signals({
## Torrent Menu # Torrent Menu
"on_menuitem_pause_activate": self.on_menuitem_pause_activate, "on_menuitem_pause_activate": self.on_menuitem_pause_activate,
"on_menuitem_resume_activate": self.on_menuitem_resume_activate, "on_menuitem_resume_activate": self.on_menuitem_resume_activate,
"on_menuitem_updatetracker_activate": self.on_menuitem_updatetracker_activate, "on_menuitem_updatetracker_activate": self.on_menuitem_updatetracker_activate,

View File

@ -557,7 +557,7 @@ class PathChooserPopup(object):
""" """
# Necessary for the first call, to make treeview.size_request give sensible values # Necessary for the first call, to make treeview.size_request give sensible values
#self.popup_window.realize() # self.popup_window.realize()
self.treeview.realize() self.treeview.realize()
# We start with the coordinates of the parent window # We start with the coordinates of the parent window
@ -1249,7 +1249,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self.auto_completer._end_completion(args) self.auto_completer._end_completion(args)
###################################### ######################################
## Callbacks and internal functions # Callbacks and internal functions
###################################### ######################################
def on_entry_text_changed(self, entry): def on_entry_text_changed(self, entry):
@ -1349,7 +1349,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
self._stored_values_popping_down = False self._stored_values_popping_down = False
###################################### ######################################
## Config dialog # Config dialog
###################################### ######################################
def _on_button_toggle_dropdown_button_press_event(self, widget, event): def _on_button_toggle_dropdown_button_press_event(self, widget, event):
@ -1535,7 +1535,7 @@ if __name__ == "__main__":
cursor_end=False) cursor_end=False)
entry2.set_filechooser_button_visible(False) entry2.set_filechooser_button_visible(False)
#entry2.set_enable_properties(False) # entry2.set_enable_properties(False)
entry2.set_filechooser_button_enabled(False) entry2.set_filechooser_button_enabled(False)
def list_value_added_event(widget, values): def list_value_added_event(widget, values):

View File

@ -341,11 +341,11 @@ class PeersTab(Tab):
value = txt_ip.get_text() value = txt_ip.get_text()
if value and ':' in value: if value and ':' in value:
if ']' in value: if ']' in value:
#ipv6 # ipv6
ip = value.split("]")[0][1:] ip = value.split("]")[0][1:]
port = value.split("]")[1][1:] port = value.split("]")[1][1:]
else: else:
#ipv4 # ipv4
ip = value.split(":")[0] ip = value.split(":")[0]
port = value.split(":")[1] port = value.split(":")[1]
if deluge.common.is_ip(ip): if deluge.common.is_ip(ip):

View File

@ -72,7 +72,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
def _on_plugin_disabled_event(self, name): def _on_plugin_disabled_event(self, name):
self.disable_plugin(name) self.disable_plugin(name)
## Hook functions # Hook functions
def run_on_show_prefs(self): def run_on_show_prefs(self):
"""This hook is run before the user is shown the preferences dialog. """This hook is run before the user is shown the preferences dialog.
It is designed so that plugins can update their preference page with It is designed so that plugins can update their preference page with
@ -89,7 +89,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon
for function in self.hooks["on_apply_prefs"]: for function in self.hooks["on_apply_prefs"]:
function() function()
## Plugin functions.. will likely move to own class.. # Plugin functions.. will likely move to own class..
def add_torrentview_text_column(self, *args, **kwargs): def add_torrentview_text_column(self, *args, **kwargs):
return component.get("TorrentView").add_text_column(*args, **kwargs) return component.get("TorrentView").add_text_column(*args, **kwargs)

View File

@ -358,7 +358,7 @@ class SystemTray(component.Component):
def on_tray_setbwdown(self, widget, data=None): def on_tray_setbwdown(self, widget, data=None):
if isinstance(widget, gtk.RadioMenuItem): if isinstance(widget, gtk.RadioMenuItem):
#ignore previous radiomenuitem value # ignore previous radiomenuitem value
if not widget.get_active(): if not widget.get_active():
return return
self.setbwlimit(widget, _("Download Speed Limit"), _("Set the maximum download speed"), self.setbwlimit(widget, _("Download Speed Limit"), _("Set the maximum download speed"),
@ -367,7 +367,7 @@ class SystemTray(component.Component):
def on_tray_setbwup(self, widget, data=None): def on_tray_setbwup(self, widget, data=None):
if isinstance(widget, gtk.RadioMenuItem): if isinstance(widget, gtk.RadioMenuItem):
#ignore previous radiomenuitem value # ignore previous radiomenuitem value
if not widget.get_active(): if not widget.get_active():
return return
self.setbwlimit(widget, _("Upload Speed Limit"), _("Set the maximum upload speed"), self.setbwlimit(widget, _("Upload Speed Limit"), _("Set the maximum upload speed"),

View File

@ -145,7 +145,7 @@ class TorrentDetails(component.Component):
def add_tab(self, tab, generate_menu=True, visible=None): def add_tab(self, tab, generate_menu=True, visible=None):
name = tab.get_name() name = tab.get_name()
#find position of tab in self.state, this is the tab weight # find position of tab in self.state, this is the tab weight
weight = None weight = None
for w, item in enumerate(self.state): for w, item in enumerate(self.state):
if item[0] == name: if item[0] == name:
@ -164,7 +164,7 @@ class TorrentDetails(component.Component):
if visible: if visible:
tab.is_visible = True tab.is_visible = True
#add the tab at position guided by the weight # add the tab at position guided by the weight
insert_pos = self.tab_insert_position(weight) insert_pos = self.tab_insert_position(weight)
log.debug("Trying to insert tab at %d" % insert_pos) log.debug("Trying to insert tab at %d" % insert_pos)
pos = self.notebook.insert_page( pos = self.notebook.insert_page(
@ -382,9 +382,9 @@ class TorrentDetails(component.Component):
def save_state(self): def save_state(self):
"""We save the state, which is basically the tab_index list""" """We save the state, which is basically the tab_index list"""
#Update the visiblity status of all tabs # Update the visiblity status of all tabs
#Leave tabs we dont know anything about it the state as they # Leave tabs we dont know anything about it the state as they
#might come from a plugin # might come from a plugin
for i, (name, visible) in enumerate(self.state): for i, (name, visible) in enumerate(self.state):
log.debug("Testing name: %s" % name) log.debug("Testing name: %s" % name)
if name in self.tabs: if name in self.tabs:

View File

@ -69,7 +69,7 @@ def cell_data_statusicon(column, cell, model, row, data):
icon = ICON_STATE[state] icon = ICON_STATE[state]
#Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed # Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
original_filters = warnings.filters[:] original_filters = warnings.filters[:]
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
try: try:
@ -101,7 +101,7 @@ def set_icon(icon, cell):
else: else:
pixbuf = create_blank_pixbuf() pixbuf = create_blank_pixbuf()
#Suppress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed # Suppress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
cell.set_property("pixbuf", pixbuf) cell.set_property("pixbuf", pixbuf)

View File

@ -188,7 +188,7 @@ class SessionProxy(component.Component):
for k in value: for k in value:
self.cache_times[key][k] = t self.cache_times[key][k] = t
except KeyError: except KeyError:
#The torrent was removed # The torrent was removed
continue continue
# Create the status dict # Create the status dict