diff options
author | Calum Lind <calumlind+deluge@gmail.com> | 2016-11-03 21:26:46 +0000 |
---|---|---|
committer | Calum Lind <calumlind+deluge@gmail.com> | 2016-11-03 21:45:45 +0000 |
commit | 3a2ff0c188b0e8da893b733cccb1e164b54f2471 (patch) | |
tree | 2997d64b20e6e280016792cd4a04bfd20ff89992 /deluge/ui | |
parent | d4a8a38586251575a17c50735a10ddfba30fdc31 (diff) | |
download | deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.tar.gz deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.tar.bz2 deluge-3a2ff0c188b0e8da893b733cccb1e164b54f2471.zip |
[Lint] Convert all python double quotes to single quotes
* A rather disruptive change but for a few reasons such as easier to read,
easier type, keep consistent and javascript code uses single quotes.
* There are a few exceptions for the automated process:
* Any double quotes in comments
* Triple double quotes for docstrings
* Strings containing single quotes are left e.g. "they're"
* To deal with merge conflicts from feature branches it is best to follow
these steps for each commit:
* Create a patch: `git format-patch -1 <sha1>`
* Edit the patch and replace double quotes with single except those in
comments or strings containing an unescaped apostrophe.
* Check the patch `git apply --check <patchfile>` and fix any remaining
issues if it outputs an error.
* Apply the patch `git am < <patchfile>`
Diffstat (limited to 'deluge/ui')
102 files changed, 5391 insertions, 5391 deletions
diff --git a/deluge/ui/Win32IconImagePlugin.py b/deluge/ui/Win32IconImagePlugin.py index 5e56de798..03f9bf9ee 100644 --- a/deluge/ui/Win32IconImagePlugin.py +++ b/deluge/ui/Win32IconImagePlugin.py @@ -131,7 +131,7 @@ class Win32IcoFile(object): else: # XOR + AND mask bmp frame im = PIL.BmpImagePlugin.DibImageFile(self.buf) - log.debug("Loaded image: %s %s %s %s", im.format, im.mode, im.size, im.info) + log.debug('Loaded image: %s %s %s %s', im.format, im.mode, im.size, im.info) # change tile dimension to only encompass XOR image im.size = im.size[0], im.size[1] // 2 @@ -146,7 +146,7 @@ class Win32IcoFile(object): bpp = k break # 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)) if bpp == 32: @@ -171,7 +171,7 @@ class Win32IcoFile(object): # apply mask image as alpha channel im = im.convert('RGBA') im.putalpha(mask) - log.debug("image mode: %s", im.mode) + log.debug('image mode: %s', im.mode) else: # get AND image from end of bitmap @@ -181,7 +181,7 @@ class Win32IcoFile(object): w += 32 - (im.size[0] % 32) # the total mask data is padded row size * height / bits per char total_bytes = (w * im.size[1]) // 8 - log.debug("tot=%d, off=%d, w=%d, size=%d", len(data), and_mask_offset, w, total_bytes) + log.debug('tot=%d, off=%d, w=%d, size=%d', len(data), and_mask_offset, w, total_bytes) self.buf.seek(and_mask_offset) mask_data = self.buf.read(total_bytes) @@ -199,7 +199,7 @@ class Win32IcoFile(object): # set mask as alpha channel im = im.convert('RGBA') im.putalpha(mask) - log.debug("image mode: %s", im.mode) + log.debug('image mode: %s', im.mode) # end if !'RGBA' # end if (png)/else(bmp) @@ -256,4 +256,4 @@ def _accept(prefix): # register our decoder with PIL PIL.Image.register_open(Win32IconImageFile.format, Win32IconImageFile, _accept) -PIL.Image.register_extension(Win32IconImageFile.format, ".ico") +PIL.Image.register_extension(Win32IconImageFile.format, '.ico') diff --git a/deluge/ui/baseargparser.py b/deluge/ui/baseargparser.py index 4684f1de8..75da06340 100644 --- a/deluge/ui/baseargparser.py +++ b/deluge/ui/baseargparser.py @@ -85,14 +85,14 @@ argparse.ArgumentParser.set_default_subparser = set_default_subparser def get_version(): - version_str = "%s\n" % (common.get_version()) + version_str = '%s\n' % (common.get_version()) try: from deluge._libtorrent import lt - version_str += "libtorrent: %s\n" % lt.__version__ + version_str += 'libtorrent: %s\n' % lt.__version__ except ImportError: pass - version_str += "Python: %s\n" % platform.python_version() - version_str += "OS: %s %s\n" % (platform.system(), " ".join(common.get_os_version())) + version_str += 'Python: %s\n' % platform.python_version() + version_str += 'OS: %s %s\n' % (platform.system(), ' '.join(common.get_os_version())) return version_str @@ -107,7 +107,7 @@ class DelugeTextHelpFormatter(argparse.RawDescriptionHelpFormatter): """ wrapped_lines = [] for l in text.splitlines(): - wrapped_lines.extend(textwrap.wrap(l, width, subsequent_indent=" ")) + wrapped_lines.extend(textwrap.wrap(l, width, subsequent_indent=' ')) return wrapped_lines def _format_action_invocation(self, action): @@ -133,16 +133,16 @@ class DelugeTextHelpFormatter(argparse.RawDescriptionHelpFormatter): else: default = action.dest.upper() args_string = self._format_args(action, default) - opt = ", ".join(action.option_strings) - parts.append("%s %s" % (opt, args_string)) - return ", ".join(parts) + opt = ', '.join(action.option_strings) + parts.append('%s %s' % (opt, args_string)) + return ', '.join(parts) class HelpAction(argparse._HelpAction): def __call__(self, parser, namespace, values, option_string=None): - if hasattr(parser, "subparser"): - subparser = getattr(parser, "subparser") + if hasattr(parser, 'subparser'): + subparser = getattr(parser, 'subparser') subparser.print_help() else: parser.print_help() @@ -152,42 +152,42 @@ class HelpAction(argparse._HelpAction): class BaseArgParser(argparse.ArgumentParser): def __init__(self, *args, **kwargs): - if "formatter_class" not in kwargs: - kwargs["formatter_class"] = lambda prog: DelugeTextHelpFormatter(prog, max_help_position=33, width=90) + if 'formatter_class' not in kwargs: + kwargs['formatter_class'] = lambda prog: DelugeTextHelpFormatter(prog, max_help_position=33, width=90) - kwargs["add_help"] = kwargs.get("add_help", False) - common_help = kwargs.pop("common_help", True) + kwargs['add_help'] = kwargs.get('add_help', False) + common_help = kwargs.pop('common_help', True) self.log_stream = sys.stdout - if "log_stream" in kwargs: - self.log_stream = kwargs["log_stream"] - del kwargs["log_stream"] + if 'log_stream' in kwargs: + self.log_stream = kwargs['log_stream'] + del kwargs['log_stream'] super(BaseArgParser, self).__init__(*args, **kwargs) self.common_setup = False self.process_arg_group = False - self.group = self.add_argument_group(_("Common Options")) + self.group = self.add_argument_group(_('Common Options')) if common_help: - self.group.add_argument("-h", "--help", action=HelpAction, - help=_("Print this help message")) - self.group.add_argument("-V", "--version", action="version", version="%(prog)s " + get_version(), - help=_("Print version information")) - self.group.add_argument("-v", action="version", version="%(prog)s " + get_version(), + self.group.add_argument('-h', '--help', action=HelpAction, + help=_('Print this help message')) + self.group.add_argument('-V', '--version', action='version', version='%(prog)s ' + get_version(), + help=_('Print version information')) + self.group.add_argument('-v', action='version', version='%(prog)s ' + get_version(), help=argparse.SUPPRESS) # Deprecated arg - self.group.add_argument("-c", "--config", metavar="<config>", - help=_("Set the config directory path")) - self.group.add_argument("-l", "--logfile", metavar="<logfile>", - help=_("Output to specified logfile instead of stdout")) - self.group.add_argument("-L", "--loglevel", choices=[l for k in deluge.log.levels for l in (k, k.upper())], - help=_("Set the log level (none, error, warning, info, debug)"), metavar="<level>") - self.group.add_argument("--logrotate", nargs="?", const="2M", metavar="<max-size>", - help=_("Enable logfile rotation, with optional maximum logfile size, " - "default: %(const)s (Logfile rotation count is 5)")) - self.group.add_argument("-q", "--quiet", action="store_true", - help=_("Quieten logging output (Same as `--loglevel none`)")) - self.group.add_argument("--profile", metavar="<profile-file>", nargs="?", default=False, - help=_("Profile %(prog)s with cProfile. Outputs to stdout " - "unless a filename is specified")) + self.group.add_argument('-c', '--config', metavar='<config>', + help=_('Set the config directory path')) + self.group.add_argument('-l', '--logfile', metavar='<logfile>', + help=_('Output to specified logfile instead of stdout')) + self.group.add_argument('-L', '--loglevel', choices=[l for k in deluge.log.levels for l in (k, k.upper())], + help=_('Set the log level (none, error, warning, info, debug)'), metavar='<level>') + self.group.add_argument('--logrotate', nargs='?', const='2M', metavar='<max-size>', + help=_('Enable logfile rotation, with optional maximum logfile size, ' + 'default: %(const)s (Logfile rotation count is 5)')) + self.group.add_argument('-q', '--quiet', action='store_true', + help=_('Quieten logging output (Same as `--loglevel none`)')) + self.group.add_argument('--profile', metavar='<profile-file>', nargs='?', default=False, + help=_('Profile %(prog)s with cProfile. Outputs to stdout ' + 'unless a filename is specified')) def parse_args(self, args=None): """Parse UI arguments and handle common and process group options. @@ -238,14 +238,14 @@ class BaseArgParser(argparse.ArgumentParser): # Setup the logger if options.quiet: - options.loglevel = "none" + options.loglevel = 'none' if options.loglevel: options.loglevel = options.loglevel.lower() - logfile_mode = "w" + logfile_mode = 'w' logrotate = options.logrotate if options.logrotate: - logfile_mode = "a" + logfile_mode = 'a' logrotate = common.parse_human_size(options.logrotate) # Setup the logger @@ -255,7 +255,7 @@ class BaseArgParser(argparse.ArgumentParser): if options.config: if not set_config_dir(options.config): log = logging.getLogger(__name__) - log.error("There was an error setting the config dir! Exiting..") + log.error('There was an error setting the config dir! Exiting..') sys.exit(1) else: if not os.path.exists(common.get_default_config_dir()): @@ -276,8 +276,8 @@ class BaseArgParser(argparse.ArgumentParser): # Write pid file before chuid if options.pidfile: - with open(options.pidfile, "wb") as _file: - _file.write("%d\n" % os.getpid()) + with open(options.pidfile, 'wb') as _file: + _file.write('%d\n' % os.getpid()) if not common.windows_check(): if options.user: @@ -297,15 +297,15 @@ class BaseArgParser(argparse.ArgumentParser): """Adds a grouping of common process args to control a daemon to the parser""" self.process_arg_group = True - self.group = self.add_argument_group(_("Process Control Options")) - self.group.add_argument("-P", "--pidfile", metavar="<pidfile>", action="store", - help=_("Pidfile to store the process id")) + self.group = self.add_argument_group(_('Process Control Options')) + self.group.add_argument('-P', '--pidfile', metavar='<pidfile>', action='store', + help=_('Pidfile to store the process id')) if not common.windows_check(): - self.group.add_argument("-d", "--do-not-daemonize", dest="donotdaemonize", action="store_true", - help=_("Do not daemonize (fork) this process")) - self.group.add_argument("-f", "--fork", dest="donotdaemonize", action="store_false", + self.group.add_argument('-d', '--do-not-daemonize', dest='donotdaemonize', action='store_true', + help=_('Do not daemonize (fork) this process')) + self.group.add_argument('-f', '--fork', dest='donotdaemonize', action='store_false', help=argparse.SUPPRESS) # Deprecated arg - self.group.add_argument("-U", "--user", metavar="<user>", action="store", - help=_("Change to this user on startup (Requires root)")) - self.group.add_argument("-g", "--group", metavar="<group>", action="store", - help=_("Change to this group on startup (Requires root)")) + self.group.add_argument('-U', '--user', metavar='<user>', action='store', + help=_('Change to this user on startup (Requires root)')) + self.group.add_argument('-g', '--group', metavar='<group>', action='store', + help=_('Change to this group on startup (Requires root)')) diff --git a/deluge/ui/client.py b/deluge/ui/client.py index 2ec72b086..a07f21d47 100644 --- a/deluge/ui/client.py +++ b/deluge/ui/client.py @@ -28,7 +28,7 @@ log = logging.getLogger(__name__) def format_kwargs(kwargs): - return ", ".join([key + "=" + str(value) for key, value in kwargs.items()]) + return ', '.join([key + '=' + str(value) for key, value in kwargs.items()]) class DelugeRPCRequest(object): @@ -47,14 +47,14 @@ class DelugeRPCRequest(object): Returns a string of the RPCRequest in the following form: method(arg, kwarg=foo, ...) """ - s = self.method + "(" + s = self.method + '(' if self.args: - s += ", ".join([str(x) for x in self.args]) + s += ', '.join([str(x) for x in self.args]) if self.kwargs: if self.args: - s += ", " + s += ', ' s += format_kwargs(self.kwargs) - s += ")" + s += ')' return s @@ -66,7 +66,7 @@ class DelugeRPCRequest(object): :returns: a properly formated RPCRequest """ if self.request_id is None or self.method is None or self.args is None or self.kwargs is None: - raise TypeError("You must set the properties of this object before calling format_message!") + raise TypeError('You must set the properties of this object before calling format_message!') return (self.request_id, self.method, self.args, self.kwargs) @@ -82,7 +82,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): self.factory.daemon.host = peer.host self.factory.daemon.port = peer.port self.factory.daemon.connected = True - log.debug("Connected to daemon at %s:%s..", peer.host, peer.port) + log.debug('Connected to daemon at %s:%s..', peer.host, peer.port) self.factory.daemon.connect_deferred.callback((peer.host, peer.port)) def message_received(self, request): @@ -93,11 +93,11 @@ class DelugeRPCProtocol(DelugeTransferProtocol): """ if not isinstance(request, tuple): - log.debug("Received invalid message: type is not tuple") + log.debug('Received invalid message: type is not tuple') return if len(request) < 3: - log.debug("Received invalid message: number of items in " - "response is %s", len(request)) + log.debug('Received invalid message: number of items in ' + 'response is %s', len(request)) return message_type = request[0] @@ -129,7 +129,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): exception_cls = getattr(error, request[2]) exception = exception_cls(*request[3], **request[4]) except TypeError: - log.warn("Received invalid RPC_ERROR (Old daemon?): %s", request[2]) + log.warn('Received invalid RPC_ERROR (Old daemon?): %s', request[2]) return # Ideally we would chain the deferreds instead of instance @@ -140,17 +140,17 @@ class DelugeRPCProtocol(DelugeTransferProtocol): # So, just do some instance checking and just log rpc error at # diferent levels. r = self.__rpc_requests[request_id] - msg = "RPCError Message Received!" - msg += "\n" + "-" * 80 - msg += "\n" + "RPCRequest: " + r.__repr__() - msg += "\n" + "-" * 80 + msg = 'RPCError Message Received!' + msg += '\n' + '-' * 80 + msg += '\n' + 'RPCRequest: ' + r.__repr__() + msg += '\n' + '-' * 80 if isinstance(exception, error.WrappedException): - msg += "\n" + exception.type + "\n" + exception.message + ": " + msg += '\n' + exception.type + '\n' + exception.message + ': ' msg += exception.traceback else: - msg += "\n" + request[5] + "\n" + request[2] + ": " + msg += '\n' + request[5] + '\n' + request[2] + ': ' msg += str(exception) - msg += "\n" + "-" * 80 + msg += '\n' + '-' * 80 if not isinstance(exception, error._ClientSideRecreateError): # Let's log these as errors @@ -161,7 +161,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): log.debug(msg) except Exception: import traceback - log.error("Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s", + log.error('Failed to handle RPC_ERROR (Old daemon?): %s\nLocal error: %s', request[2], traceback.format_exc()) d.errback(exception) del self.__rpc_requests[request_id] @@ -182,7 +182,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol): # Send the request in a tuple because multiple requests can be sent at once self.transfer_message((request.format_message(),)) except Exception as ex: - log.warn("Error occurred when sending message: %s", ex) + log.warn('Error occurred when sending message: %s', ex) class DelugeRPCClientFactory(ClientFactory): @@ -257,7 +257,7 @@ class DaemonSSLProxy(DaemonProxy): :returns: twisted.Deferred """ - log.debug("sslproxy.connect()") + log.debug('sslproxy.connect()') self.host = host self.port = port self.__connector = reactor.connectSSL(self.host, self.port, @@ -273,7 +273,7 @@ class DaemonSSLProxy(DaemonProxy): return self.daemon_info_deferred def disconnect(self): - log.debug("sslproxy.disconnect()") + log.debug('sslproxy.disconnect()') self.disconnect_deferred = defer.Deferred() self.__connector.disconnect() return self.disconnect_deferred @@ -340,7 +340,7 @@ class DaemonSSLProxy(DaemonProxy): # that we're interested in receiving this type of event self.__factory.event_handlers[event] = [] if self.connected: - self.call("daemon.set_event_interest", [event]) + self.call('daemon.set_event_interest', [event]) # Only add the handler if it's not already registered if handler not in self.__factory.event_handlers[event]: @@ -360,43 +360,43 @@ class DaemonSSLProxy(DaemonProxy): self.__factory.event_handlers[event].remove(handler) def __on_connect(self, result): - log.debug("__on_connect called") + log.debug('__on_connect called') def on_info(daemon_info): self.daemon_info = daemon_info - log.debug("Got info from daemon: %s", daemon_info) + log.debug('Got info from daemon: %s', daemon_info) self.daemon_info_deferred.callback(daemon_info) def on_info_fail(reason): - log.debug("Failed to get info from daemon") + log.debug('Failed to get info from daemon') log.exception(reason) self.daemon_info_deferred.errback(reason) - self.call("daemon.info").addCallback(on_info).addErrback(on_info_fail) + self.call('daemon.info').addCallback(on_info).addErrback(on_info_fail) return self.daemon_info_deferred def __on_connect_fail(self, reason): self.daemon_info_deferred.errback(reason) def authenticate(self, username, password): - log.debug("%s.authenticate: %s", self.__class__.__name__, username) + log.debug('%s.authenticate: %s', self.__class__.__name__, username) login_deferred = defer.Deferred() - d = self.call("daemon.login", username, password, + d = self.call('daemon.login', username, password, client_version=deluge.common.get_version()) d.addCallbacks(self.__on_login, self.__on_login_fail, callbackArgs=[username, login_deferred], errbackArgs=[login_deferred]) return login_deferred def __on_login(self, result, username, login_deferred): - log.debug("__on_login called: %s %s", username, result) + log.debug('__on_login called: %s %s', username, result) self.username = username self.authentication_level = result # We need to tell the daemon what events we're interested in receiving if self.__factory.event_handlers: - self.call("daemon.set_event_interest", + self.call('daemon.set_event_interest', self.__factory.event_handlers.keys()) - self.call("core.get_auth_levels_mappings").addCallback( + self.call('core.get_auth_levels_mappings').addCallback( self.__on_auth_levels_mappings ) @@ -431,15 +431,15 @@ class DaemonStandaloneProxy(DaemonProxy): from deluge.core import daemon self.__daemon = daemon.Daemon(standalone=True) self.__daemon.start() - log.debug("daemon created!") + log.debug('daemon created!') self.connected = True - self.host = "localhost" + self.host = 'localhost' self.port = 58846 # Running in standalone mode, it's safe to import auth level from deluge.core.authmanager import (AUTH_LEVEL_ADMIN, AUTH_LEVELS_MAPPING, AUTH_LEVELS_MAPPING_REVERSE) - self.username = "localclient" + self.username = 'localclient' self.authentication_level = AUTH_LEVEL_ADMIN self.auth_levels_mapping = AUTH_LEVELS_MAPPING self.auth_levels_mapping_reverse = AUTH_LEVELS_MAPPING_REVERSE @@ -506,7 +506,7 @@ class DottedObject(object): raise Exception("You must make calls in the form of 'component.method'!") def __getattr__(self, name): - return RemoteMethod(self.daemon, self.base + "." + name) + return RemoteMethod(self.daemon, self.base + '.' + name) class RemoteMethod(DottedObject): @@ -530,7 +530,7 @@ class Client(object): self.disconnect_callback = None self.__started_standalone = False - def connect(self, host="127.0.0.1", port=58846, username="", password="", + def connect(self, host='127.0.0.1', port=58846, username='', password='', skip_authentication=False): """ Connects to a daemon process. @@ -550,24 +550,24 @@ class Client(object): d = self._daemon_proxy.connect(host, port) def on_connected(daemon_version): - log.debug("on_connected. Daemon version: %s", daemon_version) + log.debug('on_connected. Daemon version: %s', daemon_version) return daemon_version def on_connect_fail(reason): - log.debug("on_connect_fail: %s", reason) + log.debug('on_connect_fail: %s', reason) self.disconnect() return reason def on_authenticate(result, daemon_info): - log.debug("Authentication successful: %s", result) + log.debug('Authentication successful: %s', result) return result def on_authenticate_fail(reason): - log.debug("Failed to authenticate: %s", reason.value) + log.debug('Failed to authenticate: %s', reason.value) return reason def authenticate(daemon_version, username, password): - if not username and host in ("127.0.0.1", "localhost"): + if not username and host in ('127.0.0.1', 'localhost'): # No username provided and it's localhost, so attempt to get credentials from auth file. username, password = get_localhost_auth() @@ -633,7 +633,7 @@ class Client(object): # subprocess.popen does not work with unicode args (with non-ascii characters) on windows config = config.encode(sys.getfilesystemencoding()) try: - subprocess.Popen(["deluged", "--port=%s" % port, "--config=%s" % config]) + subprocess.Popen(['deluged', '--port=%s' % port, '--config=%s' % config]) except OSError as ex: from errno import ENOENT if ex.errno == ENOENT: @@ -643,7 +643,7 @@ that you forgot to install the deluged package or it's not in your PATH.")) log.exception(ex) raise ex except Exception as ex: - log.error("Unable to start daemon!") + log.error('Unable to start daemon!') log.exception(ex) return False else: @@ -656,7 +656,7 @@ that you forgot to install the deluged package or it's not in your PATH.")) :returns: bool, True if connected to a localhost """ - if (self._daemon_proxy and self._daemon_proxy.host in ("127.0.0.1", "localhost") or + if (self._daemon_proxy and self._daemon_proxy.host in ('127.0.0.1', 'localhost') or isinstance(self._daemon_proxy, DaemonStandaloneProxy)): return True return False diff --git a/deluge/ui/common.py b/deluge/ui/common.py index 81bdd37bb..686963aee 100644 --- a/deluge/ui/common.py +++ b/deluge/ui/common.py @@ -33,75 +33,75 @@ def _(message): return message STATE_TRANSLATION = { - "All": _("All"), - "Active": _("Active"), - "Allocating": _("Allocating"), - "Checking": _("Checking"), - "Downloading": _("Downloading"), - "Seeding": _("Seeding"), - "Paused": _("Paused"), - "Queued": _("Queued"), - "Error": _("Error"), + 'All': _('All'), + 'Active': _('Active'), + 'Allocating': _('Allocating'), + 'Checking': _('Checking'), + 'Downloading': _('Downloading'), + 'Seeding': _('Seeding'), + 'Paused': _('Paused'), + 'Queued': _('Queued'), + 'Error': _('Error'), } TORRENT_DATA_FIELD = { - "queue": {"name": "#", "status": ["queue"]}, - "name": {"name": _("Name"), "status": ["state", "name"]}, - "progress_state": {"name": _("Progress"), "status": ["progress", "state"]}, - "state": {"name": _("State"), "status": ["state"]}, - "progress": {"name": _("Progress"), "status": ["progress"]}, - "size": {"name": _("Size"), "status": ["total_wanted"]}, - "downloaded": {"name": _("Downloaded"), "status": ["all_time_download"]}, - "uploaded": {"name": _("Uploaded"), "status": ["total_uploaded"]}, - "remaining": {"name": _("Remaining"), "status": ["total_remaining"]}, - "ratio": {"name": _("Ratio"), "status": ["ratio"]}, - "download_speed": {"name": _("Down Speed"), "status": ["download_payload_rate"]}, - "upload_speed": {"name": _("Up Speed"), "status": ["upload_payload_rate"]}, - "max_download_speed": {"name": _("Down Limit"), "status": ["max_download_speed"]}, - "max_upload_speed": {"name": _("Up Limit"), "status": ["max_upload_speed"]}, - "max_connections": {"name": _("Max Connections"), "status": ["max_connections"]}, - "max_upload_slots": {"name": _("Max Upload Slots"), "status": ["max_upload_slots"]}, - "peers": {"name": _("Peers"), "status": ["num_peers", "total_peers"]}, - "seeds": {"name": _("Seeds"), "status": ["num_seeds", "total_seeds"]}, - "avail": {"name": _("Avail"), "status": ["distributed_copies"]}, - "seeds_peers_ratio": {"name": _("Seeds:Peers"), "status": ["seeds_peers_ratio"]}, - "time_added": {"name": _("Added"), "status": ["time_added"]}, - "tracker": {"name": _("Tracker"), "status": ["tracker_host"]}, - "download_location": {"name": _("Download Folder"), "status": ["download_location"]}, - "seeding_time": {"name": _("Seeding Time"), "status": ["seeding_time"]}, - "active_time": {"name": _("Active Time"), "status": ["active_time"]}, - "finished_time": {"name": _("Finished Time"), "status": ["finished_time"]}, - "last_seen_complete": {"name": _("Complete Seen"), "status": ["last_seen_complete"]}, - "completed_time": {"name": _("Completed"), "status": ["completed_time"]}, - "eta": {"name": _("ETA"), "status": ["eta"]}, - "shared": {"name": _("Shared"), "status": ["shared"]}, - "prioritize_first_last": {"name": _("Prioritize First/Last"), "status": ["prioritize_first_last"]}, - "sequential_download": {"name": _("Sequential Download"), "status": ["sequential_download"]}, - "is_auto_managed": {"name": _("Auto Managed"), "status": ["is_auto_managed"]}, - "auto_managed": {"name": _("Auto Managed"), "status": ["auto_managed"]}, - "stop_at_ratio": {"name": _("Stop At Ratio"), "status": ["stop_at_ratio"]}, - "stop_ratio": {"name": _("Stop Ratio"), "status": ["stop_ratio"]}, - "remove_at_ratio": {"name": _("Remove At Ratio"), "status": ["remove_at_ratio"]}, - "move_completed": {"name": _("Move On Completed"), "status": ["move_completed"]}, - "move_completed_path": {"name": _("Move Completed Path"), "status": ["move_completed_path"]}, - "move_on_completed": {"name": _("Move On Completed"), "status": ["move_on_completed"]}, - "move_on_completed_path": {"name": _("Move On Completed Path"), "status": ["move_on_completed_path"]}, - "owner": {"name": _("Owner"), "status": ["owner"]} + 'queue': {'name': '#', 'status': ['queue']}, + 'name': {'name': _('Name'), 'status': ['state', 'name']}, + 'progress_state': {'name': _('Progress'), 'status': ['progress', 'state']}, + 'state': {'name': _('State'), 'status': ['state']}, + 'progress': {'name': _('Progress'), 'status': ['progress']}, + 'size': {'name': _('Size'), 'status': ['total_wanted']}, + 'downloaded': {'name': _('Downloaded'), 'status': ['all_time_download']}, + 'uploaded': {'name': _('Uploaded'), 'status': ['total_uploaded']}, + 'remaining': {'name': _('Remaining'), 'status': ['total_remaining']}, + 'ratio': {'name': _('Ratio'), 'status': ['ratio']}, + 'download_speed': {'name': _('Down Speed'), 'status': ['download_payload_rate']}, + 'upload_speed': {'name': _('Up Speed'), 'status': ['upload_payload_rate']}, + 'max_download_speed': {'name': _('Down Limit'), 'status': ['max_download_speed']}, + 'max_upload_speed': {'name': _('Up Limit'), 'status': ['max_upload_speed']}, + 'max_connections': {'name': _('Max Connections'), 'status': ['max_connections']}, + 'max_upload_slots': {'name': _('Max Upload Slots'), 'status': ['max_upload_slots']}, + 'peers': {'name': _('Peers'), 'status': ['num_peers', 'total_peers']}, + 'seeds': {'name': _('Seeds'), 'status': ['num_seeds', 'total_seeds']}, + 'avail': {'name': _('Avail'), 'status': ['distributed_copies']}, + 'seeds_peers_ratio': {'name': _('Seeds:Peers'), 'status': ['seeds_peers_ratio']}, + 'time_added': {'name': _('Added'), 'status': ['time_added']}, + 'tracker': {'name': _('Tracker'), 'status': ['tracker_host']}, + 'download_location': {'name': _('Download Folder'), 'status': ['download_location']}, + 'seeding_time': {'name': _('Seeding Time'), 'status': ['seeding_time']}, + 'active_time': {'name': _('Active Time'), 'status': ['active_time']}, + 'finished_time': {'name': _('Finished Time'), 'status': ['finished_time']}, + 'last_seen_complete': {'name': _('Complete Seen'), 'status': ['last_seen_complete']}, + 'completed_time': {'name': _('Completed'), 'status': ['completed_time']}, + 'eta': {'name': _('ETA'), 'status': ['eta']}, + 'shared': {'name': _('Shared'), 'status': ['shared']}, + 'prioritize_first_last': {'name': _('Prioritize First/Last'), 'status': ['prioritize_first_last']}, + 'sequential_download': {'name': _('Sequential Download'), 'status': ['sequential_download']}, + 'is_auto_managed': {'name': _('Auto Managed'), 'status': ['is_auto_managed']}, + 'auto_managed': {'name': _('Auto Managed'), 'status': ['auto_managed']}, + 'stop_at_ratio': {'name': _('Stop At Ratio'), 'status': ['stop_at_ratio']}, + 'stop_ratio': {'name': _('Stop Ratio'), 'status': ['stop_ratio']}, + 'remove_at_ratio': {'name': _('Remove At Ratio'), 'status': ['remove_at_ratio']}, + 'move_completed': {'name': _('Move On Completed'), 'status': ['move_completed']}, + 'move_completed_path': {'name': _('Move Completed Path'), 'status': ['move_completed_path']}, + 'move_on_completed': {'name': _('Move On Completed'), 'status': ['move_on_completed']}, + 'move_on_completed_path': {'name': _('Move On Completed Path'), 'status': ['move_on_completed_path']}, + 'owner': {'name': _('Owner'), 'status': ['owner']} } TRACKER_STATUS_TRANSLATION = { - "Error": _("Error"), - "Warning": _("Warning"), - "Announce OK": _("Announce OK"), - "Announce Sent": _("Announce Sent") + 'Error': _('Error'), + 'Warning': _('Warning'), + 'Announce OK': _('Announce OK'), + 'Announce Sent': _('Announce Sent') } del _ -DEFAULT_HOST = "127.0.0.1" +DEFAULT_HOST = '127.0.0.1' DEFAULT_PORT = 58846 DEFAULT_HOSTS = { - "hosts": [(sha(str(time.time())).hexdigest(), DEFAULT_HOST, DEFAULT_PORT, "", "")] + 'hosts': [(sha(str(time.time())).hexdigest(), DEFAULT_HOST, DEFAULT_PORT, '', '')] } @@ -116,73 +116,73 @@ class TorrentInfo(object): def __init__(self, filename, filetree=1): # Get the torrent data from the torrent file try: - log.debug("Attempting to open %s.", filename) - with open(filename, "rb") as _file: + log.debug('Attempting to open %s.', filename) + with open(filename, 'rb') as _file: self.__m_filedata = _file.read() except IOError as ex: - log.warning("Unable to open %s: %s", filename, ex) + log.warning('Unable to open %s: %s', filename, ex) raise ex try: self.__m_metadata = bencode.bdecode(self.__m_filedata) except bencode.BTFailure as ex: - log.warning("Failed to decode %s: %s", filename, ex) + log.warning('Failed to decode %s: %s', filename, ex) raise ex - self.__m_info_hash = sha(bencode.bencode(self.__m_metadata["info"])).hexdigest() + self.__m_info_hash = sha(bencode.bencode(self.__m_metadata['info'])).hexdigest() # Get encoding from torrent file if available self.encoding = None - if "encoding" in self.__m_metadata: - self.encoding = self.__m_metadata["encoding"] - elif "codepage" in self.__m_metadata: - self.encoding = str(self.__m_metadata["codepage"]) + if 'encoding' in self.__m_metadata: + self.encoding = self.__m_metadata['encoding'] + elif 'codepage' in self.__m_metadata: + self.encoding = str(self.__m_metadata['codepage']) if not self.encoding: - self.encoding = "UTF-8" + self.encoding = 'UTF-8' # Check if 'name.utf-8' is in the torrent and if not try to decode the string # using the encoding found. - if "name.utf-8" in self.__m_metadata["info"]: - self.__m_name = utf8_encoded(self.__m_metadata["info"]["name.utf-8"]) + if 'name.utf-8' in self.__m_metadata['info']: + self.__m_name = utf8_encoded(self.__m_metadata['info']['name.utf-8']) else: - self.__m_name = utf8_encoded(self.__m_metadata["info"]["name"], self.encoding) + self.__m_name = utf8_encoded(self.__m_metadata['info']['name'], self.encoding) # Get list of files from torrent info paths = {} dirs = {} - if "files" in self.__m_metadata["info"]: - prefix = "" - if len(self.__m_metadata["info"]["files"]) > 1: + if 'files' in self.__m_metadata['info']: + prefix = '' + if len(self.__m_metadata['info']['files']) > 1: prefix = self.__m_name - for index, f in enumerate(self.__m_metadata["info"]["files"]): - if "path.utf-8" in f: - path = os.path.join(prefix, *f["path.utf-8"]) - del f["path.utf-8"] + for index, f in enumerate(self.__m_metadata['info']['files']): + if 'path.utf-8' in f: + path = os.path.join(prefix, *f['path.utf-8']) + del f['path.utf-8'] else: - path = utf8_encoded(os.path.join(prefix, utf8_encoded(os.path.join(*f["path"]), + path = utf8_encoded(os.path.join(prefix, utf8_encoded(os.path.join(*f['path']), self.encoding)), self.encoding) - f["path"] = path - f["index"] = index - if "sha1" in f and len(f["sha1"]) == 20: - f["sha1"] = f["sha1"].encode('hex') - if "ed2k" in f and len(f["ed2k"]) == 16: - f["ed2k"] = f["ed2k"].encode('hex') - if "filehash" in f and len(f["filehash"]) == 20: - f["filehash"] = f["filehash"].encode('hex') + f['path'] = path + f['index'] = index + if 'sha1' in f and len(f['sha1']) == 20: + f['sha1'] = f['sha1'].encode('hex') + if 'ed2k' in f and len(f['ed2k']) == 16: + f['ed2k'] = f['ed2k'].encode('hex') + if 'filehash' in f and len(f['filehash']) == 20: + f['filehash'] = f['filehash'].encode('hex') paths[path] = f dirname = os.path.dirname(path) while dirname: dirinfo = dirs.setdefault(dirname, {}) - dirinfo["length"] = dirinfo.get("length", 0) + f["length"] + dirinfo['length'] = dirinfo.get('length', 0) + f['length'] dirname = os.path.dirname(dirname) if filetree == 2: def walk(path, item): - if item["type"] == "dir": + if item['type'] == 'dir': item.update(dirs[path]) else: item.update(paths[path]) - item["download"] = True + item['download'] = True file_tree = FileTree2(paths.keys()) file_tree.walk(walk) @@ -190,7 +190,7 @@ class TorrentInfo(object): def walk(path, item): if isinstance(item, dict): return item - return [paths[path]["index"], paths[path]["length"], True] + return [paths[path]['index'], paths[path]['length'], True] file_tree = FileTree(paths) file_tree.walk(walk) @@ -198,37 +198,37 @@ class TorrentInfo(object): else: if filetree == 2: self.__m_files_tree = { - "contents": { + 'contents': { self.__m_name: { - "type": "file", - "index": 0, - "length": self.__m_metadata["info"]["length"], - "download": True + 'type': 'file', + 'index': 0, + 'length': self.__m_metadata['info']['length'], + 'download': True } } } else: self.__m_files_tree = { - self.__m_name: (0, self.__m_metadata["info"]["length"], True) + self.__m_name: (0, self.__m_metadata['info']['length'], True) } self.__m_files = [] - if "files" in self.__m_metadata["info"]: - prefix = "" - if len(self.__m_metadata["info"]["files"]) > 1: + if 'files' in self.__m_metadata['info']: + prefix = '' + if len(self.__m_metadata['info']['files']) > 1: prefix = self.__m_name - for f in self.__m_metadata["info"]["files"]: + for f in self.__m_metadata['info']['files']: self.__m_files.append({ - 'path': f["path"], - 'size': f["length"], + 'path': f['path'], + 'size': f['length'], 'download': True }) else: self.__m_files.append({ - "path": self.__m_name, - "size": self.__m_metadata["info"]["length"], - "download": True + 'path': self.__m_name, + 'size': self.__m_metadata['info']['length'], + 'download': True }) def as_dict(self, *keys): @@ -314,33 +314,33 @@ class FileTree2(object): """ def __init__(self, paths): - self.tree = {"contents": {}, "type": "dir"} + self.tree = {'contents': {}, 'type': 'dir'} def get_parent(path): parent = self.tree - while "/" in path: - directory, path = path.split("/", 1) - child = parent["contents"].get(directory) + while '/' in path: + directory, path = path.split('/', 1) + child = parent['contents'].get(directory) if child is None: - parent["contents"][directory] = { - "type": "dir", - "contents": {} + parent['contents'][directory] = { + 'type': 'dir', + 'contents': {} } - parent = parent["contents"][directory] + parent = parent['contents'][directory] return parent, path for path in paths: - if path[-1] == "/": + if path[-1] == '/': path = path[:-1] parent, path = get_parent(path) - parent["contents"][path] = { - "type": "dir", - "contents": {} + parent['contents'][path] = { + 'type': 'dir', + 'contents': {} } else: parent, path = get_parent(path) - parent["contents"][path] = { - "type": "file" + parent['contents'][path] = { + 'type': 'file' } def get_tree(self): @@ -363,29 +363,29 @@ class FileTree2(object): :type callback: function """ def walk(directory, parent_path): - for path in directory["contents"].keys(): - full_path = os.path.join(parent_path, path).replace("\\", "/") - if directory["contents"][path]["type"] == "dir": - directory["contents"][path] = callback( - full_path, directory["contents"][path] - ) or directory["contents"][path] - walk(directory["contents"][path], full_path) + for path in directory['contents'].keys(): + full_path = os.path.join(parent_path, path).replace('\\', '/') + if directory['contents'][path]['type'] == 'dir': + directory['contents'][path] = callback( + full_path, directory['contents'][path] + ) or directory['contents'][path] + walk(directory['contents'][path], full_path) else: - directory["contents"][path] = callback( - full_path, directory["contents"][path] - ) or directory["contents"][path] - walk(self.tree, "") + directory['contents'][path] = callback( + full_path, directory['contents'][path] + ) or directory['contents'][path] + walk(self.tree, '') def __str__(self): lines = [] def write(path, item): - depth = path.count("/") + depth = path.count('/') path = os.path.basename(path) - path = path + "/" if item["type"] == "dir" else path - lines.append(" " * depth + path) + path = path + '/' if item['type'] == 'dir' else path + lines.append(' ' * depth + path) self.walk(write) - return "\n".join(lines) + return '\n'.join(lines) class FileTree(object): @@ -401,8 +401,8 @@ class FileTree(object): def get_parent(path): parent = self.tree - while "/" in path: - directory, path = path.split("/", 1) + while '/' in path: + directory, path = path.split('/', 1) child = parent.get(directory) if child is None: parent[directory] = {} @@ -410,7 +410,7 @@ class FileTree(object): return parent, path for path in paths: - if path[-1] == "/": + if path[-1] == '/': path = path[:-1] parent, path = get_parent(path) parent[path] = {} @@ -450,18 +450,18 @@ class FileTree(object): walk(directory[path], full_path) else: directory[path] = callback(full_path, directory[path]) or directory[path] - walk(self.tree, "") + walk(self.tree, '') def __str__(self): lines = [] def write(path, item): - depth = path.count("/") + depth = path.count('/') path = os.path.basename(path) - path = isinstance(item, dict) and path + "/" or path - lines.append(" " * depth + path) + path = isinstance(item, dict) and path + '/' or path + lines.append(' ' * depth + path) self.walk(write) - return "\n".join(lines) + return '\n'.join(lines) def get_localhost_auth(): @@ -471,7 +471,7 @@ def get_localhost_auth(): :returns: with the username and password to login as :rtype: tuple """ - auth_file = deluge.configmanager.get_config_dir("auth") + auth_file = deluge.configmanager.get_config_dir('auth') if not os.path.exists(auth_file): from deluge.common import create_localclient_account create_localclient_account() @@ -479,19 +479,19 @@ def get_localhost_auth(): with open(auth_file) as auth: for line in auth: line = line.strip() - if line.startswith("#") or not line: + if line.startswith('#') or not line: # This is a comment or blank line continue - lsplit = line.split(":") + lsplit = line.split(':') if len(lsplit) == 2: username, password = lsplit elif len(lsplit) == 3: username, password, level = lsplit else: - log.error("Your auth file is malformed: Incorrect number of fields!") + log.error('Your auth file is malformed: Incorrect number of fields!') continue - if username == "localclient": + if username == 'localclient': return (username, password) diff --git a/deluge/ui/console/cmdline/command.py b/deluge/ui/console/cmdline/command.py index 2dfe87e84..bacd05ab2 100644 --- a/deluge/ui/console/cmdline/command.py +++ b/deluge/ui/console/cmdline/command.py @@ -65,17 +65,17 @@ class Commander(object): """ if not cmd_line: return - cmd, _, line = cmd_line.partition(" ") + cmd, _, line = cmd_line.partition(' ') try: parser = self._commands[cmd].create_parser() except KeyError: - self.write("{!error!}Unknown command: %s" % cmd) + self.write('{!error!}Unknown command: %s' % cmd) return try: args = [cmd] + self._commands[cmd].split(line) except ValueError as ex: - self.write("{!error!}Error parsing command: %s" % ex) + self.write('{!error!}Error parsing command: %s' % ex) return # Do a little hack here to print 'command --help' properly @@ -89,32 +89,32 @@ class Commander(object): parser.print_help = print_help # Only these commands can be run when not connected to a daemon - not_connected_cmds = ["help", "connect", "quit"] + not_connected_cmds = ['help', 'connect', 'quit'] aliases = [] for c in not_connected_cmds: aliases.extend(self._commands[c].aliases) not_connected_cmds.extend(aliases) if not client.connected() and cmd not in not_connected_cmds: - self.write("{!error!}Not connected to a daemon, please use the connect command first.") + self.write('{!error!}Not connected to a daemon, please use the connect command first.') return try: options = parser.parse_args(args=args) options.command = cmd except TypeError as ex: - self.write("{!error!}Error parsing options: %s" % ex) + self.write('{!error!}Error parsing options: %s' % ex) import traceback - self.write("%s" % traceback.format_exc()) + self.write('%s' % traceback.format_exc()) return except OptionParserError as ex: import traceback log.warn("Error parsing command '%s': %s", args, ex) - self.write("{!error!} %s" % ex) + self.write('{!error!} %s' % ex) parser.print_help() return - if getattr(parser, "_exit", False): + if getattr(parser, '_exit', False): return return options @@ -131,10 +131,10 @@ class Commander(object): try: ret = self._commands[options.command].handle(options) except Exception as ex: # pylint: disable=broad-except - self.write("{!error!} %s" % ex) + self.write('{!error!} %s' % ex) log.exception(ex) import traceback - self.write("%s" % traceback.format_exc()) + self.write('%s' % traceback.format_exc()) return defer.succeed(True) else: return ret @@ -145,8 +145,8 @@ class BaseCommand(object): usage = None interactive_only = False aliases = [] - _name = "base" - epilog = "" + _name = 'base' + epilog = '' def complete(self, text, *args): return [] @@ -160,7 +160,7 @@ class BaseCommand(object): @property def name_with_alias(self): - return "/".join([self._name] + self.aliases) + return '/'.join([self._name] + self.aliases) @property def description(self): @@ -168,27 +168,27 @@ class BaseCommand(object): def split(self, text): if windows_check(): - text = text.replace("\\", "\\\\") + text = text.replace('\\', '\\\\') result = shlex.split(text) for i, s in enumerate(result): - result[i] = s.replace(r"\ ", " ") - result = [s for s in result if s != ""] + result[i] = s.replace(r'\ ', ' ') + result = [s for s in result if s != ''] return result def create_parser(self): - opts = {"prog": self.name_with_alias, "description": self.__doc__, "epilog": self.epilog} + opts = {'prog': self.name_with_alias, 'description': self.__doc__, 'epilog': self.epilog} if self.usage: - opts["usage"] = self.usage + opts['usage'] = self.usage parser = OptionParser(**opts) - parser.add_argument(self.name, metavar="") + parser.add_argument(self.name, metavar='') parser.base_parser = parser self.add_arguments(parser) return parser def add_subparser(self, subparsers): - opts = {"prog": self.name_with_alias, "help": self.__doc__, "description": self.__doc__} + opts = {'prog': self.name_with_alias, 'help': self.__doc__, 'description': self.__doc__} if self.usage: - opts["usage"] = self.usage + opts['usage'] = self.usage parser = subparsers.add_parser(self.name, **opts) self.add_arguments(parser) diff --git a/deluge/ui/console/cmdline/commands/add.py b/deluge/ui/console/cmdline/commands/add.py index c34eaa492..ee25591e1 100644 --- a/deluge/ui/console/cmdline/commands/add.py +++ b/deluge/ui/console/cmdline/commands/add.py @@ -26,25 +26,25 @@ class Command(BaseCommand): """Add torrents""" def add_arguments(self, parser): - parser.add_argument("-p", "--path", dest="path", help=_("download folder for torrent")) - parser.add_argument("torrents", metavar="<torrent>", nargs="+", - help=_("One or more torrent files, URLs or magnet URIs")) + parser.add_argument('-p', '--path', dest='path', help=_('download folder for torrent')) + parser.add_argument('torrents', metavar='<torrent>', nargs='+', + help=_('One or more torrent files, URLs or magnet URIs')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') t_options = {} if options.path: - t_options["download_location"] = os.path.expanduser(options.path) + t_options['download_location'] = os.path.expanduser(options.path) def on_success(result): if not result: - self.console.write("{!error!}Torrent was not added: Already in session") + self.console.write('{!error!}Torrent was not added: Already in session') else: - self.console.write("{!success!}Torrent added!") + self.console.write('{!success!}Torrent added!') def on_fail(result): - self.console.write("{!error!}Torrent was not added: %s" % result) + self.console.write('{!error!}Torrent was not added: %s' % result) # Keep a list of deferreds to make a DeferredList deferreds = [] @@ -52,27 +52,27 @@ class Command(BaseCommand): if not torrent.strip(): continue if deluge.common.is_url(torrent): - self.console.write("{!info!}Attempting to add torrent from url: %s" % torrent) + self.console.write('{!info!}Attempting to add torrent from url: %s' % torrent) deferreds.append(client.core.add_torrent_url(torrent, t_options).addCallback(on_success).addErrback( on_fail)) elif deluge.common.is_magnet(torrent): - self.console.write("{!info!}Attempting to add torrent from magnet uri: %s" % torrent) + self.console.write('{!info!}Attempting to add torrent from magnet uri: %s' % torrent) deferreds.append(client.core.add_torrent_magnet(torrent, t_options).addCallback(on_success).addErrback( on_fail)) else: # Just a file - if urlparse(torrent).scheme == "file": + if urlparse(torrent).scheme == 'file': torrent = url2pathname(urlparse(torrent).path) path = os.path.abspath(os.path.expanduser(torrent)) if not os.path.exists(path): self.console.write("{!error!}%s doesn't exist!" % path) continue if not os.path.isfile(path): - self.console.write("{!error!}This is a directory!") + self.console.write('{!error!}This is a directory!') continue - self.console.write("{!info!}Attempting to add torrent: %s" % path) + self.console.write('{!info!}Attempting to add torrent: %s' % path) filename = os.path.split(path)[-1] - with open(path, "rb") as _file: + with open(path, 'rb') as _file: filedump = base64.encodestring(_file.read()) deferreds.append(client.core.add_torrent_file(filename, filedump, t_options).addCallback( on_success).addErrback(on_fail)) @@ -80,4 +80,4 @@ class Command(BaseCommand): return defer.DeferredList(deferreds) def complete(self, line): - return component.get("ConsoleUI").tab_complete_path(line, ext=".torrent", sort="date") + return component.get('ConsoleUI').tab_complete_path(line, ext='.torrent', sort='date') diff --git a/deluge/ui/console/cmdline/commands/cache.py b/deluge/ui/console/cmdline/commands/cache.py index 158cfca5d..abcce523c 100644 --- a/deluge/ui/console/cmdline/commands/cache.py +++ b/deluge/ui/console/cmdline/commands/cache.py @@ -17,11 +17,11 @@ class Command(BaseCommand): """Show information about the disk cache""" def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') def on_cache_status(status): for key, value in status.items(): - self.console.write("{!info!}%s: {!input!}%s" % (key, value)) + self.console.write('{!info!}%s: {!input!}%s' % (key, value)) d = client.core.get_cache_status() d.addCallback(on_cache_status) diff --git a/deluge/ui/console/cmdline/commands/config.py b/deluge/ui/console/cmdline/commands/config.py index 48333575e..3ac0b94a8 100644 --- a/deluge/ui/console/cmdline/commands/config.py +++ b/deluge/ui/console/cmdline/commands/config.py @@ -23,18 +23,18 @@ log = logging.getLogger(__name__) def atom(src, token): """taken with slight modifications from http://effbot.org/zone/simple-iterator-parser.htm""" - if token[1] == "(": + if token[1] == '(': out = [] token = next(src) - while token[1] != ")": + while token[1] != ')': out.append(atom(src, token)) token = next(src) - if token[1] == ",": + if token[1] == ',': token = next(src) return tuple(out) - elif token[0] is tokenize.NUMBER or token[1] == "-": + elif token[0] is tokenize.NUMBER or token[1] == '-': try: - if token[1] == "-": + if token[1] == '-': return int(token[-1], 0) else: return int(token[1], 0) @@ -43,14 +43,14 @@ def atom(src, token): return float(token[-1]) except ValueError: return str(token[-1]) - elif token[1].lower() == "true": + elif token[1].lower() == 'true': return True - elif token[1].lower() == "false": + elif token[1].lower() == 'false': return False - elif token[0] is tokenize.STRING or token[1] == "/": - return token[-1].decode("string-escape") + elif token[0] is tokenize.STRING or token[1] == '/': + return token[-1].decode('string-escape') - raise SyntaxError("malformed expression (%s)" % token[1]) + raise SyntaxError('malformed expression (%s)' % token[1]) def simple_eval(source): @@ -66,17 +66,17 @@ def simple_eval(source): class Command(BaseCommand): """Show and set configuration values""" - usage = _("Usage: config [--set <key> <value>] [<key> [<key>...] ]") + usage = _('Usage: config [--set <key> <value>] [<key> [<key>...] ]') def add_arguments(self, parser): - set_group = parser.add_argument_group("setting a value") - set_group.add_argument("-s", "--set", action="store", metavar="<key>", help=_("set value for this key")) - set_group.add_argument("values", metavar="<value>", nargs="+", help=_("Value to set")) - get_group = parser.add_argument_group("getting values") - get_group.add_argument("keys", metavar="<keys>", nargs="*", help=_("one or more keys separated by space")) + set_group = parser.add_argument_group('setting a value') + set_group.add_argument('-s', '--set', action='store', metavar='<key>', help=_('set value for this key')) + set_group.add_argument('values', metavar='<value>', nargs='+', help=_('Value to set')) + get_group = parser.add_argument_group('getting values') + get_group.add_argument('keys', metavar='<keys>', nargs='*', help=_('one or more keys separated by space')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') if options.set: return self._set_config(options) else: @@ -85,11 +85,11 @@ class Command(BaseCommand): def _get_config(self, options): def _on_get_config(config): keys = sorted(config.keys()) - s = "" + s = '' for key in keys: if key not in options.values: continue - color = "{!white,black,bold!}" + color = '{!white,black,bold!}' value = config[key] try: color = colors.type_color[type(value)] @@ -102,23 +102,23 @@ class Command(BaseCommand): value = pprint.pformat(value, 2, 80) new_value = [] for line in value.splitlines(): - new_value.append("%s%s" % (color, line)) - value = "\n".join(new_value) + new_value.append('%s%s' % (color, line)) + value = '\n'.join(new_value) - s += "%s: %s%s\n" % (key, color, value) + s += '%s: %s%s\n' % (key, color, value) self.console.write(s.strip()) return client.core.get_config().addCallback(_on_get_config) def _set_config(self, options): - config = component.get("CoreConfig") + config = component.get('CoreConfig') key = options.set - val = " ".join(options.values) + val = ' '.join(options.values) try: val = simple_eval(val) except SyntaxError as ex: - self.console.write("{!error!}%s" % ex) + self.console.write('{!error!}%s' % ex) return if key not in config.keys(): @@ -129,14 +129,14 @@ class Command(BaseCommand): try: val = type(config[key])(val) except TypeError: - self.config.write("{!error!}Configuration value provided has incorrect type.") + self.config.write('{!error!}Configuration value provided has incorrect type.') return def on_set_config(result): - self.console.write("{!success!}Configuration value successfully updated.") + self.console.write('{!success!}Configuration value successfully updated.') self.console.write("Setting '%s' to '%s'" % (key, val)) return client.core.set_config({key: val}).addCallback(on_set_config) def complete(self, text): - return [k for k in component.get("CoreConfig").keys() if k.startswith(text)] + return [k for k in component.get('CoreConfig').keys() if k.startswith(text)] diff --git a/deluge/ui/console/cmdline/commands/connect.py b/deluge/ui/console/cmdline/commands/connect.py index 77fbf0bbc..d7d26e0c7 100644 --- a/deluge/ui/console/cmdline/commands/connect.py +++ b/deluge/ui/console/cmdline/commands/connect.py @@ -21,23 +21,23 @@ log = logging.getLogger(__name__) class Command(BaseCommand): """Connect to a new deluge server.""" - usage = _("Usage: connect <host[:port]> [<username>] [<password>]") + usage = _('Usage: connect <host[:port]> [<username>] [<password>]') def add_arguments(self, parser): - parser.add_argument("host", help=_("Daemon host and port"), metavar="<host[:port]>") - parser.add_argument("username", help=_("Username"), metavar="<username>", nargs="?", default="") - parser.add_argument("password", help=_("Password"), metavar="<password>", nargs="?", default="") + parser.add_argument('host', help=_('Daemon host and port'), metavar='<host[:port]>') + parser.add_argument('username', help=_('Username'), metavar='<username>', nargs='?', default='') + parser.add_argument('password', help=_('Password'), metavar='<password>', nargs='?', default='') def add_parser(self, subparsers): - parser = subparsers.add_parser(self.name, help=self.__doc__, description=self.__doc__, prog="connect") + parser = subparsers.add_parser(self.name, help=self.__doc__, description=self.__doc__, prog='connect') self.add_arguments(parser) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') host = options.host try: - host, port = host.split(":") + host, port = host.split(':') port = int(port) except ValueError: port = 58846 @@ -47,7 +47,7 @@ class Command(BaseCommand): def on_connect(result): if self.console.interactive: - self.console.write("{!success!}Connected to %s:%s!" % (host, port)) + self.console.write('{!success!}Connected to %s:%s!' % (host, port)) return component.start() def on_connect_fail(result): @@ -55,7 +55,7 @@ class Command(BaseCommand): msg = result.value.exception_msg except AttributeError: msg = result.value.message - self.console.write("{!error!}Failed to connect to %s:%s with reason: %s" % (host, port, msg)) + self.console.write('{!error!}Failed to connect to %s:%s with reason: %s' % (host, port, msg)) return result d.addCallbacks(on_connect, on_connect_fail) diff --git a/deluge/ui/console/cmdline/commands/debug.py b/deluge/ui/console/cmdline/commands/debug.py index 04a3f47ad..b8647abc1 100644 --- a/deluge/ui/console/cmdline/commands/debug.py +++ b/deluge/ui/console/cmdline/commands/debug.py @@ -20,17 +20,17 @@ class Command(BaseCommand): """Enable and disable debugging""" def add_arguments(self, parser): - parser.add_argument("state", metavar="<on|off>", choices=["on", "off"], help=_("The new state")) + parser.add_argument('state', metavar='<on|off>', choices=['on', 'off'], help=_('The new state')) def handle(self, options): - if options.state == "on": - deluge.log.set_logger_level("debug") - elif options.state == "off": - deluge.log.set_logger_level("error") + if options.state == 'on': + deluge.log.set_logger_level('debug') + elif options.state == 'off': + deluge.log.set_logger_level('error') else: - component.get("ConsoleUI").write("{!error!}%s" % self.usage) + component.get('ConsoleUI').write('{!error!}%s' % self.usage) return defer.succeed(True) def complete(self, text): - return [x for x in ["on", "off"] if x.startswith(text)] + return [x for x in ['on', 'off'] if x.startswith(text)] diff --git a/deluge/ui/console/cmdline/commands/gui.py b/deluge/ui/console/cmdline/commands/gui.py index d4726732a..3b91a22a6 100644 --- a/deluge/ui/console/cmdline/commands/gui.py +++ b/deluge/ui/console/cmdline/commands/gui.py @@ -21,7 +21,7 @@ class Command(BaseCommand): interactive_only = True def handle(self, options): - console = component.get("ConsoleUI") - at = console.set_mode("TorrentList") + console = component.get('ConsoleUI') + at = console.set_mode('TorrentList') at.go_top = True at.resume() diff --git a/deluge/ui/console/cmdline/commands/halt.py b/deluge/ui/console/cmdline/commands/halt.py index 75bade966..471af73ad 100644 --- a/deluge/ui/console/cmdline/commands/halt.py +++ b/deluge/ui/console/cmdline/commands/halt.py @@ -15,15 +15,15 @@ from . import BaseCommand class Command(BaseCommand): - "Shutdown the deluge server" + 'Shutdown the deluge server' def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') def on_shutdown(result): - self.console.write("{!success!}Daemon was shutdown") + self.console.write('{!success!}Daemon was shutdown') def on_shutdown_fail(reason): - self.console.write("{!error!}Unable to shutdown daemon: %s" % reason) + self.console.write('{!error!}Unable to shutdown daemon: %s' % reason) return client.daemon.shutdown().addCallback(on_shutdown).addErrback(on_shutdown_fail) diff --git a/deluge/ui/console/cmdline/commands/help.py b/deluge/ui/console/cmdline/commands/help.py index 94690ff68..1e75a3cb3 100644 --- a/deluge/ui/console/cmdline/commands/help.py +++ b/deluge/ui/console/cmdline/commands/help.py @@ -23,10 +23,10 @@ class Command(BaseCommand): """displays help on other commands""" def add_arguments(self, parser): - parser.add_argument("commands", metavar="<command>", nargs="*", help=_("One or more commands")) + parser.add_argument('commands', metavar='<command>', nargs='*', help=_('One or more commands')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') self._commands = self.console._commands deferred = defer.succeed(True) if options.commands: @@ -34,30 +34,30 @@ class Command(BaseCommand): try: cmd = self._commands[arg] except KeyError: - self.console.write("{!error!}Unknown command %s" % arg) + self.console.write('{!error!}Unknown command %s' % arg) continue try: parser = cmd.create_parser() self.console.write(parser.format_help()) except AttributeError: - self.console.write(cmd.__doc__ or "No help for this command") - self.console.write(" ") + self.console.write(cmd.__doc__ or 'No help for this command') + self.console.write(' ') else: self.console.set_batch_write(True) - cmds_doc = "" + cmds_doc = '' for cmd in sorted(self._commands): if cmd in self._commands[cmd].aliases: continue parser = self._commands[cmd].create_parser() - cmd_doc = "{!info!}" + "%-9s" % self._commands[cmd].name_with_alias + "{!input!} - "\ - + self._commands[cmd].__doc__ + "\n " + parser.format_usage() or '' + cmd_doc = '{!info!}' + '%-9s' % self._commands[cmd].name_with_alias + '{!input!} - '\ + + self._commands[cmd].__doc__ + '\n ' + parser.format_usage() or '' cmds_doc += parser.formatter.format_colors(cmd_doc) self.console.write(cmds_doc) - self.console.write(" ") + self.console.write(' ') self.console.write("For help on a specific command, use '<command> --help'") self.console.set_batch_write(False) return deferred def complete(self, line): - return [x for x in component.get("ConsoleUI")._commands if x.startswith(line)] + return [x for x in component.get('ConsoleUI')._commands if x.startswith(line)] diff --git a/deluge/ui/console/cmdline/commands/info.py b/deluge/ui/console/cmdline/commands/info.py index b71f7d2e8..d6fd21fcd 100644 --- a/deluge/ui/console/cmdline/commands/info.py +++ b/deluge/ui/console/cmdline/commands/info.py @@ -24,38 +24,38 @@ strwidth = format_utils.strwidth STATUS_KEYS = [ - "state", - "download_location", - "tracker_host", - "tracker_status", - "next_announce", - "name", - "total_size", - "progress", - "num_seeds", - "total_seeds", - "num_peers", - "total_peers", - "eta", - "download_payload_rate", - "upload_payload_rate", - "ratio", - "distributed_copies", - "num_pieces", - "piece_length", - "total_done", - "files", - "file_priorities", - "file_progress", - "peers", - "is_seed", - "is_finished", - "active_time", - "seeding_time" + 'state', + 'download_location', + 'tracker_host', + 'tracker_status', + 'next_announce', + 'name', + 'total_size', + 'progress', + 'num_seeds', + 'total_seeds', + 'num_peers', + 'total_peers', + 'eta', + 'download_payload_rate', + 'upload_payload_rate', + 'ratio', + 'distributed_copies', + 'num_pieces', + 'piece_length', + 'total_done', + 'files', + 'file_priorities', + 'file_progress', + 'peers', + 'is_seed', + 'is_finished', + 'active_time', + 'seeding_time' ] # Add filter specific state to torrent states -STATES = ["Active"] + common.TORRENT_STATE +STATES = ['Active'] + common.TORRENT_STATE def format_progressbar(progress, width): @@ -69,11 +69,11 @@ def format_progressbar(progress, width): """ w = width - 2 # we use a [] for the beginning and end - s = "[" + s = '[' p = int(round((progress / 100) * w)) - s += "#" * p - s += "-" * (w - p) - s += "]" + s += '#' * p + s += '-' * (w - p) + s += ']' return s @@ -84,13 +84,13 @@ def format_time(seconds): minutes = minutes - hours * 60 days = hours // 24 hours = hours - days * 24 - return "%d days %02d:%02d:%02d" % (days, hours, minutes, seconds) + return '%d days %02d:%02d:%02d' % (days, hours, minutes, seconds) class Command(BaseCommand): """Show information about the torrents""" - sort_help = "sort items. Possible keys: " + ", ".join(STATUS_KEYS) + sort_help = 'sort items. Possible keys: ' + ', '.join(STATUS_KEYS) epilog = """ You can give the first few characters of a torrent-id to identify the torrent. @@ -103,17 +103,17 @@ class Command(BaseCommand): """ def add_arguments(self, parser): - parser.add_argument("-v", "--verbose", action="store_true", default=False, dest="verbose", - help=_("Show more information per torrent.")) - parser.add_argument("-d", "--detailed", action="store_true", default=False, dest="detailed", - help=_("Show more detailed information including files and peers.")) - parser.add_argument("-s", "--state", action="store", dest="state", - help=_("Show torrents with state STATE: %s." % (", ".join(STATES)))) - parser.add_argument("--sort", action="store", type=str, default="", dest="sort", help=self.sort_help) - parser.add_argument("--sort-reverse", action="store", type=str, default="", dest="sort_rev", - help=_("Same as --sort but items are in reverse order.")) - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="*", - help=_("One or more torrent ids. If none is given, list all")) + parser.add_argument('-v', '--verbose', action='store_true', default=False, dest='verbose', + help=_('Show more information per torrent.')) + parser.add_argument('-d', '--detailed', action='store_true', default=False, dest='detailed', + help=_('Show more detailed information including files and peers.')) + parser.add_argument('-s', '--state', action='store', dest='state', + help=_('Show torrents with state STATE: %s.' % (', '.join(STATES)))) + parser.add_argument('--sort', action='store', type=str, default='', dest='sort', help=self.sort_help) + parser.add_argument('--sort-reverse', action='store', type=str, default='', dest='sort_rev', + help=_('Same as --sort but items are in reverse order.')) + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='*', + help=_('One or more torrent ids. If none is given, list all')) def add_subparser(self, subparsers): parser = subparsers.add_parser(self.name, prog=self.name, help=self.__doc__, @@ -121,7 +121,7 @@ class Command(BaseCommand): self.add_arguments(parser) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') # Compile a list of torrent_ids to request the status of torrent_ids = [] @@ -129,7 +129,7 @@ class Command(BaseCommand): for t_id in options.torrent_ids: torrent_ids.extend(self.console.match_torrent(t_id)) else: - torrent_ids.extend(self.console.match_torrent("")) + torrent_ids.extend(self.console.match_torrent('')) def on_torrents_status(status): # Print out the information for each torrent @@ -139,28 +139,28 @@ class Command(BaseCommand): sort_key = options.sort_rev sort_reverse = True if not sort_key: - sort_key = "name" + sort_key = 'name' sort_reverse = False if sort_key not in STATUS_KEYS: - self.console.write("") - self.console.write("{!error!}Unknown sort key: " + sort_key + ", will sort on name") - sort_key = "name" + self.console.write('') + self.console.write('{!error!}Unknown sort key: ' + sort_key + ', will sort on name') + sort_key = 'name' sort_reverse = False for key, value in sorted(status.items(), key=lambda x: x[1].get(sort_key), reverse=sort_reverse): self.show_info(key, status[key], options.verbose, options.detailed) def on_torrents_status_fail(reason): - self.console.write("{!error!}Error getting torrent info: %s" % reason) + self.console.write('{!error!}Error getting torrent info: %s' % reason) - status_dict = {"id": torrent_ids} + status_dict = {'id': torrent_ids} if options.state: options.state = options.state.capitalize() if options.state in STATES: status_dict.state = options.state else: - self.console.write("Invalid state: %s" % options.state) - self.console.write("Possible values are: %s." % (", ".join(STATES))) + self.console.write('Invalid state: %s' % options.state) + self.console.write('Possible values are: %s.' % (', '.join(STATES))) return d = client.core.get_torrents_status(status_dict, STATUS_KEYS) @@ -171,72 +171,72 @@ class Command(BaseCommand): def show_file_info(self, torrent_id, status): spaces_per_level = 2 - if hasattr(self.console, "screen"): + if hasattr(self.console, 'screen'): cols = self.console.screen.cols else: cols = 80 prevpath = [] - for index, torrent_file in enumerate(status["files"]): - filename = torrent_file["path"].split(dirsep)[-1] - filepath = torrent_file["path"].split(dirsep)[:-1] + for index, torrent_file in enumerate(status['files']): + filename = torrent_file['path'].split(dirsep)[-1] + filepath = torrent_file['path'].split(dirsep)[:-1] for depth, subdir in enumerate(filepath): - indent = " " * depth * spaces_per_level + indent = ' ' * depth * spaces_per_level if depth >= len(prevpath): - self.console.write("%s{!cyan!}%s" % (indent, subdir)) + self.console.write('%s{!cyan!}%s' % (indent, subdir)) elif subdir != prevpath[depth]: - self.console.write("%s{!cyan!}%s" % (indent, subdir)) + self.console.write('%s{!cyan!}%s' % (indent, subdir)) depth = len(filepath) - indent = " " * depth * spaces_per_level + indent = ' ' * depth * spaces_per_level col_filename = indent + filename - col_size = " ({!cyan!}%s{!input!})" % common.fsize(torrent_file["size"]) - col_progress = " {!input!}%.2f%%" % (status["file_progress"][index] * 100) + col_size = ' ({!cyan!}%s{!input!})' % common.fsize(torrent_file['size']) + col_progress = ' {!input!}%.2f%%' % (status['file_progress'][index] * 100) - col_priority = " {!info!}Priority: " + col_priority = ' {!info!}Priority: ' - file_priority = common.FILE_PRIORITY[status["file_priorities"][index]].replace("Priority", "") - if status["file_progress"][index] != 1.0: - if file_priority == "Do Not Download": - col_priority += "{!error!}" + file_priority = common.FILE_PRIORITY[status['file_priorities'][index]].replace('Priority', '') + if status['file_progress'][index] != 1.0: + if file_priority == 'Do Not Download': + col_priority += '{!error!}' else: - col_priority += "{!success!}" + col_priority += '{!success!}' else: - col_priority += "{!input!}" + col_priority += '{!input!}' col_priority += file_priority def tlen(string): return strwidth(format_utils.remove_formatting(string)) if not isinstance(col_filename, unicode): - col_filename = unicode(col_filename, "utf-8") + col_filename = unicode(col_filename, 'utf-8') col_all_info = col_size + col_progress + col_priority # Check how much space we've got left after writing all the info space_left = cols - tlen(col_all_info) # 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 there is enough space, pad it all nicely - col_all_info = "" - col_all_info += " (" - spaces_to_add = tlen(" (1000.0 MiB)") - tlen(col_size) - col_all_info += " " * spaces_to_add + col_all_info = '' + col_all_info += ' (' + spaces_to_add = tlen(' (1000.0 MiB)') - tlen(col_size) + col_all_info += ' ' * spaces_to_add col_all_info += col_size[2:] - spaces_to_add = tlen(" 100.00%") - tlen(col_progress) - col_all_info += " " * spaces_to_add + spaces_to_add = tlen(' 100.00%') - tlen(col_progress) + col_all_info += ' ' * spaces_to_add col_all_info += col_progress - 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 += " " * spaces_to_add + col_all_info += ' ' * spaces_to_add # 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: # 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: # And if there is not, shorten the name col_filename = format_utils.trim_string(col_filename, space_left, True) @@ -245,38 +245,38 @@ class Command(BaseCommand): prevpath = filepath def show_peer_info(self, torrent_id, status): - if len(status["peers"]) == 0: - self.console.write(" None") + if len(status['peers']) == 0: + self.console.write(' None') else: - s = "" - for peer in status["peers"]: - if peer["seed"]: - s += "%sSeed\t{!input!}" % colors.state_color["Seeding"] + s = '' + for peer in status['peers']: + if peer['seed']: + s += '%sSeed\t{!input!}' % colors.state_color['Seeding'] else: - s += "%sPeer\t{!input!}" % colors.state_color["Downloading"] + s += '%sPeer\t{!input!}' % colors.state_color['Downloading'] - s += peer["country"] + "\t" + s += peer['country'] + '\t' - if peer["ip"].count(":") == 1: + if peer['ip'].count(':') == 1: # IPv4 - s += peer["ip"] + s += peer['ip'] else: # IPv6 - s += "[%s]:%s" % (":".join(peer["ip"].split(":")[:-1]), peer["ip"].split(":")[-1]) + s += '[%s]:%s' % (':'.join(peer['ip'].split(':')[:-1]), peer['ip'].split(':')[-1]) - c = peer["client"] - s += "\t" + c + c = peer['client'] + s += '\t' + c if len(c) < 16: - s += "\t\t" + s += '\t\t' else: - s += "\t" - s += "%s%s\t%s%s" % ( - colors.state_color["Seeding"], - common.fspeed(peer["up_speed"]), - colors.state_color["Downloading"], - common.fspeed(peer["down_speed"])) - s += "\n" + s += '\t' + s += '%s%s\t%s%s' % ( + colors.state_color['Seeding'], + common.fspeed(peer['up_speed']), + colors.state_color['Downloading'], + common.fspeed(peer['down_speed'])) + s += '\n' self.console.write(s[:-1]) @@ -288,82 +288,82 @@ class Command(BaseCommand): """ self.console.set_batch_write(True) - if hasattr(self.console, "screen"): + if hasattr(self.console, 'screen'): cols = self.console.screen.cols else: cols = 80 if verbose or detailed: - self.console.write(" ") - self.console.write("{!info!}Name: {!input!}%s" % (status["name"])) - self.console.write("{!info!}ID: {!input!}%s" % (torrent_id)) - s = "{!info!}State: %s%s" % (colors.state_color[status["state"]], status["state"]) + self.console.write(' ') + self.console.write('{!info!}Name: {!input!}%s' % (status['name'])) + self.console.write('{!info!}ID: {!input!}%s' % (torrent_id)) + s = '{!info!}State: %s%s' % (colors.state_color[status['state']], status['state']) # Only show speed if active - if status["state"] in ("Seeding", "Downloading"): - if status["state"] != "Seeding": - s += " {!info!}Down Speed: {!input!}%s" % common.fspeed(status["download_payload_rate"]) - s += " {!info!}Up Speed: {!input!}%s" % common.fspeed(status["upload_payload_rate"]) + if status['state'] in ('Seeding', 'Downloading'): + if status['state'] != 'Seeding': + s += ' {!info!}Down Speed: {!input!}%s' % common.fspeed(status['download_payload_rate']) + s += ' {!info!}Up Speed: {!input!}%s' % common.fspeed(status['upload_payload_rate']) - if common.ftime(status["eta"]): - s += " {!info!}ETA: {!input!}%s" % common.ftime(status["eta"]) + if common.ftime(status['eta']): + s += ' {!info!}ETA: {!input!}%s' % common.ftime(status['eta']) self.console.write(s) - if status["state"] in ("Seeding", "Downloading", "Queued"): - s = "{!info!}Seeds: {!input!}%s (%s)" % (status["num_seeds"], status["total_seeds"]) - s += " {!info!}Peers: {!input!}%s (%s)" % (status["num_peers"], status["total_peers"]) - s += " {!info!}Availability: {!input!}%.2f" % status["distributed_copies"] + if status['state'] in ('Seeding', 'Downloading', 'Queued'): + s = '{!info!}Seeds: {!input!}%s (%s)' % (status['num_seeds'], status['total_seeds']) + s += ' {!info!}Peers: {!input!}%s (%s)' % (status['num_peers'], status['total_peers']) + s += ' {!info!}Availability: {!input!}%.2f' % status['distributed_copies'] self.console.write(s) - total_done = common.fsize(status["total_done"]) - total_size = common.fsize(status["total_size"]) + total_done = common.fsize(status['total_done']) + total_size = common.fsize(status['total_size']) if total_done == total_size: - s = "{!info!}Size: {!input!}%s" % (total_size) + s = '{!info!}Size: {!input!}%s' % (total_size) else: - s = "{!info!}Size: {!input!}%s/%s" % (total_done, total_size) - s += " {!info!}Ratio: {!input!}%.3f" % status["ratio"] - s += " {!info!}Uploaded: {!input!}%s" % common.fsize(status["ratio"] * status["total_done"]) + s = '{!info!}Size: {!input!}%s/%s' % (total_done, total_size) + s += ' {!info!}Ratio: {!input!}%.3f' % status['ratio'] + s += ' {!info!}Uploaded: {!input!}%s' % common.fsize(status['ratio'] * status['total_done']) self.console.write(s) - s = "{!info!}Seed time: {!input!}%s" % format_time(status["seeding_time"]) - s += " {!info!}Active: {!input!}%s" % format_time(status["active_time"]) + s = '{!info!}Seed time: {!input!}%s' % format_time(status['seeding_time']) + s += ' {!info!}Active: {!input!}%s' % format_time(status['active_time']) self.console.write(s) - s = "{!info!}Tracker: {!input!}%s" % status["tracker_host"] + s = '{!info!}Tracker: {!input!}%s' % status['tracker_host'] self.console.write(s) - self.console.write("{!info!}Tracker status: {!input!}%s" % status["tracker_status"]) + self.console.write('{!info!}Tracker status: {!input!}%s' % status['tracker_status']) - if not status["is_finished"]: - pbar = format_progressbar(status["progress"], cols - (13 + len("%.2f%%" % status["progress"]))) - s = "{!info!}Progress: {!input!}%.2f%% %s" % (status["progress"], pbar) + if not status['is_finished']: + pbar = format_progressbar(status['progress'], cols - (13 + len('%.2f%%' % status['progress']))) + s = '{!info!}Progress: {!input!}%.2f%% %s' % (status['progress'], pbar) self.console.write(s) - s = "{!info!}Download Folder: {!input!}%s" % status["download_location"] + s = '{!info!}Download Folder: {!input!}%s' % status['download_location'] self.console.write(s) if detailed: - self.console.write("{!info!}Files in torrent") + self.console.write('{!info!}Files in torrent') self.show_file_info(torrent_id, status) - self.console.write("{!info!}Connected peers") + self.console.write('{!info!}Connected peers') self.show_peer_info(torrent_id, status) else: - self.console.write(" ") - up_color = colors.state_color["Seeding"] - down_color = colors.state_color["Downloading"] + self.console.write(' ') + up_color = colors.state_color['Seeding'] + down_color = colors.state_color['Downloading'] - s = "%s%s" % (colors.state_color[status["state"]], "[" + status["state"][0] + "]") + s = '%s%s' % (colors.state_color[status['state']], '[' + status['state'][0] + ']') - s += " {!info!}" + ("%.2f%%" % status["progress"]).ljust(7, " ") - s += " {!input!}%s" % (status["name"]) + s += ' {!info!}' + ('%.2f%%' % status['progress']).ljust(7, ' ') + s += ' {!input!}%s' % (status['name']) # Shorten the ID if it's necessary. Pretty hacky # 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: # There's enough space, print it - s += " {!cyan!}%s" % torrent_id + s += ' {!cyan!}%s' % torrent_id else: # Shorten the ID a = space_left * 2 // 3 @@ -376,31 +376,31 @@ class Command(BaseCommand): b = 0 if a > 8: # 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: # It has wrapped over to the second row anyway - s += " {!cyan!}%s" % torrent_id + s += ' {!cyan!}%s' % torrent_id self.console.write(s) - dl_info = "{!info!}DL: {!input!}" - dl_info += "%s" % common.fsize(status["total_done"]) - if status["total_done"] != status["total_size"]: - dl_info += "/%s" % common.fsize(status["total_size"]) - if status["download_payload_rate"] > 0: - dl_info += " @ %s%s" % (down_color, common.fspeed(status["download_payload_rate"])) + dl_info = '{!info!}DL: {!input!}' + dl_info += '%s' % common.fsize(status['total_done']) + if status['total_done'] != status['total_size']: + dl_info += '/%s' % common.fsize(status['total_size']) + if status['download_payload_rate'] > 0: + dl_info += ' @ %s%s' % (down_color, common.fspeed(status['download_payload_rate'])) - ul_info = " {!info!}UL: {!input!}" - ul_info += "%s" % common.fsize(status["ratio"] * status["total_done"]) - if status["upload_payload_rate"] > 0: - ul_info += " @ %s%s" % (up_color, common.fspeed(status["upload_payload_rate"])) + ul_info = ' {!info!}UL: {!input!}' + ul_info += '%s' % common.fsize(status['ratio'] * status['total_done']) + if status['upload_payload_rate'] > 0: + ul_info += ' @ %s%s' % (up_color, common.fspeed(status['upload_payload_rate'])) - eta = "" - if common.ftime(status["eta"]): - eta = " {!info!}ETA: {!magenta!}%s" % common.ftime(status["eta"]) + eta = '' + if common.ftime(status['eta']): + eta = ' {!info!}ETA: {!magenta!}%s' % common.ftime(status['eta']) - self.console.write(" " + dl_info + ul_info + eta) + self.console.write(' ' + dl_info + ul_info + eta) self.console.set_batch_write(False) def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/manage.py b/deluge/ui/console/cmdline/commands/manage.py index bc5a203ea..9ee9719df 100644 --- a/deluge/ui/console/cmdline/commands/manage.py +++ b/deluge/ui/console/cmdline/commands/manage.py @@ -20,37 +20,37 @@ from . import BaseCommand log = logging.getLogger(__name__) torrent_options = { - "max_download_speed": float, - "max_upload_speed": float, - "max_connections": int, - "max_upload_slots": int, - "private": bool, - "prioritize_first_last": bool, - "is_auto_managed": bool, - "stop_at_ratio": bool, - "stop_ratio": float, - "remove_at_ratio": bool, - "move_completed": bool, - "move_completed_path": str + 'max_download_speed': float, + 'max_upload_speed': float, + 'max_connections': int, + 'max_upload_slots': int, + 'private': bool, + 'prioritize_first_last': bool, + 'is_auto_managed': bool, + 'stop_at_ratio': bool, + 'stop_ratio': float, + 'remove_at_ratio': bool, + 'move_completed': bool, + 'move_completed_path': str } class Command(BaseCommand): """Show and manage per-torrent options""" - usage = _("Usage: manage <torrent-id> [--set <key> <value>] [<key> [<key>...] ]") + usage = _('Usage: manage <torrent-id> [--set <key> <value>] [<key> [<key>...] ]') def add_arguments(self, parser): - parser.add_argument("torrent", metavar="<torrent>", - help=_("an expression matched against torrent ids and torrent names")) - set_group = parser.add_argument_group("setting a value") - set_group.add_argument("-s", "--set", action="store", metavar="<key>", help=_("set value for this key")) - set_group.add_argument("values", metavar="<value>", nargs="+", help=_("Value to set")) - get_group = parser.add_argument_group("getting values") - get_group.add_argument("keys", metavar="<keys>", nargs="*", help=_("one or more keys separated by space")) + parser.add_argument('torrent', metavar='<torrent>', + help=_('an expression matched against torrent ids and torrent names')) + set_group = parser.add_argument_group('setting a value') + set_group.add_argument('-s', '--set', action='store', metavar='<key>', help=_('set value for this key')) + set_group.add_argument('values', metavar='<value>', nargs='+', help=_('Value to set')) + get_group = parser.add_argument_group('getting values') + get_group.add_argument('keys', metavar='<keys>', nargs='*', help=_('one or more keys separated by space')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') if options.set: return self._set_option(options) else: @@ -83,14 +83,14 @@ class Command(BaseCommand): request_options = [opt for opt in torrent_options.keys()] request_options.append('name') - d = client.core.get_torrents_status({"id": torrent_ids}, request_options) + d = client.core.get_torrents_status({'id': torrent_ids}, request_options) d.addCallbacks(on_torrents_status, on_torrents_status_fail) return d def _set_option(self, options): deferred = defer.Deferred() key = options.set - val = " " .join(options.values) + val = ' ' .join(options.values) torrent_ids = self.console.match_torrent(options.torrent) if key not in torrent_options: @@ -100,13 +100,13 @@ class Command(BaseCommand): val = torrent_options[key](val) def on_set_config(result): - self.console.write("{!success!}Torrent option successfully updated.") + self.console.write('{!success!}Torrent option successfully updated.') deferred.callback(True) - self.console.write("Setting %s to %s for torrents %s.." % (key, val, torrent_ids)) + self.console.write('Setting %s to %s for torrents %s..' % (key, val, torrent_ids)) client.core.set_torrent_options(torrent_ids, {key: val}).addCallback(on_set_config) return deferred def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/move.py b/deluge/ui/console/cmdline/commands/move.py index 5e1b1715c..f04523258 100644 --- a/deluge/ui/console/cmdline/commands/move.py +++ b/deluge/ui/console/cmdline/commands/move.py @@ -22,14 +22,14 @@ class Command(BaseCommand): """Move torrents' storage location""" def add_arguments(self, parser): - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", help=_("One or more torrent ids")) - parser.add_argument("path", metavar="<path>", help=_("The path to move the torrents to")) + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids')) + parser.add_argument('path', metavar='<path>', help=_('The path to move the torrents to')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') if os.path.exists(options.path) and not os.path.isdir(options.path): - self.console.write("{!error!}Cannot Move Download Folder: %s exists and is not a directory" % options.path) + self.console.write('{!error!}Cannot Move Download Folder: %s exists and is not a directory' % options.path) return ids = [] @@ -40,7 +40,7 @@ class Command(BaseCommand): names.append(self.console.get_torrent_name(tid)) def on_move(res): - msg = "Moved \"%s\" to %s" % (", ".join(names), options.path) + msg = "Moved \"%s\" to %s" % (', '.join(names), options.path) self.console.write(msg) log.info(msg) @@ -58,11 +58,11 @@ class Command(BaseCommand): # ret.extend(os.listdir(line)) for f in os.listdir(line): # Skip hidden - if f.startswith("."): + if f.startswith('.'): continue f = os.path.join(line, f) if os.path.isdir(f): - f += "/" + f += '/' ret.append(f) else: # This is a file, but we could be looking for another file that @@ -80,6 +80,6 @@ class Command(BaseCommand): p = os.path.join(os.path.dirname(line), f) if os.path.isdir(p): - p += "/" + p += '/' ret.append(p) return ret diff --git a/deluge/ui/console/cmdline/commands/pause.py b/deluge/ui/console/cmdline/commands/pause.py index 34d040792..24e62e2a1 100644 --- a/deluge/ui/console/cmdline/commands/pause.py +++ b/deluge/ui/console/cmdline/commands/pause.py @@ -16,16 +16,16 @@ from . import BaseCommand class Command(BaseCommand): """Pause torrents""" - usage = "pause [ * | <torrent-id> [<torrent-id> ...] ]" + usage = 'pause [ * | <torrent-id> [<torrent-id> ...] ]' def add_arguments(self, parser): - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_("One or more torrent ids. '*' pauses all torrents")) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') - if options.torrent_ids[0] == "*": + if options.torrent_ids[0] == '*': client.core.pause_session() return @@ -38,4 +38,4 @@ class Command(BaseCommand): def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/plugin.py b/deluge/ui/console/cmdline/commands/plugin.py index 4b6e5ad1a..959fdcdaa 100644 --- a/deluge/ui/console/cmdline/commands/plugin.py +++ b/deluge/ui/console/cmdline/commands/plugin.py @@ -18,37 +18,37 @@ class Command(BaseCommand): """Manage plugins""" def add_arguments(self, parser): - parser.add_argument("-l", "--list", action="store_true", default=False, dest="list", - help=_("Lists available plugins")) - parser.add_argument("-s", "--show", action="store_true", default=False, dest="show", - help=_("Shows enabled plugins")) - parser.add_argument("-e", "--enable", dest="enable", nargs="+", help=_("Enables a plugin")) - parser.add_argument("-d", "--disable", dest="disable", nargs="+", help=_("Disables a plugin")) - parser.add_argument("-r", "--reload", action="store_true", default=False, dest="reload", - help=_("Reload list of available plugins")) - parser.add_argument("-i", "--install", help=_("Install a plugin from an .egg file")) + parser.add_argument('-l', '--list', action='store_true', default=False, dest='list', + help=_('Lists available plugins')) + parser.add_argument('-s', '--show', action='store_true', default=False, dest='show', + help=_('Shows enabled plugins')) + parser.add_argument('-e', '--enable', dest='enable', nargs='+', help=_('Enables a plugin')) + parser.add_argument('-d', '--disable', dest='disable', nargs='+', help=_('Disables a plugin')) + parser.add_argument('-r', '--reload', action='store_true', default=False, dest='reload', + help=_('Reload list of available plugins')) + parser.add_argument('-i', '--install', help=_('Install a plugin from an .egg file')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') if options.reload: client.core.pluginmanager.rescan_plugins() - self.console.write("{!green!}Plugin list successfully reloaded") + self.console.write('{!green!}Plugin list successfully reloaded') return elif options.list: def on_available_plugins(result): - self.console.write("{!info!}Available Plugins:") + self.console.write('{!info!}Available Plugins:') for p in result: - self.console.write("{!input!} " + p) + self.console.write('{!input!} ' + p) return client.core.get_available_plugins().addCallback(on_available_plugins) elif options.show: def on_enabled_plugins(result): - self.console.write("{!info!}Enabled Plugins:") + self.console.write('{!info!}Enabled Plugins:') for p in result: - self.console.write("{!input!} " + p) + self.console.write('{!input!} ' + p) return client.core.get_enabled_plugins().addCallback(on_enabled_plugins) @@ -82,26 +82,26 @@ class Command(BaseCommand): filepath = options.install if not os.path.exists(filepath): - self.console.write("{!error!}Invalid path: %s" % filepath) + self.console.write('{!error!}Invalid path: %s' % filepath) return config_dir = deluge.configmanager.get_config_dir() filename = os.path.split(filepath)[1] - shutil.copyfile(filepath, os.path.join(config_dir, "plugins", filename)) + shutil.copyfile(filepath, os.path.join(config_dir, 'plugins', filename)) client.core.rescan_plugins() if not client.is_localhost(): # We need to send this plugin to the daemon - with open(filepath, "rb") as _file: + with open(filepath, 'rb') as _file: filedump = base64.encodestring(_file.read()) try: client.core.upload_plugin(filename, filedump) client.core.rescan_plugins() except Exception: - self.console.write("{!error!}An error occurred, plugin was not installed") + self.console.write('{!error!}An error occurred, plugin was not installed') - self.console.write("{!green!}Plugin was successfully installed: %s" % filename) + self.console.write('{!green!}Plugin was successfully installed: %s' % filename) def complete(self, line): - return component.get("ConsoleUI").tab_complete_path(line, ext=".egg", sort="name", dirs_first=-1) + return component.get('ConsoleUI').tab_complete_path(line, ext='.egg', sort='name', dirs_first=-1) diff --git a/deluge/ui/console/cmdline/commands/quit.py b/deluge/ui/console/cmdline/commands/quit.py index d0f577330..374367b5e 100644 --- a/deluge/ui/console/cmdline/commands/quit.py +++ b/deluge/ui/console/cmdline/commands/quit.py @@ -17,7 +17,7 @@ from . import BaseCommand class Command(BaseCommand): """Exit the client.""" - aliases = ["exit"] + aliases = ['exit'] interactive_only = True def handle(self, options): diff --git a/deluge/ui/console/cmdline/commands/recheck.py b/deluge/ui/console/cmdline/commands/recheck.py index 3aaef4a03..a2f9f71e0 100644 --- a/deluge/ui/console/cmdline/commands/recheck.py +++ b/deluge/ui/console/cmdline/commands/recheck.py @@ -15,16 +15,16 @@ from . import BaseCommand class Command(BaseCommand): """Forces a recheck of the torrent data""" - usage = "recheck [ * | <torrent-id> [<torrent-id> ...] ]" + usage = 'recheck [ * | <torrent-id> [<torrent-id> ...] ]' def add_arguments(self, parser): - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", help=_("One or more torrent ids")) + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') - if options.torrent_ids[0] == "*": - client.core.force_recheck(self.console.match_torrent("")) + if options.torrent_ids[0] == '*': + client.core.force_recheck(self.console.match_torrent('')) return torrent_ids = [] @@ -36,4 +36,4 @@ class Command(BaseCommand): def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/resume.py b/deluge/ui/console/cmdline/commands/resume.py index 6fda7e2bb..65da8a8b8 100644 --- a/deluge/ui/console/cmdline/commands/resume.py +++ b/deluge/ui/console/cmdline/commands/resume.py @@ -16,16 +16,16 @@ from . import BaseCommand class Command(BaseCommand): """Resume torrents""" - usage = _("Usage: resume [ * | <torrent-id> [<torrent-id> ...] ]") + usage = _('Usage: resume [ * | <torrent-id> [<torrent-id> ...] ]') def add_arguments(self, parser): - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_("One or more torrent ids. '*' resumes all torrents")) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') - if options.torrent_ids[0] == "*": + if options.torrent_ids[0] == '*': client.core.resume_session() return @@ -38,4 +38,4 @@ class Command(BaseCommand): def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/rm.py b/deluge/ui/console/cmdline/commands/rm.py index 62acb51bf..0cbda3b19 100644 --- a/deluge/ui/console/cmdline/commands/rm.py +++ b/deluge/ui/console/cmdline/commands/rm.py @@ -20,38 +20,38 @@ log = logging.getLogger(__name__) class Command(BaseCommand): """Remove a torrent""" - aliases = ["del"] + aliases = ['del'] def add_arguments(self, parser): - parser.add_argument("--remove_data", action="store_true", default=False, help=_("remove the torrent's data")) - parser.add_argument("-c", "--confirm", action="store_true", default=False, - help=_("List the matching torrents without removing.")) - parser.add_argument("torrent_ids", metavar="<torrent-id>", nargs="+", help=_("One or more torrent ids")) + parser.add_argument('--remove_data', action='store_true', default=False, help=_("remove the torrent's data")) + parser.add_argument('-c', '--confirm', action='store_true', default=False, + help=_('List the matching torrents without removing.')) + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help=_('One or more torrent ids')) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') torrent_ids = self.console.match_torrents(options.torrent_ids) if not options.confirm: - self.console.write("{!info!}%d %s %s{!info!}" % (len(torrent_ids), - _n("torrent", "torrents", len(torrent_ids)), - _n("match", "matches", len(torrent_ids)))) + self.console.write('{!info!}%d %s %s{!info!}' % (len(torrent_ids), + _n('torrent', 'torrents', len(torrent_ids)), + _n('match', 'matches', len(torrent_ids)))) for t_id in torrent_ids: name = self.console.get_torrent_name(t_id) - self.console.write("* %-50s (%s)" % (name, t_id)) - self.console.write(_("Confirm with -c to remove the listed torrents (Count: %d)") % len(torrent_ids)) + self.console.write('* %-50s (%s)' % (name, t_id)) + self.console.write(_('Confirm with -c to remove the listed torrents (Count: %d)') % len(torrent_ids)) return def on_removed_finished(errors): if errors: - self.console.write("Error(s) occured when trying to delete torrent(s).") + self.console.write('Error(s) occured when trying to delete torrent(s).') for t_id, e_msg in errors: - self.console.write("Error removing torrent %s : %s" % (t_id, e_msg)) + self.console.write('Error removing torrent %s : %s' % (t_id, e_msg)) - log.info("Removing %d torrents", len(torrent_ids)) + log.info('Removing %d torrents', len(torrent_ids)) d = client.core.remove_torrents(torrent_ids, options.remove_data) d.addCallback(on_removed_finished) def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/cmdline/commands/status.py b/deluge/ui/console/cmdline/commands/status.py index 915054950..9ae8df354 100644 --- a/deluge/ui/console/cmdline/commands/status.py +++ b/deluge/ui/console/cmdline/commands/status.py @@ -24,14 +24,14 @@ class Command(BaseCommand): """Shows a various status information from the daemon.""" def add_arguments(self, parser): - parser.add_argument("-r", "--raw", action="store_true", default=False, dest="raw", + parser.add_argument('-r', '--raw', action='store_true', default=False, dest='raw', help=_("Don't format upload/download rates in KiB/s " - "(useful for scripts that want to do their own parsing)")) - parser.add_argument("-n", "--no-torrents", action="store_false", default=True, dest="show_torrents", + '(useful for scripts that want to do their own parsing)')) + parser.add_argument('-n', '--no-torrents', action='store_false', default=True, dest='show_torrents', help=_("Don't show torrent status (this will make the command a bit faster)")) def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') self.status = None self.torrents = 1 if options.show_torrents else 0 self.raw = options.raw @@ -43,17 +43,17 @@ class Command(BaseCommand): self.torrents = status def on_torrents_status_fail(reason): - log.warn("Failed to retrieve session status: %s", reason) + log.warn('Failed to retrieve session status: %s', reason) self.torrents = -2 deferreds = [] - ds = client.core.get_session_status(["num_peers", "payload_upload_rate", "payload_download_rate", "dht_nodes"]) + ds = client.core.get_session_status(['num_peers', 'payload_upload_rate', 'payload_download_rate', 'dht_nodes']) ds.addCallback(on_session_status) deferreds.append(ds) if options.show_torrents: - dt = client.core.get_torrents_status({}, ["state"]) + dt = client.core.get_torrents_status({}, ['state']) dt.addCallback(on_torrents_status) dt.addErrback(on_torrents_status_fail) deferreds.append(dt) @@ -63,25 +63,25 @@ class Command(BaseCommand): def print_status(self, *args): self.console.set_batch_write(True) if self.raw: - self.console.write("{!info!}Total upload: %f" % self.status["payload_upload_rate"]) - self.console.write("{!info!}Total download: %f" % self.status["payload_download_rate"]) + self.console.write('{!info!}Total upload: %f' % self.status['payload_upload_rate']) + self.console.write('{!info!}Total download: %f' % self.status['payload_download_rate']) else: - self.console.write("{!info!}Total upload: %s" % fspeed(self.status["payload_upload_rate"])) - self.console.write("{!info!}Total download: %s" % fspeed(self.status["payload_download_rate"])) - self.console.write("{!info!}DHT Nodes: %i" % self.status["dht_nodes"]) + self.console.write('{!info!}Total upload: %s' % fspeed(self.status['payload_upload_rate'])) + self.console.write('{!info!}Total download: %s' % fspeed(self.status['payload_download_rate'])) + self.console.write('{!info!}DHT Nodes: %i' % self.status['dht_nodes']) if isinstance(self.torrents, int): if self.torrents == -2: - self.console.write("{!error!}Error getting torrent info") + self.console.write('{!error!}Error getting torrent info') else: - self.console.write("{!info!}Total torrents: %i" % len(self.torrents)) + self.console.write('{!info!}Total torrents: %i' % len(self.torrents)) state_counts = {} for state in TORRENT_STATE: state_counts[state] = 0 for t in self.torrents: s = self.torrents[t] - state_counts[s["state"]] += 1 + state_counts[s['state']] += 1 for state in TORRENT_STATE: - self.console.write("{!info!} %s: %i" % (state, state_counts[state])) + self.console.write('{!info!} %s: %i' % (state, state_counts[state])) self.console.set_batch_write(False) diff --git a/deluge/ui/console/cmdline/commands/update_tracker.py b/deluge/ui/console/cmdline/commands/update_tracker.py index 756075e6e..52e70d8d9 100644 --- a/deluge/ui/console/cmdline/commands/update_tracker.py +++ b/deluge/ui/console/cmdline/commands/update_tracker.py @@ -16,18 +16,18 @@ from . import BaseCommand class Command(BaseCommand): """Update tracker for torrent(s)""" - usage = "update_tracker [ * | <torrent-id> [<torrent-id> ...] ]" + usage = 'update_tracker [ * | <torrent-id> [<torrent-id> ...] ]' aliases = ['reannounce'] def add_arguments(self, parser): - parser.add_argument('torrent_ids', metavar="<torrent-id>", nargs='+', + parser.add_argument('torrent_ids', metavar='<torrent-id>', nargs='+', help='One or more torrent ids. "*" updates all torrents') def handle(self, options): - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') args = options.torrent_ids - if options.torrent_ids[0] == "*": - args = [""] + if options.torrent_ids[0] == '*': + args = [''] torrent_ids = [] for arg in args: @@ -37,4 +37,4 @@ class Command(BaseCommand): def complete(self, line): # We use the ConsoleUI torrent tab complete method - return component.get("ConsoleUI").tab_complete_torrent(line) + return component.get('ConsoleUI').tab_complete_torrent(line) diff --git a/deluge/ui/console/console.py b/deluge/ui/console/console.py index eeec87c9f..058202149 100644 --- a/deluge/ui/console/console.py +++ b/deluge/ui/console/console.py @@ -64,30 +64,30 @@ class Console(UI): cmd_description = """Console or command-line user interface""" def __init__(self, *args, **kwargs): - super(Console, self).__init__("console", *args, log_stream=LogStream(), **kwargs) + super(Console, self).__init__('console', *args, log_stream=LogStream(), **kwargs) - group = self.parser.add_argument_group(_("Console Options"), - _("These daemon connect options will be " - "used for commands, or if console ui autoconnect is enabled.")) - group.add_argument("-d", "--daemon", dest="daemon_addr", required=False, default="127.0.0.1") - group.add_argument("-p", "--port", dest="daemon_port", type=int, required=False, default="58846") - group.add_argument("-U", "--username", dest="daemon_user", required=False) - group.add_argument("-P", "--password", dest="daemon_pass", required=False) + group = self.parser.add_argument_group(_('Console Options'), + _('These daemon connect options will be ' + 'used for commands, or if console ui autoconnect is enabled.')) + group.add_argument('-d', '--daemon', dest='daemon_addr', required=False, default='127.0.0.1') + group.add_argument('-p', '--port', dest='daemon_port', type=int, required=False, default='58846') + group.add_argument('-U', '--username', dest='daemon_user', required=False) + group.add_argument('-P', '--password', dest='daemon_pass', required=False) # To properly print help message for the console commands ( e.g. deluge-console info -h), # we add a subparser for each command which will trigger the help/usage when given from deluge.ui.console.parser import ConsoleCommandParser # import here because (see top) self.console_parser = ConsoleCommandParser(parents=[self.parser], add_help=False, prog=self.parser.prog, - description="Starts the Deluge console interface", + description='Starts the Deluge console interface', formatter_class=lambda prog: DelugeTextHelpFormatter(prog, max_help_position=33, width=90)) self.parser.subparser = self.console_parser self.console_parser.base_parser = self.parser - subparsers = self.console_parser.add_subparsers(title=_("Console commands"), help=_("Description"), - description=_("The following console commands are available:"), - metavar=_("Command"), dest="command") + subparsers = self.console_parser.add_subparsers(title=_('Console commands'), help=_('Description'), + description=_('The following console commands are available:'), + metavar=_('Command'), dest='command') from deluge.ui.console import UI_PATH # Must import here - self.console_cmds = load_commands(os.path.join(UI_PATH, "cmdline", "commands")) + self.console_cmds = load_commands(os.path.join(UI_PATH, 'cmdline', 'commands')) for c in sorted(self.console_cmds): self.console_cmds[c].add_subparser(subparsers) diff --git a/deluge/ui/console/main.py b/deluge/ui/console/main.py index aeeab5c2a..6328023b0 100644 --- a/deluge/ui/console/main.py +++ b/deluge/ui/console/main.py @@ -39,30 +39,30 @@ from deluge.ui.sessionproxy import SessionProxy log = logging.getLogger(__name__) DEFAULT_CONSOLE_PREFS = { - "ring_bell": False, - "first_run": True, - "language": "", - "torrentview": { - "sort_primary": "queue", - "sort_secondary": "name", - "show_sidebar": True, - "sidebar_width": 25, - "separate_complete": True, - "move_selection": True, - "columns": {} + 'ring_bell': False, + 'first_run': True, + 'language': '', + 'torrentview': { + 'sort_primary': 'queue', + 'sort_secondary': 'name', + 'show_sidebar': True, + 'sidebar_width': 25, + 'separate_complete': True, + 'move_selection': True, + 'columns': {} }, - "addtorrents": { - "show_misc_files": False, # TODO: Showing/hiding this - "show_hidden_folders": False, # TODO: Showing/hiding this - "sort_column": "date", - "reverse_sort": True, - "last_path": "~", + 'addtorrents': { + 'show_misc_files': False, # TODO: Showing/hiding this + 'show_hidden_folders': False, # TODO: Showing/hiding this + 'sort_column': 'date', + 'reverse_sort': True, + 'last_path': '~', }, - "cmdline": { - "ignore_duplicate_lines": False, - "third_tab_lists_all": False, - "torrents_per_tab_press": 15, - "save_command_history": True, + 'cmdline': { + 'ignore_duplicate_lines': False, + 'third_tab_lists_all': False, + 'torrents_per_tab_press': 15, + 'save_command_history': True, } } @@ -70,7 +70,7 @@ DEFAULT_CONSOLE_PREFS = { class ConsoleUI(component.Component, TermResizeHandler): def __init__(self, options, cmds, log_stream): - component.Component.__init__(self, "ConsoleUI") + component.Component.__init__(self, 'ConsoleUI') TermResizeHandler.__init__(self) self.options = options self.log_stream = log_stream @@ -84,12 +84,12 @@ class ConsoleUI(component.Component, TermResizeHandler): self.initialized = False try: - locale.setlocale(locale.LC_ALL, "") + locale.setlocale(locale.LC_ALL, '') self.encoding = locale.getpreferredencoding() except locale.Error: self.encoding = sys.getdefaultencoding() - log.debug("Using encoding: %s", self.encoding) + log.debug('Using encoding: %s', self.encoding) # start up the session proxy self.sessionproxy = SessionProxy() @@ -117,7 +117,7 @@ class ConsoleUI(component.Component, TermResizeHandler): if self.options.parsed_cmds: self.interactive = False if not self._commands: - print("No valid console commands found") + print('No valid console commands found') return deferred = self.exec_args(self.options) @@ -170,10 +170,10 @@ Please use commands from the command line, e.g.:\n return commander.exec_command(cmd) d = defer.succeed(None) for command in options.parsed_cmds: - if command.command in ("quit", "exit"): + if command.command in ('quit', 'exit'): break d.addCallback(exec_command, command) - d.addCallback(do_command, "quit") + d.addCallback(do_command, 'quit') return d # We need to wait for the rpcs in start() to finish before processing @@ -189,14 +189,14 @@ Please use commands from the command line, e.g.:\n rm = reason.getErrorMessage() else: rm = reason.value.message - print("Could not connect to daemon: %s:%s\n %s" % (options.daemon_addr, options.daemon_port, rm)) - commander.do_command("quit") + print('Could not connect to daemon: %s:%s\n %s' % (options.daemon_addr, options.daemon_port, rm)) + commander.do_command('quit') d = None - if not self.interactive and options.parsed_cmds[0].command == "connect": + if not self.interactive and options.parsed_cmds[0].command == 'connect': d = commander.do_command(options.parsed_cmds.pop(0)) else: - log.info("connect: host=%s, port=%s, username=%s, password=%s", + log.info('connect: host=%s, port=%s, username=%s, password=%s', options.daemon_addr, options.daemon_port, options.daemon_user, options.daemon_pass) d = client.connect(options.daemon_addr, options.daemon_port, options.daemon_user, options.daemon_pass) d.addCallback(on_connect) @@ -214,7 +214,7 @@ Please use commands from the command line, e.g.:\n # pass it the function that handles commands colors.init_colors() self.stdscr = stdscr - self.config = ConfigManager("console.conf", defaults=DEFAULT_CONSOLE_PREFS, file_version=2) + self.config = ConfigManager('console.conf', defaults=DEFAULT_CONSOLE_PREFS, file_version=2) self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2) self.statusbars = StatusBars() @@ -230,8 +230,8 @@ Please use commands from the command line, e.g.:\n self.eventlog = EventLog() - self.active_mode.topbar = "{!status!}Deluge " + deluge.common.get_version() + " Console" - self.active_mode.bottombar = "{!status!}" + self.active_mode.topbar = '{!status!}Deluge ' + deluge.common.get_version() + ' Console' + self.active_mode.bottombar = '{!status!}' self.active_mode.refresh() # Start the twisted mainloop reactor.run() @@ -269,7 +269,7 @@ Please use commands from the command line, e.g.:\n # This can lead to the popup border being visible for short periods # while the current modes' screen is repainted. log.error("Mode '%s' still has popups available after being paused." - " Ensure all popups are removed on pause!", mode.popup.title) + ' Ensure all popups are removed on pause!', mode.popup.title) d.addCallback(on_mode_paused, self.active_mode) reactor.removeReader(self.active_mode) @@ -281,7 +281,7 @@ Please use commands from the command line, e.g.:\n reactor.addReader(self.active_mode) self.stdscr.clear() - if self.active_mode._component_state == "Stopped": + if self.active_mode._component_state == 'Stopped': component.start([self.active_mode.mode_name]) else: component.resume([self.active_mode.mode_name]) @@ -296,20 +296,20 @@ Please use commands from the command line, e.g.:\n if arg and True in arg[0]: func() else: - self.messages.append(("Error", error_smg)) - component.stop(["TorrentList"]).addCallback(on_stop) + self.messages.append(('Error', error_smg)) + component.stop(['TorrentList']).addCallback(on_stop) def is_active_mode(self, mode): return mode == self.active_mode def start_components(self): def on_started(result): - component.pause(["TorrentList", "EventView", "AddTorrents", "TorrentDetail", "Preferences"]) + component.pause(['TorrentList', 'EventView', 'AddTorrents', 'TorrentDetail', 'Preferences']) if self.interactive: d = component.start().addCallback(on_started) else: - d = component.start(["SessionProxy", "ConsoleUI", "CoreConfig"]) + d = component.start(['SessionProxy', 'ConsoleUI', 'CoreConfig']) return d def start_console(self): @@ -321,8 +321,8 @@ Please use commands from the command line, e.g.:\n d = self.start_components() else: def on_stopped(result): - return component.start(["SessionProxy"]) - d = component.stop(["SessionProxy"]).addCallback(on_stopped) + return component.start(['SessionProxy']) + d = component.stop(['SessionProxy']).addCallback(on_stopped) return d def start(self): @@ -332,22 +332,22 @@ Please use commands from the command line, e.g.:\n def on_torrents_status(torrents): for torrent_id, status in torrents.items(): - self.torrents.append((torrent_id, status["name"])) + self.torrents.append((torrent_id, status['name'])) self.started_deferred.callback(True) - client.core.get_torrents_status({"id": result}, ["name"]).addCallback(on_torrents_status) + client.core.get_torrents_status({'id': result}, ['name']).addCallback(on_torrents_status) d = client.core.get_session_state().addCallback(on_session_state) # Register event handlers to keep the torrent list up-to-date - client.register_event_handler("TorrentAddedEvent", self.on_torrent_added_event) - client.register_event_handler("TorrentRemovedEvent", self.on_torrent_removed_event) + client.register_event_handler('TorrentAddedEvent', self.on_torrent_added_event) + client.register_event_handler('TorrentRemovedEvent', self.on_torrent_removed_event) return d def on_torrent_added_event(self, event, from_state=False): def on_torrent_status(status): - self.torrents.append((event, status["name"])) - client.core.get_torrent_status(event, ["name"]).addCallback(on_torrent_status) + self.torrents.append((event, status['name'])) + client.core.get_torrent_status(event, ['name']).addCallback(on_torrent_status) def on_torrent_removed_event(self, event): for index, (tid, name) in enumerate(self.torrents): @@ -374,15 +374,15 @@ Please use commands from the command line, e.g.:\n if not isinstance(string, unicode): string = unicode(string, self.encoding) - if string == "*" or string == "": + if string == '*' or string == '': return [tid for tid, name in self.torrents] - match_func = "__eq__" - if string.startswith("*"): + match_func = '__eq__' + if string.startswith('*'): string = string[1:] - match_func = "endswith" - if string.endswith("*"): - match_func = "__contains__" if match_func == "endswith" else "startswith" + match_func = 'endswith' + if string.endswith('*'): + match_func = '__contains__' if match_func == 'endswith' else 'startswith' string = string[:-1] matches = [] @@ -407,7 +407,7 @@ Please use commands from the command line, e.g.:\n if self.interactive and isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine): return self.active_mode.tab_complete_torrent(line) - def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=True): + def tab_complete_path(self, line, path_type='file', ext='', sort='name', dirs_first=True): if self.interactive and isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine): return self.active_mode.tab_complete_path(line, path_type=path_type, ext=ext, sort=sort, dirs_first=dirs_first) @@ -420,7 +420,7 @@ Please use commands from the command line, e.g.:\n if isinstance(self.active_mode, deluge.ui.console.modes.cmdline.CmdLine): self.active_mode.write(s) else: - component.get("CmdLine").add_line(s, False) + component.get('CmdLine').add_line(s, False) self.events.append(s) else: print(colors.strip_colors(deluge.common.utf8_encoded(s))) @@ -431,7 +431,7 @@ Please use commands from the command line, e.g.:\n self.events.append(s) self.active_mode.write(s) else: - component.get("CmdLine").add_line(s, False) + component.get('CmdLine').add_line(s, False) self.events.append(s) else: print(colors.strip_colors(deluge.common.utf8_encoded(s))) @@ -448,50 +448,50 @@ Please use commands from the command line, e.g.:\n del source[source_key] # These are moved to 'torrentview' sub dict - for k in ["sort_primary", "sort_secondary", "move_selection", "separate_complete"]: - move_key(config, config["torrentview"], k) + for k in ['sort_primary', 'sort_secondary', 'move_selection', 'separate_complete']: + move_key(config, config['torrentview'], k) # These are moved to 'addtorrents' sub dict - for k in ["show_misc_files", "show_hidden_folders", "sort_column", "reverse_sort", "last_path"]: - move_key(config, config["addtorrents"], "addtorrents_%s" % k, dest_key=k) + for k in ['show_misc_files', 'show_hidden_folders', 'sort_column', 'reverse_sort', 'last_path']: + move_key(config, config['addtorrents'], 'addtorrents_%s' % k, dest_key=k) # These are moved to 'cmdline' sub dict - for k in ["ignore_duplicate_lines", "torrents_per_tab_press", "third_tab_lists_all"]: - move_key(config, config["cmdline"], k) + for k in ['ignore_duplicate_lines', 'torrents_per_tab_press', 'third_tab_lists_all']: + move_key(config, config['cmdline'], k) - move_key(config, config["cmdline"], "save_legacy_history", dest_key="save_command_history") + move_key(config, config['cmdline'], 'save_legacy_history', dest_key='save_command_history') # Add key for localization - config["language"] = DEFAULT_CONSOLE_PREFS["language"] + config['language'] = DEFAULT_CONSOLE_PREFS['language'] # Migrate column settings - columns = ["queue", "size", "state", "progress", "seeds", "peers", "downspeed", "upspeed", - "eta", "ratio", "avail", "added", "tracker", "savepath", "downloaded", "uploaded", - "remaining", "owner", "downloading_time", "seeding_time", "completed", "seeds_peers_ratio", - "complete_seen", "down_limit", "up_limit", "shared", "name"] + columns = ['queue', 'size', 'state', 'progress', 'seeds', 'peers', 'downspeed', 'upspeed', + 'eta', 'ratio', 'avail', 'added', 'tracker', 'savepath', 'downloaded', 'uploaded', + 'remaining', 'owner', 'downloading_time', 'seeding_time', 'completed', 'seeds_peers_ratio', + 'complete_seen', 'down_limit', 'up_limit', 'shared', 'name'] column_name_mapping = { - "downspeed": "download_speed", - "upspeed": "upload_speed", - "added": "time_added", - "savepath": "download_location", - "completed": "completed_time", - "complete_seen": "last_seen_complete", - "down_limit": "max_download_speed", - "up_limit": "max_upload_speed", - "downloading_time": "active_time" + 'downspeed': 'download_speed', + 'upspeed': 'upload_speed', + 'added': 'time_added', + 'savepath': 'download_location', + 'completed': 'completed_time', + 'complete_seen': 'last_seen_complete', + 'down_limit': 'max_download_speed', + 'up_limit': 'max_upload_speed', + 'downloading_time': 'active_time' } from deluge.ui.console.modes.torrentlist.torrentview import default_columns # These are moved to 'torrentview.columns' sub dict for k in columns: column_name = column_name_mapping.get(k, k) - config["torrentview"]["columns"][column_name] = {} - if k == "name": - config["torrentview"]["columns"][column_name]["visible"] = True + config['torrentview']['columns'][column_name] = {} + if k == 'name': + config['torrentview']['columns'][column_name]['visible'] = True else: - move_key(config, config["torrentview"]["columns"][column_name], "show_%s" % k, dest_key="visible") - move_key(config, config["torrentview"]["columns"][column_name], "%s_width" % k, dest_key="width") - config["torrentview"]["columns"][column_name]["order"] = default_columns[column_name]["order"] + move_key(config, config['torrentview']['columns'][column_name], 'show_%s' % k, dest_key='visible') + move_key(config, config['torrentview']['columns'][column_name], '%s_width' % k, dest_key='width') + config['torrentview']['columns'][column_name]['order'] = default_columns[column_name]['order'] return config @@ -501,21 +501,21 @@ class EventLog(component.Component): Prints out certain events as they are received from the core. """ def __init__(self): - component.Component.__init__(self, "EventLog") - self.console = component.get("ConsoleUI") - self.prefix = "{!event!}* [%H:%M:%S] " - self.date_change_format = "On {!yellow!}%a, %d %b %Y{!input!} %Z:" - - client.register_event_handler("TorrentAddedEvent", self.on_torrent_added_event) - client.register_event_handler("PreTorrentRemovedEvent", self.on_torrent_removed_event) - client.register_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed_event) - client.register_event_handler("TorrentFinishedEvent", self.on_torrent_finished_event) - client.register_event_handler("NewVersionAvailableEvent", self.on_new_version_available_event) - client.register_event_handler("SessionPausedEvent", self.on_session_paused_event) - client.register_event_handler("SessionResumedEvent", self.on_session_resumed_event) - client.register_event_handler("ConfigValueChangedEvent", self.on_config_value_changed_event) - client.register_event_handler("PluginEnabledEvent", self.on_plugin_enabled_event) - client.register_event_handler("PluginDisabledEvent", self.on_plugin_disabled_event) + component.Component.__init__(self, 'EventLog') + self.console = component.get('ConsoleUI') + self.prefix = '{!event!}* [%H:%M:%S] ' + self.date_change_format = 'On {!yellow!}%a, %d %b %Y{!input!} %Z:' + + client.register_event_handler('TorrentAddedEvent', self.on_torrent_added_event) + client.register_event_handler('PreTorrentRemovedEvent', self.on_torrent_removed_event) + client.register_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed_event) + client.register_event_handler('TorrentFinishedEvent', self.on_torrent_finished_event) + client.register_event_handler('NewVersionAvailableEvent', self.on_new_version_available_event) + client.register_event_handler('SessionPausedEvent', self.on_session_paused_event) + client.register_event_handler('SessionResumedEvent', self.on_session_resumed_event) + client.register_event_handler('ConfigValueChangedEvent', self.on_config_value_changed_event) + client.register_event_handler('PluginEnabledEvent', self.on_plugin_enabled_event) + client.register_event_handler('PluginDisabledEvent', self.on_plugin_disabled_event) self.previous_time = time.localtime(0) @@ -524,15 +524,15 @@ class EventLog(component.Component): return def on_torrent_status(status): - self.write("{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})" % - (status["name"], torrent_id)) + self.write('{!green!}Torrent Added: {!info!}%s ({!cyan!}%s{!info!})' % + (status['name'], torrent_id)) # 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) def on_torrent_removed_event(self, torrent_id): - self.write("{!red!}Torrent Removed: {!info!}%s ({!cyan!}%s{!info!})" % + self.write('{!red!}Torrent Removed: {!info!}%s ({!cyan!}%s{!info!})' % (self.console.get_torrent_name(torrent_id), torrent_id)) def on_torrent_state_changed_event(self, torrent_id, state): @@ -549,40 +549,40 @@ class EventLog(component.Component): if not t_name: return - self.write("%s: {!info!}%s ({!cyan!}%s{!info!})" % + self.write('%s: {!info!}%s ({!cyan!}%s{!info!})' % (state, t_name, torrent_id)) def on_torrent_finished_event(self, torrent_id): - if not deluge.common.windows_check() and component.get("TorrentList").config["ring_bell"]: + if not deluge.common.windows_check() and component.get('TorrentList').config['ring_bell']: import curses.beep curses.beep() - self.write("{!info!}Torrent Finished: %s ({!cyan!}%s{!info!})" % + self.write('{!info!}Torrent Finished: %s ({!cyan!}%s{!info!})' % (self.console.get_torrent_name(torrent_id), torrent_id)) def on_new_version_available_event(self, version): - self.write("{!input!}New Deluge version available: {!info!}%s" % + self.write('{!input!}New Deluge version available: {!info!}%s' % (version)) def on_session_paused_event(self): - self.write("{!input!}Session Paused") + self.write('{!input!}Session Paused') def on_session_resumed_event(self): - self.write("{!green!}Session Resumed") + self.write('{!green!}Session Resumed') def on_config_value_changed_event(self, key, value): - color = "{!white,black,bold!}" + color = '{!white,black,bold!}' try: color = colors.type_color[type(value)] except KeyError: pass - self.write("ConfigValueChanged: {!input!}%s: %s%s" % (key, color, value)) + self.write('ConfigValueChanged: {!input!}%s: %s%s' % (key, color, value)) def write(self, s): current_time = time.localtime() date_different = False - for field in ["tm_mday", "tm_mon", "tm_year"]: + for field in ['tm_mday', 'tm_mon', 'tm_year']: c = getattr(current_time, field) p = getattr(self.previous_time, field) if c != p: @@ -590,7 +590,7 @@ class EventLog(component.Component): if date_different: string = time.strftime(self.date_change_format) - self.console.write_event(" ") + self.console.write_event(' ') self.console.write_event(string) p = time.strftime(self.prefix) @@ -599,7 +599,7 @@ class EventLog(component.Component): self.previous_time = current_time def on_plugin_enabled_event(self, name): - self.write("PluginEnabled: {!info!}%s" % name) + self.write('PluginEnabled: {!info!}%s' % name) def on_plugin_disabled_event(self, name): - self.write("PluginDisabled: {!info!}%s" % name) + self.write('PluginDisabled: {!info!}%s' % name) diff --git a/deluge/ui/console/modes/add_util.py b/deluge/ui/console/modes/add_util.py index 88756f495..994f77429 100644 --- a/deluge/ui/console/modes/add_util.py +++ b/deluge/ui/console/modes/add_util.py @@ -22,7 +22,7 @@ log = logging.getLogger(__name__) def _bracket_fixup(path): - if path.find("[") == -1 and path.find("]") == -1: + if path.find('[') == -1 and path.find(']') == -1: return path sentinal = 256 while path.find(unichr(sentinal)) != -1: @@ -30,27 +30,27 @@ def _bracket_fixup(path): if sentinal > 65535: log.error("Can't fix brackets in path, path contains all possible sentinal characters") return path - newpath = path.replace("]", unichr(sentinal)) - newpath = newpath.replace("[", "[[]") - newpath = newpath.replace(unichr(sentinal), "[]]") + newpath = path.replace(']', unichr(sentinal)) + newpath = newpath.replace('[', '[[]') + newpath = newpath.replace(unichr(sentinal), '[]]') return newpath def add_torrent(t_file, options, success_cb, fail_cb, ress): t_options = {} - if options["path"]: - t_options["download_location"] = os.path.expanduser(options["path"]) - t_options["add_paused"] = options["add_paused"] + if options['path']: + t_options['download_location'] = os.path.expanduser(options['path']) + t_options['add_paused'] = options['add_paused'] - is_url = (options["path_type"] != 1) and (deluge.common.is_url(t_file) or options["path_type"] == 2) - is_magnet = not(is_url) and (options["path_type"] != 1) and deluge.common.is_magnet(t_file) + is_url = (options['path_type'] != 1) and (deluge.common.is_url(t_file) or options['path_type'] == 2) + is_magnet = not(is_url) and (options['path_type'] != 1) and deluge.common.is_magnet(t_file) if is_url or is_magnet: files = [t_file] else: files = glob.glob(_bracket_fixup(t_file)) num_files = len(files) - ress["total"] = num_files + ress['total'] = num_files if num_files <= 0: fail_cb("Doesn't exist", t_file, ress) @@ -65,7 +65,7 @@ def add_torrent(t_file, options, success_cb, fail_cb, ress): fail_cb("Doesn't exist", f, ress) continue if not os.path.isfile(f): - fail_cb("Is a directory", f, ress) + fail_cb('Is a directory', f, ress) continue try: diff --git a/deluge/ui/console/modes/addtorrents.py b/deluge/ui/console/modes/addtorrents.py index 2b6767b6b..70c202ec8 100644 --- a/deluge/ui/console/modes/addtorrents.py +++ b/deluge/ui/console/modes/addtorrents.py @@ -68,9 +68,9 @@ class AddTorrents(BaseMode): self.marked = set() self.last_mark = -1 - path = os.path.expanduser(self.console_config["addtorrents"]["last_path"]) + path = os.path.expanduser(self.console_config['addtorrents']['last_path']) - self.path_stack = ["/"] + path.strip("/").split("/") + self.path_stack = ['/'] + path.strip('/').split('/') self.path_stack_pos = len(self.path_stack) self.listing_files = [] self.listing_dirs = [] @@ -80,8 +80,8 @@ class AddTorrents(BaseMode): self.raw_rows_dirs = [] self.formatted_rows = [] - self.sort_column = self.console_config["addtorrents"]["sort_column"] - self.reverse_sort = self.console_config["addtorrents"]["reverse_sort"] + self.sort_column = self.console_config['addtorrents']['sort_column'] + self.reverse_sort = self.console_config['addtorrents']['reverse_sort'] BaseMode.__init__(self, stdscr, encoding) @@ -114,14 +114,14 @@ class AddTorrents(BaseMode): for f in listing: if os.path.isdir(os.path.join(path, f)): - if self.console_config["addtorrents"]["show_hidden_folders"]: + if self.console_config['addtorrents']['show_hidden_folders']: self.listing_dirs.append(f) - elif f[0] != ".": + elif f[0] != '.': self.listing_dirs.append(f) elif os.path.isfile(os.path.join(path, f)): - if self.console_config["addtorrents"]["show_misc_files"]: + if self.console_config['addtorrents']['show_misc_files']: self.listing_files.append(f) - elif f.endswith(".torrent"): + elif f.endswith('.torrent'): self.listing_files.append(f) for dirname in self.listing_dirs: @@ -162,15 +162,15 @@ class AddTorrents(BaseMode): self.__sort_rows() def __sort_rows(self): - self.console_config["addtorrents"]["sort_column"] = self.sort_column - self.console_config["addtorrents"]["reverse_sort"] = self.reverse_sort + self.console_config['addtorrents']['sort_column'] = self.sort_column + self.console_config['addtorrents']['reverse_sort'] = self.reverse_sort self.console_config.save() self.raw_rows_dirs.sort(key=lambda r: r[0].lower()) - if self.sort_column == "name": + if self.sort_column == 'name': self.raw_rows_files.sort(key=lambda r: r[0].lower(), reverse=self.reverse_sort) - elif self.sort_column == "date": + elif self.sort_column == 'date': self.raw_rows_files.sort(key=lambda r: r[2], reverse=self.reverse_sort) self.raw_rows = self.raw_rows_dirs + self.raw_rows_files self.__refresh_rows() @@ -185,9 +185,9 @@ class AddTorrents(BaseMode): if row[4]: if size != -1: - size_str = "%i items" % size + size_str = '%i items' % size else: - size_str = " unknown" + size_str = ' unknown' cols = [filename, size_str, deluge.common.fdate(time)] widths = [self.cols - 35, 12, 23] @@ -237,44 +237,44 @@ class AddTorrents(BaseMode): off = 1 # Render breadcrumbs - s = "Location: " + s = 'Location: ' for i, e in enumerate(self.path_stack): - if e == "/": + if e == '/': if i == self.path_stack_pos - 1: - s += "{!black,red,bold!}root" + s += '{!black,red,bold!}root' else: - s += "{!red,black,bold!}root" + s += '{!red,black,bold!}root' else: if i == self.path_stack_pos - 1: - s += "{!black,white,bold!}%s" % e + s += '{!black,white,bold!}%s' % e else: - s += "{!white,black,bold!}%s" % e + s += '{!white,black,bold!}%s' % e if e != len(self.path_stack) - 1: - s += "{!white,black!}/" + s += '{!white,black!}/' self.add_string(off, s) off += 1 # Render header - cols = ["Name", "Contents", "Modification time"] + cols = ['Name', 'Contents', 'Modification time'] widths = [self.cols - 35, 12, 23] - s = "" + s = '' for i, (c, w) in enumerate(zip(cols, widths)): - cn = "" + cn = '' if i == 0: - cn = "name" + cn = 'name' elif i == 2: - cn = "date" + cn = 'date' if cn == self.sort_column: - s += "{!black,green,bold!}" + c.ljust(w - 2) + s += '{!black,green,bold!}' + c.ljust(w - 2) if self.reverse_sort: - s += "^ " + s += '^ ' else: - s += "v " + s += 'v ' else: - s += "{!green,black,bold!}" + c.ljust(w) + s += '{!green,black,bold!}' + c.ljust(w) self.add_string(off, s) off += 1 @@ -282,26 +282,26 @@ class AddTorrents(BaseMode): for i, row in enumerate(self.formatted_rows[self.view_offset:]): i += self.view_offset # It's a folder - color_string = "" + color_string = '' if self.raw_rows[i][4]: if self.raw_rows[i][1] == -1: if i == self.cursel: - color_string = "{!black,red,bold!}" + color_string = '{!black,red,bold!}' else: - color_string = "{!red,black!}" + color_string = '{!red,black!}' else: if i == self.cursel: - color_string = "{!black,cyan,bold!}" + color_string = '{!black,cyan,bold!}' else: - color_string = "{!cyan,black!}" + color_string = '{!cyan,black!}' elif i == self.cursel: if self.raw_rows[i][0] in self.marked: - color_string = "{!blue,white,bold!}" + color_string = '{!blue,white,bold!}' else: - color_string = "{!black,white,bold!}" + color_string = '{!black,white,bold!}' elif self.raw_rows[i][0] in self.marked: - color_string = "{!white,blue,bold!}" + color_string = '{!white,blue,bold!}' self.add_string(off, color_string + row) off += 1 @@ -309,7 +309,7 @@ class AddTorrents(BaseMode): if off > self.rows - 2: break - if not component.get("ConsoleUI").is_active_mode(self): + if not component.get('ConsoleUI').is_active_mode(self): return self.stdscr.noutrefresh() @@ -321,7 +321,7 @@ class AddTorrents(BaseMode): def back_to_overview(self): self.parent_mode.go_top = False - component.get("ConsoleUI").set_mode(self.parent_mode.mode_name) + component.get('ConsoleUI').set_mode(self.parent_mode.mode_name) def _perform_action(self): if self.cursel < len(self.listing_dirs): @@ -346,7 +346,7 @@ class AddTorrents(BaseMode): if not os.access(path, os.R_OK): self.path_stack = self.path_stack[:self.path_stack_pos] - self.popup = MessagePopup(self, "Error", "{!error!}Access denied: %s" % path) + self.popup = MessagePopup(self, 'Error', '{!error!}Access denied: %s' % path) self.__refresh_listing() return @@ -362,23 +362,23 @@ class AddTorrents(BaseMode): def _show_add_dialog(self): def _do_add(result, **kwargs): - ress = {"succ": 0, "fail": 0, "total": len(self.marked), "fmsg": []} + ress = {'succ': 0, 'fail': 0, 'total': len(self.marked), 'fmsg': []} def fail_cb(msg, t_file, ress): - log.debug("failed to add torrent: %s: %s", t_file, msg) - ress["fail"] += 1 - ress["fmsg"].append("{!input!} * %s: {!error!}%s" % (t_file, msg)) - if (ress["succ"] + ress["fail"]) >= ress["total"]: - report_add_status(component.get("TorrentList"), ress["succ"], ress["fail"], ress["fmsg"]) + log.debug('failed to add torrent: %s: %s', t_file, msg) + ress['fail'] += 1 + ress['fmsg'].append('{!input!} * %s: {!error!}%s' % (t_file, msg)) + if (ress['succ'] + ress['fail']) >= ress['total']: + report_add_status(component.get('TorrentList'), ress['succ'], ress['fail'], ress['fmsg']) def success_cb(tid, t_file, ress): if tid: - log.debug("added torrent: %s (%s)", t_file, tid) - ress["succ"] += 1 - if (ress["succ"] + ress["fail"]) >= ress["total"]: - report_add_status(component.get("TorrentList"), ress["succ"], ress["fail"], ress["fmsg"]) + log.debug('added torrent: %s (%s)', t_file, tid) + ress['succ'] += 1 + if (ress['succ'] + ress['fail']) >= ress['total']: + report_add_status(component.get('TorrentList'), ress['succ'], ress['fail'], ress['fmsg']) else: - fail_cb("Already in session (probably)", t_file, ress) + fail_cb('Already in session (probably)', t_file, ress) for m in self.marked: filename = m @@ -387,39 +387,39 @@ class AddTorrents(BaseMode): with open(path) as _file: filedump = base64.encodestring(_file.read()) t_options = {} - if result["location"]["value"]: - t_options["download_location"] = result["location"]["value"] - t_options["add_paused"] = result["add_paused"]["value"] + if result['location']['value']: + t_options['download_location'] = result['location']['value'] + t_options['add_paused'] = result['add_paused']['value'] d = client.core.add_torrent_file(filename, filedump, t_options) d.addCallback(success_cb, filename, ress) d.addErrback(fail_cb, filename, ress) - self.console_config["addtorrents"]["last_path"] = os.path.join(*self.path_stack[:self.path_stack_pos]) + self.console_config['addtorrents']['last_path'] = os.path.join(*self.path_stack[:self.path_stack_pos]) self.console_config.save() self.back_to_overview() - config = component.get("ConsoleUI").coreconfig - if config["add_paused"]: + config = component.get('ConsoleUI').coreconfig + if config['add_paused']: ap = 0 else: ap = 1 - self.popup = InputPopup(self, "Add Torrents (Esc to cancel)", close_cb=_do_add, height_req=17) + self.popup = InputPopup(self, 'Add Torrents (Esc to cancel)', close_cb=_do_add, height_req=17) - msg = "Adding torrent files:" + msg = 'Adding torrent files:' for i, m in enumerate(self.marked): name = m - msg += "\n * {!input!}%s" % name + msg += '\n * {!input!}%s' % name if i == 5: if i < len(self.marked): - msg += "\n {!red!}And %i more" % (len(self.marked) - 5) + msg += '\n {!red!}And %i more' % (len(self.marked) - 5) break self.popup.add_text(msg) self.popup.add_spaces(1) - self.popup.add_text_input("location", "Download Folder:", config["download_location"], complete=True) - self.popup.add_select_input("add_paused", "Add Paused:", ["Yes", "No"], [True, False], ap) + self.popup.add_text_input('location', 'Download Folder:', config['download_location'], complete=True) + self.popup.add_select_input('add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], ap) def _go_up(self): # Go up in directory hierarchy @@ -443,7 +443,7 @@ class AddTorrents(BaseMode): return if util.is_printable_char(c): - if chr(c) == "Q": + if chr(c) == 'Q': from twisted.internet import reactor if client.connected(): def on_disconnect(result): @@ -452,7 +452,7 @@ class AddTorrents(BaseMode): else: reactor.stop() return - elif chr(c) == "q": + elif chr(c) == 'q': self.back_to_overview() return @@ -480,23 +480,23 @@ class AddTorrents(BaseMode): self.back_to_overview() else: if util.is_printable_char(c): - if chr(c) == "h": - self.popup = MessagePopup(self, "Help", HELP_STR, width_req=0.75) - elif chr(c) == ">": - if self.sort_column == "date": + if chr(c) == 'h': + self.popup = MessagePopup(self, 'Help', HELP_STR, width_req=0.75) + elif chr(c) == '>': + if self.sort_column == 'date': self.reverse_sort = not self.reverse_sort else: - self.sort_column = "date" + self.sort_column = 'date' self.reverse_sort = True self.__sort_rows() - elif chr(c) == "<": - if self.sort_column == "name": + elif chr(c) == '<': + if self.sort_column == 'name': self.reverse_sort = not self.reverse_sort else: - self.sort_column = "name" + self.sort_column = 'name' self.reverse_sort = False self.__sort_rows() - elif chr(c) == "m": + elif chr(c) == 'm': s = self.raw_rows[self.cursel][0] if s in self.marked: self.marked.remove(s) @@ -504,11 +504,11 @@ class AddTorrents(BaseMode): self.marked.add(s) self.last_mark = self.cursel - elif chr(c) == "j": + elif chr(c) == 'j': self.scroll_list_up(1) - elif chr(c) == "k": + elif chr(c) == 'k': self.scroll_list_down(1) - elif chr(c) == "M": + elif chr(c) == 'M': if self.last_mark != -1: if self.last_mark > self.cursel: m = range(self.cursel, self.last_mark) diff --git a/deluge/ui/console/modes/basemode.py b/deluge/ui/console/modes/basemode.py index 416554d80..dffb980a2 100644 --- a/deluge/ui/console/modes/basemode.py +++ b/deluge/ui/console/modes/basemode.py @@ -67,11 +67,11 @@ class TermResizeHandler(object): try: signal.signal(signal.SIGWINCH, self.on_terminal_size) except ValueError as ex: - log.debug("Unable to catch SIGWINCH signal: %s", ex) + log.debug('Unable to catch SIGWINCH signal: %s', ex) def on_terminal_size(self, *args): # Get the new rows and cols value - rows, cols = struct.unpack("hhhh", ioctl(0, termios.TIOCGWINSZ, "\000" * 8))[0:2] + rows, cols = struct.unpack('hhhh', ioctl(0, termios.TIOCGWINSZ, '\000' * 8))[0:2] curses.resizeterm(rows, cols) return rows, cols @@ -91,7 +91,7 @@ class CursesStdIO(object): pass def logPrefix(self): # NOQA - return "CursesClient" + return 'CursesClient' class BaseMode(CursesStdIO, component.Component): @@ -125,8 +125,8 @@ class BaseMode(CursesStdIO, component.Component): self.paused = False # Strings for the 2 status bars - self.statusbars = component.get("StatusBars") - self.help_hstr = "{!status!} Press {!magenta,blue,bold!}[h]{!status!} for help" + self.statusbars = component.get('StatusBars') + self.help_hstr = '{!status!} Press {!magenta,blue,bold!}[h]{!status!} for help' # Keep track of the screen size self.rows, self.cols = self.stdscr.getmaxyx() @@ -161,7 +161,7 @@ class BaseMode(CursesStdIO, component.Component): if bottombar_help: if bottombar_help is True: bottombar_help = self.help_hstr - bottombar += " " * (self.cols - len(remove_formatting(bottombar)) - + bottombar += ' ' * (self.cols - len(remove_formatting(bottombar)) - len(remove_formatting(bottombar_help))) + bottombar_help self.add_string(self.rows + bottom_row, bottombar, scr=scr) @@ -219,7 +219,7 @@ class BaseMode(CursesStdIO, component.Component): curses.endwin() -def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", trim="...", leaveok=0): +def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=' ', trim='...', leaveok=0): """ Adds a string to the desired `:param:row`. @@ -256,7 +256,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri try: parsed = colors.parse_color_string(string, encoding) except colors.BadColorString as ex: - log.error("Cannot add bad color string %s: %s", string, ex) + log.error('Cannot add bad color string %s: %s', string, ex) return if leaveok: @@ -274,7 +274,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri if (col + len(s)) > max_x: if trim: - s = "%s%s" % (s[0:max_x - len(trim) - col], trim) + s = '%s%s' % (s[0:max_x - len(trim) - col], trim) else: s = s[0:max_x - col] @@ -290,7 +290,7 @@ def add_string(row, string, screen, encoding, col=0, pad=True, pad_char=" ", tri log.warn("FAILED on call screen.addstr(%s, %s, '%s', %s) - max_y: %s, max_x: %s, " "curses.LINES: %s, curses.COLS: %s, Error: '%s', trace:\n%s", row, col, s, color, max_y, max_x, curses.LINES, curses.COLS, ex, - "".join(traceback.format_stack(limit=5))) + ''.join(traceback.format_stack(limit=5))) col += len(s) @@ -334,4 +334,4 @@ def move_cursor(screen, row, col): except curses.error as ex: import traceback log.warn("Error on screen.move(%s, %s): (curses.LINES: %s, curses.COLS: %s) Error: '%s'\nStack: %s", - row, col, curses.LINES, curses.COLS, ex, "".join(traceback.format_stack())) + row, col, curses.LINES, curses.COLS, ex, ''.join(traceback.format_stack())) diff --git a/deluge/ui/console/modes/cmdline.py b/deluge/ui/console/modes/cmdline.py index a82197a4e..8afd6c39c 100644 --- a/deluge/ui/console/modes/cmdline.py +++ b/deluge/ui/console/modes/cmdline.py @@ -36,20 +36,20 @@ MAX_HISTFILE_SIZE = 2000 def complete_line(line, possible_matches): - "Find the common prefix of possible matches, proritizing matching-case elements" + 'Find the common prefix of possible matches, proritizing matching-case elements' if not possible_matches: return line - line = line.replace(r"\ ", " ") + line = line.replace(r'\ ', ' ') matches1 = [] matches2 = [] for match in possible_matches: match = remove_formatting(match) - match = match.replace(r"\ ", " ") - m1, m2 = "", "" + match = match.replace(r'\ ', ' ') + m1, m2 = '', '' for i, c in enumerate(line): if m1 and m2: break @@ -76,13 +76,13 @@ def complete_line(line, possible_matches): maxlen = min(maxlen, i) break - return possible_matches[0][:maxlen].replace(" ", r"\ ") + return possible_matches[0][:maxlen].replace(' ', r'\ ') def commonprefix(m): - "Given a list of pathnames, returns the longest common leading component" + 'Given a list of pathnames, returns the longest common leading component' if not m: - return "" + return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): @@ -95,7 +95,7 @@ class CmdLine(BaseMode, Commander): def __init__(self, stdscr, encoding=None): # Get a handle to the main console - self.console = component.get("ConsoleUI") + self.console = component.get('ConsoleUI') Commander.__init__(self, self.console._commands, interactive=True) self.batch_write = False @@ -106,8 +106,8 @@ class CmdLine(BaseMode, Commander): self.display_lines_offset = 0 # Holds the user input and is cleared on 'enter' - self.input = u"" - self.input_incomplete = u"" + self.input = u'' + self.input_incomplete = u'' # Keep track of where the cursor is self.input_cursor = 0 @@ -118,7 +118,7 @@ class CmdLine(BaseMode, Commander): # Keep track of double- and multi-tabs self.tab_count = 0 - self.console_config = component.get("TorrentList").config + self.console_config = component.get('TorrentList').config # To avoid having to truncate the file every time we're writing # or doing it on exit(and therefore relying on an error-less @@ -126,13 +126,13 @@ class CmdLine(BaseMode, Commander): # that we swap around based on length config_dir = deluge.configmanager.get_config_dir() self.history_file = [ - os.path.join(config_dir, "cmd_line.hist1"), - os.path.join(config_dir, "cmd_line.hist2") + os.path.join(config_dir, 'cmd_line.hist1'), + os.path.join(config_dir, 'cmd_line.hist2') ] self._hf_lines = [0, 0] - if self.console_config["cmdline"]["save_command_history"]: + if self.console_config['cmdline']['save_command_history']: try: - with open(self.history_file[0], "r") as _file: + with open(self.history_file[0], 'r') as _file: lines1 = _file.read().splitlines() self._hf_lines[0] = len(lines1) except IOError: @@ -140,7 +140,7 @@ class CmdLine(BaseMode, Commander): self._hf_lines[0] = 0 try: - with open(self.history_file[1], "r") as _file: + with open(self.history_file[1], 'r') as _file: lines2 = _file.read().splitlines() self._hf_lines[1] = len(lines2) except IOError: @@ -163,9 +163,9 @@ class CmdLine(BaseMode, Commander): # line = line.encode(self.encoding) # self.lines[i] = line line = remove_formatting(line) - if line.startswith(">>> "): + if line.startswith('>>> '): console_input = line[4:] - if self.console_config["cmdline"]["ignore_duplicate_lines"]: + if self.console_config['cmdline']['ignore_duplicate_lines']: if len(self.input_history) > 0: if self.input_history[-1] != console_input: self.input_history.append(console_input) @@ -176,11 +176,11 @@ class CmdLine(BaseMode, Commander): # show the cursor util.safe_curs_set(util.Curser.VERY_VISIBLE) - BaseMode.__init__(self, stdscr, encoding, depend=["SessionProxy"]) + BaseMode.__init__(self, stdscr, encoding, depend=['SessionProxy']) @overrides(component.Component) def update(self): - if not component.get("ConsoleUI").is_active_mode(self): + if not component.get('ConsoleUI').is_active_mode(self): return # Update just the status bars self.draw_statusbars(bottom_row=-2, bottombar_help=False) @@ -215,16 +215,16 @@ class CmdLine(BaseMode, Commander): # We clear the input string and send it to the command parser on ENTER if c in [curses.KEY_ENTER, util.KEY_ENTER2]: if self.input: - if self.input.endswith("\\"): + if self.input.endswith('\\'): self.input = self.input[:-1] self.input_cursor -= 1 - self.add_line("{!yellow,black,bold!}>>>{!input!} %s" % self.input) + self.add_line('{!yellow,black,bold!}>>>{!input!} %s' % self.input) self.do_command(self.input) if len(self.input_history) == INPUT_HISTORY_SIZE: # Remove the oldest input history if the max history size # is reached. del self.input_history[0] - if self.console_config["cmdline"]["ignore_duplicate_lines"]: + if self.console_config['cmdline']['ignore_duplicate_lines']: if len(self.input_history) > 0: if self.input_history[-1] != self.input: self.input_history.append(self.input) @@ -233,8 +233,8 @@ class CmdLine(BaseMode, Commander): else: self.input_history.append(self.input) self.input_history_index = len(self.input_history) - self.input = u"" - self.input_incomplete = u"" + self.input = u'' + self.input_incomplete = u'' self.input_cursor = 0 self.stdscr.refresh() @@ -246,7 +246,7 @@ class CmdLine(BaseMode, Commander): if self.tab_completer: # We only call the tab completer function if we're at the end of # the input string on the cursor is on a space - if self.input_cursor == len(self.input) or self.input[self.input_cursor] == " ": + if self.input_cursor == len(self.input) or self.input[self.input_cursor] == ' ': self.input, self.input_cursor = self.tab_completer(self.input, self.input_cursor, self.tab_count) # We use the UP and DOWN keys to cycle through input history @@ -315,7 +315,7 @@ class CmdLine(BaseMode, Commander): if c > 31 and c < 256: # Emulate getwch stroke = chr(c) - uchar = "" + uchar = '' while not uchar: try: uchar = stroke.decode(self.encoding) @@ -348,7 +348,7 @@ class CmdLine(BaseMode, Commander): Updates the lines based on the`:attr:lines` based on the `:attr:display_lines_offset` attribute and the status bars. """ - if not component.get("ConsoleUI").is_active_mode(self): + if not component.get('ConsoleUI').is_active_mode(self): return self.stdscr.erase() @@ -367,7 +367,7 @@ class CmdLine(BaseMode, Commander): elif len(self.lines) == available_lines: lines = self.lines else: - lines = [""] * (available_lines - len(self.lines)) + lines = [''] * (available_lines - len(self.lines)) lines.extend(self.lines) # Add the lines to the screen @@ -408,7 +408,7 @@ class CmdLine(BaseMode, Commander): """ - if self.console_config["cmdline"]["save_command_history"]: + if self.console_config['cmdline']['save_command_history']: # Determine which file is the active one # 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: @@ -419,7 +419,7 @@ class CmdLine(BaseMode, Commander): active_file = 0 # Write the line - with open(self.history_file[active_file], "a") as _file: + with open(self.history_file[active_file], 'a') as _file: if isinstance(text, unicode): text = text.encode(self.encoding) _file.write(text) @@ -432,7 +432,7 @@ class CmdLine(BaseMode, Commander): # therefore swapping the currently active file if self._hf_lines[active_file] == MAX_HISTFILE_SIZE: self._hf_lines[1 - active_file] = 0 - with open(self.history_file[1 - active_file], "w") as _file: + with open(self.history_file[1 - active_file], 'w') as _file: _file.truncate(0) def get_line_chunks(line): @@ -440,21 +440,21 @@ class CmdLine(BaseMode, Commander): Returns a list of 2-tuples (color string, text) """ - if not line or line.count("{!") != line.count("!}"): + if not line or line.count('{!') != line.count('!}'): return [] chunks = [] - if not line.startswith("{!"): - begin = line.find("{!") + if not line.startswith('{!'): + begin = line.find('{!') if begin == -1: begin = len(line) - chunks.append(("", line[:begin])) + chunks.append(('', line[:begin])) line = line[begin:] while line: # We know the line starts with "{!" here - end_color = line.find("!}") - next_color = line.find("{!", end_color) + end_color = line.find('!}') + next_color = line.find('{!', end_color) if next_color == -1: next_color = len(line) chunks.append((line[:end_color + 2], line[end_color + 2:next_color])) @@ -466,11 +466,11 @@ class CmdLine(BaseMode, Commander): try: line_length = colors.get_line_width(line) except colors.BadColorString: - log.error("Passed a bad colored line: %s", line) + log.error('Passed a bad colored line: %s', line) continue if line_length >= (self.cols - 1): - s = "" + s = '' # The length of the text without the color tags s_len = 0 # We need to split this over multiple lines @@ -515,13 +515,13 @@ class CmdLine(BaseMode, Commander): try: parsed = colors.parse_color_string(string, self.encoding) except colors.BadColorString as ex: - log.error("Cannot add bad color string %s: %s", string, ex) + log.error('Cannot add bad color string %s: %s', string, ex) return for index, (color, s) in enumerate(parsed): if index + 1 == len(parsed): # This is the last string so lets append some " " to it - s += " " * (self.cols - (col + strwidth(s)) - 1) + s += ' ' * (self.cols - (col + strwidth(s)) - 1) try: self.stdscr.addstr(row, col, s, color) except curses.error: @@ -571,9 +571,9 @@ class CmdLine(BaseMode, Commander): # We don't want to split by escaped spaces def split(string): - return re.split(r"(?<!\\) ", string) + return re.split(r'(?<!\\) ', string) - if " " not in line: + if ' ' not in line: possible_matches = [] # Iterate through the commands looking for ones that startwith the # line. @@ -581,13 +581,13 @@ class CmdLine(BaseMode, Commander): if cmd.startswith(line): possible_matches.append(cmd) - line_prefix = "" + line_prefix = '' else: cmd = split(line)[0] if cmd in self.console._commands: # Call the command's complete method to get 'er done possible_matches = self.console._commands[cmd].complete(split(line)[-1]) - line_prefix = " ".join(split(line)[:-1]) + " " + line_prefix = ' '.join(split(line)[:-1]) + ' ' else: # This is a bogus command return (line, cursor) @@ -601,70 +601,70 @@ class CmdLine(BaseMode, Commander): elif len(possible_matches) == 1: # Do not append space after directory names new_line = line_prefix + possible_matches[0] - if not new_line.endswith("/") and not new_line.endswith(r"\\"): - new_line += " " + if not new_line.endswith('/') and not new_line.endswith(r'\\'): + new_line += ' ' # We only want to print eventual colors or other control characters, not return them new_line = remove_formatting(new_line) return (new_line, len(new_line)) else: if hits == 1: - p = " ".join(split(line)[:-1]) + p = ' '.join(split(line)[:-1]) try: l_arg = split(line)[-1] except IndexError: - l_arg = "" + l_arg = '' - new_line = " ".join([p, complete_line(l_arg, possible_matches)]).lstrip() + new_line = ' '.join([p, complete_line(l_arg, possible_matches)]).lstrip() if len(remove_formatting(new_line)) > len(line): line = new_line cursor = len(line) elif hits >= 2: - max_list = self.console_config["cmdline"]["torrents_per_tab_press"] + max_list = self.console_config['cmdline']['torrents_per_tab_press'] match_count = len(possible_matches) listed = (hits - 2) * max_list pages = (match_count - 1) // max_list + 1 left = match_count - listed if hits == 2: - self.write(" ") + self.write(' ') 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 - if self.console_config["cmdline"]["third_tab_lists_all"]: + if self.console_config['cmdline']['third_tab_lists_all']: if hits == 2 and left > max_list: for i in range(listed, listed + max_list): match = possible_matches[i] - self.write(match.replace(r"\ ", " ")) - self.write("{!error!}And %i more. Press <tab> to list them" % (left - max_list)) + self.write(match.replace(r'\ ', ' ')) + self.write('{!error!}And %i more. Press <tab> to list them' % (left - max_list)) else: self.tab_count = 0 for match in possible_matches[listed:]: - self.write(match.replace(r"\ ", " ")) + self.write(match.replace(r'\ ', ' ')) else: if left > max_list: for i in range(listed, listed + max_list): match = possible_matches[i] - self.write(match.replace(r"\ ", " ")) - self.write("{!error!}And %i more (%i/%i). Press <tab> to view more" % ( + self.write(match.replace(r'\ ', ' ')) + self.write('{!error!}And %i more (%i/%i). Press <tab> to view more' % ( left - max_list, hits - 1, pages)) else: self.tab_count = 0 for match in possible_matches[listed:]: - self.write(match.replace(r"\ ", " ")) + self.write(match.replace(r'\ ', ' ')) 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 line = remove_formatting(line) cursor = len(line) return (line, cursor) - def tab_complete_path(self, line, path_type="file", ext="", sort="name", dirs_first=1): - self.console = component.get("ConsoleUI") + def tab_complete_path(self, line, path_type='file', ext='', sort='name', dirs_first=1): + self.console = component.get('ConsoleUI') - line = line.replace("\\ ", " ") + line = line.replace('\\ ', ' ') line = os.path.abspath(os.path.expanduser(line)) ret = [] if os.path.exists(line): @@ -675,19 +675,19 @@ class CmdLine(BaseMode, Commander): try: for f in os.listdir(line): # Skip hidden - if f.startswith("."): + if f.startswith('.'): continue f = os.path.join(line, f) if os.path.isdir(f): - if os.sep == "\\": # Windows path support - f += "\\" + if os.sep == '\\': # Windows path support + f += '\\' else: # Unix - f += "/" + f += '/' elif not f.endswith(ext): continue ret.append(f) except OSError: - self.console.write("{!error!}Permission denied: {!info!}%s" % line) + self.console.write('{!error!}Permission denied: {!info!}%s' % line) else: try: # This is a file, but we could be looking for another file that @@ -696,7 +696,7 @@ class CmdLine(BaseMode, Commander): if f.startswith(os.path.split(line)[1]): ret.append(os.path.join(os.path.dirname(line), f)) except OSError: - self.console.write("{!error!}Permission denied: {!info!}%s" % line) + self.console.write('{!error!}Permission denied: {!info!}%s' % line) else: # This path does not exist, so lets do a listdir on it's parent # and find any matches. @@ -708,15 +708,15 @@ class CmdLine(BaseMode, Commander): p = os.path.join(os.path.dirname(line), f) if os.path.isdir(p): - if os.sep == "\\": # Windows path support - p += "\\" + if os.sep == '\\': # Windows path support + p += '\\' else: # Unix - p += "/" + p += '/' ret.append(p) except OSError: - self.console.write("{!error!}Permission denied: {!info!}%s" % line) + self.console.write('{!error!}Permission denied: {!info!}%s' % line) - if sort == "date": + if sort == 'date': ret = sorted(ret, key=os.path.getmtime, reverse=True) if dirs_first == 1: @@ -727,10 +727,10 @@ class CmdLine(BaseMode, Commander): # Highlight directory names for i, filename in enumerate(ret): if os.path.isdir(filename): - ret[i] = "{!cyan!}%s" % filename + ret[i] = '{!cyan!}%s' % filename for i in range(0, len(ret)): - ret[i] = ret[i].replace(" ", r"\ ") + ret[i] = ret[i].replace(' ', r'\ ') return ret def tab_complete_torrent(self, line): @@ -746,11 +746,11 @@ class CmdLine(BaseMode, Commander): empty = len(line) == 0 # Remove dangling backslashes to avoid breaking shlex - if line.endswith("\\"): + if line.endswith('\\'): line = line[:-1] raw_line = line - line = line.replace("\\ ", " ") + line = line.replace('\\ ', ' ') possible_matches = [] possible_matches2 = [] @@ -769,7 +769,7 @@ class CmdLine(BaseMode, Commander): for torrent_id, torrent_name in self.console.torrents: # Escape spaces to avoid, for example, expanding "Doc" into "Doctor Who" and removing # everything containing one of these words - escaped_name = torrent_name.replace(" ", "\\ ") + escaped_name = torrent_name.replace(' ', '\\ ') # If we only matched one torrent, don't add the full name or it'll also get autocompleted if match_count == 1: if torrent_id.startswith(line): @@ -791,11 +791,11 @@ class CmdLine(BaseMode, Commander): text = "{!info!}%s{!input!}%s - '%s'" % (torrent_id[:l], torrent_id[l:], torrent_name) possible_matches.append(text) if torrent_name.startswith(line): - text = "{!info!}%s{!input!}%s ({!cyan!}%s{!input!})" % ( + text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % ( escaped_name[:l], escaped_name[l:], torrent_id) possible_matches.append(text) elif torrent_name.lower().startswith(line.lower()): - text = "{!info!}%s{!input!}%s ({!cyan!}%s{!input!})" % ( + text = '{!info!}%s{!input!}%s ({!cyan!}%s{!input!})' % ( escaped_name[:l], escaped_name[l:], torrent_id) possible_matches2.append(text) diff --git a/deluge/ui/console/modes/connectionmanager.py b/deluge/ui/console/modes/connectionmanager.py index 90a7f0665..168d086dd 100644 --- a/deluge/ui/console/modes/connectionmanager.py +++ b/deluge/ui/console/modes/connectionmanager.py @@ -33,7 +33,7 @@ class ConnectionManager(BaseMode, PopupsHandler): PopupsHandler.__init__(self) self.statuses = {} self.all_torrents = None - self.config = ConfigManager("hostlist.conf.1.2", uicommon.DEFAULT_HOSTS) + self.config = ConfigManager('hostlist.conf.1.2', uicommon.DEFAULT_HOSTS) self.update_hosts_status() BaseMode.__init__(self, stdscr, encoding=encoding) self.update_select_host_popup() @@ -43,19 +43,19 @@ class ConnectionManager(BaseMode, PopupsHandler): if self.popup: selected_index = self.popup.current_selection() - popup = SelectablePopup(self, _("Select Host"), self._host_selected, border_off_west=1, active_wrap=True) + popup = SelectablePopup(self, _('Select Host'), self._host_selected, border_off_west=1, active_wrap=True) popup.add_header("{!white,black,bold!}'Q'=%s, 'a'=%s, 'D'=%s" % - (_("quit"), _("add new host"), _("delete host")), + (_('quit'), _('add new host'), _('delete host')), space_below=True) self.push_popup(popup, clear=True) - for host in self.config["hosts"]: - args = {"data": host[0], "foreground": "red"} - state = "Offline" + for host in self.config['hosts']: + args = {'data': host[0], 'foreground': 'red'} + state = 'Offline' if host[0] in self.statuses: - state = "Online" - args.update({"data": self.statuses[host[0]], "foreground": "green"}) - host_str = "%s:%d [%s]" % (host[1], host[2], state) + state = 'Online' + args.update({'data': self.statuses[host[0]], 'foreground': 'green'}) + host_str = '%s:%d [%s]' % (host[1], host[2], state) self.popup.add_line(host[0], host_str, selectable=True, use_underline=True, **args) if selected_index is not None: @@ -85,34 +85,34 @@ class ConnectionManager(BaseMode, PopupsHandler): del self.statuses[host_id] self.update_select_host_popup() - for host in self.config["hosts"]: + for host in self.config['hosts']: c = Client() hadr = host[1] port = host[2] user = host[3] password = host[4] - log.debug("connect: hadr=%s, port=%s, user=%s, password=%s", hadr, port, user, password) + log.debug('connect: hadr=%s, port=%s, user=%s, password=%s', hadr, port, user, password) d = c.connect(hadr, port, user, password) d.addCallback(on_connect, c, host[0]) d.addErrback(on_connect_failed, host[0]) def _on_connected(self, result): - d = component.get("ConsoleUI").start_console() + d = component.get('ConsoleUI').start_console() def on_console_start(result): - component.get("ConsoleUI").set_mode("TorrentList") + component.get('ConsoleUI').set_mode('TorrentList') d.addCallback(on_console_start) def _on_connect_fail(self, result): - self.report_message("Failed to connect!", result) + self.report_message('Failed to connect!', result) self.refresh() - if hasattr(result, "getTraceback"): + if hasattr(result, 'getTraceback'): log.exception(result) def _host_selected(self, selected_host, *args, **kwargs): if selected_host not in self.statuses: return - for host in self.config["hosts"]: + for host in self.config['hosts']: if host[0] == selected_host: d = client.connect(host[1], host[2], host[3], host[4]) d.addCallback(self._on_connected) @@ -121,44 +121,44 @@ class ConnectionManager(BaseMode, PopupsHandler): return False def _do_add(self, result, **kwargs): - if not result or kwargs.get("close", False): + if not result or kwargs.get('close', False): self.pop_popup() return - hostname = result["hostname"]["value"] + hostname = result['hostname']['value'] try: - port = int(result["port"]["value"]) + port = int(result['port']['value']) except ValueError: - self.report_message("Can't add host", "Invalid port. Must be an integer") + self.report_message("Can't add host", 'Invalid port. Must be an integer') return - username = result["username"]["value"] - password = result["password"]["value"] - for host in self.config["hosts"]: + username = result['username']['value'] + password = result['password']['value'] + for host in self.config['hosts']: if (host[1], host[2], host[3]) == (hostname, port, username): - self.report_message("Can't add host", "Host already in list") + self.report_message("Can't add host", 'Host already in list') return newid = hashlib.sha1(str(time.time())).hexdigest() - self.config["hosts"].append((newid, hostname, port, username, password)) + self.config['hosts'].append((newid, hostname, port, username, password)) self.config.save() self.update_select_host_popup() def add_popup(self): self.inlist = False - popup = InputPopup(self, "Add Host (up & down arrows to navigate, esc to cancel)", + popup = InputPopup(self, 'Add Host (up & down arrows to navigate, esc to cancel)', border_off_north=1, border_off_east=1, close_cb=self._do_add) - popup.add_text_input("hostname", "%s:" % _("Hostname")) - popup.add_text_input("port", "%s:" % _("Port")) - popup.add_text_input("username", "%s:" % _("Username")) - popup.add_text_input("password", "%s:" % _("Password")) + popup.add_text_input('hostname', '%s:' % _('Hostname')) + popup.add_text_input('port', '%s:' % _('Port')) + popup.add_text_input('username', '%s:' % _('Username')) + popup.add_text_input('password', '%s:' % _('Password')) self.push_popup(popup, clear=True) self.refresh() def delete_current_host(self): idx, data = self.popup.current_selection() - log.debug("deleting host: %s", data) - for host in self.config["hosts"]: + log.debug('deleting host: %s', data) + for host in self.config['hosts']: if host[0] == data: - self.config["hosts"].remove(host) + self.config['hosts'].remove(host) break self.config.save() @@ -210,9 +210,9 @@ class ConnectionManager(BaseMode, PopupsHandler): c = self.stdscr.getch() if c > 31 and c < 256: - if chr(c) == "q" and self.inlist: + if chr(c) == 'q' and self.inlist: return - if chr(c) == "Q": + if chr(c) == 'Q': from twisted.internet import reactor if client.connected(): def on_disconnect(result): @@ -221,11 +221,11 @@ class ConnectionManager(BaseMode, PopupsHandler): else: reactor.stop() return - if chr(c) == "D" and self.inlist: + if chr(c) == 'D' and self.inlist: self.delete_current_host() self.update_select_host_popup() return - if chr(c) == "a" and self.inlist: + if chr(c) == 'a' and self.inlist: self.add_popup() return diff --git a/deluge/ui/console/modes/eventview.py b/deluge/ui/console/modes/eventview.py index dc7601667..534f09ed8 100644 --- a/deluge/ui/console/modes/eventview.py +++ b/deluge/ui/console/modes/eventview.py @@ -30,7 +30,7 @@ class EventView(BaseMode): self.offset = 0 def back_to_overview(self): - component.get("ConsoleUI").set_mode(self.parent_mode.mode_name) + component.get('ConsoleUI').set_mode(self.parent_mode.mode_name) @overrides(component.Component) def update(self): @@ -41,7 +41,7 @@ class EventView(BaseMode): """ This method just shows each line of the event log """ - events = component.get("ConsoleUI").events + events = component.get('ConsoleUI').events self.stdscr.erase() self.draw_statusbars() @@ -51,7 +51,7 @@ class EventView(BaseMode): if i - self.offset >= self.rows - 2: more = len(events) - self.offset - self.rows + 2 if more > 0: - self.add_string(i - self.offset, " (And %i more)" % more) + self.add_string(i - self.offset, ' (And %i more)' % more) break elif i - self.offset < 0: @@ -61,9 +61,9 @@ class EventView(BaseMode): except curses.error: pass # This'll just cut the line. Note: This seriously should be fixed in a better way else: - self.add_string(1, "{!white,black,bold!}No events to show yet") + self.add_string(1, '{!white,black,bold!}No events to show yet') - if not component.get("ConsoleUI").is_active_mode(self): + if not component.get('ConsoleUI').is_active_mode(self): return self.stdscr.noutrefresh() @@ -84,7 +84,7 @@ class EventView(BaseMode): # TODO: Scroll event list jumplen = self.rows - 3 - num_events = len(component.get("ConsoleUI").events) + num_events = len(component.get('ConsoleUI').events) if c == curses.KEY_UP: self.offset -= 1 @@ -98,9 +98,9 @@ class EventView(BaseMode): self.offset += jumplen elif c == curses.KEY_END: self.offset += num_events - elif c == ord("j"): + elif c == ord('j'): self.offset -= 1 - elif c == ord("k"): + elif c == ord('k'): self.offset += 1 if self.offset <= 0: diff --git a/deluge/ui/console/modes/preferences/preference_panes.py b/deluge/ui/console/modes/preferences/preference_panes.py index a156398d8..2801ff1ff 100644 --- a/deluge/ui/console/modes/preferences/preference_panes.py +++ b/deluge/ui/console/modes/preferences/preference_panes.py @@ -24,7 +24,7 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler): def __init__(self, name, preferences): PopupsHandler.__init__(self) self.preferences = preferences - BaseWindow.__init__(self, "%s" % name, self.pane_width, preferences.height, posy=1, posx=self.pane_x_pos) + BaseWindow.__init__(self, '%s' % name, self.pane_width, preferences.height, posy=1, posx=self.pane_x_pos) BaseInputPane.__init__(self, preferences, border_off_east=1) self.name = name @@ -72,39 +72,39 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler): for ipt in self.inputs: if ipt.has_input(): # gross, have to special case in/out ports since they are tuples - if ipt.name in ("listen_ports_to", "listen_ports_from", "out_ports_from", "out_ports_to", - "i2p_port", "i2p_hostname", "proxy_type", "proxy_username", "proxy_hostnames", - "proxy_password", "proxy_hostname", "proxy_port", "proxy_peer_connections", - "listen_interface"): - if ipt.name == "listen_ports_to": - conf_dict["listen_ports"] = (self.infrom.get_value(), self.into.get_value()) - elif ipt.name == "out_ports_to": - conf_dict["outgoing_ports"] = (self.outfrom.get_value(), self.outto.get_value()) - elif ipt.name == "listen_interface": + if ipt.name in ('listen_ports_to', 'listen_ports_from', 'out_ports_from', 'out_ports_to', + 'i2p_port', 'i2p_hostname', 'proxy_type', 'proxy_username', 'proxy_hostnames', + 'proxy_password', 'proxy_hostname', 'proxy_port', 'proxy_peer_connections', + 'listen_interface'): + if ipt.name == 'listen_ports_to': + conf_dict['listen_ports'] = (self.infrom.get_value(), self.into.get_value()) + elif ipt.name == 'out_ports_to': + conf_dict['outgoing_ports'] = (self.outfrom.get_value(), self.outto.get_value()) + elif ipt.name == 'listen_interface': interface = ipt.get_value().strip() if is_ip(interface) or not interface: - conf_dict["listen_interface"] = interface - elif ipt.name == "i2p_port": - conf_dict.setdefault("i2p_proxy", {})["port"] = ipt.get_value() - elif ipt.name == "i2p_hostname": - conf_dict.setdefault("i2p_proxy", {})["hostname"] = ipt.get_value() - elif ipt.name == "proxy_type": - conf_dict.setdefault("proxy", {})["type"] = ipt.get_value() - elif ipt.name == "proxy_username": - conf_dict.setdefault("proxy", {})["username"] = ipt.get_value() - elif ipt.name == "proxy_password": - conf_dict.setdefault("proxy", {})["password"] = ipt.get_value() - elif ipt.name == "proxy_hostname": - conf_dict.setdefault("proxy", {})["hostname"] = ipt.get_value() - elif ipt.name == "proxy_port": - conf_dict.setdefault("proxy", {})["port"] = ipt.get_value() - elif ipt.name == "proxy_hostnames": - conf_dict.setdefault("proxy", {})["proxy_hostnames"] = ipt.get_value() - elif ipt.name == "proxy_peer_connections": - conf_dict.setdefault("proxy", {})["proxy_peer_connections"] = ipt.get_value() + conf_dict['listen_interface'] = interface + elif ipt.name == 'i2p_port': + conf_dict.setdefault('i2p_proxy', {})['port'] = ipt.get_value() + elif ipt.name == 'i2p_hostname': + conf_dict.setdefault('i2p_proxy', {})['hostname'] = ipt.get_value() + elif ipt.name == 'proxy_type': + conf_dict.setdefault('proxy', {})['type'] = ipt.get_value() + elif ipt.name == 'proxy_username': + conf_dict.setdefault('proxy', {})['username'] = ipt.get_value() + elif ipt.name == 'proxy_password': + conf_dict.setdefault('proxy', {})['password'] = ipt.get_value() + elif ipt.name == 'proxy_hostname': + conf_dict.setdefault('proxy', {})['hostname'] = ipt.get_value() + elif ipt.name == 'proxy_port': + conf_dict.setdefault('proxy', {})['port'] = ipt.get_value() + elif ipt.name == 'proxy_hostnames': + conf_dict.setdefault('proxy', {})['proxy_hostnames'] = ipt.get_value() + elif ipt.name == 'proxy_peer_connections': + conf_dict.setdefault('proxy', {})['proxy_peer_connections'] = ipt.get_value() else: conf_dict[ipt.name] = ipt.get_value() - if hasattr(ipt, "get_child"): + if hasattr(ipt, 'get_child'): c = ipt.get_child() conf_dict[c.name] = c.get_value() @@ -115,7 +115,7 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler): ipt.set_value(conf_dict[ipt.name]) except KeyError: # just ignore if it's not in dict pass - if hasattr(ipt, "get_child"): + if hasattr(ipt, 'get_child'): try: c = ipt.get_child() c.set_value(conf_dict[c.name]) @@ -145,257 +145,257 @@ class BasePreferencePane(BaseInputPane, BaseWindow, PopupsHandler): class InterfacePane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Interface"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Interface'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("General options")) - - self.add_checked_input("ring_bell", _("Ring system bell when a download finishes"), - console_config["ring_bell"]) - self.add_header("Console UI", space_above=True) - self.add_checked_input("separate_complete", - _("List complete torrents after incomplete regardless of sorting order"), - console_config["torrentview"]["separate_complete"]) - self.add_checked_input("move_selection", _("Move selection when moving torrents in the queue"), - console_config["torrentview"]["move_selection"]) + self.add_header(_('General options')) + + self.add_checked_input('ring_bell', _('Ring system bell when a download finishes'), + console_config['ring_bell']) + self.add_header('Console UI', space_above=True) + self.add_checked_input('separate_complete', + _('List complete torrents after incomplete regardless of sorting order'), + console_config['torrentview']['separate_complete']) + self.add_checked_input('move_selection', _('Move selection when moving torrents in the queue'), + console_config['torrentview']['move_selection']) from deluge.ui.util import lang langs = lang.get_languages() - langs.insert(0, ("", "System Default")) - self.add_combo_input("language", _("Language"), - langs, default=console_config["language"]) - self.add_header(_("Command Line Mode"), space_above=True) - self.add_checked_input("ignore_duplicate_lines", _("Do not store duplicate input in history"), - console_config["cmdline"]["ignore_duplicate_lines"]) - self.add_checked_input("save_command_history", _("Store and load command line history in command line mode"), - console_config["cmdline"]["save_command_history"]) - self.add_header("") - self.add_checked_input("third_tab_lists_all", _("Third tab lists all remaining torrents in command line mode"), - console_config["cmdline"]["third_tab_lists_all"]) - self.add_int_spin_input("torrents_per_tab_press", _("Torrents per tab press"), - console_config["cmdline"]["torrents_per_tab_press"], min_val=5, max_val=10000) + langs.insert(0, ('', 'System Default')) + self.add_combo_input('language', _('Language'), + langs, default=console_config['language']) + self.add_header(_('Command Line Mode'), space_above=True) + self.add_checked_input('ignore_duplicate_lines', _('Do not store duplicate input in history'), + console_config['cmdline']['ignore_duplicate_lines']) + self.add_checked_input('save_command_history', _('Store and load command line history in command line mode'), + console_config['cmdline']['save_command_history']) + self.add_header('') + self.add_checked_input('third_tab_lists_all', _('Third tab lists all remaining torrents in command line mode'), + console_config['cmdline']['third_tab_lists_all']) + self.add_int_spin_input('torrents_per_tab_press', _('Torrents per tab press'), + console_config['cmdline']['torrents_per_tab_press'], min_val=5, max_val=10000) class DownloadsPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Downloads"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Downloads'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("Folders")) - self.add_text_input("download_location", "%s:" % _("Download To"), core_conf["download_location"], - complete=True, activate_input=True, col="+1") - cmptxt = TextInput(self.preferences, "move_completed_path", None, self.move, self.pane_width, - core_conf["move_completed_path"], False) - self.add_checkedplus_input("move_completed", "%s:" % _("Move completed to"), - cmptxt, core_conf["move_completed"]) - copytxt = TextInput(self.preferences, "torrentfiles_location", None, self.move, self.pane_width, - core_conf["torrentfiles_location"], False) - self.add_checkedplus_input("copy_torrent_file", "%s:" % _("Copy of .torrent files to"), copytxt, - core_conf["copy_torrent_file"]) - self.add_checked_input("del_copy_torrent_file", _("Delete copy of torrent file on remove"), - core_conf["del_copy_torrent_file"]) - - self.add_header(_("Options"), space_above=True) - self.add_checked_input("prioritize_first_last_pieces", ("Prioritize first and last pieces of torrent"), - core_conf["prioritize_first_last_pieces"]) - self.add_checked_input("sequential_download", _("Sequential download"), - core_conf["sequential_download"]) - self.add_checked_input("add_paused", _("Add Paused"), core_conf["add_paused"]) - self.add_checked_input("pre_allocate_storage", _("Pre-Allocate disk space"), - core_conf["pre_allocate_storage"]) + self.add_header(_('Folders')) + self.add_text_input('download_location', '%s:' % _('Download To'), core_conf['download_location'], + complete=True, activate_input=True, col='+1') + cmptxt = TextInput(self.preferences, 'move_completed_path', None, self.move, self.pane_width, + core_conf['move_completed_path'], False) + self.add_checkedplus_input('move_completed', '%s:' % _('Move completed to'), + cmptxt, core_conf['move_completed']) + copytxt = TextInput(self.preferences, 'torrentfiles_location', None, self.move, self.pane_width, + core_conf['torrentfiles_location'], False) + self.add_checkedplus_input('copy_torrent_file', '%s:' % _('Copy of .torrent files to'), copytxt, + core_conf['copy_torrent_file']) + self.add_checked_input('del_copy_torrent_file', _('Delete copy of torrent file on remove'), + core_conf['del_copy_torrent_file']) + + self.add_header(_('Options'), space_above=True) + self.add_checked_input('prioritize_first_last_pieces', ('Prioritize first and last pieces of torrent'), + core_conf['prioritize_first_last_pieces']) + self.add_checked_input('sequential_download', _('Sequential download'), + core_conf['sequential_download']) + self.add_checked_input('add_paused', _('Add Paused'), core_conf['add_paused']) + self.add_checked_input('pre_allocate_storage', _('Pre-Allocate disk space'), + core_conf['pre_allocate_storage']) class NetworkPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Network"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Network'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("Incomming Ports")) - inrand = self.add_checked_input("random_port", "Use Random Ports Active Port: %d" + self.add_header(_('Incomming Ports')) + inrand = self.add_checked_input('random_port', 'Use Random Ports Active Port: %d' % self.preferences.active_port, - core_conf["random_port"]) - listen_ports = core_conf["listen_ports"] - self.infrom = self.add_int_spin_input("listen_ports_from", " %s:" % _("From"), + core_conf['random_port']) + listen_ports = core_conf['listen_ports'] + self.infrom = self.add_int_spin_input('listen_ports_from', ' %s:' % _('From'), value=listen_ports[0], min_val=0, max_val=65535) self.infrom.set_depend(inrand, inverse=True) - self.into = self.add_int_spin_input("listen_ports_to", " %s:" % _("To"), + self.into = self.add_int_spin_input('listen_ports_to', ' %s:' % _('To'), value=listen_ports[1], min_val=0, max_val=65535) self.into.set_depend(inrand, inverse=True) - self.add_header(_("Outgoing Ports"), space_above=True) - outrand = self.add_checked_input("random_outgoing_ports", _("Use Random Ports"), - core_conf["random_outgoing_ports"]) - out_ports = core_conf["outgoing_ports"] - self.outfrom = self.add_int_spin_input("out_ports_from", " %s:" % _("From"), + self.add_header(_('Outgoing Ports'), space_above=True) + outrand = self.add_checked_input('random_outgoing_ports', _('Use Random Ports'), + core_conf['random_outgoing_ports']) + out_ports = core_conf['outgoing_ports'] + self.outfrom = self.add_int_spin_input('out_ports_from', ' %s:' % _('From'), value=out_ports[0], min_val=0, max_val=65535) self.outfrom.set_depend(outrand, inverse=True) - self.outto = self.add_int_spin_input("out_ports_to", " %s:" % _("To"), + self.outto = self.add_int_spin_input('out_ports_to', ' %s:' % _('To'), value=out_ports[1], min_val=0, max_val=65535) self.outto.set_depend(outrand, inverse=True) - self.add_header(_("Interface"), space_above=True) - self.add_text_input("listen_interface", "%s:" % _("IP address of the interface to listen on " - "(leave empty for default)"), - core_conf["listen_interface"]) + self.add_header(_('Interface'), space_above=True) + self.add_text_input('listen_interface', '%s:' % _('IP address of the interface to listen on ' + '(leave empty for default)'), + core_conf['listen_interface']) - self.add_header("TOS", space_above=True) - self.add_text_input("peer_tos", "Peer TOS Byte:", core_conf["peer_tos"]) + self.add_header('TOS', space_above=True) + self.add_text_input('peer_tos', 'Peer TOS Byte:', core_conf['peer_tos']) - self.add_header(_("Network Extras"), space_above=True) - self.add_checked_input("upnp", "UPnP", core_conf["upnp"]) - self.add_checked_input("natpmp", "NAT-PMP", core_conf["natpmp"]) - self.add_checked_input("utpex", "Peer Exchange", core_conf["utpex"]) - self.add_checked_input("lsd", "LSD", core_conf["lsd"]) - self.add_checked_input("dht", "DHT", core_conf["dht"]) + self.add_header(_('Network Extras'), space_above=True) + self.add_checked_input('upnp', 'UPnP', core_conf['upnp']) + self.add_checked_input('natpmp', 'NAT-PMP', core_conf['natpmp']) + self.add_checked_input('utpex', 'Peer Exchange', core_conf['utpex']) + self.add_checked_input('lsd', 'LSD', core_conf['lsd']) + self.add_checked_input('dht', 'DHT', core_conf['dht']) - self.add_header(_("Encryption"), space_above=True) - self.add_select_input("enc_in_policy", "%s:" % _("Inbound"), [_("Forced"), _("Enabled"), _("Disabled")], - [0, 1, 2], core_conf["enc_in_policy"], active_default=True, col="+1") - self.add_select_input("enc_out_policy", "%s:" % _("Outbound"), [_("Forced"), _("Enabled"), _("Disabled")], - [0, 1, 2], core_conf["enc_out_policy"], active_default=True) - self.add_select_input("enc_level", "%s:" % _("Level"), [_("Handshake"), _("Full Stream"), _("Either")], - [0, 1, 2], core_conf["enc_level"], active_default=True) + self.add_header(_('Encryption'), space_above=True) + self.add_select_input('enc_in_policy', '%s:' % _('Inbound'), [_('Forced'), _('Enabled'), _('Disabled')], + [0, 1, 2], core_conf['enc_in_policy'], active_default=True, col='+1') + self.add_select_input('enc_out_policy', '%s:' % _('Outbound'), [_('Forced'), _('Enabled'), _('Disabled')], + [0, 1, 2], core_conf['enc_out_policy'], active_default=True) + self.add_select_input('enc_level', '%s:' % _('Level'), [_('Handshake'), _('Full Stream'), _('Either')], + [0, 1, 2], core_conf['enc_level'], active_default=True) class BandwidthPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Bandwidth"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Bandwidth'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("Global Bandwidth Usage")) - self.add_int_spin_input("max_connections_global", "%s:" % _("Maximum Connections"), - core_conf["max_connections_global"], min_val=-1, max_val=9000) - self.add_int_spin_input("max_upload_slots_global", "%s:" % _("Maximum Upload Slots"), - core_conf["max_upload_slots_global"], min_val=-1, max_val=9000) - self.add_float_spin_input("max_download_speed", "%s:" % _("Maximum Download Speed (KiB/s)"), - core_conf["max_download_speed"], min_val=-1.0, max_val=60000.0) - self.add_float_spin_input("max_upload_speed", "%s:" % _("Maximum Upload Speed (KiB/s)"), - core_conf["max_upload_speed"], min_val=-1.0, max_val=60000.0) - self.add_int_spin_input("max_half_open_connections", "%s:" % _("Maximum Half-Open Connections"), - core_conf["max_half_open_connections"], min_val=-1, max_val=9999) - self.add_int_spin_input("max_connections_per_second", "%s:" % _("Maximum Connection Attempts per Second"), - core_conf["max_connections_per_second"], min_val=-1, max_val=9999) - self.add_checked_input("ignore_limits_on_local_network", _("Ignore limits on local network"), - core_conf["ignore_limits_on_local_network"]) - self.add_checked_input("rate_limit_ip_overhead", _("Rate Limit IP Overhead"), - core_conf["rate_limit_ip_overhead"]) - self.add_header(_("Per Torrent Bandwidth Usage"), space_above=True) - self.add_int_spin_input("max_connections_per_torrent", "%s:" % _("Maximum Connections"), - core_conf["max_connections_per_torrent"], min_val=-1, max_val=9000) - self.add_int_spin_input("max_upload_slots_per_torrent", "%s:" % _("Maximum Upload Slots"), - core_conf["max_upload_slots_per_torrent"], min_val=-1, max_val=9000) - self.add_float_spin_input("max_download_speed_per_torrent", "%s:" % _("Maximum Download Speed (KiB/s)"), - core_conf["max_download_speed_per_torrent"], min_val=-1.0, max_val=60000.0) - self.add_float_spin_input("max_upload_speed_per_torrent", "%s:" % _("Maximum Upload Speed (KiB/s)"), - core_conf["max_upload_speed_per_torrent"], min_val=-1.0, max_val=60000.0) + self.add_header(_('Global Bandwidth Usage')) + self.add_int_spin_input('max_connections_global', '%s:' % _('Maximum Connections'), + core_conf['max_connections_global'], min_val=-1, max_val=9000) + self.add_int_spin_input('max_upload_slots_global', '%s:' % _('Maximum Upload Slots'), + core_conf['max_upload_slots_global'], min_val=-1, max_val=9000) + self.add_float_spin_input('max_download_speed', '%s:' % _('Maximum Download Speed (KiB/s)'), + core_conf['max_download_speed'], min_val=-1.0, max_val=60000.0) + self.add_float_spin_input('max_upload_speed', '%s:' % _('Maximum Upload Speed (KiB/s)'), + core_conf['max_upload_speed'], min_val=-1.0, max_val=60000.0) + self.add_int_spin_input('max_half_open_connections', '%s:' % _('Maximum Half-Open Connections'), + core_conf['max_half_open_connections'], min_val=-1, max_val=9999) + self.add_int_spin_input('max_connections_per_second', '%s:' % _('Maximum Connection Attempts per Second'), + core_conf['max_connections_per_second'], min_val=-1, max_val=9999) + self.add_checked_input('ignore_limits_on_local_network', _('Ignore limits on local network'), + core_conf['ignore_limits_on_local_network']) + self.add_checked_input('rate_limit_ip_overhead', _('Rate Limit IP Overhead'), + core_conf['rate_limit_ip_overhead']) + self.add_header(_('Per Torrent Bandwidth Usage'), space_above=True) + self.add_int_spin_input('max_connections_per_torrent', '%s:' % _('Maximum Connections'), + core_conf['max_connections_per_torrent'], min_val=-1, max_val=9000) + self.add_int_spin_input('max_upload_slots_per_torrent', '%s:' % _('Maximum Upload Slots'), + core_conf['max_upload_slots_per_torrent'], min_val=-1, max_val=9000) + self.add_float_spin_input('max_download_speed_per_torrent', '%s:' % _('Maximum Download Speed (KiB/s)'), + core_conf['max_download_speed_per_torrent'], min_val=-1.0, max_val=60000.0) + self.add_float_spin_input('max_upload_speed_per_torrent', '%s:' % _('Maximum Upload Speed (KiB/s)'), + core_conf['max_upload_speed_per_torrent'], min_val=-1.0, max_val=60000.0) class OtherPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Other"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Other'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("System Information")) - self.add_info_field("info1", " Help us improve Deluge by sending us your", "") - self.add_info_field("info2", " Python version, PyGTK version, OS and processor", "") - self.add_info_field("info3", " types. Absolutely no other information is sent.", "") - self.add_checked_input("send_info", _("Yes, please send anonymous statistics."), core_conf["send_info"]) - self.add_header(_("GeoIP Database"), space_above=True) - self.add_text_input("geoip_db_location", "Location:", core_conf["geoip_db_location"]) + self.add_header(_('System Information')) + self.add_info_field('info1', ' Help us improve Deluge by sending us your', '') + self.add_info_field('info2', ' Python version, PyGTK version, OS and processor', '') + self.add_info_field('info3', ' types. Absolutely no other information is sent.', '') + self.add_checked_input('send_info', _('Yes, please send anonymous statistics.'), core_conf['send_info']) + self.add_header(_('GeoIP Database'), space_above=True) + self.add_text_input('geoip_db_location', 'Location:', core_conf['geoip_db_location']) class DaemonPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Daemon"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Daemon'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header("Port") - self.add_int_spin_input("daemon_port", "%s:" % _("Daemon Port"), core_conf["daemon_port"], + self.add_header('Port') + self.add_int_spin_input('daemon_port', '%s:' % _('Daemon Port'), core_conf['daemon_port'], min_val=0, max_val=65535) - self.add_header("Connections", space_above=True) - self.add_checked_input("allow_remote", _("Allow remote connections"), core_conf["allow_remote"]) - self.add_header("Other", space_above=True) - self.add_checked_input("new_release_check", _("Periodically check the website for new releases"), - core_conf["new_release_check"]) + self.add_header('Connections', space_above=True) + self.add_checked_input('allow_remote', _('Allow remote connections'), core_conf['allow_remote']) + self.add_header('Other', space_above=True) + self.add_checked_input('new_release_check', _('Periodically check the website for new releases'), + core_conf['new_release_check']) class QueuePane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Queue"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Queue'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("New Torrents")) - self.add_checked_input("queue_new_to_top", _("Queue to top"), core_conf["queue_new_to_top"]) - self.add_header(_("Active Torrents"), True) - self.add_int_spin_input("max_active_limit", "%s:" % _("Total"), core_conf["max_active_limit"], + self.add_header(_('New Torrents')) + self.add_checked_input('queue_new_to_top', _('Queue to top'), core_conf['queue_new_to_top']) + self.add_header(_('Active Torrents'), True) + self.add_int_spin_input('max_active_limit', '%s:' % _('Total'), core_conf['max_active_limit'], min_val=-1, max_val=9999) - self.add_int_spin_input("max_active_downloading", "%s:" % _("Downloading"), - core_conf["max_active_downloading"], min_val=-1, max_val=9999) - self.add_int_spin_input("max_active_seeding", "%s:" % _("Seeding"), - core_conf["max_active_seeding"], min_val=-1, max_val=9999) - self.add_checked_input("dont_count_slow_torrents", "Ignore slow torrents", - core_conf["dont_count_slow_torrents"]) - self.add_checked_input("auto_manage_prefer_seeds", "Prefer seeding torrents", - core_conf["auto_manage_prefer_seeds"]) - self.add_header(_("Seeding Rotation"), space_above=True) - self.add_float_spin_input("share_ratio_limit", "%s:" % _("Share Ratio"), - core_conf["share_ratio_limit"], precision=2, min_val=-1.0, max_val=100.0) - self.add_float_spin_input("seed_time_ratio_limit", "%s:" % _("Time Ratio"), - core_conf["seed_time_ratio_limit"], precision=2, min_val=-1.0, max_val=100.0) - self.add_int_spin_input("seed_time_limit", "%s:" % _("Time (m)"), core_conf["seed_time_limit"], + self.add_int_spin_input('max_active_downloading', '%s:' % _('Downloading'), + core_conf['max_active_downloading'], min_val=-1, max_val=9999) + self.add_int_spin_input('max_active_seeding', '%s:' % _('Seeding'), + core_conf['max_active_seeding'], min_val=-1, max_val=9999) + self.add_checked_input('dont_count_slow_torrents', 'Ignore slow torrents', + core_conf['dont_count_slow_torrents']) + self.add_checked_input('auto_manage_prefer_seeds', 'Prefer seeding torrents', + core_conf['auto_manage_prefer_seeds']) + self.add_header(_('Seeding Rotation'), space_above=True) + self.add_float_spin_input('share_ratio_limit', '%s:' % _('Share Ratio'), + core_conf['share_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0) + self.add_float_spin_input('seed_time_ratio_limit', '%s:' % _('Time Ratio'), + core_conf['seed_time_ratio_limit'], precision=2, min_val=-1.0, max_val=100.0) + self.add_int_spin_input('seed_time_limit', '%s:' % _('Time (m)'), core_conf['seed_time_limit'], min_val=1, max_val=10000) - seedratio = FloatSpinInput(self.mode, "stop_seed_ratio", "", self.move, core_conf["stop_seed_ratio"], + seedratio = FloatSpinInput(self.mode, 'stop_seed_ratio', '', self.move, core_conf['stop_seed_ratio'], precision=2, inc_amt=0.1, min_val=0.5, max_val=100.0) - self.add_checkedplus_input("stop_seed_at_ratio", "%s:" % _("Share Ratio Reached"), seedratio, - core_conf["stop_seed_at_ratio"]) - self.add_checked_input("remove_seed_at_ratio", _("Remove torrent (Unchecked pauses torrent)"), - core_conf["remove_seed_at_ratio"]) + self.add_checkedplus_input('stop_seed_at_ratio', '%s:' % _('Share Ratio Reached'), seedratio, + core_conf['stop_seed_at_ratio']) + self.add_checked_input('remove_seed_at_ratio', _('Remove torrent (Unchecked pauses torrent)'), + core_conf['remove_seed_at_ratio']) class ProxyPane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Proxy"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Proxy'), preferences) @overrides(BasePreferencePane) def create_pane(self, core_conf, console_config): - self.add_header(_("Proxy Settings")) - self.add_header(_("Proxy"), space_above=True) - proxy = core_conf["proxy"] - self.add_int_spin_input("proxy_type", "%s:" % _("Type"), proxy["type"], min_val=0, max_val=5) - self.add_info_field("proxy_info_1", " 0: None 1: Socks4 2: Socks5", "") - self.add_info_field("proxy_info_2", " 3: Socks5 Auth 4: HTTP 5: HTTP Auth", "") - self.add_text_input("proxy_username", "%s:" % _("Username"), proxy["username"]) - self.add_text_input("proxy_password", "%s:" % _("Password"), proxy["password"]) - self.add_text_input("proxy_hostname", "%s:" % _("Hostname"), proxy["hostname"]) - self.add_int_spin_input("proxy_port", "%s:" % _("Port"), proxy["port"], min_val=0, max_val=65535) - self.add_checked_input("proxy_hostnames", _("Proxy hostnames"), proxy["proxy_hostnames"]) - self.add_checked_input("proxy_peer_connections", _("Proxy peer connections"), proxy["proxy_peer_connections"]) - - self.add_header(_("I2P Proxy"), space_above=True) - self.add_text_input("i2p_hostname", "%s:" % _("Hostname"), - core_conf["i2p_proxy"]["hostname"]) - self.add_int_spin_input("i2p_port", - "%s:" % _("Port"), core_conf["i2p_proxy"]["port"], min_val=0, max_val=65535) - self.add_checked_input("anonymous_mode", _("Anonymous Mode"), core_conf["anonymous_mode"]) + self.add_header(_('Proxy Settings')) + self.add_header(_('Proxy'), space_above=True) + proxy = core_conf['proxy'] + self.add_int_spin_input('proxy_type', '%s:' % _('Type'), proxy['type'], min_val=0, max_val=5) + self.add_info_field('proxy_info_1', ' 0: None 1: Socks4 2: Socks5', '') + self.add_info_field('proxy_info_2', ' 3: Socks5 Auth 4: HTTP 5: HTTP Auth', '') + self.add_text_input('proxy_username', '%s:' % _('Username'), proxy['username']) + self.add_text_input('proxy_password', '%s:' % _('Password'), proxy['password']) + self.add_text_input('proxy_hostname', '%s:' % _('Hostname'), proxy['hostname']) + self.add_int_spin_input('proxy_port', '%s:' % _('Port'), proxy['port'], min_val=0, max_val=65535) + self.add_checked_input('proxy_hostnames', _('Proxy hostnames'), proxy['proxy_hostnames']) + self.add_checked_input('proxy_peer_connections', _('Proxy peer connections'), proxy['proxy_peer_connections']) + + self.add_header(_('I2P Proxy'), space_above=True) + self.add_text_input('i2p_hostname', '%s:' % _('Hostname'), + core_conf['i2p_proxy']['hostname']) + self.add_int_spin_input('i2p_port', + '%s:' % _('Port'), core_conf['i2p_proxy']['port'], min_val=0, max_val=65535) + self.add_checked_input('anonymous_mode', _('Anonymous Mode'), core_conf['anonymous_mode']) class CachePane(BasePreferencePane): def __init__(self, preferences): - BasePreferencePane.__init__(self, " %s " % _("Cache"), preferences) + BasePreferencePane.__init__(self, ' %s ' % _('Cache'), preferences) self.created = False @overrides(BasePreferencePane) @@ -404,32 +404,32 @@ class CachePane(BasePreferencePane): def build_pane(self, core_conf, status): self.created = True - self.add_header(_("Settings"), space_below=True) - self.add_int_spin_input("cache_size", - "%s:" % _("Cache Size (16 KiB blocks)"), core_conf["cache_size"], + self.add_header(_('Settings'), space_below=True) + self.add_int_spin_input('cache_size', + '%s:' % _('Cache Size (16 KiB blocks)'), core_conf['cache_size'], min_val=0, max_val=99999) - self.add_int_spin_input("cache_expiry", - "%s:" % _("Cache Expiry (seconds)"), core_conf["cache_expiry"], + self.add_int_spin_input('cache_expiry', + '%s:' % _('Cache Expiry (seconds)'), core_conf['cache_expiry'], min_val=1, max_val=32000) - self.add_header(" %s" % _("Write"), space_above=True) - self.add_info_field("blocks_written", " %s:" % _("Blocks Written"), status["blocks_written"]) - self.add_info_field("writes", " %s:" % _("Writes"), status["writes"]) - self.add_info_field("write_hit_ratio", - " %s:" % _("Write Cache Hit Ratio"), "%.2f" % status["write_hit_ratio"]) - self.add_header(" %s" % _("Read")) - self.add_info_field("blocks_read", - " %s:" % _("Blocks Read"), status["blocks_read"]) - self.add_info_field("blocks_read_hit", - " %s:" % _("Blocks Read hit"), status["blocks_read_hit"]) - self.add_info_field("reads", - " %s:" % _("Reads"), status["reads"]) - self.add_info_field("read_hit_ratio", - " %s:" % _("Read Cache Hit Ratio"), "%.2f" % status["read_hit_ratio"]) - self.add_header(" %s" % _("Size")) - self.add_info_field("cache_size_info", - " %s:" % _("Cache Size"), status["cache_size"]) - self.add_info_field("read_cache_size", - " %s:" % _("Read Cache Size"), status["read_cache_size"]) + self.add_header(' %s' % _('Write'), space_above=True) + self.add_info_field('blocks_written', ' %s:' % _('Blocks Written'), status['blocks_written']) + self.add_info_field('writes', ' %s:' % _('Writes'), status['writes']) + self.add_info_field('write_hit_ratio', + ' %s:' % _('Write Cache Hit Ratio'), '%.2f' % status['write_hit_ratio']) + self.add_header(' %s' % _('Read')) + self.add_info_field('blocks_read', + ' %s:' % _('Blocks Read'), status['blocks_read']) + self.add_info_field('blocks_read_hit', + ' %s:' % _('Blocks Read hit'), status['blocks_read_hit']) + self.add_info_field('reads', + ' %s:' % _('Reads'), status['reads']) + self.add_info_field('read_hit_ratio', + ' %s:' % _('Read Cache Hit Ratio'), '%.2f' % status['read_hit_ratio']) + self.add_header(' %s' % _('Size')) + self.add_info_field('cache_size_info', + ' %s:' % _('Cache Size'), status['cache_size']) + self.add_info_field('read_cache_size', + ' %s:' % _('Read Cache Size'), status['read_cache_size']) @overrides(BasePreferencePane) def update(self, active): diff --git a/deluge/ui/console/modes/preferences/preferences.py b/deluge/ui/console/modes/preferences/preferences.py index b083cd915..77adc5db0 100644 --- a/deluge/ui/console/modes/preferences/preferences.py +++ b/deluge/ui/console/modes/preferences/preferences.py @@ -74,11 +74,11 @@ class PreferenceSidebar(Sidebar): def __init__(self, torrentview, width): height = curses.LINES - 2 Sidebar.__init__(self, torrentview, width, height, title=None, border_off_north=1) - self.categories = [_("Interface"), _("Downloads"), _("Network"), _("Bandwidth"), - _("Other"), _("Daemon"), _("Queue"), _("Proxy"), _("Cache")] + self.categories = [_('Interface'), _('Downloads'), _('Network'), _('Bandwidth'), + _('Other'), _('Daemon'), _('Queue'), _('Proxy'), _('Cache')] for name in self.categories: - self.add_text_field(name, name, selectable=True, font_unfocused_active="bold", - color_unfocused_active="white,black") + self.add_text_field(name, name, selectable=True, font_unfocused_active='bold', + color_unfocused_active='white,black') def on_resize(self): self.resize_window(curses.LINES - 2, self.width) @@ -117,7 +117,7 @@ class Preferences(BaseMode, PopupsHandler): CachePane(self) ] - self.action_input = SelectInput(self, None, None, [_("Cancel"), _("Apply"), _("OK")], [0, 1, 2], 0) + self.action_input = SelectInput(self, None, None, [_('Cancel'), _('Apply'), _('OK')], [0, 1, 2], 0) def load_config(self): if self.config_loaded: @@ -160,7 +160,7 @@ class Preferences(BaseMode, PopupsHandler): def _draw_actions(self): selected = self.active_zone == ZONE.ACTIONS - self.stdscr.hline(self.rows - 3, self.sidebar_width, "_", self.cols) + self.stdscr.hline(self.rows - 3, self.sidebar_width, '_', self.cols) self.action_input.render(self.stdscr, self.rows - 2, width=self.cols, active=selected, focus=True, col=self.cols - 22) @@ -187,7 +187,7 @@ class Preferences(BaseMode, PopupsHandler): @overrides(BaseMode) def refresh(self): - if not component.get("ConsoleUI").is_active_mode(self) or not self.config_loaded: + if not component.get('ConsoleUI').is_active_mode(self) or not self.config_loaded: return if self.popup is None and self.messages: @@ -248,13 +248,13 @@ class Preferences(BaseMode, PopupsHandler): # are ever reordered, so do it the slightly slower but safer way if isinstance(pane, InterfacePane): pane.add_config_values(new_console_config) - for k in ["ring_bell", "language"]: + for k in ['ring_bell', 'language']: didupdate = update_conf_value(k, new_console_config, self.console_config, didupdate) - for k in ["separate_complete", "move_selection"]: - didupdate = update_conf_value(k, new_console_config, self.console_config["torrentview"], didupdate) - for k in ["ignore_duplicate_lines", "save_command_history", - "third_tab_lists_all", "torrents_per_tab_press"]: - didupdate = update_conf_value(k, new_console_config, self.console_config["cmdline"], didupdate) + for k in ['separate_complete', 'move_selection']: + didupdate = update_conf_value(k, new_console_config, self.console_config['torrentview'], didupdate) + for k in ['ignore_duplicate_lines', 'save_command_history', + 'third_tab_lists_all', 'torrents_per_tab_press']: + didupdate = update_conf_value(k, new_console_config, self.console_config['cmdline'], didupdate) if didupdate: self.parent_mode.on_config_changed() @@ -278,7 +278,7 @@ class Preferences(BaseMode, PopupsHandler): self.back_to_parent() def back_to_parent(self): - component.get("ConsoleUI").set_mode(self.parent_mode.mode_name) + component.get('ConsoleUI').set_mode(self.parent_mode.mode_name) @overrides(BaseMode) def read_input(self): @@ -291,7 +291,7 @@ class Preferences(BaseMode, PopupsHandler): return if util.is_printable_char(c): - if chr(c) == "Q": + if chr(c) == 'Q': from twisted.internet import reactor if client.connected(): def on_disconnect(result): @@ -300,8 +300,8 @@ class Preferences(BaseMode, PopupsHandler): else: reactor.stop() return - elif chr(c) == "h": - self.push_popup(MessagePopup(self, "Preferences Help", HELP_STR)) + elif chr(c) == 'h': + self.push_popup(MessagePopup(self, 'Preferences Help', HELP_STR)) if self.sidebar.has_focus() and c == util.KEY_ESC: self.back_to_parent() diff --git a/deluge/ui/console/modes/torrentdetail.py b/deluge/ui/console/modes/torrentdetail.py index 7957faf55..95f934ce8 100644 --- a/deluge/ui/console/modes/torrentdetail.py +++ b/deluge/ui/console/modes/torrentdetail.py @@ -72,33 +72,33 @@ class TorrentDetail(BaseMode, PopupsHandler): self.parent_mode = parent_mode self.torrentid = None self.torrent_state = None - self._status_keys = ["files", "name", "state", "download_payload_rate", "upload_payload_rate", - "progress", "eta", "all_time_download", "total_uploaded", "ratio", - "num_seeds", "total_seeds", "num_peers", "total_peers", "active_time", - "seeding_time", "time_added", "distributed_copies", "num_pieces", - "piece_length", "download_location", "file_progress", "file_priorities", "message", - "total_wanted", "tracker_host", "owner", "seed_rank", "last_seen_complete", - "completed_time"] + self._status_keys = ['files', 'name', 'state', 'download_payload_rate', 'upload_payload_rate', + 'progress', 'eta', 'all_time_download', 'total_uploaded', 'ratio', + 'num_seeds', 'total_seeds', 'num_peers', 'total_peers', 'active_time', + 'seeding_time', 'time_added', 'distributed_copies', 'num_pieces', + 'piece_length', 'download_location', 'file_progress', 'file_priorities', 'message', + 'total_wanted', 'tracker_host', 'owner', 'seed_rank', 'last_seen_complete', + 'completed_time'] self.file_list = None self.current_file = None self.current_file_idx = 0 self.file_off = 0 self.more_to_draw = False self.full_names = None - self.column_string = "" + self.column_string = '' self.files_sep = None self.marked = {} BaseMode.__init__(self, stdscr, encoding) - self.column_names = ["Filename", "Size", "Progress", "Priority"] + self.column_names = ['Filename', 'Size', 'Progress', 'Priority'] self.__update_columns() self._listing_start = self.rows // 2 self._listing_space = self._listing_start - self._listing_start - client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event) - client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event) - client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event) + client.register_event_handler('TorrentFileRenamedEvent', self._on_torrentfilerenamed_event) + client.register_event_handler('TorrentFolderRenamedEvent', self._on_torrentfolderrenamed_event) + client.register_event_handler('TorrentRemovedEvent', self._on_torrentremoved_event) util.safe_curs_set(util.Curser.INVISIBLE) self.stdscr.notimeout(0) @@ -108,7 +108,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.file_list = None def back_to_overview(self): - component.get("ConsoleUI").set_mode(self.parent_mode.mode_name) + component.get('ConsoleUI').set_mode(self.parent_mode.mode_name) @overrides(component.Component) def start(self): @@ -120,7 +120,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.set_torrent_id(torrentid) if self.torrentid: - component.get("SessionProxy").get_torrent_status(self.torrentid, + component.get('SessionProxy').get_torrent_status(self.torrentid, self._status_keys).addCallback(self.set_state) @overrides(BaseMode) @@ -139,31 +139,31 @@ class TorrentDetail(BaseMode, PopupsHandler): def set_state(self, state): - if state.get("files"): - self.full_names = dict([(x["index"], x["path"]) for x in state["files"]]) + if state.get('files'): + self.full_names = dict([(x['index'], x['path']) for x in state['files']]) need_prio_update = False if not self.file_list: # don't keep getting the files once we've got them once - if state.get("files"): - self.files_sep = "{!green,black,bold,underline!}%s" % ( - ("Files (torrent has %d files)" % len(state["files"])).center(self.cols)) - self.file_list, self.file_dict = self.build_file_list(state["files"], state["file_progress"], - state["file_priorities"]) + if state.get('files'): + self.files_sep = '{!green,black,bold,underline!}%s' % ( + ('Files (torrent has %d files)' % len(state['files'])).center(self.cols)) + self.file_list, self.file_dict = self.build_file_list(state['files'], state['file_progress'], + state['file_priorities']) else: - self.files_sep = "{!green,black,bold,underline!}%s" % (("Files (File list unknown)").center(self.cols)) + self.files_sep = '{!green,black,bold,underline!}%s' % (('Files (File list unknown)').center(self.cols)) need_prio_update = True - self.__fill_progress(self.file_list, state["file_progress"]) + self.__fill_progress(self.file_list, state['file_progress']) - for i, prio in enumerate(state["file_priorities"]): + for i, prio in enumerate(state['file_priorities']): if self.file_dict[i][6] != prio: need_prio_update = True self.file_dict[i][6] = prio if need_prio_update: self.__fill_prio(self.file_list) - del state["file_progress"] - del state["file_priorities"] + del state['file_progress'] + del state['file_priorities'] self.torrent_state = state self.refresh() @@ -186,15 +186,15 @@ class TorrentDetail(BaseMode, PopupsHandler): dir_idx = len(torrent_files) for torrent_file in torrent_files: cur = file_list - paths = torrent_file["path"].split("/") + paths = torrent_file['path'].split('/') for path in paths: if not cur or path != cur[-1][0]: child_list = [] if path == paths[-1]: - file_progress = format_progress(progress[torrent_file["index"]] * 100) - entry = [path, torrent_file["index"], torrent_file["size"], child_list, - False, file_progress, priority[torrent_file["index"]]] - file_dict[torrent_file["index"]] = entry + file_progress = format_progress(progress[torrent_file['index']] * 100) + entry = [path, torrent_file['index'], torrent_file['size'], child_list, + False, file_progress, priority[torrent_file['index']]] + file_dict[torrent_file['index']] = entry else: entry = [path, dir_idx, -1, child_list, False, 0, -1] file_dict[dir_idx] = entry @@ -261,7 +261,7 @@ class TorrentDetail(BaseMode, PopupsHandler): if self.column_widths[i] < 0: self.column_widths[i] = vw - self.column_string = "{!green,black,bold!}%s" % ("".join(["%s%s" % (self.column_names[i], " " * ( + self.column_string = '{!green,black,bold!}%s' % (''.join(['%s%s' % (self.column_names[i], ' ' * ( self.column_widths[i] - len(self.column_names[i]))) for i in range(0, len(self.column_names))])) def _on_torrentremoved_event(self, torrent_id): @@ -270,31 +270,31 @@ class TorrentDetail(BaseMode, PopupsHandler): def _on_torrentfilerenamed_event(self, torrent_id, index, new_name): if torrent_id == self.torrentid: - self.file_dict[index][0] = new_name.split("/")[-1] - component.get("SessionProxy").get_torrent_status( + self.file_dict[index][0] = new_name.split('/')[-1] + component.get('SessionProxy').get_torrent_status( self.torrentid, self._status_keys).addCallback(self.set_state) def _on_torrentfolderrenamed_event(self, torrent_id, old_folder, new_folder): if torrent_id == self.torrentid: fe = None fl = None - for i in old_folder.strip("/").split("/"): + for i in old_folder.strip('/').split('/'): if not fl: fe = fl = self.file_list - s = [files for files in fl if files[0].strip("/") == i][0] + s = [files for files in fl if files[0].strip('/') == i][0] fe = s fl = s[3] - fe[0] = new_folder.strip("/").rpartition("/")[-1] + fe[0] = new_folder.strip('/').rpartition('/')[-1] # self.__get_file_by_name(old_folder, self.file_list)[0] = new_folder.strip("/") - component.get("SessionProxy").get_torrent_status( + component.get('SessionProxy').get_torrent_status( self.torrentid, self._status_keys).addCallback(self.set_state) def draw_files(self, files, depth, off, idx): - color_selected = "blue" - color_partially_selected = "magenta" - color_highlighted = "white" + color_selected = 'blue' + color_partially_selected = 'magenta' + color_highlighted = 'white' for fl in files: # from sys import stderr # print >> stderr, fl[6] @@ -304,20 +304,20 @@ class TorrentDetail(BaseMode, PopupsHandler): return -1, -1 # default color values - fg = "white" - bg = "black" - attr = "" + fg = 'white' + bg = 'black' + attr = '' if fl[6] == -2: pass # Mixed elif fl[6] == 0: - fg = "red" # Do Not Download + fg = 'red' # Do Not Download elif fl[6] == 1: pass # Normal elif fl[6] <= 6: - fg = "yellow" # High + fg = 'yellow' # High elif fl[6] == 7: - fg = "green" # Highest + fg = 'green' # Highest if idx >= self.file_off: # set fg/bg colors based on whether the file is selected/marked or not @@ -327,7 +327,7 @@ class TorrentDetail(BaseMode, PopupsHandler): if fl[3]: if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]): bg = color_partially_selected - attr = "bold" + attr = 'bold' if idx == self.current_file_idx: self.current_file = fl @@ -338,29 +338,29 @@ class TorrentDetail(BaseMode, PopupsHandler): if self.marked[fl[1]] < self.__get_contained_files_count(file_list=fl[3]): fg = color_partially_selected else: - if fg == "white": - fg = "black" - attr = "bold" + if fg == 'white': + fg = 'black' + attr = 'bold' if attr: - color_string = "{!%s,%s,%s!}" % (fg, bg, attr) + color_string = '{!%s,%s,%s!}' % (fg, bg, attr) else: - color_string = "{!%s,%s!}" % (fg, bg) + color_string = '{!%s,%s!}' % (fg, bg) # actually draw the dir/file string if fl[3] and fl[4]: # this is an expanded directory - xchar = "v" + xchar = 'v' elif fl[3]: # collapsed directory - xchar = ">" + xchar = '>' else: # file - xchar = "-" + xchar = '-' - r = format_row(["%s%s %s" % (" " * depth, xchar, fl[0]), + r = format_row(['%s%s %s' % (' ' * depth, xchar, fl[0]), fsize(fl[2]), fl[5], format_priority(fl[6])], self.column_widths) - self.add_string(off, "%s%s" % (color_string, r), trim=False) + self.add_string(off, '%s%s' % (color_string, r), trim=False) off += 1 if fl[3] and fl[4]: @@ -410,12 +410,12 @@ class TorrentDetail(BaseMode, PopupsHandler): def render_header(self, row): status = self.torrent_state - download_color = "{!info!}" - if status["download_payload_rate"] > 0: - download_color = colors.state_color["Downloading"] + download_color = '{!info!}' + if status['download_payload_rate'] > 0: + download_color = colors.state_color['Downloading'] - def add_field(name, row, pre_color="{!info!}", post_color="{!input!}"): - s = "%s%s: %s%s" % (pre_color, torrent_data_fields[name]["name"], + def add_field(name, row, pre_color='{!info!}', post_color='{!input!}'): + s = '%s%s: %s%s' % (pre_color, torrent_data_fields[name]['name'], post_color, get_column_value(name, status)) if row: row = self.add_string(row, s) @@ -423,63 +423,63 @@ class TorrentDetail(BaseMode, PopupsHandler): return s # Name - row = add_field("name", row) + row = add_field('name', row) # State - row = add_field("state", row) + row = add_field('state', row) # Print DL info and ETA - s = add_field("downloaded", 0, download_color) - if status["progress"] != 100.0: - s += "/%s" % fsize(status["total_wanted"]) - if status["download_payload_rate"] > 0: - s += " {!yellow!}@ %s%s" % (download_color, fsize(status["download_payload_rate"])) - s += add_field("eta", 0) + s = add_field('downloaded', 0, download_color) + if status['progress'] != 100.0: + s += '/%s' % fsize(status['total_wanted']) + if status['download_payload_rate'] > 0: + s += ' {!yellow!}@ %s%s' % (download_color, fsize(status['download_payload_rate'])) + s += add_field('eta', 0) if s: row = self.add_string(row, s) # Print UL info and ratio - s = add_field("uploaded", 0, download_color) - if status["upload_payload_rate"] > 0: - s += " {!yellow!}@ %s%s" % (colors.state_color["Seeding"], fsize(status["upload_payload_rate"])) - s += " " + add_field("ratio", 0) + s = add_field('uploaded', 0, download_color) + if status['upload_payload_rate'] > 0: + s += ' {!yellow!}@ %s%s' % (colors.state_color['Seeding'], fsize(status['upload_payload_rate'])) + s += ' ' + add_field('ratio', 0) row = self.add_string(row, s) # Seed/peer info - s = "{!info!}%s:{!green!} %s {!input!}(%s)" % (torrent_data_fields["seeds"]["name"], - status["num_seeds"], status["total_seeds"]) + s = '{!info!}%s:{!green!} %s {!input!}(%s)' % (torrent_data_fields['seeds']['name'], + status['num_seeds'], status['total_seeds']) row = self.add_string(row, s) - s = "{!info!}%s:{!red!} %s {!input!}(%s)" % (torrent_data_fields["peers"]["name"], - status["num_peers"], status["total_peers"]) + s = '{!info!}%s:{!red!} %s {!input!}(%s)' % (torrent_data_fields['peers']['name'], + status['num_peers'], status['total_peers']) row = self.add_string(row, s) # Tracker - tracker_color = "{!green!}" if status["message"] == "OK" else "{!red!}" + tracker_color = '{!green!}' if status['message'] == 'OK' else '{!red!}' s = "{!info!}%s: {!magenta!}%s{!input!} says \"%s%s{!input!}\"" % ( - torrent_data_fields["tracker"]["name"], status["tracker_host"], tracker_color, status["message"]) + torrent_data_fields['tracker']['name'], status['tracker_host'], tracker_color, status['message']) row = self.add_string(row, s) # Pieces and availability - s = "{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s" % ( - torrent_data_fields["pieces"]["name"], status["num_pieces"], fsize(status["piece_length"])) - if status["distributed_copies"]: - s += "{!info!}%s: {!input!}%s" % (torrent_data_fields["seed_rank"]["name"], status["seed_rank"]) + s = '{!info!}%s: {!yellow!}%s {!input!}x {!yellow!}%s' % ( + torrent_data_fields['pieces']['name'], status['num_pieces'], fsize(status['piece_length'])) + if status['distributed_copies']: + s += '{!info!}%s: {!input!}%s' % (torrent_data_fields['seed_rank']['name'], status['seed_rank']) row = self.add_string(row, s) # Time added - row = add_field("time_added", row) + row = add_field('time_added', row) # Time active - row = add_field("active_time", row) - if status["seeding_time"]: - row = add_field("seeding_time", row) + row = add_field('active_time', row) + if status['seeding_time']: + row = add_field('seeding_time', row) # Download Folder - row = add_field("download_location", row) + row = add_field('download_location', row) # Seed Rank - row = add_field("seed_rank", row) + row = add_field('seed_rank', row) # Last seen complete - row = add_field("last_seen_complete", row) + row = add_field('last_seen_complete', row) # Owner - if status["owner"]: - row = add_field("owner", row) + if status['owner']: + row = add_field('owner', row) return row @overrides(BaseMode) @@ -492,7 +492,7 @@ class TorrentDetail(BaseMode, PopupsHandler): if self.torrent_state: row = self.render_header(row) else: - self.add_string(1, "Waiting for torrent state") + self.add_string(1, 'Waiting for torrent state') row += 1 @@ -509,7 +509,7 @@ class TorrentDetail(BaseMode, PopupsHandler): self.more_to_draw = False self.draw_files(self.file_list, 0, row, 0) - if not component.get("ConsoleUI").is_active_mode(self): + if not component.get('ConsoleUI').is_active_mode(self): return self.stdscr.noutrefresh() @@ -580,14 +580,14 @@ class TorrentDetail(BaseMode, PopupsHandler): return self.do_priority(data, kwargs[data], was_empty) if self.marked: - popup = SelectablePopup(self, "Set File Priority", popup_func, border_off_north=1) - popup.add_line("do_not_download", "_Do Not Download", - cb_arg=FILE_PRIORITY["Do Not Download"], foreground="red") - popup.add_line("normal_priority", "_Normal Priority", cb_arg=FILE_PRIORITY["Normal Priority"]) - popup.add_line("high_priority", "_High Priority", - cb_arg=FILE_PRIORITY["High Priority"], foreground="yellow") - popup.add_line("highest_priority", "H_ighest Priority", - cb_arg=FILE_PRIORITY["Highest Priority"], foreground="green") + popup = SelectablePopup(self, 'Set File Priority', popup_func, border_off_north=1) + popup.add_line('do_not_download', '_Do Not Download', + cb_arg=FILE_PRIORITY['Do Not Download'], foreground='red') + popup.add_line('normal_priority', '_Normal Priority', cb_arg=FILE_PRIORITY['Normal Priority']) + popup.add_line('high_priority', '_High Priority', + cb_arg=FILE_PRIORITY['High Priority'], foreground='yellow') + popup.add_line('highest_priority', 'H_ighest Priority', + cb_arg=FILE_PRIORITY['Highest Priority'], foreground='green') popup._selected = 1 self.push_popup(popup) @@ -656,7 +656,7 @@ class TorrentDetail(BaseMode, PopupsHandler): def __get_file_by_name(self, name, file_list, idx=0): for element in file_list: - if element[0].strip("/") == name.strip("/"): + if element[0].strip('/') == name.strip('/'): return element if element[3] and element[4]: i = self.__get_file_by_name(name, element[3], idx + 1) @@ -732,7 +732,7 @@ class TorrentDetail(BaseMode, PopupsHandler): return (idx, true_idx) - def _get_full_folder_path(self, num, file_list=None, path="", idx=0): + def _get_full_folder_path(self, num, file_list=None, path='', idx=0): if not file_list: file_list = self.file_list @@ -741,9 +741,9 @@ class TorrentDetail(BaseMode, PopupsHandler): idx += 1 continue if num == idx: - return "%s%s/" % (path, element[0]) + return '%s%s/' % (path, element[0]) if element[4]: - i = self._get_full_folder_path(num, element[3], path + element[0] + "/", idx + 1) + i = self._get_full_folder_path(num, element[3], path + element[0] + '/', idx + 1) if not isinstance(i, int): return i idx = i @@ -762,7 +762,7 @@ class TorrentDetail(BaseMode, PopupsHandler): def _show_rename_popup(self): # Perhaps in the future: Renaming multiple files if self.marked: - self.report_message("Error (Enter to close)", + self.report_message('Error (Enter to close)', "Sorry, you can't rename multiple files, please clear " "selection with {!info!}'c'{!normal!} key") else: @@ -774,27 +774,27 @@ class TorrentDetail(BaseMode, PopupsHandler): if _file[3]: def do_rename(result, **kwargs): - if not result or not result["new_foldername"]["value"] or kwargs.get("close", False): + if not result or not result['new_foldername']['value'] or kwargs.get('close', False): self.popup.close(None, call_cb=False) return old_fname = self._get_full_folder_path(self.current_file_idx) - new_fname = "%s/%s/" % (old_fname.strip("/").rpartition("/")[0], result["new_foldername"]["value"]) + new_fname = '%s/%s/' % (old_fname.strip('/').rpartition('/')[0], result['new_foldername']['value']) self._do_rename_folder(tid, old_fname, new_fname) - popup = InputPopup(self, "Rename folder (Esc to cancel)", close_cb=do_rename) - popup.add_text_input("new_foldername", "Enter new folder name:", old_filename.strip("/"), complete=True) + popup = InputPopup(self, 'Rename folder (Esc to cancel)', close_cb=do_rename) + popup.add_text_input('new_foldername', 'Enter new folder name:', old_filename.strip('/'), complete=True) self.push_popup(popup) else: def do_rename(result, **kwargs): - if not result or not result["new_filename"]["value"] or kwargs.get("close", False): + if not result or not result['new_filename']['value'] or kwargs.get('close', False): self.popup.close(None, call_cb=False) return - fname = "%s/%s" % (self.full_names[idx].rpartition("/")[0], result["new_filename"]["value"]) + fname = '%s/%s' % (self.full_names[idx].rpartition('/')[0], result['new_filename']['value']) self._do_rename_file(tid, idx, fname) - popup = InputPopup(self, " Rename file ", close_cb=do_rename) - popup.add_text_input("new_filename", "Enter new filename:", old_filename, complete=True) + popup = InputPopup(self, ' Rename file ', close_cb=do_rename) + popup.add_text_input('new_filename', 'Enter new filename:', old_filename, complete=True) self.push_popup(popup) @overrides(BaseMode) @@ -853,7 +853,7 @@ class TorrentDetail(BaseMode, PopupsHandler): torrent_actions_popup(self, [self.torrentid], action=ACTION.TORRENT_OPTIONS) return elif c == ord('h'): - self.push_popup(MessagePopup(self, "Help", HELP_STR, width_req=0.75)) + self.push_popup(MessagePopup(self, 'Help', HELP_STR, width_req=0.75)) elif c == ord('j'): self.file_list_up() elif c == ord('k'): diff --git a/deluge/ui/console/modes/torrentlist/__init__.py b/deluge/ui/console/modes/torrentlist/__init__.py index bc2952647..2d99252c6 100644 --- a/deluge/ui/console/modes/torrentlist/__init__.py +++ b/deluge/ui/console/modes/torrentlist/__init__.py @@ -1,18 +1,18 @@ class ACTION(object): - PAUSE = "pause" - RESUME = "resume" - REANNOUNCE = "update_tracker" + PAUSE = 'pause' + RESUME = 'resume' + REANNOUNCE = 'update_tracker' EDIT_TRACKERS = 3 - RECHECK = "force_recheck" - REMOVE = "remove_torrent" + RECHECK = 'force_recheck' + REMOVE = 'remove_torrent' REMOVE_DATA = 6 REMOVE_NODATA = 7 - DETAILS = "torrent_details" - MOVE_STORAGE = ("move_download_folder") - QUEUE = "queue" - QUEUE_TOP = "queue_top" - QUEUE_UP = "queue_up" - QUEUE_DOWN = "queue_down" - QUEUE_BOTTOM = "queue_bottom" - TORRENT_OPTIONS = "torrent_options" + DETAILS = 'torrent_details' + MOVE_STORAGE = ('move_download_folder') + QUEUE = 'queue' + QUEUE_TOP = 'queue_top' + QUEUE_UP = 'queue_up' + QUEUE_DOWN = 'queue_down' + QUEUE_BOTTOM = 'queue_bottom' + TORRENT_OPTIONS = 'torrent_options' diff --git a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py index e7d6266b2..40a726495 100644 --- a/deluge/ui/console/modes/torrentlist/add_torrents_popup.py +++ b/deluge/ui/console/modes/torrentlist/add_torrents_popup.py @@ -18,70 +18,70 @@ log = logging.getLogger(__name__) def report_add_status(torrentlist, succ_cnt, fail_cnt, fail_msgs): if fail_cnt == 0: - torrentlist.report_message("Torrents Added", "{!success!}Successfully added %d torrent(s)" % succ_cnt) + torrentlist.report_message('Torrents Added', '{!success!}Successfully added %d torrent(s)' % succ_cnt) else: - msg = ("{!error!}Failed to add the following %d torrent(s):\n {!input!}" % fail_cnt) + "\n ".join(fail_msgs) + msg = ('{!error!}Failed to add the following %d torrent(s):\n {!input!}' % fail_cnt) + '\n '.join(fail_msgs) if succ_cnt != 0: - msg += "\n \n{!success!}Successfully added %d torrent(s)" % succ_cnt - torrentlist.report_message("Torrent Add Report", msg) + msg += '\n \n{!success!}Successfully added %d torrent(s)' % succ_cnt + torrentlist.report_message('Torrent Add Report', msg) def show_torrent_add_popup(torrentlist): def do_add_from_url(data=None, **kwargs): torrentlist.pop_popup() - if not data or kwargs.get("close", False): + if not data or kwargs.get('close', False): return def fail_cb(msg, url): - log.debug("failed to add torrent: %s: %s", url, msg) - error_msg = "{!input!} * %s: {!error!}%s" % (url, msg) + log.debug('failed to add torrent: %s: %s', url, msg) + error_msg = '{!input!} * %s: {!error!}%s' % (url, msg) report_add_status(torrentlist, 0, 1, [error_msg]) def success_cb(tid, url): if tid: - log.debug("added torrent: %s (%s)", url, tid) + log.debug('added torrent: %s (%s)', url, tid) report_add_status(torrentlist, 1, 0, []) else: - fail_cb("Already in session (probably)", url) + fail_cb('Already in session (probably)', url) - url = data["url"]["value"] + url = data['url']['value'] if not url: return - t_options = {"download_location": data["path"]["value"], "add_paused": data["add_paused"]["value"]} + t_options = {'download_location': data['path']['value'], 'add_paused': data['add_paused']['value']} if deluge.common.is_magnet(url): client.core.add_torrent_magnet(url, t_options).addCallback(success_cb, url).addErrback(fail_cb, url) elif deluge.common.is_url(url): client.core.add_torrent_url(url, t_options).addCallback(success_cb, url).addErrback(fail_cb, url) else: - torrentlist.report_message("Error", "{!error!}Invalid URL or magnet link: %s" % url) + torrentlist.report_message('Error', '{!error!}Invalid URL or magnet link: %s' % url) return - log.debug("Adding Torrent(s): %s (dl path: %s) (paused: %d)", - url, data["path"]["value"], data["add_paused"]["value"]) + log.debug('Adding Torrent(s): %s (dl path: %s) (paused: %d)', + url, data['path']['value'], data['add_paused']['value']) def show_add_url_popup(): - add_paused = 1 if "add_paused" in torrentlist.coreconfig else 0 - popup = InputPopup(torrentlist, "Add Torrent (Esc to cancel)", close_cb=do_add_from_url) - popup.add_text_input("url", "Enter torrent URL or Magnet link:") - popup.add_text_input("path", "Enter save path:", torrentlist.coreconfig.get("download_location", ""), + add_paused = 1 if 'add_paused' in torrentlist.coreconfig else 0 + popup = InputPopup(torrentlist, 'Add Torrent (Esc to cancel)', close_cb=do_add_from_url) + popup.add_text_input('url', 'Enter torrent URL or Magnet link:') + popup.add_text_input('path', 'Enter save path:', torrentlist.coreconfig.get('download_location', ''), complete=True) - popup.add_select_input("add_paused", "Add Paused:", ["Yes", "No"], [True, False], add_paused) + popup.add_select_input('add_paused', 'Add Paused:', ['Yes', 'No'], [True, False], add_paused) torrentlist.push_popup(popup) def option_chosen(selected, *args, **kwargs): - if not selected or selected == "cancel": + if not selected or selected == 'cancel': torrentlist.pop_popup() return - if selected == "file": - torrentlist.consoleui.set_mode("AddTorrents") - elif selected == "url": + if selected == 'file': + torrentlist.consoleui.set_mode('AddTorrents') + elif selected == 'url': show_add_url_popup() - popup = SelectablePopup(torrentlist, "Add torrent", option_chosen) - popup.add_line("file", "- From _File(s)", use_underline=True) - popup.add_line("url", "- From _URL or Magnet", use_underline=True) - popup.add_line("cancel", "- _Cancel", use_underline=True) + popup = SelectablePopup(torrentlist, 'Add torrent', option_chosen) + popup.add_line('file', '- From _File(s)', use_underline=True) + popup.add_line('url', '- From _URL or Magnet', use_underline=True) + popup.add_line('cancel', '- _Cancel', use_underline=True) torrentlist.push_popup(popup, clear=True) diff --git a/deluge/ui/console/modes/torrentlist/filtersidebar.py b/deluge/ui/console/modes/torrentlist/filtersidebar.py index 6b0a2373e..aff1f826c 100644 --- a/deluge/ui/console/modes/torrentlist/filtersidebar.py +++ b/deluge/ui/console/modes/torrentlist/filtersidebar.py @@ -30,22 +30,22 @@ class FilterSidebar(Sidebar, Component): def __init__(self, torrentlist, config): self.config = config height = curses.LINES - 2 - width = self.config["torrentview"]["sidebar_width"] - Sidebar.__init__(self, torrentlist, width, height, title=" Filter ", border_off_north=1, + width = self.config['torrentview']['sidebar_width'] + Sidebar.__init__(self, torrentlist, width, height, title=' Filter ', border_off_north=1, allow_resize=True) - Component.__init__(self, "FilterSidebar") + Component.__init__(self, 'FilterSidebar') self.checked_index = 0 - kwargs = {"checked_char": "*", "unchecked_char": "-", "checkbox_format": " %s ", "col": 0} - self.add_checked_input("All", "All", checked=True, **kwargs) - self.add_checked_input("Active", "Active", **kwargs) - self.add_checked_input("Downloading", "Downloading", color="green,black", **kwargs) - self.add_checked_input("Seeding", "Seeding", color="cyan,black", **kwargs) - self.add_checked_input("Paused", "Paused", **kwargs) - self.add_checked_input("Error", "Error", color="red,black", **kwargs) - self.add_checked_input("Checking", "Checking", color="blue,black", **kwargs) - self.add_checked_input("Queued", "Queued", **kwargs) - self.add_checked_input("Allocating", "Allocating", color="yellow,black", **kwargs) - self.add_checked_input("Moving", "Moving", color="green,black", **kwargs) + kwargs = {'checked_char': '*', 'unchecked_char': '-', 'checkbox_format': ' %s ', 'col': 0} + self.add_checked_input('All', 'All', checked=True, **kwargs) + self.add_checked_input('Active', 'Active', **kwargs) + self.add_checked_input('Downloading', 'Downloading', color='green,black', **kwargs) + self.add_checked_input('Seeding', 'Seeding', color='cyan,black', **kwargs) + self.add_checked_input('Paused', 'Paused', **kwargs) + self.add_checked_input('Error', 'Error', color='red,black', **kwargs) + self.add_checked_input('Checking', 'Checking', color='blue,black', **kwargs) + self.add_checked_input('Queued', 'Queued', **kwargs) + self.add_checked_input('Allocating', 'Allocating', color='yellow,black', **kwargs) + self.add_checked_input('Moving', 'Moving', color='green,black', **kwargs) @overrides(Component) def update(self): @@ -59,7 +59,7 @@ class FilterSidebar(Sidebar, Component): def _cb_update_filter_tree(self, filter_items): """Callback function on client.core.get_filter_tree""" - states = filter_items["state"] + states = filter_items['state'] largest_count = 0 largest_state_width = 0 for state in states: @@ -74,7 +74,7 @@ class FilterSidebar(Sidebar, Component): for state in states: field = self.get_input(state[0]) if field: - txt = ("%%-%ds%%%ds" % (filter_state_width, filter_count_width) % (state[0], state[1])) + txt = ('%%-%ds%%%ds' % (filter_state_width, filter_count_width) % (state[0], state[1])) if field.set_message(txt): changed = True return changed @@ -97,9 +97,9 @@ class FilterSidebar(Sidebar, Component): @overrides(Sidebar) def on_resize(self, width): - sidebar_width = self.config["torrentview"]["sidebar_width"] + sidebar_width = self.config['torrentview']['sidebar_width'] if sidebar_width != width: - self.config["torrentview"]["sidebar_width"] = width + self.config['torrentview']['sidebar_width'] = width self.config.save() self.resize_window(self.height, width) self.parent.toggle_sidebar() diff --git a/deluge/ui/console/modes/torrentlist/queue_mode.py b/deluge/ui/console/modes/torrentlist/queue_mode.py index 917db396d..6c9cae62a 100644 --- a/deluge/ui/console/modes/torrentlist/queue_mode.py +++ b/deluge/ui/console/modes/torrentlist/queue_mode.py @@ -44,8 +44,8 @@ class QueueMode(object): self.torrent_ids = torrent_ids def set_statusbar_args(self, statusbar_args): - statusbar_args["bottombar"] = "{!black,white!}Queue mode: change queue position of selected torrents." - statusbar_args["bottombar_help"] = " Press [h] for help" + statusbar_args['bottombar'] = '{!black,white!}Queue mode: change queue position of selected torrents.' + statusbar_args['bottombar_help'] = ' Press [h] for help' def update_cursor(self): pass @@ -57,19 +57,19 @@ class QueueMode(object): if c in [util.KEY_ESC, util.KEY_BELL]: # If Escape key or CTRL-g, we abort self.torrentslist.set_minor_mode(None) elif c == ord('h'): - popup = MessagePopup(self.torrentslist, "Help", QUEUE_MODE_HELP_STR, width_req=0.65, border_off_west=1) + popup = MessagePopup(self.torrentslist, 'Help', QUEUE_MODE_HELP_STR, width_req=0.65, border_off_west=1) self.torrentslist.push_popup(popup, clear=True) elif c in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_HOME, curses.KEY_END, curses.KEY_NPAGE, curses.KEY_PPAGE]: action = key_to_action[c] self.do_queue(action) def move_selection(self, cb_arg, qact): - if self.torrentslist.config["torrentview"]["move_selection"] is False: + if self.torrentslist.config['torrentview']['move_selection'] is False: return queue_length = 0 selected_num = 0 for tid in self.torrentview.curstate: - tq = self.torrentview.curstate[tid]["queue"] + tq = self.torrentview.curstate[tid]['queue'] if tq != -1: queue_length += 1 if tq in self.torrentview.marked: @@ -107,9 +107,9 @@ class QueueMode(object): client.core.queue_down(self.torrent_ids).addCallback(self.move_selection, qact) def popup(self, **kwargs): - popup = SelectablePopup(self.torrentslist, "Queue Action", self.do_queue, cb_args=kwargs, border_off_west=1) - popup.add_line(ACTION.QUEUE_TOP, "_Top") - popup.add_line(ACTION.QUEUE_UP, "_Up") - popup.add_line(ACTION.QUEUE_DOWN, "_Down") - popup.add_line(ACTION.QUEUE_BOTTOM, "_Bottom") + popup = SelectablePopup(self.torrentslist, 'Queue Action', self.do_queue, cb_args=kwargs, border_off_west=1) + popup.add_line(ACTION.QUEUE_TOP, '_Top') + popup.add_line(ACTION.QUEUE_UP, '_Up') + popup.add_line(ACTION.QUEUE_DOWN, '_Down') + popup.add_line(ACTION.QUEUE_BOTTOM, '_Bottom') self.torrentslist.push_popup(popup) diff --git a/deluge/ui/console/modes/torrentlist/search_mode.py b/deluge/ui/console/modes/torrentlist/search_mode.py index c0b8eed7d..554a254f1 100644 --- a/deluge/ui/console/modes/torrentlist/search_mode.py +++ b/deluge/ui/console/modes/torrentlist/search_mode.py @@ -40,12 +40,12 @@ SEARCH_START_REACHED = 3 SEARCH_END_REACHED = 4 SEARCH_FORMAT = { - SEARCH_EMPTY: "{!black,white!}Search torrents: %s{!black,white!}", - SEARCH_SUCCESS: "{!black,white!}Search torrents: {!black,green!}%s{!black,white!}", - SEARCH_FAILING: "{!black,white!}Search torrents: {!black,red!}%s{!black,white!}", + SEARCH_EMPTY: '{!black,white!}Search torrents: %s{!black,white!}', + SEARCH_SUCCESS: '{!black,white!}Search torrents: {!black,green!}%s{!black,white!}', + SEARCH_FAILING: '{!black,white!}Search torrents: {!black,red!}%s{!black,white!}', SEARCH_START_REACHED: - "{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (start reached)", - SEARCH_END_REACHED: "{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (end reached)" + '{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (start reached)', + SEARCH_END_REACHED: '{!black,white!}Search torrents: {!black,yellow!}%s{!black,white!} (end reached)' } @@ -56,15 +56,15 @@ class SearchMode(InputKeyHandler): self.torrentlist = torrentlist self.torrentview = torrentlist.torrentview self.search_state = SEARCH_EMPTY - self.search_string = "" + self.search_string = '' def update_cursor(self): util.safe_curs_set(util.Curser.VERY_VISIBLE) move_cursor(self.torrentlist.stdscr, self.torrentlist.rows - 1, len(self.search_string) + 17) def set_statusbar_args(self, statusbar_args): - statusbar_args["bottombar"] = SEARCH_FORMAT[self.search_state] % self.search_string - statusbar_args["bottombar_help"] = False + statusbar_args['bottombar'] = SEARCH_FORMAT[self.search_state] % self.search_string + statusbar_args['bottombar_help'] = False def update_colors(self, tidx, colors): if len(self.search_string) > 1: @@ -74,14 +74,14 @@ class SearchMode(InputKeyHandler): if tidx == self.torrentview.cursel: pass elif tidx in self.torrentview.marked: - colors["bg"] = "magenta" + colors['bg'] = 'magenta' else: - colors["bg"] = "green" - if colors["fg"] == "green": - colors["fg"] = "black" - colors["attr"] = "bold" + colors['bg'] = 'green' + if colors['fg'] == 'green': + colors['fg'] = 'black' + colors['attr'] = 'bold' - def do_search(self, direction="first"): + def do_search(self, direction='first'): """ Performs a search on visible torrent and sets cursor to the match @@ -91,11 +91,11 @@ class SearchMode(InputKeyHandler): """ search_space = list(enumerate(self.torrentview.torrent_names)) - if direction == "last": + if direction == 'last': search_space = reversed(search_space) - elif direction == "next": + elif direction == 'next': search_space = search_space[self.torrentview.cursel + 1:] - elif direction == "previous": + elif direction == 'previous': search_space = reversed(search_space[:self.torrentview.cursel]) search_string = self.search_string.lower() @@ -110,11 +110,11 @@ class SearchMode(InputKeyHandler): self.torrentview.curoff = max(0, self.torrentview.cursel) self.search_state = SEARCH_SUCCESS return - if direction in ["first", "last"]: + if direction in ['first', 'last']: self.search_state = SEARCH_FAILING - elif direction == "next": + elif direction == 'next': self.search_state = SEARCH_END_REACHED - elif direction == "previous": + elif direction == 'previous': self.search_state = SEARCH_START_REACHED @overrides(InputKeyHandler) @@ -134,16 +134,16 @@ class SearchMode(InputKeyHandler): self.torrentlist.set_minor_mode(None) self.search_state = SEARCH_EMPTY elif c == curses.KEY_DC: - self.search_string = "" + self.search_string = '' self.search_state = SEARCH_SUCCESS elif c == curses.KEY_UP: - self.do_search("previous") + self.do_search('previous') elif c == curses.KEY_DOWN: - self.do_search("next") + self.do_search('next') elif c == curses.KEY_LEFT: self.torrentlist.set_minor_mode(None) self.search_state = SEARCH_EMPTY - elif c == ord("/"): + elif c == ord('/'): self.torrentlist.set_minor_mode(None) self.search_state = SEARCH_EMPTY elif c == curses.KEY_RIGHT: @@ -151,21 +151,21 @@ class SearchMode(InputKeyHandler): self.torrentlist.show_torrent_details(tid) refresh = False elif c == curses.KEY_HOME: - self.do_search("first") + self.do_search('first') elif c == curses.KEY_END: - self.do_search("last") + self.do_search('last') elif c in [10, curses.KEY_ENTER]: self.last_mark = -1 tid = self.torrentview.current_torrent_id() torrent_actions_popup(self.torrentlist, [tid], details=True) refresh = False elif c == util.KEY_ESC: - self.search_string = "" + self.search_string = '' self.search_state = SEARCH_EMPTY elif c > 31 and c < 256: old_search_string = self.search_string stroke = chr(c) - uchar = "" + uchar = '' while not uchar: try: uchar = stroke.decode(self.torrentlist.encoding) diff --git a/deluge/ui/console/modes/torrentlist/torrentactions.py b/deluge/ui/console/modes/torrentlist/torrentactions.py index 1f3a034f2..53bc730b8 100644 --- a/deluge/ui/console/modes/torrentlist/torrentactions.py +++ b/deluge/ui/console/modes/torrentlist/torrentactions.py @@ -24,14 +24,14 @@ from . import ACTION log = logging.getLogger(__name__) torrent_options = [ - "max_download_speed", "max_upload_speed", "max_connections", "max_upload_slots", - "prioritize_first_last", "sequential_download", "is_auto_managed", "stop_at_ratio", - "stop_ratio", "remove_at_ratio", "move_completed", "move_completed_path"] + 'max_download_speed', 'max_upload_speed', 'max_connections', 'max_upload_slots', + 'prioritize_first_last', 'sequential_download', 'is_auto_managed', 'stop_at_ratio', + 'stop_ratio', 'remove_at_ratio', 'move_completed', 'move_completed_path'] def action_error(error, mode): rerr = error.value - mode.report_message("An Error Occurred", "%s got error %s: %s" % ( + mode.report_message('An Error Occurred', '%s got error %s: %s' % ( rerr.method, rerr.exception_type, rerr.exception_msg)) mode.refresh() @@ -40,61 +40,61 @@ def action_remove(mode=None, torrent_ids=None, **kwargs): def do_remove(*args, **kwargs): data = args[0] if args else None - if data is None or kwargs.get("close", False): + if data is None or kwargs.get('close', False): mode.pop_popup() return True mode.clear_marked() - remove_data = data["remove_files"]["value"] + remove_data = data['remove_files']['value'] def on_removed_finished(errors): if errors: - error_msgs = "" + error_msgs = '' for t_id, e_msg in errors: - error_msgs += "Error removing torrent %s : %s\n" % (t_id, e_msg) - mode.report_message("Error(s) occured when trying to delete torrent(s).", error_msgs) + error_msgs += 'Error removing torrent %s : %s\n' % (t_id, e_msg) + mode.report_message('Error(s) occured when trying to delete torrent(s).', error_msgs) mode.refresh() d = client.core.remove_torrents(torrent_ids, remove_data) d.addCallback(on_removed_finished) def got_status(status): - return (status["name"], status["state"]) + return (status['name'], status['state']) callbacks = [] for tid in torrent_ids: - d = client.core.get_torrent_status(tid, ["name", "state"]) + d = client.core.get_torrent_status(tid, ['name', 'state']) callbacks.append(d.addCallback(got_status)) def remove_dialog(status): status = [t_status[1] for t_status in status] if len(torrent_ids) == 1: - rem_msg = "{!info!}Remove the following torrent?{!input!}" + rem_msg = '{!info!}Remove the following torrent?{!input!}' else: - rem_msg = "{!info!}Remove the following %d torrents?{!input!}" % len(torrent_ids) + rem_msg = '{!info!}Remove the following %d torrents?{!input!}' % len(torrent_ids) show_max = 6 for i, (name, state) in enumerate(status): color = colors.state_color[state] - rem_msg += "\n %s* {!input!}%s" % (color, name) + rem_msg += '\n %s* {!input!}%s' % (color, name) if i == show_max - 1: if i < len(status) - 1: - rem_msg += "\n {!red!}And %i more" % (len(status) - show_max) + rem_msg += '\n {!red!}And %i more' % (len(status) - show_max) break - popup = InputPopup(mode, "(Esc to cancel, Enter to remove)", close_cb=do_remove, + popup = InputPopup(mode, '(Esc to cancel, Enter to remove)', close_cb=do_remove, border_off_west=1, border_off_north=1) popup.add_text(rem_msg) popup.add_spaces(1) - popup.add_select_input("remove_files", "{!info!}Torrent files:", - ["Keep", "Remove"], [False, True], False) + popup.add_select_input('remove_files', '{!info!}Torrent files:', + ['Keep', 'Remove'], [False, True], False) mode.push_popup(popup) defer.DeferredList(callbacks).addCallback(remove_dialog) def action_torrent_info(mode=None, torrent_ids=None, **kwargs): - popup = MessagePopup(mode, "Torrent options", "Querying core, please wait...") + popup = MessagePopup(mode, 'Torrent options', 'Querying core, please wait...') mode.push_popup(popup) torrents = torrent_ids options = {} @@ -102,8 +102,8 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): def _do_set_torrent_options(torrent_ids, result): options = {} for opt, val in result.iteritems(): - if val["value"] not in ["multiple", None]: - options[opt] = val["value"] + if val['value'] not in ['multiple', None]: + options[opt] = val['value'] client.core.set_torrent_options(torrent_ids, options) def on_torrent_status(status): @@ -111,7 +111,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): if key not in options: options[key] = status[key] elif options[key] != status[key]: - options[key] = "multiple" + options[key] = 'multiple' def create_popup(status): mode.pop_popup() @@ -120,14 +120,14 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): if result is None: return _do_set_torrent_options(torrent_ids, result) - if kwargs.get("close", False): + if kwargs.get('close', False): mode.pop_popup() return True - option_popup = InputPopup(mode, " Set Torrent Options ", close_cb=cb, + option_popup = InputPopup(mode, ' Set Torrent Options ', close_cb=cb, border_off_west=1, border_off_north=1, - base_popup=kwargs.get("base_popup", None)) + base_popup=kwargs.get('base_popup', None)) for field in torrent_options: - caption = "{!info!}" + TORRENT_DATA_FIELD[field]["name"] + caption = '{!info!}' + TORRENT_DATA_FIELD[field]['name'] value = options[field] field_type = type(value) if field_type in [str, unicode]: @@ -135,7 +135,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): value = str(value) option_popup.add_text_input(field, caption, value) elif field_type == bool: - choices = (["Yes", "No"], [True, False], [True, False].index(options[field])) + choices = (['Yes', 'No'], [True, False], [True, False].index(options[field])) option_popup.add_select_input(field, caption, choices[0], choices[1], choices[2]) elif field_type == float: option_popup.add_float_spin_input(field, caption, value=value, min_val=-1) @@ -146,7 +146,7 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): callbacks = [] for tid in torrents: - deferred = component.get("SessionProxy").get_torrent_status(tid, torrent_options) + deferred = component.get('SessionProxy').get_torrent_status(tid, torrent_options) callbacks.append(deferred.addCallback(on_torrent_status)) callbacks = defer.DeferredList(callbacks) @@ -155,18 +155,18 @@ def action_torrent_info(mode=None, torrent_ids=None, **kwargs): def torrent_action(action, *args, **kwargs): retval = False - torrent_ids = kwargs.get("torrent_ids", None) - mode = kwargs.get("mode", None) + torrent_ids = kwargs.get('torrent_ids', None) + mode = kwargs.get('mode', None) if torrent_ids is None: return if action == ACTION.PAUSE: - log.debug("Pausing torrents: %s", torrent_ids) + log.debug('Pausing torrents: %s', torrent_ids) client.core.pause_torrent(torrent_ids).addErrback(action_error, mode) retval = True elif action == ACTION.RESUME: - log.debug("Resuming torrents: %s", torrent_ids) + log.debug('Resuming torrents: %s', torrent_ids) client.core.resume_torrent(torrent_ids).addErrback(action_error, mode) retval = True elif action == ACTION.QUEUE: @@ -178,34 +178,34 @@ def torrent_action(action, *args, **kwargs): return False elif action == ACTION.MOVE_STORAGE: def do_move(res, **kwargs): - if res is None or kwargs.get("close", False): + if res is None or kwargs.get('close', False): mode.pop_popup() return True - if os.path.exists(res["path"]["value"]) and not os.path.isdir(res["path"]["value"]): - mode.report_message("Cannot Move Download Folder", - "{!error!}%s exists and is not a directory" % res["path"]["value"]) + if os.path.exists(res['path']['value']) and not os.path.isdir(res['path']['value']): + mode.report_message('Cannot Move Download Folder', + '{!error!}%s exists and is not a directory' % res['path']['value']) else: - log.debug("Moving %s to: %s", torrent_ids, res["path"]["value"]) - client.core.move_storage(torrent_ids, res["path"]["value"]).addErrback(action_error, mode) - popup = InputPopup(mode, "Move Download Folder", close_cb=do_move, border_off_east=1) - popup.add_text_input("path", "Enter path to move to:", complete=True) + log.debug('Moving %s to: %s', torrent_ids, res['path']['value']) + client.core.move_storage(torrent_ids, res['path']['value']).addErrback(action_error, mode) + popup = InputPopup(mode, 'Move Download Folder', close_cb=do_move, border_off_east=1) + popup.add_text_input('path', 'Enter path to move to:', complete=True) mode.push_popup(popup) elif action == ACTION.RECHECK: - log.debug("Rechecking torrents: %s", torrent_ids) + log.debug('Rechecking torrents: %s', torrent_ids) client.core.force_recheck(torrent_ids).addErrback(action_error, mode) retval = True elif action == ACTION.REANNOUNCE: - log.debug("Reannouncing torrents: %s", torrent_ids) + log.debug('Reannouncing torrents: %s', torrent_ids) client.core.force_reannounce(torrent_ids).addErrback(action_error, mode) retval = True elif action == ACTION.DETAILS: - log.debug("Torrent details") + log.debug('Torrent details') tid = mode.torrentview.current_torrent_id() if tid: mode.show_torrent_details(tid) else: - log.error("No current torrent in _torrentaction, this is a bug") + log.error('No current torrent in _torrentaction, this is a bug') elif action == ACTION.TORRENT_OPTIONS: action_torrent_info(**kwargs) @@ -219,23 +219,23 @@ def torrent_actions_popup(mode, torrent_ids, details=False, action=None, close_c torrent_action(action, mode=mode, torrent_ids=torrent_ids) return - popup = SelectablePopup(mode, "Torrent Actions", torrent_action, - cb_args={"mode": mode, "torrent_ids": torrent_ids}, + popup = SelectablePopup(mode, 'Torrent Actions', torrent_action, + cb_args={'mode': mode, 'torrent_ids': torrent_ids}, close_cb=close_cb, border_off_north=1, border_off_west=1, border_off_east=1) - popup.add_line(ACTION.PAUSE, "_Pause") - popup.add_line(ACTION.RESUME, "_Resume") + popup.add_line(ACTION.PAUSE, '_Pause') + popup.add_line(ACTION.RESUME, '_Resume') if details: popup.add_divider() - popup.add_line(ACTION.QUEUE, "Queue") + popup.add_line(ACTION.QUEUE, 'Queue') popup.add_divider() - popup.add_line(ACTION.REANNOUNCE, "_Update Tracker") + popup.add_line(ACTION.REANNOUNCE, '_Update Tracker') popup.add_divider() - popup.add_line(ACTION.REMOVE, "Remo_ve Torrent") - popup.add_line(ACTION.RECHECK, "_Force Recheck") - popup.add_line(ACTION.MOVE_STORAGE, "_Move Download Folder") + popup.add_line(ACTION.REMOVE, 'Remo_ve Torrent') + popup.add_line(ACTION.RECHECK, '_Force Recheck') + popup.add_line(ACTION.MOVE_STORAGE, '_Move Download Folder') popup.add_divider() if details: - popup.add_line(ACTION.DETAILS, "Torrent _Details") - popup.add_line(ACTION.TORRENT_OPTIONS, "Torrent _Options") + popup.add_line(ACTION.DETAILS, 'Torrent _Details') + popup.add_line(ACTION.TORRENT_OPTIONS, 'Torrent _Options') mode.push_popup(popup) diff --git a/deluge/ui/console/modes/torrentlist/torrentlist.py b/deluge/ui/console/modes/torrentlist/torrentlist.py index e537acfdc..8c8faa1c5 100644 --- a/deluge/ui/console/modes/torrentlist/torrentlist.py +++ b/deluge/ui/console/modes/torrentlist/torrentlist.py @@ -102,14 +102,14 @@ where you input something class TorrentList(BaseMode, PopupsHandler): def __init__(self, stdscr, encoding=None): - BaseMode.__init__(self, stdscr, encoding=encoding, do_refresh=False, depend=["SessionProxy"]) + BaseMode.__init__(self, stdscr, encoding=encoding, do_refresh=False, depend=['SessionProxy']) PopupsHandler.__init__(self) self.messages = deque() self.last_mark = -1 self.go_top = False self.minor_mode = None - self.consoleui = component.get("ConsoleUI") + self.consoleui = component.get('ConsoleUI') self.coreconfig = self.consoleui.coreconfig self.config = self.consoleui.config self.sidebar = FilterSidebar(self, self.config) @@ -128,7 +128,7 @@ class TorrentList(BaseMode, PopupsHandler): self.torrentview.on_config_changed() def toggle_sidebar(self): - if self.config["torrentview"]["show_sidebar"]: + if self.config['torrentview']['show_sidebar']: self.sidebar.show() self.sidebar.resize_window(curses.LINES - 2, self.sidebar.width) self.torrentview_panel.resize(curses.LINES - 1, curses.COLS - self.sidebar.width) @@ -147,9 +147,9 @@ class TorrentList(BaseMode, PopupsHandler): self.torrentview.on_config_changed() self.toggle_sidebar() - if self.config["first_run"]: - self.push_popup(MessagePopup(self, "Welcome to Deluge", HELP_STR, width_req=0.65)) - self.config["first_run"] = False + if self.config['first_run']: + self.push_popup(MessagePopup(self, 'Welcome to Deluge', HELP_STR, width_req=0.65)) + self.config['first_run'] = False self.config.save() if client.connected(): @@ -180,7 +180,7 @@ class TorrentList(BaseMode, PopupsHandler): self.toggle_sidebar() def show_torrent_details(self, tid): - mode = self.consoleui.set_mode("TorrentDetail") + mode = self.consoleui.set_mode('TorrentDetail') mode.update(tid) def set_minor_mode(self, mode): @@ -206,9 +206,9 @@ class TorrentList(BaseMode, PopupsHandler): self.add_string(1, self.torrentview.column_string, scr=self.torrentview_panel) # Update the status bars - statusbar_args = {"scr": self.stdscr, "bottombar_help": True} + statusbar_args = {'scr': self.stdscr, 'bottombar_help': True} if self.torrentview.curr_filter is not None: - statusbar_args["topbar"] = ("%s {!filterstatus!}Current filter: %s" + statusbar_args['topbar'] = ('%s {!filterstatus!}Current filter: %s' % (self.statusbars.topbar, self.torrentview.curr_filter)) if self.minor_mode: @@ -258,7 +258,7 @@ class TorrentList(BaseMode, PopupsHandler): self.refresh() return ret if util.is_printable_char(c): - if chr(c) == "Q": + if chr(c) == 'Q': from twisted.internet import reactor if client.connected(): def on_disconnect(result): @@ -267,14 +267,14 @@ class TorrentList(BaseMode, PopupsHandler): else: reactor.stop() return - elif chr(c) == "C": - self.consoleui.set_mode("ConnectionManager") + elif chr(c) == 'C': + self.consoleui.set_mode('ConnectionManager') return - elif chr(c) == "q": + elif chr(c) == 'q': self.torrentview.update_marked(self.torrentview.cursel) self.set_minor_mode(QueueMode(self, self.torrentview._selected_torrent_ids())) return - elif chr(c) == "/": + elif chr(c) == '/': self.set_minor_mode(SearchMode(self)) return @@ -311,25 +311,25 @@ class TorrentList(BaseMode, PopupsHandler): return elif util.is_printable_char(c): - if chr(c) == "a": + if chr(c) == 'a': show_torrent_add_popup(self) - elif chr(c) == "v": + elif chr(c) == 'v': self._show_visible_columns_popup() - elif chr(c) == "h": - self.push_popup(MessagePopup(self, "Help", HELP_STR, width_req=0.65)) - elif chr(c) == "p": - mode = self.consoleui.set_mode("Preferences") + elif chr(c) == 'h': + self.push_popup(MessagePopup(self, 'Help', HELP_STR, width_req=0.65)) + elif chr(c) == 'p': + mode = self.consoleui.set_mode('Preferences') mode.load_config() return - elif chr(c) == "e": - self.consoleui.set_mode("EventView") + elif chr(c) == 'e': + self.consoleui.set_mode('EventView') return - elif chr(c) == "S": - self.config["torrentview"]["show_sidebar"] = self.config["torrentview"]["show_sidebar"] is False + elif chr(c) == 'S': + self.config['torrentview']['show_sidebar'] = self.config['torrentview']['show_sidebar'] is False self.config.save() self.toggle_sidebar() - elif chr(c) == "l": - self.consoleui.set_mode("CmdLine", refresh=True) + elif chr(c) == 'l': + self.consoleui.set_mode('CmdLine', refresh=True) return self.refresh(affected_lines) diff --git a/deluge/ui/console/modes/torrentlist/torrentview.py b/deluge/ui/console/modes/torrentlist/torrentview.py index 7b35fd8a8..dd54e6dfd 100644 --- a/deluge/ui/console/modes/torrentlist/torrentview.py +++ b/deluge/ui/console/modes/torrentlist/torrentview.py @@ -20,12 +20,12 @@ except ImportError: log = logging.getLogger(__name__) -state_fg_colors = {"Downloading": "green", - "Seeding": "cyan", - "Error": "red", - "Queued": "yellow", - "Checking": "blue", - "Moving": "green"} +state_fg_colors = {'Downloading': 'green', + 'Seeding': 'cyan', + 'Error': 'red', + 'Queued': 'yellow', + 'Checking': 'blue', + 'Moving': 'green'} def _queue_sort(v1, v2): @@ -42,47 +42,47 @@ def _queue_sort(v1, v2): reverse_sort_fields = [ - "size", - "download_speed", - "upload_speed", - "num_seeds", - "num_peers", - "distributed_copies", - "time_added", - "total_uploaded", - "all_time_download", - "total_remaining", - "progress", - "ratio", - "seeding_time", - "active_time" + 'size', + 'download_speed', + 'upload_speed', + 'num_seeds', + 'num_peers', + 'distributed_copies', + 'time_added', + 'total_uploaded', + 'all_time_download', + 'total_remaining', + 'progress', + 'ratio', + 'seeding_time', + 'active_time' ] default_column_values = { - "queue": {"width": 4, "visible": True}, - "name": {"width": -1, "visible": True}, - "size": {"width": 8, "visible": True}, - "progress": {"width": 7, "visible": True}, - "download_speed": {"width": 7, "visible": True}, - "upload_speed": {"width": 7, "visible": True}, - "state": {"width": 13}, - "eta": {"width": 8, "visible": True}, - "time_added": {"width": 15}, - "tracker": {"width": 15}, - "download_location": {"width": 15}, - "downloaded": {"width": 13}, - "uploaded": {"width": 7}, - "remaining": {"width": 13}, - "completed_time": {"width": 15}, - "last_seen_complete": {"width": 15}, - "max_upload_speed": {"width": 7}, + 'queue': {'width': 4, 'visible': True}, + 'name': {'width': -1, 'visible': True}, + 'size': {'width': 8, 'visible': True}, + 'progress': {'width': 7, 'visible': True}, + 'download_speed': {'width': 7, 'visible': True}, + 'upload_speed': {'width': 7, 'visible': True}, + 'state': {'width': 13}, + 'eta': {'width': 8, 'visible': True}, + 'time_added': {'width': 15}, + 'tracker': {'width': 15}, + 'download_location': {'width': 15}, + 'downloaded': {'width': 13}, + 'uploaded': {'width': 7}, + 'remaining': {'width': 13}, + 'completed_time': {'width': 15}, + 'last_seen_complete': {'width': 15}, + 'max_upload_speed': {'width': 7}, } default_columns = {} for col_i, col_name in enumerate(torrentviewcolumns.column_pref_names): - default_columns[col_name] = {"width": 10, "order": col_i, "visible": False} + default_columns[col_name] = {'width': 10, 'order': col_i, 'visible': False} if col_name in default_column_values: default_columns[col_name].update(default_column_values[col_name]) @@ -99,7 +99,7 @@ class TorrentView(InputKeyHandler): self.sorted_ids = None self.torrent_names = None self.numtorrents = -1 - self.column_string = "" + self.column_string = '' self.curoff = 0 self.marked = [] self.cursel = 0 @@ -124,7 +124,7 @@ class TorrentView(InputKeyHandler): self.torrent_names = [] for torrent_id in self.sorted_ids: ts = self.curstate[torrent_id] - self.torrent_names.append(ts["name"]) + self.torrent_names.append(ts['name']) if refresh: self.torrentlist.refresh() @@ -132,7 +132,7 @@ class TorrentView(InputKeyHandler): def set_torrent_filter(self, state): self.curr_filter = state filter_dict = {'state': [state]} - if state == "All": + if state == 'All': self.curr_filter = None filter_dict = {} self.filter_dict = filter_dict @@ -208,13 +208,13 @@ class TorrentView(InputKeyHandler): return False def _sort_torrents(self, state): - "sorts by primary and secondary sort fields" + 'sorts by primary and secondary sort fields' if not state: return {} - s_primary = self.config["torrentview"]["sort_primary"] - s_secondary = self.config["torrentview"]["sort_secondary"] + s_primary = self.config['torrentview']['sort_primary'] + s_secondary = self.config['torrentview']['sort_secondary'] result = state @@ -222,7 +222,7 @@ class TorrentView(InputKeyHandler): # so it all works out def sort_by_field(state, to_sort, field): - field = torrent_data_fields[field]["status"][0] + field = torrent_data_fields[field]['status'][0] reverse = field in reverse_sort_fields # Get first element so we can check if it has given field @@ -242,38 +242,38 @@ class TorrentView(InputKeyHandler): if is_string: to_sort = sorted(to_sort, _queue_sort, sort_key2, reverse) - if field == "eta": - to_sort = sorted(to_sort, key=lambda s: state.get(s)["eta"] == 0) + if field == 'eta': + to_sort = sorted(to_sort, key=lambda s: state.get(s)['eta'] == 0) return to_sort # Just in case primary and secondary fields are empty and/or # both are too ambiguous, also sort by queue position first - if "queue" not in [s_secondary, s_primary]: - result = sort_by_field(state, result, "queue") + if 'queue' not in [s_secondary, s_primary]: + result = sort_by_field(state, result, 'queue') if s_secondary != s_primary: result = sort_by_field(state, result, s_secondary) result = sort_by_field(state, result, s_primary) - if self.config["torrentview"]["separate_complete"]: - result = sorted(result, _queue_sort, lambda s: state.get(s).get("progress", 0) == 100.0) + if self.config['torrentview']['separate_complete']: + result = sorted(result, _queue_sort, lambda s: state.get(s).get('progress', 0) == 100.0) return result def _get_colors(self, row, tidx): # default style - colors = {"fg": "white", "bg": "black", "attr": None} + colors = {'fg': 'white', 'bg': 'black', 'attr': None} if tidx in self.marked: - colors.update({"bg": "blue", "attr": "bold"}) + colors.update({'bg': 'blue', 'attr': 'bold'}) if tidx == self.cursel: - col_selected = {"bg": "white", "fg": "black", "attr": "bold"} + col_selected = {'bg': 'white', 'fg': 'black', 'attr': 'bold'} if tidx in self.marked: - col_selected["fg"] = "blue" + col_selected['fg'] = 'blue' colors.update(col_selected) - colors["fg"] = state_fg_colors.get(row[1], colors["fg"]) + colors['fg'] = state_fg_colors.get(row[1], colors['fg']) if self.torrentlist.minor_mode: self.torrentlist.minor_mode.update_colors(tidx, colors) @@ -283,17 +283,17 @@ class TorrentView(InputKeyHandler): # add all the torrents if self.numtorrents == 0: cols = self.torrentlist.torrentview_columns() - msg = "No torrents match filter".center(cols) - self.torrentlist.add_string(3, "{!info!}%s" % msg, scr=self.torrentlist.torrentview_panel) + msg = 'No torrents match filter'.center(cols) + self.torrentlist.add_string(3, '{!info!}%s' % msg, scr=self.torrentlist.torrentview_panel) elif self.numtorrents == 0: - self.torrentlist.add_string(1, "Waiting for torrents from core...") + self.torrentlist.add_string(1, 'Waiting for torrents from core...') return def draw_row(index): if index not in self.cached_rows: ts = self.curstate[self.sorted_ids[index]] self.cached_rows[index] = (format_utils.format_row( - [get_column_value(name, ts) for name in self.cols_to_show], self.column_widths), ts["state"]) + [get_column_value(name, ts) for name in self.cols_to_show], self.column_widths), ts['state']) return self.cached_rows[index] tidx = self.curoff @@ -317,36 +317,36 @@ class TorrentView(InputKeyHandler): if (currow + self.torrentlist_offset - 1) > self.torrent_rows: continue colors = self._get_colors(row, tidx) - if colors["attr"]: - colorstr = "{!%(fg)s,%(bg)s,%(attr)s!}" % colors + if colors['attr']: + colorstr = '{!%(fg)s,%(bg)s,%(attr)s!}' % colors else: - colorstr = "{!%(fg)s,%(bg)s!}" % colors + colorstr = '{!%(fg)s,%(bg)s!}' % colors - self.torrentlist.add_string(currow + self.torrentlist_offset, "%s%s" % (colorstr, row[0]), + self.torrentlist.add_string(currow + self.torrentlist_offset, '%s%s' % (colorstr, row[0]), trim=False, scr=self.torrentlist.torrentview_panel) def update(self, refresh=False): - d = component.get("SessionProxy").get_torrents_status(self.filter_dict, + d = component.get('SessionProxy').get_torrents_status(self.filter_dict, self.status_fields) d.addCallback(self.update_state, refresh=refresh) def on_config_changed(self): - s_primary = self.config["torrentview"]["sort_primary"] - s_secondary = self.config["torrentview"]["sort_secondary"] + s_primary = self.config['torrentview']['sort_primary'] + s_secondary = self.config['torrentview']['sort_secondary'] changed = None for col in default_columns: - if col not in self.config["torrentview"]["columns"]: - changed = self.config["torrentview"]["columns"][col] = default_columns[col] + if col not in self.config['torrentview']['columns']: + changed = self.config['torrentview']['columns'][col] = default_columns[col] if changed: self.config.save() - self.cols_to_show = [col for col in sorted(self.config["torrentview"]["columns"], - key=lambda (k): self.config["torrentview"]["columns"][k]["order"]) - if self.config["torrentview"]["columns"][col]["visible"]] + self.cols_to_show = [col for col in sorted(self.config['torrentview']['columns'], + key=lambda (k): self.config['torrentview']['columns'][k]['order']) + if self.config['torrentview']['columns'][col]['visible']] self.status_fields = get_required_fields(self.cols_to_show) # we always need these, even if we're not displaying them - for rf in ["state", "name", "queue", "progress"]: + for rf in ['state', 'name', 'queue', 'progress']: if rf not in self.status_fields: self.status_fields.append(rf) @@ -359,7 +359,7 @@ class TorrentView(InputKeyHandler): self.update_columns() def update_columns(self): - self.column_widths = [self.config["torrentview"]["columns"][col]["width"] for col in self.cols_to_show] + self.column_widths = [self.config['torrentview']['columns'][col]['width'] for col in self.cols_to_show] requested_width = sum([width for width in self.column_widths if width >= 0]) cols = self.torrentlist.torrentview_columns() @@ -376,12 +376,12 @@ class TorrentView(InputKeyHandler): if self.column_widths[i] < 0: self.column_widths[i] = vw - self.column_string = "{!header!}" + self.column_string = '{!header!}' - primary_sort_col_name = self.config["torrentview"]["sort_primary"] + primary_sort_col_name = self.config['torrentview']['sort_primary'] for i, column in enumerate(self.cols_to_show): - ccol = torrent_data_fields[column]["name"] + ccol = torrent_data_fields[column]['name'] width = self.column_widths[i] # Trim the column if it's too long to fit @@ -389,14 +389,14 @@ class TorrentView(InputKeyHandler): ccol = ccol[:width - 1] # Padding - ccol += " " * (width - len(ccol)) + ccol += ' ' * (width - len(ccol)) # Highlight the primary sort column if column == primary_sort_col_name: if i != len(self.cols_to_show) - 1: - ccol = "{!black,green,bold!}%s{!header!}" % ccol + ccol = '{!black,green,bold!}%s{!header!}' % ccol else: - ccol = ("{!black,green,bold!}%s" % ccol)[:-1] + ccol = ('{!black,green,bold!}%s' % ccol)[:-1] self.column_string += ccol @@ -434,14 +434,14 @@ class TorrentView(InputKeyHandler): torrent_actions_popup(self.torrentlist, self._selected_torrent_ids(), details=True, close_cb=on_close) self.torrentlist.refresh() - elif c == ord("j"): + elif c == ord('j'): affected_lines = self._scroll_up(1) - elif c == ord("k"): + elif c == ord('k'): affected_lines = self._scroll_down(1) - elif c == ord("m"): + elif c == ord('m'): self.mark_unmark(self.cursel) affected_lines = [self.cursel] - elif c == ord("M"): + elif c == ord('M'): if self.last_mark >= 0: if self.cursel > self.last_mark: mrange = range(self.last_mark, self.cursel + 1) @@ -452,24 +452,24 @@ class TorrentView(InputKeyHandler): else: self.mark_unmark(self.cursel) affected_lines = [self.cursel] - elif c == ord("c"): + elif c == ord('c'): self.clear_marked() - elif c == ord("o"): + elif c == ord('o'): if not self.marked: added = self.update_marked(self.cursel, clear=True) else: self.last_mark = -1 torrent_actions_popup(self.torrentlist, self._selected_torrent_ids(), action=ACTION.TORRENT_OPTIONS) - elif c in [ord(">"), ord("<")]: + elif c in [ord('>'), ord('<')]: try: - i = self.cols_to_show.index(self.config["torrentview"]["sort_primary"]) + i = self.cols_to_show.index(self.config['torrentview']['sort_primary']) except ValueError: i = 0 if chr(c) == '<' else len(self.cols_to_show) else: i += 1 if chr(c) == '>' else -1 i = max(0, min(len(self.cols_to_show) - 1, i)) - self.config["torrentview"]["sort_primary"] = self.cols_to_show[i] + self.config['torrentview']['sort_primary'] = self.cols_to_show[i] self.config.save() self.on_config_changed() self.update_columns() diff --git a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py index b7872ca59..6b3855abd 100644 --- a/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py +++ b/deluge/ui/console/modes/torrentlist/torrentviewcolumns.py @@ -23,12 +23,12 @@ Control column visibilty with the following actions: {!info!}'CTRL+down'{!normal!} - {|indent_pos:|} Move column right """ -column_pref_names = ["queue", "name", "size", "downloaded", "uploaded", "remaining", "state", - "progress", "seeds", "peers", "seeds_peers_ratio", - "download_speed", "upload_speed", "max_download_speed", "max_upload_speed", - "eta", "ratio", "avail", "time_added", "completed_time", "last_seen_complete", - "tracker", "download_location", "active_time", "seeding_time", "finished_time", - "shared", "owner"] +column_pref_names = ['queue', 'name', 'size', 'downloaded', 'uploaded', 'remaining', 'state', + 'progress', 'seeds', 'peers', 'seeds_peers_ratio', + 'download_speed', 'upload_speed', 'max_download_speed', 'max_upload_speed', + 'eta', 'ratio', 'avail', 'time_added', 'completed_time', 'last_seen_complete', + 'tracker', 'download_location', 'active_time', 'seeding_time', 'finished_time', + 'shared', 'owner'] class ColumnAndWidth(CheckedPlusInput): @@ -54,7 +54,7 @@ class TorrentViewColumns(InputPopup): self.torrentlist = torrentlist self.torrentview = torrentlist.torrentview - title = "Visible columns (Esc to exit)" + title = 'Visible columns (Esc to exit)' InputPopup.__init__(self, torrentlist, title, close_cb=self._do_set_column_visibility, immediate_action=True, height_req=len(column_pref_names) - 5, @@ -62,20 +62,20 @@ class TorrentViewColumns(InputPopup): border_off_west=1, allow_rearrange=True) - msg_fmt = "%-25s" - self.add_header((msg_fmt % _("Columns")) + " " + _("Width"), space_below=True) + msg_fmt = '%-25s' + self.add_header((msg_fmt % _('Columns')) + ' ' + _('Width'), space_below=True) for colpref_name in column_pref_names: - col = self.torrentview.config["torrentview"]["columns"][colpref_name] - width_spin = IntSpinInput(self, colpref_name + "_ width", "", self.move, col["width"], - min_val=-1, max_val=99, fmt="%2d") + col = self.torrentview.config['torrentview']['columns'][colpref_name] + width_spin = IntSpinInput(self, colpref_name + '_ width', '', self.move, col['width'], + min_val=-1, max_val=99, fmt='%2d') def on_width_func(name, width): - self.torrentview.config["torrentview"]["columns"][name]["width"] = width + self.torrentview.config['torrentview']['columns'][name]['width'] = width - self._add_input(ColumnAndWidth(self, colpref_name, torrent_data_fields[colpref_name]["name"], width_spin, + self._add_input(ColumnAndWidth(self, colpref_name, torrent_data_fields[colpref_name]['name'], width_spin, on_width_func, - checked=col["visible"], checked_char="*", msg_fmt=msg_fmt, + checked=col['visible'], checked_char='*', msg_fmt=msg_fmt, show_usage_hints=False, child_always_visible=True)) def _do_set_column_visibility(self, data=None, state_changed=True, close=True, **kwargs): @@ -86,8 +86,8 @@ class TorrentViewColumns(InputPopup): return for key, value in data.items(): - self.torrentview.config["torrentview"]["columns"][key]["visible"] = value["value"] - self.torrentview.config["torrentview"]["columns"][key]["order"] = value["order"] + self.torrentview.config['torrentview']['columns'][key]['visible'] = value['value'] + self.torrentview.config['torrentview']['columns'][key]['order'] = value['order'] self.torrentview.config.save() self.torrentview.on_config_changed() @@ -96,7 +96,7 @@ class TorrentViewColumns(InputPopup): @overrides(InputPopup) def handle_read(self, c): if c == ord('h'): - popup = MessagePopup(self.torrentlist, "Help", COLUMN_VIEW_HELP_STR, width_req=70, border_off_west=1) + popup = MessagePopup(self.torrentlist, 'Help', COLUMN_VIEW_HELP_STR, width_req=70, border_off_west=1) self.torrentlist.push_popup(popup) return util.ReadState.READ return InputPopup.handle_read(self, c) diff --git a/deluge/ui/console/parser.py b/deluge/ui/console/parser.py index 94f911c55..42138c14c 100644 --- a/deluge/ui/console/parser.py +++ b/deluge/ui/console/parser.py @@ -29,7 +29,7 @@ class ConsoleBaseParser(argparse.ArgumentParser): """ # Handle epilog manually to keep the text formatting epilog = self.epilog - self.epilog = "" + self.epilog = '' help_str = super(ConsoleBaseParser, self).format_help() if epilog is not None: help_str += epilog @@ -44,9 +44,9 @@ class ConsoleCommandParser(ConsoleBaseParser): for a in args: if not a: continue - if ";" in a: - cmd_lines = [arg.strip() for arg in a.split(";")] - elif " " in a: + if ';' in a: + cmd_lines = [arg.strip() for arg in a.split(';')] + elif ' ' in a: cmd_lines = [a] else: continue @@ -84,8 +84,8 @@ class ConsoleCommandParser(ConsoleBaseParser): options.parsed_cmds = multi_command else: subcommand = False - if hasattr(self.base_parser, "subcommand"): - subcommand = getattr(self.base_parser, "subcommand") + if hasattr(self.base_parser, 'subcommand'): + subcommand = getattr(self.base_parser, 'subcommand') if not subcommand: # We must use parse_known_args to handle case when no subcommand # is provided, because argparse does not support parsing without @@ -100,7 +100,7 @@ class ConsoleCommandParser(ConsoleBaseParser): options = super(ConsoleCommandParser, self).parse_args(args=args) options.parsed_cmds = [options] - if not hasattr(options, "remaining"): + if not hasattr(options, 'remaining'): options.remaining = [] return options @@ -127,13 +127,13 @@ class OptionParser(ConsoleBaseParser): raise OptionParserError(msg) def print_usage(self, _file=None): - console = component.get("ConsoleUI") + console = component.get('ConsoleUI') if self.usage: for line in self.format_usage().splitlines(): console.write(line) def print_help(self, _file=None): - console = component.get("ConsoleUI") + console = component.get('ConsoleUI') console.set_batch_write(True) for line in self.format_help().splitlines(): console.write(line) diff --git a/deluge/ui/console/utils/colors.py b/deluge/ui/console/utils/colors.py index f63c91f11..37b15759a 100644 --- a/deluge/ui/console/utils/colors.py +++ b/deluge/ui/console/utils/colors.py @@ -20,55 +20,55 @@ except ImportError: log = logging.getLogger(__name__) colors = [ - "COLOR_BLACK", - "COLOR_BLUE", - "COLOR_CYAN", - "COLOR_GREEN", - "COLOR_MAGENTA", - "COLOR_RED", - "COLOR_WHITE", - "COLOR_YELLOW" + 'COLOR_BLACK', + 'COLOR_BLUE', + 'COLOR_CYAN', + 'COLOR_GREEN', + 'COLOR_MAGENTA', + 'COLOR_RED', + 'COLOR_WHITE', + 'COLOR_YELLOW' ] # {(fg, bg): pair_number, ...} color_pairs = { - ("white", "black"): 0 # Special case, can't be changed + ('white', 'black'): 0 # Special case, can't be changed } # Some default color schemes schemes = { - "input": ("white", "black"), - "normal": ("white", "black"), - "status": ("yellow", "blue", "bold"), - "info": ("white", "black", "bold"), - "error": ("red", "black", "bold"), - "success": ("green", "black", "bold"), - "event": ("magenta", "black", "bold"), - "selected": ("black", "white", "bold"), - "marked": ("white", "blue", "bold"), - "selectedmarked": ("blue", "white", "bold"), - "header": ("green", "black", "bold"), - "filterstatus": ("green", "blue", "bold") + 'input': ('white', 'black'), + 'normal': ('white', 'black'), + 'status': ('yellow', 'blue', 'bold'), + 'info': ('white', 'black', 'bold'), + 'error': ('red', 'black', 'bold'), + 'success': ('green', 'black', 'bold'), + 'event': ('magenta', 'black', 'bold'), + 'selected': ('black', 'white', 'bold'), + 'marked': ('white', 'blue', 'bold'), + 'selectedmarked': ('blue', 'white', 'bold'), + 'header': ('green', 'black', 'bold'), + 'filterstatus': ('green', 'blue', 'bold') } # Colors for various torrent states state_color = { - "Seeding": "{!blue,black,bold!}", - "Downloading": "{!green,black,bold!}", - "Paused": "{!white,black!}", - "Checking": "{!green,black!}", - "Queued": "{!yellow,black!}", - "Error": "{!red,black,bold!}", - "Moving": "{!green,black,bold!}" + 'Seeding': '{!blue,black,bold!}', + 'Downloading': '{!green,black,bold!}', + 'Paused': '{!white,black!}', + 'Checking': '{!green,black!}', + 'Queued': '{!yellow,black!}', + 'Error': '{!red,black,bold!}', + 'Moving': '{!green,black,bold!}' } type_color = { - bool: "{!yellow,black,bold!}", - int: "{!green,black,bold!}", - float: "{!green,black,bold!}", - str: "{!cyan,black,bold!}", - list: "{!magenta,black,bold!}", - dict: "{!white,black,bold!}" + bool: '{!yellow,black,bold!}', + int: '{!green,black,bold!}', + float: '{!green,black,bold!}', + str: '{!cyan,black,bold!}', + list: '{!magenta,black,bold!}', + dict: '{!white,black,bold!}' } @@ -88,7 +88,7 @@ def init_colors(): color_pairs[(fg_name, bg_name)] = counter counter += 1 except curses.error as ex: - log.warn("Error: %s", ex) + log.warn('Error: %s', ex) return counter # Create the color_pairs dict @@ -97,9 +97,9 @@ def init_colors(): for bg in colors: counter = define_pair(counter, fg[6:].lower(), bg[6:].lower(), getattr(curses, fg), getattr(curses, bg)) - counter = define_pair(counter, "white", "grey", curses.COLOR_WHITE, 241) - counter = define_pair(counter, "black", "whitegrey", curses.COLOR_BLACK, 249) - counter = define_pair(counter, "magentadark", "white", 99, curses.COLOR_WHITE) + counter = define_pair(counter, 'white', 'grey', curses.COLOR_WHITE, 241) + counter = define_pair(counter, 'black', 'whitegrey', curses.COLOR_BLACK, 249) + counter = define_pair(counter, 'magentadark', 'white', 99, curses.COLOR_WHITE) class BadColorString(Exception): @@ -111,9 +111,9 @@ def replace_tabs(line): Returns a string with tabs replaced with spaces. """ - for i in range(line.count("\t")): - tab_length = 8 - (len(line[:line.find("\t")]) % 8) - line = line.replace("\t", " " * tab_length, 1) + for i in range(line.count('\t')): + tab_length = 8 - (len(line[:line.find('\t')]) % 8) + line = line.replace('\t', ' ' * tab_length, 1) return line @@ -123,22 +123,22 @@ def strip_colors(line): """ # Remove all the color tags - while line.find("{!") != -1: - line = line[:line.find("{!")] + line[line.find("!}") + 2:] + while line.find('{!') != -1: + line = line[:line.find('{!')] + line[line.find('!}') + 2:] return line -def get_line_length(line, encoding="UTF-8"): +def get_line_length(line, encoding='UTF-8'): """ Returns the string length without the color formatting. """ - if line.count("{!") != line.count("!}"): - raise BadColorString("Number of {! is not equal to number of !}") + if line.count('{!') != line.count('!}'): + raise BadColorString('Number of {! is not equal to number of !}') if isinstance(line, unicode): - line = line.encode(encoding, "replace") + line = line.encode(encoding, 'replace') # Remove all the color tags line = strip_colors(line) @@ -148,16 +148,16 @@ def get_line_length(line, encoding="UTF-8"): return len(line) -def get_line_width(line, encoding="UTF-8"): +def get_line_width(line, encoding='UTF-8'): """ Get width of string considering double width characters """ - if line.count("{!") != line.count("!}"): - raise BadColorString("Number of {! is not equal to number of !}") + if line.count('{!') != line.count('!}'): + raise BadColorString('Number of {! is not equal to number of !}') if isinstance(line, unicode): - line = line.encode(encoding, "replace") + line = line.encode(encoding, 'replace') # Remove all the color tags line = strip_colors(line) @@ -167,7 +167,7 @@ def get_line_width(line, encoding="UTF-8"): return format_utils.strwidth(line) -def parse_color_string(s, encoding="UTF-8"): +def parse_color_string(s, encoding='UTF-8'): """ Parses a string and returns a list of 2-tuples (color, string). @@ -175,43 +175,43 @@ def parse_color_string(s, encoding="UTF-8"): :param encoding: the encoding to use on output """ - if s.count("{!") != s.count("!}"): - raise BadColorString("Number of {! is not equal to number of !}") + if s.count('{!') != s.count('!}'): + raise BadColorString('Number of {! is not equal to number of !}') if isinstance(s, unicode): - s = s.encode(encoding, "replace") + s = s.encode(encoding, 'replace') ret = [] last_color_attr = None # Keep track of where the strings - while s.find("{!") != -1: - begin = s.find("{!") + while s.find('{!') != -1: + begin = s.find('{!') if begin > 0: - ret.append((curses.color_pair(color_pairs[(schemes["input"][0], schemes["input"][1])]), s[:begin])) + ret.append((curses.color_pair(color_pairs[(schemes['input'][0], schemes['input'][1])]), s[:begin])) - end = s.find("!}") + end = s.find('!}') if end == -1: raise BadColorString("Missing closing '!}'") # Get a list of attributes in the bracketed section - attrs = s[begin + 2:end].split(",") + attrs = s[begin + 2:end].split(',') - if len(attrs) == 1 and not attrs[0].strip(" "): - raise BadColorString("No description in {! !}") + if len(attrs) == 1 and not attrs[0].strip(' '): + raise BadColorString('No description in {! !}') def apply_attrs(cp, attrs): # This function applies any additional attributes as necessary for attr in attrs: - if attr == "ignore": + if attr == 'ignore': continue mode = '+' if attr[0] in ['+', '-']: mode = attr[0] attr = attr[1:] if mode == '+': - cp |= getattr(curses, "A_" + attr.upper()) + cp |= getattr(curses, 'A_' + attr.upper()) else: - cp ^= getattr(curses, "A_" + attr.upper()) + cp ^= getattr(curses, 'A_' + attr.upper()) return cp # Check for a builtin type first @@ -219,26 +219,26 @@ def parse_color_string(s, encoding="UTF-8"): pair = (schemes[attrs[0]][0], schemes[attrs[0]][1]) if pair not in color_pairs: log.debug("Color pair doesn't exist: %s, attrs: %s", pair, attrs) - pair = ("white", "black") + pair = ('white', 'black') # Get the color pair number color_pair = curses.color_pair(color_pairs[pair]) color_pair = apply_attrs(color_pair, schemes[attrs[0]][2:]) last_color_attr = color_pair else: - attrlist = ["blink", "bold", "dim", "reverse", "standout", "underline"] + attrlist = ['blink', 'bold', 'dim', 'reverse', 'standout', 'underline'] if attrs[0][0] in ['+', '-']: # Color is not given, so use last color if last_color_attr is None: - raise BadColorString("No color value given when no previous color was used!: %s" % (attrs[0])) + raise BadColorString('No color value given when no previous color was used!: %s' % (attrs[0])) color_pair = last_color_attr for i, attr in enumerate(attrs): if attr[1:] not in attrlist: - raise BadColorString("Bad attribute value!: %s" % (attr)) + raise BadColorString('Bad attribute value!: %s' % (attr)) else: # This is a custom color scheme fg = attrs[0] - bg = "black" # Default to 'black' if no bg is chosen + bg = 'black' # Default to 'black' if no bg is chosen if len(attrs) > 1: bg = attrs[1] try: @@ -249,23 +249,23 @@ def parse_color_string(s, encoding="UTF-8"): # assume this means selection, and use "white", "black" + reverse # To have white background and black foreground log.debug("Color pair doesn't exist: %s", pair) - if pair[1] == "white": - if attrs[2] == "ignore": - attrs[2] = "reverse" + if pair[1] == 'white': + if attrs[2] == 'ignore': + attrs[2] = 'reverse' else: - attrs.append("reverse") - pair = ("white", "black") + attrs.append('reverse') + pair = ('white', 'black') color_pair = curses.color_pair(color_pairs[pair]) last_color_attr = color_pair attrs = attrs[2:] # Remove colors except KeyError: - raise BadColorString("Bad color value in tag: %s,%s" % (fg, bg)) + raise BadColorString('Bad color value in tag: %s,%s' % (fg, bg)) # Check for additional attributes and OR them to the color_pair color_pair = apply_attrs(color_pair, attrs) last_color_attr = color_pair # We need to find the text now, so lets try to find another {! and if # there isn't one, then it's the rest of the string - next_begin = s.find("{!", end) + next_begin = s.find('{!', end) if next_begin == -1: ret.append((color_pair, replace_tabs(s[end + 2:]))) @@ -286,25 +286,25 @@ class ConsoleColorFormatter(object): """ replace_dict = { - "<torrent-id>": "{!green!}%s{!input!}", - "<torrent>": "{!green!}%s{!input!}", - "<command>": "{!green!}%s{!input!}", - - "<state>": "{!yellow!}%s{!input!}", - "\\.\\.\\.": "{!yellow!}%s{!input!}", - "\\s\\*\\s": "{!blue!}%s{!input!}", - "(?<![\\-a-z])(-[a-zA-Z0-9])": "{!red!}%s{!input!}", + '<torrent-id>': '{!green!}%s{!input!}', + '<torrent>': '{!green!}%s{!input!}', + '<command>': '{!green!}%s{!input!}', + + '<state>': '{!yellow!}%s{!input!}', + '\\.\\.\\.': '{!yellow!}%s{!input!}', + '\\s\\*\\s': '{!blue!}%s{!input!}', + '(?<![\\-a-z])(-[a-zA-Z0-9])': '{!red!}%s{!input!}', # "(\-[a-zA-Z0-9])": "{!red!}%s{!input!}", - "--[_\\-a-zA-Z0-9]+": "{!green!}%s{!input!}", - "(\\[|\\])": "{!info!}%s{!input!}", - - "<tab>": "{!white!}%s{!input!}", - "[_A-Z]{3,}": "{!cyan!}%s{!input!}", - "<key>": "{!cyan!}%s{!input!}", - "<value>": "{!cyan!}%s{!input!}", - "usage:": "{!info!}%s{!input!}", - "<download-folder>": "{!yellow!}%s{!input!}", - "<torrent-file>": "{!green!}%s{!input!}" + '--[_\\-a-zA-Z0-9]+': '{!green!}%s{!input!}', + '(\\[|\\])': '{!info!}%s{!input!}', + + '<tab>': '{!white!}%s{!input!}', + '[_A-Z]{3,}': '{!cyan!}%s{!input!}', + '<key>': '{!cyan!}%s{!input!}', + '<value>': '{!cyan!}%s{!input!}', + 'usage:': '{!info!}%s{!input!}', + '<download-folder>': '{!yellow!}%s{!input!}', + '<torrent-file>': '{!green!}%s{!input!}' } diff --git a/deluge/ui/console/utils/column.py b/deluge/ui/console/utils/column.py index 016d52a69..ab63875bc 100644 --- a/deluge/ui/console/utils/column.py +++ b/deluge/ui/console/utils/column.py @@ -25,68 +25,68 @@ torrent_data_fields = copy.deepcopy(TORRENT_DATA_FIELD) def format_queue(qnum): if qnum < 0: - return "" - return "%d" % (qnum + 1) + return '' + return '%d' % (qnum + 1) formatters = { - "queue": format_queue, - "name": lambda a, b: b, - "state": None, - "tracker": None, - "download_location": None, - "owner": None, - - "progress_state": format_utils.format_progress, - "progress": format_utils.format_progress, - - "size": deluge.common.fsize, - "downloaded": deluge.common.fsize, - "uploaded": deluge.common.fsize, - "remaining": deluge.common.fsize, - - "ratio": format_utils.format_float, - "avail": format_utils.format_float, - "seeds_peers_ratio": format_utils.format_float, - - "download_speed": format_utils.format_speed, - "upload_speed": format_utils.format_speed, - "max_download_speed": format_utils.format_speed, - "max_upload_speed": format_utils.format_speed, - - "peers": format_utils.format_seeds_peers, - "seeds": format_utils.format_seeds_peers, - - "time_added": deluge.common.fdate, - "seeding_time": deluge.common.ftime, - "active_time": deluge.common.ftime, - "finished_time": deluge.common.ftime, - - "last_seen_complete": format_utils.format_date_never, - "completed_time": format_utils.format_date, - "eta": format_utils.format_time, - "pieces": format_utils.format_pieces, + 'queue': format_queue, + 'name': lambda a, b: b, + 'state': None, + 'tracker': None, + 'download_location': None, + 'owner': None, + + 'progress_state': format_utils.format_progress, + 'progress': format_utils.format_progress, + + 'size': deluge.common.fsize, + 'downloaded': deluge.common.fsize, + 'uploaded': deluge.common.fsize, + 'remaining': deluge.common.fsize, + + 'ratio': format_utils.format_float, + 'avail': format_utils.format_float, + 'seeds_peers_ratio': format_utils.format_float, + + 'download_speed': format_utils.format_speed, + 'upload_speed': format_utils.format_speed, + 'max_download_speed': format_utils.format_speed, + 'max_upload_speed': format_utils.format_speed, + + 'peers': format_utils.format_seeds_peers, + 'seeds': format_utils.format_seeds_peers, + + 'time_added': deluge.common.fdate, + 'seeding_time': deluge.common.ftime, + 'active_time': deluge.common.ftime, + 'finished_time': deluge.common.ftime, + + 'last_seen_complete': format_utils.format_date_never, + 'completed_time': format_utils.format_date, + 'eta': format_utils.format_time, + 'pieces': format_utils.format_pieces, } -torrent_data_fields["pieces"] = {"name": _("Pieces"), "status": ["num_pieces", "piece_length"]} -torrent_data_fields["seed_rank"] = {"name": _("Seed Rank"), "status": ["seed_rank"]} +torrent_data_fields['pieces'] = {'name': _('Pieces'), 'status': ['num_pieces', 'piece_length']} +torrent_data_fields['seed_rank'] = {'name': _('Seed Rank'), 'status': ['seed_rank']} for data_field in torrent_data_fields: - torrent_data_fields[data_field]["formatter"] = formatters.get(data_field, str) + torrent_data_fields[data_field]['formatter'] = formatters.get(data_field, str) def get_column_value(name, state): col = torrent_data_fields[name] - if col["formatter"]: - args = [state[key] for key in col["status"]] - return col["formatter"](*args) + if col['formatter']: + args = [state[key] for key in col['status']] + return col['formatter'](*args) else: - return state[col["status"][0]] + return state[col['status'][0]] def get_required_fields(cols): fields = [] for col in cols: - fields.extend(torrent_data_fields[col]["status"]) + fields.extend(torrent_data_fields[col]['status']) return fields diff --git a/deluge/ui/console/utils/format_utils.py b/deluge/ui/console/utils/format_utils.py index 64cdd7abb..64f7d49b8 100644 --- a/deluge/ui/console/utils/format_utils.py +++ b/deluge/ui/console/utils/format_utils.py @@ -19,69 +19,69 @@ def format_speed(speed): if speed > 0: return deluge.common.fspeed(speed) else: - return "-" + return '-' def format_time(time): if time > 0: return deluge.common.ftime(time) else: - return "-" + return '-' def format_date(time): if time > 0: return deluge.common.fdate(time) else: - return "" + return '' def format_date_never(time): if time > 0: return deluge.common.fdate(time) else: - return "Never" + return 'Never' def format_float(x): if x < 0: - return "-" + return '-' else: - return "%.3f" % x + return '%.3f' % x def format_seeds_peers(num, total): - return "%d (%d)" % (num, total) + return '%d (%d)' % (num, total) def format_progress(perc): if perc < 100: - return "%.2f%%" % perc + return '%.2f%%' % perc else: - return "100%" + return '100%' def format_pieces(num, size): - return "%d (%s)" % (num, deluge.common.fsize(size)) + return '%d (%s)' % (num, deluge.common.fsize(size)) def format_priority(prio): if prio == - 2: - return "[Mixed]" + return '[Mixed]' if prio < 0: - return "-" + return '-' pstring = deluge.common.FILE_PRIORITY[prio] if prio > 0: - return pstring[:pstring.index("Priority") - 1] + return pstring[:pstring.index('Priority') - 1] else: return pstring def trim_string(string, w, have_dbls): if w <= 0: - return "" + return '' elif w == 1: - return u" " + return u' ' elif have_dbls: # have to do this the slow way chrs = [] @@ -89,17 +89,17 @@ def trim_string(string, w, have_dbls): idx = 0 while width < w: chrs.append(string[idx]) - if east_asian_width(string[idx]) in ["W", "F"]: + if east_asian_width(string[idx]) in ['W', 'F']: width += 2 else: width += 1 idx += 1 if width != w: chrs.pop() - chrs.append(".") - return u"%s " % ("".join(chrs)) + chrs.append('.') + return u'%s ' % (''.join(chrs)) else: - return u"%s " % (string[0:w - 1]) + return u'%s ' % (string[0:w - 1]) def format_column(col, lim): @@ -109,25 +109,25 @@ def format_column(col, lim): # for unicode strings. if col.__class__ is unicode: # might have some double width chars - col = ud_normalize("NFC", col) - dbls = sum(east_asian_width(c) in "WF" for c in col) + col = ud_normalize('NFC', col) + dbls = sum(east_asian_width(c) in 'WF' for c in col) size = len(col) + dbls if size >= lim - 1: return trim_string(col, lim, dbls > 0) else: - return "%s%s" % (col, " " * (lim - size)) + return '%s%s' % (col, ' ' * (lim - size)) def format_row(row, column_widths): - return "".join([format_column(row[i], column_widths[i]) for i in range(0, len(row))]) + return ''.join([format_column(row[i], column_widths[i]) for i in range(0, len(row))]) -_strip_re = re.compile("\\{!.*?!\\}") +_strip_re = re.compile('\\{!.*?!\\}') -_format_code = re.compile(r"\{\|(.*)\|\}") +_format_code = re.compile(r'\{\|(.*)\|\}') def remove_formatting(string): - return re.sub(_strip_re, "", string) + return re.sub(_strip_re, '', string) def wrap_string(string, width, min_lines=0, strip_colors=True): @@ -141,8 +141,8 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): width of the line. They will still be present in the output. """ ret = [] - s1 = string.split("\n") - indent = "" + s1 = string.split('\n') + indent = '' def insert_clr(s, offset, mtchs, clrs): end_pos = offset + len(s) @@ -150,20 +150,20 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): mtc = mtchs.popleft() - offset clr = clrs.popleft() end_pos += len(clr) - s = "%s%s%s" % (s[:mtc], clr, s[mtc:]) + s = '%s%s%s' % (s[:mtc], clr, s[mtc:]) return s for s in s1: offset = 0 - indent = "" + indent = '' m = _format_code.search(remove_formatting(s)) if m: - if m.group(1).startswith("indent:"): - indent = m.group(1)[len("indent:"):] - elif m.group(1).startswith("indent_pos:"): + if m.group(1).startswith('indent:'): + indent = m.group(1)[len('indent:'):] + elif m.group(1).startswith('indent_pos:'): begin = m.start(0) - indent = " " * begin - s = _format_code.sub("", s) + indent = ' ' * begin + s = _format_code.sub('', s) if strip_colors: mtchs = deque() @@ -171,7 +171,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): for m in _strip_re.finditer(s): mtchs.append(m.start()) clrs.append(m.group()) - cstr = _strip_re.sub("", s) + cstr = _strip_re.sub('', s) else: cstr = s @@ -186,7 +186,7 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): max_width = width - (len(indent) if offset != 0 else 0) if len(cstr) < max_width: break - sidx = cstr.rfind(" ", 0, max_width - 1) + sidx = cstr.rfind(' ', 0, max_width - 1) sidx += 1 if sidx > 0: if strip_colors: @@ -221,15 +221,15 @@ def wrap_string(string, width, min_lines=0, strip_colors=True): if min_lines > 0: for i in range(len(ret), min_lines): - ret.append(" ") + ret.append(' ') # Carry colors over to the next line - last_color_string = "" + last_color_string = '' for i, line in enumerate(ret): if i != 0: - ret[i] = "%s%s" % (last_color_string, ret[i]) + ret[i] = '%s%s' % (last_color_string, ret[i]) - colors = re.findall("\\{![^!]+!\\}", line) + colors = re.findall('\\{![^!]+!\\}', line) if colors: last_color_string = colors[-1] @@ -241,20 +241,20 @@ def strwidth(string): Measure width of a string considering asian double width characters """ if not isinstance(string, unicode): - string = unicode(string, "utf-8") - return sum([1 + (east_asian_width(char) in ["W", "F"]) for char in string]) + string = unicode(string, 'utf-8') + return sum([1 + (east_asian_width(char) in ['W', 'F']) for char in string]) -def pad_string(string, length, character=" ", side="right"): +def pad_string(string, length, character=' ', side='right'): """ Pad string with specified character to desired length, considering double width characters. """ w = strwidth(string) diff = length - w - if side == "left": - return "%s%s" % (character * diff, string) - elif side == "right": - return "%s%s" % (string, character * diff) + if side == 'left': + return '%s%s' % (character * diff, string) + elif side == 'right': + return '%s%s' % (string, character * diff) def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/"): @@ -271,8 +271,8 @@ def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/") if (not seg_start) or (input_cursor == 0): break if deleted and seg_start[-1] in sep_chars: - if seg_start[-1] == " ": - if seg_start[-2] == " " or none_space_deleted is False: + if seg_start[-1] == ' ': + if seg_start[-2] == ' ' or none_space_deleted is False: # Continue as long as: # * next char is also a space # * no none-space characters have been deleted @@ -283,7 +283,7 @@ def delete_alt_backspace(input_text, input_cursor, sep_chars=" *?!._~-#$^;'\"/") break if not none_space_deleted: - none_space_deleted = seg_start[-1] != " " + none_space_deleted = seg_start[-1] != ' ' seg_start = seg_start[:-1] deleted += 1 input_cursor -= 1 diff --git a/deluge/ui/console/widgets/fields.py b/deluge/ui/console/widgets/fields.py index acbf03d90..7e1ca57d9 100644 --- a/deluge/ui/console/widgets/fields.py +++ b/deluge/ui/console/widgets/fields.py @@ -33,16 +33,16 @@ class BaseField(InputKeyHandler): self.name = name self.parent = parent self.fmt_keys = {} - self.set_fmt_key("font", "ignore", kwargs) - self.set_fmt_key("color", "white,black", kwargs) - self.set_fmt_key("color_end", "white,black", kwargs) - self.set_fmt_key("color_active", "black,white", kwargs) - self.set_fmt_key("color_unfocused", "color", kwargs) - self.set_fmt_key("color_unfocused_active", "black,whitegrey", kwargs) - self.set_fmt_key("font_active", "font", kwargs) - self.set_fmt_key("font_unfocused", "font", kwargs) - self.set_fmt_key("font_unfocused_active", "font_active", kwargs) - self.default_col = kwargs.get("col", -1) + self.set_fmt_key('font', 'ignore', kwargs) + self.set_fmt_key('color', 'white,black', kwargs) + self.set_fmt_key('color_end', 'white,black', kwargs) + self.set_fmt_key('color_active', 'black,white', kwargs) + self.set_fmt_key('color_unfocused', 'color', kwargs) + self.set_fmt_key('color_unfocused_active', 'black,whitegrey', kwargs) + self.set_fmt_key('font_active', 'font', kwargs) + self.set_fmt_key('font_unfocused', 'font', kwargs) + self.set_fmt_key('font_unfocused_active', 'font_active', kwargs) + self.default_col = kwargs.get('col', -1) self._selectable = selectable self.value = None @@ -56,19 +56,19 @@ class BaseField(InputKeyHandler): self.fmt_keys[key] = value def get_fmt_keys(self, focused, active, **kwargs): - color_key = kwargs.get("color_key", "color") - font_key = "font" + color_key = kwargs.get('color_key', 'color') + font_key = 'font' if not focused: - color_key += "_unfocused" - font_key += "_unfocused" + color_key += '_unfocused' + font_key += '_unfocused' if active: - color_key += "_active" - font_key += "_active" + color_key += '_active' + font_key += '_active' return color_key, font_key - def build_fmt_string(self, focused, active, value_key="msg", **kwargs): + def build_fmt_string(self, focused, active, value_key='msg', **kwargs): color_key, font_key = self.get_fmt_keys(focused, active, **kwargs) - return "{!%%(%s)s,%%(%s)s!}%%(%s)s{!%%(%s)s!}" % (color_key, font_key, value_key, "color_end") + return '{!%%(%s)s,%%(%s)s!}%%(%s)s{!%%(%s)s!}' % (color_key, font_key, value_key, 'color_end') def depend_skip(self): return False @@ -124,7 +124,7 @@ class InputField(BaseField): def set_depend(self, i, inverse=False): if not isinstance(i, CheckedInput): - raise Exception("Can only depend on CheckedInputs") + raise Exception('Can only depend on CheckedInputs') self.depend = i self.inverse = inverse @@ -140,10 +140,10 @@ class InputField(BaseField): class Header(NoInputField): def __init__(self, parent, header, space_above, space_below, **kwargs): - if "name" not in kwargs: - kwargs["name"] = header + if 'name' not in kwargs: + kwargs['name'] = header NoInputField.__init__(self, parent=parent, **kwargs) - self.header = "{!white,black,bold!}%s" % header + self.header = '{!white,black,bold!}%s' % header self.space_above = space_above self.space_below = space_below @@ -169,7 +169,7 @@ class InfoField(NoInputField): NoInputField.__init__(self, parent=parent, name=name, **kwargs) self.label = label self.value = value - self.txt = "%s %s" % (label, value) + self.txt = '%s %s' % (label, value) @overrides(BaseField) def render(self, screen, row, col=0, **kwargs): @@ -180,27 +180,27 @@ class InfoField(NoInputField): def set_value(self, v): self.value = v if isinstance(v, float): - self.txt = "%s %.2f" % (self.label, self.value) + self.txt = '%s %.2f' % (self.label, self.value) else: - self.txt = "%s %s" % (self.label, self.value) + self.txt = '%s %s' % (self.label, self.value) class CheckedInput(InputField): - def __init__(self, parent, name, message, checked=False, checked_char="X", unchecked_char=" ", - checkbox_format="[%s] ", **kwargs): + def __init__(self, parent, name, message, checked=False, checked_char='X', unchecked_char=' ', + checkbox_format='[%s] ', **kwargs): InputField.__init__(self, parent, name, message, **kwargs) self.set_value(checked) - self.fmt_keys.update({"msg": message, "checkbox_format": checkbox_format, - "unchecked_char": unchecked_char, "checked_char": checked_char}) - self.set_fmt_key("font_checked", "font", kwargs) - self.set_fmt_key("font_unfocused_checked", "font_checked", kwargs) - self.set_fmt_key("font_active_checked", "font_active", kwargs) - self.set_fmt_key("font_unfocused_active_checked", "font_active_checked", kwargs) - self.set_fmt_key("color_checked", "color", kwargs) - self.set_fmt_key("color_active_checked", "color_active", kwargs) - self.set_fmt_key("color_unfocused_checked", "color_checked", kwargs) - self.set_fmt_key("color_unfocused_active_checked", "color_unfocused_active", kwargs) + self.fmt_keys.update({'msg': message, 'checkbox_format': checkbox_format, + 'unchecked_char': unchecked_char, 'checked_char': checked_char}) + self.set_fmt_key('font_checked', 'font', kwargs) + self.set_fmt_key('font_unfocused_checked', 'font_checked', kwargs) + self.set_fmt_key('font_active_checked', 'font_active', kwargs) + self.set_fmt_key('font_unfocused_active_checked', 'font_active_checked', kwargs) + self.set_fmt_key('color_checked', 'color', kwargs) + self.set_fmt_key('color_active_checked', 'color_active', kwargs) + self.set_fmt_key('color_unfocused_checked', 'color_checked', kwargs) + self.set_fmt_key('color_unfocused_active_checked', 'color_unfocused_active', kwargs) @property def checked(self): @@ -210,16 +210,16 @@ class CheckedInput(InputField): def get_fmt_keys(self, focused, active, **kwargs): color_key, font_key = super(CheckedInput, self).get_fmt_keys(focused, active, **kwargs) if self.checked: - color_key += "_checked" - font_key += "_checked" + color_key += '_checked' + font_key += '_checked' return color_key, font_key def build_msg_string(self, focused, active): fmt_str = self.build_fmt_string(focused, active) - char = self.fmt_keys["checked_char" if self.checked else "unchecked_char"] - chk_box = "" + char = self.fmt_keys['checked_char' if self.checked else 'unchecked_char'] + chk_box = '' try: - chk_box = self.fmt_keys["checkbox_format"] % char + chk_box = self.fmt_keys['checkbox_format'] % char except KeyError: pass msg = fmt_str % self.fmt_keys @@ -227,7 +227,7 @@ class CheckedInput(InputField): @overrides(InputField) def render(self, screen, row, col=0, **kwargs): - string = self.build_msg_string(kwargs.get("focused"), kwargs.get("active")) + string = self.build_msg_string(kwargs.get('focused'), kwargs.get('active')) self.parent.add_string(row, string, scr=screen, col=col, pad=False) return 1 @@ -242,9 +242,9 @@ class CheckedInput(InputField): @overrides(InputField) def set_message(self, msg): changed = InputField.set_message(self, msg) - if "msg" in self.fmt_keys and self.fmt_keys["msg"] != msg: + if 'msg' in self.fmt_keys and self.fmt_keys['msg'] != msg: changed = True - self.fmt_keys.update({"msg": msg}) + self.fmt_keys.update({'msg': msg}) return changed @@ -252,7 +252,7 @@ class CheckedInput(InputField): class CheckedPlusInput(CheckedInput): def __init__(self, parent, name, message, child, child_always_visible=False, - show_usage_hints=True, msg_fmt="%s ", **kwargs): + show_usage_hints=True, msg_fmt='%s ', **kwargs): CheckedInput.__init__(self, parent, name, message, **kwargs) self.child = child self.child_active = False @@ -270,7 +270,7 @@ class CheckedPlusInput(CheckedInput): CheckedInput.render(self, screen, row, width=width, active=isact, focused=focused, col=col) rows = 1 if self.show_usage_hints and (self.child_always_visible or (active and self.checked)): - msg = "(esc to leave)" if self.child_active else "(right arrow to edit)" + msg = '(esc to leave)' if self.child_active else '(right arrow to edit)' self.parent.add_string(row + 1, msg, scr=screen, col=col, pad=False) rows += 1 @@ -282,7 +282,7 @@ class CheckedPlusInput(CheckedInput): col=col + msglen, cursor_offset=msglen) rows = max(rows, crows) else: - self.parent.add_string(row, "(enable to view/edit value)", scr=screen, + self.parent.add_string(row, '(enable to view/edit value)', scr=screen, col=col + msglen, pad=False) return rows @@ -310,7 +310,7 @@ class CheckedPlusInput(CheckedInput): class IntSpinInput(InputField): def __init__(self, parent, name, message, move_func, value, min_val=None, max_val=None, - inc_amt=1, incr_large=10, strict_validation=False, fmt="%d", **kwargs): + inc_amt=1, incr_large=10, strict_validation=False, fmt='%d', **kwargs): InputField.__init__(self, parent, name, message, **kwargs) self.convert_func = int self.fmt = fmt @@ -344,16 +344,16 @@ class IntSpinInput(InputField): self.set_value(self.valstr, validate=True, value_on_fail=self.last_valid_value) self.last_active = False - fmt_str = self.build_fmt_string(focused, active, value_key="value") - value_format = "%(msg)s {!input!}" + fmt_str = self.build_fmt_string(focused, active, value_key='value') + value_format = '%(msg)s {!input!}' if not self.valstr: - value_format += "[ ]" + value_format += '[ ]' elif self.format_default and self.valstr == self.default_str: - value_format += "[ {!magenta,black!}%(value)s{!input!} ]" + value_format += '[ {!magenta,black!}%(value)s{!input!} ]' else: - value_format += "[ " + fmt_str + " ]" + value_format += '[ ' + fmt_str + ' ]' - self.parent.add_string(row, value_format % dict({"msg": self.message, "value": "%s" % self.valstr}, + self.parent.add_string(row, value_format % dict({'msg': self.message, 'value': '%s' % self.valstr}, **self.fmt_keys), scr=screen, col=col, pad=False) if active: @@ -409,7 +409,7 @@ class IntSpinInput(InputField): self.set_value(new_val, validate=True, cursor=self.cursor + 1, value_on_fail=self.valstr, on_invalid=self.value) else: - minus_place = self.valstr.find("-") + minus_place = self.valstr.find('-') if self.cursor > minus_place: new_val = self.valstr[:self.cursor] + chr(c) + self.valstr[self.cursor:] self.set_value(new_val, validate=True, cursor=self.cursor + 1, on_invalid=self.value) @@ -447,7 +447,7 @@ class IntSpinInput(InputField): self.cursor = cursor except TypeError: import traceback - log.warn("TypeError: %s", "".join(traceback.format_exc())) + log.warn('TypeError: %s', ''.join(traceback.format_exc())) else: if cursor is True: self.cursor = len(self.valstr) @@ -460,7 +460,7 @@ class FloatSpinInput(IntSpinInput): def __init__(self, parent, message, name, move_func, value, precision=1, **kwargs): self.precision = precision IntSpinInput.__init__(self, parent, message, name, move_func, value, **kwargs) - self.fmt = "%%.%df" % precision + self.fmt = '%%.%df' % precision self.convert_func = lambda valstr: round(float(valstr), self.precision) self.set_value(value) self.cursor = len(self.valstr) @@ -468,10 +468,10 @@ class FloatSpinInput(IntSpinInput): @overrides(IntSpinInput) def handle_read(self, c): if c == ord('.'): - minus_place = self.valstr.find("-") + minus_place = self.valstr.find('-') if self.cursor <= minus_place: return util.ReadState.READ - point_place = self.valstr.find(".") + point_place = self.valstr.find('.') if point_place >= 0: return util.ReadState.READ new_val = self.valstr[:self.cursor] + chr(c) + self.valstr[self.cursor:] @@ -491,27 +491,27 @@ class SelectInput(InputField): self.selected_index = active_index self.default_option = active_index if active_default else None self.require_select_action = require_select_action - self.fmt_keys.update({"font_active": "bold"}) - font_selected = kwargs.get("font_selected", "bold,underline") - - self.set_fmt_key("font_selected", font_selected, kwargs) - self.set_fmt_key("font_active_selected", "font_selected", kwargs) - self.set_fmt_key("font_unfocused_selected", "font_selected", kwargs) - self.set_fmt_key("font_unfocused_active_selected", "font_active_selected", kwargs) - - self.set_fmt_key("color_selected", "color", kwargs) - self.set_fmt_key("color_active_selected", "color_active", kwargs) - self.set_fmt_key("color_unfocused_selected", "color_selected", kwargs) - self.set_fmt_key("color_unfocused_active_selected", "color_unfocused_active", kwargs) - self.set_fmt_key("color_default_value", "magenta,black", kwargs) - - self.set_fmt_key("color_default_value", "magenta,black") - self.set_fmt_key("color_default_value_active", "magentadark,white") - self.set_fmt_key("color_default_value_selected", "color_default_value", kwargs) - self.set_fmt_key("color_default_value_unfocused", "color_default_value", kwargs) - self.set_fmt_key("color_default_value_unfocused_selected", "color_default_value_selected", kwargs) - self.set_fmt_key("color_default_value_active_selected", "magentadark,white") - self.set_fmt_key("color_default_value_unfocused_active_selected", "color_unfocused_active", kwargs) + self.fmt_keys.update({'font_active': 'bold'}) + font_selected = kwargs.get('font_selected', 'bold,underline') + + self.set_fmt_key('font_selected', font_selected, kwargs) + self.set_fmt_key('font_active_selected', 'font_selected', kwargs) + self.set_fmt_key('font_unfocused_selected', 'font_selected', kwargs) + self.set_fmt_key('font_unfocused_active_selected', 'font_active_selected', kwargs) + + self.set_fmt_key('color_selected', 'color', kwargs) + self.set_fmt_key('color_active_selected', 'color_active', kwargs) + self.set_fmt_key('color_unfocused_selected', 'color_selected', kwargs) + self.set_fmt_key('color_unfocused_active_selected', 'color_unfocused_active', kwargs) + self.set_fmt_key('color_default_value', 'magenta,black', kwargs) + + self.set_fmt_key('color_default_value', 'magenta,black') + self.set_fmt_key('color_default_value_active', 'magentadark,white') + self.set_fmt_key('color_default_value_selected', 'color_default_value', kwargs) + self.set_fmt_key('color_default_value_unfocused', 'color_default_value', kwargs) + self.set_fmt_key('color_default_value_unfocused_selected', 'color_default_value_selected', kwargs) + self.set_fmt_key('color_default_value_active_selected', 'magentadark,white') + self.set_fmt_key('color_default_value_unfocused_active_selected', 'color_unfocused_active', kwargs) @property def height(self): @@ -521,8 +521,8 @@ class SelectInput(InputField): def get_fmt_keys(self, focused, active, selected=False, **kwargs): color_key, font_key = super(SelectInput, self).get_fmt_keys(focused, active, **kwargs) if selected: - color_key += "_selected" - font_key += "_selected" + color_key += '_selected' + font_key += '_selected' return color_key, font_key @overrides(InputField) @@ -533,12 +533,12 @@ class SelectInput(InputField): off = col + 1 for i, opt in enumerate(self.opts): - self.fmt_keys["msg"] = opt - fmt_args = {"selected": i == self.selected_index} + self.fmt_keys['msg'] = opt + fmt_args = {'selected': i == self.selected_index} if i == self.default_option: - fmt_args["color_key"] = "color_default_value" + fmt_args['color_key'] = 'color_default_value' fmt = self.build_fmt_string(focused, (i == self.active_index) and active, **fmt_args) - string = "[%s]" % (fmt % self.fmt_keys) + string = '[%s]' % (fmt % self.fmt_keys) self.parent.add_string(row, string, scr=screen, col=off, pad=False) off += len(opt) + 3 if self.message: @@ -573,7 +573,7 @@ class SelectInput(InputField): if value == val: self.selected_index = i return - raise Exception("Invalid value for SelectInput") + raise Exception('Invalid value for SelectInput') class TextInput(InputField): @@ -665,11 +665,11 @@ class TextInput(InputField): x_pos = self.calculate_cursor_pos(width, col) self.move_func(row, x_pos) - fmt = "{!black,white,bold!}%s" + fmt = '{!black,white,bold!}%s' if self.format_default and len(self.value) != 0 and self.value == self.default_value: - fmt = "{!magenta,white!}%s" + fmt = '{!magenta,white!}%s' if not active or not focused or self.input_active: - fmt = "{!white,grey,bold!}%s" + fmt = '{!white,grey,bold!}%s' self.parent.add_string(row, fmt % vstr, scr=screen, col=col, pad=False, trim=False) return self.height @@ -709,13 +709,13 @@ class TextInput(InputField): # We only call the tab completer function if we're at the end of # the input string on the cursor is on a space - if self.cursor == len(self.value) or self.value[self.cursor] == " ": + if self.cursor == len(self.value) or self.value[self.cursor] == ' ': if self.opts: prev = self.opt_off self.opt_off += self.width - 3 # now find previous double space, best guess at a split point # in future could keep opts unjoined to get this really right - self.opt_off = self.opts.rfind(" ", 0, self.opt_off) + 2 + self.opt_off = self.opts.rfind(' ', 0, self.opt_off) + 2 if second_hit and self.opt_off == prev: # double tap and we're at the end self.opt_off = 0 else: @@ -732,7 +732,7 @@ class TextInput(InputField): if len(opts) > 1 and second_hit: # display multiple options on second tab hit sp = self.value.rfind(os.sep) + 1 - self.opts = " ".join([o[sp:] for o in opts]) + self.opts = ' '.join([o[sp:] for o in opts]) # Cursor movement elif c == curses.KEY_LEFT: @@ -757,7 +757,7 @@ class TextInput(InputField): elif c > 31 and c < 256: # Emulate getwch stroke = chr(c) - uchar = "" + uchar = '' while not uchar: try: uchar = stroke.decode(self.parent.encoding) @@ -789,7 +789,7 @@ class TextInput(InputField): # Directory, so we need to show contents of directory for f in os.listdir(line): # Skip hidden - if f.startswith("."): + if f.startswith('.'): continue f = os.path.join(line, f) if os.path.isdir(f): @@ -831,8 +831,8 @@ class ComboInput(InputField): @overrides(BaseField) def render(self, screen, row, col=0, **kwargs): - fmt_str = self.build_fmt_string(kwargs.get("focused"), kwargs.get("active")) - string = "%s: [%10s]" % (self.message, fmt_str % self.fmt_keys) + fmt_str = self.build_fmt_string(kwargs.get('focused'), kwargs.get('active')) + string = '%s: [%10s]' % (self.message, fmt_str % self.fmt_keys) self.parent.add_string(row, string, scr=screen, col=col, pad=False) return 1 @@ -865,11 +865,11 @@ class ComboInput(InputField): select_in_range(0, selected) from deluge.ui.console.widgets.popup import SelectablePopup # Must import here - select_popup = SelectablePopup(self.parent, " %s " % _("Select Language"), self._lang_selected, + select_popup = SelectablePopup(self.parent, ' %s ' % _('Select Language'), self._lang_selected, input_cb=search_handler if self.searchable else None, border_off_west=1, active_wrap=False, width_req=self.choices_width + 12) for choice in self.choices: - args = {"data": choice[0]} + args = {'data': choice[0]} select_popup.add_line(choice[0], choice[1], selectable=True, selected=choice[0] == self.get_value(), **args) self.parent.push_popup(select_popup) @@ -886,12 +886,12 @@ class ComboInput(InputField): break if msg is None: log.warn("Setting a value '%s' found found in choices: %s", val, self.choices) - self.fmt_keys.update({"msg": msg}) + self.fmt_keys.update({'msg': msg}) class TextField(BaseField): - def __init__(self, parent, name, value, selectable=True, value_fmt="%s", **kwargs): + def __init__(self, parent, name, value, selectable=True, value_fmt='%s', **kwargs): BaseField.__init__(self, parent=parent, name=name, selectable=selectable, **kwargs) self.value = value self.value_fmt = value_fmt @@ -910,7 +910,7 @@ class TextField(BaseField): def render(self, screen, row, active=False, focused=False, col=0, **kwargs): util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active fmt = self.build_fmt_string(focused, active) - self.fmt_keys["msg"] = self.txt + self.fmt_keys['msg'] = self.txt string = fmt % self.fmt_keys self.parent.add_string(row, string, scr=screen, col=col, pad=False, trim=False) return 1 @@ -918,17 +918,17 @@ class TextField(BaseField): class TextArea(TextField): - def __init__(self, parent, name, value, value_fmt="%s", **kwargs): + def __init__(self, parent, name, value, value_fmt='%s', **kwargs): TextField.__init__(self, parent, name, value, selectable=False, value_fmt=value_fmt, **kwargs) @overrides(TextField) def render(self, screen, row, col=0, **kwargs): util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active - color = "{!white,black!}" + color = '{!white,black!}' lines = wrap_string(self.txt, self.parent.width - 3, 3, True) for i, line in enumerate(lines): - self.parent.add_string(row + i, "%s%s" % (color, line), scr=screen, col=col, pad=False, trim=False) + self.parent.add_string(row + i, '%s%s' % (color, line), scr=screen, col=col, pad=False, trim=False) return len(lines) @property @@ -943,7 +943,7 @@ class TextArea(TextField): class DividerField(NoInputField): - def __init__(self, parent, name, value, selectable=False, fill_width=True, value_fmt="%s", **kwargs): + def __init__(self, parent, name, value, selectable=False, fill_width=True, value_fmt='%s', **kwargs): NoInputField.__init__(self, parent=parent, name=name, selectable=selectable, **kwargs) self.value = value self.value_fmt = value_fmt @@ -959,12 +959,12 @@ class DividerField(NoInputField): def render(self, screen, row, active=False, focused=False, col=0, width=None, **kwargs): util.safe_curs_set(util.Curser.INVISIBLE) # Make cursor invisible when text field is active fmt = self.build_fmt_string(focused, active) - self.fmt_keys["msg"] = self.txt + self.fmt_keys['msg'] = self.txt if self.fill_width: - self.fmt_keys["msg"] = "" + self.fmt_keys['msg'] = '' string_len = len(remove_formatting(fmt % self.fmt_keys)) fill_len = width - string_len - (len(self.txt) - 1) - self.fmt_keys["msg"] = self.txt * fill_len + self.fmt_keys['msg'] = self.txt * fill_len string = fmt % self.fmt_keys self.parent.add_string(row, string, scr=screen, col=col, pad=False, trim=False) return 1 diff --git a/deluge/ui/console/widgets/inputpane.py b/deluge/ui/console/widgets/inputpane.py index ce1b92383..c8eab01a9 100644 --- a/deluge/ui/console/widgets/inputpane.py +++ b/deluge/ui/console/widgets/inputpane.py @@ -47,24 +47,24 @@ class BaseInputPane(InputKeyHandler): self.border_off_south = border_off_south self.last_lineoff_move = 0 - if not hasattr(self, "visible_content_pane_height"): + if not hasattr(self, 'visible_content_pane_height'): log.error("The class '%s' does not have the attribute '%s' required by super class '%s'", - self.__class__.__name__, "visible_content_pane_height", BaseInputPane.__name__) - raise AttributeError("visible_content_pane_height") + self.__class__.__name__, 'visible_content_pane_height', BaseInputPane.__name__) + raise AttributeError('visible_content_pane_height') @property def visible_content_pane_width(self): return self.mode.width def add_spaces(self, num): - string = "" + string = '' for i in range(num): - string += "\n" + string += '\n' - self.add_text_area("space %d" % len(self.inputs), string) + self.add_text_area('space %d' % len(self.inputs), string) def add_text(self, string): - self.add_text_area("", string) + self.add_text_area('', string) def move(self, r, c): self._cursor_row = r @@ -82,7 +82,7 @@ class BaseInputPane(InputKeyHandler): if e.name == input_element.name: import traceback log.warn("Input element with name '%s' already exists in input pane (%s):\n%s", - input_element.name, e, "".join(traceback.format_stack(limit=5))) + input_element.name, e, ''.join(traceback.format_stack(limit=5))) return self.inputs.append(input_element) @@ -97,7 +97,7 @@ class BaseInputPane(InputKeyHandler): def add_info_field(self, name, label, value): return self._add_input(InfoField(self, name, label, value)) - def add_text_field(self, name, message, selectable=True, col="+1", **kwargs): + def add_text_field(self, name, message, selectable=True, col='+1', **kwargs): return self._add_input(TextField(self, name, message, selectable=selectable, col=col, **kwargs)) def add_text_area(self, name, message, **kwargs): @@ -106,7 +106,7 @@ class BaseInputPane(InputKeyHandler): def add_divider_field(self, name, message, **kwargs): return self._add_input(DividerField(self, name, message, **kwargs)) - def add_text_input(self, name, message, value="", col="+1", **kwargs): + def add_text_input(self, name, message, value='', col='+1', **kwargs): """ Add a text input field @@ -121,19 +121,19 @@ class BaseInputPane(InputKeyHandler): def add_select_input(self, name, message, opts, vals, default_index=0, **kwargs): return self._add_input(SelectInput(self, name, message, opts, vals, default_index, **kwargs)) - def add_checked_input(self, name, message, checked=False, col="+1", **kwargs): + def add_checked_input(self, name, message, checked=False, col='+1', **kwargs): return self._add_input(CheckedInput(self, name, message, checked=checked, col=col, **kwargs)) - def add_checkedplus_input(self, name, message, child, checked=False, col="+1", **kwargs): + def add_checkedplus_input(self, name, message, child, checked=False, col='+1', **kwargs): return self._add_input(CheckedPlusInput(self, name, message, child, checked=checked, col=col, **kwargs)) - def add_float_spin_input(self, name, message, value=0.0, col="+1", **kwargs): + def add_float_spin_input(self, name, message, value=0.0, col='+1', **kwargs): return self._add_input(FloatSpinInput(self, name, message, self.move, value, col=col, **kwargs)) - def add_int_spin_input(self, name, message, value=0, col="+1", **kwargs): + def add_int_spin_input(self, name, message, value=0, col='+1', **kwargs): return self._add_input(IntSpinInput(self, name, message, self.move, value, col=col, **kwargs)) - def add_combo_input(self, name, message, choices, col="+1", **kwargs): + def add_combo_input(self, name, message, choices, col='+1', **kwargs): return self._add_input(ComboInput(self, name, message, choices, col=col, **kwargs)) @overrides(InputKeyHandler) @@ -190,7 +190,7 @@ class BaseInputPane(InputKeyHandler): for i, ipt in enumerate(self.inputs): if not ipt.has_input(): continue - vals[ipt.name] = {"value": ipt.get_value(), "order": i, "active": self.active_input == i} + vals[ipt.name] = {'value': ipt.get_value(), 'order': i, 'active': self.active_input == i} return vals def immediate_action_cb(self, state_changed=True): diff --git a/deluge/ui/console/widgets/popup.py b/deluge/ui/console/widgets/popup.py index e5df2a878..4f3a12f63 100644 --- a/deluge/ui/console/widgets/popup.py +++ b/deluge/ui/console/widgets/popup.py @@ -174,7 +174,7 @@ class Popup(BaseWindow, InputKeyHandler): def close(self, *args, **kwargs): self._closed = True - if kwargs.get("call_cb", True): + if kwargs.get('call_cb', True): self._call_close_cb(*args) self.panel.hide() @@ -209,15 +209,15 @@ class SelectablePopup(BaseInputPane, Popup): """ Popup.__init__(self, parent_mode, title, close_cb=close_cb, **kwargs) - kwargs.update({"allow_rearrange": allow_rearrange, "immediate_action": immediate_action}) + kwargs.update({'allow_rearrange': allow_rearrange, 'immediate_action': immediate_action}) BaseInputPane.__init__(self, self, **kwargs) self.selection_cb = selection_cb self.input_cb = input_cb self.hotkeys = {} self.cb_arg = {} - self.cb_args = kwargs.get("cb_args", {}) - if "base_popup" not in self.cb_args: - self.cb_args["base_popup"] = self + self.cb_args = kwargs.get('cb_args', {}) + if 'base_popup' not in self.cb_args: + self.cb_args['base_popup'] = self @property @overrides(BaseWindow) @@ -226,7 +226,7 @@ class SelectablePopup(BaseInputPane, Popup): return Popup.visible_content_pane_height.fget(self) def current_selection(self): - "Returns a tuple of (selected index, selected data)" + 'Returns a tuple of (selected index, selected data)' return self.active_input def set_selection(self, index): @@ -238,15 +238,15 @@ class SelectablePopup(BaseInputPane, Popup): hotkey = None self.cb_arg[name] = cb_arg if use_underline: - udx = string.find("_") + udx = string.find('_') if udx >= 0: hotkey = string[udx].lower() - string = string[:udx] + "{!+underline!}" + string[udx + 1] + "{!-underline!}" + string[udx + 2:] + string = string[:udx] + '{!+underline!}' + string[udx + 1] + '{!-underline!}' + string[udx + 2:] - kwargs["selectable"] = selectable + kwargs['selectable'] = selectable if foreground: - kwargs["color_active"] = "%s,white" % foreground - kwargs["color"] = "%s,black" % foreground + kwargs['color_active'] = '%s,white' % foreground + kwargs['color'] = '%s,black' % foreground field = self.add_text_field(name, string, **kwargs) if hotkey: @@ -259,7 +259,7 @@ class SelectablePopup(BaseInputPane, Popup): def handle_read(self, c): if c in [curses.KEY_ENTER, util.KEY_ENTER2]: for k, v in self.get_values().iteritems(): - if v["active"]: + if v['active']: if self.selection_cb(k, **dict(self.cb_args, data=self.cb_arg)): self.close(None) return util.ReadState.READ @@ -279,12 +279,12 @@ class SelectablePopup(BaseInputPane, Popup): self.refresh() return util.ReadState.IGNORED - def add_divider(self, message=None, char="-", fill_width=True, color="white"): + def add_divider(self, message=None, char='-', fill_width=True, color='white'): if message is not None: fill_width = False else: message = char - self.add_divider_field("", message, selectable=False, fill_width=fill_width) + self.add_divider_field('', message, selectable=False, fill_width=fill_width) class MessagePopup(Popup, BaseInputPane): @@ -304,7 +304,7 @@ class MessagePopup(Popup, BaseInputPane): self.handle_resize() self.no_refresh = False - self.add_text_area("TextMessage", message) + self.add_text_area('TextMessage', message) @overrides(Popup, BaseInputPane) def handle_read(self, c): diff --git a/deluge/ui/console/widgets/statusbars.py b/deluge/ui/console/widgets/statusbars.py index 5a002823d..5c43fb1d6 100644 --- a/deluge/ui/console/widgets/statusbars.py +++ b/deluge/ui/console/widgets/statusbars.py @@ -15,101 +15,101 @@ from deluge.ui.client import client class StatusBars(component.Component): def __init__(self): - component.Component.__init__(self, "StatusBars", 2, depend=["CoreConfig"]) - self.config = component.get("CoreConfig") + component.Component.__init__(self, 'StatusBars', 2, depend=['CoreConfig']) + self.config = component.get('CoreConfig') # Hold some values we get from the core self.connections = 0 - self.download = "" - self.upload = "" + self.download = '' + self.upload = '' self.dht = 0 - self.external_ip = "" + self.external_ip = '' # Default values - self.topbar = "{!status!}Deluge %s Console - " % deluge.common.get_version() - self.bottombar = "{!status!}C: %s" % self.connections + self.topbar = '{!status!}Deluge %s Console - ' % deluge.common.get_version() + self.bottombar = '{!status!}C: %s' % self.connections def start(self): self.update() def update(self): def on_get_session_status(status): - self.upload = deluge.common.fsize(status["payload_upload_rate"]) - self.download = deluge.common.fsize(status["payload_download_rate"]) - self.connections = status["num_peers"] - if "dht_nodes" in status: - self.dht = status["dht_nodes"] + self.upload = deluge.common.fsize(status['payload_upload_rate']) + self.download = deluge.common.fsize(status['payload_download_rate']) + self.connections = status['num_peers'] + if 'dht_nodes' in status: + self.dht = status['dht_nodes'] self.update_statusbars() def on_get_external_ip(external_ip): self.external_ip = external_ip - keys = ["num_peers", "payload_upload_rate", "payload_download_rate"] + keys = ['num_peers', 'payload_upload_rate', 'payload_download_rate'] - if self.config["dht"]: - keys.append("dht_nodes") + if self.config['dht']: + keys.append('dht_nodes') client.core.get_session_status(keys).addCallback(on_get_session_status) client.core.get_external_ip().addCallback(on_get_external_ip) def update_statusbars(self): # Update the topbar string - self.topbar = "{!status!}Deluge %s Console - " % deluge.common.get_version() + self.topbar = '{!status!}Deluge %s Console - ' % deluge.common.get_version() if client.connected(): info = client.connection_info() - connection_info = "" + connection_info = '' # Client name - if info[2] == "localclient": - connection_info += "{!white,blue!}%s" + if info[2] == 'localclient': + connection_info += '{!white,blue!}%s' else: - connection_info += "{!green,blue,bold!}%s" + connection_info += '{!green,blue,bold!}%s' # Hostname - if info[0] == "127.0.0.1": - connection_info += "{!white,blue,bold!}@{!white,blue!}%s" + if info[0] == '127.0.0.1': + connection_info += '{!white,blue,bold!}@{!white,blue!}%s' else: - connection_info += "{!white,blue,bold!}@{!red,blue,bold!}%s" + connection_info += '{!white,blue,bold!}@{!red,blue,bold!}%s' # Port - if info[1] == DEFAULT_PREFS["daemon_port"]: - connection_info += "{!white,blue!}:%s" + if info[1] == DEFAULT_PREFS['daemon_port']: + connection_info += '{!white,blue!}:%s' else: - connection_info += "{!status!}:%s" + connection_info += '{!status!}:%s' # Change color back to normal, just in case - connection_info += "{!status!}" + connection_info += '{!status!}' self.topbar += connection_info % (info[2], info[0], info[1]) else: - self.topbar += "Not Connected" + self.topbar += 'Not Connected' # Update the bottombar string - self.bottombar = "{!status!}C: {!white,blue!}%s{!status!}" % self.connections + self.bottombar = '{!status!}C: {!white,blue!}%s{!status!}' % self.connections - if self.config["max_connections_global"] > -1: - self.bottombar += " (%s)" % self.config["max_connections_global"] + if self.config['max_connections_global'] > -1: + self.bottombar += ' (%s)' % self.config['max_connections_global'] - if self.download != "0.0 KiB": - self.bottombar += " D: {!magenta,blue,bold!}%s{!status!}" % self.download + if self.download != '0.0 KiB': + self.bottombar += ' D: {!magenta,blue,bold!}%s{!status!}' % self.download else: - self.bottombar += " D: {!white,blue!}%s{!status!}" % self.download + self.bottombar += ' D: {!white,blue!}%s{!status!}' % self.download - if self.config["max_download_speed"] > -1: - self.bottombar += " (%s " % self.config["max_download_speed"] + _("KiB/s") + ")" + if self.config['max_download_speed'] > -1: + self.bottombar += ' (%s ' % self.config['max_download_speed'] + _('KiB/s') + ')' - if self.upload != "0.0 KiB": - self.bottombar += " U: {!green,blue,bold!}%s{!status!}" % self.upload + if self.upload != '0.0 KiB': + self.bottombar += ' U: {!green,blue,bold!}%s{!status!}' % self.upload else: - self.bottombar += " U: {!white,blue!}%s{!status!}" % self.upload + self.bottombar += ' U: {!white,blue!}%s{!status!}' % self.upload - if self.config["max_upload_speed"] > -1: - self.bottombar += " (%s " % self.config["max_upload_speed"] + _("KiB/s") + ")" + if self.config['max_upload_speed'] > -1: + self.bottombar += ' (%s ' % self.config['max_upload_speed'] + _('KiB/s') + ')' - if self.config["dht"]: - self.bottombar += " " + _("DHT") + ": {!white,blue!}%s{!status!}" % self.dht + if self.config['dht']: + self.bottombar += ' ' + _('DHT') + ': {!white,blue!}%s{!status!}' % self.dht - self.bottombar += " " + _("IP {!white,blue!}%s{!status!}") % ( - self.external_ip if self.external_ip else _("n/a")) + self.bottombar += ' ' + _('IP {!white,blue!}%s{!status!}') % ( + self.external_ip if self.external_ip else _('n/a')) diff --git a/deluge/ui/console/widgets/window.py b/deluge/ui/console/widgets/window.py index 1c83c1b25..a82107c66 100644 --- a/deluge/ui/console/widgets/window.py +++ b/deluge/ui/console/widgets/window.py @@ -40,14 +40,14 @@ class BaseWindow(object): self.posy, self.posx = posy, posx if encoding is None: from deluge import component - encoding = component.get("ConsoleUI").encoding + encoding = component.get('ConsoleUI').encoding self.encoding = encoding self.panel = mkpanel(curses.COLOR_GREEN, height, width, posy, posx) self.outer_screen = self.panel.window() self.outer_screen.bkgdset(0, curses.COLOR_RED) by, bx = self.outer_screen.getbegyx() - self.screen = mkpad(get_color_pair("white", "black"), height - 1, width - 2) + self.screen = mkpad(get_color_pair('white', 'black'), height - 1, width - 2) self._height, self._width = self.outer_screen.getmaxyx() @property @@ -120,7 +120,7 @@ class BaseWindow(object): indicator_row = min(indicator_row, self.visible_content_pane_height) indicator_col = self.width + 1 - add_string(indicator_row, "{!red,black,bold!}#", screen, self.encoding, + add_string(indicator_row, '{!red,black,bold!}#', screen, self.encoding, col=indicator_col, pad=False, trim=False) def refresh(self): @@ -130,7 +130,7 @@ class BaseWindow(object): if self.title: toff = max(1, (self.width // 2) - (len(self.title) // 2)) - self.add_string(0, "{!white,black,bold!}%s" % self.title, scr=self.outer_screen, col=toff, pad=False) + self.add_string(0, '{!white,black,bold!}%s' % self.title, scr=self.outer_screen, col=toff, pad=False) self.draw_scroll_indicator(self.outer_screen) self.outer_screen.noutrefresh() @@ -149,4 +149,4 @@ class BaseWindow(object): except curses.error as ex: import traceback log.warn("Error on screen.noutrefresh(%s, %s, %s, %s, %s, %s) Error: '%s'\nStack: %s", - pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, "".join(traceback.format_stack())) + pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol, ex, ''.join(traceback.format_stack())) diff --git a/deluge/ui/coreconfig.py b/deluge/ui/coreconfig.py index 887e37e50..2014bb869 100644 --- a/deluge/ui/coreconfig.py +++ b/deluge/ui/coreconfig.py @@ -17,13 +17,13 @@ log = logging.getLogger(__name__) class CoreConfig(component.Component): def __init__(self): - log.debug("CoreConfig init..") - component.Component.__init__(self, "CoreConfig") + log.debug('CoreConfig init..') + component.Component.__init__(self, 'CoreConfig') self.config = {} def on_configvaluechanged_event(key, value): self.config[key] = value - client.register_event_handler("ConfigValueChangedEvent", on_configvaluechanged_event) + client.register_event_handler('ConfigValueChangedEvent', on_configvaluechanged_event) def start(self): def on_get_config(config): diff --git a/deluge/ui/gtkui/__init__.py b/deluge/ui/gtkui/__init__.py index 5836b7ecd..4f64705ee 100644 --- a/deluge/ui/gtkui/__init__.py +++ b/deluge/ui/gtkui/__init__.py @@ -20,12 +20,12 @@ class Gtk(UI): cmd_description = """GTK-based graphical user interface""" def __init__(self, *args, **kwargs): - super(Gtk, self).__init__("gtk", *args, description="Starts the Deluge GTK+ interface", **kwargs) + super(Gtk, self).__init__('gtk', *args, description='Starts the Deluge GTK+ interface', **kwargs) - group = self.parser.add_argument_group(_("GTK Options")) - group.add_argument("torrents", metavar="<torrent>", nargs="*", default=None, - help=_("Add one or more torrent files, torrent URLs or magnet URIs" - " to a currently running Deluge GTK instance")) + group = self.parser.add_argument_group(_('GTK Options')) + group.add_argument('torrents', metavar='<torrent>', nargs='*', default=None, + help=_('Add one or more torrent files, torrent URLs or magnet URIs' + ' to a currently running Deluge GTK instance')) def start(self): super(Gtk, self).start() diff --git a/deluge/ui/gtkui/aboutdialog.py b/deluge/ui/gtkui/aboutdialog.py index 037411423..3ddf489ab 100644 --- a/deluge/ui/gtkui/aboutdialog.py +++ b/deluge/ui/gtkui/aboutdialog.py @@ -24,251 +24,251 @@ class AboutDialog(object): gtk.about_dialog_set_url_hook(url_hook) self.about = gtk.AboutDialog() self.about.set_position(gtk.WIN_POS_CENTER) - self.about.set_name("Deluge") - self.about.set_program_name(_("Deluge")) + self.about.set_name('Deluge') + self.about.set_program_name(_('Deluge')) version = get_version() self.about.set_copyright( - _("Copyright %(year_start)s-%(year_end)s Deluge Team") % {"year_start": 2007, "year_end": 2015}) + _('Copyright %(year_start)s-%(year_end)s Deluge Team') % {'year_start': 2007, 'year_end': 2015}) self.about.set_comments( - _("A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.") + - "\n\n" + _("Client:") + " %s\n" % version) + _('A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.') + + '\n\n' + _('Client:') + ' %s\n' % version) self.about.set_version(version) self.about.set_authors([ - _("Current Developers:"), "Andrew Resch", "Damien Churchill", - "John Garland", "Calum Lind", "", "libtorrent (libtorrent.org):", - "Arvid Norberg", "", _("Past Developers or Contributors:"), - "Zach Tibbitts", "Alon Zakai", "Marcos Mobley", "Alex Dedul", - "Sadrul Habib Chowdhury", "Ido Abramovich", "Martijn Voncken" + _('Current Developers:'), 'Andrew Resch', 'Damien Churchill', + 'John Garland', 'Calum Lind', '', 'libtorrent (libtorrent.org):', + 'Arvid Norberg', '', _('Past Developers or Contributors:'), + 'Zach Tibbitts', 'Alon Zakai', 'Marcos Mobley', 'Alex Dedul', + 'Sadrul Habib Chowdhury', 'Ido Abramovich', 'Martijn Voncken' ]) - self.about.set_artists(["Andrew Wedderburn", "Andrew Resch"]) - self.about.set_translator_credits("\n".join([ - "Aaron Wang Shi", "abbigss", "ABCdatos", "Abcx", "Actam", "Adam", - "adaminikisi", "adi_oporanu", "Adrian Goll", "afby", "Ahmades", - "Ahmad Farghal", "Ahmad Gharbeia أحمد غربية", "akira", "Aki Sivula", - "Alan Pepelko", "Alberto", "Alberto Ferrer", "alcatr4z", "AlckO", - "Aleksej Korgenkov", "Alessio Treglia", "Alexander Ilyashov", - "Alexander Matveev", "Alexander Saltykov", "Alexander Taubenkorb", - "Alexander Telenga", "Alexander Yurtsev", "Alexandre Martani", - "Alexandre Rosenfeld", "Alexandre Sapata Carbonell", - "Alexey Osipov", "Alin Claudiu Radut", "allah", "AlSim", - "Alvaro Carrillanca P.", "A.Matveev", "Andras Hipsag", - "András Kárász", "Andrea Ratto", "Andreas Johansson", "Andreas Str", - "André F. Oliveira", "AndreiF", "andrewh", "Angel Guzman Maeso", - "Aníbal Deboni Neto", "animarval", "Antonio Cono", "antoniojreyes", - "Anton Shestakov", "Anton Yakutovich", "antou", - "Arkadiusz Kalinowski", "Artin", "artir", "Astur", - "Athanasios Lefteris", "Athmane MOKRAOUI (ButterflyOfFire)", - "Augusta Carla Klug", "Avoledo Marco", "axaard", "AxelRafn", - "Axezium", "Ayont", "b3rx", "Bae Taegil", "Bajusz Tamás", - "Balaam's Miracle", "Ballestein", "Bent Ole Fosse", "berto89", - "bigx", "Bjorn Inge Berg", "blackbird", "Blackeyed", "blackmx", - "BlueSky", "Blutheo", "bmhm", "bob00work", "boenki", - "Bogdan Bădic-Spătariu", "bonpu", "Boone", "boss01", - "Branislav Jovanović", "bronze", "brownie", "Brus46", "bumper", - "butely", "BXCracer", "c0nfidencal", "Can Kaya", - "Carlos Alexandro Becker", "cassianoleal", "Cédric.h", - "César Rubén", "chaoswizard", "Chen Tao", "chicha", - "Chien Cheng Wei", "Christian Kopac", "Christian Widell", - "Christoffer Brodd-Reijer", "christooss", "CityAceE", "Clopy", - "Clusty", "cnu", "Commandant", "Constantinos Koniaris", "Coolmax", - "cosmix", "Costin Chirvasuta", "CoVaLiDiTy", "cow_2001", - "Crispin Kirchner", "crom", "Cruster", "Cybolic", "Dan Bishop", - "Danek", "Dani", "Daniel Demarco", "Daniel Ferreira", - "Daniel Frank", "Daniel Holm", "Daniel Høyer Iversen", - "Daniel Marynicz", "Daniel Nylander", "Daniel Patriche", - "Daniel Schildt", "Daniil Sorokin", "Dante Díaz", "Daria Michalska", - "DarkenCZ", "Darren", "Daspah", "David Eurenius", "davidhjelm", - "David Machakhelidze", "Dawid Dziurdzia", "Daya Adianto ", "dcruz", - "Deady", "Dereck Wonnacott", "Devgru", "Devid Antonio Filoni" - "DevilDogTG", "di0rz`", "Dialecti Valsamou", "Diego Medeiros", - "Dkzoffy", "Dmitrij D. Czarkoff", "Dmitriy Geels", - "Dmitry Olyenyov", "Dominik Kozaczko", "Dominik Lübben", "doomster", - "Dorota Król", "Doyen Philippe", "Dread Knight", "DreamSonic", - "duan", "Duong Thanh An", "DvoglavaZver", "dwori", "dylansmrjones", - "Ebuntor", "Edgar Alejandro Jarquin Flores", "Eetu", "ekerazha", - "Elias Julkunen", "elparia", "Emberke", "Emiliano Goday Caneda", - "EndelWar", "eng.essam", "enubuntu", "ercangun", "Erdal Ronahi", - "ergin üresin", "Eric", "Éric Lassauge", "Erlend Finvåg", "Errdil", - "ethan shalev", "Evgeni Spasov", "ezekielnin", "Fabian Ordelmans", - "Fabio Mazanatti", "Fábio Nogueira", "FaCuZ", "Felipe Lerena", - "Fernando Pereira", "fjetland", "Florian Schäfer", "FoBoS", "Folke", - "Force", "fosk", "fragarray", "freddeg", "Frédéric Perrin", - "Fredrik Kilegran", "FreeAtMind", "Fulvio Ciucci", "Gabor Kelemen", - "Galatsanos Panagiotis", "Gaussian", "gdevitis", "Georg Brzyk", - "George Dumitrescu", "Georgi Arabadjiev", "Georg Sieber", - "Gerd Radecke", "Germán Heusdens", "Gianni Vialetto", - "Gigih Aji Ibrahim", "Giorgio Wicklein", "Giovanni Rapagnani", - "Giuseppe", "gl", "glen", "granjerox", "Green Fish", "greentea", - "Greyhound", "G. U.", "Guillaume BENOIT", "Guillaume Pelletier", - "Gustavo Henrique Klug", "gutocarvalho", "Guybrush88", - "Hans Rødtang", "HardDisk", "Hargas Gábor", - "Heitor Thury Barreiros Barbosa", "helios91940", "helix84", - "Helton Rodrigues", "Hendrik Luup", "Henrique Ferreiro", - "Henry Goury-Laffont", "Hezy Amiel", "hidro", "hoball", "hokten", - "Holmsss", "hristo.num", "Hubert Życiński", "Hyo", "Iarwain", "ibe", - "ibear", "Id2ndR", "Igor Zubarev", "IKON (Ion)", "imen", - "Ionuț Jula", "Isabelle STEVANT", "István Nyitrai", "Ivan Petrovic", - "Ivan Prignano", "IvaSerge", "jackmc", "Jacks0nxD", "Jack Shen", - "Jacky Yeung", "Jacques Stadler", "Janek Thomaschewski", "Jan Kaláb", - "Jan Niklas Hasse", "Jasper Groenewegen", "Javi Rodríguez", - "Jayasimha (ಜಯಸಿಂಹ)", "jeannich", "Jeff Bailes", "Jesse Zilstorff", - "Joan Duran", "João Santos", "Joar Bagge", "Joe Anderson", - "Joel Calado", "Johan Linde", "John Garland", "Jojan", "jollyr0ger", - "Jonas Bo Grimsgaard", "Jonas Granqvist", "Jonas Slivka", - "Jonathan Zeppettini", "Jørgen", "Jørgen Tellnes", "josé", - "José Geraldo Gouvêa", "José Iván León Islas", "José Lou C.", - "Jose Sun", "Jr.", "Jukka Kauppinen", "Julián Alarcón", - "julietgolf", "Jusic", "Justzupi", "Kaarel", "Kai Thomsen", - "Kalman Tarnay", "Kamil Páral", "Kane_F", "kaotiks@gmail.com", - "Kateikyoushii", "kaxhinaz", "Kazuhiro NISHIYAMA", "Kerberos", - "Keresztes Ákos", "kevintyk", "kiersie", "Kimbo^", "Kim Lübbe", - "kitzOgen", "Kjetil Rydland", "kluon", "kmikz", "Knedlyk", - "koleoptero", "Kőrösi Krisztián", "Kouta", "Krakatos", - "Krešo Kunjas", "kripken", "Kristaps", "Kristian Øllegaard", - "Kristoffer Egil Bonarjee", "Krzysztof Janowski", - "Krzysztof Zawada", "Larry Wei Liu", "laughterwym", "Laur Mõtus", - "lazka", "leandrud", "lê bình", "Le Coz Florent", "Leo", "liorda", - "LKRaider", "LoLo_SaG", "Long Tran", "Lorenz", "Low Kian Seong", - "Luca Andrea Rossi", "Luca Ferretti", "Lucky LIX", "Luis Gomes", - "Luis Reis", "Łukasz Wyszyński", "luojie-dune", "maaark", - "Maciej Chojnacki", "Maciej Meller", "Mads Peter Rommedahl", - "Major Kong", "Malaki", "malde", "Malte Lenz", "Mantas Kriaučiūnas", - "Mara Sorella", "Marcin", "Marcin Falkiewicz", "marcobra", - "Marco da Silva", "Marco de Moulin", "Marco Rodrigues", "Marcos", - "Marcos Escalier", "Marcos Mobley", "Marcus Ekstrom", - "Marek Dębowski", "Mário Buči", "Mario Munda", "Marius Andersen", - "Marius Hudea", "Marius Mihai", "Mariusz Cielecki", - "Mark Krapivner", "marko-markovic", "Markus Brummer", - "Markus Sutter", "Martin", "Martin Dybdal", "Martin Iglesias", - "Martin Lettner", "Martin Pihl", "Masoud Kalali", "mat02", - "Matej Urbančič", "Mathias-K", "Mathieu Arès", - "Mathieu D. (MatToufoutu)", "Mathijs", "Matrik", "Matteo Renzulli", - "Matteo Settenvini", "Matthew Gadd", "Matthias Benkard", - "Matthias Mailänder", "Mattias Ohlsson", "Mauro de Carvalho", - "Max Molchanov", "Me", "MercuryCC", "Mert Bozkurt", "Mert Dirik", - "MFX", "mhietar", "mibtha", "Michael Budde", "Michael Kaliszka", - "Michalis Makaronides", "Michał Tokarczyk", "Miguel Pires da Rosa", - "Mihai Capotă", "Miika Metsälä", "Mikael Fernblad", "Mike Sierra", - "mikhalek", "Milan Prvulović", "Milo Casagrande", "Mindaugas", - "Miroslav Matejaš", "misel", "mithras", "Mitja Pagon", "M.Kitchen", - "Mohamed Magdy", "moonkey", "MrBlonde", "muczy", "Münir Ekinci", - "Mustafa Temizel", "mvoncken", "Mytonn", "NagyMarton", "neaion", - "Neil Lin", "Nemo", "Nerijus Arlauskas", "Nicklas Larsson", - "Nicolaj Wyke", "Nicola Piovesan", "Nicolas Sabatier", - "Nicolas Velin", "Nightfall", "NiKoB", "Nikolai M. Riabov", - "Niko_Thien", "niska", "Nithir", "noisemonkey", "nomemohes", - "nosense", "null", "Nuno Estêvão", "Nuno Santos", "nxxs", "nyo", - "obo", "Ojan", "Olav Andreas Lindekleiv", "oldbeggar", - "Olivier FAURAX", "orphe", "osantana", "Osman Tosun", "OssiR", - "otypoks", "ounn", "Oz123", "Özgür BASKIN", "Pablo Carmona A.", - "Pablo Ledesma", "Pablo Navarro Castillo", "Paco Molinero", - "Pål-Eivind Johnsen", "pano", "Paolo Naldini", "Paracelsus", - "Patryk13_03", "Patryk Skorupa", "PattogoTehen", "Paul Lange", - "Pavcio", "Paweł Wysocki", "Pedro Brites Moita", - "Pedro Clemente Pereira Neto", "Pekka \"PEXI\" Niemistö", "Penegal", - "Penzo", "perdido", "Peter Kotrcka", "Peter Skov", - "Peter Van den Bosch", "Petter Eklund", "Petter Viklund", - "phatsphere", "Phenomen", "Philipi", "Philippides Homer", "phoenix", - "pidi", "Pierre Quillery", "Pierre Rudloff", "Pierre Slamich", - "Pietrao", "Piotr Strębski", "Piotr Wicijowski", "Pittmann Tamás", - "Playmolas", "Prescott", "Prescott_SK", "pronull", - "Przemysław Kulczycki", "Pumy", "pushpika", "PY", "qubicllj", - "r21vo", "Rafał Barański", "rainofchaos", "Rajbir", "ras0ir", "Rat", - "rd1381", "Renato", "Rene Hennig", "Rene Pärts", "Ricardo Duarte", - "Richard", "Robert Hrovat", "Roberth Sjonøy", "Robert Lundmark", - "Robin Jakobsson", "Robin Kåveland", "Rodrigo Donado", - "Roel Groeneveld", "rohmaru", "Rolf Christensen", "Rolf Leggewie", - "Roni Kantis", "Ronmi", "Rostislav Raykov", "royto", "RuiAmaro", - "Rui Araújo", "Rui Moura", "Rune Svendsen", "Rusna", "Rytis", - "Sabirov Mikhail", "salseeg", "Sami Koskinen", "Samir van de Sand", - "Samuel Arroyo Acuña", "Samuel R. C. Vale", "Sanel", "Santi", - "Santi Martínez Cantelli", "Sardan", "Sargate Kanogan", - "Sarmad Jari", "Saša Bodiroža", "sat0shi", "Saulius Pranckevičius", - "Savvas Radevic", "Sebastian Krauß", "Sebastián Porta", "Sedir", - "Sefa Denizoğlu", "sekolands", "Selim Suerkan", "semsomi", - "Sergii Golovatiuk", "setarcos", "Sheki", "Shironeko", "Shlomil", - "silfiriel", "Simone Tolotti", "Simone Vendemia", "sirkubador", - "Sławomir Więch", "slip", "slyon", "smoke", "Sonja", "spectral", - "spin_555", "spitf1r3", "Spiziuz", "Spyros Theodoritsis", "SqUe", - "Squigly", "srtck", "Stefan Horning", "Stefano Maggiolo", - "Stefano Roberto Soleti", "steinberger", "Stéphane Travostino", - "Stephan Klein", "Steven De Winter", "Stevie", "Stian24", "stylius", - "Sukarn Maini", "Sunjae Park", "Susana Pereira", "szymon siglowy", - "takercena", "TAS", "Taygeto", "temy4", "texxxxxx", "thamood", - "Thanos Chatziathanassiou", "Tharawut Paripaiboon", "Theodoor", - "Théophane Anestis", "Thor Marius K. Høgås", "Tiago Silva", - "Tiago Sousa", "Tikkel", "tim__b", "Tim Bordemann", "Tim Fuchs", - "Tim Kornhammar", "Timo", "Timo Jyrinki", "Timothy Babych", - "TitkosRejtozo", "Tom", "Tomas Gustavsson", "Tomas Valentukevičius", - "Tomasz Dominikowski", "Tomislav Plavčić", "Tom Mannerhagen", - "Tommy Mikkelsen", "Tom Verdaat", "Tony Manco", - "Tor Erling H. Opsahl", "Toudi", "tqm_z", "Trapanator", "Tribaal", - "Triton", "TuniX12", "Tuomo Sipola", "turbojugend_gr", "Turtle.net", - "twilight", "tymmej", "Ulrik", "Umarzuki Mochlis", "unikob", - "Vadim Gusev", "Vagi", "Valentin Bora", "Valmantas Palikša", - "VASKITTU", "Vassilis Skoullis", "vetal17", "vicedo", "viki", - "villads hamann", "Vincent Garibal", "Vincent Ortalda", "vinchi007", - "Vinícius de Figueiredo Silva", "Vinzenz Vietzke", "virtoo", - "virtual_spirit", "Vitor Caike", "Vitor Lamas Gatti", - "Vladimir Lazic", "Vladimir Sharshov", "Wanderlust", "Wander Nauta", - "Ward De Ridder", "WebCrusader", "webdr", "Wentao Tang", "wilana", - "Wilfredo Ernesto Guerrero Campos", "Wim Champagne", "World Sucks", - "Xabi Ezpeleta", "Xavi de Moner", "XavierToo", "XChesser", - "Xiaodong Xu", "xyb", "Yaron", "Yasen Pramatarov", "YesPoX", - "Yuren Ju", "Yves MATHIEU", "zekopeko", "zhuqin", "Zissan", - "Γιάννης Κατσαμπίρης", "Артём Попов", "Миша", "Шаймарданов Максим", - "蔡查理" + self.about.set_artists(['Andrew Wedderburn', 'Andrew Resch']) + self.about.set_translator_credits('\n'.join([ + 'Aaron Wang Shi', 'abbigss', 'ABCdatos', 'Abcx', 'Actam', 'Adam', + 'adaminikisi', 'adi_oporanu', 'Adrian Goll', 'afby', 'Ahmades', + 'Ahmad Farghal', 'Ahmad Gharbeia أحمد غربية', 'akira', 'Aki Sivula', + 'Alan Pepelko', 'Alberto', 'Alberto Ferrer', 'alcatr4z', 'AlckO', + 'Aleksej Korgenkov', 'Alessio Treglia', 'Alexander Ilyashov', + 'Alexander Matveev', 'Alexander Saltykov', 'Alexander Taubenkorb', + 'Alexander Telenga', 'Alexander Yurtsev', 'Alexandre Martani', + 'Alexandre Rosenfeld', 'Alexandre Sapata Carbonell', + 'Alexey Osipov', 'Alin Claudiu Radut', 'allah', 'AlSim', + 'Alvaro Carrillanca P.', 'A.Matveev', 'Andras Hipsag', + 'András Kárász', 'Andrea Ratto', 'Andreas Johansson', 'Andreas Str', + 'André F. Oliveira', 'AndreiF', 'andrewh', 'Angel Guzman Maeso', + 'Aníbal Deboni Neto', 'animarval', 'Antonio Cono', 'antoniojreyes', + 'Anton Shestakov', 'Anton Yakutovich', 'antou', + 'Arkadiusz Kalinowski', 'Artin', 'artir', 'Astur', + 'Athanasios Lefteris', 'Athmane MOKRAOUI (ButterflyOfFire)', + 'Augusta Carla Klug', 'Avoledo Marco', 'axaard', 'AxelRafn', + 'Axezium', 'Ayont', 'b3rx', 'Bae Taegil', 'Bajusz Tamás', + "Balaam's Miracle", 'Ballestein', 'Bent Ole Fosse', 'berto89', + 'bigx', 'Bjorn Inge Berg', 'blackbird', 'Blackeyed', 'blackmx', + 'BlueSky', 'Blutheo', 'bmhm', 'bob00work', 'boenki', + 'Bogdan Bădic-Spătariu', 'bonpu', 'Boone', 'boss01', + 'Branislav Jovanović', 'bronze', 'brownie', 'Brus46', 'bumper', + 'butely', 'BXCracer', 'c0nfidencal', 'Can Kaya', + 'Carlos Alexandro Becker', 'cassianoleal', 'Cédric.h', + 'César Rubén', 'chaoswizard', 'Chen Tao', 'chicha', + 'Chien Cheng Wei', 'Christian Kopac', 'Christian Widell', + 'Christoffer Brodd-Reijer', 'christooss', 'CityAceE', 'Clopy', + 'Clusty', 'cnu', 'Commandant', 'Constantinos Koniaris', 'Coolmax', + 'cosmix', 'Costin Chirvasuta', 'CoVaLiDiTy', 'cow_2001', + 'Crispin Kirchner', 'crom', 'Cruster', 'Cybolic', 'Dan Bishop', + 'Danek', 'Dani', 'Daniel Demarco', 'Daniel Ferreira', + 'Daniel Frank', 'Daniel Holm', 'Daniel Høyer Iversen', + 'Daniel Marynicz', 'Daniel Nylander', 'Daniel Patriche', + 'Daniel Schildt', 'Daniil Sorokin', 'Dante Díaz', 'Daria Michalska', + 'DarkenCZ', 'Darren', 'Daspah', 'David Eurenius', 'davidhjelm', + 'David Machakhelidze', 'Dawid Dziurdzia', 'Daya Adianto ', 'dcruz', + 'Deady', 'Dereck Wonnacott', 'Devgru', 'Devid Antonio Filoni' + 'DevilDogTG', 'di0rz`', 'Dialecti Valsamou', 'Diego Medeiros', + 'Dkzoffy', 'Dmitrij D. Czarkoff', 'Dmitriy Geels', + 'Dmitry Olyenyov', 'Dominik Kozaczko', 'Dominik Lübben', 'doomster', + 'Dorota Król', 'Doyen Philippe', 'Dread Knight', 'DreamSonic', + 'duan', 'Duong Thanh An', 'DvoglavaZver', 'dwori', 'dylansmrjones', + 'Ebuntor', 'Edgar Alejandro Jarquin Flores', 'Eetu', 'ekerazha', + 'Elias Julkunen', 'elparia', 'Emberke', 'Emiliano Goday Caneda', + 'EndelWar', 'eng.essam', 'enubuntu', 'ercangun', 'Erdal Ronahi', + 'ergin üresin', 'Eric', 'Éric Lassauge', 'Erlend Finvåg', 'Errdil', + 'ethan shalev', 'Evgeni Spasov', 'ezekielnin', 'Fabian Ordelmans', + 'Fabio Mazanatti', 'Fábio Nogueira', 'FaCuZ', 'Felipe Lerena', + 'Fernando Pereira', 'fjetland', 'Florian Schäfer', 'FoBoS', 'Folke', + 'Force', 'fosk', 'fragarray', 'freddeg', 'Frédéric Perrin', + 'Fredrik Kilegran', 'FreeAtMind', 'Fulvio Ciucci', 'Gabor Kelemen', + 'Galatsanos Panagiotis', 'Gaussian', 'gdevitis', 'Georg Brzyk', + 'George Dumitrescu', 'Georgi Arabadjiev', 'Georg Sieber', + 'Gerd Radecke', 'Germán Heusdens', 'Gianni Vialetto', + 'Gigih Aji Ibrahim', 'Giorgio Wicklein', 'Giovanni Rapagnani', + 'Giuseppe', 'gl', 'glen', 'granjerox', 'Green Fish', 'greentea', + 'Greyhound', 'G. U.', 'Guillaume BENOIT', 'Guillaume Pelletier', + 'Gustavo Henrique Klug', 'gutocarvalho', 'Guybrush88', + 'Hans Rødtang', 'HardDisk', 'Hargas Gábor', + 'Heitor Thury Barreiros Barbosa', 'helios91940', 'helix84', + 'Helton Rodrigues', 'Hendrik Luup', 'Henrique Ferreiro', + 'Henry Goury-Laffont', 'Hezy Amiel', 'hidro', 'hoball', 'hokten', + 'Holmsss', 'hristo.num', 'Hubert Życiński', 'Hyo', 'Iarwain', 'ibe', + 'ibear', 'Id2ndR', 'Igor Zubarev', 'IKON (Ion)', 'imen', + 'Ionuț Jula', 'Isabelle STEVANT', 'István Nyitrai', 'Ivan Petrovic', + 'Ivan Prignano', 'IvaSerge', 'jackmc', 'Jacks0nxD', 'Jack Shen', + 'Jacky Yeung', 'Jacques Stadler', 'Janek Thomaschewski', 'Jan Kaláb', + 'Jan Niklas Hasse', 'Jasper Groenewegen', 'Javi Rodríguez', + 'Jayasimha (ಜಯಸಿಂಹ)', 'jeannich', 'Jeff Bailes', 'Jesse Zilstorff', + 'Joan Duran', 'João Santos', 'Joar Bagge', 'Joe Anderson', + 'Joel Calado', 'Johan Linde', 'John Garland', 'Jojan', 'jollyr0ger', + 'Jonas Bo Grimsgaard', 'Jonas Granqvist', 'Jonas Slivka', + 'Jonathan Zeppettini', 'Jørgen', 'Jørgen Tellnes', 'josé', + 'José Geraldo Gouvêa', 'José Iván León Islas', 'José Lou C.', + 'Jose Sun', 'Jr.', 'Jukka Kauppinen', 'Julián Alarcón', + 'julietgolf', 'Jusic', 'Justzupi', 'Kaarel', 'Kai Thomsen', + 'Kalman Tarnay', 'Kamil Páral', 'Kane_F', 'kaotiks@gmail.com', + 'Kateikyoushii', 'kaxhinaz', 'Kazuhiro NISHIYAMA', 'Kerberos', + 'Keresztes Ákos', 'kevintyk', 'kiersie', 'Kimbo^', 'Kim Lübbe', + 'kitzOgen', 'Kjetil Rydland', 'kluon', 'kmikz', 'Knedlyk', + 'koleoptero', 'Kőrösi Krisztián', 'Kouta', 'Krakatos', + 'Krešo Kunjas', 'kripken', 'Kristaps', 'Kristian Øllegaard', + 'Kristoffer Egil Bonarjee', 'Krzysztof Janowski', + 'Krzysztof Zawada', 'Larry Wei Liu', 'laughterwym', 'Laur Mõtus', + 'lazka', 'leandrud', 'lê bình', 'Le Coz Florent', 'Leo', 'liorda', + 'LKRaider', 'LoLo_SaG', 'Long Tran', 'Lorenz', 'Low Kian Seong', + 'Luca Andrea Rossi', 'Luca Ferretti', 'Lucky LIX', 'Luis Gomes', + 'Luis Reis', 'Łukasz Wyszyński', 'luojie-dune', 'maaark', + 'Maciej Chojnacki', 'Maciej Meller', 'Mads Peter Rommedahl', + 'Major Kong', 'Malaki', 'malde', 'Malte Lenz', 'Mantas Kriaučiūnas', + 'Mara Sorella', 'Marcin', 'Marcin Falkiewicz', 'marcobra', + 'Marco da Silva', 'Marco de Moulin', 'Marco Rodrigues', 'Marcos', + 'Marcos Escalier', 'Marcos Mobley', 'Marcus Ekstrom', + 'Marek Dębowski', 'Mário Buči', 'Mario Munda', 'Marius Andersen', + 'Marius Hudea', 'Marius Mihai', 'Mariusz Cielecki', + 'Mark Krapivner', 'marko-markovic', 'Markus Brummer', + 'Markus Sutter', 'Martin', 'Martin Dybdal', 'Martin Iglesias', + 'Martin Lettner', 'Martin Pihl', 'Masoud Kalali', 'mat02', + 'Matej Urbančič', 'Mathias-K', 'Mathieu Arès', + 'Mathieu D. (MatToufoutu)', 'Mathijs', 'Matrik', 'Matteo Renzulli', + 'Matteo Settenvini', 'Matthew Gadd', 'Matthias Benkard', + 'Matthias Mailänder', 'Mattias Ohlsson', 'Mauro de Carvalho', + 'Max Molchanov', 'Me', 'MercuryCC', 'Mert Bozkurt', 'Mert Dirik', + 'MFX', 'mhietar', 'mibtha', 'Michael Budde', 'Michael Kaliszka', + 'Michalis Makaronides', 'Michał Tokarczyk', 'Miguel Pires da Rosa', + 'Mihai Capotă', 'Miika Metsälä', 'Mikael Fernblad', 'Mike Sierra', + 'mikhalek', 'Milan Prvulović', 'Milo Casagrande', 'Mindaugas', + 'Miroslav Matejaš', 'misel', 'mithras', 'Mitja Pagon', 'M.Kitchen', + 'Mohamed Magdy', 'moonkey', 'MrBlonde', 'muczy', 'Münir Ekinci', + 'Mustafa Temizel', 'mvoncken', 'Mytonn', 'NagyMarton', 'neaion', + 'Neil Lin', 'Nemo', 'Nerijus Arlauskas', 'Nicklas Larsson', + 'Nicolaj Wyke', 'Nicola Piovesan', 'Nicolas Sabatier', + 'Nicolas Velin', 'Nightfall', 'NiKoB', 'Nikolai M. Riabov', + 'Niko_Thien', 'niska', 'Nithir', 'noisemonkey', 'nomemohes', + 'nosense', 'null', 'Nuno Estêvão', 'Nuno Santos', 'nxxs', 'nyo', + 'obo', 'Ojan', 'Olav Andreas Lindekleiv', 'oldbeggar', + 'Olivier FAURAX', 'orphe', 'osantana', 'Osman Tosun', 'OssiR', + 'otypoks', 'ounn', 'Oz123', 'Özgür BASKIN', 'Pablo Carmona A.', + 'Pablo Ledesma', 'Pablo Navarro Castillo', 'Paco Molinero', + 'Pål-Eivind Johnsen', 'pano', 'Paolo Naldini', 'Paracelsus', + 'Patryk13_03', 'Patryk Skorupa', 'PattogoTehen', 'Paul Lange', + 'Pavcio', 'Paweł Wysocki', 'Pedro Brites Moita', + 'Pedro Clemente Pereira Neto', "Pekka \"PEXI\" Niemistö", 'Penegal', + 'Penzo', 'perdido', 'Peter Kotrcka', 'Peter Skov', + 'Peter Van den Bosch', 'Petter Eklund', 'Petter Viklund', + 'phatsphere', 'Phenomen', 'Philipi', 'Philippides Homer', 'phoenix', + 'pidi', 'Pierre Quillery', 'Pierre Rudloff', 'Pierre Slamich', + 'Pietrao', 'Piotr Strębski', 'Piotr Wicijowski', 'Pittmann Tamás', + 'Playmolas', 'Prescott', 'Prescott_SK', 'pronull', + 'Przemysław Kulczycki', 'Pumy', 'pushpika', 'PY', 'qubicllj', + 'r21vo', 'Rafał Barański', 'rainofchaos', 'Rajbir', 'ras0ir', 'Rat', + 'rd1381', 'Renato', 'Rene Hennig', 'Rene Pärts', 'Ricardo Duarte', + 'Richard', 'Robert Hrovat', 'Roberth Sjonøy', 'Robert Lundmark', + 'Robin Jakobsson', 'Robin Kåveland', 'Rodrigo Donado', + 'Roel Groeneveld', 'rohmaru', 'Rolf Christensen', 'Rolf Leggewie', + 'Roni Kantis', 'Ronmi', 'Rostislav Raykov', 'royto', 'RuiAmaro', + 'Rui Araújo', 'Rui Moura', 'Rune Svendsen', 'Rusna', 'Rytis', + 'Sabirov Mikhail', 'salseeg', 'Sami Koskinen', 'Samir van de Sand', + 'Samuel Arroyo Acuña', 'Samuel R. C. Vale', 'Sanel', 'Santi', + 'Santi Martínez Cantelli', 'Sardan', 'Sargate Kanogan', + 'Sarmad Jari', 'Saša Bodiroža', 'sat0shi', 'Saulius Pranckevičius', + 'Savvas Radevic', 'Sebastian Krauß', 'Sebastián Porta', 'Sedir', + 'Sefa Denizoğlu', 'sekolands', 'Selim Suerkan', 'semsomi', + 'Sergii Golovatiuk', 'setarcos', 'Sheki', 'Shironeko', 'Shlomil', + 'silfiriel', 'Simone Tolotti', 'Simone Vendemia', 'sirkubador', + 'Sławomir Więch', 'slip', 'slyon', 'smoke', 'Sonja', 'spectral', + 'spin_555', 'spitf1r3', 'Spiziuz', 'Spyros Theodoritsis', 'SqUe', + 'Squigly', 'srtck', 'Stefan Horning', 'Stefano Maggiolo', + 'Stefano Roberto Soleti', 'steinberger', 'Stéphane Travostino', + 'Stephan Klein', 'Steven De Winter', 'Stevie', 'Stian24', 'stylius', + 'Sukarn Maini', 'Sunjae Park', 'Susana Pereira', 'szymon siglowy', + 'takercena', 'TAS', 'Taygeto', 'temy4', 'texxxxxx', 'thamood', + 'Thanos Chatziathanassiou', 'Tharawut Paripaiboon', 'Theodoor', + 'Théophane Anestis', 'Thor Marius K. Høgås', 'Tiago Silva', + 'Tiago Sousa', 'Tikkel', 'tim__b', 'Tim Bordemann', 'Tim Fuchs', + 'Tim Kornhammar', 'Timo', 'Timo Jyrinki', 'Timothy Babych', + 'TitkosRejtozo', 'Tom', 'Tomas Gustavsson', 'Tomas Valentukevičius', + 'Tomasz Dominikowski', 'Tomislav Plavčić', 'Tom Mannerhagen', + 'Tommy Mikkelsen', 'Tom Verdaat', 'Tony Manco', + 'Tor Erling H. Opsahl', 'Toudi', 'tqm_z', 'Trapanator', 'Tribaal', + 'Triton', 'TuniX12', 'Tuomo Sipola', 'turbojugend_gr', 'Turtle.net', + 'twilight', 'tymmej', 'Ulrik', 'Umarzuki Mochlis', 'unikob', + 'Vadim Gusev', 'Vagi', 'Valentin Bora', 'Valmantas Palikša', + 'VASKITTU', 'Vassilis Skoullis', 'vetal17', 'vicedo', 'viki', + 'villads hamann', 'Vincent Garibal', 'Vincent Ortalda', 'vinchi007', + 'Vinícius de Figueiredo Silva', 'Vinzenz Vietzke', 'virtoo', + 'virtual_spirit', 'Vitor Caike', 'Vitor Lamas Gatti', + 'Vladimir Lazic', 'Vladimir Sharshov', 'Wanderlust', 'Wander Nauta', + 'Ward De Ridder', 'WebCrusader', 'webdr', 'Wentao Tang', 'wilana', + 'Wilfredo Ernesto Guerrero Campos', 'Wim Champagne', 'World Sucks', + 'Xabi Ezpeleta', 'Xavi de Moner', 'XavierToo', 'XChesser', + 'Xiaodong Xu', 'xyb', 'Yaron', 'Yasen Pramatarov', 'YesPoX', + 'Yuren Ju', 'Yves MATHIEU', 'zekopeko', 'zhuqin', 'Zissan', + 'Γιάννης Κατσαμπίρης', 'Артём Попов', 'Миша', 'Шаймарданов Максим', + '蔡查理' ])) self.about.set_wrap_license(True) self.about.set_license(_( - "This program is free software; you can redistribute it and/or " - "modify it under the terms of the GNU General Public License as " - "published by the Free Software Foundation; either version 3 of " - "the License, or (at your option) any later version. \n\n" - "This program " - "is distributed in the hope that it will be useful, but WITHOUT " - "ANY WARRANTY; without even the implied warranty of " - "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU " - "General Public License for more details. \n\n" - "You should have received " - "a copy of the GNU General Public License along with this program; " - "if not, see <http://www.gnu.org/licenses>. \n\n" - "In addition, as a " - "special exception, the copyright holders give permission to link " - "the code of portions of this program with the OpenSSL library. " - "You must obey the GNU General Public License in all respects for " - "all of the code used other than OpenSSL. \n\n" - "If you modify file(s) " - "with this exception, you may extend this exception to your " - "version of the file(s), but you are not obligated to do so. If " - "you do not wish to do so, delete this exception statement from " - "your version. If you delete this exception statement from all " - "source files in the program, then also delete it here." + 'This program is free software; you can redistribute it and/or ' + 'modify it under the terms of the GNU General Public License as ' + 'published by the Free Software Foundation; either version 3 of ' + 'the License, or (at your option) any later version. \n\n' + 'This program ' + 'is distributed in the hope that it will be useful, but WITHOUT ' + 'ANY WARRANTY; without even the implied warranty of ' + 'MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ' + 'General Public License for more details. \n\n' + 'You should have received ' + 'a copy of the GNU General Public License along with this program; ' + 'if not, see <http://www.gnu.org/licenses>. \n\n' + 'In addition, as a ' + 'special exception, the copyright holders give permission to link ' + 'the code of portions of this program with the OpenSSL library. ' + 'You must obey the GNU General Public License in all respects for ' + 'all of the code used other than OpenSSL. \n\n' + 'If you modify file(s) ' + 'with this exception, you may extend this exception to your ' + 'version of the file(s), but you are not obligated to do so. If ' + 'you do not wish to do so, delete this exception statement from ' + 'your version. If you delete this exception statement from all ' + 'source files in the program, then also delete it here.' )) - self.about.set_website("http://deluge-torrent.org") - self.about.set_website_label("deluge-torrent.org") + self.about.set_website('http://deluge-torrent.org') + self.about.set_website_label('deluge-torrent.org') self.about.set_icon(get_deluge_icon()) - self.about.set_logo(gtk.gdk.pixbuf_new_from_file(get_pixmap("deluge-about.png"))) + self.about.set_logo(gtk.gdk.pixbuf_new_from_file(get_pixmap('deluge-about.png'))) if client.connected(): if not client.is_standalone(): self.about.set_comments( - self.about.get_comments() + _("Server:") + " %coreversion%\n") + self.about.get_comments() + _('Server:') + ' %coreversion%\n') self.about.set_comments( - self.about.get_comments() + "\n" + _("libtorrent:") + " %ltversion%\n") + self.about.get_comments() + '\n' + _('libtorrent:') + ' %ltversion%\n') def on_lt_version(result): c = self.about.get_comments() - c = c.replace("%ltversion%", result) + c = c.replace('%ltversion%', result) self.about.set_comments(c) def on_info(result): c = self.about.get_comments() - c = c.replace("%coreversion%", result) + c = c.replace('%coreversion%', result) self.about.set_comments(c) client.core.get_libtorrent_version().addCallback(on_lt_version) diff --git a/deluge/ui/gtkui/addtorrentdialog.py b/deluge/ui/gtkui/addtorrentdialog.py index 6b7f60efa..8227fa913 100644 --- a/deluge/ui/gtkui/addtorrentdialog.py +++ b/deluge/ui/gtkui/addtorrentdialog.py @@ -36,36 +36,36 @@ log = logging.getLogger(__name__) class AddTorrentDialog(component.Component): def __init__(self): - component.Component.__init__(self, "AddTorrentDialog") + component.Component.__init__(self, 'AddTorrentDialog') self.builder = gtk.Builder() # The base dialog self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "add_torrent_dialog.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.ui') )) # The infohash dialog self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "add_torrent_dialog.infohash.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.infohash.ui') )) # The url dialog self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "add_torrent_dialog.url.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'add_torrent_dialog.url.ui') )) - self.dialog = self.builder.get_object("dialog_add_torrent") + self.dialog = self.builder.get_object('dialog_add_torrent') - self.dialog.connect("delete-event", self._on_delete_event) + self.dialog.connect('delete-event', self._on_delete_event) self.builder.connect_signals({ - "on_button_file_clicked": self._on_button_file_clicked, - "on_button_url_clicked": self._on_button_url_clicked, - "on_button_hash_clicked": self._on_button_hash_clicked, - "on_button_remove_clicked": self._on_button_remove_clicked, - "on_button_trackers_clicked": self._on_button_trackers_clicked, - "on_button_cancel_clicked": self._on_button_cancel_clicked, - "on_button_add_clicked": self._on_button_add_clicked, - "on_button_apply_clicked": self._on_button_apply_clicked, - "on_button_revert_clicked": self._on_button_revert_clicked, - "on_chk_move_completed_toggled": self._on_chk_move_completed_toggled + 'on_button_file_clicked': self._on_button_file_clicked, + 'on_button_url_clicked': self._on_button_url_clicked, + 'on_button_hash_clicked': self._on_button_hash_clicked, + 'on_button_remove_clicked': self._on_button_remove_clicked, + 'on_button_trackers_clicked': self._on_button_trackers_clicked, + 'on_button_cancel_clicked': self._on_button_cancel_clicked, + 'on_button_add_clicked': self._on_button_add_clicked, + 'on_button_apply_clicked': self._on_button_apply_clicked, + 'on_button_revert_clicked': self._on_button_revert_clicked, + 'on_chk_move_completed_toggled': self._on_chk_move_completed_toggled }) # download?, path, filesize, sequence number, inconsistent? @@ -81,34 +81,34 @@ class AddTorrentDialog(component.Component): self.previous_selected_torrent = None - self.listview_torrents = self.builder.get_object("listview_torrents") - self.listview_files = self.builder.get_object("listview_files") + self.listview_torrents = self.builder.get_object('listview_torrents') + self.listview_files = self.builder.get_object('listview_files') render = gtk.CellRendererText() render.connect('edited', self._on_torrent_name_edit) render.set_property('editable', True) - column = gtk.TreeViewColumn(_("Torrent"), render, text=1) + column = gtk.TreeViewColumn(_('Torrent'), render, text=1) self.listview_torrents.append_column(column) render = gtk.CellRendererToggle() - render.connect("toggled", self._on_file_toggled) + render.connect('toggled', self._on_file_toggled) column = gtk.TreeViewColumn(None, render, active=0, inconsistent=4) self.listview_files.append_column(column) - column = gtk.TreeViewColumn(_("Filename")) + column = gtk.TreeViewColumn(_('Filename')) render = gtk.CellRendererPixbuf() column.pack_start(render, False) - column.add_attribute(render, "stock-id", 5) + column.add_attribute(render, 'stock-id', 5) render = gtk.CellRendererText() - render.set_property("editable", True) - render.connect("edited", self._on_filename_edited) + render.set_property('editable', True) + render.connect('edited', self._on_filename_edited) column.pack_start(render, True) - column.add_attribute(render, "text", 1) + column.add_attribute(render, 'text', 1) column.set_expand(True) self.listview_files.append_column(column) render = gtk.CellRendererText() - column = gtk.TreeViewColumn(_("Size")) + column = gtk.TreeViewColumn(_('Size')) column.pack_start(render) column.set_cell_data_func(render, cell_data_size, 2) self.listview_files.append_column(column) @@ -119,29 +119,29 @@ class AddTorrentDialog(component.Component): self.listview_files.set_model(self.files_treestore) self.listview_files.get_selection().set_mode(gtk.SELECTION_MULTIPLE) - self.listview_torrents.get_selection().connect("changed", self._on_torrent_changed) + self.listview_torrents.get_selection().connect('changed', self._on_torrent_changed) self.setup_move_completed_path_chooser() self.setup_download_location_path_chooser() # Get default config values from the core self.core_keys = [ - "pre_allocate_storage", - "max_connections_per_torrent", - "max_upload_slots_per_torrent", - "max_upload_speed_per_torrent", - "max_download_speed_per_torrent", - "prioritize_first_last_pieces", - "sequential_download", - "add_paused", - "download_location", - "download_location_paths_list", - "move_completed", - "move_completed_path", - "move_completed_paths_list", + 'pre_allocate_storage', + 'max_connections_per_torrent', + 'max_upload_slots_per_torrent', + 'max_upload_speed_per_torrent', + 'max_download_speed_per_torrent', + 'prioritize_first_last_pieces', + 'sequential_download', + 'add_paused', + 'download_location', + 'download_location_paths_list', + 'move_completed', + 'move_completed_path', + 'move_completed_paths_list', ] # self.core_keys += self.move_completed_path_chooser.get_config_keys() - self.builder.get_object("notebook1").connect("switch-page", self._on_switch_page) + self.builder.get_object('notebook1').connect('switch-page', self._on_switch_page) def start(self): self.update_core_config() @@ -150,8 +150,8 @@ class AddTorrentDialog(component.Component): return self.update_core_config(True, focus) def _show(self, focus=False): - if component.get("MainWindow").is_on_active_workspace(): - self.dialog.set_transient_for(component.get("MainWindow").window) + if component.get('MainWindow').is_on_active_workspace(): + self.dialog.set_transient_for(component.get('MainWindow').window) else: self.dialog.set_transient_for(None) @@ -169,7 +169,7 @@ class AddTorrentDialog(component.Component): self.previous_selected_torrent = None self.torrent_liststore.clear() self.files_treestore.clear() - self.dialog.set_transient_for(component.get("MainWindow").window) + self.dialog.set_transient_for(component.get('MainWindow').window) return None def update_core_config(self, show=False, focus=False): @@ -192,8 +192,8 @@ class AddTorrentDialog(component.Component): try: info = TorrentInfo(filename) except Exception as ex: - log.debug("Unable to open torrent file: %s", ex) - ErrorDialog(_("Invalid File"), ex, self.dialog).run() + log.debug('Unable to open torrent file: %s', ex) + ErrorDialog(_('Invalid File'), ex, self.dialog).run() continue if info.info_hash in self.files: @@ -212,13 +212,13 @@ class AddTorrentDialog(component.Component): if not row and new_row: self.listview_torrents.get_selection().select_iter(new_row) - self.dialog.set_title(_("Add Torrents (%d)") % len(self.torrent_liststore)) + self.dialog.set_title(_('Add Torrents (%d)') % len(self.torrent_liststore)) if already_added: - log.debug("Tried to add %d duplicate torrents!", already_added) + log.debug('Tried to add %d duplicate torrents!', already_added) ErrorDialog( - _("Duplicate Torrent(s)"), - _("You cannot add the same torrent twice. %d torrents were already added." % already_added), + _('Duplicate Torrent(s)'), + _('You cannot add the same torrent twice. %d torrents were already added.' % already_added), self.dialog ).run() @@ -228,14 +228,14 @@ class AddTorrentDialog(component.Component): for uri in uris: magnet = deluge.common.get_magnet_info(uri) if not magnet: - log.error("Invalid magnet: %s", uri) + log.error('Invalid magnet: %s', uri) continue - if magnet["info_hash"] in self.infos: - log.info("Torrent already in Add Dialog list: %s", uri) + if magnet['info_hash'] in self.infos: + log.info('Torrent already in Add Dialog list: %s', uri) continue - new_row = self.torrent_liststore.append([magnet["info_hash"], magnet["name"], xml_escape(uri)]) - self.files[magnet["info_hash"]] = magnet["files_tree"] - self.infos[magnet["info_hash"]] = None + new_row = self.torrent_liststore.append([magnet['info_hash'], magnet['name'], xml_escape(uri)]) + self.files[magnet['info_hash']] = magnet['files_tree'] + self.infos[magnet['info_hash']] = None self.listview_torrents.get_selection().select_iter(new_row) self.set_default_options() self.save_torrent_options(new_row) @@ -284,10 +284,10 @@ class AddTorrentDialog(component.Component): split_files = {} for i, _file in enumerate(files): self.prepare_file( - _file, _file["path"], i, _file["download"], split_files + _file, _file['path'], i, _file['download'], split_files ) self.add_files(None, split_files) - self.listview_files.expand_row("0", False) + self.listview_files.expand_row('0', False) def prepare_file(self, _file, file_name, file_num, download, files_storage): first_slash_index = file_name.find(os.path.sep) @@ -311,10 +311,10 @@ class AddTorrentDialog(component.Component): ret += chunk_size else: self.files_treestore.append(parent_iter, [ - value[2], key, value[1]["size"], + value[2], key, value[1]['size'], value[0], False, gtk.STOCK_FILE ]) - ret += value[1]["size"] + ret += value[1]['size'] if parent_iter and self.files_treestore.iter_has_child(parent_iter): # Iterate through the children and see what we should label the # folder, download true, download false or inconsistent. @@ -338,21 +338,21 @@ class AddTorrentDialog(component.Component): return ret def load_path_choosers_data(self): - self.move_completed_path_chooser.set_text(self.core_config["move_completed_path"], + self.move_completed_path_chooser.set_text(self.core_config['move_completed_path'], cursor_end=False, default_text=True) - self.download_location_path_chooser.set_text(self.core_config["download_location"], + self.download_location_path_chooser.set_text(self.core_config['download_location'], cursor_end=False, default_text=True) - self.builder.get_object("chk_move_completed").set_active(self.core_config["move_completed"]) + self.builder.get_object('chk_move_completed').set_active(self.core_config['move_completed']) def setup_move_completed_path_chooser(self): - self.move_completed_hbox = self.builder.get_object("hbox_move_completed_chooser") - self.move_completed_path_chooser = PathChooser("move_completed_paths_list") + self.move_completed_hbox = self.builder.get_object('hbox_move_completed_chooser') + self.move_completed_path_chooser = PathChooser('move_completed_paths_list') self.move_completed_hbox.add(self.move_completed_path_chooser) self.move_completed_hbox.show_all() def setup_download_location_path_chooser(self): - self.download_location_hbox = self.builder.get_object("hbox_download_location_chooser") - self.download_location_path_chooser = PathChooser("download_location_paths_list") + self.download_location_hbox = self.builder.get_object('hbox_download_location_chooser') + self.download_location_path_chooser = PathChooser('download_location_paths_list') self.download_location_hbox.add(self.download_location_path_chooser) self.download_location_hbox.show_all() @@ -363,27 +363,27 @@ class AddTorrentDialog(component.Component): options = self.options[torrent_id] - self.download_location_path_chooser.set_text(options["download_location"], cursor_end=True) - self.move_completed_path_chooser.set_text(options["move_completed_path"], cursor_end=True) - - self.builder.get_object("spin_maxdown").set_value( - options["max_download_speed"]) - self.builder.get_object("spin_maxup").set_value( - options["max_upload_speed"]) - self.builder.get_object("spin_maxconnections").set_value( - options["max_connections"]) - self.builder.get_object("spin_maxupslots").set_value( - options["max_upload_slots"]) - self.builder.get_object("chk_paused").set_active( - options["add_paused"]) - self.builder.get_object("chk_pre_alloc").set_active( - options["pre_allocate_storage"]) - self.builder.get_object("chk_prioritize").set_active( - options["prioritize_first_last_pieces"]) - self.builder.get_object("chk_sequential_download").set_active( - options["sequential_download"]) - self.builder.get_object("chk_move_completed").set_active( - options["move_completed"]) + self.download_location_path_chooser.set_text(options['download_location'], cursor_end=True) + self.move_completed_path_chooser.set_text(options['move_completed_path'], cursor_end=True) + + self.builder.get_object('spin_maxdown').set_value( + options['max_download_speed']) + self.builder.get_object('spin_maxup').set_value( + options['max_upload_speed']) + self.builder.get_object('spin_maxconnections').set_value( + options['max_connections']) + self.builder.get_object('spin_maxupslots').set_value( + options['max_upload_slots']) + self.builder.get_object('chk_paused').set_active( + options['add_paused']) + self.builder.get_object('chk_pre_alloc').set_active( + options['pre_allocate_storage']) + self.builder.get_object('chk_prioritize').set_active( + options['prioritize_first_last_pieces']) + self.builder.get_object('chk_sequential_download').set_active( + options['sequential_download']) + self.builder.get_object('chk_move_completed').set_active( + options['move_completed']) def save_torrent_options(self, row=None): # Keeps the torrent options dictionary up-to-date with what the user has @@ -402,20 +402,20 @@ class AddTorrentDialog(component.Component): else: options = {} - options["download_location"] = self.download_location_path_chooser.get_text() - options["move_completed_path"] = self.move_completed_path_chooser.get_text() - options["pre_allocate_storage"] = self.builder.get_object("chk_pre_alloc").get_active() - options["move_completed"] = self.builder.get_object("chk_move_completed").get_active() - options["max_download_speed"] = self.builder.get_object("spin_maxdown").get_value() - options["max_upload_speed"] = self.builder.get_object("spin_maxup").get_value() - options["max_connections"] = self.builder.get_object("spin_maxconnections").get_value_as_int() - options["max_upload_slots"] = self.builder.get_object("spin_maxupslots").get_value_as_int() - options["add_paused"] = self.builder.get_object("chk_paused").get_active() - options["prioritize_first_last_pieces"] = self.builder.get_object("chk_prioritize").get_active() - options["sequential_download"] = self.builder.get_object( - "chk_sequential_download").get_active() or False - options["move_completed"] = self.builder.get_object("chk_move_completed").get_active() - options["seed_mode"] = self.builder.get_object("chk_seed_mode").get_active() + options['download_location'] = self.download_location_path_chooser.get_text() + options['move_completed_path'] = self.move_completed_path_chooser.get_text() + options['pre_allocate_storage'] = self.builder.get_object('chk_pre_alloc').get_active() + options['move_completed'] = self.builder.get_object('chk_move_completed').get_active() + options['max_download_speed'] = self.builder.get_object('spin_maxdown').get_value() + options['max_upload_speed'] = self.builder.get_object('spin_maxup').get_value() + options['max_connections'] = self.builder.get_object('spin_maxconnections').get_value_as_int() + options['max_upload_slots'] = self.builder.get_object('spin_maxupslots').get_value_as_int() + options['add_paused'] = self.builder.get_object('chk_paused').get_active() + options['prioritize_first_last_pieces'] = self.builder.get_object('chk_prioritize').get_active() + options['sequential_download'] = self.builder.get_object( + 'chk_sequential_download').get_active() or False + options['move_completed'] = self.builder.get_object('chk_move_completed').get_active() + options['seed_mode'] = self.builder.get_object('chk_seed_mode').get_active() self.options[torrent_id] = options @@ -426,7 +426,7 @@ class AddTorrentDialog(component.Component): if len(files_priorities) > 0: for i, file_dict in enumerate(self.files[torrent_id]): - file_dict["download"] = files_priorities[i] + file_dict['download'] = files_priorities[i] def build_priorities(self, _iter, priorities): while _iter is not None: @@ -445,32 +445,32 @@ class AddTorrentDialog(component.Component): self.load_path_choosers_data() - self.builder.get_object("chk_pre_alloc").set_active( - self.core_config["pre_allocate_storage"]) - self.builder.get_object("spin_maxdown").set_value( - self.core_config["max_download_speed_per_torrent"]) - self.builder.get_object("spin_maxup").set_value( - self.core_config["max_upload_speed_per_torrent"]) - self.builder.get_object("spin_maxconnections").set_value( - self.core_config["max_connections_per_torrent"]) - self.builder.get_object("spin_maxupslots").set_value( - self.core_config["max_upload_slots_per_torrent"]) - self.builder.get_object("chk_paused").set_active( - self.core_config["add_paused"]) - self.builder.get_object("chk_prioritize").set_active( - self.core_config["prioritize_first_last_pieces"]) - self.builder.get_object("chk_sequential_download").set_active( - self.core_config["sequential_download"]) - self.builder.get_object("chk_move_completed").set_active( - self.core_config["move_completed"]) - self.builder.get_object("chk_seed_mode").set_active(False) + self.builder.get_object('chk_pre_alloc').set_active( + self.core_config['pre_allocate_storage']) + self.builder.get_object('spin_maxdown').set_value( + self.core_config['max_download_speed_per_torrent']) + self.builder.get_object('spin_maxup').set_value( + self.core_config['max_upload_speed_per_torrent']) + self.builder.get_object('spin_maxconnections').set_value( + self.core_config['max_connections_per_torrent']) + self.builder.get_object('spin_maxupslots').set_value( + self.core_config['max_upload_slots_per_torrent']) + self.builder.get_object('chk_paused').set_active( + self.core_config['add_paused']) + self.builder.get_object('chk_prioritize').set_active( + self.core_config['prioritize_first_last_pieces']) + self.builder.get_object('chk_sequential_download').set_active( + self.core_config['sequential_download']) + self.builder.get_object('chk_move_completed').set_active( + self.core_config['move_completed']) + self.builder.get_object('chk_seed_mode').set_active(False) def get_file_priorities(self, torrent_id): # A list of priorities files_list = [] for file_dict in self.files[torrent_id]: - if not file_dict["download"]: + if not file_dict['download']: files_list.append(0) else: files_list.append(1) @@ -520,10 +520,10 @@ class AddTorrentDialog(component.Component): return this_level_toggle def _on_button_file_clicked(self, widget): - log.debug("_on_button_file_clicked") + log.debug('_on_button_file_clicked') # Setup the filechooserdialog chooser = gtk.FileChooserDialog( - _("Choose a .torrent file"), + _('Choose a .torrent file'), None, gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, @@ -532,30 +532,30 @@ class AddTorrentDialog(component.Component): chooser.set_transient_for(self.dialog) chooser.set_select_multiple(True) - chooser.set_property("skip-taskbar-hint", True) + chooser.set_property('skip-taskbar-hint', True) chooser.set_local_only(False) # Add .torrent and * file filters file_filter = gtk.FileFilter() - file_filter.set_name(_("Torrent files")) - file_filter.add_pattern("*." + "torrent") + file_filter.set_name(_('Torrent files')) + file_filter.add_pattern('*.' + 'torrent') chooser.add_filter(file_filter) file_filter = gtk.FileFilter() - file_filter.set_name(_("All files")) - file_filter.add_pattern("*") + file_filter.set_name(_('All files')) + file_filter.add_pattern('*') chooser.add_filter(file_filter) # Load the 'default_load_path' from the config - self.config = ConfigManager("gtkui.conf") - if self.config["default_load_path"] is not None: - chooser.set_current_folder(self.config["default_load_path"]) + self.config = ConfigManager('gtkui.conf') + if self.config['default_load_path'] is not None: + chooser.set_current_folder(self.config['default_load_path']) # Run the dialog response = chooser.run() if response == gtk.RESPONSE_OK: result = chooser.get_filenames() - self.config["default_load_path"] = chooser.get_current_folder() + self.config['default_load_path'] = chooser.get_current_folder() else: chooser.destroy() return @@ -564,9 +564,9 @@ class AddTorrentDialog(component.Component): self.add_from_files(result) def _on_button_url_clicked(self, widget): - log.debug("_on_button_url_clicked") - dialog = self.builder.get_object("url_dialog") - entry = self.builder.get_object("entry_url") + log.debug('_on_button_url_clicked') + dialog = self.builder.get_object('url_dialog') + entry = self.builder.get_object('entry_url') dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_transient_for(self.dialog) @@ -583,16 +583,16 @@ class AddTorrentDialog(component.Component): response = dialog.run() if response == gtk.RESPONSE_OK: - url = entry.get_text().decode("utf-8") + url = entry.get_text().decode('utf-8') else: url = None - entry.set_text("") + entry.set_text('') dialog.hide() # This is where we need to fetch the .torrent file from the URL and # add it to the list. - log.debug("url: %s", url) + log.debug('url: %s', url) if url: if deluge.common.is_url(url): self.add_from_url(url) @@ -600,14 +600,14 @@ class AddTorrentDialog(component.Component): self.add_from_magnets([url]) else: ErrorDialog( - _("Invalid URL"), - "%s %s" % (url, _("is not a valid URL.")), + _('Invalid URL'), + '%s %s' % (url, _('is not a valid URL.')), self.dialog ).run() def add_from_url(self, url): dialog = gtk.Dialog( - _("Downloading..."), + _('Downloading...'), flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR, parent=self.dialog) dialog.set_transient_for(self.dialog) @@ -624,23 +624,23 @@ class AddTorrentDialog(component.Component): if total_length: percent = current_length / total_length pb.set_fraction(percent) - pb.set_text("%.2f%% (%s / %s)" % ( + pb.set_text('%.2f%% (%s / %s)' % ( percent * 100, deluge.common.fsize(current_length), deluge.common.fsize(total_length))) else: pb.pulse() - pb.set_text("%s" % deluge.common.fsize(current_length)) + pb.set_text('%s' % deluge.common.fsize(current_length)) def on_download_success(result): self.add_from_files([result]) dialog.destroy() def on_download_fail(result): - log.debug("Download failed: %s", result) + log.debug('Download failed: %s', result) dialog.destroy() ErrorDialog( - _("Download Failed"), "%s %s" % (_("Failed to download:"), url), + _('Download Failed'), '%s %s' % (_('Failed to download:'), url), details=result.getErrorMessage(), parent=self.dialog ).run() return result @@ -650,10 +650,10 @@ class AddTorrentDialog(component.Component): d.addCallbacks(on_download_success, on_download_fail) def _on_button_hash_clicked(self, widget): - log.debug("_on_button_hash_clicked") - dialog = self.builder.get_object("dialog_infohash") - entry = self.builder.get_object("entry_hash") - textview = self.builder.get_object("text_trackers") + log.debug('_on_button_hash_clicked') + dialog = self.builder.get_object('dialog_infohash') + entry = self.builder.get_object('entry_hash') + textview = self.builder.get_object('text_trackers') dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_transient_for(self.dialog) @@ -670,24 +670,24 @@ class AddTorrentDialog(component.Component): if response == gtk.RESPONSE_OK and deluge.common.is_infohash(infohash): trackers = [] b = textview.get_buffer() - lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n") - log.debug("lines: %s", lines) + lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n') + log.debug('lines: %s', lines) for l in lines: if deluge.common.is_url(l): trackers.append(l) # Convert the information to a magnet uri, this is just easier to # handle this way. - log.debug("trackers: %s", trackers) + log.debug('trackers: %s', trackers) magnet = deluge.common.create_magnet_uri(infohash, infohash, trackers) - log.debug("magnet uri: %s", magnet) + log.debug('magnet uri: %s', magnet) self.add_from_magnets([magnet]) - entry.set_text("") - textview.get_buffer().set_text("") + entry.set_text('') + textview.get_buffer().set_text('') dialog.hide() def _on_button_remove_clicked(self, widget): - log.debug("_on_button_remove_clicked") + log.debug('_on_button_remove_clicked') (model, row) = self.listview_torrents.get_selection().get_selected() if row is None: return @@ -699,14 +699,14 @@ class AddTorrentDialog(component.Component): del self.infos[torrent_id] def _on_button_trackers_clicked(self, widget): - log.debug("_on_button_trackers_clicked") + log.debug('_on_button_trackers_clicked') def _on_button_cancel_clicked(self, widget): - log.debug("_on_button_cancel_clicked") + log.debug('_on_button_cancel_clicked') self.hide() def _on_button_add_clicked(self, widget): - log.debug("_on_button_add_clicked") + log.debug('_on_button_add_clicked') self.add_torrents() self.hide() @@ -728,10 +728,10 @@ class AddTorrentDialog(component.Component): file_priorities = self.get_file_priorities(torrent_id) if options is not None: - options["file_priorities"] = file_priorities + options['file_priorities'] = file_priorities if deluge.common.is_magnet(filename): - del options["file_priorities"] + del options['file_priorities'] client.core.add_torrent_magnet(filename, options) else: torrents_to_add.append((os.path.split(filename)[-1], @@ -741,15 +741,15 @@ class AddTorrentDialog(component.Component): def on_torrents_added(errors): if errors: - log.info("Failed to add %d out of %d torrents.", len(errors), len(torrents_to_add)) + log.info('Failed to add %d out of %d torrents.', len(errors), len(torrents_to_add)) for e in errors: - log.info("Torrent add failed: %s", e) + log.info('Torrent add failed: %s', e) else: - log.info("Successfully added %d torrents.", len(torrents_to_add)) + log.info('Successfully added %d torrents.', len(torrents_to_add)) client.core.add_torrent_files(torrents_to_add).addCallback(on_torrents_added) def _on_button_apply_clicked(self, widget): - log.debug("_on_button_apply_clicked") + log.debug('_on_button_apply_clicked') (model, row) = self.listview_torrents.get_selection().get_selected() if row is None: return @@ -758,7 +758,7 @@ class AddTorrentDialog(component.Component): # The options, except file renames, we want all the torrents to have options = self.options[model.get_value(row, 0)].copy() - options.pop("mapped_files", None) + options.pop('mapped_files', None) # Set all the torrent options row = model.get_iter_first() @@ -768,7 +768,7 @@ class AddTorrentDialog(component.Component): row = model.iter_next(row) def _on_button_revert_clicked(self, widget): - log.debug("_on_button_revert_clicked") + log.debug('_on_button_revert_clicked') (model, row) = self.listview_torrents.get_selection().get_selected() if row is None: return @@ -784,7 +784,7 @@ class AddTorrentDialog(component.Component): self.hide() return True - def get_file_path(self, row, path=""): + def get_file_path(self, row, path=''): if not row: return path @@ -807,8 +807,8 @@ class AddTorrentDialog(component.Component): (model, row) = self.listview_torrents.get_selection().get_selected() torrent_id = model[row][0] - if "mapped_files" not in self.options[torrent_id]: - self.options[torrent_id]["mapped_files"] = {} + if 'mapped_files' not in self.options[torrent_id]: + self.options[torrent_id]['mapped_files'] = {} if index > -1: # We're renaming a file! Yay! That's easy! @@ -838,7 +838,7 @@ class AddTorrentDialog(component.Component): # file path. # We'll send this to the core when adding the torrent so it knows # what to rename before adding. - self.options[torrent_id]["mapped_files"][index] = file_path + self.options[torrent_id]['mapped_files'][index] = file_path self.files[torrent_id][index]['path'] = file_path else: # Folder! @@ -865,7 +865,7 @@ class AddTorrentDialog(component.Component): file_path = file_path_base + self.files_treestore[row][1] # Update the file path in the mapped_files dict - self.options[torrent_id]["mapped_files"][index] = file_path + self.options[torrent_id]['mapped_files'][index] = file_path self.files[torrent_id][index]['path'] = file_path # Get the next siblings iter @@ -895,7 +895,7 @@ class AddTorrentDialog(component.Component): # We need to re-expand the view because it might contracted # if we change the root iter - self.listview_files.expand_row("0", False) + self.listview_files.expand_row('0', False) else: # This was a simple folder rename without any splits, so just # change the path for itr diff --git a/deluge/ui/gtkui/common.py b/deluge/ui/gtkui/common.py index 39637c332..152a06c3e 100644 --- a/deluge/ui/gtkui/common.py +++ b/deluge/ui/gtkui/common.py @@ -36,9 +36,9 @@ def get_logo(size): Returns: gtk.gdk.Pixbuf: deluge logo """ - filename = "deluge.svg" + filename = 'deluge.svg' if deluge.common.windows_check() or deluge.common.osx_check(): - filename = "deluge.png" + filename = 'deluge.png' try: return gtk.gdk.pixbuf_new_from_file_at_size(deluge.common.get_pixmap(filename), size, size) except GError as ex: @@ -46,7 +46,7 @@ def get_logo(size): def build_menu_radio_list(value_list, callback, pref_value=None, suffix=None, show_notset=False, - notset_label="∞", notset_lessthan=0, show_other=False): + notset_label='∞', notset_lessthan=0, show_other=False): """Build a menu with radio menu items from a list and connect them to the callback. Params: @@ -74,29 +74,29 @@ def build_menu_radio_list(value_list, callback, pref_value=None, suffix=None, sh for value in sorted(value_list): item_text = str(value) if suffix: - item_text += " " + suffix + item_text += ' ' + suffix menuitem = gtk.RadioMenuItem(group, item_text) group = menuitem if pref_value and value == pref_value: menuitem.set_active(True) if callback: - menuitem.connect("toggled", callback) + menuitem.connect('toggled', callback) menu.append(menuitem) if show_notset: menuitem = gtk.RadioMenuItem(group, notset_label) - menuitem.set_name("unlimited") + menuitem.set_name('unlimited') if pref_value and pref_value < notset_lessthan: menuitem.set_active(True) - menuitem.connect("toggled", callback) + menuitem.connect('toggled', callback) menu.append(menuitem) if show_other: menuitem = gtk.SeparatorMenuItem() menu.append(menuitem) - menuitem = gtk.MenuItem(_("Other...")) - menuitem.set_name("other") - menuitem.connect("activate", callback) + menuitem = gtk.MenuItem(_('Other...')) + menuitem.set_name('other') + menuitem.connect('activate', callback) menu.append(menuitem) return menu @@ -144,7 +144,7 @@ def get_deluge_icon(): else: try: icon_theme = gtk.icon_theme_get_default() - return icon_theme.load_icon("deluge", 64, 0) + return icon_theme.load_icon('deluge', 64, 0) except GError: return get_logo(64) @@ -164,25 +164,25 @@ def associate_magnet_links(overwrite=False): import _winreg try: - hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, "Magnet") + hkey = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, 'Magnet') except WindowsError: # pylint: disable=undefined-variable overwrite = True else: _winreg.CloseKey(hkey) if overwrite: - deluge_exe = os.path.join(os.path.dirname(sys.executable), "deluge.exe") + deluge_exe = os.path.join(os.path.dirname(sys.executable), 'deluge.exe') try: - magnet_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, "Magnet") + magnet_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT, 'Magnet') except WindowsError: # pylint: disable=undefined-variable # Could not create for all users, falling back to current user - magnet_key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, "Software\\Classes\\Magnet") + magnet_key = _winreg.CreateKey(_winreg.HKEY_CURRENT_USER, 'Software\\Classes\\Magnet') - _winreg.SetValue(magnet_key, "", _winreg.REG_SZ, "URL:Magnet Protocol") - _winreg.SetValueEx(magnet_key, "URL Protocol", 0, _winreg.REG_SZ, "") - _winreg.SetValueEx(magnet_key, "BrowserFlags", 0, _winreg.REG_DWORD, 0x8) - _winreg.SetValue(magnet_key, "DefaultIcon", _winreg.REG_SZ, "{},0".format(deluge_exe)) - _winreg.SetValue(magnet_key, r"shell\open\command", _winreg.REG_SZ, '"{}" "%1"'.format(deluge_exe)) + _winreg.SetValue(magnet_key, '', _winreg.REG_SZ, 'URL:Magnet Protocol') + _winreg.SetValueEx(magnet_key, 'URL Protocol', 0, _winreg.REG_SZ, '') + _winreg.SetValueEx(magnet_key, 'BrowserFlags', 0, _winreg.REG_DWORD, 0x8) + _winreg.SetValue(magnet_key, 'DefaultIcon', _winreg.REG_SZ, '{},0'.format(deluge_exe)) + _winreg.SetValue(magnet_key, r'shell\open\command', _winreg.REG_SZ, '"{}" "%1"'.format(deluge_exe)) _winreg.CloseKey(magnet_key) # Don't try associate magnet on OSX see: #2420 @@ -191,20 +191,20 @@ def associate_magnet_links(overwrite=False): try: import gconf except ImportError: - log.debug("gconf not available, so will not attempt to register magnet uri handler") + log.debug('gconf not available, so will not attempt to register magnet uri handler') return False else: - key = "/desktop/gnome/url-handlers/magnet/command" + key = '/desktop/gnome/url-handlers/magnet/command' gconf_client = gconf.client_get_default() if (gconf_client.get(key) and overwrite) or not gconf_client.get(key): # We are either going to overwrite the key, or do it if it hasn't been set yet if gconf_client.set_string(key, "deluge '%s'"): - gconf_client.set_bool("/desktop/gnome/url-handlers/magnet/needs_terminal", False) - gconf_client.set_bool("/desktop/gnome/url-handlers/magnet/enabled", True) - log.info("Deluge registered as default magnet uri handler!") + gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/needs_terminal', False) + gconf_client.set_bool('/desktop/gnome/url-handlers/magnet/enabled', True) + log.info('Deluge registered as default magnet uri handler!') return True else: - log.error("Unable to register Deluge as default magnet uri handler.") + log.error('Unable to register Deluge as default magnet uri handler.') return False return False @@ -217,29 +217,29 @@ def save_pickled_state_file(filename, state): state (state): The data to be pickled and written to file """ from deluge.configmanager import get_config_dir - filepath = os.path.join(get_config_dir(), "gtkui_state", filename) - filepath_bak = filepath + ".bak" - filepath_tmp = filepath + ".tmp" + filepath = os.path.join(get_config_dir(), 'gtkui_state', filename) + filepath_bak = filepath + '.bak' + filepath_tmp = filepath + '.tmp' try: if os.path.isfile(filepath): - log.debug("Creating backup of %s at: %s", filename, filepath_bak) + log.debug('Creating backup of %s at: %s', filename, filepath_bak) shutil.copy2(filepath, filepath_bak) except IOError as ex: - log.error("Unable to backup %s to %s: %s", filepath, filepath_bak, ex) + log.error('Unable to backup %s to %s: %s', filepath, filepath_bak, ex) else: - log.info("Saving the %s at: %s", filename, filepath) + log.info('Saving the %s at: %s', filename, filepath) try: - with open(filepath_tmp, "wb") as _file: + with open(filepath_tmp, 'wb') as _file: # Pickle the state object cPickle.dump(state, _file) _file.flush() os.fsync(_file.fileno()) shutil.move(filepath_tmp, filepath) except (IOError, EOFError, cPickle.PicklingError) as ex: - log.error("Unable to save %s: %s", filename, ex) + log.error('Unable to save %s: %s', filename, ex) if os.path.isfile(filepath_bak): - log.info("Restoring backup of %s from: %s", filename, filepath_bak) + log.info('Restoring backup of %s from: %s', filename, filepath_bak) shutil.move(filepath_bak, filepath) @@ -253,19 +253,19 @@ def load_pickled_state_file(filename): state: the unpickled state """ from deluge.configmanager import get_config_dir - filepath = os.path.join(get_config_dir(), "gtkui_state", filename) - filepath_bak = filepath + ".bak" + filepath = os.path.join(get_config_dir(), 'gtkui_state', filename) + filepath_bak = filepath + '.bak' old_data_filepath = os.path.join(get_config_dir(), filename) for _filepath in (filepath, filepath_bak, old_data_filepath): - log.info("Opening %s for load: %s", filename, _filepath) + log.info('Opening %s for load: %s', filename, _filepath) try: - with open(_filepath, "rb") as _file: + with open(_filepath, 'rb') as _file: state = cPickle.load(_file) except (IOError, cPickle.UnpicklingError) as ex: - log.warning("Unable to load %s: %s", _filepath, ex) + log.warning('Unable to load %s: %s', _filepath, ex) else: - log.info("Successfully loaded %s: %s", filename, _filepath) + log.info('Successfully loaded %s: %s', filename, _filepath) return state diff --git a/deluge/ui/gtkui/connectionmanager.py b/deluge/ui/gtkui/connectionmanager.py index 383336141..89c08ceca 100644 --- a/deluge/ui/gtkui/connectionmanager.py +++ b/deluge/ui/gtkui/connectionmanager.py @@ -27,7 +27,7 @@ from deluge.ui.gtkui.dialogs import AuthenticationDialog, ErrorDialog log = logging.getLogger(__name__) -DEFAULT_HOST = "127.0.0.1" +DEFAULT_HOST = '127.0.0.1' DEFAULT_PORT = 58846 HOSTLIST_COL_ID = 0 @@ -44,17 +44,17 @@ HOSTLIST_PIXBUFS = [ ] HOSTLIST_STATUS = [ - "Offline", - "Online", - "Connected" + 'Offline', + 'Online', + 'Connected' ] def cell_render_host(column, cell, model, row, data): host, port, username = model.get(row, *data) - text = host + ":" + str(port) + text = host + ':' + str(port) if username: - text = username + "@" + text + text = username + '@' + text cell.set_property('text', text) @@ -64,13 +64,13 @@ def cell_render_status(column, cell, model, row, data): if status in HOSTLIST_STATUS: pixbuf = HOSTLIST_PIXBUFS[HOSTLIST_STATUS.index(status)] - cell.set_property("pixbuf", pixbuf) + cell.set_property('pixbuf', pixbuf) class ConnectionManager(component.Component): def __init__(self): - component.Component.__init__(self, "ConnectionManager") - self.gtkui_config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'ConnectionManager') + self.gtkui_config = ConfigManager('gtkui.conf') self.config = self.__load_config() self.running = False @@ -87,14 +87,14 @@ class ConnectionManager(component.Component): pass def __load_config(self): - auth_file = get_config_dir("auth") + auth_file = get_config_dir('auth') if not os.path.exists(auth_file): from deluge.common import create_localclient_account create_localclient_account() localclient_username, localclient_password = get_localhost_auth() default_config = { - "hosts": [( + 'hosts': [( hashlib.sha1(str(time.time())).hexdigest(), DEFAULT_HOST, DEFAULT_PORT, @@ -102,7 +102,7 @@ class ConnectionManager(component.Component): localclient_password )] } - config = ConfigManager("hostlist.conf.1.2", defaults=default_config, file_version=2) + config = ConfigManager('hostlist.conf.1.2', defaults=default_config, file_version=2) config.run_converter((0, 1), 2, self.__migrate_config_1_to_2) return config @@ -116,32 +116,32 @@ class ConnectionManager(component.Component): self.builder = gtk.Builder() # The main dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "connection_manager.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.ui') )) # The add host dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "connection_manager.addhost.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.addhost.ui') )) # The ask password dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "connection_manager.askpassword.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'connection_manager.askpassword.ui') )) - self.window = component.get("MainWindow") + self.window = component.get('MainWindow') # Setup the ConnectionManager dialog - self.connection_manager = self.builder.get_object("connection_manager") + self.connection_manager = self.builder.get_object('connection_manager') self.connection_manager.set_transient_for(self.window.window) self.connection_manager.set_icon(get_deluge_icon()) - self.builder.get_object("image1").set_from_pixbuf(get_logo(32)) + self.builder.get_object('image1').set_from_pixbuf(get_logo(32)) - self.askpassword_dialog = self.builder.get_object("askpassword_dialog") + self.askpassword_dialog = self.builder.get_object('askpassword_dialog') self.askpassword_dialog.set_transient_for(self.connection_manager) self.askpassword_dialog.set_icon(get_deluge_icon()) - self.askpassword_dialog_entry = self.builder.get_object("askpassword_dialog_entry") + self.askpassword_dialog_entry = self.builder.get_object('askpassword_dialog_entry') - self.hostlist = self.builder.get_object("hostlist") + self.hostlist = self.builder.get_object('hostlist') # Create status pixbufs if not HOSTLIST_PIXBUFS: @@ -159,22 +159,22 @@ class ConnectionManager(component.Component): # Setup host list treeview self.hostlist.set_model(self.liststore) render = gtk.CellRendererPixbuf() - column = gtk.TreeViewColumn(_("Status"), render) + column = gtk.TreeViewColumn(_('Status'), render) column.set_cell_data_func(render, cell_render_status, 3) self.hostlist.append_column(column) render = gtk.CellRendererText() - column = gtk.TreeViewColumn(_("Host"), render, text=HOSTLIST_COL_HOST) + column = gtk.TreeViewColumn(_('Host'), render, text=HOSTLIST_COL_HOST) column.set_cell_data_func(render, cell_render_host, (1, 2, 4)) column.set_expand(True) self.hostlist.append_column(column) render = gtk.CellRendererText() - column = gtk.TreeViewColumn(_("Version"), render, text=HOSTLIST_COL_VERSION) + column = gtk.TreeViewColumn(_('Version'), render, text=HOSTLIST_COL_VERSION) self.hostlist.append_column(column) # Connect the signals to the handlers self.builder.connect_signals(self) self.hostlist.get_selection().connect( - "changed", self.on_hostlist_selection_changed + 'changed', self.on_hostlist_selection_changed ) # Load any saved host entries @@ -187,7 +187,7 @@ class ConnectionManager(component.Component): # if possible self.hostlist.get_selection().unselect_all() if len(self.liststore) > 0: - self.hostlist.get_selection().select_path("0") + self.hostlist.get_selection().select_path('0') # Run the dialog self.connection_manager.run() @@ -204,7 +204,7 @@ class ConnectionManager(component.Component): del self.liststore del self.hostlist - def add_host(self, host, port, username="", password=""): + def add_host(self, host, port, username='', password=''): """ Adds a host to the list. @@ -218,7 +218,7 @@ class ConnectionManager(component.Component): # if thats the case for entry in self.liststore: if [entry[HOSTLIST_COL_HOST], entry[HOSTLIST_COL_PORT], entry[HOSTLIST_COL_USER]] == [host, port, username]: - raise Exception("Host already in list!") + raise Exception('Host already in list!') # Host isn't in the list, so lets add it row = self.liststore.append() @@ -227,7 +227,7 @@ class ConnectionManager(component.Component): self.liststore[row][HOSTLIST_COL_PORT] = port self.liststore[row][HOSTLIST_COL_USER] = username self.liststore[row][HOSTLIST_COL_PASS] = password - self.liststore[row][HOSTLIST_COL_STATUS] = "Offline" + self.liststore[row][HOSTLIST_COL_STATUS] = 'Offline' # Save the host list to file self.__save_hostlist() @@ -241,9 +241,9 @@ class ConnectionManager(component.Component): Save the current hostlist to the config file. """ # Grab the hosts from the liststore - self.config["hosts"] = [] + self.config['hosts'] = [] for row in self.liststore: - self.config["hosts"].append((row[HOSTLIST_COL_ID], + self.config['hosts'].append((row[HOSTLIST_COL_ID], row[HOSTLIST_COL_HOST], row[HOSTLIST_COL_PORT], row[HOSTLIST_COL_USER], @@ -255,15 +255,15 @@ class ConnectionManager(component.Component): """ Load saved host entries """ - for host in self.config["hosts"]: + for host in self.config['hosts']: new_row = self.liststore.append() self.liststore[new_row][HOSTLIST_COL_ID] = host[0] self.liststore[new_row][HOSTLIST_COL_HOST] = host[1] self.liststore[new_row][HOSTLIST_COL_PORT] = host[2] self.liststore[new_row][HOSTLIST_COL_USER] = host[3] self.liststore[new_row][HOSTLIST_COL_PASS] = host[4] - self.liststore[new_row][HOSTLIST_COL_STATUS] = "Offline" - self.liststore[new_row][HOSTLIST_COL_VERSION] = "" + self.liststore[new_row][HOSTLIST_COL_STATUS] = 'Offline' + self.liststore[new_row][HOSTLIST_COL_VERSION] = '' def __get_host_row(self, host_id): """ @@ -277,7 +277,7 @@ class ConnectionManager(component.Component): def __update_list(self): """Updates the host status""" - if not hasattr(self, "liststore"): + if not hasattr(self, 'liststore'): # This callback was probably fired after the window closed return @@ -291,7 +291,7 @@ class ConnectionManager(component.Component): if not self.running: return if row: - row[HOSTLIST_COL_STATUS] = "Online" + row[HOSTLIST_COL_STATUS] = 'Online' row[HOSTLIST_COL_VERSION] = info self.__update_buttons() c.disconnect() @@ -300,7 +300,7 @@ class ConnectionManager(component.Component): if not self.running: return if row: - row[HOSTLIST_COL_STATUS] = "Offline" + row[HOSTLIST_COL_STATUS] = 'Offline' self.__update_buttons() c.disconnect() @@ -313,8 +313,8 @@ class ConnectionManager(component.Component): return row = self.__get_host_row(host_id) if row: - row[HOSTLIST_COL_STATUS] = "Offline" - row[HOSTLIST_COL_VERSION] = "" + row[HOSTLIST_COL_STATUS] = 'Offline' + row[HOSTLIST_COL_VERSION] = '' self.__update_buttons() for row in self.liststore: @@ -326,16 +326,16 @@ class ConnectionManager(component.Component): if client.connected() and ( gethostbyname(host), port, - "localclient" if not user and host in ("127.0.0.1", "localhost") else user + 'localclient' if not user and host in ('127.0.0.1', 'localhost') else user ) == client.connection_info(): def on_info(info, row): if not self.running: return - log.debug("Client connected, query info: %s", info) + log.debug('Client connected, query info: %s', info) row[HOSTLIST_COL_VERSION] = info self.__update_buttons() - row[HOSTLIST_COL_STATUS] = "Connected" + row[HOSTLIST_COL_STATUS] = 'Connected' log.debug("Query daemon's info") client.daemon.info().addCallback(on_info, row) continue @@ -350,24 +350,24 @@ class ConnectionManager(component.Component): """ Set the widgets to show the correct options from the config. """ - self.builder.get_object("chk_autoconnect").set_active( - self.gtkui_config["autoconnect"] + self.builder.get_object('chk_autoconnect').set_active( + self.gtkui_config['autoconnect'] ) - self.builder.get_object("chk_autostart").set_active( - self.gtkui_config["autostart_localhost"] + self.builder.get_object('chk_autostart').set_active( + self.gtkui_config['autostart_localhost'] ) - self.builder.get_object("chk_donotshow").set_active( - not self.gtkui_config["show_connection_manager_on_start"] + self.builder.get_object('chk_donotshow').set_active( + not self.gtkui_config['show_connection_manager_on_start'] ) def __save_options(self): """ Set options in gtkui config from the toggle buttons. """ - self.gtkui_config["autoconnect"] = self.builder.get_object("chk_autoconnect").get_active() - self.gtkui_config["autostart_localhost"] = self.builder.get_object("chk_autostart").get_active() - self.gtkui_config["show_connection_manager_on_start"] = not self.builder.get_object( - "chk_donotshow").get_active() + self.gtkui_config['autoconnect'] = self.builder.get_object('chk_autoconnect').get_active() + self.gtkui_config['autostart_localhost'] = self.builder.get_object('chk_autostart').get_active() + self.gtkui_config['show_connection_manager_on_start'] = not self.builder.get_object( + 'chk_donotshow').get_active() def __update_buttons(self): """ @@ -375,19 +375,19 @@ class ConnectionManager(component.Component): """ if len(self.liststore) == 0: # There is nothing in the list - self.builder.get_object("button_startdaemon").set_sensitive(True) - self.builder.get_object("button_connect").set_sensitive(False) - self.builder.get_object("button_removehost").set_sensitive(False) - self.builder.get_object("image_startdaemon").set_from_stock( + self.builder.get_object('button_startdaemon').set_sensitive(True) + self.builder.get_object('button_connect').set_sensitive(False) + self.builder.get_object('button_removehost').set_sensitive(False) + self.builder.get_object('image_startdaemon').set_from_stock( gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU) - self.builder.get_object("label_startdaemon").set_text("_Start Daemon") + self.builder.get_object('label_startdaemon').set_text('_Start Daemon') model, row = self.hostlist.get_selection().get_selected() if not row: - self.builder.get_object("button_edithost").set_sensitive(False) + self.builder.get_object('button_edithost').set_sensitive(False) return - self.builder.get_object("button_edithost").set_sensitive(True) + self.builder.get_object('button_edithost').set_sensitive(True) # Get some values about the selected host status = model[row][HOSTLIST_COL_STATUS] @@ -396,54 +396,54 @@ class ConnectionManager(component.Component): user = model[row][HOSTLIST_COL_USER] passwd = model[row][HOSTLIST_COL_PASS] - log.debug("Status: %s", status) + log.debug('Status: %s', status) # Check to see if we have a localhost entry selected localhost = False - if host in ("127.0.0.1", "localhost"): + if host in ('127.0.0.1', 'localhost'): localhost = True # Make sure buttons are sensitive at start - self.builder.get_object("button_startdaemon").set_sensitive(True) - self.builder.get_object("button_connect").set_sensitive(True) - self.builder.get_object("button_removehost").set_sensitive(True) + self.builder.get_object('button_startdaemon').set_sensitive(True) + self.builder.get_object('button_connect').set_sensitive(True) + self.builder.get_object('button_removehost').set_sensitive(True) # See if this is the currently connected host - if status == "Connected": + if status == 'Connected': # Display a disconnect button if we're connected to this host - self.builder.get_object("button_connect").set_label("gtk-disconnect") - self.builder.get_object("button_removehost").set_sensitive(False) + self.builder.get_object('button_connect').set_label('gtk-disconnect') + self.builder.get_object('button_removehost').set_sensitive(False) else: - self.builder.get_object("button_connect").set_label("gtk-connect") - if status == "Offline" and not localhost: - self.builder.get_object("button_connect").set_sensitive(False) + self.builder.get_object('button_connect').set_label('gtk-connect') + if status == 'Offline' and not localhost: + self.builder.get_object('button_connect').set_sensitive(False) # Check to see if the host is online - if status == "Connected" or status == "Online": - self.builder.get_object("image_startdaemon").set_from_stock( + if status == 'Connected' or status == 'Online': + self.builder.get_object('image_startdaemon').set_from_stock( gtk.STOCK_STOP, gtk.ICON_SIZE_MENU) - self.builder.get_object("label_startdaemon").set_text( - _("_Stop Daemon")) + self.builder.get_object('label_startdaemon').set_text( + _('_Stop Daemon')) # Update the start daemon button if the selected host is localhost - if localhost and status == "Offline": + if localhost and status == 'Offline': # The localhost is not online - self.builder.get_object("image_startdaemon").set_from_stock( + self.builder.get_object('image_startdaemon').set_from_stock( gtk.STOCK_EXECUTE, gtk.ICON_SIZE_MENU) - self.builder.get_object("label_startdaemon").set_text( - _("_Start Daemon")) + self.builder.get_object('label_startdaemon').set_text( + _('_Start Daemon')) if client.connected() and (host, port, user) == client.connection_info(): # If we're connected, we can stop the dameon - self.builder.get_object("button_startdaemon").set_sensitive(True) + self.builder.get_object('button_startdaemon').set_sensitive(True) elif user and passwd: # In this case we also have all the info to shutdown the daemon - self.builder.get_object("button_startdaemon").set_sensitive(True) + self.builder.get_object('button_startdaemon').set_sensitive(True) else: # Can't stop non localhost daemons, specially without the necessary info - self.builder.get_object("button_startdaemon").set_sensitive(False) + self.builder.get_object('button_startdaemon').set_sensitive(False) # Make sure label is displayed correctly using mnemonics - self.builder.get_object("label_startdaemon").set_use_underline(True) + self.builder.get_object('label_startdaemon').set_use_underline(True) def start_daemon(self, port, config): """ @@ -456,9 +456,9 @@ class ConnectionManager(component.Component): from errno import ENOENT if ex.errno == ENOENT: ErrorDialog( - _("Unable to start daemon!"), + _('Unable to start daemon!'), _("Deluge cannot find the 'deluged' executable, it is " - "likely that you forgot to install the deluged package " + 'likely that you forgot to install the deluged package ' "or it's not in your PATH.")).run() return False else: @@ -468,8 +468,8 @@ class ConnectionManager(component.Component): import sys tb = sys.exc_info() ErrorDialog( - _("Unable to start daemon!"), - _("Please examine the details for more information."), + _('Unable to start daemon!'), + _('Please examine the details for more information.'), details=traceback.format_exc(tb[2])).run() # Signal handlers @@ -488,8 +488,8 @@ class ConnectionManager(component.Component): return do_connect() def __on_connected(self, daemon_info, host_id): - if self.gtkui_config["autoconnect"]: - self.gtkui_config["autoconnect_host_id"] = host_id + if self.gtkui_config['autoconnect']: + self.gtkui_config['autoconnect_host_id'] = host_id if self.running: # When connected to a client, and then trying to connect to another, # this component will be stopped(while the connect deferred is @@ -500,10 +500,10 @@ class ConnectionManager(component.Component): def __on_connected_failed(self, reason, host_id, host, port, user, passwd, try_counter): - log.debug("Failed to connect: %s", reason.value) + log.debug('Failed to connect: %s', reason.value) if reason.check(AuthenticationRequired, BadLoginError): - log.debug("PasswordRequired exception") + log.debug('PasswordRequired exception') dialog = AuthenticationDialog(reason.value.message, reason.value.username) def dialog_finished(response_id, host, port, user): @@ -516,29 +516,29 @@ class ConnectionManager(component.Component): elif reason.trap(IncompatibleClient): dialog = ErrorDialog( - _("Incompatible Client"), reason.value.message + _('Incompatible Client'), reason.value.message ) return dialog.run() if try_counter: - log.info("Retrying connection.. Retries left: %s", try_counter) + log.info('Retrying connection.. Retries left: %s', try_counter) return reactor.callLater( 0.5, self.__connect, host_id, host, port, user, passwd, try_counter=try_counter - 1 ) msg = str(reason.value) - if not self.builder.get_object("chk_autostart").get_active(): - msg += '\n' + _("Auto-starting the daemon locally is not enabled. " + if not self.builder.get_object('chk_autostart').get_active(): + msg += '\n' + _('Auto-starting the daemon locally is not enabled. ' "See \"Options\" on the \"Connection Manager\".") - ErrorDialog(_("Failed To Connect"), msg).run() + ErrorDialog(_('Failed To Connect'), msg).run() def on_button_connect_clicked(self, widget=None): model, row = self.hostlist.get_selection().get_selected() if not row: return status = model[row][HOSTLIST_COL_STATUS] - if status == "Connected": + if status == 'Connected': def on_disconnect(reason): self.__update_list() client.disconnect().addCallback(on_disconnect) @@ -550,10 +550,10 @@ class ConnectionManager(component.Component): user = model[row][HOSTLIST_COL_USER] password = model[row][HOSTLIST_COL_PASS] - if (status == "Offline" and self.builder.get_object("chk_autostart").get_active() and - host in ("127.0.0.1", "localhost")): + if (status == 'Offline' and self.builder.get_object('chk_autostart').get_active() and + host in ('127.0.0.1', 'localhost')): if not self.start_daemon(port, get_config_dir()): - log.debug("Failed to auto-start daemon") + log.debug('Failed to auto-start daemon') return return self.__connect( host_id, host, port, user, password, try_counter=6 @@ -564,17 +564,17 @@ class ConnectionManager(component.Component): self.connection_manager.response(gtk.RESPONSE_CLOSE) def on_button_addhost_clicked(self, widget): - log.debug("on_button_addhost_clicked") - dialog = self.builder.get_object("addhost_dialog") + log.debug('on_button_addhost_clicked') + dialog = self.builder.get_object('addhost_dialog') dialog.set_transient_for(self.connection_manager) dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT) - hostname_entry = self.builder.get_object("entry_hostname") - port_spinbutton = self.builder.get_object("spinbutton_port") - username_entry = self.builder.get_object("entry_username") - password_entry = self.builder.get_object("entry_password") - button_addhost_save = self.builder.get_object("button_addhost_save") + hostname_entry = self.builder.get_object('entry_hostname') + port_spinbutton = self.builder.get_object('spinbutton_port') + username_entry = self.builder.get_object('entry_username') + password_entry = self.builder.get_object('entry_password') + button_addhost_save = self.builder.get_object('button_addhost_save') button_addhost_save.hide() - button_addhost_add = self.builder.get_object("button_addhost_add") + button_addhost_add = self.builder.get_object('button_addhost_add') button_addhost_add.show() response = dialog.run() if response == 1: @@ -582,7 +582,7 @@ class ConnectionManager(component.Component): password = password_entry.get_text() hostname = hostname_entry.get_text() - if (not password and not username or username == "localclient") and hostname in ["127.0.0.1", "localhost"]: + if (not password and not username or username == 'localclient') and hostname in ['127.0.0.1', 'localhost']: username, password = get_localhost_auth() # We add the host @@ -590,34 +590,34 @@ class ConnectionManager(component.Component): self.add_host(hostname, port_spinbutton.get_value_as_int(), username, password) except Exception as ex: - ErrorDialog(_("Error Adding Host"), ex).run() + ErrorDialog(_('Error Adding Host'), ex).run() - username_entry.set_text("") - password_entry.set_text("") - hostname_entry.set_text("") + username_entry.set_text('') + password_entry.set_text('') + hostname_entry.set_text('') port_spinbutton.set_value(58846) dialog.hide() def on_button_edithost_clicked(self, widget=None): - log.debug("on_button_edithost_clicked") + log.debug('on_button_edithost_clicked') model, row = self.hostlist.get_selection().get_selected() status = model[row][HOSTLIST_COL_STATUS] - if status == "Connected": + if status == 'Connected': def on_disconnect(reason): self.__update_list() client.disconnect().addCallback(on_disconnect) return - dialog = self.builder.get_object("addhost_dialog") + dialog = self.builder.get_object('addhost_dialog') dialog.set_transient_for(self.connection_manager) dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT) - hostname_entry = self.builder.get_object("entry_hostname") - port_spinbutton = self.builder.get_object("spinbutton_port") - username_entry = self.builder.get_object("entry_username") - password_entry = self.builder.get_object("entry_password") - button_addhost_save = self.builder.get_object("button_addhost_save") + hostname_entry = self.builder.get_object('entry_hostname') + port_spinbutton = self.builder.get_object('spinbutton_port') + username_entry = self.builder.get_object('entry_username') + password_entry = self.builder.get_object('entry_password') + button_addhost_save = self.builder.get_object('button_addhost_save') button_addhost_save.show() - button_addhost_add = self.builder.get_object("button_addhost_add") + button_addhost_add = self.builder.get_object('button_addhost_add') button_addhost_add.hide() username_entry.set_text(self.liststore[row][HOSTLIST_COL_USER]) @@ -632,14 +632,14 @@ class ConnectionManager(component.Component): password = password_entry.get_text() hostname = hostname_entry.get_text() - if (not password and not username or username == "localclient") and hostname in ["127.0.0.1", "localhost"]: + if (not password and not username or username == 'localclient') and hostname in ['127.0.0.1', 'localhost']: username, password = get_localhost_auth() self.liststore[row][HOSTLIST_COL_HOST] = hostname self.liststore[row][HOSTLIST_COL_PORT] = port_spinbutton.get_value_as_int() self.liststore[row][HOSTLIST_COL_USER] = username self.liststore[row][HOSTLIST_COL_PASS] = password - self.liststore[row][HOSTLIST_COL_STATUS] = "Offline" + self.liststore[row][HOSTLIST_COL_STATUS] = 'Offline' # Save the host list to file self.__save_hostlist() @@ -647,14 +647,14 @@ class ConnectionManager(component.Component): # Update the status of the hosts self.__update_list() - username_entry.set_text("") - password_entry.set_text("") - hostname_entry.set_text("") + username_entry.set_text('') + password_entry.set_text('') + hostname_entry.set_text('') port_spinbutton.set_value(58846) dialog.hide() def on_button_removehost_clicked(self, widget): - log.debug("on_button_removehost_clicked") + log.debug('on_button_removehost_clicked') # Get the selected rows paths = self.hostlist.get_selection().get_selected_rows()[1] for path in paths: @@ -667,7 +667,7 @@ class ConnectionManager(component.Component): self.__save_hostlist() def on_button_startdaemon_clicked(self, widget): - log.debug("on_button_startdaemon_clicked") + log.debug('on_button_startdaemon_clicked') if self.liststore.iter_n_children(None) < 1: # There is nothing in the list, so lets create a localhost entry self.add_host(DEFAULT_HOST, DEFAULT_PORT, *get_localhost_auth()) @@ -687,10 +687,10 @@ class ConnectionManager(component.Component): user = self.liststore[paths[0]][HOSTLIST_COL_USER] password = self.liststore[paths[0]][HOSTLIST_COL_PASS] - if host not in ("127.0.0.1", "localhost"): + if host not in ('127.0.0.1', 'localhost'): return - if status in ("Online", "Connected"): + if status in ('Online', 'Connected'): # We need to stop this daemon # Call the shutdown method on the daemon def on_daemon_shutdown(d): @@ -703,12 +703,12 @@ class ConnectionManager(component.Component): c = Client() def on_connect(d, c): - log.debug("on_connect") + log.debug('on_connect') c.daemon.shutdown().addCallback(on_daemon_shutdown) c.connect(host, port, user, password).addCallback(on_connect, c) - elif status == "Offline": + elif status == 'Offline': self.start_daemon(port, get_config_dir()) reactor.callLater(0.8, self.__update_list) @@ -722,7 +722,7 @@ class ConnectionManager(component.Component): self.__update_buttons() def on_askpassword_dialog_connect_button_clicked(self, widget): - log.debug("on on_askpassword_dialog_connect_button_clicked") + log.debug('on on_askpassword_dialog_connect_button_clicked') self.askpassword_dialog.response(gtk.RESPONSE_OK) def on_askpassword_dialog_entry_activate(self, entry): @@ -733,9 +733,9 @@ class ConnectionManager(component.Component): if not localclient_username: # Nothing to do here, there's no auth file return - for idx, (_, host, _, username, _) in enumerate(config["hosts"][:]): - if host in ("127.0.0.1", "localhost"): + for idx, (_, host, _, username, _) in enumerate(config['hosts'][:]): + if host in ('127.0.0.1', 'localhost'): if not username: - config["hosts"][idx][3] = localclient_username - config["hosts"][idx][4] = localclient_password + config['hosts'][idx][3] = localclient_username + config['hosts'][idx][4] = localclient_password return config diff --git a/deluge/ui/gtkui/createtorrentdialog.py b/deluge/ui/gtkui/createtorrentdialog.py index 596f73579..9734b3fc5 100644 --- a/deluge/ui/gtkui/createtorrentdialog.py +++ b/deluge/ui/gtkui/createtorrentdialog.py @@ -36,75 +36,75 @@ class CreateTorrentDialog(object): # The main dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "create_torrent_dialog.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.ui') )) # The remote path dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "create_torrent_dialog.remote_path.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_path.ui') )) # The remote save dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "create_torrent_dialog.remote_save.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.remote_save.ui') )) # The progress dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "create_torrent_dialog.progress.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'create_torrent_dialog.progress.ui') )) - self.config = ConfigManager("gtkui.conf") + self.config = ConfigManager('gtkui.conf') - self.dialog = self.builder.get_object("create_torrent_dialog") - self.dialog.set_transient_for(component.get("MainWindow").window) + self.dialog = self.builder.get_object('create_torrent_dialog') + self.dialog.set_transient_for(component.get('MainWindow').window) self.builder.connect_signals({ - "on_button_file_clicked": self._on_button_file_clicked, - "on_button_folder_clicked": self._on_button_folder_clicked, - "on_button_remote_path_clicked": self._on_button_remote_path_clicked, - "on_button_cancel_clicked": self._on_button_cancel_clicked, - "on_button_save_clicked": self._on_button_save_clicked, - "on_button_up_clicked": self._on_button_up_clicked, - "on_button_add_clicked": self._on_button_add_clicked, - "on_button_remove_clicked": self._on_button_remove_clicked, - "on_button_down_clicked": self._on_button_down_clicked + 'on_button_file_clicked': self._on_button_file_clicked, + 'on_button_folder_clicked': self._on_button_folder_clicked, + 'on_button_remote_path_clicked': self._on_button_remote_path_clicked, + 'on_button_cancel_clicked': self._on_button_cancel_clicked, + 'on_button_save_clicked': self._on_button_save_clicked, + 'on_button_up_clicked': self._on_button_up_clicked, + 'on_button_add_clicked': self._on_button_add_clicked, + 'on_button_remove_clicked': self._on_button_remove_clicked, + 'on_button_down_clicked': self._on_button_down_clicked }) # path, icon, size self.files_treestore = gtk.TreeStore(str, str, gobject.TYPE_UINT64) - column = gtk.TreeViewColumn(_("Filename")) + column = gtk.TreeViewColumn(_('Filename')) render = gtk.CellRendererPixbuf() column.pack_start(render, False) - column.add_attribute(render, "stock-id", 1) + column.add_attribute(render, 'stock-id', 1) render = gtk.CellRendererText() column.pack_start(render, True) - column.add_attribute(render, "text", 0) + column.add_attribute(render, 'text', 0) column.set_expand(True) - self.builder.get_object("treeview_files").append_column(column) + self.builder.get_object('treeview_files').append_column(column) - column = gtk.TreeViewColumn(_("Size")) + column = gtk.TreeViewColumn(_('Size')) render = gtk.CellRendererText() column.pack_start(render) column.set_cell_data_func(render, cell_data_size, 2) - self.builder.get_object("treeview_files").append_column(column) + self.builder.get_object('treeview_files').append_column(column) - self.builder.get_object("treeview_files").set_model(self.files_treestore) - self.builder.get_object("treeview_files").set_show_expanders(False) + self.builder.get_object('treeview_files').set_model(self.files_treestore) + self.builder.get_object('treeview_files').set_show_expanders(False) # tier, url self.trackers_liststore = gtk.ListStore(int, str) - self.builder.get_object("tracker_treeview").append_column( - gtk.TreeViewColumn(_("Tier"), gtk.CellRendererText(), text=0)) - self.builder.get_object("tracker_treeview").append_column( - gtk.TreeViewColumn(_("Tracker"), gtk.CellRendererText(), text=1)) + self.builder.get_object('tracker_treeview').append_column( + gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0)) + self.builder.get_object('tracker_treeview').append_column( + gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1)) - self.builder.get_object("tracker_treeview").set_model(self.trackers_liststore) + self.builder.get_object('tracker_treeview').set_model(self.trackers_liststore) self.trackers_liststore.set_sort_column_id(0, gtk.SORT_ASCENDING) if not client.is_localhost() and client.connected(): - self.builder.get_object("button_remote_path").show() + self.builder.get_object('button_remote_path').show() else: - self.builder.get_object("button_remote_path").hide() + self.builder.get_object('button_remote_path').hide() self.dialog.show() @@ -123,18 +123,18 @@ class CreateTorrentDialog(object): def adjust_piece_size(self): """Adjusts the recommended piece based on the file/folder/path selected.""" size = self.files_treestore[0][2] - model = self.builder.get_object("combo_piece_size").get_model() + model = self.builder.get_object('combo_piece_size').get_model() for index, value in enumerate(model): psize = self.parse_piece_size_text(value[0]) pieces = size // psize if pieces < 2048 or (index + 1) == len(model): - self.builder.get_object("combo_piece_size").set_active(index) + self.builder.get_object('combo_piece_size').set_active(index) break def _on_button_file_clicked(self, widget): - log.debug("_on_button_file_clicked") + log.debug('_on_button_file_clicked') # Setup the filechooserdialog - chooser = gtk.FileChooserDialog(_("Choose a file"), + chooser = gtk.FileChooserDialog(_('Choose a file'), self.dialog, gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, @@ -142,7 +142,7 @@ class CreateTorrentDialog(object): chooser.set_transient_for(self.dialog) chooser.set_select_multiple(False) - chooser.set_property("skip-taskbar-hint", True) + chooser.set_property('skip-taskbar-hint', True) # Run the dialog response = chooser.run() @@ -161,9 +161,9 @@ class CreateTorrentDialog(object): chooser.destroy() def _on_button_folder_clicked(self, widget): - log.debug("_on_button_folder_clicked") + log.debug('_on_button_folder_clicked') # Setup the filechooserdialog - chooser = gtk.FileChooserDialog(_("Choose a folder"), + chooser = gtk.FileChooserDialog(_('Choose a folder'), self.dialog, gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, @@ -171,7 +171,7 @@ class CreateTorrentDialog(object): chooser.set_transient_for(self.dialog) chooser.set_select_multiple(False) - chooser.set_property("skip-taskbar-hint", True) + chooser.set_property('skip-taskbar-hint', True) # Run the dialog response = chooser.run() @@ -189,11 +189,11 @@ class CreateTorrentDialog(object): chooser.destroy() def _on_button_remote_path_clicked(self, widget): - log.debug("_on_button_remote_path_clicked") - dialog = self.builder.get_object("remote_path_dialog") - entry = self.builder.get_object("entry_path") + log.debug('_on_button_remote_path_clicked') + dialog = self.builder.get_object('remote_path_dialog') + entry = self.builder.get_object('entry_path') dialog.set_transient_for(self.dialog) - entry.set_text("/") + entry.set_text('/') entry.grab_focus() response = dialog.run() @@ -201,7 +201,7 @@ class CreateTorrentDialog(object): result = entry.get_text() def _on_get_path_size(size): - log.debug("size: %s", size) + log.debug('size: %s', size) if size > 0: self.files_treestore.clear() self.files_treestore.append(None, [result, gtk.STOCK_NETWORK, size]) @@ -212,26 +212,26 @@ class CreateTorrentDialog(object): dialog.hide() def _on_button_cancel_clicked(self, widget): - log.debug("_on_button_cancel_clicked") + log.debug('_on_button_cancel_clicked') self.dialog.destroy() def _on_button_save_clicked(self, widget): - log.debug("_on_button_save_clicked") + log.debug('_on_button_save_clicked') if len(self.files_treestore) == 0: return # Get the path - path = self.files_treestore[0][0].rstrip("\\/") - torrent_filename = "%s.torrent" % os.path.split(path)[-1] + path = self.files_treestore[0][0].rstrip('\\/') + torrent_filename = '%s.torrent' % os.path.split(path)[-1] is_remote = self.files_treestore[0][1] == gtk.STOCK_NETWORK if is_remote: # This is a remote path - dialog = self.builder.get_object("remote_save_dialog") + dialog = self.builder.get_object('remote_save_dialog') dialog.set_transient_for(self.dialog) - dialog_save_path = self.builder.get_object("entry_save_path") - dialog_save_path.set_text(path + ".torrent") + dialog_save_path = self.builder.get_object('entry_save_path') + dialog_save_path.set_text(path + '.torrent') response = dialog.run() if response == gtk.RESPONSE_OK: result = dialog_save_path.get_text() @@ -241,23 +241,23 @@ class CreateTorrentDialog(object): dialog.hide() else: # Setup the filechooserdialog - chooser = gtk.FileChooserDialog(_("Save .torrent file"), self.dialog, + chooser = gtk.FileChooserDialog(_('Save .torrent file'), self.dialog, gtk.FILE_CHOOSER_ACTION_SAVE, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) chooser.set_transient_for(self.dialog) chooser.set_select_multiple(False) - chooser.set_property("skip-taskbar-hint", True) + chooser.set_property('skip-taskbar-hint', True) # Add .torrent and * file filters file_filter = gtk.FileFilter() - file_filter.set_name(_("Torrent files")) - file_filter.add_pattern("*." + "torrent") + file_filter.set_name(_('Torrent files')) + file_filter.add_pattern('*.' + 'torrent') chooser.add_filter(file_filter) file_filter = gtk.FileFilter() - file_filter.set_name(_("All files")) - file_filter.add_pattern("*") + file_filter.set_name(_('All files')) + file_filter.add_pattern('*') chooser.add_filter(file_filter) chooser.set_current_name(torrent_filename) @@ -273,9 +273,9 @@ class CreateTorrentDialog(object): # Fix up torrent filename if len(result) < 9: - result += ".torrent" - elif result[-8:] != ".torrent": - result += ".torrent" + result += '.torrent' + elif result[-8:] != '.torrent': + result += '.torrent' # Get a list of trackers trackers = [] @@ -293,24 +293,24 @@ class CreateTorrentDialog(object): # Get a list of webseeds webseeds = [] - b = self.builder.get_object("textview_webseeds").get_buffer() - lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n") + b = self.builder.get_object('textview_webseeds').get_buffer() + lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n') for l in lines: if is_url(l): webseeds.append(l) # Get the piece length in bytes - combo = self.builder.get_object("combo_piece_size") + combo = self.builder.get_object('combo_piece_size') piece_length = self.parse_piece_size_text(combo.get_model()[combo.get_active()][0]) - author = self.builder.get_object("entry_author").get_text() - comment = self.builder.get_object("entry_comments").get_text() - private = self.builder.get_object("chk_private_flag").get_active() - add_to_session = self.builder.get_object("chk_add_to_session").get_active() + author = self.builder.get_object('entry_author').get_text() + comment = self.builder.get_object('entry_comments').get_text() + private = self.builder.get_object('chk_private_flag').get_active() + add_to_session = self.builder.get_object('chk_add_to_session').get_active() if is_remote: def torrent_created(): - self.builder.get_object("progress_dialog").hide_all() - client.deregister_event_handler("CreateTorrentProgressEvent", on_create_torrent_progress_event) + self.builder.get_object('progress_dialog').hide_all() + client.deregister_event_handler('CreateTorrentProgressEvent', on_create_torrent_progress_event) def on_create_torrent_progress_event(piece_count, num_pieces): self._on_create_torrent_progress(piece_count, num_pieces) @@ -318,7 +318,7 @@ class CreateTorrentDialog(object): from twisted.internet import reactor reactor.callLater(0.5, torrent_created) - client.register_event_handler("CreateTorrentProgressEvent", on_create_torrent_progress_event) + client.register_event_handler('CreateTorrentProgressEvent', on_create_torrent_progress_event) client.core.create_torrent( path, @@ -335,7 +335,7 @@ class CreateTorrentDialog(object): else: def hide_progress(result): - self.builder.get_object("progress_dialog").hide_all() + self.builder.get_object('progress_dialog').hide_all() deferToThread(self.create_torrent, path.decode('utf-8'), @@ -351,8 +351,8 @@ class CreateTorrentDialog(object): add_to_session).addCallback(hide_progress) # Setup progress dialog - self.builder.get_object("progress_dialog").set_transient_for(component.get("MainWindow").window) - self.builder.get_object("progress_dialog").show_all() + self.builder.get_object('progress_dialog').set_transient_for(component.get('MainWindow').window) + self.builder.get_object('progress_dialog').show_all() self.dialog.destroy() @@ -372,17 +372,17 @@ class CreateTorrentDialog(object): trackers=trackers) if add_to_session: - with open(target, "rb") as _file: + with open(target, 'rb') as _file: filedump = base64.encodestring(_file.read()) client.core.add_torrent_file(os.path.split(target)[-1], filedump, - {"download_location": os.path.split(path)[0]}) + {'download_location': os.path.split(path)[0]}) def _on_create_torrent_progress(self, value, num_pieces): percent = value / num_pieces def update_pbar_with_gobject(percent): - pbar = self.builder.get_object("progressbar") - pbar.set_text("%.2f%%" % (percent * 100)) + pbar = self.builder.get_object('progressbar') + pbar.set_text('%.2f%%' % (percent * 100)) pbar.set_fraction(percent) return False @@ -392,8 +392,8 @@ class CreateTorrentDialog(object): gobject.idle_add(update_pbar_with_gobject, percent) def _on_button_up_clicked(self, widget): - log.debug("_on_button_up_clicked") - row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1] + log.debug('_on_button_up_clicked') + row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1] if row is None: return if self.trackers_liststore[row][0] == 0: @@ -402,25 +402,25 @@ class CreateTorrentDialog(object): self.trackers_liststore[row][0] -= 1 def _on_button_down_clicked(self, widget): - log.debug("_on_button_down_clicked") - row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1] + log.debug('_on_button_down_clicked') + row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1] if row is None: return self.trackers_liststore[row][0] += 1 def _on_button_add_clicked(self, widget): - log.debug("_on_button_add_clicked") + log.debug('_on_button_add_clicked') builder = gtk.Builder() builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "edit_trackers.add.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui') )) - dialog = builder.get_object("add_tracker_dialog") + dialog = builder.get_object('add_tracker_dialog') dialog.set_transient_for(self.dialog) - textview = builder.get_object("textview_trackers") - if self.config["createtorrent.trackers"]: - textview.get_buffer().set_text("\n".join(self.config["createtorrent.trackers"])) + textview = builder.get_object('textview_trackers') + if self.config['createtorrent.trackers']: + textview.get_buffer().set_text('\n'.join(self.config['createtorrent.trackers'])) else: - textview.get_buffer().set_text("") + textview.get_buffer().set_text('') textview.grab_focus() response = dialog.run() @@ -428,9 +428,9 @@ class CreateTorrentDialog(object): # Create a list of trackers from the textview buffer trackers = [] b = textview.get_buffer() - lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n") - self.config["createtorrent.trackers"] = lines - log.debug("lines: %s", lines) + lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n') + self.config['createtorrent.trackers'] = lines + log.debug('lines: %s', lines) for l in lines: if is_url(l): trackers.append(l) @@ -447,8 +447,8 @@ class CreateTorrentDialog(object): dialog.destroy() def _on_button_remove_clicked(self, widget): - log.debug("_on_button_remove_clicked") - row = self.builder.get_object("tracker_treeview").get_selection().get_selected()[1] + log.debug('_on_button_remove_clicked') + row = self.builder.get_object('tracker_treeview').get_selection().get_selected()[1] if row is None: return self.trackers_liststore.remove(row) diff --git a/deluge/ui/gtkui/details_tab.py b/deluge/ui/gtkui/details_tab.py index 10d69d3ff..0c71b3f0a 100644 --- a/deluge/ui/gtkui/details_tab.py +++ b/deluge/ui/gtkui/details_tab.py @@ -23,29 +23,29 @@ class DetailsTab(Tab): Tab.__init__(self) # Get the labels we need to update. # widget name, modifier function, status keys - builder = component.get("MainWindow").get_builder() + builder = component.get('MainWindow').get_builder() - self._name = "Details" - self._child_widget = builder.get_object("details_tab") - self._tab_label = builder.get_object("details_tab_label") + self._name = 'Details' + self._child_widget = builder.get_object('details_tab') + self._tab_label = builder.get_object('details_tab_label') self.label_widgets = [ - (builder.get_object("summary_name"), None, ("name",)), - (builder.get_object("summary_total_size"), fsize, ("total_size",)), - (builder.get_object("summary_num_files"), str, ("num_files",)), - (builder.get_object("summary_completed"), fdate_or_dash, ("completed_time",)), - (builder.get_object("summary_date_added"), fdate, ("time_added",)), - (builder.get_object("summary_torrent_path"), None, ("download_location",)), - (builder.get_object("summary_hash"), str, ("hash",)), - (builder.get_object("summary_comments"), str, ("comment",)), - (builder.get_object("summary_pieces"), fpieces_num_size, ("num_pieces", "piece_length")), + (builder.get_object('summary_name'), None, ('name',)), + (builder.get_object('summary_total_size'), fsize, ('total_size',)), + (builder.get_object('summary_num_files'), str, ('num_files',)), + (builder.get_object('summary_completed'), fdate_or_dash, ('completed_time',)), + (builder.get_object('summary_date_added'), fdate, ('time_added',)), + (builder.get_object('summary_torrent_path'), None, ('download_location',)), + (builder.get_object('summary_hash'), str, ('hash',)), + (builder.get_object('summary_comments'), str, ('comment',)), + (builder.get_object('summary_pieces'), fpieces_num_size, ('num_pieces', 'piece_length')), ] self.status_keys = [status for widget in self.label_widgets for status in widget[2]] def update(self): # Get the first selected torrent - selected = component.get("TorrentView").get_selected_torrents() + selected = component.get('TorrentView').get_selected_torrents() # Only use the first torrent in the list or return if None selected if selected: @@ -55,7 +55,7 @@ class DetailsTab(Tab): self.clear() return - session = component.get("SessionProxy") + session = component.get('SessionProxy') session.get_torrent_status(selected, self.status_keys).addCallback(self._on_get_torrent_status) def _on_get_torrent_status(self, status): @@ -67,11 +67,11 @@ class DetailsTab(Tab): for widget in self.label_widgets: txt = xml_escape(self.get_status_for_widget(widget, status)) if widget[0].get_text() != txt: - if widget[2][0] == "comment" and is_url(txt): + if widget[2][0] == 'comment' and is_url(txt): widget[0].set_markup('<a href="%s">%s</a>' % (txt, txt)) else: widget[0].set_markup(txt) def clear(self): for widget in self.label_widgets: - widget[0].set_text("") + widget[0].set_text('') diff --git a/deluge/ui/gtkui/dialogs.py b/deluge/ui/gtkui/dialogs.py index 6a5a616e6..342f50c9d 100644 --- a/deluge/ui/gtkui/dialogs.py +++ b/deluge/ui/gtkui/dialogs.py @@ -32,24 +32,24 @@ class BaseDialog(gtk.Dialog): """ super(BaseDialog, self).__init__( title=header, - parent=parent if parent else component.get("MainWindow").window, + parent=parent if parent else component.get('MainWindow').window, flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT | gtk.DIALOG_NO_SEPARATOR, buttons=buttons) self.set_icon(get_deluge_icon()) - self.connect("delete-event", self._on_delete_event) - self.connect("response", self._on_response) + self.connect('delete-event', self._on_delete_event) + self.connect('response', self._on_response) # Setup all the formatting and such to make our dialog look pretty self.set_border_width(5) self.set_default_size(200, 100) hbox = gtk.HBox(spacing=5) image = gtk.Image() - if not gtk.stock_lookup(icon) and (icon.endswith(".svg") or icon.endswith(".png")): + if not gtk.stock_lookup(icon) and (icon.endswith('.svg') or icon.endswith('.png')): # Hack for Windows since it doesn't support svg - if icon.endswith(".svg") and (windows_check() or osx_check()): - icon = icon.rpartition(".svg")[0] + "16.png" + if icon.endswith('.svg') and (windows_check() or osx_check()): + icon = icon.rpartition('.svg')[0] + '16.png' pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(get_pixmap(icon), 32, 32) image.set_from_pixbuf(pixbuf) else: @@ -156,7 +156,7 @@ class ErrorDialog(BaseDialog): tb = sys.exc_info() tb = traceback.format_exc(tb[2]) if details: - details += "\n" + tb + details += '\n' + tb else: details = tb @@ -169,7 +169,7 @@ class ErrorDialog(BaseDialog): sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) sw.set_shadow_type(gtk.SHADOW_IN) sw.add(textview) - label = gtk.Label(_("Details:")) + label = gtk.Label(_('Details:')) label.set_alignment(0.0, 0.5) self.vbox.pack_start(label, False, False) self.vbox.pack_start(sw) @@ -183,20 +183,20 @@ class AuthenticationDialog(BaseDialog): When run(), it will return either a gtk.RESPONSE_CANCEL or a gtk.RESPONSE_OK. """ - def __init__(self, err_msg="", username=None, parent=None): + def __init__(self, err_msg='', username=None, parent=None): """ :param err_msg: the error message we got back from the server :type err_msg: string """ super(AuthenticationDialog, self).__init__( - _("Authenticate"), err_msg, + _('Authenticate'), err_msg, gtk.STOCK_DIALOG_AUTHENTICATION, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK), parent) table = gtk.Table(2, 2, False) self.username_label = gtk.Label() - self.username_label.set_markup("<b>" + _("Username:") + "</b>") + self.username_label.set_markup('<b>' + _('Username:') + '</b>') self.username_label.set_alignment(1.0, 0.5) self.username_label.set_padding(5, 5) self.username_entry = gtk.Entry() @@ -204,12 +204,12 @@ class AuthenticationDialog(BaseDialog): table.attach(self.username_entry, 1, 2, 0, 1) self.password_label = gtk.Label() - self.password_label.set_markup("<b>" + _("Password:") + "</b>") + self.password_label.set_markup('<b>' + _('Password:') + '</b>') self.password_label.set_alignment(1.0, 0.5) self.password_label.set_padding(5, 5) self.password_entry = gtk.Entry() self.password_entry.set_visibility(False) - self.password_entry.connect("activate", self.on_password_activate) + self.password_entry.connect('activate', self.on_password_activate) table.attach(self.password_label, 0, 1, 1, 2) table.attach(self.password_entry, 1, 2, 1, 2) @@ -238,16 +238,16 @@ class AccountDialog(BaseDialog): levels_mapping=None, parent=None): if username: super(AccountDialog, self).__init__( - _("Edit Account"), - _("Edit existing account"), + _('Edit Account'), + _('Edit existing account'), gtk.STOCK_DIALOG_INFO, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_APPLY, gtk.RESPONSE_OK), parent) else: super(AccountDialog, self).__init__( - _("New Account"), - _("Create a new account"), + _('New Account'), + _('Create a new account'), gtk.STOCK_DIALOG_INFO, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_ADD, gtk.RESPONSE_OK), @@ -257,7 +257,7 @@ class AccountDialog(BaseDialog): table = gtk.Table(2, 3, False) self.username_label = gtk.Label() - self.username_label.set_markup("<b>" + _("Username:") + "</b>") + self.username_label.set_markup('<b>' + _('Username:') + '</b>') self.username_label.set_alignment(1.0, 0.5) self.username_label.set_padding(5, 5) self.username_entry = gtk.Entry() @@ -265,7 +265,7 @@ class AccountDialog(BaseDialog): table.attach(self.username_entry, 1, 2, 0, 1) self.authlevel_label = gtk.Label() - self.authlevel_label.set_markup("<b>" + _("Authentication Level:") + "</b>") + self.authlevel_label.set_markup('<b>' + _('Authentication Level:') + '</b>') self.authlevel_label.set_alignment(1.0, 0.5) self.authlevel_label.set_padding(5, 5) @@ -285,7 +285,7 @@ class AccountDialog(BaseDialog): table.attach(self.authlevel_combo, 1, 2, 1, 2) self.password_label = gtk.Label() - self.password_label.set_markup("<b>" + _("Password:") + "</b>") + self.password_label.set_markup('<b>' + _('Password:') + '</b>') self.password_label.set_alignment(1.0, 0.5) self.password_label.set_padding(5, 5) self.password_entry = gtk.Entry() @@ -324,10 +324,10 @@ class OtherDialog(BaseDialog): Returns: int or float: """ - def __init__(self, header, text="", unit_text="", icon=None, default=0, parent=None): + def __init__(self, header, text='', unit_text='', icon=None, default=0, parent=None): self.value_type = type(default) if self.value_type not in (int, float): - raise TypeError("default value needs to be an int or float") + raise TypeError('default value needs to be an int or float') if not icon: icon = gtk.STOCK_DIALOG_INFO @@ -383,25 +383,25 @@ class PasswordDialog(BaseDialog): When run(), it will return either a gtk.RESPONSE_CANCEL or a gtk.RESPONSE_OK. """ - def __init__(self, password_msg="", parent=None): + def __init__(self, password_msg='', parent=None): """ :param password_msg: the error message we got back from the server :type password_msg: string """ super(PasswordDialog, self).__init__( - _("Password Protected"), password_msg, + _('Password Protected'), password_msg, gtk.STOCK_DIALOG_AUTHENTICATION, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_CONNECT, gtk.RESPONSE_OK), parent) table = gtk.Table(1, 2, False) self.password_label = gtk.Label() - self.password_label.set_markup("<b>" + _("Password:") + "</b>") + self.password_label.set_markup('<b>' + _('Password:') + '</b>') self.password_label.set_alignment(1.0, 0.5) self.password_label.set_padding(5, 5) self.password_entry = gtk.Entry() self.password_entry.set_visibility(False) - self.password_entry.connect("activate", self.on_password_activate) + self.password_entry.connect('activate', self.on_password_activate) table.attach(self.password_label, 0, 1, 1, 2) table.attach(self.password_entry, 1, 2, 1, 2) diff --git a/deluge/ui/gtkui/edittrackersdialog.py b/deluge/ui/gtkui/edittrackersdialog.py index 04718d4ad..695df07f6 100644 --- a/deluge/ui/gtkui/edittrackersdialog.py +++ b/deluge/ui/gtkui/edittrackersdialog.py @@ -26,26 +26,26 @@ class EditTrackersDialog(object): def __init__(self, torrent_id, parent=None): self.torrent_id = torrent_id self.builder = gtk.Builder() - self.gtkui_config = ConfigManager("gtkui.conf") + self.gtkui_config = ConfigManager('gtkui.conf') # Main dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "edit_trackers.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.ui') )) # add tracker dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "edit_trackers.add.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.add.ui') )) # edit tracker dialog self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "edit_trackers.edit.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'edit_trackers.edit.ui') )) - self.dialog = self.builder.get_object("edit_trackers_dialog") - self.treeview = self.builder.get_object("tracker_treeview") - self.add_tracker_dialog = self.builder.get_object("add_tracker_dialog") + self.dialog = self.builder.get_object('edit_trackers_dialog') + self.treeview = self.builder.get_object('tracker_treeview') + self.add_tracker_dialog = self.builder.get_object('add_tracker_dialog') self.add_tracker_dialog.set_transient_for(self.dialog) - self.edit_tracker_entry = self.builder.get_object("edit_tracker_entry") + self.edit_tracker_entry = self.builder.get_object('edit_tracker_entry') self.edit_tracker_entry.set_transient_for(self.dialog) self.dialog.set_icon(get_deluge_icon()) @@ -56,16 +56,16 @@ class EditTrackersDialog(object): # Connect the signals self.builder.connect_signals({ - "on_button_up_clicked": self.on_button_up_clicked, - "on_button_add_clicked": self.on_button_add_clicked, - "on_button_edit_clicked": self.on_button_edit_clicked, - "on_button_edit_cancel_clicked": self.on_button_edit_cancel_clicked, - "on_button_edit_ok_clicked": self.on_button_edit_ok_clicked, - "on_button_remove_clicked": self.on_button_remove_clicked, - "on_button_down_clicked": self.on_button_down_clicked, - "on_button_add_ok_clicked": self.on_button_add_ok_clicked, - "on_button_add_cancel_clicked": self.on_button_add_cancel_clicked, - "on_edit_trackers_dialog_configure_event": self.on_edit_trackers_dialog_configure_event + 'on_button_up_clicked': self.on_button_up_clicked, + 'on_button_add_clicked': self.on_button_add_clicked, + 'on_button_edit_clicked': self.on_button_edit_clicked, + 'on_button_edit_cancel_clicked': self.on_button_edit_cancel_clicked, + 'on_button_edit_ok_clicked': self.on_button_edit_ok_clicked, + 'on_button_remove_clicked': self.on_button_remove_clicked, + 'on_button_down_clicked': self.on_button_down_clicked, + 'on_button_add_ok_clicked': self.on_button_add_ok_clicked, + 'on_button_add_cancel_clicked': self.on_button_add_cancel_clicked, + 'on_edit_trackers_dialog_configure_event': self.on_edit_trackers_dialog_configure_event }) # Create a liststore for tier, url @@ -73,15 +73,15 @@ class EditTrackersDialog(object): # Create the columns self.treeview.append_column( - gtk.TreeViewColumn(_("Tier"), gtk.CellRendererText(), text=0)) + gtk.TreeViewColumn(_('Tier'), gtk.CellRendererText(), text=0)) self.treeview.append_column( - gtk.TreeViewColumn(_("Tracker"), gtk.CellRendererText(), text=1)) + gtk.TreeViewColumn(_('Tracker'), gtk.CellRendererText(), text=1)) self.treeview.set_model(self.liststore) self.liststore.set_sort_column_id(0, gtk.SORT_ASCENDING) - self.dialog.connect("delete-event", self._on_delete_event) - self.dialog.connect("response", self._on_response) + self.dialog.connect('delete-event', self._on_delete_event) + self.dialog.connect('response', self._on_response) def run(self): # Make sure we have a torrent_id.. if not just return @@ -89,9 +89,9 @@ class EditTrackersDialog(object): return # Get the trackers for this torrent - session = component.get("SessionProxy") + session = component.get('SessionProxy') session.get_torrent_status( - self.torrent_id, ["trackers"] + self.torrent_id, ['trackers'] ).addCallback(self._on_get_torrent_status) client.force_call() @@ -102,14 +102,14 @@ class EditTrackersDialog(object): del self.gtkui_config def load_edit_trackers_dialog_state(self): - w = self.gtkui_config["edit_trackers_dialog_width"] - h = self.gtkui_config["edit_trackers_dialog_height"] + w = self.gtkui_config['edit_trackers_dialog_width'] + h = self.gtkui_config['edit_trackers_dialog_height'] if w is not None and h is not None: self.dialog.resize(w, h) def on_edit_trackers_dialog_configure_event(self, widget, event): - self.gtkui_config["edit_trackers_dialog_width"] = event.width - self.gtkui_config["edit_trackers_dialog_height"] = event.height + self.gtkui_config['edit_trackers_dialog_width'] = event.width + self.gtkui_config['edit_trackers_dialog_height'] = event.height def _on_delete_event(self, widget, event): self.deferred.callback(gtk.RESPONSE_DELETE_EVENT) @@ -121,8 +121,8 @@ class EditTrackersDialog(object): def each(model, path, _iter, data): tracker = {} - tracker["tier"] = model.get_value(_iter, 0) - tracker["url"] = model.get_value(_iter, 1) + tracker['tier'] = model.get_value(_iter, 0) + tracker['url'] = model.get_value(_iter, 1) self.trackers.append(tracker) self.liststore.foreach(each, None) if self.old_trackers != self.trackers: @@ -137,9 +137,9 @@ class EditTrackersDialog(object): def _on_get_torrent_status(self, status): """Display trackers dialog""" - self.old_trackers = list(status["trackers"]) + self.old_trackers = list(status['trackers']) for tracker in self.old_trackers: - self.add_tracker(tracker["tier"], tracker["url"]) + self.add_tracker(tracker['tier'], tracker['url']) self.treeview.set_cursor((0)) self.dialog.show() @@ -152,43 +152,43 @@ class EditTrackersDialog(object): return self.treeview.get_selection().get_selected()[1] def on_button_add_clicked(self, widget): - log.debug("on_button_add_clicked") + log.debug('on_button_add_clicked') # Show the add tracker dialog self.add_tracker_dialog.show() - self.builder.get_object("textview_trackers").grab_focus() + self.builder.get_object('textview_trackers').grab_focus() def on_button_remove_clicked(self, widget): - log.debug("on_button_remove_clicked") + log.debug('on_button_remove_clicked') selected = self.get_selected() if selected is not None: self.liststore.remove(selected) def on_button_edit_clicked(self, widget): """edits an existing tracker""" - log.debug("on_button_edit_clicked") + log.debug('on_button_edit_clicked') selected = self.get_selected() if selected: tracker = self.liststore.get_value(selected, 1) - self.builder.get_object("entry_edit_tracker").set_text(tracker) + self.builder.get_object('entry_edit_tracker').set_text(tracker) self.edit_tracker_entry.show() self.edit_tracker_entry.grab_focus() self.dialog.set_sensitive(False) def on_button_edit_cancel_clicked(self, widget): - log.debug("on_button_edit_cancel_clicked") + log.debug('on_button_edit_cancel_clicked') self.dialog.set_sensitive(True) self.edit_tracker_entry.hide() def on_button_edit_ok_clicked(self, widget): - log.debug("on_button_edit_ok_clicked") + log.debug('on_button_edit_ok_clicked') selected = self.get_selected() - tracker = self.builder.get_object("entry_edit_tracker").get_text() + tracker = self.builder.get_object('entry_edit_tracker').get_text() self.liststore.set_value(selected, 1, tracker) self.dialog.set_sensitive(True) self.edit_tracker_entry.hide() def on_button_up_clicked(self, widget): - log.debug("on_button_up_clicked") + log.debug('on_button_up_clicked') selected = self.get_selected() num_rows = self.liststore.iter_n_children(None) if selected is not None and num_rows > 1: @@ -200,7 +200,7 @@ class EditTrackersDialog(object): self.liststore.set_value(selected, 0, new_tier) def on_button_down_clicked(self, widget): - log.debug("on_button_down_clicked") + log.debug('on_button_down_clicked') selected = self.get_selected() num_rows = self.liststore.iter_n_children(None) if selected is not None and num_rows > 1: @@ -210,13 +210,13 @@ class EditTrackersDialog(object): self.liststore.set_value(selected, 0, new_tier) def on_button_add_ok_clicked(self, widget): - log.debug("on_button_add_ok_clicked") + log.debug('on_button_add_ok_clicked') # Create a list of trackers from the textview widget - textview = self.builder.get_object("textview_trackers") + textview = self.builder.get_object('textview_trackers') trackers = [] b = textview.get_buffer() - lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split("\n") + lines = b.get_text(b.get_start_iter(), b.get_end_iter()).strip().split('\n') for l in lines: if is_url(l): trackers.append(l) @@ -241,12 +241,12 @@ class EditTrackersDialog(object): self.add_tracker(highest_tier + 1, tracker) # Clear the entry widget and hide the dialog - textview.get_buffer().set_text("") + textview.get_buffer().set_text('') self.add_tracker_dialog.hide() def on_button_add_cancel_clicked(self, widget): - log.debug("on_button_add_cancel_clicked") + log.debug('on_button_add_cancel_clicked') # Clear the entry widget and hide the dialog b = gtk.TextBuffer() - self.builder.get_object("textview_trackers").set_buffer(b) + self.builder.get_object('textview_trackers').set_buffer(b) self.add_tracker_dialog.hide() diff --git a/deluge/ui/gtkui/files_tab.py b/deluge/ui/gtkui/files_tab.py index 36835dce4..eda87bdc2 100644 --- a/deluge/ui/gtkui/files_tab.py +++ b/deluge/ui/gtkui/files_tab.py @@ -32,10 +32,10 @@ def _(message): return message TRANSLATE = { - "Do Not Download": _("Do Not Download"), - "Normal Priority": _("Normal Priority"), - "High Priority": _("High Priority"), - "Highest Priority": _("Highest Priority"), + 'Do Not Download': _('Do Not Download'), + 'Normal Priority': _('Normal Priority'), + 'High Priority': _('High Priority'), + 'Highest Priority': _('Highest Priority'), } del _ @@ -50,52 +50,52 @@ def _t(text): def cell_priority(column, cell, model, row, data): if model.get_value(row, 5) == -1: # This is a folder, so lets just set it blank for now - cell.set_property("text", "") + cell.set_property('text', '') return priority = model.get_value(row, data) - cell.set_property("text", _t(FILE_PRIORITY[priority])) + cell.set_property('text', _t(FILE_PRIORITY[priority])) def cell_priority_icon(column, cell, model, row, data): if model.get_value(row, 5) == -1: # This is a folder, so lets just set it blank for now - cell.set_property("stock-id", None) + cell.set_property('stock-id', None) return priority = model.get_value(row, data) - if FILE_PRIORITY[priority] == "Do Not Download": - cell.set_property("stock-id", gtk.STOCK_NO) - elif FILE_PRIORITY[priority] == "Normal Priority": - cell.set_property("stock-id", gtk.STOCK_YES) - elif FILE_PRIORITY[priority] == "High Priority": - cell.set_property("stock-id", gtk.STOCK_GO_UP) - elif FILE_PRIORITY[priority] == "Highest Priority": - cell.set_property("stock-id", gtk.STOCK_GOTO_TOP) + if FILE_PRIORITY[priority] == 'Do Not Download': + cell.set_property('stock-id', gtk.STOCK_NO) + elif FILE_PRIORITY[priority] == 'Normal Priority': + cell.set_property('stock-id', gtk.STOCK_YES) + elif FILE_PRIORITY[priority] == 'High Priority': + cell.set_property('stock-id', gtk.STOCK_GO_UP) + elif FILE_PRIORITY[priority] == 'Highest Priority': + cell.set_property('stock-id', gtk.STOCK_GOTO_TOP) def cell_filename(column, cell, model, row, data): """Only show the tail portion of the file path""" filepath = model.get_value(row, data) - cell.set_property("text", os.path.split(filepath)[1]) + cell.set_property('text', os.path.split(filepath)[1]) def cell_progress(column, cell, model, row, data): text = model.get_value(row, data[0]) value = model.get_value(row, data[1]) - cell.set_property("visible", True) - cell.set_property("text", text) - cell.set_property("value", value) + cell.set_property('visible', True) + cell.set_property('text', text) + cell.set_property('value', value) class FilesTab(Tab): def __init__(self): Tab.__init__(self) - builder = component.get("MainWindow").get_builder() + builder = component.get('MainWindow').get_builder() - self._name = "Files" - self._child_widget = builder.get_object("files_tab") - self._tab_label = builder.get_object("files_tab_label") + self._name = 'Files' + self._child_widget = builder.get_object('files_tab') + self._tab_label = builder.get_object('files_tab_label') - self.listview = builder.get_object("files_listview") + self.listview = builder.get_object('files_listview') # filename, size, progress string, progress value, priority, file index, icon id self.treestore = gtk.TreeStore(str, gobject.TYPE_UINT64, str, float, int, int, str) self.treestore.set_sort_column_id(0, gtk.SORT_ASCENDING) @@ -105,18 +105,18 @@ class FilesTab(Tab): self._editing_index = None # Filename column - self.filename_column_name = _("Filename") + self.filename_column_name = _('Filename') column = gtk.TreeViewColumn(self.filename_column_name) render = gtk.CellRendererPixbuf() column.pack_start(render, False) - column.add_attribute(render, "stock-id", 6) + column.add_attribute(render, 'stock-id', 6) render = gtk.CellRendererText() - render.set_property("editable", True) - render.connect("edited", self._on_filename_edited) - render.connect("editing-started", self._on_filename_editing_start) - render.connect("editing-canceled", self._on_filename_editing_canceled) + render.set_property('editable', True) + render.connect('edited', self._on_filename_edited) + render.connect('editing-started', self._on_filename_editing_start) + render.connect('editing-canceled', self._on_filename_editing_canceled) column.pack_start(render, True) - column.add_attribute(render, "text", 0) + column.add_attribute(render, 'text', 0) column.set_sort_column_id(0) column.set_clickable(True) column.set_resizable(True) @@ -126,7 +126,7 @@ class FilesTab(Tab): self.listview.append_column(column) # Size column - column = gtk.TreeViewColumn(_("Size")) + column = gtk.TreeViewColumn(_('Size')) render = gtk.CellRendererText() column.pack_start(render, False) column.set_cell_data_func(render, cell_data_size, 1) @@ -139,7 +139,7 @@ class FilesTab(Tab): self.listview.append_column(column) # Progress column - column = gtk.TreeViewColumn(_("Progress")) + column = gtk.TreeViewColumn(_('Progress')) render = gtk.CellRendererProgress() column.pack_start(render) column.set_cell_data_func(render, cell_progress, (2, 3)) @@ -152,7 +152,7 @@ class FilesTab(Tab): self.listview.append_column(column) # Priority column - column = gtk.TreeViewColumn(_("Priority")) + column = gtk.TreeViewColumn(_('Priority')) render = gtk.CellRendererPixbuf() column.pack_start(render, False) column.set_cell_data_func(render, cell_priority_icon, 4) @@ -173,24 +173,24 @@ class FilesTab(Tab): self.listview.get_selection().set_mode(gtk.SELECTION_MULTIPLE) - self.file_menu = builder.get_object("menu_file_tab") + self.file_menu = builder.get_object('menu_file_tab') self.file_menu_priority_items = [ - builder.get_object("menuitem_donotdownload"), - builder.get_object("menuitem_normal"), - builder.get_object("menuitem_high"), - builder.get_object("menuitem_highest"), - builder.get_object("menuitem_priority_sep") + builder.get_object('menuitem_donotdownload'), + builder.get_object('menuitem_normal'), + builder.get_object('menuitem_high'), + builder.get_object('menuitem_highest'), + builder.get_object('menuitem_priority_sep') ] self.localhost_widgets = [ - builder.get_object("menuitem_open_file"), - builder.get_object("menuitem_show_file"), - builder.get_object("menuitem3") + builder.get_object('menuitem_open_file'), + builder.get_object('menuitem_show_file'), + builder.get_object('menuitem3') ] - self.listview.connect("row-activated", self._on_row_activated) - self.listview.connect("key-press-event", self._on_key_press_event) - self.listview.connect("button-press-event", self._on_button_press_event) + self.listview.connect('row-activated', self._on_row_activated) + self.listview.connect('key-press-event', self._on_key_press_event) + self.listview.connect('button-press-event', self._on_button_press_event) self.listview.enable_model_drag_source( gtk.gdk.BUTTON1_MASK, @@ -198,23 +198,23 @@ class FilesTab(Tab): gtk.gdk.ACTION_DEFAULT | gtk.gdk.ACTION_MOVE) self.listview.enable_model_drag_dest([('text/plain', 0, 0)], gtk.gdk.ACTION_DEFAULT) - self.listview.connect("drag_data_get", self._on_drag_data_get_data) - self.listview.connect("drag_data_received", self._on_drag_data_received_data) - - component.get("MainWindow").connect_signals({ - "on_menuitem_open_file_activate": self._on_menuitem_open_file_activate, - "on_menuitem_show_file_activate": self._on_menuitem_show_file_activate, - "on_menuitem_donotdownload_activate": self._on_menuitem_donotdownload_activate, - "on_menuitem_normal_activate": self._on_menuitem_normal_activate, - "on_menuitem_high_activate": self._on_menuitem_high_activate, - "on_menuitem_highest_activate": self._on_menuitem_highest_activate, - "on_menuitem_expand_all_activate": self._on_menuitem_expand_all_activate + self.listview.connect('drag_data_get', self._on_drag_data_get_data) + self.listview.connect('drag_data_received', self._on_drag_data_received_data) + + component.get('MainWindow').connect_signals({ + 'on_menuitem_open_file_activate': self._on_menuitem_open_file_activate, + 'on_menuitem_show_file_activate': self._on_menuitem_show_file_activate, + 'on_menuitem_donotdownload_activate': self._on_menuitem_donotdownload_activate, + 'on_menuitem_normal_activate': self._on_menuitem_normal_activate, + 'on_menuitem_high_activate': self._on_menuitem_high_activate, + 'on_menuitem_highest_activate': self._on_menuitem_highest_activate, + 'on_menuitem_expand_all_activate': self._on_menuitem_expand_all_activate }) # Connect to various events from the daemon - client.register_event_handler("TorrentFileRenamedEvent", self._on_torrentfilerenamed_event) - client.register_event_handler("TorrentFolderRenamedEvent", self._on_torrentfolderrenamed_event) - client.register_event_handler("TorrentRemovedEvent", self._on_torrentremoved_event) + client.register_event_handler('TorrentFileRenamedEvent', self._on_torrentfilerenamed_event) + client.register_event_handler('TorrentFolderRenamedEvent', self._on_torrentfolderrenamed_event) + client.register_event_handler('TorrentRemovedEvent', self._on_torrentremoved_event) # Attempt to load state self.load_state() @@ -225,7 +225,7 @@ class FilesTab(Tab): self.torrent_id = None def start(self): - attr = "hide" if not client.is_localhost() else "show" + attr = 'hide' if not client.is_localhost() else 'show' for widget in self.localhost_widgets: getattr(widget, attr)() @@ -235,47 +235,47 @@ class FilesTab(Tab): # Setup state dict state = { - "columns": {}, - "sort_id": int(column_id) if column_id >= 0 else None, - "sort_order": int(sort_order) if sort_order >= 0 else None + 'columns': {}, + 'sort_id': int(column_id) if column_id >= 0 else None, + 'sort_order': int(sort_order) if sort_order >= 0 else None } for index, column in enumerate(self.listview.get_columns()): - state["columns"][column.get_title()] = { - "position": index, - "width": column.get_width() + state['columns'][column.get_title()] = { + 'position': index, + 'width': column.get_width() } - save_pickled_state_file("files_tab.state", state) + save_pickled_state_file('files_tab.state', state) def load_state(self): - state = load_pickled_state_file("files_tab.state") + state = load_pickled_state_file('files_tab.state') if not state: return - if state["sort_id"] is not None and state["sort_order"] is not None: - self.treestore.set_sort_column_id(state["sort_id"], state["sort_order"]) + if state['sort_id'] is not None and state['sort_order'] is not None: + self.treestore.set_sort_column_id(state['sort_id'], state['sort_order']) for (index, column) in enumerate(self.listview.get_columns()): cname = column.get_title() - if cname in state["columns"]: - cstate = state["columns"][cname] + if cname in state['columns']: + cstate = state['columns'][cname] column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED) - column.set_fixed_width(cstate["width"] if cstate["width"] > 0 else 10) - if state["sort_id"] == index and state["sort_order"] is not None: + column.set_fixed_width(cstate['width'] if cstate['width'] > 0 else 10) + if state['sort_id'] == index and state['sort_order'] is not None: column.set_sort_indicator(True) - column.set_sort_order(state["sort_order"]) - if cstate["position"] != index: + column.set_sort_order(state['sort_order']) + if cstate['position'] != index: # Column is in wrong position - if cstate["position"] == 0: + if cstate['position'] == 0: self.listview.move_column_after(column, None) - elif self.listview.get_columns()[cstate["position"] - 1].get_title() != cname: - self.listview.move_column_after(column, self.listview.get_columns()[cstate["position"] - 1]) + elif self.listview.get_columns()[cstate['position'] - 1].get_title() != cname: + self.listview.move_column_after(column, self.listview.get_columns()[cstate['position'] - 1]) def update(self): # Get the first selected torrent - torrent_id = component.get("TorrentView").get_selected_torrents() + torrent_id = component.get('TorrentView').get_selected_torrents() # Only use the first torrent in the list or return if None selected if len(torrent_id) != 0: @@ -285,12 +285,12 @@ class FilesTab(Tab): self.clear() return - status_keys = ["file_progress", "file_priorities"] + status_keys = ['file_progress', 'file_priorities'] if torrent_id != self.torrent_id: # We only want to do this if the torrent_id has changed self.treestore.clear() self.torrent_id = torrent_id - status_keys += ["storage_mode", "is_seed"] + status_keys += ['storage_mode', 'is_seed'] if self.torrent_id in self.files_list: # We already have the files list stored, so just update the view @@ -298,10 +298,10 @@ class FilesTab(Tab): if self.torrent_id not in self.files_list or not self.files_list[self.torrent_id]: # We need to get the files list - log.debug("Getting file list from core..") - status_keys += ["files"] + log.debug('Getting file list from core..') + status_keys += ['files'] - component.get("SessionProxy").get_torrent_status( + component.get('SessionProxy').get_torrent_status( self.torrent_id, status_keys).addCallback(self._on_get_torrent_status, self.torrent_id) def clear(self): @@ -311,7 +311,7 @@ class FilesTab(Tab): def _on_row_activated(self, tree, path, view_column): self._on_menuitem_open_file_activate(None) - def get_file_path(self, row, path=""): + def get_file_path(self, row, path=''): if not row: return path @@ -325,8 +325,8 @@ class FilesTab(Tab): selected.append(self.treestore.get_iter(path)) for select in selected: - path = self.get_file_path(select).split("/") - filepath = os.path.join(status["download_location"], *path) + path = self.get_file_path(select).split('/') + filepath = os.path.join(status['download_location'], *path) log.debug("Open file '%s'", filepath) timestamp = gtk.get_current_event_time() open_file(filepath, timestamp=timestamp) @@ -338,8 +338,8 @@ class FilesTab(Tab): selected.append(self.treestore.get_iter(path)) for select in selected: - path = self.get_file_path(select).split("/") - filepath = os.path.join(status["download_location"], *path) + path = self.get_file_path(select).split('/') + filepath = os.path.join(status['download_location'], *path) log.debug("Show file '%s'", filepath) timestamp = gtk.get_current_event_time() show_file(filepath, timestamp=timestamp) @@ -348,11 +348,11 @@ class FilesTab(Tab): def prepare_file_store(self, torrent_files): split_files = {} for index, torrent_file in enumerate(torrent_files): - self.prepare_file(torrent_file, torrent_file["path"], index, split_files) + self.prepare_file(torrent_file, torrent_file['path'], index, split_files) self.add_files(None, split_files) def prepare_file(self, torrent_file, file_name, file_num, files_storage): - first_slash_index = file_name.find("/") + first_slash_index = file_name.find('/') if first_slash_index == -1: files_storage[file_name] = (file_num, torrent_file) else: @@ -365,22 +365,22 @@ class FilesTab(Tab): def add_files(self, parent_iter, split_files): chunk_size_total = 0 for key, value in split_files.iteritems(): - if key.endswith("/"): + if key.endswith('/'): chunk_iter = self.treestore.append(parent_iter, - [key, 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY]) + [key, 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY]) chunk_size = self.add_files(chunk_iter, value) self.treestore.set(chunk_iter, 1, chunk_size) chunk_size_total += chunk_size else: self.treestore.append(parent_iter, - [key, value[1]["size"], "", 0, 0, value[0], gtk.STOCK_FILE]) - chunk_size_total += value[1]["size"] + [key, value[1]['size'], '', 0, 0, value[0], gtk.STOCK_FILE]) + chunk_size_total += value[1]['size'] return chunk_size_total def update_files(self): with listview_replace_treestore(self.listview): self.prepare_file_store(self.files_list[self.torrent_id]) - self.listview.expand_row("0", False) + self.listview.expand_row('0', False) def get_selected_files(self): """Returns a list of file indexes that are selected.""" @@ -435,7 +435,7 @@ class FilesTab(Tab): # Catch the unusal error found when moving folders around value = 0 self.treestore[parent][3] = value - self.treestore[parent][2] = "%i%%" % value + self.treestore[parent][2] = '%i%%' % value return completed_bytes get_completed_bytes(self.treestore.iter_children(root)) @@ -445,11 +445,11 @@ class FilesTab(Tab): if self.torrent_id != torrent_id: return - if "is_seed" in status: - self.__is_seed = status["is_seed"] + if 'is_seed' in status: + self.__is_seed = status['is_seed'] - if "files" in status: - self.files_list[self.torrent_id] = status["files"] + if 'files' in status: + self.files_list[self.torrent_id] = status['files'] self.update_files() # (index, iter) @@ -462,15 +462,15 @@ class FilesTab(Tab): continue try: - progress_string = "%i%%" % (status["file_progress"][index] * 100) + progress_string = '%i%%' % (status['file_progress'][index] * 100) except IndexError: continue if row[2] != progress_string: row[2] = progress_string - progress_value = status["file_progress"][index] * 100 + progress_value = status['file_progress'][index] * 100 if row[3] != progress_value: row[3] = progress_value - file_priority = status["file_priorities"][index] + file_priority = status['file_priorities'][index] if row[4] != file_priority: row[4] = file_priority if self._editing_index != -1: @@ -479,7 +479,7 @@ class FilesTab(Tab): def _on_button_press_event(self, widget, event): """This is a callback for showing the right-click context menu.""" - log.debug("on_button_press_event") + log.debug('on_button_press_event') # We only care about right-clicks if event.button == 3: x, y = event.get_coords() @@ -520,13 +520,13 @@ class FilesTab(Tab): def _on_menuitem_open_file_activate(self, menuitem): if client.is_localhost: - component.get("SessionProxy").get_torrent_status( - self.torrent_id, ["download_location"]).addCallback(self._on_open_file) + component.get('SessionProxy').get_torrent_status( + self.torrent_id, ['download_location']).addCallback(self._on_open_file) def _on_menuitem_show_file_activate(self, menuitem): if client.is_localhost: - component.get("SessionProxy").get_torrent_status( - self.torrent_id, ["download_location"]).addCallback(self._on_show_file) + component.get('SessionProxy').get_torrent_status( + self.torrent_id, ['download_location']).addCallback(self._on_show_file) def _set_file_priorities_on_user_change(self, selected, priority): """Sets the file priorities in the core. It will change the selected with the 'priority'""" @@ -542,36 +542,36 @@ class FilesTab(Tab): self.treestore.foreach(set_file_priority, None) file_priorities.sort() priorities = [p[1] for p in file_priorities] - log.debug("priorities: %s", priorities) + log.debug('priorities: %s', priorities) client.core.set_torrent_file_priorities(self.torrent_id, priorities) def _on_menuitem_donotdownload_activate(self, menuitem): self._set_file_priorities_on_user_change( self.get_selected_files(), - FILE_PRIORITY["Do Not Download"]) + FILE_PRIORITY['Do Not Download']) def _on_menuitem_normal_activate(self, menuitem): self._set_file_priorities_on_user_change( self.get_selected_files(), - FILE_PRIORITY["Normal Priority"]) + FILE_PRIORITY['Normal Priority']) def _on_menuitem_high_activate(self, menuitem): self._set_file_priorities_on_user_change( self.get_selected_files(), - FILE_PRIORITY["High Priority"]) + FILE_PRIORITY['High Priority']) def _on_menuitem_highest_activate(self, menuitem): self._set_file_priorities_on_user_change( self.get_selected_files(), - FILE_PRIORITY["Highest Priority"]) + FILE_PRIORITY['Highest Priority']) def _on_menuitem_expand_all_activate(self, menuitem): self.listview.expand_all() def _on_filename_edited(self, renderer, path, new_text): index = self.treestore[path][5] - log.debug("new_text: %s", new_text) + log.debug('new_text: %s', new_text) # Don't do anything if the text hasn't changed if new_text == self.treestore[path][0]: @@ -585,7 +585,7 @@ class FilesTab(Tab): def get_filepath(i): ip = self.treestore.iter_parent(i) - fp = "" + fp = '' while ip: fp = self.treestore[ip][0] + fp ip = self.treestore.iter_parent(ip) @@ -597,14 +597,14 @@ class FilesTab(Tab): else: filepath = new_text - log.debug("filepath: %s", filepath) + log.debug('filepath: %s', filepath) client.core.rename_files(self.torrent_id, [(index, filepath)]) else: # We are renaming a folder folder = self.treestore[path][0] - parent_path = "" + parent_path = '' itr = self.treestore.iter_parent(self.treestore.get_iter(path)) while itr: parent_path = self.treestore[itr][0] + parent_path @@ -621,45 +621,45 @@ class FilesTab(Tab): self._editing_index = None def _on_torrentfilerenamed_event(self, torrent_id, index, name): - log.debug("index: %s name: %s", index, name) + log.debug('index: %s name: %s', index, name) if torrent_id not in self.files_list: return - old_name = self.files_list[torrent_id][index]["path"] - self.files_list[torrent_id][index]["path"] = name + old_name = self.files_list[torrent_id][index]['path'] + self.files_list[torrent_id][index]['path'] = name # We need to update the filename displayed if we're currently viewing # this torrents files. if torrent_id != self.torrent_id: return - old_name_parent = old_name.split("/")[:-1] - parent_path = name.split("/")[:-1] + old_name_parent = old_name.split('/')[:-1] + parent_path = name.split('/')[:-1] if old_name_parent != parent_path: if parent_path: for i, p in enumerate(parent_path): - p_itr = self.get_iter_at_path("/".join(parent_path[:i + 1]) + "/") + p_itr = self.get_iter_at_path('/'.join(parent_path[:i + 1]) + '/') if not p_itr: - p_itr = self.get_iter_at_path("/".join(parent_path[:i]) + "/") + p_itr = self.get_iter_at_path('/'.join(parent_path[:i]) + '/') p_itr = self.treestore.append( - p_itr, [parent_path[i] + "/", 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY]) - p_itr = self.get_iter_at_path("/".join(parent_path) + "/") + p_itr, [parent_path[i] + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY]) + p_itr = self.get_iter_at_path('/'.join(parent_path) + '/') old_name_itr = self.get_iter_at_path(old_name) self.treestore.append(p_itr, self.treestore.get(old_name_itr, *xrange(self.treestore.get_n_columns()))) self.treestore.remove(old_name_itr) # Remove old parent path - p_itr = self.get_iter_at_path("/".join(old_name_parent) + "/") + p_itr = self.get_iter_at_path('/'.join(old_name_parent) + '/') self.remove_childless_folders(p_itr) else: - new_folders = name.split("/")[:-1] + new_folders = name.split('/')[:-1] parent_iter = None for f in new_folders: parent_iter = self.treestore.append( - parent_iter, [f + "/", 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY]) + parent_iter, [f + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY]) child = self.get_iter_at_path(old_name) self.treestore.append(parent_iter, self.treestore.get(child, *xrange(self.treestore.get_n_columns()))) @@ -675,26 +675,26 @@ class FilesTab(Tab): def get_iter_at_path(self, filepath): """Returns the gtkTreeIter for filepath.""" - log.debug("get_iter_at_path: %s", filepath) + log.debug('get_iter_at_path: %s', filepath) is_dir = False - if filepath[-1] == "/": + if filepath[-1] == '/': is_dir = True - filepath = filepath.split("/") - if "" in filepath: - filepath.remove("") + filepath = filepath.split('/') + if '' in filepath: + filepath.remove('') path_iter = None itr = self.treestore.iter_children(None) level = 0 while itr: ipath = self.treestore[itr][0] - if (level + 1) != len(filepath) and ipath == filepath[level] + "/": + if (level + 1) != len(filepath) and ipath == filepath[level] + '/': # We're not at the last index, but we do have a match itr = self.treestore.iter_children(itr) level += 1 continue - elif (level + 1) == len(filepath) and ipath == (filepath[level] + "/" if is_dir else filepath[level]): + elif (level + 1) == len(filepath) and ipath == (filepath[level] + '/' if is_dir else filepath[level]): # This is the iter we've been searching for path_iter = itr break @@ -711,33 +711,33 @@ class FilesTab(Tab): itr = parent def _on_torrentfolderrenamed_event(self, torrent_id, old_folder, new_folder): - log.debug("on_torrent_folder_renamed_signal") - log.debug("old_folder: %s new_folder: %s", old_folder, new_folder) + log.debug('on_torrent_folder_renamed_signal') + log.debug('old_folder: %s new_folder: %s', old_folder, new_folder) if torrent_id not in self.files_list: return - if old_folder[-1] != "/": - old_folder += "/" + if old_folder[-1] != '/': + old_folder += '/' - if len(new_folder) > 0 and new_folder[-1] != "/": - new_folder += "/" + if len(new_folder) > 0 and new_folder[-1] != '/': + new_folder += '/' for fd in self.files_list[torrent_id]: - if fd["path"].startswith(old_folder): - fd["path"] = fd["path"].replace(old_folder, new_folder, 1) + if fd['path'].startswith(old_folder): + fd['path'] = fd['path'].replace(old_folder, new_folder, 1) if torrent_id == self.torrent_id: - old_split = old_folder.split("/") + old_split = old_folder.split('/') try: - old_split.remove("") + old_split.remove('') except ValueError: pass - new_split = new_folder.split("/") + new_split = new_folder.split('/') try: - new_split.remove("") + new_split.remove('') except ValueError: pass @@ -748,7 +748,7 @@ class FilesTab(Tab): if len(new_split) == len(old_split): # These are at the same tree depth, so it's a simple rename - self.treestore[old_folder_iter][0] = new_split[-1] + "/" + self.treestore[old_folder_iter][0] = new_split[-1] + '/' return if new_folder_iter: # This means that a folder by this name already exists @@ -757,9 +757,9 @@ class FilesTab(Tab): parent = old_folder_iter_parent if new_split: for ns in new_split[:-1]: - parent = self.treestore.append(parent, [ns + "/", 0, "", 0, 0, -1, gtk.STOCK_DIRECTORY]) + parent = self.treestore.append(parent, [ns + '/', 0, '', 0, 0, -1, gtk.STOCK_DIRECTORY]) - self.treestore[old_folder_iter][0] = new_split[-1] + "/" + self.treestore[old_folder_iter][0] = new_split[-1] + '/' reparent_iter(self.treestore, old_folder_iter, parent) else: child_itr = self.treestore.iter_children(old_folder_iter) @@ -781,15 +781,15 @@ class FilesTab(Tab): try: selected = cPickle.loads(selection.data) except cPickle.UnpicklingError: - log.debug("Invalid selection data: %s", selection.data) + log.debug('Invalid selection data: %s', selection.data) return - log.debug("selection.data: %s", selected) + log.debug('selection.data: %s', selected) drop_info = treeview.get_dest_row_at_pos(x, y) model = treeview.get_model() if drop_info: itr = model.get_iter(drop_info[0]) parent_iter = model.iter_parent(itr) - parent_path = "" + parent_path = '' if model[itr][5] == -1: parent_path += model[itr][0] @@ -798,10 +798,10 @@ class FilesTab(Tab): parent_iter = model.iter_parent(parent_iter) if model[selected[0]][5] == -1: - log.debug("parent_path: %s", parent_path) - log.debug("rename_to: %s", parent_path + model[selected[0]][0]) + log.debug('parent_path: %s', parent_path) + log.debug('rename_to: %s', parent_path + model[selected[0]][0]) # Get the full path of the folder we want to rename - pp = "" + pp = '' itr = self.treestore.iter_parent(self.treestore.get_iter(selected[0])) while itr: pp = self.treestore[itr][0] + pp @@ -813,5 +813,5 @@ class FilesTab(Tab): to_rename = [] for s in selected: to_rename.append((model[s][5], parent_path + model[s][0])) - log.debug("to_rename: %s", to_rename) + log.debug('to_rename: %s', to_rename) client.core.rename_files(self.torrent_id, to_rename) diff --git a/deluge/ui/gtkui/filtertreeview.py b/deluge/ui/gtkui/filtertreeview.py index c788048ec..f257f3556 100644 --- a/deluge/ui/gtkui/filtertreeview.py +++ b/deluge/ui/gtkui/filtertreeview.py @@ -25,21 +25,21 @@ from deluge.ui.client import client log = logging.getLogger(__name__) STATE_PIX = { - "All": "all", - "Downloading": "downloading", - "Seeding": "seeding", - "Paused": "inactive", - "Checking": "checking", - "Queued": "queued", - "Error": "alert", - "Active": "active", - "Allocating": "checking", - "Moving": "checking" + 'All': 'all', + 'Downloading': 'downloading', + 'Seeding': 'seeding', + 'Paused': 'inactive', + 'Checking': 'checking', + 'Queued': 'queued', + 'Error': 'alert', + 'Active': 'active', + 'Allocating': 'checking', + 'Moving': 'checking' } TRACKER_PIX = { - "All": "tracker_all", - "Error": "tracker_warning", + 'All': 'tracker_all', + 'Error': 'tracker_warning', } FILTER_COLUMN = 5 @@ -47,25 +47,25 @@ FILTER_COLUMN = 5 class FilterTreeView(component.Component): def __init__(self): - component.Component.__init__(self, "FilterTreeView", interval=2) - self.window = component.get("MainWindow") - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'FilterTreeView', interval=2) + self.window = component.get('MainWindow') + self.config = ConfigManager('gtkui.conf') - self.tracker_icons = component.get("TrackerIcons") + self.tracker_icons = component.get('TrackerIcons') - self.sidebar = component.get("SideBar") + self.sidebar = component.get('SideBar') 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: - self.sidebar.notebook.connect("hide", self._on_hide) + self.sidebar.notebook.connect('hide', self._on_hide) # Create the treestore # cat, value, label, count, pixmap, visible self.treestore = gtk.TreeStore(str, str, str, int, gtk.gdk.Pixbuf, bool) # Create the column and cells - column = gtk.TreeViewColumn("Filters") + column = gtk.TreeViewColumn('Filters') column.set_sizing(gtk.TREE_VIEW_COLUMN_AUTOSIZE) # icon cell self.cell_pix = gtk.CellRendererPixbuf() @@ -93,10 +93,10 @@ class FilterTreeView(component.Component): class "GtkTreeView" style "treeview-style" """) self.treeview.set_model(self.treestore) - self.treeview.get_selection().connect("changed", self.on_selection_changed) + self.treeview.get_selection().connect('changed', self.on_selection_changed) self.create_model_filter() - 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. style = self.window.window.get_style() @@ -105,12 +105,12 @@ class FilterTreeView(component.Component): # filtertree menu builder = gtk.Builder() - builder.add_from_file(resource_filename("deluge.ui.gtkui", os.path.join("glade", "filtertree_menu.ui"))) - self.menu = builder.get_object("filtertree_menu") + builder.add_from_file(resource_filename('deluge.ui.gtkui', os.path.join('glade', 'filtertree_menu.ui'))) + self.menu = builder.get_object('filtertree_menu') builder.connect_signals({ - "select_all": self.on_select_all, - "pause_all": self.on_pause_all, - "resume_all": self.on_resume_all + 'select_all': self.on_select_all, + 'pause_all': self.on_pause_all, + 'resume_all': self.on_resume_all }) self.default_menu_items = self.menu.get_children() @@ -121,19 +121,19 @@ class FilterTreeView(component.Component): self.filters = {} # initial order of state filter: - self.cat_nodes["state"] = self.treestore.append(None, ["cat", "state", _("States"), 0, None, False]) - for state in ["All", "Active"] + TORRENT_STATE: - self.update_row("state", state, 0, _(state)) + self.cat_nodes['state'] = self.treestore.append(None, ['cat', 'state', _('States'), 0, None, False]) + for state in ['All', 'Active'] + TORRENT_STATE: + self.update_row('state', state, 0, _(state)) - self.cat_nodes["tracker_host"] = self.treestore.append(None, ["cat", "tracker_host", - _("Trackers"), 0, None, False]) - self.update_row("tracker_host", "All", 0, _("All")) - self.update_row("tracker_host", "Error", 0, _("Error")) - self.update_row("tracker_host", "", 0, _("None")) + self.cat_nodes['tracker_host'] = self.treestore.append(None, ['cat', 'tracker_host', + _('Trackers'), 0, None, False]) + self.update_row('tracker_host', 'All', 0, _('All')) + self.update_row('tracker_host', 'Error', 0, _('Error')) + self.update_row('tracker_host', '', 0, _('None')) - self.cat_nodes["owner"] = self.treestore.append(None, ["cat", "owner", _("Owner"), 0, None, False]) - self.update_row("owner", "localclient", 0, _("Admin")) - self.update_row("owner", "", 0, _("None")) + self.cat_nodes['owner'] = self.treestore.append(None, ['cat', 'owner', _('Owner'), 0, None, False]) + self.update_row('owner', 'localclient', 0, _('Admin')) + self.update_row('owner', '', 0, _('None')) # We set to this expand the rows on start-up self.expand_rows = True @@ -153,9 +153,9 @@ class FilterTreeView(component.Component): for cat in filter_items: if cat not in self.cat_nodes: label = _(cat) - if cat == "label": - label = _("Labels") - self.cat_nodes[cat] = self.treestore.append(None, ["cat", cat, label, 0, None, False]) + if cat == 'label': + label = _('Labels') + self.cat_nodes[cat] = self.treestore.append(None, ['cat', cat, label, 0, None, False]) # update rows visible_filters = [] @@ -191,18 +191,18 @@ class FilterTreeView(component.Component): else: pix = self.get_pixmap(cat, value) - if value == "": - if cat == "label": - label = _("No Label") - elif cat == "owner": - label = _("No Owner") + if value == '': + if cat == 'label': + label = _('No Label') + elif cat == 'owner': + label = _('No Owner') elif not label and value: label = _(value) row = self.treestore.append(self.cat_nodes[cat], [cat, value, label, count, pix, True]) self.filters[(cat, value)] = row - if cat == "tracker_host" and value not in ("All", "Error") and value: + if cat == 'tracker_host' and value not in ('All', 'Error') and value: d = self.tracker_icons.fetch(value) d.addCallback(on_get_icon) @@ -216,35 +216,35 @@ class FilterTreeView(component.Component): # Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed original_filters = warnings.filters[:] - warnings.simplefilter("ignore") + warnings.simplefilter('ignore') try: pix = model.get_value(row, 4) finally: warnings.filters = original_filters - self.cell_pix.set_property("visible", True if pix else False) + self.cell_pix.set_property('visible', True if pix else False) - if cat == "cat": - self.cell_count.set_property("visible", False) + if cat == 'cat': + self.cell_count.set_property('visible', False) cell.set_padding(10, 2) - label = "<b>%s</b>" % label + label = '<b>%s</b>' % label else: - count_txt = "<small>%s</small>" % count + count_txt = '<small>%s</small>' % count self.cell_count.set_property('markup', count_txt) - self.cell_count.set_property("visible", True) + self.cell_count.set_property('visible', True) cell.set_padding(2, 1) cell.set_property('markup', label) def get_pixmap(self, cat, value): pix = None - if cat == "state": + if cat == 'state': pix = STATE_PIX.get(value, None) - elif cat == "tracker_host": + elif cat == 'tracker_host': pix = TRACKER_PIX.get(value, None) if pix: try: - return gtk.gdk.pixbuf_new_from_file(get_pixmap("%s16.png" % pix)) + return gtk.gdk.pixbuf_new_from_file(get_pixmap('%s16.png' % pix)) except GError as ex: log.warning(ex) return self.get_transparent_pix(16, 16) @@ -271,17 +271,17 @@ class FilterTreeView(component.Component): try: (model, row) = self.treeview.get_selection().get_selected() if not row: - log.debug("nothing selected") + log.debug('nothing selected') return cat = model.get_value(row, 0) value = model.get_value(row, 1) filter_dict = {cat: [value]} - if value == "All" or cat == "cat": + if value == 'All' or cat == 'cat': filter_dict = {} - component.get("TorrentView").set_filter(filter_dict) + component.get('TorrentView').set_filter(filter_dict) self.selected_path = model.get_path(row) @@ -293,11 +293,11 @@ class FilterTreeView(component.Component): def update(self): try: hide_cat = [] - if not self.config["sidebar_show_trackers"]: - hide_cat.append("tracker_host") - if not self.config["sidebar_show_owners"]: - hide_cat.append("owner") - client.core.get_filter_tree(self.config["sidebar_show_zero"], + if not self.config['sidebar_show_trackers']: + hide_cat.append('tracker_host') + if not self.config['sidebar_show_owners']: + hide_cat.append('owner') + client.core.get_filter_tree(self.config['sidebar_show_zero'], hide_cat).addCallback(self.cb_update_filter_tree) except Exception as ex: log.debug(ex) @@ -314,7 +314,7 @@ class FilterTreeView(component.Component): if event.button == 1: # Prevent selecting a category label - if cat == "cat": + if cat == 'cat': if self.treeview.row_expanded(path): self.treeview.collapse_row(path) else: @@ -342,37 +342,37 @@ class FilterTreeView(component.Component): self.menu.popup(None, None, None, event.button, event.time) self.menu.show() - if cat == "cat": + if cat == 'cat': # Do not select the row return True def set_menu_sensitivity(self): # 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: item.set_sensitive(sensitive) def select_all(self): - "for use in popup menu" - component.get("TorrentView").treeview.get_selection().select_all() + 'for use in popup menu' + component.get('TorrentView').treeview.get_selection().select_all() def on_select_all(self, event): self.select_all() def on_pause_all(self, event): self.select_all() - func = getattr(component.get("MenuBar"), "on_menuitem_%s_activate" % "pause") + func = getattr(component.get('MenuBar'), 'on_menuitem_%s_activate' % 'pause') func(event) def on_resume_all(self, event): self.select_all() - func = getattr(component.get("MenuBar"), "on_menuitem_%s_activate" % "resume") + func = getattr(component.get('MenuBar'), 'on_menuitem_%s_activate' % 'resume') func(event) def _on_hide(self, *args): self.select_default_filter() def select_default_filter(self): - row = self.filters[("state", "All")] + row = self.filters[('state', 'All')] path = self.treestore.get_path(row) self.treeview.get_selection().select_path(path) diff --git a/deluge/ui/gtkui/gtkui.py b/deluge/ui/gtkui/gtkui.py index b9201611b..e676f76b2 100644 --- a/deluge/ui/gtkui/gtkui.py +++ b/deluge/ui/gtkui/gtkui.py @@ -56,7 +56,7 @@ from deluge.ui.tracker_icons import TrackerIcons from deluge.ui.util import lang -gobject.set_prgname("deluge") +gobject.set_prgname('deluge') log = logging.getLogger(__name__) @@ -71,64 +71,64 @@ except ImportError: DEFAULT_PREFS = { - "standalone": True, - "interactive_add": True, - "focus_add_dialog": True, - "enable_system_tray": True, - "close_to_tray": False, - "start_in_tray": False, - "enable_appindicator": False, - "lock_tray": False, - "tray_password": "", - "check_new_releases": True, - "default_load_path": None, - "window_maximized": False, - "window_x_pos": 0, - "window_y_pos": 0, - "window_width": 640, - "window_height": 480, - "pref_dialog_width": None, - "pref_dialog_height": None, - "edit_trackers_dialog_width": None, - "edit_trackers_dialog_height": None, - "window_pane_position": 235, - "tray_download_speed_list": [5.0, 10.0, 30.0, 80.0, 300.0], - "tray_upload_speed_list": [5.0, 10.0, 30.0, 80.0, 300.0], - "connection_limit_list": [50, 100, 200, 300, 500], - "enabled_plugins": [], - "show_connection_manager_on_start": True, - "autoconnect": False, - "autoconnect_host_id": None, - "autostart_localhost": False, - "autoadd_queued": False, - "choose_directory_dialog_path": deluge.common.get_default_download_dir(), - "show_new_releases": True, - "ntf_tray_blink": True, - "ntf_sound": False, - "ntf_sound_path": deluge.common.get_default_download_dir(), - "ntf_popup": False, - "ntf_email": False, - "ntf_email_add": "", - "ntf_username": "", - "ntf_pass": "", - "ntf_server": "", - "ntf_security": None, - "show_sidebar": True, - "show_toolbar": True, - "show_statusbar": True, - "sidebar_show_zero": False, - "sidebar_show_trackers": True, - "sidebar_show_owners": True, - "sidebar_position": 170, - "show_rate_in_title": False, - "createtorrent.trackers": [], - "show_piecesbar": False, - "pieces_color_missing": [65535, 0, 0], - "pieces_color_waiting": [4874, 56494, 0], - "pieces_color_downloading": [65535, 55255, 0], - "pieces_color_completed": [4883, 26985, 56540], - "focus_main_window_on_add": True, - "language": None, + 'standalone': True, + 'interactive_add': True, + 'focus_add_dialog': True, + 'enable_system_tray': True, + 'close_to_tray': False, + 'start_in_tray': False, + 'enable_appindicator': False, + 'lock_tray': False, + 'tray_password': '', + 'check_new_releases': True, + 'default_load_path': None, + 'window_maximized': False, + 'window_x_pos': 0, + 'window_y_pos': 0, + 'window_width': 640, + 'window_height': 480, + 'pref_dialog_width': None, + 'pref_dialog_height': None, + 'edit_trackers_dialog_width': None, + 'edit_trackers_dialog_height': None, + 'window_pane_position': 235, + 'tray_download_speed_list': [5.0, 10.0, 30.0, 80.0, 300.0], + 'tray_upload_speed_list': [5.0, 10.0, 30.0, 80.0, 300.0], + 'connection_limit_list': [50, 100, 200, 300, 500], + 'enabled_plugins': [], + 'show_connection_manager_on_start': True, + 'autoconnect': False, + 'autoconnect_host_id': None, + 'autostart_localhost': False, + 'autoadd_queued': False, + 'choose_directory_dialog_path': deluge.common.get_default_download_dir(), + 'show_new_releases': True, + 'ntf_tray_blink': True, + 'ntf_sound': False, + 'ntf_sound_path': deluge.common.get_default_download_dir(), + 'ntf_popup': False, + 'ntf_email': False, + 'ntf_email_add': '', + 'ntf_username': '', + 'ntf_pass': '', + 'ntf_server': '', + 'ntf_security': None, + 'show_sidebar': True, + 'show_toolbar': True, + 'show_statusbar': True, + 'sidebar_show_zero': False, + 'sidebar_show_trackers': True, + 'sidebar_show_owners': True, + 'sidebar_position': 170, + 'show_rate_in_title': False, + 'createtorrent.trackers': [], + 'show_piecesbar': False, + 'pieces_color_missing': [65535, 0, 0], + 'pieces_color_waiting': [4874, 56494, 0], + 'pieces_color_downloading': [65535, 55255, 0], + 'pieces_color_completed': [4883, 26985, 56540], + 'focus_main_window_on_add': True, + 'language': None, } @@ -147,10 +147,10 @@ class GtkUI(object): SetConsoleCtrlHandler(on_die, True) log.debug("Win32 'die' handler registered") elif deluge.common.osx_check(): - if gtk.gdk.WINDOWING == "quartz": + if gtk.gdk.WINDOWING == 'quartz': import gtkosx_application self.osxapp = gtkosx_application.gtkosx_application_get() - self.osxapp.connect("NSApplicationWillTerminate", on_die) + self.osxapp.connect('NSApplicationWillTerminate', on_die) log.debug("OSX quartz 'die' handler registered") # Set process name again to fix gtk issue @@ -161,15 +161,15 @@ class GtkUI(object): associate_magnet_links(False) # Make sure gtkui.conf has at least the defaults set - self.config = ConfigManager("gtkui.conf", DEFAULT_PREFS) + self.config = ConfigManager('gtkui.conf', DEFAULT_PREFS) # Make sure the gtkui state folder has been created - if not os.path.exists(os.path.join(get_config_dir(), "gtkui_state")): - os.makedirs(os.path.join(get_config_dir(), "gtkui_state")) + if not os.path.exists(os.path.join(get_config_dir(), 'gtkui_state')): + os.makedirs(os.path.join(get_config_dir(), 'gtkui_state')) # Set language - if self.config["language"] is not None: - lang.set_language(self.config["language"]) + if self.config['language'] is not None: + lang.set_language(self.config['language']) # Start the IPC Interface before anything else.. Just in case we are # already running. @@ -197,13 +197,13 @@ class GtkUI(object): self.statusbar = StatusBar() self.addtorrentdialog = AddTorrentDialog() - if deluge.common.osx_check() and gtk.gdk.WINDOWING == "quartz": + if deluge.common.osx_check() and gtk.gdk.WINDOWING == 'quartz': def nsapp_open_file(osxapp, filename): # Ignore command name which is raised at app launch (python opening main script). if filename == sys.argv[0]: return True process_args([filename]) - self.osxapp.connect("NSApplicationOpenFile", nsapp_open_file) + self.osxapp.connect('NSApplicationOpenFile', nsapp_open_file) from deluge.ui.gtkui.menubar_osx import menubar_osx menubar_osx(self, self.osxapp) self.osxapp.ready() @@ -221,7 +221,7 @@ class GtkUI(object): self.closing = False # Twisted catches signals to terminate, so have it call a pre_shutdown method. - reactor.addSystemEventTrigger("before", "gtkui_close", self.close) + reactor.addSystemEventTrigger('before', 'gtkui_close', self.close) def gtkui_sigint_handler(num, frame): log.debug("SIGINT signal caught - firing event: 'gtkui_close'") @@ -240,7 +240,7 @@ class GtkUI(object): gtk.gdk.threads_leave() def shutdown(self, *args, **kwargs): - log.debug("GTKUI shutting down...") + log.debug('GTKUI shutting down...') # Shutdown all components if client.is_standalone: return component.shutdown() @@ -276,21 +276,21 @@ class GtkUI(object): self.daemon_bps = (t, sent, recv) sent_rate = deluge.common.fspeed(delta_sent / delta_time) recv_rate = deluge.common.fspeed(delta_recv / delta_time) - log.debug("RPC: Sent %s (%s) Recv %s (%s)", + log.debug('RPC: Sent %s (%s) Recv %s (%s)', deluge.common.fsize(sent), sent_rate, deluge.common.fsize(recv), recv_rate) def _on_reactor_start(self): - log.debug("_on_reactor_start") + log.debug('_on_reactor_start') self.mainwindow.first_show() - if self.config["standalone"]: + if self.config['standalone']: def on_dialog_response(response): if response != gtk.RESPONSE_YES: # The user does not want to turn Standalone Mode off, so just quit self.mainwindow.quit() return # Turning off standalone - self.config["standalone"] = False + self.config['standalone'] = False self.__start_thinclient() try: @@ -298,19 +298,19 @@ class GtkUI(object): client.start_standalone() except DaemonRunningError: d = YesNoDialog( - _("Switch to Thin Client Mode?"), - _("A Deluge daemon process (deluged) is already running. " - "To use Standalone mode, stop this daemon and restart Deluge." - "\n\n" - "Continue in Thin Client mode?")).run() + _('Switch to Thin Client Mode?'), + _('A Deluge daemon process (deluged) is already running. ' + 'To use Standalone mode, stop this daemon and restart Deluge.' + '\n\n' + 'Continue in Thin Client mode?')).run() d.addCallback(on_dialog_response) except ImportError as ex: - if "No module named libtorrent" in ex.message: + if 'No module named libtorrent' in ex.message: d = YesNoDialog( - _("Switch to Thin Client Mode?"), - _("Only Thin Client mode is available because libtorrent is not installed." - "\n\n" - "To use Deluge Standalone mode, please install libtorrent.")).run() + _('Switch to Thin Client Mode?'), + _('Only Thin Client mode is available because libtorrent is not installed.' + '\n\n' + 'To use Deluge Standalone mode, please install libtorrent.')).run() d.addCallback(on_dialog_response) else: raise ex @@ -321,15 +321,15 @@ class GtkUI(object): import traceback tb = sys.exc_info() ed = ErrorDialog( - _("Error Starting Core"), - _("An error occurred starting the core component required to run Deluge in Standalone mode." - "\n\n" - "Please see the details below for more information."), details=traceback.format_exc(tb[2])).run() + _('Error Starting Core'), + _('An error occurred starting the core component required to run Deluge in Standalone mode.' + '\n\n' + 'Please see the details below for more information.'), details=traceback.format_exc(tb[2])).run() def on_ed_response(response): d = YesNoDialog( - _("Switch to Thin Client Mode?"), - _("Unable to start Standalone mode would you like to continue in Thin Client mode?") + _('Switch to Thin Client Mode?'), + _('Unable to start Standalone mode would you like to continue in Thin Client mode?') ).run() d.addCallback(on_dialog_response) ed.addCallback(on_ed_response) @@ -339,35 +339,35 @@ class GtkUI(object): def __start_thinclient(self): # Autoconnect to a host - if self.config["autoconnect"]: + if self.config['autoconnect']: def update_connection_manager(): if not self.connectionmanager.running: return - self.connectionmanager.builder.get_object("button_refresh").emit("clicked") + self.connectionmanager.builder.get_object('button_refresh').emit('clicked') def close_connection_manager(): if not self.connectionmanager.running: return - self.connectionmanager.builder.get_object("button_close").emit("clicked") + self.connectionmanager.builder.get_object('button_close').emit('clicked') - for host_config in self.connectionmanager.config["hosts"]: + for host_config in self.connectionmanager.config['hosts']: hostid, host, port, user, passwd = host_config - if hostid == self.config["autoconnect_host_id"]: + if hostid == self.config['autoconnect_host_id']: try_connect = True # Check to see if we need to start the localhost daemon - if self.config["autostart_localhost"] and host in ("localhost", "127.0.0.1"): - log.debug("Autostarting localhost:%s", host) + if self.config['autostart_localhost'] and host in ('localhost', '127.0.0.1'): + log.debug('Autostarting localhost:%s', host) try_connect = client.start_daemon( port, get_config_dir() ) - log.debug("Localhost started: %s", try_connect) + log.debug('Localhost started: %s', try_connect) if not try_connect: ErrorDialog( - _("Error Starting Daemon"), - _("There was an error starting the daemon " - "process. Try running it from a console " - "to see if there is an error.") + _('Error Starting Daemon'), + _('There was an error starting the daemon ' + 'process. Try running it from a console ' + 'to see if there is an error.') ).run() # Daemon Started, let's update it's info @@ -384,7 +384,7 @@ class GtkUI(object): return if reason.check(AuthenticationRequired, BadLoginError): - log.debug("PasswordRequired exception") + log.debug('PasswordRequired exception') dialog = AuthenticationDialog(reason.value.message, reason.value.username) def dialog_finished(response_id, host, port): @@ -396,15 +396,15 @@ class GtkUI(object): dialog.run().addCallback(dialog_finished, host, port) return - log.info("Connection to host failed..") - log.info("Retrying connection.. Retries left: " - "%s", try_counter) + log.info('Connection to host failed..') + log.info('Retrying connection.. Retries left: ' + '%s', try_counter) reactor.callLater(0.5, update_connection_manager) reactor.callLater(0.5, do_connect, try_counter - 1, host, port, user, passwd) def do_connect(try_counter, host, port, user, passwd): - log.debug("Trying to connect to %s@%s:%s", + log.debug('Trying to connect to %s@%s:%s', user, host, port) d = client.connect(host, port, user, passwd) d.addCallback(on_connect) @@ -417,7 +417,7 @@ class GtkUI(object): ) break - if self.config["show_connection_manager_on_start"]: + if self.config['show_connection_manager_on_start']: if deluge.common.windows_check(): # Call to simulate() required to workaround showing daemon status (see #2813) reactor.simulate() diff --git a/deluge/ui/gtkui/ipcinterface.py b/deluge/ui/gtkui/ipcinterface.py index 22eaa7a23..ba83c5682 100644 --- a/deluge/ui/gtkui/ipcinterface.py +++ b/deluge/ui/gtkui/ipcinterface.py @@ -39,10 +39,10 @@ class IPCProtocolServer(Protocol): pass def dataReceived(self, data): # NOQA - config = ConfigManager("gtkui.conf") + config = ConfigManager('gtkui.conf') data = rencode.loads(data, decode_utf8=True) - if not data or config["focus_main_window_on_add"]: - component.get("MainWindow").present() + if not data or config['focus_main_window_on_add']: + component.get('MainWindow').present() process_args(data) @@ -67,25 +67,25 @@ class IPCClientFactory(ClientFactory): self.stop = False def clientConnectionFailed(self, connector, reason): # NOQA - log.warning("Connection to running instance failed.") + log.warning('Connection to running instance failed.') reactor.stop() class IPCInterface(component.Component): def __init__(self, args): - component.Component.__init__(self, "IPCInterface") + component.Component.__init__(self, 'IPCInterface') self.listener = None - ipc_dir = get_config_dir("ipc") + ipc_dir = get_config_dir('ipc') if not os.path.exists(ipc_dir): os.makedirs(ipc_dir) - socket = os.path.join(ipc_dir, "deluge-gtk") + socket = os.path.join(ipc_dir, 'deluge-gtk') if windows_check(): # If we're on windows we need to check the global mutex to see if deluge is # already running. import win32event import win32api import winerror - self.mutex = win32event.CreateMutex(None, False, "deluge") + self.mutex = win32event.CreateMutex(None, False, 'deluge') if win32api.GetLastError() != winerror.ERROR_ALREADY_EXISTS: # Create listen socket self.factory = Factory() @@ -94,7 +94,7 @@ class IPCInterface(component.Component): port = random.randrange(20000, 65535) self.listener = reactor.listenTCP(port, self.factory) # Store the port number in the socket file - with open(socket, "w") as _file: + with open(socket, 'w') as _file: _file.write(str(port)) # We need to process any args when starting this process process_args(args) @@ -105,7 +105,7 @@ class IPCInterface(component.Component): self.factory = ClientFactory() self.factory.args = args self.factory.protocol = IPCProtocolClient - reactor.connectTCP("127.0.0.1", port, self.factory) + reactor.connectTCP('127.0.0.1', port, self.factory) reactor.run() sys.exit(0) else: @@ -113,8 +113,8 @@ class IPCInterface(component.Component): restart_tempfile = glob(os.path.join(ipc_dir, 'restart.*')) for f in restart_tempfile: os.remove(f) - lockfile = socket + ".lock" - log.debug("Checking if lockfile exists: %s", lockfile) + lockfile = socket + '.lock' + log.debug('Checking if lockfile exists: %s', lockfile) if os.path.lexists(lockfile): def delete_lockfile(): log.debug("Removing lockfile since it's stale.") @@ -122,7 +122,7 @@ class IPCInterface(component.Component): os.remove(lockfile) os.remove(socket) except OSError as ex: - log.error("Failed to delete lockfile: %s", ex) + log.error('Failed to delete lockfile: %s', ex) try: os.kill(int(os.readlink(lockfile)), 0) @@ -130,26 +130,26 @@ class IPCInterface(component.Component): delete_lockfile() else: if restart_tempfile: - log.warning("Found running PID but it is not a Deluge process, removing lockfile...") + log.warning('Found running PID but it is not a Deluge process, removing lockfile...') delete_lockfile() try: self.factory = Factory() self.factory.protocol = IPCProtocolServer self.listener = reactor.listenUNIX(socket, self.factory, wantPID=True) except twisted.internet.error.CannotListenError as ex: - log.info("Deluge is already running! Sending arguments to running instance...") + log.info('Deluge is already running! Sending arguments to running instance...') self.factory = IPCClientFactory() self.factory.args = args reactor.connectUNIX(socket, self.factory, checkPID=True) reactor.run() if self.factory.stop: - log.info("Success sending arguments to running Deluge.") + log.info('Success sending arguments to running Deluge.') import gtk gtk.gdk.notify_startup_complete() sys.exit(0) else: if restart_tempfile: - log.error("Deluge restart failed: %s", ex) + log.error('Deluge restart failed: %s', ex) sys.exit(1) else: log.warning('Restarting Deluge... (%s)', ex) @@ -171,49 +171,49 @@ def process_args(args): """Process arguments sent to already running Deluge""" # Make sure args is a list args = list(args) - log.debug("Processing args from other process: %s", args) + log.debug('Processing args from other process: %s', args) if not client.connected(): # We're not connected so add these to the queue - log.debug("Not connected to host.. Adding to queue.") - component.get("QueuedTorrents").add_to_queue(args) + log.debug('Not connected to host.. Adding to queue.') + component.get('QueuedTorrents').add_to_queue(args) return - config = ConfigManager("gtkui.conf") + config = ConfigManager('gtkui.conf') for arg in args: if not arg.strip(): continue - log.debug("arg: %s", arg) + log.debug('arg: %s', arg) if is_url(arg): - log.debug("Attempting to add url (%s) from external source...", arg) - if config["interactive_add"]: - component.get("AddTorrentDialog").add_from_url(arg) - component.get("AddTorrentDialog").show(config["focus_add_dialog"]) + log.debug('Attempting to add url (%s) from external source...', arg) + if config['interactive_add']: + component.get('AddTorrentDialog').add_from_url(arg) + component.get('AddTorrentDialog').show(config['focus_add_dialog']) else: client.core.add_torrent_url(arg, None) elif is_magnet(arg): - log.debug("Attempting to add magnet (%s) from external source...", arg) - if config["interactive_add"]: - component.get("AddTorrentDialog").add_from_magnets([arg]) - component.get("AddTorrentDialog").show(config["focus_add_dialog"]) + log.debug('Attempting to add magnet (%s) from external source...', arg) + if config['interactive_add']: + component.get('AddTorrentDialog').add_from_magnets([arg]) + component.get('AddTorrentDialog').show(config['focus_add_dialog']) else: client.core.add_torrent_magnet(arg, {}) else: - log.debug("Attempting to add file (%s) from external source...", arg) - if urlparse(arg).scheme == "file": + log.debug('Attempting to add file (%s) from external source...', arg) + if urlparse(arg).scheme == 'file': arg = url2pathname(urlparse(arg).path) path = os.path.abspath(decode_string(arg)) if not os.path.exists(path): - log.error("No such file: %s", path) + log.error('No such file: %s', path) continue - if config["interactive_add"]: - component.get("AddTorrentDialog").add_from_files([path]) - component.get("AddTorrentDialog").show(config["focus_add_dialog"]) + if config['interactive_add']: + component.get('AddTorrentDialog').add_from_files([path]) + component.get('AddTorrentDialog').show(config['focus_add_dialog']) else: - with open(path, "rb") as _file: + with open(path, 'rb') as _file: filedump = base64.encodestring(_file.read()) client.core.add_torrent_file(os.path.split(path)[-1], filedump, None) diff --git a/deluge/ui/gtkui/listview.py b/deluge/ui/gtkui/listview.py index 004560973..27ea626b8 100644 --- a/deluge/ui/gtkui/listview.py +++ b/deluge/ui/gtkui/listview.py @@ -124,7 +124,7 @@ class ListView(object): self.set_attributes(renderer, **kw) def __init__(self, treeview_widget=None, state_file=None): - log.debug("ListView initialized..") + log.debug('ListView initialized..') if treeview_widget is not None: # User supplied a treeview widget @@ -169,7 +169,7 @@ class ListView(object): self.default_sort_column_id = None # Create the model filter and column - self.add_bool_column("filter", hidden=True) + self.add_bool_column('filter', hidden=True) def create_model_filter(self): """create new filter-model @@ -177,10 +177,10 @@ class ListView(object): """ model_filter = self.liststore.filter_new() model_filter.set_visible_column( - self.columns["filter"].column_indices[0]) + self.columns['filter'].column_indices[0]) self.model_filter = gtk.TreeModelSort(model_filter) - self.model_filter.connect("sort-column-changed", self.on_model_sort_changed) - self.model_filter.connect("row-inserted", self.on_model_row_inserted) + self.model_filter.connect('sort-column-changed', self.on_model_sort_changed) + self.model_filter.connect('row-inserted', self.on_model_row_inserted) self.treeview.set_model(self.model_filter) self.set_sort_functions() self.set_model_sort() @@ -350,7 +350,7 @@ class ListView(object): if column.column.get_visible() is True: menuitem.set_active(True) # Connect to the 'toggled' event - menuitem.connect("toggled", self.on_menuitem_toggled) + menuitem.connect('toggled', self.on_menuitem_toggled) # Add the new checkmenuitem to the menu menu.append(menuitem) @@ -388,23 +388,23 @@ class ListView(object): column = self.columns[header] tree_column = self.columns[header].column - if column.column_type == "text": + if column.column_type == 'text': if add: tree_column.pack_start(column.renderer) tree_column.set_col_attributes(column.renderer, add=add, text=column.column_indices[column.text_index]) - elif column.column_type == "bool": + elif column.column_type == 'bool': if add: tree_column.pack_start(column.renderer) tree_column.set_col_attributes(column.renderer, active=column.column_indices[0]) - elif column.column_type == "func": + elif column.column_type == 'func': if add: tree_column.pack_start(column.renderer, True) indice_arg = column.column_indices[0] if len(column.column_indices) > 1: indice_arg = tuple(column.column_indices) tree_column.set_cell_data_func(column.renderer, column.data_func, indice_arg) - elif column.column_type == "progress": + elif column.column_type == 'progress': if add: tree_column.pack_start(column.renderer) if column.data_func is None: @@ -414,7 +414,7 @@ class ListView(object): else: tree_column.set_cell_data_func(column.renderer, column.data_func, tuple(column.column_indices)) - elif column.column_type == "texticon": + elif column.column_type == 'texticon': if add: tree_column.pack_start(column.renderer[column.pixbuf_index], False) tree_column.pack_start(column.renderer[column.text_index], True) @@ -563,7 +563,7 @@ class ListView(object): return True def add_text_column(self, header, col_type=str, hidden=False, position=None, - status_field=None, sortid=0, column_type="text", + status_field=None, sortid=0, column_type='text', sort_func=None, tooltip=None, default=True, unique=False, default_sort=False): """Add a text column to the listview. Only the header name is required. @@ -578,7 +578,7 @@ class ListView(object): def add_bool_column(self, header, col_type=bool, hidden=False, position=None, status_field=None, sortid=0, - column_type="bool", tooltip=None, default=True): + column_type='bool', tooltip=None, default=True): """Add a bool column to the listview""" render = gtk.CellRendererToggle() self.add_column(header, render, col_type, hidden, position, @@ -587,7 +587,7 @@ class ListView(object): def add_func_column(self, header, function, col_types, sortid=0, hidden=False, position=None, status_field=None, - column_type="func", sort_func=None, tooltip=None, default=True): + column_type='func', sort_func=None, tooltip=None, default=True): """Add a function column to the listview. Need a header name, the function and the column types.""" @@ -600,7 +600,7 @@ class ListView(object): def add_progress_column(self, header, col_types=None, sortid=0, hidden=False, position=None, status_field=None, - function=None, column_type="progress", + function=None, column_type='progress', tooltip=None, sort_func=None, default=True): """Add a progress column to the listview.""" @@ -616,7 +616,7 @@ class ListView(object): def add_texticon_column(self, header, col_types=None, sortid=1, hidden=False, position=None, status_field=None, - column_type="texticon", function=None, sort_func=None, + column_type='texticon', function=None, sort_func=None, tooltip=None, default=True, default_sort=False): """Adds a texticon column to the listview.""" if col_types is None: @@ -632,7 +632,7 @@ class ListView(object): return True def on_keypress_search_by_name(self, model, column, key, _iter): - torrent_name_col = self.columns["Name"].column_indices[1] + torrent_name_col = self.columns['Name'].column_indices[1] return not model[_iter][torrent_name_col].lower().startswith(key.lower()) def restore_columns_order_from_state(self): diff --git a/deluge/ui/gtkui/mainwindow.py b/deluge/ui/gtkui/mainwindow.py index c365daac5..a02a2dd06 100644 --- a/deluge/ui/gtkui/mainwindow.py +++ b/deluge/ui/gtkui/mainwindow.py @@ -44,7 +44,7 @@ class _GtkBuilderSignalsHolder(object): for name, handler in mapping_or_class.iteritems(): if hasattr(self, name): raise RuntimeError( - "A handler for signal %r has already been registered: %s" % + 'A handler for signal %r has already been registered: %s' % (name, getattr(self, name)) ) setattr(self, name, handler) @@ -53,7 +53,7 @@ class _GtkBuilderSignalsHolder(object): if not name.startswith('on_'): continue if hasattr(self, name): - raise RuntimeError("A handler for signal %r has already been registered: %s" % + raise RuntimeError('A handler for signal %r has already been registered: %s' % (name, getattr(self, name))) setattr(self, name, getattr(mapping_or_class, name)) @@ -62,8 +62,8 @@ class MainWindow(component.Component): def __init__(self): if wnck: self.screen = wnck.screen_get_default() - component.Component.__init__(self, "MainWindow", interval=2) - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'MainWindow', interval=2) + self.config = ConfigManager('gtkui.conf') self.gtk_builder_signals_holder = _GtkBuilderSignalsHolder() self.main_builder = gtk.Builder() # Patch this GtkBuilder to avoid connecting signals from elsewhere @@ -74,32 +74,32 @@ class MainWindow(component.Component): self.main_builder.prev_connect_signals = copy.deepcopy(self.main_builder.connect_signals) def patched_connect_signals(*a, **k): - raise RuntimeError("In order to connect signals to this GtkBuilder instance please use " + raise RuntimeError('In order to connect signals to this GtkBuilder instance please use ' "'component.get(\"MainWindow\").connect_signals()'") self.main_builder.connect_signals = patched_connect_signals # Get the gtk builder file for the main window self.main_builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "main_window.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'main_window.ui'))) # The new release dialog self.main_builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "main_window.new_release.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'main_window.new_release.ui'))) # The tabs self.main_builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.ui'))) # The tabs file menu self.main_builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.menu_file.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.menu_file.ui'))) # The tabs peer menu self.main_builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "main_window.tabs.menu_peer.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'main_window.tabs.menu_peer.ui'))) - self.window = self.main_builder.get_object("main_window") + self.window = self.main_builder.get_object('main_window') self.window.set_icon(deluge.ui.gtkui.common.get_deluge_icon()) - self.vpaned = self.main_builder.get_object("vpaned") + self.vpaned = self.main_builder.get_object('vpaned') - self.initial_vpaned_position = self.config["window_pane_position"] + self.initial_vpaned_position = self.config['window_pane_position'] # Load the window state self.load_window_state() @@ -111,25 +111,25 @@ class MainWindow(component.Component): self.window.drag_dest_set(gtk.DEST_DEFAULT_ALL, [('text/uri-list', 0, 80)], gtk.gdk.ACTION_COPY) # Connect events - self.window.connect("window-state-event", self.on_window_state_event) - self.window.connect("configure-event", self.on_window_configure_event) - self.window.connect("delete-event", self.on_window_delete_event) - self.window.connect("drag-data-received", self.on_drag_data_received_event) - self.vpaned.connect("notify::position", self.on_vpaned_position_event) - self.window.connect("expose-event", self.on_expose_event) + self.window.connect('window-state-event', self.on_window_state_event) + self.window.connect('configure-event', self.on_window_configure_event) + self.window.connect('delete-event', self.on_window_delete_event) + self.window.connect('drag-data-received', self.on_drag_data_received_event) + self.vpaned.connect('notify::position', self.on_vpaned_position_event) + self.window.connect('expose-event', self.on_expose_event) - self.config.register_set_function("show_rate_in_title", self._on_set_show_rate_in_title, apply_now=False) + self.config.register_set_function('show_rate_in_title', self._on_set_show_rate_in_title, apply_now=False) - client.register_event_handler("NewVersionAvailableEvent", self.on_newversionavailable_event) + client.register_event_handler('NewVersionAvailableEvent', self.on_newversionavailable_event) def connect_signals(self, mapping_or_class): self.gtk_builder_signals_holder.connect_signals(mapping_or_class) def first_show(self): - if not(self.config["start_in_tray"] and - self.config["enable_system_tray"]) and not \ - self.window.get_property("visible"): - log.debug("Showing window") + if not(self.config['start_in_tray'] and + self.config['enable_system_tray']) and not \ + self.window.get_property('visible'): + log.debug('Showing window') self.main_builder.prev_connect_signals(self.gtk_builder_signals_holder) self.vpaned.set_position(self.initial_vpaned_position) self.show() @@ -138,18 +138,18 @@ class MainWindow(component.Component): def show(self): try: - component.resume("TorrentView") - component.resume("StatusBar") - component.resume("TorrentDetails") + component.resume('TorrentView') + component.resume('StatusBar') + component.resume('TorrentDetails') except Exception: pass self.window.show() def hide(self): - component.pause("TorrentView") - component.get("TorrentView").save_state() - component.pause("StatusBar") - component.pause("TorrentDetails") + component.pause('TorrentView') + component.get('TorrentView').save_state() + component.pause('StatusBar') + component.pause('TorrentDetails') # Store the x, y positions for when we restore the window self.window_x_pos = self.window.get_position()[0] self.window_y_pos = self.window.get_position()[1] @@ -160,29 +160,29 @@ class MainWindow(component.Component): # Restore the proper x,y coords for the window prior to showing it try: if self.window_x_pos == -32000 or self.window_y_pos == -32000: - self.config["window_x_pos"] = 0 - self.config["window_y_pos"] = 0 + self.config['window_x_pos'] = 0 + self.config['window_y_pos'] = 0 else: - self.config["window_x_pos"] = self.window_x_pos - self.config["window_y_pos"] = self.window_y_pos + self.config['window_x_pos'] = self.window_x_pos + self.config['window_y_pos'] = self.window_y_pos except Exception: pass try: - component.resume("TorrentView") - component.resume("StatusBar") - component.resume("TorrentDetails") + component.resume('TorrentView') + component.resume('StatusBar') + component.resume('TorrentDetails') except Exception: pass self.window.present() self.load_window_state() - if self.config["lock_tray"] and not self.visible(): - dialog = PasswordDialog(_("Enter your password to show Deluge...")) + if self.config['lock_tray'] and not self.visible(): + dialog = PasswordDialog(_('Enter your password to show Deluge...')) def on_dialog_response(response_id): if response_id == gtk.RESPONSE_OK: - if self.config["tray_password"] == sha(dialog.get_password()).hexdigest(): + if self.config['tray_password'] == sha(dialog.get_password()).hexdigest(): restore() dialog.run().addCallback(on_dialog_response) else: @@ -194,7 +194,7 @@ class MainWindow(component.Component): def visible(self): """Returns True if window is visible, False if not.""" - return self.window.get_property("visible") + return self.window.get_property('visible') def get_builder(self): """Returns a reference to the main window GTK builder object.""" @@ -212,7 +212,7 @@ class MainWindow(component.Component): try: reactor.callLater(0, reactor.fireSystemEvent, 'gtkui_close') except ReactorNotRunning: - log.debug("Attempted to stop the reactor but it is not running...") + log.debug('Attempted to stop the reactor but it is not running...') if shutdown: client.daemon.shutdown().addCallback(stop_gtk_reactor) @@ -221,59 +221,59 @@ class MainWindow(component.Component): else: stop_gtk_reactor() - if self.config["lock_tray"] and not self.visible(): - dialog = PasswordDialog(_("Enter your password to Quit Deluge...")) + if self.config['lock_tray'] and not self.visible(): + dialog = PasswordDialog(_('Enter your password to Quit Deluge...')) def on_dialog_response(response_id): if response_id == gtk.RESPONSE_OK: - if self.config["tray_password"] == sha(dialog.get_password()).hexdigest(): + if self.config['tray_password'] == sha(dialog.get_password()).hexdigest(): quit_gtkui() dialog.run().addCallback(on_dialog_response) else: quit_gtkui() def load_window_state(self): - x = self.config["window_x_pos"] - y = self.config["window_y_pos"] - w = self.config["window_width"] - h = self.config["window_height"] + x = self.config['window_x_pos'] + y = self.config['window_y_pos'] + w = self.config['window_width'] + h = self.config['window_height'] self.window.move(x, y) self.window.resize(w, h) - if self.config["window_maximized"]: + if self.config['window_maximized']: self.window.maximize() def on_window_configure_event(self, widget, event): - if not self.config["window_maximized"] and self.visible: - self.config["window_x_pos"] = self.window.get_position()[0] - self.config["window_y_pos"] = self.window.get_position()[1] - self.config["window_width"] = event.width - self.config["window_height"] = event.height + if not self.config['window_maximized'] and self.visible: + self.config['window_x_pos'] = self.window.get_position()[0] + self.config['window_y_pos'] = self.window.get_position()[1] + self.config['window_width'] = event.width + self.config['window_height'] = event.height def on_window_state_event(self, widget, event): if event.changed_mask & gtk.gdk.WINDOW_STATE_MAXIMIZED: if event.new_window_state & gtk.gdk.WINDOW_STATE_MAXIMIZED: - log.debug("pos: %s", self.window.get_position()) - self.config["window_maximized"] = True + log.debug('pos: %s', self.window.get_position()) + self.config['window_maximized'] = True elif not event.new_window_state & gtk.gdk.WINDOW_STATE_WITHDRAWN: - self.config["window_maximized"] = False + self.config['window_maximized'] = False if event.changed_mask & gtk.gdk.WINDOW_STATE_ICONIFIED: if event.new_window_state & gtk.gdk.WINDOW_STATE_ICONIFIED: - log.debug("MainWindow is minimized..") - component.pause("TorrentView") - component.pause("StatusBar") + log.debug('MainWindow is minimized..') + component.pause('TorrentView') + component.pause('StatusBar') self.is_minimized = True else: - log.debug("MainWindow is not minimized..") + log.debug('MainWindow is not minimized..') try: - component.resume("TorrentView") - component.resume("StatusBar") + component.resume('TorrentView') + component.resume('StatusBar') except Exception: pass self.is_minimized = False return False def on_window_delete_event(self, widget, event): - if self.config["close_to_tray"] and self.config["enable_system_tray"]: + if self.config['close_to_tray'] and self.config['enable_system_tray']: self.hide() else: self.quit() @@ -281,10 +281,10 @@ class MainWindow(component.Component): return True def on_vpaned_position_event(self, obj, param): - self.config["window_pane_position"] = self.vpaned.get_position() + self.config['window_pane_position'] = self.vpaned.get_position() def on_drag_data_received_event(self, widget, drag_context, x, y, selection_data, info, timestamp): - log.debug("Selection(s) dropped on main window %s", selection_data.data) + log.debug('Selection(s) dropped on main window %s', selection_data.data) if selection_data.get_uris(): process_args(selection_data.get_uris()) else: @@ -292,29 +292,29 @@ class MainWindow(component.Component): drag_context.finish(True, True) def on_expose_event(self, widget, event): - component.get("SystemTray").blink(False) + component.get('SystemTray').blink(False) def stop(self): - self.window.set_title("Deluge") + self.window.set_title('Deluge') def update(self): # Update the window title def _on_get_session_status(status): - download_rate = deluge.common.fspeed(status["payload_download_rate"], precision=0, shortform=True) - upload_rate = deluge.common.fspeed(status["payload_upload_rate"], precision=0, shortform=True) - self.window.set_title(_("D: %s U: %s - Deluge" % (download_rate, upload_rate))) - if self.config["show_rate_in_title"]: - client.core.get_session_status(["payload_download_rate", - "payload_upload_rate"]).addCallback(_on_get_session_status) + download_rate = deluge.common.fspeed(status['payload_download_rate'], precision=0, shortform=True) + upload_rate = deluge.common.fspeed(status['payload_upload_rate'], precision=0, shortform=True) + self.window.set_title(_('D: %s U: %s - Deluge' % (download_rate, upload_rate))) + if self.config['show_rate_in_title']: + client.core.get_session_status(['payload_download_rate', + 'payload_upload_rate']).addCallback(_on_get_session_status) def _on_set_show_rate_in_title(self, key, value): if value: self.update() else: - self.window.set_title(_("Deluge")) + self.window.set_title(_('Deluge')) def on_newversionavailable_event(self, new_version): - if self.config["show_new_releases"]: + if self.config['show_new_releases']: from deluge.ui.gtkui.new_release_dialog import NewReleaseDialog reactor.callLater(5.0, NewReleaseDialog().show, new_version) diff --git a/deluge/ui/gtkui/menubar.py b/deluge/ui/gtkui/menubar.py index b36f45e71..e002d5006 100644 --- a/deluge/ui/gtkui/menubar.py +++ b/deluge/ui/gtkui/menubar.py @@ -31,131 +31,131 @@ log = logging.getLogger(__name__) class MenuBar(component.Component): def __init__(self): - log.debug("MenuBar init..") - component.Component.__init__(self, "MenuBar") - self.window = component.get("MainWindow") + log.debug('MenuBar init..') + component.Component.__init__(self, 'MenuBar') + self.window = component.get('MainWindow') self.main_builder = self.window.get_builder() - self.config = ConfigManager("gtkui.conf") + self.config = ConfigManager('gtkui.conf') self.builder = gtk.Builder() # Get the torrent menu from the gtk builder file self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "torrent_menu.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.ui') )) # Get the torrent options menu from the gtk builder file self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "torrent_menu.options.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.options.ui') )) # Get the torrent queue menu from the gtk builder file self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "torrent_menu.queue.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'torrent_menu.queue.ui') )) # Attach queue torrent menu - torrent_queue_menu = self.builder.get_object("queue_torrent_menu") - self.builder.get_object("menuitem_queue").set_submenu(torrent_queue_menu) + torrent_queue_menu = self.builder.get_object('queue_torrent_menu') + self.builder.get_object('menuitem_queue').set_submenu(torrent_queue_menu) # Attach options torrent menu - torrent_options_menu = self.builder.get_object("options_torrent_menu") - self.builder.get_object("menuitem_options").set_submenu(torrent_options_menu) + torrent_options_menu = self.builder.get_object('options_torrent_menu') + self.builder.get_object('menuitem_options').set_submenu(torrent_options_menu) - self.builder.get_object("download-limit-image").set_from_file(deluge.common.get_pixmap("downloading16.png")) - self.builder.get_object("upload-limit-image").set_from_file(deluge.common.get_pixmap("seeding16.png")) + self.builder.get_object('download-limit-image').set_from_file(deluge.common.get_pixmap('downloading16.png')) + self.builder.get_object('upload-limit-image').set_from_file(deluge.common.get_pixmap('seeding16.png')) - for menuitem in ("menuitem_down_speed", "menuitem_up_speed", - "menuitem_max_connections", "menuitem_upload_slots"): + for menuitem in ('menuitem_down_speed', 'menuitem_up_speed', + 'menuitem_max_connections', 'menuitem_upload_slots'): submenu = gtk.Menu() - item = gtk.MenuItem(_("Set Unlimited")) + item = gtk.MenuItem(_('Set Unlimited')) item.set_name(menuitem) - item.connect("activate", self.on_menuitem_set_unlimited) + item.connect('activate', self.on_menuitem_set_unlimited) submenu.append(item) - item = gtk.MenuItem(_("Other...")) + item = gtk.MenuItem(_('Other...')) item.set_name(menuitem) - item.connect("activate", self.on_menuitem_set_other) + item.connect('activate', self.on_menuitem_set_other) submenu.append(item) submenu.show_all() self.builder.get_object(menuitem).set_submenu(submenu) submenu = gtk.Menu() - item = gtk.MenuItem(_("On")) - item.connect("activate", self.on_menuitem_set_automanaged_on) + item = gtk.MenuItem(_('On')) + item.connect('activate', self.on_menuitem_set_automanaged_on) submenu.append(item) - item = gtk.MenuItem(_("Off")) - item.connect("activate", self.on_menuitem_set_automanaged_off) + item = gtk.MenuItem(_('Off')) + item.connect('activate', self.on_menuitem_set_automanaged_off) submenu.append(item) submenu.show_all() - self.builder.get_object("menuitem_auto_managed").set_submenu(submenu) + self.builder.get_object('menuitem_auto_managed').set_submenu(submenu) submenu = gtk.Menu() - item = gtk.MenuItem(_("Disable")) - item.connect("activate", self.on_menuitem_set_stop_seed_at_ratio_disable) + item = gtk.MenuItem(_('Disable')) + item.connect('activate', self.on_menuitem_set_stop_seed_at_ratio_disable) submenu.append(item) - item = gtk.MenuItem(_("Enable...")) - item.set_name("menuitem_stop_seed_at_ratio") - item.connect("activate", self.on_menuitem_set_other) + item = gtk.MenuItem(_('Enable...')) + item.set_name('menuitem_stop_seed_at_ratio') + item.connect('activate', self.on_menuitem_set_other) submenu.append(item) submenu.show_all() - self.builder.get_object("menuitem_stop_seed_at_ratio").set_submenu(submenu) + self.builder.get_object('menuitem_stop_seed_at_ratio').set_submenu(submenu) - self.torrentmenu = self.builder.get_object("torrent_menu") - self.menu_torrent = self.main_builder.get_object("menu_torrent") + self.torrentmenu = self.builder.get_object('torrent_menu') + self.menu_torrent = self.main_builder.get_object('menu_torrent') # Attach the torrent_menu to the Torrent file menu self.menu_torrent.set_submenu(self.torrentmenu) # Make sure the view menuitems are showing the correct active state - self.main_builder.get_object("menuitem_toolbar").set_active(self.config["show_toolbar"]) - self.main_builder.get_object("menuitem_sidebar").set_active(self.config["show_sidebar"]) - self.main_builder.get_object("menuitem_statusbar").set_active(self.config["show_statusbar"]) - self.main_builder.get_object("sidebar_show_zero").set_active(self.config["sidebar_show_zero"]) - self.main_builder.get_object("sidebar_show_trackers").set_active(self.config["sidebar_show_trackers"]) - self.main_builder.get_object("sidebar_show_owners").set_active(self.config["sidebar_show_owners"]) + self.main_builder.get_object('menuitem_toolbar').set_active(self.config['show_toolbar']) + self.main_builder.get_object('menuitem_sidebar').set_active(self.config['show_sidebar']) + self.main_builder.get_object('menuitem_statusbar').set_active(self.config['show_statusbar']) + self.main_builder.get_object('sidebar_show_zero').set_active(self.config['sidebar_show_zero']) + self.main_builder.get_object('sidebar_show_trackers').set_active(self.config['sidebar_show_trackers']) + self.main_builder.get_object('sidebar_show_owners').set_active(self.config['sidebar_show_owners']) # Connect main window Signals # - component.get("MainWindow").connect_signals({ + component.get('MainWindow').connect_signals({ # File Menu - "on_menuitem_addtorrent_activate": self.on_menuitem_addtorrent_activate, - "on_menuitem_createtorrent_activate": self.on_menuitem_createtorrent_activate, - "on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate, - "on_menuitem_quit_activate": self.on_menuitem_quit_activate, + 'on_menuitem_addtorrent_activate': self.on_menuitem_addtorrent_activate, + 'on_menuitem_createtorrent_activate': self.on_menuitem_createtorrent_activate, + 'on_menuitem_quitdaemon_activate': self.on_menuitem_quitdaemon_activate, + 'on_menuitem_quit_activate': self.on_menuitem_quit_activate, # Edit Menu - "on_menuitem_preferences_activate": self.on_menuitem_preferences_activate, - "on_menuitem_connectionmanager_activate": self.on_menuitem_connectionmanager_activate, + 'on_menuitem_preferences_activate': self.on_menuitem_preferences_activate, + 'on_menuitem_connectionmanager_activate': self.on_menuitem_connectionmanager_activate, # View Menu - "on_menuitem_toolbar_toggled": self.on_menuitem_toolbar_toggled, - "on_menuitem_sidebar_toggled": self.on_menuitem_sidebar_toggled, - "on_menuitem_statusbar_toggled": self.on_menuitem_statusbar_toggled, + 'on_menuitem_toolbar_toggled': self.on_menuitem_toolbar_toggled, + 'on_menuitem_sidebar_toggled': self.on_menuitem_sidebar_toggled, + 'on_menuitem_statusbar_toggled': self.on_menuitem_statusbar_toggled, # Help Menu - "on_menuitem_homepage_activate": self.on_menuitem_homepage_activate, - "on_menuitem_faq_activate": self.on_menuitem_faq_activate, - "on_menuitem_community_activate": self.on_menuitem_community_activate, - "on_menuitem_about_activate": self.on_menuitem_about_activate, - "on_menuitem_sidebar_zero_toggled": self.on_menuitem_sidebar_zero_toggled, - "on_menuitem_sidebar_trackers_toggled": self.on_menuitem_sidebar_trackers_toggled, - "on_menuitem_sidebar_owners_toggled": self.on_menuitem_sidebar_owners_toggled + 'on_menuitem_homepage_activate': self.on_menuitem_homepage_activate, + 'on_menuitem_faq_activate': self.on_menuitem_faq_activate, + 'on_menuitem_community_activate': self.on_menuitem_community_activate, + 'on_menuitem_about_activate': self.on_menuitem_about_activate, + 'on_menuitem_sidebar_zero_toggled': self.on_menuitem_sidebar_zero_toggled, + 'on_menuitem_sidebar_trackers_toggled': self.on_menuitem_sidebar_trackers_toggled, + 'on_menuitem_sidebar_owners_toggled': self.on_menuitem_sidebar_owners_toggled }) # Connect menubar signals self.builder.connect_signals({ # Torrent Menu - "on_menuitem_pause_activate": self.on_menuitem_pause_activate, - "on_menuitem_resume_activate": self.on_menuitem_resume_activate, - "on_menuitem_updatetracker_activate": self.on_menuitem_updatetracker_activate, - "on_menuitem_edittrackers_activate": self.on_menuitem_edittrackers_activate, - "on_menuitem_remove_activate": self.on_menuitem_remove_activate, - "on_menuitem_recheck_activate": self.on_menuitem_recheck_activate, - "on_menuitem_open_folder_activate": self.on_menuitem_open_folder_activate, - "on_menuitem_move_activate": self.on_menuitem_move_activate, - "on_menuitem_queue_top_activate": self.on_menuitem_queue_top_activate, - "on_menuitem_queue_up_activate": self.on_menuitem_queue_up_activate, - "on_menuitem_queue_down_activate": self.on_menuitem_queue_down_activate, - "on_menuitem_queue_bottom_activate": self.on_menuitem_queue_bottom_activate + 'on_menuitem_pause_activate': self.on_menuitem_pause_activate, + 'on_menuitem_resume_activate': self.on_menuitem_resume_activate, + 'on_menuitem_updatetracker_activate': self.on_menuitem_updatetracker_activate, + 'on_menuitem_edittrackers_activate': self.on_menuitem_edittrackers_activate, + 'on_menuitem_remove_activate': self.on_menuitem_remove_activate, + 'on_menuitem_recheck_activate': self.on_menuitem_recheck_activate, + 'on_menuitem_open_folder_activate': self.on_menuitem_open_folder_activate, + 'on_menuitem_move_activate': self.on_menuitem_move_activate, + 'on_menuitem_queue_top_activate': self.on_menuitem_queue_top_activate, + 'on_menuitem_queue_up_activate': self.on_menuitem_queue_up_activate, + 'on_menuitem_queue_down_activate': self.on_menuitem_queue_down_activate, + 'on_menuitem_queue_bottom_activate': self.on_menuitem_queue_bottom_activate }) self.change_sensitivity = [ - "menuitem_addtorrent" + 'menuitem_addtorrent' ] def start(self): @@ -164,8 +164,8 @@ class MenuBar(component.Component): # Only show open_folder menuitem and separator if connected to a localhost daemon. localhost_items = [ - "menuitem_open_folder", - "separator4" + 'menuitem_open_folder', + 'separator4' ] if client.is_localhost(): for widget in localhost_items: @@ -176,9 +176,9 @@ class MenuBar(component.Component): self.builder.get_object(widget).hide() self.builder.get_object(widget).set_no_show_all(True) - self.main_builder.get_object("separatormenuitem").set_visible(not self.config["standalone"]) - self.main_builder.get_object("menuitem_quitdaemon").set_visible(not self.config["standalone"]) - self.main_builder.get_object("menuitem_connectionmanager").set_visible(not self.config["standalone"]) + self.main_builder.get_object('separatormenuitem').set_visible(not self.config['standalone']) + self.main_builder.get_object('menuitem_quitdaemon').set_visible(not self.config['standalone']) + self.main_builder.get_object('menuitem_connectionmanager').set_visible(not self.config['standalone']) # Show the Torrent menu because we're connected to a host self.menu_torrent.show() @@ -188,18 +188,18 @@ class MenuBar(component.Component): client.core.get_known_accounts().addCallback( self._on_known_accounts).addErrback(self._on_known_accounts_fail) - client.register_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event) - client.register_event_handler("TorrentResumedEvent", self.on_torrentresumed_event) - client.register_event_handler("SessionPausedEvent", self.on_sessionpaused_event) - client.register_event_handler("SessionResumedEvent", self.on_sessionresumed_event) + client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event) + client.register_event_handler('TorrentResumedEvent', self.on_torrentresumed_event) + client.register_event_handler('SessionPausedEvent', self.on_sessionpaused_event) + client.register_event_handler('SessionResumedEvent', self.on_sessionresumed_event) def stop(self): - log.debug("MenuBar stopping") + log.debug('MenuBar stopping') - client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event) - client.deregister_event_handler("TorrentResumedEvent", self.on_torrentresumed_event) - client.deregister_event_handler("SessionPausedEvent", self.on_sessionpaused_event) - client.deregister_event_handler("SessionResumedEvent", self.on_sessionresumed_event) + client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event) + client.deregister_event_handler('TorrentResumedEvent', self.on_torrentresumed_event) + client.deregister_event_handler('SessionPausedEvent', self.on_sessionpaused_event) + client.deregister_event_handler('SessionResumedEvent', self.on_sessionresumed_event) for widget in self.change_sensitivity: self.main_builder.get_object(widget).set_sensitive(False) @@ -207,8 +207,8 @@ class MenuBar(component.Component): # Hide the Torrent menu self.menu_torrent.hide() - self.main_builder.get_object("separatormenuitem").hide() - self.main_builder.get_object("menuitem_quitdaemon").hide() + self.main_builder.get_object('separatormenuitem').hide() + self.main_builder.get_object('menuitem_quitdaemon').hide() def update_menu(self): selected = component.get('TorrentView').get_selected_torrents() @@ -229,7 +229,7 @@ class MenuBar(component.Component): # Callbacks # def on_torrentstatechanged_event(self, torrent_id, state): - if state == "Paused": + if state == 'Paused': self.update_menu() def on_torrentresumed_event(self, torrent_id): @@ -243,99 +243,99 @@ class MenuBar(component.Component): # File Menu # def on_menuitem_addtorrent_activate(self, data=None): - log.debug("on_menuitem_addtorrent_activate") - component.get("AddTorrentDialog").show() + log.debug('on_menuitem_addtorrent_activate') + component.get('AddTorrentDialog').show() def on_menuitem_createtorrent_activate(self, data=None): - log.debug("on_menuitem_createtorrent_activate") + log.debug('on_menuitem_createtorrent_activate') from deluge.ui.gtkui.createtorrentdialog import CreateTorrentDialog CreateTorrentDialog().show() def on_menuitem_quitdaemon_activate(self, data=None): - log.debug("on_menuitem_quitdaemon_activate") + log.debug('on_menuitem_quitdaemon_activate') self.window.quit(shutdown=True) def on_menuitem_quit_activate(self, data=None): - log.debug("on_menuitem_quit_activate") + log.debug('on_menuitem_quit_activate') self.window.quit() # Edit Menu # def on_menuitem_preferences_activate(self, data=None): - log.debug("on_menuitem_preferences_activate") - component.get("Preferences").show() + log.debug('on_menuitem_preferences_activate') + component.get('Preferences').show() def on_menuitem_connectionmanager_activate(self, data=None): - log.debug("on_menuitem_connectionmanager_activate") - component.get("ConnectionManager").show() + log.debug('on_menuitem_connectionmanager_activate') + component.get('ConnectionManager').show() # Torrent Menu # def on_menuitem_pause_activate(self, data=None): - log.debug("on_menuitem_pause_activate") + log.debug('on_menuitem_pause_activate') client.core.pause_torrent( - component.get("TorrentView").get_selected_torrents()) + component.get('TorrentView').get_selected_torrents()) def on_menuitem_resume_activate(self, data=None): - log.debug("on_menuitem_resume_activate") + log.debug('on_menuitem_resume_activate') client.core.resume_torrent( - component.get("TorrentView").get_selected_torrents()) + component.get('TorrentView').get_selected_torrents()) def on_menuitem_updatetracker_activate(self, data=None): - log.debug("on_menuitem_updatetracker_activate") + log.debug('on_menuitem_updatetracker_activate') client.core.force_reannounce( - component.get("TorrentView").get_selected_torrents()) + component.get('TorrentView').get_selected_torrents()) def on_menuitem_edittrackers_activate(self, data=None): - log.debug("on_menuitem_edittrackers_activate") + log.debug('on_menuitem_edittrackers_activate') from deluge.ui.gtkui.edittrackersdialog import EditTrackersDialog dialog = EditTrackersDialog( - component.get("TorrentView").get_selected_torrent(), - component.get("MainWindow").window) + component.get('TorrentView').get_selected_torrent(), + component.get('MainWindow').window) dialog.run() def on_menuitem_remove_activate(self, data=None): - log.debug("on_menuitem_remove_activate") - torrent_ids = component.get("TorrentView").get_selected_torrents() + log.debug('on_menuitem_remove_activate') + torrent_ids = component.get('TorrentView').get_selected_torrents() if torrent_ids: from deluge.ui.gtkui.removetorrentdialog import RemoveTorrentDialog RemoveTorrentDialog(torrent_ids).run() def on_menuitem_recheck_activate(self, data=None): - log.debug("on_menuitem_recheck_activate") + log.debug('on_menuitem_recheck_activate') client.core.force_recheck( - component.get("TorrentView").get_selected_torrents()) + component.get('TorrentView').get_selected_torrents()) def on_menuitem_open_folder_activate(self, data=None): - log.debug("on_menuitem_open_folder") + log.debug('on_menuitem_open_folder') def _on_torrent_status(status): timestamp = gtk.get_current_event_time() - path = os.path.join(status["download_location"], status["files"][0]["path"].split('/')[0]) + path = os.path.join(status['download_location'], status['files'][0]['path'].split('/')[0]) deluge.common.show_file(path, timestamp=timestamp) - for torrent_id in component.get("TorrentView").get_selected_torrents(): - component.get("SessionProxy").get_torrent_status( - torrent_id, ["download_location", "files"]).addCallback(_on_torrent_status) + for torrent_id in component.get('TorrentView').get_selected_torrents(): + component.get('SessionProxy').get_torrent_status( + torrent_id, ['download_location', 'files']).addCallback(_on_torrent_status) def on_menuitem_move_activate(self, data=None): - log.debug("on_menuitem_move_activate") - component.get("SessionProxy").get_torrent_status( - component.get("TorrentView").get_selected_torrent(), - ["download_location"]).addCallback(self.show_move_storage_dialog) + log.debug('on_menuitem_move_activate') + component.get('SessionProxy').get_torrent_status( + component.get('TorrentView').get_selected_torrent(), + ['download_location']).addCallback(self.show_move_storage_dialog) def show_move_storage_dialog(self, status): - log.debug("show_move_storage_dialog") + log.debug('show_move_storage_dialog') builder = gtk.Builder() builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "move_storage_dialog.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'move_storage_dialog.ui') )) # Keep it referenced: # https://bugzilla.gnome.org/show_bug.cgi?id=546802 - self.move_storage_dialog = builder.get_object("move_storage_dialog") + self.move_storage_dialog = builder.get_object('move_storage_dialog') self.move_storage_dialog.set_transient_for(self.window.window) - self.move_storage_dialog_hbox = builder.get_object("hbox_entry") - self.move_storage_path_chooser = PathChooser("move_completed_paths_list") + self.move_storage_dialog_hbox = builder.get_object('hbox_entry') + self.move_storage_path_chooser = PathChooser('move_completed_paths_list') self.move_storage_dialog_hbox.add(self.move_storage_path_chooser) self.move_storage_dialog_hbox.show_all() - self.move_storage_path_chooser.set_text(status["download_location"]) + self.move_storage_path_chooser.set_text(status['download_location']) def on_dialog_response_event(widget, response_id): def on_core_result(result): @@ -348,95 +348,95 @@ class MenuBar(component.Component): on_core_result(None) if response_id == gtk.RESPONSE_OK: - log.debug("Moving torrents to %s", + log.debug('Moving torrents to %s', self.move_storage_path_chooser.get_text()) path = self.move_storage_path_chooser.get_text() client.core.move_storage( - component.get("TorrentView").get_selected_torrents(), path + component.get('TorrentView').get_selected_torrents(), path ).addCallback(on_core_result) - self.move_storage_dialog.connect("response", on_dialog_response_event) + self.move_storage_dialog.connect('response', on_dialog_response_event) self.move_storage_dialog.show() def on_menuitem_queue_top_activate(self, value): - log.debug("on_menuitem_queue_top_activate") - client.core.queue_top(component.get("TorrentView").get_selected_torrents()) + log.debug('on_menuitem_queue_top_activate') + client.core.queue_top(component.get('TorrentView').get_selected_torrents()) def on_menuitem_queue_up_activate(self, value): - log.debug("on_menuitem_queue_up_activate") - client.core.queue_up(component.get("TorrentView").get_selected_torrents()) + log.debug('on_menuitem_queue_up_activate') + client.core.queue_up(component.get('TorrentView').get_selected_torrents()) def on_menuitem_queue_down_activate(self, value): - log.debug("on_menuitem_queue_down_activate") - client.core.queue_down(component.get("TorrentView").get_selected_torrents()) + log.debug('on_menuitem_queue_down_activate') + client.core.queue_down(component.get('TorrentView').get_selected_torrents()) def on_menuitem_queue_bottom_activate(self, value): - log.debug("on_menuitem_queue_bottom_activate") - client.core.queue_bottom(component.get("TorrentView").get_selected_torrents()) + log.debug('on_menuitem_queue_bottom_activate') + client.core.queue_bottom(component.get('TorrentView').get_selected_torrents()) # View Menu # def on_menuitem_toolbar_toggled(self, value): - log.debug("on_menuitem_toolbar_toggled") - component.get("ToolBar").visible(value.get_active()) + log.debug('on_menuitem_toolbar_toggled') + component.get('ToolBar').visible(value.get_active()) def on_menuitem_sidebar_toggled(self, value): - log.debug("on_menuitem_sidebar_toggled") - component.get("SideBar").visible(value.get_active()) + log.debug('on_menuitem_sidebar_toggled') + component.get('SideBar').visible(value.get_active()) def on_menuitem_statusbar_toggled(self, value): - log.debug("on_menuitem_statusbar_toggled") - component.get("StatusBar").visible(value.get_active()) + log.debug('on_menuitem_statusbar_toggled') + component.get('StatusBar').visible(value.get_active()) # Help Menu # def on_menuitem_homepage_activate(self, data=None): - log.debug("on_menuitem_homepage_activate") - deluge.common.open_url_in_browser("http://deluge-torrent.org") + log.debug('on_menuitem_homepage_activate') + deluge.common.open_url_in_browser('http://deluge-torrent.org') def on_menuitem_faq_activate(self, data=None): - log.debug("on_menuitem_faq_activate") - deluge.common.open_url_in_browser("http://dev.deluge-torrent.org/wiki/Faq") + log.debug('on_menuitem_faq_activate') + deluge.common.open_url_in_browser('http://dev.deluge-torrent.org/wiki/Faq') def on_menuitem_community_activate(self, data=None): - log.debug("on_menuitem_community_activate") - deluge.common.open_url_in_browser("http://forum.deluge-torrent.org/") + log.debug('on_menuitem_community_activate') + deluge.common.open_url_in_browser('http://forum.deluge-torrent.org/') def on_menuitem_about_activate(self, data=None): - log.debug("on_menuitem_about_activate") + log.debug('on_menuitem_about_activate') from deluge.ui.gtkui.aboutdialog import AboutDialog AboutDialog().run() def on_menuitem_set_unlimited(self, widget): - log.debug("widget.name: %s", widget.name) + log.debug('widget.name: %s', widget.name) funcs = { - "menuitem_down_speed": client.core.set_torrent_max_download_speed, - "menuitem_up_speed": client.core.set_torrent_max_upload_speed, - "menuitem_max_connections": client.core.set_torrent_max_connections, - "menuitem_upload_slots": client.core.set_torrent_max_upload_slots + 'menuitem_down_speed': client.core.set_torrent_max_download_speed, + 'menuitem_up_speed': client.core.set_torrent_max_upload_speed, + 'menuitem_max_connections': client.core.set_torrent_max_connections, + 'menuitem_upload_slots': client.core.set_torrent_max_upload_slots } if widget.name in funcs.keys(): - for torrent in component.get("TorrentView").get_selected_torrents(): + for torrent in component.get('TorrentView').get_selected_torrents(): funcs[widget.name](torrent, -1) def on_menuitem_set_other(self, widget): - log.debug("widget.name: %s", widget.name) + log.debug('widget.name: %s', widget.name) status_map = { - "menuitem_down_speed": ["max_download_speed", "max_download_speed"], - "menuitem_up_speed": ["max_upload_speed", "max_upload_speed"], - "menuitem_max_connections": ["max_connections", "max_connections_global"], - "menuitem_upload_slots": ["max_upload_slots", "max_upload_slots_global"], - "menuitem_stop_seed_at_ratio": ["stop_ratio", "stop_seed_ratio"] + 'menuitem_down_speed': ['max_download_speed', 'max_download_speed'], + 'menuitem_up_speed': ['max_upload_speed', 'max_upload_speed'], + 'menuitem_max_connections': ['max_connections', 'max_connections_global'], + 'menuitem_upload_slots': ['max_upload_slots', 'max_upload_slots_global'], + 'menuitem_stop_seed_at_ratio': ['stop_ratio', 'stop_seed_ratio'] } other_dialog_info = { - "menuitem_down_speed": [_("Download Speed Limit"), _("Set the maximum download speed"), - _("KiB/s"), "downloading.svg"], - "menuitem_up_speed": [_("Upload Speed Limit"), _("Set the maximum upload speed"), - _("KiB/s"), "seeding.svg"], - "menuitem_max_connections": [_("Incoming Connections"), _("Set the maximum incoming connections"), - "", gtk.STOCK_NETWORK], - "menuitem_upload_slots": [_("Peer Upload Slots"), _("Set the maximum upload slots"), - "", gtk.STOCK_SORT_ASCENDING], - "menuitem_stop_seed_at_ratio": [_("Stop Seed At Ratio"), "Stop torrent seeding at ratio", "", None] + 'menuitem_down_speed': [_('Download Speed Limit'), _('Set the maximum download speed'), + _('KiB/s'), 'downloading.svg'], + 'menuitem_up_speed': [_('Upload Speed Limit'), _('Set the maximum upload speed'), + _('KiB/s'), 'seeding.svg'], + 'menuitem_max_connections': [_('Incoming Connections'), _('Set the maximum incoming connections'), + '', gtk.STOCK_NETWORK], + 'menuitem_upload_slots': [_('Peer Upload Slots'), _('Set the maximum upload slots'), + '', gtk.STOCK_SORT_ASCENDING], + 'menuitem_stop_seed_at_ratio': [_('Stop Seed At Ratio'), 'Stop torrent seeding at ratio', '', None] } core_key = status_map[widget.name][0] @@ -453,44 +453,44 @@ class MenuBar(component.Component): if value == 0: value += -1 options = {core_key: value} - if core_key == "stop_ratio": - options["stop_at_ratio"] = True + if core_key == 'stop_ratio': + options['stop_at_ratio'] = True client.core.set_torrent_options(torrent_ids, options) dialog = OtherDialog(*other_dialog) dialog.run().addCallback(set_value) - torrent_ids = component.get("TorrentView").get_selected_torrents() + torrent_ids = component.get('TorrentView').get_selected_torrents() if len(torrent_ids) == 1: core_key_global = core_key - d = component.get("SessionProxy").get_torrent_status(torrent_ids[0], [core_key]) + d = component.get('SessionProxy').get_torrent_status(torrent_ids[0], [core_key]) else: d = client.core.get_config_values([core_key_global]) d.addCallback(_on_torrent_status) def on_menuitem_set_automanaged_on(self, widget): - for torrent in component.get("TorrentView").get_selected_torrents(): + for torrent in component.get('TorrentView').get_selected_torrents(): client.core.set_torrent_auto_managed(torrent, True) def on_menuitem_set_automanaged_off(self, widget): - for torrent in component.get("TorrentView").get_selected_torrents(): + for torrent in component.get('TorrentView').get_selected_torrents(): client.core.set_torrent_auto_managed(torrent, False) def on_menuitem_set_stop_seed_at_ratio_disable(self, widget): - client.core.set_torrent_options(component.get("TorrentView").get_selected_torrents(), - {"stop_at_ratio": False}) + client.core.set_torrent_options(component.get('TorrentView').get_selected_torrents(), + {'stop_at_ratio': False}) def on_menuitem_sidebar_zero_toggled(self, widget): - self.config["sidebar_show_zero"] = widget.get_active() - component.get("FilterTreeView").update() + self.config['sidebar_show_zero'] = widget.get_active() + component.get('FilterTreeView').update() def on_menuitem_sidebar_trackers_toggled(self, widget): - self.config["sidebar_show_trackers"] = widget.get_active() - component.get("FilterTreeView").update() + self.config['sidebar_show_trackers'] = widget.get_active() + component.get('FilterTreeView').update() def on_menuitem_sidebar_owners_toggled(self, widget): - self.config["sidebar_show_owners"] = widget.get_active() - component.get("FilterTreeView").update() + self.config['sidebar_show_owners'] = widget.get_active() + component.get('FilterTreeView').update() def _on_known_accounts(self, known_accounts): known_accounts_to_log = [] @@ -501,11 +501,11 @@ class MenuBar(component.Component): value = '*' * len(value) account_to_log[key] = value known_accounts_to_log.append(account_to_log) - log.debug("_on_known_accounts: %s", known_accounts_to_log) + log.debug('_on_known_accounts: %s', known_accounts_to_log) if len(known_accounts) <= 1: return - self.builder.get_object("menuitem_change_owner").set_visible(True) + self.builder.get_object('menuitem_change_owner').set_visible(True) self.change_owner_submenu = gtk.Menu() self.change_owner_submenu_items = {} @@ -514,41 +514,41 @@ class MenuBar(component.Component): self.change_owner_submenu_items[None] = gtk.RadioMenuItem(maingroup) for account in known_accounts: - username = account["username"] + username = account['username'] item = gtk.RadioMenuItem(maingroup, username) self.change_owner_submenu_items[username] = item self.change_owner_submenu.append(item) - item.connect("toggled", self._on_change_owner_toggled, username) + item.connect('toggled', self._on_change_owner_toggled, username) self.change_owner_submenu.show_all() self.change_owner_submenu_items[None].set_active(True) self.change_owner_submenu_items[None].hide() - self.builder.get_object("menuitem_change_owner").connect( - "activate", self._on_change_owner_submenu_active + self.builder.get_object('menuitem_change_owner').connect( + 'activate', self._on_change_owner_submenu_active ) - self.builder.get_object("menuitem_change_owner").set_submenu(self.change_owner_submenu) + self.builder.get_object('menuitem_change_owner').set_submenu(self.change_owner_submenu) def _on_known_accounts_fail(self, reason): - self.builder.get_object("menuitem_change_owner").set_visible(False) + self.builder.get_object('menuitem_change_owner').set_visible(False) def _on_change_owner_submenu_active(self, widget): - log.debug("_on_change_owner_submenu_active") - selected = component.get("TorrentView").get_selected_torrents() + log.debug('_on_change_owner_submenu_active') + selected = component.get('TorrentView').get_selected_torrents() if len(selected) > 1: self.change_owner_submenu_items[None].set_active(True) return - torrent_owner = component.get("TorrentView").get_torrent_status(selected[0])["owner"] + torrent_owner = component.get('TorrentView').get_torrent_status(selected[0])['owner'] for username, item in self.change_owner_submenu_items.iteritems(): item.set_active(username == torrent_owner) def _on_change_owner_toggled(self, widget, username): - log.debug("_on_change_owner_toggled") + log.debug('_on_change_owner_toggled') update_torrents = [] - selected = component.get("TorrentView").get_selected_torrents() + selected = component.get('TorrentView').get_selected_torrents() for torrent_id in selected: - torrent_status = component.get("TorrentView").get_torrent_status(torrent_id) - if torrent_status["owner"] != username: + torrent_status = component.get('TorrentView').get_torrent_status(torrent_id) + if torrent_status['owner'] != username: update_torrents.append(torrent_id) if update_torrents: @@ -556,8 +556,8 @@ class MenuBar(component.Component): def failed_change_owner(failure): ErrorDialog( - _("Ownership Change Error"), - _("There was an error while trying changing ownership."), + _('Ownership Change Error'), + _('There was an error while trying changing ownership.'), self.window.window, details=failure.value.logable() ).run() client.core.set_owner( diff --git a/deluge/ui/gtkui/menubar_osx.py b/deluge/ui/gtkui/menubar_osx.py index 5593cd155..7b5a6a4fe 100644 --- a/deluge/ui/gtkui/menubar_osx.py +++ b/deluge/ui/gtkui/menubar_osx.py @@ -14,7 +14,7 @@ from deluge.configmanager import ConfigManager def accel_swap(item, group, skey, smod, dkey, dmod): item.remove_accelerator(group, ord(skey), smod) - item.add_accelerator("activate", group, ord(dkey), dmod, gtk.ACCEL_VISIBLE) + item.add_accelerator('activate', group, ord(dkey), dmod, gtk.ACCEL_VISIBLE) def accel_meta(item, group, key): @@ -24,16 +24,16 @@ def accel_meta(item, group, key): def menubar_osx(gtkui, osxapp): window = gtkui.mainwindow main_builder = window.get_builder() - menubar = main_builder.get_object("menubar") + menubar = main_builder.get_object('menubar') group = gtk.accel_groups_from_object(window.window)[0] - config = ConfigManager("gtkui.conf") + config = ConfigManager('gtkui.conf') # NOTE: accel maps doesn't work with glade file format # because of libglade not setting MenuItem accel groups # That's why we remove / set accelerators by hand... (dirty) # Clean solution: migrate glades files to gtkbuilder format - file_menu = main_builder.get_object("menu_file").get_submenu() + file_menu = main_builder.get_object('menu_file').get_submenu() file_items = file_menu.get_children() accel_meta(file_items[0], group, 'o') accel_meta(file_items[1], group, 'n') @@ -43,7 +43,7 @@ def menubar_osx(gtkui, osxapp): for item in range(2, len(file_items)): # remove quits file_menu.remove(file_items[item]) - menu_widget = main_builder.get_object("menu_edit") + menu_widget = main_builder.get_object('menu_edit') edit_menu = menu_widget.get_submenu() edit_items = edit_menu.get_children() pref_item = edit_items[0] @@ -56,7 +56,7 @@ def menubar_osx(gtkui, osxapp): menubar.remove(menu_widget) - help_menu = main_builder.get_object("menu_help").get_submenu() + help_menu = main_builder.get_object('menu_help').get_submenu() help_items = help_menu.get_children() about_item = help_items[4] help_menu.remove(about_item) @@ -68,7 +68,7 @@ def menubar_osx(gtkui, osxapp): osxapp.insert_app_menu_item(about_item, 0) osxapp.insert_app_menu_item(gtk.SeparatorMenuItem(), 1) osxapp.insert_app_menu_item(pref_item, 2) - if not config["standalone"]: + if not config['standalone']: osxapp.insert_app_menu_item(conn_item, 3) if quit_all_item.get_visible(): osxapp.insert_app_menu_item(gtk.SeparatorMenuItem(), 4) diff --git a/deluge/ui/gtkui/new_release_dialog.py b/deluge/ui/gtkui/new_release_dialog.py index cff8ce93d..fd0a0c960 100644 --- a/deluge/ui/gtkui/new_release_dialog.py +++ b/deluge/ui/gtkui/new_release_dialog.py @@ -19,41 +19,41 @@ class NewReleaseDialog(object): pass def show(self, available_version): - self.config = ConfigManager("gtkui.conf") - builder = component.get("MainWindow").get_builder() - self.dialog = builder.get_object("new_release_dialog") + self.config = ConfigManager('gtkui.conf') + builder = component.get('MainWindow').get_builder() + self.dialog = builder.get_object('new_release_dialog') # Set the version labels if deluge.common.windows_check() or deluge.common.osx_check(): - builder.get_object("image_new_release").set_from_file( - deluge.common.get_pixmap("deluge16.png")) + builder.get_object('image_new_release').set_from_file( + deluge.common.get_pixmap('deluge16.png')) else: - builder.get_object("image_new_release").set_from_icon_name("deluge", 4) - builder.get_object("label_available_version").set_text(available_version) - builder.get_object("label_client_version").set_text( + builder.get_object('image_new_release').set_from_icon_name('deluge', 4) + builder.get_object('label_available_version').set_text(available_version) + builder.get_object('label_client_version').set_text( deluge.common.get_version()) - self.chk_not_show_dialog = builder.get_object("chk_do_not_show_new_release") - builder.get_object("button_goto_downloads").connect( - "clicked", self._on_button_goto_downloads) - builder.get_object("button_close_new_release").connect( - "clicked", self._on_button_close_new_release) + self.chk_not_show_dialog = builder.get_object('chk_do_not_show_new_release') + builder.get_object('button_goto_downloads').connect( + 'clicked', self._on_button_goto_downloads) + builder.get_object('button_close_new_release').connect( + 'clicked', self._on_button_close_new_release) if client.connected(): def on_info(version): - builder.get_object("label_server_version").set_text(version) - builder.get_object("label_server_version").show() - builder.get_object("label_server_version_text").show() + builder.get_object('label_server_version').set_text(version) + builder.get_object('label_server_version').show() + builder.get_object('label_server_version_text').show() if not client.is_standalone(): - builder.get_object("label_client_version_text").set_label(_("<i>Client Version</i>")) + builder.get_object('label_client_version_text').set_label(_('<i>Client Version</i>')) client.daemon.info().addCallback(on_info) self.dialog.show() def _on_button_goto_downloads(self, widget): - deluge.common.open_url_in_browser("http://deluge-torrent.org") - self.config["show_new_releases"] = not self.chk_not_show_dialog.get_active() + deluge.common.open_url_in_browser('http://deluge-torrent.org') + self.config['show_new_releases'] = not self.chk_not_show_dialog.get_active() self.dialog.destroy() def _on_button_close_new_release(self, widget): - self.config["show_new_releases"] = not self.chk_not_show_dialog.get_active() + self.config['show_new_releases'] = not self.chk_not_show_dialog.get_active() self.dialog.destroy() diff --git a/deluge/ui/gtkui/options_tab.py b/deluge/ui/gtkui/options_tab.py index 485659485..a17d0c9bf 100644 --- a/deluge/ui/gtkui/options_tab.py +++ b/deluge/ui/gtkui/options_tab.py @@ -18,52 +18,52 @@ from deluge.ui.gtkui.torrentdetails import Tab class OptionsTab(Tab): def __init__(self): Tab.__init__(self) - builder = component.get("MainWindow").get_builder() - - self._name = "Options" - self._child_widget = builder.get_object("options_tab") - self._tab_label = builder.get_object("options_tab_label") - - self.spin_max_download = builder.get_object("spin_max_download") - self.spin_max_upload = builder.get_object("spin_max_upload") - self.spin_max_connections = builder.get_object("spin_max_connections") - self.spin_max_upload_slots = builder.get_object("spin_max_upload_slots") - self.chk_prioritize_first_last = builder.get_object("chk_prioritize_first_last") - self.chk_sequential_download = builder.get_object("chk_sequential_download") - self.chk_auto_managed = builder.get_object("chk_auto_managed") - self.chk_stop_at_ratio = builder.get_object("chk_stop_at_ratio") - self.chk_remove_at_ratio = builder.get_object("chk_remove_at_ratio") - self.spin_stop_ratio = builder.get_object("spin_stop_ratio") - self.chk_move_completed = builder.get_object("chk_move_completed") - self.entry_move_completed = builder.get_object("entry_move_completed") - self.chk_shared = builder.get_object("chk_shared") - self.button_apply = builder.get_object("button_apply") - self.summary_owner = builder.get_object("summary_owner") - - self.move_completed_hbox = builder.get_object("hbox_move_completed_path_chooser") - self.move_completed_path_chooser = PathChooser("move_completed_paths_list") + builder = component.get('MainWindow').get_builder() + + self._name = 'Options' + self._child_widget = builder.get_object('options_tab') + self._tab_label = builder.get_object('options_tab_label') + + self.spin_max_download = builder.get_object('spin_max_download') + self.spin_max_upload = builder.get_object('spin_max_upload') + self.spin_max_connections = builder.get_object('spin_max_connections') + self.spin_max_upload_slots = builder.get_object('spin_max_upload_slots') + self.chk_prioritize_first_last = builder.get_object('chk_prioritize_first_last') + self.chk_sequential_download = builder.get_object('chk_sequential_download') + self.chk_auto_managed = builder.get_object('chk_auto_managed') + self.chk_stop_at_ratio = builder.get_object('chk_stop_at_ratio') + self.chk_remove_at_ratio = builder.get_object('chk_remove_at_ratio') + self.spin_stop_ratio = builder.get_object('spin_stop_ratio') + self.chk_move_completed = builder.get_object('chk_move_completed') + self.entry_move_completed = builder.get_object('entry_move_completed') + self.chk_shared = builder.get_object('chk_shared') + self.button_apply = builder.get_object('button_apply') + self.summary_owner = builder.get_object('summary_owner') + + self.move_completed_hbox = builder.get_object('hbox_move_completed_path_chooser') + self.move_completed_path_chooser = PathChooser('move_completed_paths_list') self.move_completed_path_chooser.set_sensitive(self.chk_move_completed.get_active()) self.move_completed_hbox.add(self.move_completed_path_chooser) self.move_completed_hbox.show_all() - self.move_completed_path_chooser.connect("text-changed", self._on_path_chooser_text_changed_event) + self.move_completed_path_chooser.connect('text-changed', self._on_path_chooser_text_changed_event) self.prev_torrent_id = None self.prev_status = None - component.get("MainWindow").connect_signals({ - "on_button_apply_clicked": self._on_button_apply_clicked, - "on_chk_move_completed_toggled": self._on_chk_move_completed_toggled, - "on_chk_stop_at_ratio_toggled": self._on_chk_stop_at_ratio_toggled, - "on_chk_toggled": self._on_chk_toggled, - "on_spin_value_changed": self._on_spin_value_changed, - "on_move_completed_file_set": self._on_move_completed_file_set + component.get('MainWindow').connect_signals({ + 'on_button_apply_clicked': self._on_button_apply_clicked, + 'on_chk_move_completed_toggled': self._on_chk_move_completed_toggled, + 'on_chk_stop_at_ratio_toggled': self._on_chk_stop_at_ratio_toggled, + 'on_chk_toggled': self._on_chk_toggled, + 'on_spin_value_changed': self._on_spin_value_changed, + 'on_move_completed_file_set': self._on_move_completed_file_set }) - self.spin_max_download.connect("key-press-event", self._on_key_press_event) - self.spin_max_upload.connect("key-press-event", self._on_key_press_event) - self.spin_max_connections.connect("key-press-event", self._on_key_press_event) - self.spin_max_upload_slots.connect("key-press-event", self._on_key_press_event) - self.spin_stop_ratio.connect("key-press-event", self._on_key_press_event) + self.spin_max_download.connect('key-press-event', self._on_key_press_event) + self.spin_max_upload.connect('key-press-event', self._on_key_press_event) + self.spin_max_connections.connect('key-press-event', self._on_key_press_event) + self.spin_max_upload_slots.connect('key-press-event', self._on_key_press_event) + self.spin_stop_ratio.connect('key-press-event', self._on_key_press_event) def start(self): pass @@ -73,7 +73,7 @@ class OptionsTab(Tab): def update(self): # Get the first selected torrent - torrent_id = component.get("TorrentView").get_selected_torrents() + torrent_id = component.get('TorrentView').get_selected_torrents() # Only use the first torrent in the list or return if None selected if torrent_id: @@ -87,22 +87,22 @@ class OptionsTab(Tab): if torrent_id != self.prev_torrent_id: self.prev_status = None - component.get("SessionProxy").get_torrent_status(torrent_id, [ - "max_download_speed", - "max_upload_speed", - "max_connections", - "max_upload_slots", - "prioritize_first_last", - "is_auto_managed", - "stop_at_ratio", - "stop_ratio", - "remove_at_ratio", - "storage_mode", - "sequential_download", - "move_on_completed", - "move_on_completed_path", - "shared", - "owner" + component.get('SessionProxy').get_torrent_status(torrent_id, [ + 'max_download_speed', + 'max_upload_speed', + 'max_connections', + 'max_upload_slots', + 'prioritize_first_last', + 'is_auto_managed', + 'stop_at_ratio', + 'stop_ratio', + 'remove_at_ratio', + 'storage_mode', + 'sequential_download', + 'move_on_completed', + 'move_on_completed_path', + 'shared', + 'owner' ]).addCallback(self._on_get_torrent_status) self.prev_torrent_id = torrent_id @@ -117,43 +117,43 @@ class OptionsTab(Tab): self.prev_status = {}.fromkeys(status.keys(), None) if status != self.prev_status: - if status["max_download_speed"] != self.prev_status["max_download_speed"]: - self.spin_max_download.set_value(status["max_download_speed"]) - if status["max_upload_speed"] != self.prev_status["max_upload_speed"]: - self.spin_max_upload.set_value(status["max_upload_speed"]) - if status["max_connections"] != self.prev_status["max_connections"]: - self.spin_max_connections.set_value(status["max_connections"]) - if status["max_upload_slots"] != self.prev_status["max_upload_slots"]: - self.spin_max_upload_slots.set_value(status["max_upload_slots"]) - if status["prioritize_first_last"] != self.prev_status["prioritize_first_last"]: - self.chk_prioritize_first_last.set_active(status["prioritize_first_last"]) - if status["is_auto_managed"] != self.prev_status["is_auto_managed"]: - self.chk_auto_managed.set_active(status["is_auto_managed"]) - if status["stop_at_ratio"] != self.prev_status["stop_at_ratio"]: - self.chk_stop_at_ratio.set_active(status["stop_at_ratio"]) - self.spin_stop_ratio.set_sensitive(status["stop_at_ratio"]) - self.chk_remove_at_ratio.set_sensitive(status["stop_at_ratio"]) - if status["stop_ratio"] != self.prev_status["stop_ratio"]: - self.spin_stop_ratio.set_value(status["stop_ratio"]) - if status["remove_at_ratio"] != self.prev_status["remove_at_ratio"]: - self.chk_remove_at_ratio.set_active(status["remove_at_ratio"]) - if status["move_on_completed"] != self.prev_status["move_on_completed"]: - self.chk_move_completed.set_active(status["move_on_completed"]) - if status["move_on_completed_path"] != self.prev_status["move_on_completed_path"]: - self.move_completed_path_chooser.set_text(status["move_on_completed_path"], + if status['max_download_speed'] != self.prev_status['max_download_speed']: + self.spin_max_download.set_value(status['max_download_speed']) + if status['max_upload_speed'] != self.prev_status['max_upload_speed']: + self.spin_max_upload.set_value(status['max_upload_speed']) + if status['max_connections'] != self.prev_status['max_connections']: + self.spin_max_connections.set_value(status['max_connections']) + if status['max_upload_slots'] != self.prev_status['max_upload_slots']: + self.spin_max_upload_slots.set_value(status['max_upload_slots']) + if status['prioritize_first_last'] != self.prev_status['prioritize_first_last']: + self.chk_prioritize_first_last.set_active(status['prioritize_first_last']) + if status['is_auto_managed'] != self.prev_status['is_auto_managed']: + self.chk_auto_managed.set_active(status['is_auto_managed']) + if status['stop_at_ratio'] != self.prev_status['stop_at_ratio']: + self.chk_stop_at_ratio.set_active(status['stop_at_ratio']) + self.spin_stop_ratio.set_sensitive(status['stop_at_ratio']) + self.chk_remove_at_ratio.set_sensitive(status['stop_at_ratio']) + if status['stop_ratio'] != self.prev_status['stop_ratio']: + self.spin_stop_ratio.set_value(status['stop_ratio']) + if status['remove_at_ratio'] != self.prev_status['remove_at_ratio']: + self.chk_remove_at_ratio.set_active(status['remove_at_ratio']) + if status['move_on_completed'] != self.prev_status['move_on_completed']: + self.chk_move_completed.set_active(status['move_on_completed']) + if status['move_on_completed_path'] != self.prev_status['move_on_completed_path']: + self.move_completed_path_chooser.set_text(status['move_on_completed_path'], cursor_end=False, default_text=True) - if status["shared"] != self.prev_status["shared"]: - self.chk_shared.set_active(status["shared"]) - if status["owner"] != self.prev_status["owner"]: - self.summary_owner.set_text(status["owner"]) - - if status["prioritize_first_last"] != self.prev_status["prioritize_first_last"]: - self.chk_prioritize_first_last.set_active(status["prioritize_first_last"]) - if not self.chk_prioritize_first_last.get_property("visible"): + if status['shared'] != self.prev_status['shared']: + self.chk_shared.set_active(status['shared']) + if status['owner'] != self.prev_status['owner']: + self.summary_owner.set_text(status['owner']) + + if status['prioritize_first_last'] != self.prev_status['prioritize_first_last']: + self.chk_prioritize_first_last.set_active(status['prioritize_first_last']) + if not self.chk_prioritize_first_last.get_property('visible'): self.chk_prioritize_first_last.show() - if status["sequential_download"] != self.prev_status["sequential_download"]: - self.chk_sequential_download.set_active(status["sequential_download"]) - if not self.chk_sequential_download.get_property("visible"): + if status['sequential_download'] != self.prev_status['sequential_download']: + self.chk_sequential_download.set_active(status['sequential_download']) + if not self.chk_sequential_download.get_property('visible'): self.chk_sequential_download.show() if self.button_apply.is_sensitive(): @@ -162,36 +162,36 @@ class OptionsTab(Tab): self.prev_status = status def _on_button_apply_clicked(self, button): - if self.spin_max_download.get_value() != self.prev_status["max_download_speed"]: + if self.spin_max_download.get_value() != self.prev_status['max_download_speed']: client.core.set_torrent_max_download_speed(self.prev_torrent_id, self.spin_max_download.get_value()) - if self.spin_max_upload.get_value() != self.prev_status["max_upload_speed"]: + if self.spin_max_upload.get_value() != self.prev_status['max_upload_speed']: client.core.set_torrent_max_upload_speed(self.prev_torrent_id, self.spin_max_upload.get_value()) - if self.spin_max_connections.get_value_as_int() != self.prev_status["max_connections"]: + if self.spin_max_connections.get_value_as_int() != self.prev_status['max_connections']: client.core.set_torrent_max_connections( self.prev_torrent_id, self.spin_max_connections.get_value_as_int()) - if self.spin_max_upload_slots.get_value_as_int() != self.prev_status["max_upload_slots"]: + if self.spin_max_upload_slots.get_value_as_int() != self.prev_status['max_upload_slots']: client.core.set_torrent_max_upload_slots( self.prev_torrent_id, self.spin_max_upload_slots.get_value_as_int()) - if self.chk_prioritize_first_last.get_active() != self.prev_status["prioritize_first_last"]: + if self.chk_prioritize_first_last.get_active() != self.prev_status['prioritize_first_last']: client.core.set_torrent_prioritize_first_last( self.prev_torrent_id, self.chk_prioritize_first_last.get_active()) - if self.chk_sequential_download.get_active() != self.prev_status["sequential_download"]: + if self.chk_sequential_download.get_active() != self.prev_status['sequential_download']: client.core.set_torrent_options( - [self.prev_torrent_id], {"sequential_download": self.chk_sequential_download.get_active()}) - if self.chk_auto_managed.get_active() != self.prev_status["is_auto_managed"]: + [self.prev_torrent_id], {'sequential_download': self.chk_sequential_download.get_active()}) + if self.chk_auto_managed.get_active() != self.prev_status['is_auto_managed']: client.core.set_torrent_auto_managed(self.prev_torrent_id, self.chk_auto_managed.get_active()) - if self.chk_stop_at_ratio.get_active() != self.prev_status["stop_at_ratio"]: + if self.chk_stop_at_ratio.get_active() != self.prev_status['stop_at_ratio']: client.core.set_torrent_stop_at_ratio(self.prev_torrent_id, self.chk_stop_at_ratio.get_active()) - if self.spin_stop_ratio.get_value() != self.prev_status["stop_ratio"]: + if self.spin_stop_ratio.get_value() != self.prev_status['stop_ratio']: client.core.set_torrent_stop_ratio(self.prev_torrent_id, self.spin_stop_ratio.get_value()) - if self.chk_remove_at_ratio.get_active() != self.prev_status["remove_at_ratio"]: + if self.chk_remove_at_ratio.get_active() != self.prev_status['remove_at_ratio']: client.core.set_torrent_remove_at_ratio(self.prev_torrent_id, self.chk_remove_at_ratio.get_active()) - if self.chk_move_completed.get_active() != self.prev_status["move_on_completed"]: + if self.chk_move_completed.get_active() != self.prev_status['move_on_completed']: client.core.set_torrent_move_completed(self.prev_torrent_id, self.chk_move_completed.get_active()) if self.chk_move_completed.get_active(): path = self.move_completed_path_chooser.get_text() client.core.set_torrent_move_completed_path(self.prev_torrent_id, path) - if self.chk_shared.get_active() != self.prev_status["shared"]: + if self.chk_shared.get_active() != self.prev_status['shared']: client.core.set_torrents_shared(self.prev_torrent_id, self.chk_shared.get_active()) self.button_apply.set_sensitive(False) @@ -220,8 +220,8 @@ class OptionsTab(Tab): self.button_apply.set_sensitive(True) def _on_key_press_event(self, widget, event): - keyname = gtk.gdk.keyval_name(event.keyval).lstrip("KP_").lower() - if keyname.isdigit() or keyname in ["period", "minus", "delete", "backspace"]: + keyname = gtk.gdk.keyval_name(event.keyval).lstrip('KP_').lower() + if keyname.isdigit() or keyname in ['period', 'minus', 'delete', 'backspace']: if not self.button_apply.is_sensitive(): self.button_apply.set_sensitive(True) diff --git a/deluge/ui/gtkui/path_chooser.py b/deluge/ui/gtkui/path_chooser.py index 21f8b23c2..d0a82be62 100644 --- a/deluge/ui/gtkui/path_chooser.py +++ b/deluge/ui/gtkui/path_chooser.py @@ -31,19 +31,19 @@ class PathChoosersHandler(component.Component): def __init__(self, paths_config_key=None): # self.chooser_name = "PathChooser_%d" % (len(PathChooser.path_choosers) +1) - component.Component.__init__(self, "PathChoosersHandler") + component.Component.__init__(self, 'PathChoosersHandler') self.path_choosers = [] self.paths_list_keys = [] self.config_properties = {} self.started = False self.config_keys_to_funcs_mapping = { - "path_chooser_show_chooser_button_on_localhost": "filechooser_button_visible", - "path_chooser_show_path_entry": "path_entry_visible", - "path_chooser_auto_complete_enabled": "auto_complete_enabled", - "path_chooser_show_folder_name": "show_folder_name_on_button", - "path_chooser_accelerator_string": "accelerator_string", - "path_chooser_show_hidden_files": "show_hidden_files", - "path_chooser_max_popup_rows": "max_popup_rows", + 'path_chooser_show_chooser_button_on_localhost': 'filechooser_button_visible', + 'path_chooser_show_path_entry': 'path_entry_visible', + 'path_chooser_auto_complete_enabled': 'auto_complete_enabled', + 'path_chooser_show_folder_name': 'show_folder_name_on_button', + 'path_chooser_accelerator_string': 'accelerator_string', + 'path_chooser_show_hidden_files': 'show_hidden_files', + 'path_chooser_max_popup_rows': 'max_popup_rows', } def start(self): @@ -66,8 +66,8 @@ class PathChoosersHandler(component.Component): chooser.config_key_funcs = {} for key in self.config_keys_to_funcs_mapping: chooser.config_key_funcs[key] = [None, None] - chooser.config_key_funcs[key][0] = getattr(chooser, "get_%s" % self.config_keys_to_funcs_mapping[key]) - chooser.config_key_funcs[key][1] = getattr(chooser, "set_%s" % self.config_keys_to_funcs_mapping[key]) + chooser.config_key_funcs[key][0] = getattr(chooser, 'get_%s' % self.config_keys_to_funcs_mapping[key]) + chooser.config_key_funcs[key][1] = getattr(chooser, 'set_%s' % self.config_keys_to_funcs_mapping[key]) self.path_choosers.append(chooser) if chooser.paths_config_key not in self.paths_list_keys: @@ -82,7 +82,7 @@ class PathChoosersHandler(component.Component): chooser.config_key_funcs[key][1](value) # Save to core - if key is not "path_chooser_max_popup_rows": + if key is not 'path_chooser_max_popup_rows': client.core.set_config({key: value}) else: # Since the max rows value can be changed fast with a spinbutton, we @@ -92,7 +92,7 @@ class PathChoosersHandler(component.Component): def update(value_): # The value hasn't been changed in one second, so save to core if self.max_rows_value_set == value_: - client.core.set_config({"path_chooser_max_popup_rows": value}) + client.core.set_config({'path_chooser_max_popup_rows': value}) from twisted.internet import reactor reactor.callLater(1, update, value) @@ -120,35 +120,35 @@ class PathChooser(PathChooserComboBox): self.chooser_handler = PathChoosersHandler() self.chooser_handler.register_chooser(self) self.set_auto_completer_func(self.on_completion) - self.connect("list-values-changed", self.on_list_values_changed_event) - self.connect("auto-complete-enabled-toggled", self.on_auto_complete_enabled_toggled) - self.connect("show-filechooser-toggled", self.on_show_filechooser_toggled) - self.connect("show-folder-name-on-button", self.on_show_folder_on_button_toggled) - self.connect("show-path-entry-toggled", self.on_show_path_entry_toggled) - self.connect("accelerator-set", self.on_accelerator_set) - self.connect("max-rows-changed", self.on_max_rows_changed) - self.connect("show-hidden-files-toggled", self.on_show_hidden_files_toggled) + self.connect('list-values-changed', self.on_list_values_changed_event) + self.connect('auto-complete-enabled-toggled', self.on_auto_complete_enabled_toggled) + self.connect('show-filechooser-toggled', self.on_show_filechooser_toggled) + self.connect('show-folder-name-on-button', self.on_show_folder_on_button_toggled) + self.connect('show-path-entry-toggled', self.on_show_path_entry_toggled) + self.connect('accelerator-set', self.on_accelerator_set) + self.connect('max-rows-changed', self.on_max_rows_changed) + self.connect('show-hidden-files-toggled', self.on_show_hidden_files_toggled) def on_auto_complete_enabled_toggled(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_auto_complete_enabled") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_auto_complete_enabled') def on_show_filechooser_toggled(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_chooser_button_on_localhost") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_chooser_button_on_localhost') def on_show_folder_on_button_toggled(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_folder_name") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_folder_name') def on_show_path_entry_toggled(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_path_entry") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_path_entry') def on_accelerator_set(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_accelerator_string") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_accelerator_string') def on_show_hidden_files_toggled(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_show_hidden_files") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_show_hidden_files') def on_max_rows_changed(self, widget, value): - self.chooser_handler.set_value_for_path_choosers(value, "path_chooser_max_popup_rows") + self.chooser_handler.set_value_for_path_choosers(value, 'path_chooser_max_popup_rows') def on_list_values_changed_event(self, widget, values): self.chooser_handler.on_list_values_changed(values, self.paths_config_key, self) @@ -160,7 +160,7 @@ class PathChooser(PathChooserComboBox): try: self.config_key_funcs[key][1](config[key]) except TypeError as ex: - log.warn("TypeError: %s", ex) + log.warn('TypeError: %s', ex) # Set the saved paths if self.paths_config_key and self.paths_config_key in config: diff --git a/deluge/ui/gtkui/path_combo_chooser.py b/deluge/ui/gtkui/path_combo_chooser.py index 95b6c61a4..b033cc32c 100755 --- a/deluge/ui/gtkui/path_combo_chooser.py +++ b/deluge/ui/gtkui/path_combo_chooser.py @@ -52,8 +52,8 @@ def key_is_enter(keyval): def path_without_trailing_path_sep(path): - while path.endswith("/") or path.endswith("\\"): - if path == "/": + while path.endswith('/') or path.endswith('\\'): + if path == '/': return path path = path[0:-1] return path @@ -106,8 +106,8 @@ class ValueList(object): self.handle_list_scroll(path=tree_path) if emit_signal: - self.emit("list-value-added", paths) - self.emit("list-values-changed", self.get_values()) + self.emit('list-value-added', paths) + self.emit('list-values-changed', self.get_values()) def set_values(self, paths, scroll_to_row=False, preserve_selection=True): """ @@ -155,8 +155,8 @@ class ValueList(object): path = (index, ) self.treeview.set_cursor(path) self.set_path_selected(path) - self.emit("list-value-removed", path_value) - self.emit("list-values-changed", self.get_values()) + self.emit('list-value-removed', path_value) + self.emit('list-values-changed', self.get_values()) def set_selected_value(self, value, select_first=False): """ @@ -300,8 +300,8 @@ class ValueList(object): p2 = self.tree_store[new_path][0] self.tree_store.swap(self.tree_store.get_iter(path), self.tree_store.get_iter(new_path)) - self.emit("list-values-reordered", [p1, p2]) - self.emit("list-values-changed", self.get_values()) + self.emit('list-values-reordered', [p1, p2]) + self.emit('list-values-changed', self.get_values()) path = new_path self.treeview.set_cursor(path) @@ -313,21 +313,21 @@ class ValueList(object): class StoredValuesList(ValueList): def __init__(self): - self.tree_store = self.builder.get_object("stored_values_tree_store") - self.tree_column = self.builder.get_object("stored_values_treeview_column") - self.rendererText = self.builder.get_object("stored_values_cellrenderertext") + self.tree_store = self.builder.get_object('stored_values_tree_store') + self.tree_column = self.builder.get_object('stored_values_treeview_column') + self.rendererText = self.builder.get_object('stored_values_cellrenderertext') self.paths_without_trailing_path_sep = False # Add signal handlers - self.signal_handlers["on_stored_values_treeview_mouse_button_press_event"] = \ + self.signal_handlers['on_stored_values_treeview_mouse_button_press_event'] = \ self.on_treeview_mouse_button_press_event - self.signal_handlers["on_stored_values_treeview_key_press_event"] = \ + self.signal_handlers['on_stored_values_treeview_key_press_event'] = \ self.on_stored_values_treeview_key_press_event - self.signal_handlers["on_stored_values_treeview_key_release_event"] = \ + self.signal_handlers['on_stored_values_treeview_key_release_event'] = \ self.on_stored_values_treeview_key_release_event - self.signal_handlers["on_cellrenderertext_edited"] = self.on_cellrenderertext_edited + self.signal_handlers['on_cellrenderertext_edited'] = self.on_cellrenderertext_edited def on_cellrenderertext_edited(self, cellrenderertext, path, new_text): """ @@ -376,9 +376,9 @@ class StoredValuesList(ValueList): treeview.set_cursor(path, col, 0) self.path_list_popup = gtk.Menu() - menuitem_edit = gtk.MenuItem("Edit path") + menuitem_edit = gtk.MenuItem('Edit path') self.path_list_popup.append(menuitem_edit) - menuitem_remove = gtk.MenuItem("Remove path") + menuitem_remove = gtk.MenuItem('Remove path') self.path_list_popup.append(menuitem_remove) def on_edit_clicked(widget, path): @@ -387,8 +387,8 @@ class StoredValuesList(ValueList): def on_remove_clicked(widget, path): self.remove_selected_path() - menuitem_edit.connect("activate", on_edit_clicked, path) - menuitem_remove.connect("activate", on_remove_clicked, path) + menuitem_edit.connect('activate', on_edit_clicked, path) + menuitem_remove.connect('activate', on_remove_clicked, path) self.path_list_popup.popup(None, None, None, event.button, time, data=path) self.path_list_popup.show_all() @@ -449,17 +449,17 @@ class StoredValuesList(ValueList): class CompletionList(ValueList): def __init__(self): - self.tree_store = self.builder.get_object("completion_tree_store") - self.tree_column = self.builder.get_object("completion_treeview_column") - self.rendererText = self.builder.get_object("completion_cellrenderertext") - self.completion_scrolled_window = self.builder.get_object("completion_scrolled_window") - self.signal_handlers["on_completion_treeview_key_press_event"] = \ + self.tree_store = self.builder.get_object('completion_tree_store') + self.tree_column = self.builder.get_object('completion_treeview_column') + self.rendererText = self.builder.get_object('completion_cellrenderertext') + self.completion_scrolled_window = self.builder.get_object('completion_scrolled_window') + self.signal_handlers['on_completion_treeview_key_press_event'] = \ self.on_completion_treeview_key_press_event - self.signal_handlers["on_completion_treeview_motion_notify_event"] = \ + self.signal_handlers['on_completion_treeview_motion_notify_event'] = \ self.on_completion_treeview_motion_notify_event # Add super class signal handler - self.signal_handlers["on_completion_treeview_mouse_button_press_event"] = \ + self.signal_handlers['on_completion_treeview_mouse_button_press_event'] = \ super(CompletionList, self).on_treeview_mouse_button_press_event def reduce_values(self, prefix): @@ -709,9 +709,9 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup): """ def __init__(self, builder, path_entry, max_visible_rows, popup_alignment_widget): self.builder = builder - self.treeview = self.builder.get_object("stored_values_treeview") - self.popup_window = self.builder.get_object("stored_values_popup_window") - self.button_default = self.builder.get_object("button_default") + self.treeview = self.builder.get_object('stored_values_treeview') + self.popup_window = self.builder.get_object('stored_values_popup_window') + self.button_default = self.builder.get_object('button_default') self.path_entry = path_entry self.text_entry = path_entry.text_entry @@ -719,27 +719,27 @@ class StoredValuesPopup(StoredValuesList, PathChooserPopup): PathChooserPopup.__init__(self, 0, max_visible_rows, popup_alignment_widget) StoredValuesList.__init__(self) - self.popup_buttonbox = self.builder.get_object("buttonbox") + self.popup_buttonbox = self.builder.get_object('buttonbox') # Add signal handlers - self.signal_handlers["on_buttonbox_key_press_event"] = self.on_buttonbox_key_press_event - self.signal_handlers["on_stored_values_treeview_scroll_event"] = self.on_scroll_event - self.signal_handlers["on_button_toggle_dropdown_scroll_event"] = self.on_scroll_event - self.signal_handlers["on_entry_text_scroll_event"] = self.on_scroll_event - self.signal_handlers["on_stored_values_popup_window_focus_out_event"] = \ + self.signal_handlers['on_buttonbox_key_press_event'] = self.on_buttonbox_key_press_event + self.signal_handlers['on_stored_values_treeview_scroll_event'] = self.on_scroll_event + self.signal_handlers['on_button_toggle_dropdown_scroll_event'] = self.on_scroll_event + self.signal_handlers['on_entry_text_scroll_event'] = self.on_scroll_event + self.signal_handlers['on_stored_values_popup_window_focus_out_event'] = \ self.on_stored_values_popup_window_focus_out_event # For when clicking outside the popup - self.signal_handlers["on_stored_values_popup_window_button_press_event"] = \ + self.signal_handlers['on_stored_values_popup_window_button_press_event'] = \ self.on_popup_window_button_press_event # Buttons for manipulating the list - self.signal_handlers["on_button_add_clicked"] = self.on_button_add_clicked - self.signal_handlers["on_button_edit_clicked"] = self.on_button_edit_clicked - self.signal_handlers["on_button_remove_clicked"] = self.on_button_remove_clicked - self.signal_handlers["on_button_up_clicked"] = self.on_button_up_clicked - self.signal_handlers["on_button_down_clicked"] = self.on_button_down_clicked - self.signal_handlers["on_button_default_clicked"] = self.on_button_default_clicked - self.signal_handlers["on_button_properties_clicked"] = self.path_entry._on_button_properties_clicked + self.signal_handlers['on_button_add_clicked'] = self.on_button_add_clicked + self.signal_handlers['on_button_edit_clicked'] = self.on_button_edit_clicked + self.signal_handlers['on_button_remove_clicked'] = self.on_button_remove_clicked + self.signal_handlers['on_button_up_clicked'] = self.on_button_up_clicked + self.signal_handlers['on_button_down_clicked'] = self.on_button_down_clicked + self.signal_handlers['on_button_default_clicked'] = self.on_button_default_clicked + self.signal_handlers['on_button_properties_clicked'] = self.path_entry._on_button_properties_clicked def popup(self): """ @@ -844,8 +844,8 @@ class PathCompletionPopup(CompletionList, PathChooserPopup): """ def __init__(self, builder, path_entry, max_visible_rows): self.builder = builder - self.treeview = self.builder.get_object("completion_treeview") - self.popup_window = self.builder.get_object("completion_popup_window") + self.treeview = self.builder.get_object('completion_treeview') + self.popup_window = self.builder.get_object('completion_popup_window') self.path_entry = path_entry self.text_entry = path_entry.text_entry self.show_hidden_files = False @@ -855,12 +855,12 @@ class PathCompletionPopup(CompletionList, PathChooserPopup): CompletionList.__init__(self) # Add signal handlers - self.signal_handlers["on_completion_treeview_scroll_event"] = self.on_scroll_event - self.signal_handlers["on_completion_popup_window_focus_out_event"] = \ + self.signal_handlers['on_completion_treeview_scroll_event'] = self.on_scroll_event + self.signal_handlers['on_completion_popup_window_focus_out_event'] = \ self.on_completion_popup_window_focus_out_event # For when clicking outside the popup - self.signal_handlers["on_completion_popup_window_button_press_event"] = \ + self.signal_handlers['on_completion_popup_window_button_press_event'] = \ self.on_popup_window_button_press_event def popup(self): @@ -919,10 +919,10 @@ class PathAutoCompleter(object): self.auto_complete_enabled = True self.signal_handlers = self.completion_popup.signal_handlers - self.signal_handlers["on_completion_popup_window_key_press_event"] = \ + self.signal_handlers['on_completion_popup_window_key_press_event'] = \ self.on_completion_popup_window_key_press_event - self.signal_handlers["on_entry_text_delete_text"] = self.on_entry_text_delete_text - self.signal_handlers["on_entry_text_insert_text"] = self.on_entry_text_insert_text + self.signal_handlers['on_entry_text_delete_text'] = self.on_entry_text_delete_text + self.signal_handlers['on_entry_text_insert_text'] = self.on_entry_text_insert_text self.accelerator_string = gtk.accelerator_name(keysyms.Tab, 0) def on_entry_text_insert_text(self, entry, new_text, new_text_length, position): @@ -967,7 +967,7 @@ class PathAutoCompleter(object): else: self.completion_popup.handle_list_scroll(_next=True) return True - self.path_entry.text_entry.emit("key-press-event", event) + self.path_entry.text_entry.emit('key-press-event', event) def is_auto_completion_accelerator(self, keyval, state): return gtk.accelerator_name(keyval, state.numerator) == self.accelerator_string @@ -977,9 +977,9 @@ class PathAutoCompleter(object): value = self.path_entry.get_text() self.path_entry.text_entry.set_position(len(value)) opts = {} - opts["show_hidden_files"] = self.completion_popup.show_hidden_files - opts["completion_text"] = value - opts["forward_completion"] = forward_completion + opts['show_hidden_files'] = self.completion_popup.show_hidden_files + opts['completion_text'] = value + opts['forward_completion'] = forward_completion self._start_completion(opts) def _start_completion(self, args): @@ -987,10 +987,10 @@ class PathAutoCompleter(object): self._end_completion(args) def _end_completion(self, args): - value = args["completion_text"] - paths = args["paths"] + value = args['completion_text'] + paths = args['paths'] - if args["forward_completion"]: + if args['forward_completion']: common_prefix = os.path.commonprefix(paths) if len(common_prefix) > len(value): self.path_entry.set_text(common_prefix, set_file_chooser_folder=True, trigger_event=True) @@ -1000,25 +1000,25 @@ class PathAutoCompleter(object): if self.use_popup and len(paths) > 1: self.completion_popup.popup() - elif self.completion_popup.is_popped_up() and args["forward_completion"]: + elif self.completion_popup.is_popped_up() and args['forward_completion']: self.completion_popup.popdown() class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): __gsignals__ = { - "list-value-added": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "list-value-removed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "list-values-reordered": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "list-values-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "auto-complete-enabled-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "show-filechooser-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "show-path-entry-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "show-folder-name-on-button": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "show-hidden-files-toggled": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "accelerator-set": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "max-rows-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), - "text-changed": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'list-value-added': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'list-value-removed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'list-values-reordered': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'list-values-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'auto-complete-enabled-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'show-filechooser-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'show-path-entry-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'show-folder-name-on-button': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'show-hidden-files-toggled': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'accelerator-set': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'max-rows-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), + 'text-changed': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (object, )), } def __init__(self, max_visible_rows=20, auto_complete=True, use_completer_popup=True): @@ -1032,19 +1032,19 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): self.show_folder_name_on_button = False self.setting_accelerator_key = False self.builder = gtk.Builder() - self.popup_buttonbox = self.builder.get_object("buttonbox") + self.popup_buttonbox = self.builder.get_object('buttonbox') self.builder.add_from_file(resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "path_combo_chooser.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'path_combo_chooser.ui') )) - self.button_toggle = self.builder.get_object("button_toggle_dropdown") - self.text_entry = self.builder.get_object("entry_text") - self.open_filechooser_dialog_button = self.builder.get_object("button_open_dialog") + self.button_toggle = self.builder.get_object('button_toggle_dropdown') + self.text_entry = self.builder.get_object('entry_text') + self.open_filechooser_dialog_button = self.builder.get_object('button_open_dialog') self.filechooser_button = self.open_filechooser_dialog_button - self.filechooserdialog = self.builder.get_object("filechooserdialog") - self.folder_name_label = self.builder.get_object("folder_name_label") + self.filechooserdialog = self.builder.get_object('filechooserdialog') + self.folder_name_label = self.builder.get_object('folder_name_label') self.default_text = None - self.button_properties = self.builder.get_object("button_properties") - self.combo_hbox = self.builder.get_object("entry_combobox_hbox") + self.button_properties = self.builder.get_object('button_properties') + self.combo_hbox = self.builder.get_object('entry_combobox_hbox') # Change the parent of the hbox from the glade Window to this hbox. self.combo_hbox.reparent(self) StoredValuesPopup.__init__(self, self.builder, self, max_visible_rows, self.combo_hbox) @@ -1055,14 +1055,14 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): self._setup_config_dialog() signal_handlers = { - "on_button_toggle_dropdown_toggled": self._on_button_toggle_dropdown_toggled, + 'on_button_toggle_dropdown_toggled': self._on_button_toggle_dropdown_toggled, 'on_entry_text_key_press_event': self._on_entry_text_key_press_event, 'on_stored_values_popup_window_hide': self._on_stored_values_popup_window_hide, - "on_button_toggle_dropdown_button_press_event": self._on_button_toggle_dropdown_button_press_event, - "on_entry_combobox_hbox_realize": self._on_entry_combobox_hbox_realize, - "on_button_open_dialog_clicked": self._on_button_open_dialog_clicked, - "on_entry_text_focus_out_event": self._on_entry_text_focus_out_event, - "on_entry_text_changed": self.on_entry_text_changed, + 'on_button_toggle_dropdown_button_press_event': self._on_button_toggle_dropdown_button_press_event, + 'on_entry_combobox_hbox_realize': self._on_entry_combobox_hbox_realize, + 'on_button_open_dialog_clicked': self._on_button_open_dialog_clicked, + 'on_entry_text_focus_out_event': self._on_entry_text_focus_out_event, + 'on_entry_text_changed': self.on_entry_text_changed, } signal_handlers.update(self.signal_handlers) signal_handlers.update(self.auto_completer.signal_handlers) @@ -1092,13 +1092,13 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): self.combo_hbox.set_tooltip_text(text) if default_text: self.default_text = text - self.button_default.set_tooltip_text("Restore the default value in the text entry:\n%s" % self.default_text) + self.button_default.set_tooltip_text('Restore the default value in the text entry:\n%s' % self.default_text) self.button_default.set_sensitive(True) # Set text for the filechooser dialog button - folder_name = "" + folder_name = '' if self.show_folder_name_on_button or not self.path_entry_visible: folder_name = path_without_trailing_path_sep(text) - if folder_name is not "/" and os.path.basename(folder_name): + if folder_name is not '/' and os.path.basename(folder_name): folder_name = os.path.basename(folder_name) self.folder_name_label.set_text(folder_name) # Only trigger event if text has changed @@ -1131,7 +1131,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): keyval, mask = gtk.accelerator_parse(self.auto_completer.accelerator_string) self.auto_completer.accelerator_string = accelerator except TypeError as ex: - raise TypeError("TypeError when setting accelerator string: %s" % ex) + raise TypeError('TypeError when setting accelerator string: %s' % ex) def get_auto_complete_enabled(self): return self.auto_completer.auto_complete_enabled @@ -1215,7 +1215,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): if do_completion: self.auto_completer.do_completion() if emit_event: - self.emit("show-hidden-files-toggled", show) + self.emit('show-hidden-files-toggled', show) def set_enable_properties(self, enable): """ @@ -1247,7 +1247,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): ############## def on_entry_text_changed(self, entry): - self.emit("text-changed", self.get_text()) + self.emit('text-changed', self.get_text()) def _on_entry_text_focus_out_event(self, widget, event): # Update text on the button label @@ -1376,19 +1376,19 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): self.show_hidden_files_checkbutton.set_sensitive(val) def _setup_config_dialog(self): - self.config_dialog = self.builder.get_object("completion_config_dialog") - self.enable_completion = self.builder.get_object("enable_auto_completion_checkbutton") - self.show_filechooser_checkbutton = self.builder.get_object("show_filechooser_checkbutton") - self.show_path_entry_checkbutton = self.builder.get_object("show_path_entry_checkbutton") - set_key_button = self.builder.get_object("set_completion_accelerator_button") + self.config_dialog = self.builder.get_object('completion_config_dialog') + self.enable_completion = self.builder.get_object('enable_auto_completion_checkbutton') + self.show_filechooser_checkbutton = self.builder.get_object('show_filechooser_checkbutton') + self.show_path_entry_checkbutton = self.builder.get_object('show_path_entry_checkbutton') + set_key_button = self.builder.get_object('set_completion_accelerator_button') default_set_accelerator_tooltip = set_key_button.get_tooltip_text() - self.config_short_cuts_frame = self.builder.get_object("config_short_cuts_frame") - self.config_general_frame = self.builder.get_object("config_general_frame") - self.accelerator_label = self.builder.get_object("completion_accelerator_label") - self.visible_rows = self.builder.get_object("visible_rows_spinbutton") - self.visible_rows_label = self.builder.get_object("visible_rows_label") - self.show_hidden_files_checkbutton = self.builder.get_object("show_hidden_files_checkbutton") - self.show_folder_name_on_button_checkbutton = self.builder.get_object("show_folder_name_on_button_checkbutton") + self.config_short_cuts_frame = self.builder.get_object('config_short_cuts_frame') + self.config_general_frame = self.builder.get_object('config_general_frame') + self.accelerator_label = self.builder.get_object('completion_accelerator_label') + self.visible_rows = self.builder.get_object('visible_rows_spinbutton') + self.visible_rows_label = self.builder.get_object('visible_rows_label') + self.show_hidden_files_checkbutton = self.builder.get_object('show_hidden_files_checkbutton') + self.show_folder_name_on_button_checkbutton = self.builder.get_object('show_folder_name_on_button_checkbutton') self.config_dialog.set_transient_for(self.popup_window) def on_close(widget, event=None): @@ -1400,11 +1400,11 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): def on_enable_completion_toggled(widget): self.set_auto_complete_enabled(self.enable_completion.get_active()) - self.emit("auto-complete-enabled-toggled", self.enable_completion.get_active()) + self.emit('auto-complete-enabled-toggled', self.enable_completion.get_active()) def on_show_filechooser_toggled(widget): self.set_filechooser_button_visible(self.show_filechooser_checkbutton.get_active()) - self.emit("show-filechooser-toggled", self.show_filechooser_checkbutton.get_active()) + self.emit('show-filechooser-toggled', self.show_filechooser_checkbutton.get_active()) self.show_folder_name_on_button_checkbutton.set_sensitive(self.show_path_entry_checkbutton.get_active() and self.show_filechooser_checkbutton.get_active()) if not self.filechooser_visible and not self.path_entry_visible: @@ -1413,7 +1413,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): def on_show_path_entry_toggled(widget): self.set_path_entry_visible(self.show_path_entry_checkbutton.get_active()) - self.emit("show-path-entry-toggled", self.show_path_entry_checkbutton.get_active()) + self.emit('show-path-entry-toggled', self.show_path_entry_checkbutton.get_active()) self.show_folder_name_on_button_checkbutton.set_sensitive(self.show_path_entry_checkbutton.get_active() and self.show_filechooser_checkbutton.get_active()) if not self.filechooser_visible and not self.path_entry_visible: @@ -1423,18 +1423,18 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): def on_show_folder_name_on_button(widget): self.set_show_folder_name_on_button(self.show_folder_name_on_button_checkbutton.get_active()) self._set_path_entry_filechooser_widths() - self.emit("show-folder-name-on-button", self.show_folder_name_on_button_checkbutton.get_active()) + self.emit('show-folder-name-on-button', self.show_folder_name_on_button_checkbutton.get_active()) def on_show_hidden_files_toggled(widget): self.set_show_hidden_files(self.show_hidden_files_checkbutton.get_active(), emit_event=True) def on_max_rows_changed(widget): self.set_max_popup_rows(self.visible_rows.get_value_as_int()) - self.emit("max-rows-changed", self.visible_rows.get_value_as_int()) + self.emit('max-rows-changed', self.visible_rows.get_value_as_int()) def set_accelerator(widget): self.setting_accelerator_key = True - set_key_button.set_tooltip_text("Press the accelerator keys for triggering auto-completion") + set_key_button.set_tooltip_text('Press the accelerator keys for triggering auto-completion') self._set_properties_widgets_sensitive(False) return True @@ -1455,7 +1455,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): accelerator_mask = 0 self.auto_completer.accelerator_string = gtk.accelerator_name(event.keyval, accelerator_mask) self.accelerator_label.set_text(gtk.accelerator_get_label(event.keyval, accelerator_mask)) - self.emit("accelerator-set", self.auto_completer.accelerator_string) + self.emit('accelerator-set', self.auto_completer.accelerator_string) stop_setting_accelerator() return True else: @@ -1473,22 +1473,22 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject): return True self.config_dialog_signal_handlers = { - "on_enable_auto_completion_checkbutton_toggled": on_enable_completion_toggled, - "on_show_filechooser_checkbutton_toggled": on_show_filechooser_toggled, - "on_show_path_entry_checkbutton_toggled": on_show_path_entry_toggled, - "on_show_folder_name_on_button_checkbutton_toggled": on_show_folder_name_on_button, - "on_config_dialog_button_close_clicked": on_close, - "on_visible_rows_spinbutton_value_changed": on_max_rows_changed, - "on_completion_config_dialog_delete_event": on_close, - "on_set_completion_accelerator_button_pressed": set_accelerator, - "on_completion_config_dialog_key_release_event": on_completion_config_dialog_key_release_event, - "on_set_completion_accelerator_button_clicked": on_set_completion_accelerator_button_clicked, - "on_show_hidden_files_checkbutton_toggled": on_show_hidden_files_toggled, + 'on_enable_auto_completion_checkbutton_toggled': on_enable_completion_toggled, + 'on_show_filechooser_checkbutton_toggled': on_show_filechooser_toggled, + 'on_show_path_entry_checkbutton_toggled': on_show_path_entry_toggled, + 'on_show_folder_name_on_button_checkbutton_toggled': on_show_folder_name_on_button, + 'on_config_dialog_button_close_clicked': on_close, + 'on_visible_rows_spinbutton_value_changed': on_max_rows_changed, + 'on_completion_config_dialog_delete_event': on_close, + 'on_set_completion_accelerator_button_pressed': set_accelerator, + 'on_completion_config_dialog_key_release_event': on_completion_config_dialog_key_release_event, + 'on_set_completion_accelerator_button_clicked': on_set_completion_accelerator_button_clicked, + 'on_show_hidden_files_checkbutton_toggled': on_show_hidden_files_toggled, } gobject.type_register(PathChooserComboBox) -if __name__ == "__main__": +if __name__ == '__main__': import sys w = gtk.Window() w.set_position(gtk.WIN_POS_CENTER) @@ -1499,7 +1499,7 @@ if __name__ == "__main__": box1 = gtk.VBox(gtk.FALSE, 0) def get_resource2(filename): - return "%s/glade/%s" % (os.path.abspath(os.path.dirname(sys.argv[0])), filename) + return '%s/glade/%s' % (os.path.abspath(os.path.dirname(sys.argv[0])), filename) # Override get_resource which fetches from deluge install # get_resource = get_resource2 @@ -1511,21 +1511,21 @@ if __name__ == "__main__": box1.add(entry2) test_paths = [ - "/home/bro/Downloads", - "/media/Movies-HD", - "/media/torrent/in", - "/media/Live-show/Misc", - "/media/Live-show/Consert", - "/media/Series/1/", - "/media/Series/2", - "/media/Series/17", - "/media/Series/18", - "/media/Series/19" + '/home/bro/Downloads', + '/media/Movies-HD', + '/media/torrent/in', + '/media/Live-show/Misc', + '/media/Live-show/Consert', + '/media/Series/1/', + '/media/Series/2', + '/media/Series/17', + '/media/Series/18', + '/media/Series/19' ] entry1.add_values(test_paths) - entry1.set_text("/home/bro/", default_text=True) - entry2.set_text("/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/", + entry1.set_text('/home/bro/', default_text=True) + entry2.set_text('/home/bro/programmer/deluge/deluge-yarss-plugin/build/lib/yarss2/include/bs4/tests/', cursor_end=False) entry2.set_filechooser_button_visible(False) @@ -1533,10 +1533,10 @@ if __name__ == "__main__": entry2.set_filechooser_button_enabled(False) def list_value_added_event(widget, values): - print("Current list values:", widget.get_values()) + print('Current list values:', widget.get_values()) - entry1.connect("list-value-added", list_value_added_event) - entry2.connect("list-value-added", list_value_added_event) + entry1.connect('list-value-added', list_value_added_event) + entry2.connect('list-value-added', list_value_added_event) w.add(box1) w.show_all() gtk.main() diff --git a/deluge/ui/gtkui/peers_tab.py b/deluge/ui/gtkui/peers_tab.py index 5202fc9d4..0614b4e81 100644 --- a/deluge/ui/gtkui/peers_tab.py +++ b/deluge/ui/gtkui/peers_tab.py @@ -26,33 +26,33 @@ log = logging.getLogger(__name__) def cell_data_progress(column, cell, model, row, data): value = model.get_value(row, data) * 100 - cell.set_property("value", value) - cell.set_property("text", "%i%%" % value) + cell.set_property('value', value) + cell.set_property('text', '%i%%' % value) class PeersTab(Tab): def __init__(self): Tab.__init__(self) - builder = component.get("MainWindow").get_builder() - - self._name = "Peers" - self._child_widget = builder.get_object("peers_tab") - self._tab_label = builder.get_object("peers_tab_label") - self.peer_menu = builder.get_object("menu_peer_tab") - component.get("MainWindow").connect_signals({ - "on_menuitem_add_peer_activate": self._on_menuitem_add_peer_activate, + builder = component.get('MainWindow').get_builder() + + self._name = 'Peers' + self._child_widget = builder.get_object('peers_tab') + self._tab_label = builder.get_object('peers_tab_label') + self.peer_menu = builder.get_object('menu_peer_tab') + component.get('MainWindow').connect_signals({ + 'on_menuitem_add_peer_activate': self._on_menuitem_add_peer_activate, }) - self.listview = builder.get_object("peers_listview") + self.listview = builder.get_object('peers_listview') self.listview.props.has_tooltip = True - self.listview.connect("button-press-event", self._on_button_press_event) - self.listview.connect("query-tooltip", self._on_query_tooltip) + self.listview.connect('button-press-event', self._on_button_press_event) + self.listview.connect('query-tooltip', self._on_query_tooltip) # country pixbuf, ip, client, downspeed, upspeed, country code, int_ip, seed/peer icon, progress self.liststore = gtk.ListStore(gtk.gdk.Pixbuf, str, str, int, int, str, float, gtk.gdk.Pixbuf, float) self.cached_flag_pixbufs = {} - self.seed_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap("seeding16.png")) - self.peer_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap("downloading16.png")) + self.seed_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap('seeding16.png')) + self.peer_pixbuf = gtk.gdk.pixbuf_new_from_file(deluge.common.get_pixmap('downloading16.png')) # key is ip address, item is row iter self.peers = {} @@ -61,7 +61,7 @@ class PeersTab(Tab): column = gtk.TreeViewColumn() render = gtk.CellRendererPixbuf() column.pack_start(render, False) - column.add_attribute(render, "pixbuf", 0) + column.add_attribute(render, 'pixbuf', 0) column.set_sort_column_id(5) column.set_clickable(True) column.set_resizable(True) @@ -71,13 +71,13 @@ class PeersTab(Tab): self.listview.append_column(column) # Address column - column = gtk.TreeViewColumn(_("Address")) + column = gtk.TreeViewColumn(_('Address')) render = gtk.CellRendererPixbuf() column.pack_start(render, False) - column.add_attribute(render, "pixbuf", 7) + column.add_attribute(render, 'pixbuf', 7) render = gtk.CellRendererText() column.pack_start(render, False) - column.add_attribute(render, "text", 1) + column.add_attribute(render, 'text', 1) column.set_sort_column_id(6) column.set_clickable(True) column.set_resizable(True) @@ -87,10 +87,10 @@ class PeersTab(Tab): self.listview.append_column(column) # Client column - column = gtk.TreeViewColumn(_("Client")) + column = gtk.TreeViewColumn(_('Client')) render = gtk.CellRendererText() column.pack_start(render, False) - column.add_attribute(render, "text", 2) + column.add_attribute(render, 'text', 2) column.set_sort_column_id(2) column.set_clickable(True) column.set_resizable(True) @@ -100,7 +100,7 @@ class PeersTab(Tab): self.listview.append_column(column) # Progress column - column = gtk.TreeViewColumn(_("Progress")) + column = gtk.TreeViewColumn(_('Progress')) render = gtk.CellRendererProgress() column.pack_start(render, True) column.set_cell_data_func(render, cell_data_progress, 8) @@ -113,7 +113,7 @@ class PeersTab(Tab): self.listview.append_column(column) # Down Speed column - column = gtk.TreeViewColumn(_("Down Speed")) + column = gtk.TreeViewColumn(_('Down Speed')) render = gtk.CellRendererText() column.pack_start(render, False) column.set_cell_data_func(render, cell_data_speed_down, 3) @@ -126,7 +126,7 @@ class PeersTab(Tab): self.listview.append_column(column) # Up Speed column - column = gtk.TreeViewColumn(_("Up Speed")) + column = gtk.TreeViewColumn(_('Up Speed')) render = gtk.CellRendererText() column.pack_start(render, False) column.set_cell_data_func(render, cell_data_speed_up, 4) @@ -152,50 +152,50 @@ class PeersTab(Tab): # Setup state dict state = { - "columns": {}, - "sort_id": column_id, - "sort_order": int(sort_order) if sort_order else None + 'columns': {}, + 'sort_id': column_id, + 'sort_order': int(sort_order) if sort_order else None } for index, column in enumerate(self.listview.get_columns()): - state["columns"][column.get_title()] = { - "position": index, - "width": column.get_width() + state['columns'][column.get_title()] = { + 'position': index, + 'width': column.get_width() } - save_pickled_state_file("peers_tab.state", state) + save_pickled_state_file('peers_tab.state', state) def load_state(self): - state = load_pickled_state_file("peers_tab.state") + state = load_pickled_state_file('peers_tab.state') if state is None: return - if len(state["columns"]) != len(self.listview.get_columns()): - log.warning("peers_tab.state is not compatible! rejecting..") + if len(state['columns']) != len(self.listview.get_columns()): + log.warning('peers_tab.state is not compatible! rejecting..') return - if state["sort_id"] and state["sort_order"] is not None: - self.liststore.set_sort_column_id(state["sort_id"], state["sort_order"]) + if state['sort_id'] and state['sort_order'] is not None: + self.liststore.set_sort_column_id(state['sort_id'], state['sort_order']) for (index, column) in enumerate(self.listview.get_columns()): cname = column.get_title() - if cname in state["columns"]: - cstate = state["columns"][cname] + if cname in state['columns']: + cstate = state['columns'][cname] column.set_sizing(gtk.TREE_VIEW_COLUMN_FIXED) - column.set_fixed_width(cstate["width"] if cstate["width"] > 0 else 10) - if state["sort_id"] == index and state["sort_order"] is not None: + column.set_fixed_width(cstate['width'] if cstate['width'] > 0 else 10) + if state['sort_id'] == index and state['sort_order'] is not None: column.set_sort_indicator(True) - column.set_sort_order(state["sort_order"]) - if cstate["position"] != index: + column.set_sort_order(state['sort_order']) + if cstate['position'] != index: # Column is in wrong position - if cstate["position"] == 0: + if cstate['position'] == 0: self.listview.move_column_after(column, None) - elif self.listview.get_columns()[cstate["position"] - 1].get_title() != cname: - self.listview.move_column_after(column, self.listview.get_columns()[cstate["position"] - 1]) + elif self.listview.get_columns()[cstate['position'] - 1].get_title() != cname: + self.listview.move_column_after(column, self.listview.get_columns()[cstate['position'] - 1]) def update(self): # Get the first selected torrent - torrent_id = component.get("TorrentView").get_selected_torrents() + torrent_id = component.get('TorrentView').get_selected_torrents() # Only use the first torrent in the list or return if None selected if len(torrent_id) != 0: @@ -211,7 +211,7 @@ class PeersTab(Tab): self.peers = {} self.torrent_id = torrent_id - component.get("SessionProxy").get_torrent_status(torrent_id, ["peers"]).addCallback(self._on_get_torrent_status) + component.get('SessionProxy').get_torrent_status(torrent_id, ['peers']).addCallback(self._on_get_torrent_status) def get_flag_pixbuf(self, country): if not country.strip(): @@ -222,34 +222,34 @@ class PeersTab(Tab): try: self.cached_flag_pixbufs[country] = gtk.gdk.pixbuf_new_from_file( deluge.common.resource_filename( - "deluge", - os.path.join("ui", "data", "pixmaps", "flags", country.lower() + ".png"))) + 'deluge', + os.path.join('ui', 'data', 'pixmaps', 'flags', country.lower() + '.png'))) except Exception as ex: - log.debug("Unable to load flag: %s", ex) + log.debug('Unable to load flag: %s', ex) return None return self.cached_flag_pixbufs[country] def _on_get_torrent_status(self, status): new_ips = set() - for peer in status["peers"]: - new_ips.add(peer["ip"]) - if peer["ip"] in self.peers: + for peer in status['peers']: + new_ips.add(peer['ip']) + if peer['ip'] in self.peers: # We already have this peer in our list, so lets just update it - row = self.peers[peer["ip"]] + row = self.peers[peer['ip']] if not self.liststore.iter_is_valid(row): # This iter is invalid, delete it and continue to next iteration - del self.peers[peer["ip"]] + del self.peers[peer['ip']] continue values = self.liststore.get(row, 3, 4, 5, 7, 8) - if peer["down_speed"] != values[0]: - self.liststore.set_value(row, 3, peer["down_speed"]) - if peer["up_speed"] != values[1]: - self.liststore.set_value(row, 4, peer["up_speed"]) - if peer["country"] != values[2]: - self.liststore.set_value(row, 5, peer["country"]) - self.liststore.set_value(row, 0, self.get_flag_pixbuf(peer["country"])) - if peer["seed"]: + if peer['down_speed'] != values[0]: + self.liststore.set_value(row, 3, peer['down_speed']) + if peer['up_speed'] != values[1]: + self.liststore.set_value(row, 4, peer['up_speed']) + if peer['country'] != values[2]: + self.liststore.set_value(row, 5, peer['country']) + self.liststore.set_value(row, 0, self.get_flag_pixbuf(peer['country'])) + if peer['seed']: icon = self.seed_pixbuf else: icon = self.peer_pixbuf @@ -257,43 +257,43 @@ class PeersTab(Tab): if icon != values[3]: self.liststore.set_value(row, 7, icon) - if peer["progress"] != values[4]: - self.liststore.set_value(row, 8, peer["progress"]) + if peer['progress'] != values[4]: + self.liststore.set_value(row, 8, peer['progress']) else: # Peer is not in list so we need to add it # Create an int IP address for sorting purposes - if peer["ip"].count(":") == 1: + if peer['ip'].count(':') == 1: # This is an IPv4 address ip_int = sum([int(byte) << shift - for byte, shift in zip(peer["ip"].split(":")[0].split("."), (24, 16, 8, 0))]) - peer_ip = peer["ip"] + for byte, shift in zip(peer['ip'].split(':')[0].split('.'), (24, 16, 8, 0))]) + peer_ip = peer['ip'] else: # This is an IPv6 address import socket import binascii # Split out the :port - ip = ":".join(peer["ip"].split(":")[:-1]) + ip = ':'.join(peer['ip'].split(':')[:-1]) ip_int = int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16) - peer_ip = "[%s]:%s" % (ip, peer["ip"].split(":")[-1]) + peer_ip = '[%s]:%s' % (ip, peer['ip'].split(':')[-1]) - if peer["seed"]: + if peer['seed']: icon = self.seed_pixbuf else: icon = self.peer_pixbuf row = self.liststore.append([ - self.get_flag_pixbuf(peer["country"]), + self.get_flag_pixbuf(peer['country']), peer_ip, - peer["client"], - peer["down_speed"], - peer["up_speed"], - peer["country"], + peer['client'], + peer['down_speed'], + peer['up_speed'], + peer['country'], float(ip_int), icon, - peer["progress"]]) + peer['progress']]) - self.peers[peer["ip"]] = row + self.peers[peer['ip']] = row # Now we need to remove any ips that were not in status["peers"] list for ip in set(self.peers).difference(new_ips): @@ -305,7 +305,7 @@ class PeersTab(Tab): def _on_button_press_event(self, widget, event): """This is a callback for showing the right-click context menu.""" - log.debug("on_button_press_event") + log.debug('on_button_press_event') # We only care about right-clicks if self.torrent_id and event.button == 3: self.peer_menu.popup(None, None, None, event.button, event.time) @@ -318,7 +318,7 @@ class PeersTab(Tab): model, path, _iter = widget.get_tooltip_context(x, y, keyboard_tip) country_code = model.get(_iter, 5)[0] - if country_code != " " and country_code in COUNTRIES: + if country_code != ' ' and country_code in COUNTRIES: tooltip.set_text(COUNTRIES[country_code]) # widget here is self.listview widget.set_tooltip_cell(tooltip, path, widget.get_column(0), @@ -329,27 +329,27 @@ class PeersTab(Tab): def _on_menuitem_add_peer_activate(self, menuitem): """This is a callback for manually adding a peer""" - log.debug("on_menuitem_add_peer") + log.debug('on_menuitem_add_peer') builder = gtk.Builder() builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "connect_peer_dialog.ui") + 'deluge.ui.gtkui', os.path.join('glade', 'connect_peer_dialog.ui') )) - peer_dialog = builder.get_object("connect_peer_dialog") - txt_ip = builder.get_object("txt_ip") + peer_dialog = builder.get_object('connect_peer_dialog') + txt_ip = builder.get_object('txt_ip') response = peer_dialog.run() if response: value = txt_ip.get_text() if value and ':' in value: if ']' in value: # ipv6 - ip = value.split("]")[0][1:] - port = value.split("]")[1][1:] + ip = value.split(']')[0][1:] + port = value.split(']')[1][1:] else: # ipv4 - ip = value.split(":")[0] - port = value.split(":")[1] + ip = value.split(':')[0] + port = value.split(':')[1] if deluge.common.is_ip(ip): - log.debug("adding peer %s to %s", value, self.torrent_id) + log.debug('adding peer %s to %s', value, self.torrent_id) client.core.connect_peer(self.torrent_id, ip, port) peer_dialog.destroy() return True diff --git a/deluge/ui/gtkui/piecesbar.py b/deluge/ui/gtkui/piecesbar.py index c6e44dd79..88db3b0e5 100644 --- a/deluge/ui/gtkui/piecesbar.py +++ b/deluge/ui/gtkui/piecesbar.py @@ -18,12 +18,12 @@ from cairo import FORMAT_ARGB32, Context, ImageSurface from deluge.configmanager import ConfigManager -COLOR_STATES = ["missing", "waiting", "downloading", "completed"] +COLOR_STATES = ['missing', 'waiting', 'downloading', 'completed'] class PiecesBar(gtk.DrawingArea): # Draw in response to an expose-event - __gsignals__ = {"expose-event": "override"} + __gsignals__ = {'expose-event': 'override'} def __init__(self): gtk.DrawingArea.__init__(self) @@ -36,13 +36,13 @@ class PiecesBar(gtk.DrawingArea): del pb, pb_style self.set_size_request(-1, 25) - self.gtkui_config = ConfigManager("gtkui.conf") + self.gtkui_config = ConfigManager('gtkui.conf') self.width = self.prev_width = 0 self.height = self.prev_height = 0 self.pieces = self.prev_pieces = () self.num_pieces = None - self.text = self.prev_text = "" + self.text = self.prev_text = '' self.fraction = self.prev_fraction = 0 self.progress_overlay = self.text_overlay = self.pieces_overlay = None self.cr = None @@ -113,10 +113,10 @@ class PiecesBar(gtk.DrawingArea): pieces = self.pieces elif self.num_pieces: # Completed torrents do not send any pieces so create list using 'completed' state. - pieces = [COLOR_STATES.index("completed")] * self.num_pieces + pieces = [COLOR_STATES.index('completed')] * self.num_pieces start_pos = 0 piece_width = self.width / len(pieces) - pieces_colors = [[color / 65535 for color in self.gtkui_config["pieces_color_%s" % state]] + pieces_colors = [[color / 65535 for color in self.gtkui_config['pieces_color_%s' % state]] for state in COLOR_STATES] for state in pieces: ctx.set_source_rgb(*pieces_colors[state]) @@ -196,7 +196,7 @@ class PiecesBar(gtk.DrawingArea): def clear(self): self.pieces = self.prev_pieces = () self.num_pieces = None - self.text = self.prev_text = "" + self.text = self.prev_text = '' self.fraction = self.prev_fraction = 0 self.progress_overlay = self.text_overlay = self.pieces_overlay = None self.cr = None diff --git a/deluge/ui/gtkui/pluginmanager.py b/deluge/ui/gtkui/pluginmanager.py index ab53a53b8..1530b0b7e 100644 --- a/deluge/ui/gtkui/pluginmanager.py +++ b/deluge/ui/gtkui/pluginmanager.py @@ -19,32 +19,32 @@ log = logging.getLogger(__name__) class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Component): def __init__(self): - component.Component.__init__(self, "PluginManager") - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'PluginManager') + self.config = ConfigManager('gtkui.conf') deluge.pluginmanagerbase.PluginManagerBase.__init__( - self, "gtkui.conf", "deluge.plugin.gtkui") + self, 'gtkui.conf', 'deluge.plugin.gtkui') self.hooks = { - "on_apply_prefs": [], - "on_show_prefs": [] + 'on_apply_prefs': [], + 'on_show_prefs': [] } - client.register_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event) - client.register_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event) + client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event) + client.register_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event) def register_hook(self, hook, function): """Register a hook function with the plugin manager""" try: self.hooks[hook].append(function) except KeyError: - log.warning("Plugin attempting to register invalid hook.") + log.warning('Plugin attempting to register invalid hook.') def deregister_hook(self, hook, function): """Deregisters a hook function""" try: self.hooks[hook].remove(function) except KeyError: - log.warning("Unable to deregister hook %s", hook) + log.warning('Unable to deregister hook %s', hook) def start(self): """Start the plugin manager""" @@ -61,7 +61,7 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon pass def _on_get_enabled_plugins(self, enabled_plugins): - log.debug("Core has these plugins enabled: %s", enabled_plugins) + log.debug('Core has these plugins enabled: %s', enabled_plugins) for plugin in enabled_plugins: self.enable_plugin(plugin) @@ -81,53 +81,53 @@ class PluginManager(deluge.pluginmanagerbase.PluginManagerBase, component.Compon """This hook is run before the user is shown the preferences dialog. It is designed so that plugins can update their preference page with the config.""" - log.debug("run_on_show_prefs") - for function in self.hooks["on_show_prefs"]: + log.debug('run_on_show_prefs') + for function in self.hooks['on_show_prefs']: function() def run_on_apply_prefs(self): """This hook is run after the user clicks Apply or OK in the preferences dialog. """ - log.debug("run_on_apply_prefs") - for function in self.hooks["on_apply_prefs"]: + log.debug('run_on_apply_prefs') + for function in self.hooks['on_apply_prefs']: function() # Plugin functions.. will likely move to own class.. 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) def remove_torrentview_column(self, *args): - return component.get("TorrentView").remove_column(*args) + return component.get('TorrentView').remove_column(*args) def add_toolbar_separator(self): - return component.get("ToolBar").add_separator() + return component.get('ToolBar').add_separator() def add_toolbar_button(self, *args, **kwargs): - return component.get("ToolBar").add_toolbutton(*args, **kwargs) + return component.get('ToolBar').add_toolbutton(*args, **kwargs) def remove_toolbar_button(self, *args): - return component.get("ToolBar").remove(*args) + return component.get('ToolBar').remove(*args) def add_torrentmenu_menu(self, *args): - return component.get("MenuBar").torrentmenu.append(*args) + return component.get('MenuBar').torrentmenu.append(*args) def add_torrentmenu_separator(self): - return component.get("MenuBar").add_torrentmenu_separator() + return component.get('MenuBar').add_torrentmenu_separator() def remove_torrentmenu_item(self, *args): - return component.get("MenuBar").torrentmenu.remove(*args) + return component.get('MenuBar').torrentmenu.remove(*args) def add_preferences_page(self, *args): - return component.get("Preferences").add_page(*args) + return component.get('Preferences').add_page(*args) def remove_preferences_page(self, *args): - return component.get("Preferences").remove_page(*args) + return component.get('Preferences').remove_page(*args) def update_torrent_view(self, *args): - return component.get("TorrentView").update(*args) + return component.get('TorrentView').update(*args) def get_selected_torrents(self): """Returns a list of the selected torrent_ids""" - return component.get("TorrentView").get_selected_torrents() + return component.get('TorrentView').get_selected_torrents() diff --git a/deluge/ui/gtkui/preferences.py b/deluge/ui/gtkui/preferences.py index 2663b9dbd..35db664ad 100644 --- a/deluge/ui/gtkui/preferences.py +++ b/deluge/ui/gtkui/preferences.py @@ -34,118 +34,118 @@ ACCOUNTS_USERNAME, ACCOUNTS_LEVEL, ACCOUNTS_PASSWORD = range(3) COLOR_MISSING, COLOR_WAITING, COLOR_DOWNLOADING, COLOR_COMPLETED = range(4) COLOR_STATES = { - "missing": COLOR_MISSING, - "waiting": COLOR_WAITING, - "downloading": COLOR_DOWNLOADING, - "completed": COLOR_COMPLETED + 'missing': COLOR_MISSING, + 'waiting': COLOR_WAITING, + 'downloading': COLOR_DOWNLOADING, + 'completed': COLOR_COMPLETED } class Preferences(component.Component): def __init__(self): - component.Component.__init__(self, "Preferences") + component.Component.__init__(self, 'Preferences') self.builder = gtk.Builder() self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "preferences_dialog.ui"))) - self.pref_dialog = self.builder.get_object("pref_dialog") - self.pref_dialog.set_transient_for(component.get("MainWindow").window) + 'deluge.ui.gtkui', os.path.join('glade', 'preferences_dialog.ui'))) + self.pref_dialog = self.builder.get_object('pref_dialog') + self.pref_dialog.set_transient_for(component.get('MainWindow').window) self.pref_dialog.set_icon(get_deluge_icon()) - self.treeview = self.builder.get_object("treeview") - self.notebook = self.builder.get_object("notebook") - self.gtkui_config = ConfigManager("gtkui.conf") + self.treeview = self.builder.get_object('treeview') + self.notebook = self.builder.get_object('notebook') + self.gtkui_config = ConfigManager('gtkui.conf') self.window_open = False self.load_pref_dialog_state() - self.builder.get_object("image_magnet").set_from_file( - deluge.common.get_pixmap("magnet.png")) + self.builder.get_object('image_magnet').set_from_file( + deluge.common.get_pixmap('magnet.png')) # Hide the unused associate magnet button on OSX see: #2420 if deluge.common.osx_check(): - self.builder.get_object("button_associate_magnet").hide() + self.builder.get_object('button_associate_magnet').hide() # Setup the liststore for the categories (tab pages) self.liststore = gtk.ListStore(int, str) self.treeview.set_model(self.liststore) render = gtk.CellRendererText() - column = gtk.TreeViewColumn(_("Categories"), render, text=1) + column = gtk.TreeViewColumn(_('Categories'), render, text=1) self.treeview.append_column(column) # Add the default categories i = 0 - for category in (_("Interface"), _("Downloads"), _("Bandwidth"), _("Queue"), _("Network"), - _("Proxy"), _("Cache"), _("Other"), _("Daemon"), _("Plugins"), "_separator_"): + for category in (_('Interface'), _('Downloads'), _('Bandwidth'), _('Queue'), _('Network'), + _('Proxy'), _('Cache'), _('Other'), _('Daemon'), _('Plugins'), '_separator_'): self.liststore.append([i, category]) i += 1 def set_separator(model, _iter, data=None): - if model.get_value(_iter, 1) == "_separator_": + if model.get_value(_iter, 1) == '_separator_': return True self.treeview.set_row_separator_func(set_separator) # Setup accounts tab lisview self.accounts_levels_mapping = None - self.accounts_authlevel = self.builder.get_object("accounts_authlevel") + self.accounts_authlevel = self.builder.get_object('accounts_authlevel') self.accounts_liststore = gtk.ListStore(str, str, str, int) self.accounts_liststore.set_sort_column_id(ACCOUNTS_USERNAME, gtk.SORT_ASCENDING) - self.accounts_listview = self.builder.get_object("accounts_listview") + self.accounts_listview = self.builder.get_object('accounts_listview') self.accounts_listview.append_column( - gtk.TreeViewColumn(_("Username"), gtk.CellRendererText(), text=ACCOUNTS_USERNAME)) + gtk.TreeViewColumn(_('Username'), gtk.CellRendererText(), text=ACCOUNTS_USERNAME)) self.accounts_listview.append_column( - gtk.TreeViewColumn(_("Level"), gtk.CellRendererText(), text=ACCOUNTS_LEVEL)) + gtk.TreeViewColumn(_('Level'), gtk.CellRendererText(), text=ACCOUNTS_LEVEL)) password_column = gtk.TreeViewColumn('password', gtk.CellRendererText(), text=ACCOUNTS_PASSWORD) self.accounts_listview.append_column(password_column) password_column.set_visible(False) self.accounts_listview.set_model(self.accounts_liststore) - self.accounts_listview.get_selection().connect("changed", self._on_accounts_selection_changed) - self.accounts_frame = self.builder.get_object("AccountsFrame") + self.accounts_listview.get_selection().connect('changed', self._on_accounts_selection_changed) + self.accounts_frame = self.builder.get_object('AccountsFrame') # Setup plugin tab listview # The third entry is for holding translated plugin names self.plugin_liststore = gtk.ListStore(str, bool, str) self.plugin_liststore.set_sort_column_id(0, gtk.SORT_ASCENDING) - self.plugin_listview = self.builder.get_object("plugin_listview") + self.plugin_listview = self.builder.get_object('plugin_listview') self.plugin_listview.set_model(self.plugin_liststore) render = gtk.CellRendererToggle() - render.connect("toggled", self.on_plugin_toggled) - render.set_property("activatable", True) - self.plugin_listview.append_column(gtk.TreeViewColumn(_("Enabled"), render, active=1)) - self.plugin_listview.append_column(gtk.TreeViewColumn(_("Plugin"), gtk.CellRendererText(), text=2)) + render.connect('toggled', self.on_plugin_toggled) + render.set_property('activatable', True) + self.plugin_listview.append_column(gtk.TreeViewColumn(_('Enabled'), render, active=1)) + self.plugin_listview.append_column(gtk.TreeViewColumn(_('Plugin'), gtk.CellRendererText(), text=2)) # Connect to the 'changed' event of TreeViewSelection to get selection # changes. - self.treeview.get_selection().connect("changed", self.on_selection_changed) + self.treeview.get_selection().connect('changed', self.on_selection_changed) - self.plugin_listview.get_selection().connect("changed", self.on_plugin_selection_changed) + self.plugin_listview.get_selection().connect('changed', self.on_plugin_selection_changed) self.builder.connect_signals({ - "on_pref_dialog_delete_event": self.on_pref_dialog_delete_event, - "on_button_ok_clicked": self.on_button_ok_clicked, - "on_button_apply_clicked": self.on_button_apply_clicked, - "on_button_cancel_clicked": self.on_button_cancel_clicked, - "on_toggle": self.on_toggle, - "on_test_port_clicked": self.on_test_port_clicked, - "on_button_plugin_install_clicked": self._on_button_plugin_install_clicked, - "on_button_rescan_plugins_clicked": self._on_button_rescan_plugins_clicked, - "on_button_find_plugins_clicked": self._on_button_find_plugins_clicked, - "on_button_cache_refresh_clicked": self._on_button_cache_refresh_clicked, - "on_combo_encryption_changed": self._on_combo_encryption_changed, - "on_combo_proxy_type_changed": self._on_combo_proxy_type_changed, - "on_button_associate_magnet_clicked": self._on_button_associate_magnet_clicked, - "on_accounts_add_clicked": self._on_accounts_add_clicked, - "on_accounts_delete_clicked": self._on_accounts_delete_clicked, - "on_accounts_edit_clicked": self._on_accounts_edit_clicked, - "on_piecesbar_toggle_toggled": self._on_piecesbar_toggle_toggled, - "on_completed_color_set": self._on_completed_color_set, - "on_revert_color_completed_clicked": self._on_revert_color_completed_clicked, - "on_downloading_color_set": self._on_downloading_color_set, - "on_revert_color_downloading_clicked": self._on_revert_color_downloading_clicked, - "on_waiting_color_set": self._on_waiting_color_set, - "on_revert_color_waiting_clicked": self._on_revert_color_waiting_clicked, - "on_missing_color_set": self._on_missing_color_set, - "on_revert_color_missing_clicked": self._on_revert_color_missing_clicked, - "on_pref_dialog_configure_event": self.on_pref_dialog_configure_event, - "on_checkbutton_language_toggled": self._on_checkbutton_language_toggled, + 'on_pref_dialog_delete_event': self.on_pref_dialog_delete_event, + 'on_button_ok_clicked': self.on_button_ok_clicked, + 'on_button_apply_clicked': self.on_button_apply_clicked, + 'on_button_cancel_clicked': self.on_button_cancel_clicked, + 'on_toggle': self.on_toggle, + 'on_test_port_clicked': self.on_test_port_clicked, + 'on_button_plugin_install_clicked': self._on_button_plugin_install_clicked, + 'on_button_rescan_plugins_clicked': self._on_button_rescan_plugins_clicked, + 'on_button_find_plugins_clicked': self._on_button_find_plugins_clicked, + 'on_button_cache_refresh_clicked': self._on_button_cache_refresh_clicked, + 'on_combo_encryption_changed': self._on_combo_encryption_changed, + 'on_combo_proxy_type_changed': self._on_combo_proxy_type_changed, + 'on_button_associate_magnet_clicked': self._on_button_associate_magnet_clicked, + 'on_accounts_add_clicked': self._on_accounts_add_clicked, + 'on_accounts_delete_clicked': self._on_accounts_delete_clicked, + 'on_accounts_edit_clicked': self._on_accounts_edit_clicked, + 'on_piecesbar_toggle_toggled': self._on_piecesbar_toggle_toggled, + 'on_completed_color_set': self._on_completed_color_set, + 'on_revert_color_completed_clicked': self._on_revert_color_completed_clicked, + 'on_downloading_color_set': self._on_downloading_color_set, + 'on_revert_color_downloading_clicked': self._on_revert_color_downloading_clicked, + 'on_waiting_color_set': self._on_waiting_color_set, + 'on_revert_color_waiting_clicked': self._on_revert_color_waiting_clicked, + 'on_missing_color_set': self._on_missing_color_set, + 'on_revert_color_missing_clicked': self._on_revert_color_missing_clicked, + 'on_pref_dialog_configure_event': self.on_pref_dialog_configure_event, + 'on_checkbutton_language_toggled': self._on_checkbutton_language_toggled, }) if not deluge.common.osx_check() and not deluge.common.windows_check(): @@ -154,12 +154,12 @@ class Preferences(component.Component): except ImportError: pass else: - self.builder.get_object("alignment_tray_type").set_visible(True) + self.builder.get_object('alignment_tray_type').set_visible(True) from deluge.ui.gtkui.gtkui import DEFAULT_PREFS self.COLOR_DEFAULTS = {} - for key in ("missing", "waiting", "downloading", "completed"): - self.COLOR_DEFAULTS[key] = DEFAULT_PREFS["pieces_color_%s" % key][:] + for key in ('missing', 'waiting', 'downloading', 'completed'): + self.COLOR_DEFAULTS[key] = DEFAULT_PREFS['pieces_color_%s' % key][:] del DEFAULT_PREFS # These get updated by requests done to the core @@ -170,34 +170,34 @@ class Preferences(component.Component): self.load_languages() def setup_path_choosers(self): - self.download_location_hbox = self.builder.get_object("hbox_download_to_path_chooser") - self.download_location_path_chooser = PathChooser("download_location_paths_list") + self.download_location_hbox = self.builder.get_object('hbox_download_to_path_chooser') + self.download_location_path_chooser = PathChooser('download_location_paths_list') self.download_location_hbox.add(self.download_location_path_chooser) self.download_location_hbox.show_all() - self.move_completed_hbox = self.builder.get_object("hbox_move_completed_to_path_chooser") - self.move_completed_path_chooser = PathChooser("move_completed_paths_list") + self.move_completed_hbox = self.builder.get_object('hbox_move_completed_to_path_chooser') + self.move_completed_path_chooser = PathChooser('move_completed_paths_list') self.move_completed_hbox.add(self.move_completed_path_chooser) self.move_completed_hbox.show_all() - self.copy_torrents_to_hbox = self.builder.get_object("hbox_copy_torrent_files_path_chooser") - self.copy_torrent_files_path_chooser = PathChooser("copy_torrent_files_to_paths_list") + self.copy_torrents_to_hbox = self.builder.get_object('hbox_copy_torrent_files_path_chooser') + self.copy_torrent_files_path_chooser = PathChooser('copy_torrent_files_to_paths_list') self.copy_torrents_to_hbox.add(self.copy_torrent_files_path_chooser) self.copy_torrents_to_hbox.show_all() def load_languages(self): - self.language_combo = self.builder.get_object("combobox_language") - self.language_checkbox = self.builder.get_object("checkbutton_language") + self.language_combo = self.builder.get_object('combobox_language') + self.language_checkbox = self.builder.get_object('checkbutton_language') lang_model = self.language_combo.get_model() langs = lang.get_languages() index = -1 for i, l in enumerate(langs): lang_code, name = l lang_model.append([lang_code, name]) - if self.gtkui_config["language"] == lang_code: + if self.gtkui_config['language'] == lang_code: index = i - if self.gtkui_config["language"] is None: + if self.gtkui_config['language'] is None: self.language_checkbox.set_active(True) self.language_combo.set_visible(False) else: @@ -217,7 +217,7 @@ class Preferences(component.Component): vbox = gtk.VBox() label = gtk.Label() label.set_use_markup(True) - label.set_markup("<b><i><big>" + name + "</big></i></b>") + label.set_markup('<b><i><big>' + name + '</big></i></b>') label.set_alignment(0.00, 0.50) label.set_padding(10, 10) vbox.pack_start(label, False, True, 0) @@ -274,7 +274,7 @@ class Preferences(component.Component): self.treeview.get_selection().select_path(index) break - component.get("PluginManager").run_on_show_prefs() + component.get('PluginManager').run_on_show_prefs() # Update the preferences dialog to reflect current config settings self.core_config = {} @@ -318,84 +318,84 @@ class Preferences(component.Component): def _show(self): self.is_connected = self.core_config != {} and self.core_config is not None core_widgets = { - "chk_move_completed": ("active", "move_completed"), - "chk_copy_torrent_file": ("active", "copy_torrent_file"), - "chk_del_copy_torrent_file": ("active", "del_copy_torrent_file"), - "chk_pre_allocation": ("active", "pre_allocate_storage"), - "chk_prioritize_first_last_pieces": ("active", "prioritize_first_last_pieces"), - "chk_sequential_download": ("active", "sequential_download"), - "chk_add_paused": ("active", "add_paused"), - "active_port_label": ("text", lambda: str(self.active_port)), - "spin_incoming_port": ("value", lambda: self.core_config["listen_ports"][0]), - "chk_random_incoming_port": ("active", "random_port"), - "spin_outgoing_port_min": ("value", lambda: self.core_config["outgoing_ports"][0]), - "spin_outgoing_port_max": ("value", lambda: self.core_config["outgoing_ports"][1]), - "chk_random_outgoing_ports": ("active", "random_outgoing_ports"), - "entry_interface": ("text", "listen_interface"), - "entry_peer_tos": ("text", "peer_tos"), - "chk_dht": ("active", "dht"), - "chk_upnp": ("active", "upnp"), - "chk_natpmp": ("active", "natpmp"), - "chk_utpex": ("active", "utpex"), - "chk_lsd": ("active", "lsd"), - "chk_new_releases": ("active", "new_release_check"), - "chk_send_info": ("active", "send_info"), - "entry_geoip": ("text", "geoip_db_location"), - "combo_encin": ("active", "enc_in_policy"), - "combo_encout": ("active", "enc_out_policy"), - "combo_enclevel": ("active", "enc_level"), - "spin_max_connections_global": ("value", "max_connections_global"), - "spin_max_download": ("value", "max_download_speed"), - "spin_max_upload": ("value", "max_upload_speed"), - "spin_max_upload_slots_global": ("value", "max_upload_slots_global"), - "spin_max_half_open_connections": ("value", "max_connections_per_second"), - "spin_max_connections_per_second": ("value", "max_connections_per_second"), - "chk_ignore_limits_on_local_network": ("active", "ignore_limits_on_local_network"), - "chk_rate_limit_ip_overhead": ("active", "rate_limit_ip_overhead"), - "chk_anonymous_mode": ("active", "anonymous_mode"), - "spin_max_connections_per_torrent": ("value", "max_connections_per_torrent"), - "spin_max_upload_slots_per_torrent": ("value", "max_upload_slots_per_torrent"), - "spin_max_download_per_torrent": ("value", "max_download_speed_per_torrent"), - "spin_max_upload_per_torrent": ("value", "max_upload_speed_per_torrent"), - "spin_daemon_port": ("value", "daemon_port"), - "chk_allow_remote_connections": ("active", "allow_remote"), - "spin_active": ("value", "max_active_limit"), - "spin_seeding": ("value", "max_active_seeding"), - "spin_downloading": ("value", "max_active_downloading"), - "chk_dont_count_slow_torrents": ("active", "dont_count_slow_torrents"), - "chk_auto_manage_prefer_seeds": ("active", "auto_manage_prefer_seeds"), - "chk_queue_new_top": ("active", "queue_new_to_top"), - "spin_share_ratio_limit": ("value", "share_ratio_limit"), - "spin_seed_time_ratio_limit": ("value", "seed_time_ratio_limit"), - "spin_seed_time_limit": ("value", "seed_time_limit"), - "chk_share_ratio": ("active", "stop_seed_at_ratio"), - "spin_share_ratio": ("value", "stop_seed_ratio"), - "radio_pause_ratio": ("active", "stop_seed_at_ratio"), - "radio_remove_ratio": ("active", "remove_seed_at_ratio"), - "spin_cache_size": ("value", "cache_size"), - "spin_cache_expiry": ("value", "cache_expiry"), - "combo_proxy_type": ("active", lambda: self.core_config["proxy"]["type"]), - "entry_proxy_user": ("text", lambda: self.core_config["proxy"]["username"]), - "entry_proxy_pass": ("text", lambda: self.core_config["proxy"]["password"]), - "entry_proxy_host": ("text", lambda: self.core_config["proxy"]["hostname"]), - "spin_proxy_port": ("value", lambda: self.core_config["proxy"]["port"]), - "chk_proxy_host_resolve": ("active", lambda: self.core_config["proxy"]["proxy_hostnames"]), - "chk_proxy_peer_conn": ("active", lambda: self.core_config["proxy"]["proxy_peer_connections"]), - "entry_i2p_host": ("text", lambda: self.core_config["i2p_proxy"]["hostname"]), - "spin_i2p_port": ("value", lambda: self.core_config["i2p_proxy"]["port"]), - "accounts_add": (None, None), - "accounts_listview": (None, None), - "button_cache_refresh": (None, None), - "button_plugin_install": (None, None), - "button_rescan_plugins": (None, None), - "button_find_plugins": (None, None), - "button_testport": (None, None), - "plugin_listview": (None, None), + 'chk_move_completed': ('active', 'move_completed'), + 'chk_copy_torrent_file': ('active', 'copy_torrent_file'), + 'chk_del_copy_torrent_file': ('active', 'del_copy_torrent_file'), + 'chk_pre_allocation': ('active', 'pre_allocate_storage'), + 'chk_prioritize_first_last_pieces': ('active', 'prioritize_first_last_pieces'), + 'chk_sequential_download': ('active', 'sequential_download'), + 'chk_add_paused': ('active', 'add_paused'), + 'active_port_label': ('text', lambda: str(self.active_port)), + 'spin_incoming_port': ('value', lambda: self.core_config['listen_ports'][0]), + 'chk_random_incoming_port': ('active', 'random_port'), + 'spin_outgoing_port_min': ('value', lambda: self.core_config['outgoing_ports'][0]), + 'spin_outgoing_port_max': ('value', lambda: self.core_config['outgoing_ports'][1]), + 'chk_random_outgoing_ports': ('active', 'random_outgoing_ports'), + 'entry_interface': ('text', 'listen_interface'), + 'entry_peer_tos': ('text', 'peer_tos'), + 'chk_dht': ('active', 'dht'), + 'chk_upnp': ('active', 'upnp'), + 'chk_natpmp': ('active', 'natpmp'), + 'chk_utpex': ('active', 'utpex'), + 'chk_lsd': ('active', 'lsd'), + 'chk_new_releases': ('active', 'new_release_check'), + 'chk_send_info': ('active', 'send_info'), + 'entry_geoip': ('text', 'geoip_db_location'), + 'combo_encin': ('active', 'enc_in_policy'), + 'combo_encout': ('active', 'enc_out_policy'), + 'combo_enclevel': ('active', 'enc_level'), + 'spin_max_connections_global': ('value', 'max_connections_global'), + 'spin_max_download': ('value', 'max_download_speed'), + 'spin_max_upload': ('value', 'max_upload_speed'), + 'spin_max_upload_slots_global': ('value', 'max_upload_slots_global'), + 'spin_max_half_open_connections': ('value', 'max_connections_per_second'), + 'spin_max_connections_per_second': ('value', 'max_connections_per_second'), + 'chk_ignore_limits_on_local_network': ('active', 'ignore_limits_on_local_network'), + 'chk_rate_limit_ip_overhead': ('active', 'rate_limit_ip_overhead'), + 'chk_anonymous_mode': ('active', 'anonymous_mode'), + 'spin_max_connections_per_torrent': ('value', 'max_connections_per_torrent'), + 'spin_max_upload_slots_per_torrent': ('value', 'max_upload_slots_per_torrent'), + 'spin_max_download_per_torrent': ('value', 'max_download_speed_per_torrent'), + 'spin_max_upload_per_torrent': ('value', 'max_upload_speed_per_torrent'), + 'spin_daemon_port': ('value', 'daemon_port'), + 'chk_allow_remote_connections': ('active', 'allow_remote'), + 'spin_active': ('value', 'max_active_limit'), + 'spin_seeding': ('value', 'max_active_seeding'), + 'spin_downloading': ('value', 'max_active_downloading'), + 'chk_dont_count_slow_torrents': ('active', 'dont_count_slow_torrents'), + 'chk_auto_manage_prefer_seeds': ('active', 'auto_manage_prefer_seeds'), + 'chk_queue_new_top': ('active', 'queue_new_to_top'), + 'spin_share_ratio_limit': ('value', 'share_ratio_limit'), + 'spin_seed_time_ratio_limit': ('value', 'seed_time_ratio_limit'), + 'spin_seed_time_limit': ('value', 'seed_time_limit'), + 'chk_share_ratio': ('active', 'stop_seed_at_ratio'), + 'spin_share_ratio': ('value', 'stop_seed_ratio'), + 'radio_pause_ratio': ('active', 'stop_seed_at_ratio'), + 'radio_remove_ratio': ('active', 'remove_seed_at_ratio'), + 'spin_cache_size': ('value', 'cache_size'), + 'spin_cache_expiry': ('value', 'cache_expiry'), + 'combo_proxy_type': ('active', lambda: self.core_config['proxy']['type']), + 'entry_proxy_user': ('text', lambda: self.core_config['proxy']['username']), + 'entry_proxy_pass': ('text', lambda: self.core_config['proxy']['password']), + 'entry_proxy_host': ('text', lambda: self.core_config['proxy']['hostname']), + 'spin_proxy_port': ('value', lambda: self.core_config['proxy']['port']), + 'chk_proxy_host_resolve': ('active', lambda: self.core_config['proxy']['proxy_hostnames']), + 'chk_proxy_peer_conn': ('active', lambda: self.core_config['proxy']['proxy_peer_connections']), + 'entry_i2p_host': ('text', lambda: self.core_config['i2p_proxy']['hostname']), + 'spin_i2p_port': ('value', lambda: self.core_config['i2p_proxy']['port']), + 'accounts_add': (None, None), + 'accounts_listview': (None, None), + 'button_cache_refresh': (None, None), + 'button_plugin_install': (None, None), + 'button_rescan_plugins': (None, None), + 'button_find_plugins': (None, None), + 'button_testport': (None, None), + 'plugin_listview': (None, None), } - core_widgets[self.download_location_path_chooser] = ("path_chooser", "download_location") - core_widgets[self.move_completed_path_chooser] = ("path_chooser", "move_completed_path") - core_widgets[self.copy_torrent_files_path_chooser] = ("path_chooser", "torrentfiles_location") + core_widgets[self.download_location_path_chooser] = ('path_chooser', 'download_location') + core_widgets[self.move_completed_path_chooser] = ('path_chooser', 'move_completed_path') + core_widgets[self.copy_torrent_files_path_chooser] = ('path_chooser', 'torrentfiles_location') # Update the widgets accordingly for key in core_widgets: @@ -415,19 +415,19 @@ class Preferences(component.Component): elif isinstance(value, str): value = self.core_config[value] elif modifier: - value = {"active": False, "not_active": False, "value": 0, "text": "", "path_chooser": ""}[modifier] + value = {'active': False, 'not_active': False, 'value': 0, 'text': '', 'path_chooser': ''}[modifier] - if modifier == "active": + if modifier == 'active': widget.set_active(value) - elif modifier == "not_active": + elif modifier == 'not_active': widget.set_active(not value) - elif modifier == "value": + elif modifier == 'value': widget.set_value(float(value)) - elif modifier == "text": + elif modifier == 'text': if value is None: - value = "" + value = '' widget.set_text(value) - elif modifier == "path_chooser": + elif modifier == 'path_chooser': widget.set_text(value, cursor_end=False, default_text=True) if self.is_connected: @@ -440,28 +440,28 @@ class Preferences(component.Component): self.on_toggle(widget) # Downloads tab # - self.builder.get_object("chk_show_dialog").set_active(self.gtkui_config["interactive_add"]) - self.builder.get_object("chk_focus_dialog").set_active(self.gtkui_config["focus_add_dialog"]) + self.builder.get_object('chk_show_dialog').set_active(self.gtkui_config['interactive_add']) + self.builder.get_object('chk_focus_dialog').set_active(self.gtkui_config['focus_add_dialog']) # Interface tab # - self.builder.get_object("chk_use_tray").set_active(self.gtkui_config["enable_system_tray"]) - self.builder.get_object("chk_min_on_close").set_active(self.gtkui_config["close_to_tray"]) - self.builder.get_object("chk_start_in_tray").set_active(self.gtkui_config["start_in_tray"]) - self.builder.get_object("radio_appind").set_active(self.gtkui_config["enable_appindicator"]) - self.builder.get_object("chk_lock_tray").set_active(self.gtkui_config["lock_tray"]) - self.builder.get_object("radio_standalone").set_active(self.gtkui_config["standalone"]) - self.builder.get_object("radio_thinclient").set_active(not self.gtkui_config["standalone"]) - self.builder.get_object("chk_show_rate_in_title").set_active(self.gtkui_config["show_rate_in_title"]) - self.builder.get_object("chk_focus_main_window_on_add").set_active( - self.gtkui_config["focus_main_window_on_add"]) - self.builder.get_object("piecesbar_toggle").set_active(self.gtkui_config["show_piecesbar"]) - self.__set_color("completed", from_config=True) - self.__set_color("downloading", from_config=True) - self.__set_color("waiting", from_config=True) - self.__set_color("missing", from_config=True) + self.builder.get_object('chk_use_tray').set_active(self.gtkui_config['enable_system_tray']) + self.builder.get_object('chk_min_on_close').set_active(self.gtkui_config['close_to_tray']) + self.builder.get_object('chk_start_in_tray').set_active(self.gtkui_config['start_in_tray']) + self.builder.get_object('radio_appind').set_active(self.gtkui_config['enable_appindicator']) + self.builder.get_object('chk_lock_tray').set_active(self.gtkui_config['lock_tray']) + self.builder.get_object('radio_standalone').set_active(self.gtkui_config['standalone']) + self.builder.get_object('radio_thinclient').set_active(not self.gtkui_config['standalone']) + self.builder.get_object('chk_show_rate_in_title').set_active(self.gtkui_config['show_rate_in_title']) + self.builder.get_object('chk_focus_main_window_on_add').set_active( + self.gtkui_config['focus_main_window_on_add']) + self.builder.get_object('piecesbar_toggle').set_active(self.gtkui_config['show_piecesbar']) + self.__set_color('completed', from_config=True) + self.__set_color('downloading', from_config=True) + self.__set_color('waiting', from_config=True) + self.__set_color('missing', from_config=True) # Other tab # - self.builder.get_object("chk_show_new_releases").set_active(self.gtkui_config["show_new_releases"]) + self.builder.get_object('chk_show_new_releases').set_active(self.gtkui_config['show_new_releases']) # Cache tab # if client.connected(): @@ -495,175 +495,175 @@ class Preferences(component.Component): new_gtkui_config = {} # Downloads tab # - new_gtkui_config["interactive_add"] = self.builder.get_object("chk_show_dialog").get_active() - new_gtkui_config["focus_add_dialog"] = self.builder.get_object("chk_focus_dialog").get_active() + new_gtkui_config['interactive_add'] = self.builder.get_object('chk_show_dialog').get_active() + new_gtkui_config['focus_add_dialog'] = self.builder.get_object('chk_focus_dialog').get_active() - for state in ("missing", "waiting", "downloading", "completed"): - color = self.builder.get_object("%s_color" % state).get_color() - new_gtkui_config["pieces_color_%s" % state] = [ + for state in ('missing', 'waiting', 'downloading', 'completed'): + color = self.builder.get_object('%s_color' % state).get_color() + new_gtkui_config['pieces_color_%s' % state] = [ color.red, color.green, color.blue ] - new_core_config["copy_torrent_file"] = self.builder.get_object( - "chk_copy_torrent_file").get_active() - new_core_config["del_copy_torrent_file"] = self.builder.get_object( - "chk_del_copy_torrent_file").get_active() - new_core_config["move_completed"] = self.builder.get_object("chk_move_completed").get_active() - - new_core_config["download_location"] = self.download_location_path_chooser.get_text() - new_core_config["move_completed_path"] = self.move_completed_path_chooser.get_text() - new_core_config["torrentfiles_location"] = self.copy_torrent_files_path_chooser.get_text() - new_core_config["prioritize_first_last_pieces"] = self.builder.get_object( - "chk_prioritize_first_last_pieces").get_active() - new_core_config["sequential_download"] = self.builder.get_object( - "chk_sequential_download").get_active() - new_core_config["add_paused"] = self.builder.get_object("chk_add_paused").get_active() - new_core_config["pre_allocate_storage"] = self.builder.get_object( - "chk_pre_allocation").get_active() + new_core_config['copy_torrent_file'] = self.builder.get_object( + 'chk_copy_torrent_file').get_active() + new_core_config['del_copy_torrent_file'] = self.builder.get_object( + 'chk_del_copy_torrent_file').get_active() + new_core_config['move_completed'] = self.builder.get_object('chk_move_completed').get_active() + + new_core_config['download_location'] = self.download_location_path_chooser.get_text() + new_core_config['move_completed_path'] = self.move_completed_path_chooser.get_text() + new_core_config['torrentfiles_location'] = self.copy_torrent_files_path_chooser.get_text() + new_core_config['prioritize_first_last_pieces'] = self.builder.get_object( + 'chk_prioritize_first_last_pieces').get_active() + new_core_config['sequential_download'] = self.builder.get_object( + 'chk_sequential_download').get_active() + new_core_config['add_paused'] = self.builder.get_object('chk_add_paused').get_active() + new_core_config['pre_allocate_storage'] = self.builder.get_object( + 'chk_pre_allocation').get_active() # Network tab # - listen_ports = [self.builder.get_object("spin_incoming_port").get_value_as_int()] * 2 - new_core_config["listen_ports"] = listen_ports - new_core_config["random_port"] = self.builder.get_object("chk_random_incoming_port").get_active() + listen_ports = [self.builder.get_object('spin_incoming_port').get_value_as_int()] * 2 + new_core_config['listen_ports'] = listen_ports + new_core_config['random_port'] = self.builder.get_object('chk_random_incoming_port').get_active() outgoing_ports = ( - self.builder.get_object("spin_outgoing_port_min").get_value_as_int(), - self.builder.get_object("spin_outgoing_port_max").get_value_as_int() + self.builder.get_object('spin_outgoing_port_min').get_value_as_int(), + self.builder.get_object('spin_outgoing_port_max').get_value_as_int() ) - new_core_config["outgoing_ports"] = outgoing_ports - new_core_config["random_outgoing_ports"] = self.builder.get_object( - "chk_random_outgoing_ports").get_active() - incoming_address = self.builder.get_object("entry_interface").get_text().strip() + new_core_config['outgoing_ports'] = outgoing_ports + new_core_config['random_outgoing_ports'] = self.builder.get_object( + 'chk_random_outgoing_ports').get_active() + incoming_address = self.builder.get_object('entry_interface').get_text().strip() if deluge.common.is_ip(incoming_address) or not incoming_address: - new_core_config["listen_interface"] = incoming_address - new_core_config["peer_tos"] = self.builder.get_object("entry_peer_tos").get_text() - new_core_config["dht"] = self.builder.get_object("chk_dht").get_active() - new_core_config["upnp"] = self.builder.get_object("chk_upnp").get_active() - new_core_config["natpmp"] = self.builder.get_object("chk_natpmp").get_active() - new_core_config["utpex"] = self.builder.get_object("chk_utpex").get_active() - new_core_config["lsd"] = self.builder.get_object("chk_lsd").get_active() - new_core_config["enc_in_policy"] = self.builder.get_object("combo_encin").get_active() - new_core_config["enc_out_policy"] = self.builder.get_object("combo_encout").get_active() - new_core_config["enc_level"] = self.builder.get_object("combo_enclevel").get_active() + new_core_config['listen_interface'] = incoming_address + new_core_config['peer_tos'] = self.builder.get_object('entry_peer_tos').get_text() + new_core_config['dht'] = self.builder.get_object('chk_dht').get_active() + new_core_config['upnp'] = self.builder.get_object('chk_upnp').get_active() + new_core_config['natpmp'] = self.builder.get_object('chk_natpmp').get_active() + new_core_config['utpex'] = self.builder.get_object('chk_utpex').get_active() + new_core_config['lsd'] = self.builder.get_object('chk_lsd').get_active() + new_core_config['enc_in_policy'] = self.builder.get_object('combo_encin').get_active() + new_core_config['enc_out_policy'] = self.builder.get_object('combo_encout').get_active() + new_core_config['enc_level'] = self.builder.get_object('combo_enclevel').get_active() # Bandwidth tab # - new_core_config["max_connections_global"] = self.builder.get_object( - "spin_max_connections_global").get_value_as_int() - new_core_config["max_download_speed"] = self.builder.get_object("spin_max_download").get_value() - new_core_config["max_upload_speed"] = self.builder.get_object("spin_max_upload").get_value() - new_core_config["max_upload_slots_global"] = self.builder.get_object( - "spin_max_upload_slots_global").get_value_as_int() - new_core_config["max_half_open_connections"] = self.builder.get_object( - "spin_max_half_open_connections").get_value_as_int() - new_core_config["max_connections_per_second"] = self.builder.get_object( - "spin_max_connections_per_second").get_value_as_int() - new_core_config["max_connections_per_torrent"] = self.builder.get_object( - "spin_max_connections_per_torrent").get_value_as_int() - new_core_config["max_upload_slots_per_torrent"] = self.builder.get_object( - "spin_max_upload_slots_per_torrent").get_value_as_int() - new_core_config["max_upload_speed_per_torrent"] = self.builder.get_object( - "spin_max_upload_per_torrent").get_value() - new_core_config["max_download_speed_per_torrent"] = self.builder.get_object( - "spin_max_download_per_torrent").get_value() - new_core_config["ignore_limits_on_local_network"] = self.builder.get_object( - "chk_ignore_limits_on_local_network").get_active() - new_core_config["rate_limit_ip_overhead"] = self.builder.get_object( - "chk_rate_limit_ip_overhead").get_active() + new_core_config['max_connections_global'] = self.builder.get_object( + 'spin_max_connections_global').get_value_as_int() + new_core_config['max_download_speed'] = self.builder.get_object('spin_max_download').get_value() + new_core_config['max_upload_speed'] = self.builder.get_object('spin_max_upload').get_value() + new_core_config['max_upload_slots_global'] = self.builder.get_object( + 'spin_max_upload_slots_global').get_value_as_int() + new_core_config['max_half_open_connections'] = self.builder.get_object( + 'spin_max_half_open_connections').get_value_as_int() + new_core_config['max_connections_per_second'] = self.builder.get_object( + 'spin_max_connections_per_second').get_value_as_int() + new_core_config['max_connections_per_torrent'] = self.builder.get_object( + 'spin_max_connections_per_torrent').get_value_as_int() + new_core_config['max_upload_slots_per_torrent'] = self.builder.get_object( + 'spin_max_upload_slots_per_torrent').get_value_as_int() + new_core_config['max_upload_speed_per_torrent'] = self.builder.get_object( + 'spin_max_upload_per_torrent').get_value() + new_core_config['max_download_speed_per_torrent'] = self.builder.get_object( + 'spin_max_download_per_torrent').get_value() + new_core_config['ignore_limits_on_local_network'] = self.builder.get_object( + 'chk_ignore_limits_on_local_network').get_active() + new_core_config['rate_limit_ip_overhead'] = self.builder.get_object( + 'chk_rate_limit_ip_overhead').get_active() # Interface tab # - new_gtkui_config["enable_system_tray"] = self.builder.get_object("chk_use_tray").get_active() - new_gtkui_config["close_to_tray"] = self.builder.get_object("chk_min_on_close").get_active() - new_gtkui_config["start_in_tray"] = self.builder.get_object("chk_start_in_tray").get_active() - new_gtkui_config["enable_appindicator"] = self.builder.get_object("radio_appind").get_active() - new_gtkui_config["lock_tray"] = self.builder.get_object("chk_lock_tray").get_active() - passhex = sha(self.builder.get_object("txt_tray_password").get_text()).hexdigest() - if passhex != "c07eb5a8c0dc7bb81c217b67f11c3b7a5e95ffd7": - new_gtkui_config["tray_password"] = passhex - - was_standalone = self.gtkui_config["standalone"] - new_gtkui_standalone = self.builder.get_object("radio_standalone").get_active() - new_gtkui_config["standalone"] = new_gtkui_standalone - - new_gtkui_config["show_rate_in_title"] = self.builder.get_object( - "chk_show_rate_in_title").get_active() - new_gtkui_config["focus_main_window_on_add"] = self.builder.get_object( - "chk_focus_main_window_on_add").get_active() + new_gtkui_config['enable_system_tray'] = self.builder.get_object('chk_use_tray').get_active() + new_gtkui_config['close_to_tray'] = self.builder.get_object('chk_min_on_close').get_active() + new_gtkui_config['start_in_tray'] = self.builder.get_object('chk_start_in_tray').get_active() + new_gtkui_config['enable_appindicator'] = self.builder.get_object('radio_appind').get_active() + new_gtkui_config['lock_tray'] = self.builder.get_object('chk_lock_tray').get_active() + passhex = sha(self.builder.get_object('txt_tray_password').get_text()).hexdigest() + if passhex != 'c07eb5a8c0dc7bb81c217b67f11c3b7a5e95ffd7': + new_gtkui_config['tray_password'] = passhex + + was_standalone = self.gtkui_config['standalone'] + new_gtkui_standalone = self.builder.get_object('radio_standalone').get_active() + new_gtkui_config['standalone'] = new_gtkui_standalone + + new_gtkui_config['show_rate_in_title'] = self.builder.get_object( + 'chk_show_rate_in_title').get_active() + new_gtkui_config['focus_main_window_on_add'] = self.builder.get_object( + 'chk_focus_main_window_on_add').get_active() # Other tab # - new_gtkui_config["show_new_releases"] = self.builder.get_object( - "chk_show_new_releases").get_active() - new_core_config["send_info"] = self.builder.get_object("chk_send_info").get_active() - new_core_config["geoip_db_location"] = self.builder.get_object("entry_geoip").get_text() + new_gtkui_config['show_new_releases'] = self.builder.get_object( + 'chk_show_new_releases').get_active() + new_core_config['send_info'] = self.builder.get_object('chk_send_info').get_active() + new_core_config['geoip_db_location'] = self.builder.get_object('entry_geoip').get_text() # Daemon tab # - new_core_config["daemon_port"] = self.builder.get_object("spin_daemon_port").get_value_as_int() - new_core_config["allow_remote"] = self.builder.get_object( - "chk_allow_remote_connections").get_active() - new_core_config["new_release_check"] = self.builder.get_object("chk_new_releases").get_active() + new_core_config['daemon_port'] = self.builder.get_object('spin_daemon_port').get_value_as_int() + new_core_config['allow_remote'] = self.builder.get_object( + 'chk_allow_remote_connections').get_active() + new_core_config['new_release_check'] = self.builder.get_object('chk_new_releases').get_active() # Proxy tab # - new_core_config["proxy"] = {} - new_core_config["proxy"]["type"] = self.builder.get_object("combo_proxy_type").get_active() - new_core_config["proxy"]["username"] = self.builder.get_object("entry_proxy_user").get_text() - new_core_config["proxy"]["password"] = self.builder.get_object("entry_proxy_pass").get_text() - new_core_config["proxy"]["hostname"] = self.builder.get_object("entry_proxy_host").get_text() - new_core_config["proxy"]["port"] = self.builder.get_object("spin_proxy_port").get_value_as_int() - new_core_config["proxy"]["proxy_hostnames"] = self.builder.get_object( - "chk_proxy_host_resolve").get_active() - new_core_config["proxy"]["proxy_peer_connections"] = self.builder.get_object( - "chk_proxy_peer_conn").get_active() - new_core_config["i2p_proxy"] = {} - new_core_config["i2p_proxy"]["hostname"] = self.builder.get_object("entry_i2p_host").get_text() - new_core_config["i2p_proxy"]["port"] = self.builder.get_object("spin_i2p_port").get_value_as_int() - new_core_config["anonymous_mode"] = self.builder.get_object("chk_anonymous_mode").get_active() + new_core_config['proxy'] = {} + new_core_config['proxy']['type'] = self.builder.get_object('combo_proxy_type').get_active() + new_core_config['proxy']['username'] = self.builder.get_object('entry_proxy_user').get_text() + new_core_config['proxy']['password'] = self.builder.get_object('entry_proxy_pass').get_text() + new_core_config['proxy']['hostname'] = self.builder.get_object('entry_proxy_host').get_text() + new_core_config['proxy']['port'] = self.builder.get_object('spin_proxy_port').get_value_as_int() + new_core_config['proxy']['proxy_hostnames'] = self.builder.get_object( + 'chk_proxy_host_resolve').get_active() + new_core_config['proxy']['proxy_peer_connections'] = self.builder.get_object( + 'chk_proxy_peer_conn').get_active() + new_core_config['i2p_proxy'] = {} + new_core_config['i2p_proxy']['hostname'] = self.builder.get_object('entry_i2p_host').get_text() + new_core_config['i2p_proxy']['port'] = self.builder.get_object('spin_i2p_port').get_value_as_int() + new_core_config['anonymous_mode'] = self.builder.get_object('chk_anonymous_mode').get_active() # Queue tab # - new_core_config["queue_new_to_top"] = self.builder.get_object("chk_queue_new_top").get_active() - new_core_config["max_active_seeding"] = self.builder.get_object( - "spin_seeding").get_value_as_int() - new_core_config["max_active_downloading"] = self.builder.get_object( - "spin_downloading").get_value_as_int() - new_core_config["max_active_limit"] = self.builder.get_object("spin_active").get_value_as_int() - new_core_config["dont_count_slow_torrents"] = self.builder.get_object( - "chk_dont_count_slow_torrents").get_active() - new_core_config["auto_manage_prefer_seeds"] = self.builder.get_object( - "chk_auto_manage_prefer_seeds").get_active() - new_core_config["stop_seed_at_ratio"] = self.builder.get_object("chk_share_ratio").get_active() - new_core_config["remove_seed_at_ratio"] = self.builder.get_object( - "radio_remove_ratio").get_active() - new_core_config["stop_seed_ratio"] = self.builder.get_object("spin_share_ratio").get_value() - new_core_config["share_ratio_limit"] = self.builder.get_object( - "spin_share_ratio_limit").get_value() - new_core_config["seed_time_ratio_limit"] = self.builder.get_object( - "spin_seed_time_ratio_limit").get_value() - new_core_config["seed_time_limit"] = self.builder.get_object("spin_seed_time_limit").get_value() + new_core_config['queue_new_to_top'] = self.builder.get_object('chk_queue_new_top').get_active() + new_core_config['max_active_seeding'] = self.builder.get_object( + 'spin_seeding').get_value_as_int() + new_core_config['max_active_downloading'] = self.builder.get_object( + 'spin_downloading').get_value_as_int() + new_core_config['max_active_limit'] = self.builder.get_object('spin_active').get_value_as_int() + new_core_config['dont_count_slow_torrents'] = self.builder.get_object( + 'chk_dont_count_slow_torrents').get_active() + new_core_config['auto_manage_prefer_seeds'] = self.builder.get_object( + 'chk_auto_manage_prefer_seeds').get_active() + new_core_config['stop_seed_at_ratio'] = self.builder.get_object('chk_share_ratio').get_active() + new_core_config['remove_seed_at_ratio'] = self.builder.get_object( + 'radio_remove_ratio').get_active() + new_core_config['stop_seed_ratio'] = self.builder.get_object('spin_share_ratio').get_value() + new_core_config['share_ratio_limit'] = self.builder.get_object( + 'spin_share_ratio_limit').get_value() + new_core_config['seed_time_ratio_limit'] = self.builder.get_object( + 'spin_seed_time_ratio_limit').get_value() + new_core_config['seed_time_limit'] = self.builder.get_object('spin_seed_time_limit').get_value() # Cache tab # - new_core_config["cache_size"] = self.builder.get_object("spin_cache_size").get_value_as_int() - new_core_config["cache_expiry"] = self.builder.get_object("spin_cache_expiry").get_value_as_int() + new_core_config['cache_size'] = self.builder.get_object('spin_cache_size').get_value_as_int() + new_core_config['cache_expiry'] = self.builder.get_object('spin_cache_expiry').get_value_as_int() # Run plugin hook to apply preferences - component.get("PluginManager").run_on_apply_prefs() + component.get('PluginManager').run_on_apply_prefs() # Lanuage if self.language_checkbox.get_active(): - new_gtkui_config["language"] = None + new_gtkui_config['language'] = None else: active = self.language_combo.get_active() if active == -1: dialog = InformationDialog( - _("Attention"), - _("You must choose a language") + _('Attention'), + _('You must choose a language') ) dialog.run() return else: model = self.language_combo.get_model() - new_gtkui_config["language"] = model.get(model.get_iter(active), 0)[0] + new_gtkui_config['language'] = model.get(model.get_iter(active), 0)[0] - if new_gtkui_config["language"] != self.gtkui_config["language"]: + if new_gtkui_config['language'] != self.gtkui_config['language']: dialog = InformationDialog( - _("Attention"), - _("You must now restart the deluge UI for the changes to take effect.") + _('Attention'), + _('You must now restart the deluge UI for the changes to take effect.') ) dialog.run() @@ -701,22 +701,22 @@ class Preferences(component.Component): shutdown_daemon = (not client.is_standalone() and client.connected() and client.is_localhost()) - component.get("MainWindow").quit(shutdown=shutdown_daemon) + component.get('MainWindow').quit(shutdown=shutdown_daemon) else: - self.gtkui_config["standalone"] = not new_gtkui_standalone - self.builder.get_object("radio_standalone").set_active( - self.gtkui_config["standalone"]) - self.builder.get_object("radio_thinclient").set_active( - not self.gtkui_config["standalone"]) + self.gtkui_config['standalone'] = not new_gtkui_standalone + self.builder.get_object('radio_standalone').set_active( + self.gtkui_config['standalone']) + self.builder.get_object('radio_thinclient').set_active( + not self.gtkui_config['standalone']) dialog = YesNoDialog( - _("Switching client mode..."), - _("Your current session will be stopped. Do you wish to continue?") + _('Switching client mode...'), + _('Your current session will be stopped. Do you wish to continue?') ) dialog.run().addCallback(on_response) def hide(self): self.window_open = False - self.builder.get_object("port_img").hide() + self.builder.get_object('port_img').hide() self.pref_dialog.hide() def __update_cache_status(self): @@ -725,10 +725,10 @@ class Preferences(component.Component): 'label_cache_blocks_read', 'label_cache_blocks_read_hit', 'label_cache_read_hit_ratio', 'label_cache_reads', 'label_cache_cache_size', 'label_cache_read_cache_size'): widget = self.builder.get_object(widget_name) - key = widget_name[len("label_cache_"):] + key = widget_name[len('label_cache_'):] value = self.cache_status[key] if isinstance(value, float): - value = "%.2f" % value + value = '%.2f' % value else: value = str(value) @@ -746,14 +746,14 @@ class Preferences(component.Component): return True def load_pref_dialog_state(self): - w = self.gtkui_config["pref_dialog_width"] - h = self.gtkui_config["pref_dialog_height"] + w = self.gtkui_config['pref_dialog_width'] + h = self.gtkui_config['pref_dialog_height'] if w is not None and h is not None: self.pref_dialog.resize(w, h) def on_pref_dialog_configure_event(self, widget, event): - self.gtkui_config["pref_dialog_width"] = event.width - self.gtkui_config["pref_dialog_height"] = event.height + self.gtkui_config['pref_dialog_width'] = event.width + self.gtkui_config['pref_dialog_height'] = event.height def on_toggle(self, widget): """Handles widget sensitivity based on radio/check button values.""" @@ -763,32 +763,32 @@ class Preferences(component.Component): return path_choosers = { - "download_location_path_chooser": self.download_location_path_chooser, - "move_completed_path_chooser": self.move_completed_path_chooser, - "torrentfiles_location_path_chooser": self.copy_torrent_files_path_chooser + 'download_location_path_chooser': self.download_location_path_chooser, + 'move_completed_path_chooser': self.move_completed_path_chooser, + 'torrentfiles_location_path_chooser': self.copy_torrent_files_path_chooser } dependents = { - "chk_show_dialog": {"chk_focus_dialog": True}, - "chk_random_incoming_port": {"spin_incoming_port": False}, - "chk_random_outgoing_ports": {"spin_outgoing_port_min": False, - "spin_outgoing_port_max": False}, - "chk_use_tray": {"radio_appind": True, - "radio_systray": True, - "chk_min_on_close": True, - "chk_start_in_tray": True, - "alignment_tray_type": True, - "chk_lock_tray": True}, - "chk_lock_tray": {"txt_tray_password": True, - "password_label": True}, - "radio_open_folder_custom": {"combo_file_manager": False, - "txt_open_folder_location": True}, - "chk_move_completed": {"move_completed_path_chooser": True}, - "chk_copy_torrent_file": {"torrentfiles_location_path_chooser": True, - "chk_del_copy_torrent_file": True}, - "chk_share_ratio": {"spin_share_ratio": True, - "radio_pause_ratio": True, - "radio_remove_ratio": True} + 'chk_show_dialog': {'chk_focus_dialog': True}, + 'chk_random_incoming_port': {'spin_incoming_port': False}, + 'chk_random_outgoing_ports': {'spin_outgoing_port_min': False, + 'spin_outgoing_port_max': False}, + 'chk_use_tray': {'radio_appind': True, + 'radio_systray': True, + 'chk_min_on_close': True, + 'chk_start_in_tray': True, + 'alignment_tray_type': True, + 'chk_lock_tray': True}, + 'chk_lock_tray': {'txt_tray_password': True, + 'password_label': True}, + 'radio_open_folder_custom': {'combo_file_manager': False, + 'txt_open_folder_location': True}, + 'chk_move_completed': {'move_completed_path_chooser': True}, + 'chk_copy_torrent_file': {'torrentfiles_location_path_chooser': True, + 'chk_del_copy_torrent_file': True}, + 'chk_share_ratio': {'spin_share_ratio': True, + 'radio_pause_ratio': True, + 'radio_remove_ratio': True} } def update_dependent_widgets(name, value): @@ -809,16 +809,16 @@ class Preferences(component.Component): update_dependent_widgets(key, value) def on_button_ok_clicked(self, data): - log.debug("on_button_ok_clicked") + log.debug('on_button_ok_clicked') self.set_config(hide=True) return True def on_button_apply_clicked(self, data): - log.debug("on_button_apply_clicked") + log.debug('on_button_apply_clicked') self.set_config() def on_button_cancel_clicked(self, data): - log.debug("on_button_cancel_clicked") + log.debug('on_button_cancel_clicked') self.hide() return True @@ -826,7 +826,7 @@ class Preferences(component.Component): # Show the correct notebook page based on what row is selected. (model, row) = treeselection.get_selected() try: - if model.get_value(row, 1) == _("Daemon"): + if model.get_value(row, 1) == _('Daemon'): # Let's see update the accounts related stuff if client.connected(): self._get_accounts_tab_data() @@ -835,27 +835,27 @@ class Preferences(component.Component): pass def on_test_port_clicked(self, data): - log.debug("on_test_port_clicked") + log.debug('on_test_port_clicked') def on_get_test(status): if status: - self.builder.get_object("port_img").set_from_stock(gtk.STOCK_YES, 4) - self.builder.get_object("port_img").show() + self.builder.get_object('port_img').set_from_stock(gtk.STOCK_YES, 4) + self.builder.get_object('port_img').show() else: - self.builder.get_object("port_img").set_from_stock(gtk.STOCK_DIALOG_WARNING, 4) - self.builder.get_object("port_img").show() + self.builder.get_object('port_img').set_from_stock(gtk.STOCK_DIALOG_WARNING, 4) + self.builder.get_object('port_img').show() client.core.test_listen_port().addCallback(on_get_test) # XXX: Consider using gtk.Spinner() instead of the loading gif # It requires gtk.ver > 2.12 - self.builder.get_object("port_img").set_from_file(deluge.common.get_pixmap('loading.gif')) - self.builder.get_object("port_img").show() + self.builder.get_object('port_img').set_from_file(deluge.common.get_pixmap('loading.gif')) + self.builder.get_object('port_img').show() client.force_call() def on_plugin_toggled(self, renderer, path): row = self.plugin_liststore.get_iter_from_string(path) name = self.plugin_liststore.get_value(row, 0) value = self.plugin_liststore.get_value(row, 1) - log.debug("on_plugin_toggled - %s: %s", name, value) + log.debug('on_plugin_toggled - %s: %s', name, value) self.plugin_liststore.set_value(row, 1, not value) if not value: d = client.core.enable_plugin(name) @@ -870,22 +870,22 @@ class Preferences(component.Component): d.addBoth(on_plugin_action) def on_plugin_selection_changed(self, treeselection): - log.debug("on_plugin_selection_changed") + log.debug('on_plugin_selection_changed') (model, itr) = treeselection.get_selected() if not itr: return name = model[itr][0] - plugin_info = component.get("PluginManager").get_plugin_info(name) - self.builder.get_object("label_plugin_author").set_text(plugin_info["Author"]) - self.builder.get_object("label_plugin_version").set_text(plugin_info["Version"]) - self.builder.get_object("label_plugin_email").set_text(plugin_info["Author-email"]) - self.builder.get_object("label_plugin_homepage").set_text(plugin_info["Home-page"]) - self.builder.get_object("label_plugin_details").set_text(plugin_info["Description"]) + plugin_info = component.get('PluginManager').get_plugin_info(name) + self.builder.get_object('label_plugin_author').set_text(plugin_info['Author']) + self.builder.get_object('label_plugin_version').set_text(plugin_info['Version']) + self.builder.get_object('label_plugin_email').set_text(plugin_info['Author-email']) + self.builder.get_object('label_plugin_homepage').set_text(plugin_info['Home-page']) + self.builder.get_object('label_plugin_details').set_text(plugin_info['Description']) def _on_button_plugin_install_clicked(self, widget): - log.debug("_on_button_plugin_install_clicked") + log.debug('_on_button_plugin_install_clicked') chooser = gtk.FileChooserDialog( - _("Select the Plugin"), + _('Select the Plugin'), self.pref_dialog, gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK) @@ -893,11 +893,11 @@ class Preferences(component.Component): chooser.set_transient_for(self.pref_dialog) chooser.set_select_multiple(False) - chooser.set_property("skip-taskbar-hint", True) + chooser.set_property('skip-taskbar-hint', True) file_filter = gtk.FileFilter() - file_filter.set_name(_("Plugin Eggs")) - file_filter.add_pattern("*." + "egg") + file_filter.set_name(_('Plugin Eggs')) + file_filter.add_pattern('*.' + 'egg') chooser.add_filter(file_filter) # Run the dialog @@ -914,13 +914,13 @@ class Preferences(component.Component): filename = os.path.split(filepath)[1] shutil.copyfile( filepath, - os.path.join(get_config_dir(), "plugins", filename)) + os.path.join(get_config_dir(), 'plugins', filename)) - component.get("PluginManager").scan_for_plugins() + component.get('PluginManager').scan_for_plugins() if not client.is_localhost(): # We need to send this plugin to the daemon - with open(filepath, "rb") as _file: + with open(filepath, 'rb') as _file: filedump = base64.encodestring(_file.read()) client.core.upload_plugin(filename, filedump) @@ -930,18 +930,18 @@ class Preferences(component.Component): self.show() def _on_button_rescan_plugins_clicked(self, widget): - component.get("PluginManager").scan_for_plugins() + component.get('PluginManager').scan_for_plugins() if client.connected(): client.core.rescan_plugins() self.show() def _on_button_find_plugins_clicked(self, widget): - deluge.common.open_url_in_browser("http://dev.deluge-torrent.org/wiki/Plugins") + deluge.common.open_url_in_browser('http://dev.deluge-torrent.org/wiki/Plugins') def _on_combo_encryption_changed(self, widget): - combo_encin = self.builder.get_object("combo_encin").get_active() - combo_encout = self.builder.get_object("combo_encout").get_active() - combo_enclevel = self.builder.get_object("combo_enclevel") + combo_encin = self.builder.get_object('combo_encin').get_active() + combo_encout = self.builder.get_object('combo_encout').get_active() + combo_enclevel = self.builder.get_object('combo_enclevel') # If incoming and outgoing both set to disabled, disable level combobox if combo_encin == 2 and combo_encout == 2: @@ -950,27 +950,27 @@ class Preferences(component.Component): combo_enclevel.set_sensitive(True) def _on_combo_proxy_type_changed(self, widget): - proxy_type = self.builder.get_object("combo_proxy_type").get_active() + proxy_type = self.builder.get_object('combo_proxy_type').get_active() hides = [] shows = [] # 0:"None" if proxy_type == 0: - hides.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port", - "label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port", - "chk_proxy_host_resolve", "chk_proxy_peer_conn"]) + hides.extend(['entry_proxy_pass', 'entry_proxy_user', 'entry_proxy_host', 'spin_proxy_port', + 'label_proxy_pass', 'label_proxy_user', 'label_proxy_host', 'label_proxy_port', + 'chk_proxy_host_resolve', 'chk_proxy_peer_conn']) # 1:"Socks4", 2:"Socks5", 4:"HTTP" elif proxy_type in (1, 2, 4): if proxy_type in (2, 4): - shows.extend(["chk_proxy_host_resolve"]) - hides.extend(["entry_proxy_pass", "entry_proxy_user", "label_proxy_pass", "label_proxy_user"]) - shows.extend(["entry_proxy_host", "spin_proxy_port", "label_proxy_host", - "label_proxy_port", "chk_proxy_peer_conn"]) + shows.extend(['chk_proxy_host_resolve']) + hides.extend(['entry_proxy_pass', 'entry_proxy_user', 'label_proxy_pass', 'label_proxy_user']) + shows.extend(['entry_proxy_host', 'spin_proxy_port', 'label_proxy_host', + 'label_proxy_port', 'chk_proxy_peer_conn']) # 3:"Socks5 Auth", 5:"HTTP Auth" elif proxy_type in (3, 5): - shows.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port", - "label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port", - "chk_proxy_host_resolve", "chk_proxy_peer_conn"]) + shows.extend(['entry_proxy_pass', 'entry_proxy_user', 'entry_proxy_host', 'spin_proxy_port', + 'label_proxy_pass', 'label_proxy_user', 'label_proxy_host', 'label_proxy_port', + 'chk_proxy_host_resolve', 'chk_proxy_peer_conn']) for hide_entry in hides: self.builder.get_object(hide_entry).hide() @@ -990,8 +990,8 @@ class Preferences(component.Component): self.accounts_frame.hide() else: ErrorDialog( - _("Server Side Error"), - _("An error ocurred on the server"), + _('Server Side Error'), + _('An error ocurred on the server'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() client.core.get_known_accounts().addCallback(on_ok).addErrback(on_fail) @@ -1005,7 +1005,7 @@ class Preferences(component.Component): value = '*' * len(value) account_to_log[key] = value known_accounts_to_log.append(account_to_log) - log.debug("_on_known_accounts: %s", known_accounts_to_log) + log.debug('_on_known_accounts: %s', known_accounts_to_log) self.accounts_liststore.clear() @@ -1016,17 +1016,17 @@ class Preferences(component.Component): self.accounts_liststore.set_value(accounts_iter, ACCOUNTS_PASSWORD, account['password']) def _on_accounts_selection_changed(self, treeselection): - log.debug("_on_accounts_selection_changed") + log.debug('_on_accounts_selection_changed') (model, itr) = treeselection.get_selected() if not itr: return username = model[itr][0] if username: - self.builder.get_object("accounts_edit").set_sensitive(True) - self.builder.get_object("accounts_delete").set_sensitive(True) + self.builder.get_object('accounts_edit').set_sensitive(True) + self.builder.get_object('accounts_delete').set_sensitive(True) else: - self.builder.get_object("accounts_edit").set_sensitive(False) - self.builder.get_object("accounts_delete").set_sensitive(False) + self.builder.get_object('accounts_edit').set_sensitive(False) + self.builder.get_object('accounts_delete').set_sensitive(False) def _on_accounts_add_clicked(self, widget): dialog = AccountDialog(levels_mapping=client.auth_levels_mapping, parent=self.pref_dialog) @@ -1045,14 +1045,14 @@ class Preferences(component.Component): def add_fail(failure): if failure.type == AuthManagerError: ErrorDialog( - _("Error Adding Account"), - _("Authentication failed"), + _('Error Adding Account'), + _('Authentication failed'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() else: ErrorDialog( - _("Error Adding Account"), - _("An error ocurred while adding account"), + _('Error Adding Account'), + _('An error ocurred while adding account'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() @@ -1084,8 +1084,8 @@ class Preferences(component.Component): def update_fail(failure): ErrorDialog( - _("Error Updating Account"), - _("An error ocurred while updating account"), + _('Error Updating Account'), + _('An error ocurred while updating account'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() @@ -1104,7 +1104,7 @@ class Preferences(component.Component): return username = model[itr][0] - header = _("Remove Account") + header = _('Remove Account') text = _("Are you sure you wan't do remove the account with the " "username \"%(username)s\"?" % dict(username=username)) dialog = YesNoDialog(header, text, parent=self.pref_dialog) @@ -1116,14 +1116,14 @@ class Preferences(component.Component): def remove_fail(failure): if failure.type == AuthManagerError: ErrorDialog( - _("Error Removing Account"), - _("Auhentication failed"), + _('Error Removing Account'), + _('Auhentication failed'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() else: ErrorDialog( - _("Error Removing Account"), - _("An error ocurred while removing account"), + _('Error Removing Account'), + _('An error ocurred while removing account'), parent=self.pref_dialog, details=failure.getErrorMessage() ).run() if response_id == gtk.RESPONSE_YES: @@ -1134,53 +1134,53 @@ class Preferences(component.Component): def _on_piecesbar_toggle_toggled(self, widget): self.gtkui_config['show_piecesbar'] = widget.get_active() - colors_widget = self.builder.get_object("piecebar_colors_expander") + colors_widget = self.builder.get_object('piecebar_colors_expander') colors_widget.set_visible(widget.get_active()) def _on_checkbutton_language_toggled(self, widget): self.language_combo.set_visible(not self.language_checkbox.get_active()) def _on_completed_color_set(self, widget): - self.__set_color("completed") + self.__set_color('completed') def _on_revert_color_completed_clicked(self, widget): - self.__revert_color("completed") + self.__revert_color('completed') def _on_downloading_color_set(self, widget): - self.__set_color("downloading") + self.__set_color('downloading') def _on_revert_color_downloading_clicked(self, widget): - self.__revert_color("downloading") + self.__revert_color('downloading') def _on_waiting_color_set(self, widget): - self.__set_color("waiting") + self.__set_color('waiting') def _on_revert_color_waiting_clicked(self, widget): - self.__revert_color("waiting") + self.__revert_color('waiting') def _on_missing_color_set(self, widget): - self.__set_color("missing") + self.__set_color('missing') def _on_revert_color_missing_clicked(self, widget): - self.__revert_color("missing") + self.__revert_color('missing') def __set_color(self, state, from_config=False): if from_config: - color = gtk.gdk.Color(*self.gtkui_config["pieces_color_%s" % state]) - log.debug("Setting %r color state from config to %s", state, (color.red, color.green, color.blue)) - self.builder.get_object("%s_color" % state).set_color(color) + color = gtk.gdk.Color(*self.gtkui_config['pieces_color_%s' % state]) + log.debug('Setting %r color state from config to %s', state, (color.red, color.green, color.blue)) + self.builder.get_object('%s_color' % state).set_color(color) else: - color = self.builder.get_object("%s_color" % state).get_color() - log.debug("Setting %r color state to %s", state, (color.red, color.green, color.blue)) - self.gtkui_config["pieces_color_%s" % state] = [color.red, color.green, color.blue] + color = self.builder.get_object('%s_color' % state).get_color() + log.debug('Setting %r color state to %s', state, (color.red, color.green, color.blue)) + self.gtkui_config['pieces_color_%s' % state] = [color.red, color.green, color.blue] self.gtkui_config.save() - self.gtkui_config.apply_set_functions("pieces_colors") + self.gtkui_config.apply_set_functions('pieces_colors') - self.builder.get_object("revert_color_%s" % state).set_sensitive( + self.builder.get_object('revert_color_%s' % state).set_sensitive( [color.red, color.green, color.blue] != self.COLOR_DEFAULTS[state]) def __revert_color(self, state, from_config=False): - log.debug("Reverting %r color state", state) - self.builder.get_object("%s_color" % state).set_color(gtk.gdk.Color(*self.COLOR_DEFAULTS[state])) - self.builder.get_object("revert_color_%s" % state).set_sensitive(False) - self.gtkui_config.apply_set_functions("pieces_colors") + log.debug('Reverting %r color state', state) + self.builder.get_object('%s_color' % state).set_color(gtk.gdk.Color(*self.COLOR_DEFAULTS[state])) + self.builder.get_object('revert_color_%s' % state).set_sensitive(False) + self.gtkui_config.apply_set_functions('pieces_colors') diff --git a/deluge/ui/gtkui/queuedtorrents.py b/deluge/ui/gtkui/queuedtorrents.py index 750432bb5..be88b445a 100644 --- a/deluge/ui/gtkui/queuedtorrents.py +++ b/deluge/ui/gtkui/queuedtorrents.py @@ -24,36 +24,36 @@ log = logging.getLogger(__name__) class QueuedTorrents(component.Component): def __init__(self): - component.Component.__init__(self, "QueuedTorrents", depend=["StatusBar", "AddTorrentDialog"]) + component.Component.__init__(self, 'QueuedTorrents', depend=['StatusBar', 'AddTorrentDialog']) self.queue = [] self.status_item = None - self.config = ConfigManager("gtkui.conf") + self.config = ConfigManager('gtkui.conf') self.builder = gtk.Builder() self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "queuedtorrents.ui"))) - self.builder.get_object("chk_autoadd").set_active(self.config["autoadd_queued"]) - self.dialog = self.builder.get_object("queued_torrents_dialog") + 'deluge.ui.gtkui', os.path.join('glade', 'queuedtorrents.ui'))) + self.builder.get_object('chk_autoadd').set_active(self.config['autoadd_queued']) + self.dialog = self.builder.get_object('queued_torrents_dialog') self.dialog.set_icon(get_logo(32)) self.builder.connect_signals({ - "on_button_remove_clicked": self.on_button_remove_clicked, - "on_button_clear_clicked": self.on_button_clear_clicked, - "on_button_close_clicked": self.on_button_close_clicked, - "on_button_add_clicked": self.on_button_add_clicked, - "on_chk_autoadd_toggled": self.on_chk_autoadd_toggled + 'on_button_remove_clicked': self.on_button_remove_clicked, + 'on_button_clear_clicked': self.on_button_clear_clicked, + 'on_button_close_clicked': self.on_button_close_clicked, + 'on_button_add_clicked': self.on_button_add_clicked, + 'on_chk_autoadd_toggled': self.on_chk_autoadd_toggled }) - self.treeview = self.builder.get_object("treeview") + self.treeview = self.builder.get_object('treeview') self.treeview.append_column( - gtk.TreeViewColumn(_("Torrent"), gtk.CellRendererText(), text=0)) + gtk.TreeViewColumn(_('Torrent'), gtk.CellRendererText(), text=0)) self.liststore = gtk.ListStore(str, str) self.treeview.set_model(self.liststore) self.treeview.set_tooltip_column(1) def run(self): - self.dialog.set_transient_for(component.get("MainWindow").window) + self.dialog.set_transient_for(component.get('MainWindow').window) self.dialog.show() def start(self): @@ -64,16 +64,16 @@ class QueuedTorrents(component.Component): self.update_status_bar() # We only want the add button sensitive if we're connected to a host - self.builder.get_object("button_add").set_sensitive(True) + self.builder.get_object('button_add').set_sensitive(True) - if self.config["autoadd_queued"] or self.config["standalone"]: + if self.config['autoadd_queued'] or self.config['standalone']: self.on_button_add_clicked(None) else: self.run() def stop(self): # We only want the add button sensitive if we're connected to a host - self.builder.get_object("button_add").set_sensitive(False) + self.builder.get_object('button_add').set_sensitive(False) self.update_status_bar() def add_to_queue(self, torrents): @@ -86,7 +86,7 @@ class QueuedTorrents(component.Component): for torrent in self.queue: if deluge.common.is_magnet(torrent): magnet = deluge.common.get_magnet_info(torrent) - self.liststore.append([magnet["name"], torrent]) + self.liststore.append([magnet['name'], torrent]) else: self.liststore.append([os.path.split(torrent)[1], torrent]) @@ -98,12 +98,12 @@ class QueuedTorrents(component.Component): # If there are no queued torrents.. remove statusbar widgets and return if len(self.queue) == 0: if self.status_item is not None: - component.get("StatusBar").remove_item(self.status_item) + component.get('StatusBar').remove_item(self.status_item) self.status_item = None return False try: - component.get("StatusBar") + component.get('StatusBar') except Exception: # The statusbar hasn't been loaded yet, so we'll add a timer to # update it later. @@ -112,14 +112,14 @@ class QueuedTorrents(component.Component): # Set the label text for statusbar if len(self.queue) > 1: - label = str(len(self.queue)) + _(" Torrents Queued") + label = str(len(self.queue)) + _(' Torrents Queued') else: - label = str(len(self.queue)) + _(" Torrent Queued") + label = str(len(self.queue)) + _(' Torrent Queued') # Add the statusbar items if needed, or just modify the label if they # have already been added. if self.status_item is None: - self.status_item = component.get("StatusBar").add_item( + self.status_item = component.get('StatusBar').add_item( stock=gtk.STOCK_SORT_DESCENDING, text=label, callback=self.on_statusbar_click) @@ -130,7 +130,7 @@ class QueuedTorrents(component.Component): return False def on_statusbar_click(self, widget, event): - log.debug("on_statusbar_click") + log.debug('on_statusbar_click') self.run() def on_button_remove_clicked(self, widget): @@ -161,4 +161,4 @@ class QueuedTorrents(component.Component): self.update_status_bar() def on_chk_autoadd_toggled(self, widget): - self.config["autoadd_queued"] = widget.get_active() + self.config['autoadd_queued'] = widget.get_active() diff --git a/deluge/ui/gtkui/removetorrentdialog.py b/deluge/ui/gtkui/removetorrentdialog.py index 822f089f5..2a15f8a0b 100644 --- a/deluge/ui/gtkui/removetorrentdialog.py +++ b/deluge/ui/gtkui/removetorrentdialog.py @@ -32,45 +32,45 @@ class RemoveTorrentDialog(object): """ def __init__(self, torrent_ids, delete_files=False): if not isinstance(torrent_ids, list) and not isinstance(torrent_ids, tuple): - raise TypeError("requires a list of torrent_ids") + raise TypeError('requires a list of torrent_ids') if not torrent_ids: - raise ValueError("requires a list of torrent_ids") + raise ValueError('requires a list of torrent_ids') self.__torrent_ids = torrent_ids self.builder = gtk.Builder() self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "remove_torrent_dialog.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'remove_torrent_dialog.ui'))) - self.__dialog = self.builder.get_object("remove_torrent_dialog") - self.__dialog.set_transient_for(component.get("MainWindow").window) + self.__dialog = self.builder.get_object('remove_torrent_dialog') + self.__dialog.set_transient_for(component.get('MainWindow').window) self.builder.connect_signals({ - "on_delete_files_toggled": self.on_delete_files_toggled + 'on_delete_files_toggled': self.on_delete_files_toggled }) self.builder.get_object('delete_files').set_active(delete_files) - label_title = self.builder.get_object("label_title") - label_torrents = self.builder.get_object("label_torrents") + label_title = self.builder.get_object('label_title') + label_torrents = self.builder.get_object('label_torrents') num_torrents = len(self.__torrent_ids) if num_torrents == 1: - label_torrents.set_markup(component.get("TorrentView").get_torrent_status(self.__torrent_ids[0])["name"]) + label_torrents.set_markup(component.get('TorrentView').get_torrent_status(self.__torrent_ids[0])['name']) else: - label_title.set_markup(_("Remove the selected torrents?")) - label_torrents.set_markup(_("Total of %s torrents selected") % num_torrents) + label_title.set_markup(_('Remove the selected torrents?')) + label_torrents.set_markup(_('Total of %s torrents selected') % num_torrents) def on_delete_files_toggled(self, widget): self.builder.get_object('warning_label').set_visible(widget.get_active()) def __remove_torrents(self, remove_data): # Unselect all to avoid issues with the selection changed event - component.get("TorrentView").treeview.get_selection().unselect_all() + component.get('TorrentView').treeview.get_selection().unselect_all() def on_removed_finished(errors): if errors: - log.info("Error(s) occured when trying to delete torrent(s).") + log.info('Error(s) occured when trying to delete torrent(s).') for t_id, e_msg in errors: - log.warn("Error removing torrent %s : %s", t_id, e_msg) + log.warn('Error removing torrent %s : %s', t_id, e_msg) d = client.core.remove_torrents(self.__torrent_ids, remove_data) d.addCallback(on_removed_finished) @@ -81,5 +81,5 @@ class RemoveTorrentDialog(object): remove the torrent(s) from the session with or without their data. """ if self.__dialog.run() == gtk.RESPONSE_OK: - self.__remove_torrents(self.builder.get_object("delete_files").get_active()) + self.__remove_torrents(self.builder.get_object('delete_files').get_active()) self.__dialog.destroy() diff --git a/deluge/ui/gtkui/sidebar.py b/deluge/ui/gtkui/sidebar.py index 379794dbe..7fc5db6a2 100644 --- a/deluge/ui/gtkui/sidebar.py +++ b/deluge/ui/gtkui/sidebar.py @@ -24,40 +24,40 @@ class SideBar(component.Component): purpose : plugins """ def __init__(self): - component.Component.__init__(self, "SideBar") - self.window = component.get("MainWindow") + component.Component.__init__(self, 'SideBar') + self.window = component.get('MainWindow') builder = self.window.get_builder() - self.notebook = builder.get_object("sidebar_notebook") - self.hpaned = builder.get_object("main_window_hpaned") - self.config = ConfigManager("gtkui.conf") + self.notebook = builder.get_object('sidebar_notebook') + self.hpaned = builder.get_object('main_window_hpaned') + self.config = ConfigManager('gtkui.conf') # self.hpaned_position = self.hpaned.get_position() # Tabs holds references to the Tab widgets by their name self.tabs = {} # Hide if necessary - self.visible(self.config["show_sidebar"]) + self.visible(self.config['show_sidebar']) def shutdown(self): - log.debug("hpaned.position: %s", self.hpaned.get_position()) - self.config["sidebar_position"] = self.hpaned.get_position() + log.debug('hpaned.position: %s', self.hpaned.get_position()) + self.config['sidebar_position'] = self.hpaned.get_position() def visible(self, visible): if visible: - if self.config["sidebar_position"]: - self.hpaned.set_position(self.config["sidebar_position"]) + if self.config['sidebar_position']: + self.hpaned.set_position(self.config['sidebar_position']) self.notebook.show() else: self.notebook.hide() # Store the position for restoring upon show() - self.config["sidebar_position"] = self.hpaned.get_position() + self.config['sidebar_position'] = self.hpaned.get_position() self.hpaned.set_position(-1) - self.config["show_sidebar"] = visible + self.config['show_sidebar'] = visible def add_tab(self, widget, tab_name, label): """Adds a tab object to the notebook.""" - log.debug("add tab: %s", tab_name) + log.debug('add tab: %s', tab_name) self.tabs[tab_name] = widget scrolled = gtk.ScrolledWindow() scrolled.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) diff --git a/deluge/ui/gtkui/status_tab.py b/deluge/ui/gtkui/status_tab.py index a54632a60..7b9d2ee61 100644 --- a/deluge/ui/gtkui/status_tab.py +++ b/deluge/ui/gtkui/status_tab.py @@ -27,43 +27,43 @@ class StatusTab(Tab): Tab.__init__(self) # Get the labels we need to update. # widget name, modifier function, status keys - self.builder = builder = component.get("MainWindow").get_builder() + self.builder = builder = component.get('MainWindow').get_builder() - self._name = "Status" - self._child_widget = builder.get_object("status_tab") - self._tab_label = builder.get_object("status_tab_label") - self.config = ConfigManager("gtkui.conf") + self._name = 'Status' + self._child_widget = builder.get_object('status_tab') + self._tab_label = builder.get_object('status_tab_label') + self.config = ConfigManager('gtkui.conf') - self.progressbar = builder.get_object("progressbar") + self.progressbar = builder.get_object('progressbar') self.piecesbar = None self.piecesbar_label_widget = None self.label_widgets = [ - (builder.get_object("summary_availability"), fratio, ("distributed_copies",)), - (builder.get_object("summary_total_downloaded"), ftotal_sized, ("all_time_download", - "total_payload_download")), - (builder.get_object("summary_total_uploaded"), ftotal_sized, ("total_uploaded", "total_payload_upload")), - (builder.get_object("summary_download_speed"), fspeed_max, ("download_payload_rate", "max_download_speed")), - (builder.get_object("summary_upload_speed"), fspeed_max, ("upload_payload_rate", "max_upload_speed")), - (builder.get_object("summary_seeds"), fpeer, ("num_seeds", "total_seeds")), - (builder.get_object("summary_peers"), fpeer, ("num_peers", "total_peers")), - (builder.get_object("summary_eta"), ftime_or_dash, ("eta",)), - (builder.get_object("summary_share_ratio"), fratio, ("ratio",)), - (builder.get_object("summary_active_time"), ftime_or_dash, ("active_time",)), - (builder.get_object("summary_seed_time"), ftime_or_dash, ("seeding_time",)), - (builder.get_object("summary_seed_rank"), fseed_rank_or_dash, ("seed_rank", "seeding_time")), - (builder.get_object("progressbar"), fpcnt, ("progress", "state", "message")), - (builder.get_object("summary_last_seen_complete"), fdate_or_never, ("last_seen_complete",)), - (builder.get_object("summary_last_active"), flast_active, ("time_since_download", - "time_since_upload")), + (builder.get_object('summary_availability'), fratio, ('distributed_copies',)), + (builder.get_object('summary_total_downloaded'), ftotal_sized, ('all_time_download', + 'total_payload_download')), + (builder.get_object('summary_total_uploaded'), ftotal_sized, ('total_uploaded', 'total_payload_upload')), + (builder.get_object('summary_download_speed'), fspeed_max, ('download_payload_rate', 'max_download_speed')), + (builder.get_object('summary_upload_speed'), fspeed_max, ('upload_payload_rate', 'max_upload_speed')), + (builder.get_object('summary_seeds'), fpeer, ('num_seeds', 'total_seeds')), + (builder.get_object('summary_peers'), fpeer, ('num_peers', 'total_peers')), + (builder.get_object('summary_eta'), ftime_or_dash, ('eta',)), + (builder.get_object('summary_share_ratio'), fratio, ('ratio',)), + (builder.get_object('summary_active_time'), ftime_or_dash, ('active_time',)), + (builder.get_object('summary_seed_time'), ftime_or_dash, ('seeding_time',)), + (builder.get_object('summary_seed_rank'), fseed_rank_or_dash, ('seed_rank', 'seeding_time')), + (builder.get_object('progressbar'), fpcnt, ('progress', 'state', 'message')), + (builder.get_object('summary_last_seen_complete'), fdate_or_never, ('last_seen_complete',)), + (builder.get_object('summary_last_active'), flast_active, ('time_since_download', + 'time_since_upload')), ] self.status_keys = [status for widget in self.label_widgets for status in widget[2]] - self.config.register_set_function("show_piecesbar", self.on_show_piecesbar_config_changed, apply_now=True) + self.config.register_set_function('show_piecesbar', self.on_show_piecesbar_config_changed, apply_now=True) def update(self): # Get the first selected torrent - selected = component.get("TorrentView").get_selected_torrent() + selected = component.get('TorrentView').get_selected_torrent() if not selected: # No torrent is selected in the torrentview @@ -73,9 +73,9 @@ class StatusTab(Tab): # Get the torrent status status_keys = self.status_keys if self.config['show_piecesbar']: - status_keys.extend(["pieces", "num_pieces"]) + status_keys.extend(['pieces', 'num_pieces']) - component.get("SessionProxy").get_torrent_status( + component.get('SessionProxy').get_torrent_status( selected, status_keys).addCallback(self._on_get_torrent_status) def _on_get_torrent_status(self, status): @@ -90,12 +90,12 @@ class StatusTab(Tab): widget[0].set_text(txt) # Update progress bar seperately as it's a special case (not a label). - fraction = status["progress"] / 100 + fraction = status['progress'] / 100 if self.config['show_piecesbar']: if self.piecesbar.get_fraction() != fraction: self.piecesbar.set_fraction(fraction) - if status["state"] != "Checking" and self.piecesbar.get_pieces() != status['pieces']: + if status['state'] != 'Checking' and self.piecesbar.get_pieces() != status['pieces']: # Skip pieces assignment if checking torrent. self.piecesbar.set_pieces(status['pieces'], status['num_pieces']) self.piecesbar.update() @@ -112,8 +112,8 @@ class StatusTab(Tab): def show_piecesbar(self): if self.piecesbar is None: self.piecesbar = PiecesBar() - self.builder.get_object("status_progress_vbox").pack_start(self.piecesbar, False, False, 0) - self.piecesbar_label_widget = (self.piecesbar, fpcnt, ("progress", "state", "message")) + self.builder.get_object('status_progress_vbox').pack_start(self.piecesbar, False, False, 0) + self.piecesbar_label_widget = (self.piecesbar, fpcnt, ('progress', 'state', 'message')) self.label_widgets.append(self.piecesbar_label_widget) self.piecesbar.show() self.progressbar.hide() @@ -127,7 +127,7 @@ class StatusTab(Tab): def clear(self): for widget in self.label_widgets: - widget[0].set_text("") + widget[0].set_text('') if self.config['show_piecesbar']: self.piecesbar.clear() diff --git a/deluge/ui/gtkui/statusbar.py b/deluge/ui/gtkui/statusbar.py index fb742fcf7..61b3e7836 100644 --- a/deluge/ui/gtkui/statusbar.py +++ b/deluge/ui/gtkui/statusbar.py @@ -57,7 +57,7 @@ class StatusBarItem(object): self.show_all() def set_callback(self, callback): - self._ebox.connect("button-press-event", callback) + self._ebox.connect('button-press-event', callback) def show_all(self): self._ebox.show() @@ -100,18 +100,18 @@ class StatusBarItem(object): class StatusBar(component.Component): def __init__(self): - component.Component.__init__(self, "StatusBar", interval=3) - self.window = component.get("MainWindow") - self.statusbar = self.window.get_builder().get_object("statusbar") - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'StatusBar', interval=3) + self.window = component.get('MainWindow') + self.statusbar = self.window.get_builder().get_object('statusbar') + self.config = ConfigManager('gtkui.conf') # Status variables that are updated via callback self.max_connections_global = -1 self.num_connections = 0 self.max_download_speed = -1.0 - self.download_rate = "" + self.download_rate = '' self.max_upload_speed = -1.0 - self.upload_rate = "" + self.upload_rate = '' self.dht_nodes = 0 self.dht_status = False self.health = False @@ -119,10 +119,10 @@ class StatusBar(component.Component): self.upload_protocol_rate = 0.0 self.config_value_changed_dict = { - "max_connections_global": self._on_max_connections_global, - "max_download_speed": self._on_max_download_speed, - "max_upload_speed": self._on_max_upload_speed, - "dht": self._on_dht + 'max_connections_global': self._on_max_connections_global, + 'max_download_speed': self._on_max_download_speed, + 'max_upload_speed': self._on_max_upload_speed, + 'dht': self._on_dht } self.current_warnings = [] # Add a HBox to the statusbar after removing the initial label widget @@ -137,15 +137,15 @@ class StatusBar(component.Component): self.statusbar.show_all() # Create the not connected item self.not_connected_item = StatusBarItem( - stock=gtk.STOCK_STOP, text=_("Not Connected"), + stock=gtk.STOCK_STOP, text=_('Not Connected'), callback=self._on_notconnected_item_clicked) # Show the not connected status bar self.show_not_connected() # Hide if necessary - self.visible(self.config["show_statusbar"]) + self.visible(self.config['show_statusbar']) - client.register_event_handler("ConfigValueChangedEvent", self.on_configvaluechanged_event) + client.register_event_handler('ConfigValueChangedEvent', self.on_configvaluechanged_event) def start(self): # Add in images and labels @@ -154,51 +154,51 @@ class StatusBar(component.Component): self.connections_item = self.add_item( stock=gtk.STOCK_NETWORK, callback=self._on_connection_item_clicked, - tooltip=_("Connections (Limit)"), pack_start=True) + tooltip=_('Connections (Limit)'), pack_start=True) self.download_item = self.add_item( - image=get_pixmap("downloading16.png"), + image=get_pixmap('downloading16.png'), callback=self._on_download_item_clicked, - tooltip=_("Download Speed (Limit)"), pack_start=True) + tooltip=_('Download Speed (Limit)'), pack_start=True) self.upload_item = self.add_item( - image=get_pixmap("seeding16.png"), + image=get_pixmap('seeding16.png'), callback=self._on_upload_item_clicked, - tooltip=_("Upload Speed (Limit)"), pack_start=True) + tooltip=_('Upload Speed (Limit)'), pack_start=True) self.traffic_item = self.add_item( - image=get_pixmap("traffic16.png"), + image=get_pixmap('traffic16.png'), callback=self._on_traffic_item_clicked, - tooltip=_("Protocol Traffic (Down:Up)"), pack_start=True) + tooltip=_('Protocol Traffic (Down:Up)'), pack_start=True) self.dht_item = StatusBarItem( - image=get_pixmap("dht16.png"), tooltip=_("DHT Nodes")) + image=get_pixmap('dht16.png'), tooltip=_('DHT Nodes')) self.diskspace_item = self.add_item( stock=gtk.STOCK_HARDDISK, callback=self._on_diskspace_item_clicked, - tooltip=_("Free Disk Space"), pack_start=True) + tooltip=_('Free Disk Space'), pack_start=True) self.health_item = self.add_item( stock=gtk.STOCK_DIALOG_ERROR, - text=_("<b><small>Port Issue</small></b>"), + text=_('<b><small>Port Issue</small></b>'), markup=True, - tooltip=_("No incoming connections, check port forwarding"), + tooltip=_('No incoming connections, check port forwarding'), callback=self._on_health_icon_clicked) self.external_ip_item = self.add_item( - tooltip=_("External IP Address"), pack_start=True) + tooltip=_('External IP Address'), pack_start=True) self.health = False def update_config_values(configs): - self._on_max_connections_global(configs["max_connections_global"]) - self._on_max_download_speed(configs["max_download_speed"]) - self._on_max_upload_speed(configs["max_upload_speed"]) - self._on_dht(configs["dht"]) + self._on_max_connections_global(configs['max_connections_global']) + self._on_max_download_speed(configs['max_download_speed']) + self._on_max_upload_speed(configs['max_upload_speed']) + self._on_dht(configs['dht']) # Get some config values - client.core.get_config_values(["max_connections_global", "max_download_speed", - "max_upload_speed", "dht"]).addCallback(update_config_values) + client.core.get_config_values(['max_connections_global', 'max_download_speed', + 'max_upload_speed', 'dht']).addCallback(update_config_values) def stop(self): # When stopped, we just show the not connected thingy @@ -213,7 +213,7 @@ class StatusBar(component.Component): self.remove_item(self.diskspace_item) self.remove_item(self.external_ip_item) except Exception as ex: - log.debug("Unable to remove StatusBar item: %s", ex) + log.debug('Unable to remove StatusBar item: %s', ex) self.show_not_connected() def visible(self, visible): @@ -222,7 +222,7 @@ class StatusBar(component.Component): else: self.statusbar.hide() - self.config["show_statusbar"] = visible + self.config['show_statusbar'] = visible def show_not_connected(self): self.hbox.pack_start( @@ -244,7 +244,7 @@ class StatusBar(component.Component): try: self.hbox.remove(item.get_eventbox()) except Exception as ex: - log.debug("Unable to remove widget: %s", ex) + log.debug('Unable to remove widget: %s', ex) def add_timeout_item(self, seconds=3, image=None, stock=None, text=None, callback=None): """Adds an item to the StatusBar for seconds""" @@ -271,13 +271,13 @@ class StatusBar(component.Component): def send_status_request(self): # Sends an async request for data from the core - keys = ["num_peers", "upload_rate", "download_rate", "payload_upload_rate", "payload_download_rate"] + keys = ['num_peers', 'upload_rate', 'download_rate', 'payload_upload_rate', 'payload_download_rate'] if self.dht_status: - keys.append("dht_nodes") + keys.append('dht_nodes') if not self.health: - keys.append("has_incoming_connections") + keys.append('has_incoming_connections') client.core.get_session_status(keys).addCallback(self._on_get_session_status) client.core.get_free_space().addCallback(self._on_get_free_space) @@ -305,30 +305,30 @@ class StatusBar(component.Component): self.remove_item(self.dht_item) def _on_get_session_status(self, status): - self.download_rate = fspeed(status["payload_download_rate"], precision=0, shortform=True) - self.upload_rate = fspeed(status["payload_upload_rate"], precision=0, shortform=True) - self.download_protocol_rate = (status["download_rate"] - status["payload_download_rate"]) // 1024 - self.upload_protocol_rate = (status["upload_rate"] - status["payload_upload_rate"]) // 1024 - self.num_connections = status["num_peers"] + self.download_rate = fspeed(status['payload_download_rate'], precision=0, shortform=True) + self.upload_rate = fspeed(status['payload_upload_rate'], precision=0, shortform=True) + self.download_protocol_rate = (status['download_rate'] - status['payload_download_rate']) // 1024 + self.upload_protocol_rate = (status['upload_rate'] - status['payload_upload_rate']) // 1024 + self.num_connections = status['num_peers'] self.update_download_label() self.update_upload_label() self.update_traffic_label() self.update_connections_label() - if "dht_nodes" in status: - self.dht_nodes = status["dht_nodes"] + if 'dht_nodes' in status: + self.dht_nodes = status['dht_nodes'] self.update_dht_label() - if "has_incoming_connections" in status: - self.health = status["has_incoming_connections"] + if 'has_incoming_connections' in status: + self.health = status['has_incoming_connections'] if self.health: self.remove_item(self.health_item) def _on_get_free_space(self, space): if space >= 0: - self.diskspace_item.set_markup("<small>%s</small>" % fsize(space, shortform=True)) + self.diskspace_item.set_markup('<small>%s</small>' % fsize(space, shortform=True)) else: - self.diskspace_item.set_markup("<span foreground=\"red\">" + _("Error") + "</span>") + self.diskspace_item.set_markup("<span foreground=\"red\">" + _('Error') + '</span>') def _on_max_download_speed(self, max_download_speed): self.max_download_speed = max_download_speed @@ -339,29 +339,29 @@ class StatusBar(component.Component): self.update_upload_label() def _on_get_external_ip(self, external_ip): - ip = external_ip if external_ip else _("n/a") - self.external_ip_item.set_markup(_("<b>IP</b> <small>%s</small>") % ip) + ip = external_ip if external_ip else _('n/a') + self.external_ip_item.set_markup(_('<b>IP</b> <small>%s</small>') % ip) def update_connections_label(self): # Set the max connections label if self.max_connections_global < 0: - label_string = "%s" % self.num_connections + label_string = '%s' % self.num_connections else: - label_string = "%s <small>(%s)</small>" % (self.num_connections, self.max_connections_global) + label_string = '%s <small>(%s)</small>' % (self.num_connections, self.max_connections_global) self.connections_item.set_markup(label_string) def update_dht_label(self): # Set the max connections label - self.dht_item.set_markup("<small>%s</small>" % (self.dht_nodes)) + self.dht_item.set_markup('<small>%s</small>' % (self.dht_nodes)) def update_download_label(self): # Set the download speed label if self.max_download_speed <= 0: label_string = self.download_rate else: - label_string = "%s <small>(%i %s)</small>" % ( - self.download_rate, self.max_download_speed, _("K/s")) + label_string = '%s <small>(%i %s)</small>' % ( + self.download_rate, self.max_download_speed, _('K/s')) self.download_item.set_markup(label_string) @@ -370,27 +370,27 @@ class StatusBar(component.Component): if self.max_upload_speed <= 0: label_string = self.upload_rate else: - label_string = "%s <small>(%i %s)</small>" % ( - self.upload_rate, self.max_upload_speed, _("K/s")) + label_string = '%s <small>(%i %s)</small>' % ( + self.upload_rate, self.max_upload_speed, _('K/s')) self.upload_item.set_markup(label_string) def update_traffic_label(self): - label_string = "<small>%i:%i %s</small>" % (self.download_protocol_rate, self.upload_protocol_rate, _("K/s")) + label_string = '<small>%i:%i %s</small>' % (self.download_protocol_rate, self.upload_protocol_rate, _('K/s')) self.traffic_item.set_markup(label_string) def update(self): self.send_status_request() def set_limit_value(self, widget, core_key): - log.debug("_on_set_unlimit_other %s", core_key) + log.debug('_on_set_unlimit_other %s', core_key) other_dialog_info = { - "max_download_speed": (_("Download Speed Limit"), _("Set the maximum download speed"), - _("K/s"), "downloading.svg", self.max_download_speed), - "max_upload_speed": (_("Upload Speed Limit"), _("Set the maximum upload speed"), - _("K/s"), "seeding.svg", self.max_upload_speed), - "max_connections_global": (_("Incoming Connections"), _("Set the maximum incoming connections"), - "", gtk.STOCK_NETWORK, self.max_connections_global) + 'max_download_speed': (_('Download Speed Limit'), _('Set the maximum download speed'), + _('K/s'), 'downloading.svg', self.max_download_speed), + 'max_upload_speed': (_('Upload Speed Limit'), _('Set the maximum upload speed'), + _('K/s'), 'seeding.svg', self.max_upload_speed), + 'max_connections_global': (_('Incoming Connections'), _('Set the maximum incoming connections'), + '', gtk.STOCK_NETWORK, self.max_connections_global) } def set_value(value): @@ -403,64 +403,64 @@ class StatusBar(component.Component): if value != getattr(self, core_key): client.core.set_config({core_key: value}) - if widget.get_name() == "unlimited": + if widget.get_name() == 'unlimited': set_value(-1) - elif widget.get_name() == "other": + elif widget.get_name() == 'other': def dialog_finished(response_id): if response_id == gtk.RESPONSE_OK: set_value(dialog.get_value()) dialog = dialogs.OtherDialog(*other_dialog_info[core_key]) dialog.run().addCallback(set_value) else: - value = widget.get_children()[0].get_text().split(" ")[0] + value = widget.get_children()[0].get_text().split(' ')[0] set_value(value) def _on_download_item_clicked(self, widget, event): menu = common.build_menu_radio_list( - self.config["tray_download_speed_list"], + self.config['tray_download_speed_list'], self._on_set_download_speed, self.max_download_speed, - _("K/s"), show_notset=True, show_other=True) + _('K/s'), show_notset=True, show_other=True) menu.show_all() menu.popup(None, None, None, event.button, event.time) def _on_set_download_speed(self, widget): - log.debug("_on_set_download_speed") - self.set_limit_value(widget, "max_download_speed") + log.debug('_on_set_download_speed') + self.set_limit_value(widget, 'max_download_speed') def _on_upload_item_clicked(self, widget, event): menu = common.build_menu_radio_list( - self.config["tray_upload_speed_list"], + self.config['tray_upload_speed_list'], self._on_set_upload_speed, self.max_upload_speed, - _("K/s"), show_notset=True, show_other=True) + _('K/s'), show_notset=True, show_other=True) menu.show_all() menu.popup(None, None, None, event.button, event.time) def _on_set_upload_speed(self, widget): - log.debug("_on_set_upload_speed") - self.set_limit_value(widget, "max_upload_speed") + log.debug('_on_set_upload_speed') + self.set_limit_value(widget, 'max_upload_speed') def _on_connection_item_clicked(self, widget, event): menu = common.build_menu_radio_list( - self.config["connection_limit_list"], + self.config['connection_limit_list'], self._on_set_connection_limit, self.max_connections_global, show_notset=True, show_other=True) menu.show_all() menu.popup(None, None, None, event.button, event.time) def _on_set_connection_limit(self, widget): - log.debug("_on_set_connection_limit") - self.set_limit_value(widget, "max_connections_global") + log.debug('_on_set_connection_limit') + self.set_limit_value(widget, 'max_connections_global') def _on_health_icon_clicked(self, widget, event): - component.get("Preferences").show("Network") + component.get('Preferences').show('Network') def _on_notconnected_item_clicked(self, widget, event): - component.get("ConnectionManager").show() + component.get('ConnectionManager').show() def _on_traffic_item_clicked(self, widget, event): - component.get("Preferences").show("Network") + component.get('Preferences').show('Network') def _on_diskspace_item_clicked(self, widget, event): - component.get("Preferences").show("Downloads") + component.get('Preferences').show('Downloads') diff --git a/deluge/ui/gtkui/systemtray.py b/deluge/ui/gtkui/systemtray.py index 5fe1f2793..97fa53c0c 100644 --- a/deluge/ui/gtkui/systemtray.py +++ b/deluge/ui/gtkui/systemtray.py @@ -30,26 +30,26 @@ log = logging.getLogger(__name__) class SystemTray(component.Component): def __init__(self): - component.Component.__init__(self, "SystemTray", interval=4) - self.window = component.get("MainWindow") - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'SystemTray', interval=4) + self.window = component.get('MainWindow') + self.config = ConfigManager('gtkui.conf') # List of widgets that need to be hidden when not connected to a host self.hide_widget_list = [ - "menuitem_add_torrent", - "menuitem_pause_session", - "menuitem_resume_session", - "menuitem_download_limit", - "menuitem_upload_limit", - "menuitem_quitdaemon", - "separatormenuitem1", - "separatormenuitem2", - "separatormenuitem3", - "separatormenuitem4" + 'menuitem_add_torrent', + 'menuitem_pause_session', + 'menuitem_resume_session', + 'menuitem_download_limit', + 'menuitem_upload_limit', + 'menuitem_quitdaemon', + 'separatormenuitem1', + 'separatormenuitem2', + 'separatormenuitem3', + 'separatormenuitem4' ] - self.config.register_set_function("enable_system_tray", self.on_enable_system_tray_set) + self.config.register_set_function('enable_system_tray', self.on_enable_system_tray_set) # bit of a hack to prevent function from doing something on startup self.__enabled_set_once = False - self.config.register_set_function("enable_appindicator", self.on_enable_appindicator_set) + self.config.register_set_function('enable_appindicator', self.on_enable_appindicator_set) self.max_download_speed = -1.0 self.download_rate = 0.0 @@ -57,33 +57,33 @@ class SystemTray(component.Component): self.upload_rate = 0.0 self.config_value_changed_dict = { - "max_download_speed": self._on_max_download_speed, - "max_upload_speed": self._on_max_upload_speed + 'max_download_speed': self._on_max_download_speed, + 'max_upload_speed': self._on_max_upload_speed } def enable(self): """Enables the system tray icon.""" self.builder = gtk.Builder() self.builder.add_from_file(deluge.common.resource_filename( - "deluge.ui.gtkui", os.path.join("glade", "tray_menu.ui"))) + 'deluge.ui.gtkui', os.path.join('glade', 'tray_menu.ui'))) self.builder.connect_signals({ - "on_menuitem_show_deluge_activate": self.on_menuitem_show_deluge_activate, - "on_menuitem_add_torrent_activate": self.on_menuitem_add_torrent_activate, - "on_menuitem_pause_session_activate": self.on_menuitem_pause_session_activate, - "on_menuitem_resume_session_activate": self.on_menuitem_resume_session_activate, - "on_menuitem_quit_activate": self.on_menuitem_quit_activate, - "on_menuitem_quitdaemon_activate": self.on_menuitem_quitdaemon_activate + 'on_menuitem_show_deluge_activate': self.on_menuitem_show_deluge_activate, + 'on_menuitem_add_torrent_activate': self.on_menuitem_add_torrent_activate, + 'on_menuitem_pause_session_activate': self.on_menuitem_pause_session_activate, + 'on_menuitem_resume_session_activate': self.on_menuitem_resume_session_activate, + 'on_menuitem_quit_activate': self.on_menuitem_quit_activate, + 'on_menuitem_quitdaemon_activate': self.on_menuitem_quitdaemon_activate }) - self.tray_menu = self.builder.get_object("tray_menu") + self.tray_menu = self.builder.get_object('tray_menu') - if appindicator and self.config["enable_appindicator"]: - log.debug("Enabling the Application Indicator...") - self.indicator = appindicator.Indicator("deluge", "deluge", + if appindicator and self.config['enable_appindicator']: + log.debug('Enabling the Application Indicator...') + self.indicator = appindicator.Indicator('deluge', 'deluge', appindicator.CATEGORY_APPLICATION_STATUS) try: - self.indicator.set_property("title", _("Deluge")) + self.indicator.set_property('title', _('Deluge')) except TypeError: # Catch 'title' property error for previous appindicator versions pass @@ -91,32 +91,32 @@ class SystemTray(component.Component): self.indicator.set_menu(self.tray_menu) # Make sure the status of the Show Window MenuItem is correct - self._sig_win_hide = self.window.window.connect("hide", self._on_window_hide) - self._sig_win_show = self.window.window.connect("show", self._on_window_show) + self._sig_win_hide = self.window.window.connect('hide', self._on_window_hide) + self._sig_win_show = self.window.window.connect('show', self._on_window_show) if self.window.visible(): - self.builder.get_object("menuitem_show_deluge").set_active(True) + self.builder.get_object('menuitem_show_deluge').set_active(True) else: - self.builder.get_object("menuitem_show_deluge").set_active(False) + self.builder.get_object('menuitem_show_deluge').set_active(False) # Show the Application Indicator self.indicator.set_status(appindicator.STATUS_ACTIVE) else: - log.debug("Enabling the system tray icon..") + log.debug('Enabling the system tray icon..') if deluge.common.windows_check() or deluge.common.osx_check(): self.tray = gtk.status_icon_new_from_pixbuf(get_logo(32)) else: - self.tray = gtk.status_icon_new_from_icon_name("deluge") + self.tray = gtk.status_icon_new_from_icon_name('deluge') - self.tray.connect("activate", self.on_tray_clicked) - self.tray.connect("popup-menu", self.on_tray_popup) + self.tray.connect('activate', self.on_tray_clicked) + self.tray.connect('popup-menu', self.on_tray_popup) - self.builder.get_object("download-limit-image").set_from_file( - deluge.common.get_pixmap("downloading16.png")) - self.builder.get_object("upload-limit-image").set_from_file( - deluge.common.get_pixmap("seeding16.png")) + self.builder.get_object('download-limit-image').set_from_file( + deluge.common.get_pixmap('downloading16.png')) + self.builder.get_object('upload-limit-image').set_from_file( + deluge.common.get_pixmap('seeding16.png')) - client.register_event_handler("ConfigValueChangedEvent", self.config_value_changed) + client.register_event_handler('ConfigValueChangedEvent', self.config_value_changed) if client.connected(): # We're connected so we need to get some values from the core self.__start() @@ -126,16 +126,16 @@ class SystemTray(component.Component): self.builder.get_object(widget).hide() def __start(self): - if self.config["enable_system_tray"]: + if self.config['enable_system_tray']: - if self.config["standalone"]: + if self.config['standalone']: try: - self.hide_widget_list.remove("menuitem_quitdaemon") - self.hide_widget_list.remove("separatormenuitem4") + self.hide_widget_list.remove('menuitem_quitdaemon') + self.hide_widget_list.remove('separatormenuitem4') except ValueError: pass - self.builder.get_object("menuitem_quitdaemon").hide() - self.builder.get_object("separatormenuitem4").hide() + self.builder.get_object('menuitem_quitdaemon').hide() + self.builder.get_object('separatormenuitem4').hide() # Show widgets in the hide list because we've connected to a host for widget in self.hide_widget_list: @@ -146,35 +146,35 @@ class SystemTray(component.Component): # Get some config values def update_config_values(configs): - self._on_max_download_speed(configs["max_download_speed"]) - self._on_max_upload_speed(configs["max_upload_speed"]) - client.core.get_config_values(["max_download_speed", "max_upload_speed"]).addCallback(update_config_values) + self._on_max_download_speed(configs['max_download_speed']) + self._on_max_upload_speed(configs['max_upload_speed']) + client.core.get_config_values(['max_download_speed', 'max_upload_speed']).addCallback(update_config_values) def start(self): self.__start() def stop(self): - if self.config["enable_system_tray"] and not self.config["enable_appindicator"]: + if self.config['enable_system_tray'] and not self.config['enable_appindicator']: try: # Hide widgets in hide list because we're not connected to a host for widget in self.hide_widget_list: self.builder.get_object(widget).hide() except Exception as ex: - log.debug("Unable to hide system tray menu widgets: %s", ex) + log.debug('Unable to hide system tray menu widgets: %s', ex) - self.tray.set_tooltip(_("Deluge") + "\n" + _("Not Connected...")) + self.tray.set_tooltip(_('Deluge') + '\n' + _('Not Connected...')) def shutdown(self): - if self.config["enable_system_tray"]: - if appindicator and self.config["enable_appindicator"]: + if self.config['enable_system_tray']: + if appindicator and self.config['enable_appindicator']: self.indicator.set_status(appindicator.STATUS_PASSIVE) else: self.tray.set_visible(False) def send_status_request(self): client.core.get_session_status([ - "payload_upload_rate", - "payload_download_rate"]).addCallback(self._on_get_session_status) + 'payload_upload_rate', + 'payload_download_rate']).addCallback(self._on_get_session_status) def config_value_changed(self, key, value): """This is called when we received a config_value_changed signal from @@ -193,19 +193,19 @@ class SystemTray(component.Component): self.build_tray_bwsetsubmenu() def _on_get_session_status(self, status): - self.download_rate = fspeed(status["payload_download_rate"], shortform=True) - self.upload_rate = fspeed(status["payload_upload_rate"], shortform=True) + self.download_rate = fspeed(status['payload_download_rate'], shortform=True) + self.upload_rate = fspeed(status['payload_upload_rate'], shortform=True) def update(self): - if not self.config["enable_system_tray"]: + if not self.config['enable_system_tray']: return # Tool tip text not available for appindicator - if appindicator and self.config["enable_appindicator"]: + if appindicator and self.config['enable_appindicator']: if self.window.visible(): - self.builder.get_object("menuitem_show_deluge").set_active(True) + self.builder.get_object('menuitem_show_deluge').set_active(True) else: - self.builder.get_object("menuitem_show_deluge").set_active(False) + self.builder.get_object('menuitem_show_deluge').set_active(False) return # Set the tool tip text @@ -213,17 +213,17 @@ class SystemTray(component.Component): max_upload_speed = self.max_upload_speed if max_download_speed == -1: - max_download_speed = _("Unlimited") + max_download_speed = _('Unlimited') else: - max_download_speed = "%s %s" % (max_download_speed, _("K/s")) + max_download_speed = '%s %s' % (max_download_speed, _('K/s')) if max_upload_speed == -1: - max_upload_speed = _("Unlimited") + max_upload_speed = _('Unlimited') else: - max_upload_speed = "%s %s" % (max_upload_speed, _("K/s")) + max_upload_speed = '%s %s' % (max_upload_speed, _('K/s')) msg = '%s\n%s: %s (%s)\n%s: %s (%s)' % ( - _("Deluge"), _("Down"), self.download_rate, - max_download_speed, _("Up"), self.upload_rate, max_upload_speed + _('Deluge'), _('Down'), self.download_rate, + max_download_speed, _('Up'), self.upload_rate, max_upload_speed ) # Set the tooltip @@ -234,21 +234,21 @@ class SystemTray(component.Component): def build_tray_bwsetsubmenu(self): # Create the Download speed list sub-menu submenu_bwdownset = build_menu_radio_list( - self.config["tray_download_speed_list"], self.on_tray_setbwdown, + self.config['tray_download_speed_list'], self.on_tray_setbwdown, self.max_download_speed, - _("K/s"), show_notset=True, show_other=True + _('K/s'), show_notset=True, show_other=True ) # Create the Upload speed list sub-menu submenu_bwupset = build_menu_radio_list( - self.config["tray_upload_speed_list"], self.on_tray_setbwup, + self.config['tray_upload_speed_list'], self.on_tray_setbwup, self.max_upload_speed, - _("K/s"), show_notset=True, show_other=True + _('K/s'), show_notset=True, show_other=True ) # Add the sub-menus to the tray menu - self.builder.get_object("menuitem_download_limit").set_submenu( + self.builder.get_object('menuitem_download_limit').set_submenu( submenu_bwdownset) - self.builder.get_object("menuitem_upload_limit").set_submenu( + self.builder.get_object('menuitem_upload_limit').set_submenu( submenu_bwupset) # Show the sub-menus for all to see @@ -259,25 +259,25 @@ class SystemTray(component.Component): """Disables the system tray icon or appindicator.""" try: if invert_app_ind_conf: - app_ind_conf = not self.config["enable_appindicator"] + app_ind_conf = not self.config['enable_appindicator'] else: - app_ind_conf = self.config["enable_appindicator"] + app_ind_conf = self.config['enable_appindicator'] if appindicator and app_ind_conf: - if hasattr(self, "_sig_win_hide"): + if hasattr(self, '_sig_win_hide'): self.window.window.disconnect(self._sig_win_hide) self.window.window.disconnect(self._sig_win_show) - log.debug("Disabling the application indicator..") + log.debug('Disabling the application indicator..') self.indicator.set_status(appindicator.STATUS_PASSIVE) del self.indicator else: - log.debug("Disabling the system tray icon..") + log.debug('Disabling the system tray icon..') self.tray.set_visible(False) del self.tray del self.builder del self.tray_menu except Exception as ex: - log.debug("Unable to disable system tray: %s", ex) + log.debug('Unable to disable system tray: %s', ex) def blink(self, value): try: @@ -315,9 +315,9 @@ class SystemTray(component.Component): self.blink(False) if self.window.visible(): - self.builder.get_object("menuitem_show_deluge").set_active(True) + self.builder.get_object('menuitem_show_deluge').set_active(True) else: - self.builder.get_object("menuitem_show_deluge").set_active(False) + self.builder.get_object('menuitem_show_deluge').set_active(False) popup_function = gtk.status_icon_position_menu if deluge.common.windows_check() or deluge.common.osx_check(): @@ -326,30 +326,30 @@ class SystemTray(component.Component): self.tray_menu.popup(None, None, popup_function, button, activate_time, status_icon) def on_menuitem_show_deluge_activate(self, menuitem): - log.debug("on_menuitem_show_deluge_activate") + log.debug('on_menuitem_show_deluge_activate') if menuitem.get_active() and not self.window.visible(): self.window.present() elif not menuitem.get_active() and self.window.visible(): self.window.hide() def on_menuitem_add_torrent_activate(self, menuitem): - log.debug("on_menuitem_add_torrent_activate") - component.get("AddTorrentDialog").show() + log.debug('on_menuitem_add_torrent_activate') + component.get('AddTorrentDialog').show() def on_menuitem_pause_session_activate(self, menuitem): - log.debug("on_menuitem_pause_session_activate") + log.debug('on_menuitem_pause_session_activate') client.core.pause_session() def on_menuitem_resume_session_activate(self, menuitem): - log.debug("on_menuitem_resume_session_activate") + log.debug('on_menuitem_resume_session_activate') client.core.resume_session() def on_menuitem_quit_activate(self, menuitem): - log.debug("on_menuitem_quit_activate") + log.debug('on_menuitem_quit_activate') self.window.quit() def on_menuitem_quitdaemon_activate(self, menuitem): - log.debug("on_menuitem_quitdaemon_activate") + log.debug('on_menuitem_quitdaemon_activate') self.window.quit(shutdown=True) def on_tray_setbwdown(self, widget, data=None): @@ -357,28 +357,28 @@ class SystemTray(component.Component): # ignore previous radiomenuitem value if not widget.get_active(): return - self.setbwlimit(widget, _("Download Speed Limit"), _("Set the maximum download speed"), - "max_download_speed", "tray_download_speed_list", self.max_download_speed, - "downloading.svg") + self.setbwlimit(widget, _('Download Speed Limit'), _('Set the maximum download speed'), + 'max_download_speed', 'tray_download_speed_list', self.max_download_speed, + 'downloading.svg') def on_tray_setbwup(self, widget, data=None): if isinstance(widget, gtk.RadioMenuItem): # ignore previous radiomenuitem value if not widget.get_active(): return - self.setbwlimit(widget, _("Upload Speed Limit"), _("Set the maximum upload speed"), - "max_upload_speed", "tray_upload_speed_list", self.max_upload_speed, - "seeding.svg") + self.setbwlimit(widget, _('Upload Speed Limit'), _('Set the maximum upload speed'), + 'max_upload_speed', 'tray_upload_speed_list', self.max_upload_speed, + 'seeding.svg') def _on_window_hide(self, widget, data=None): """_on_window_hide - update the menuitem's status""" - log.debug("_on_window_hide") - self.builder.get_object("menuitem_show_deluge").set_active(False) + log.debug('_on_window_hide') + self.builder.get_object('menuitem_show_deluge').set_active(False) def _on_window_show(self, widget, data=None): """_on_window_show - update the menuitem's status""" - log.debug("_on_window_show") - self.builder.get_object("menuitem_show_deluge").set_active(True) + log.debug('_on_window_show') + self.builder.get_object('menuitem_show_deluge').set_active(True) def setbwlimit(self, widget, header, text, core_key, ui_key, default, image): """Sets the bandwidth limit based on the user selection.""" @@ -391,10 +391,10 @@ class SystemTray(component.Component): # Set the config in the core client.core.set_config({core_key: value}) - if widget.get_name() == "unlimited": + if widget.get_name() == 'unlimited': set_value(-1) - elif widget.get_name() == "other": - dialog = dialogs.OtherDialog(header, text, _("K/s"), image, default) + elif widget.get_name() == 'other': + dialog = dialogs.OtherDialog(header, text, _('K/s'), image, default) dialog.run().addCallback(set_value) else: - set_value(widget.get_children()[0].get_text().split(" ")[0]) + set_value(widget.get_children()[0].get_text().split(' ')[0]) diff --git a/deluge/ui/gtkui/tab_data_funcs.py b/deluge/ui/gtkui/tab_data_funcs.py index ef87de4ed..fcf2249b2 100644 --- a/deluge/ui/gtkui/tab_data_funcs.py +++ b/deluge/ui/gtkui/tab_data_funcs.py @@ -11,30 +11,30 @@ from deluge.common import fdate, fsize, fspeed, ftime def ftotal_sized(first, second): - return "%s (%s)" % (fsize(first, shortform=True), fsize(second, shortform=True)) + return '%s (%s)' % (fsize(first, shortform=True), fsize(second, shortform=True)) def fratio(value): - return ("%.3f" % value).rstrip('0').rstrip('.') if value > 0 else "∞" + return ('%.3f' % value).rstrip('0').rstrip('.') if value > 0 else '∞' def fpcnt(value, state, message): textstr = _(state) - if state not in ("Error", "Seeding") and value < 100: + if state not in ('Error', 'Seeding') and value < 100: textstr = ('%s %.2f' % (textstr, value)).rstrip('0').rstrip('.') + '%' - elif state == "Error": - textstr = _("%s: %s") % (textstr, message) + elif state == 'Error': + textstr = _('%s: %s') % (textstr, message) return textstr def fspeed_max(value, max_value=-1): value = fspeed(value, shortform=True) - return "%s (%s %s)" % (value, max_value, _("K/s")) if max_value > -1 else value + return '%s (%s %s)' % (value, max_value, _('K/s')) if max_value > -1 else value def fdate_or_never(value): """Display value as date, eg 05/05/08 or Never""" - return fdate(value, date_only=True) if value > 0 else _("Never") + return fdate(value, date_only=True) if value > 0 else _('Never') def fdate_or_dash(value): @@ -42,12 +42,12 @@ def fdate_or_dash(value): if value > 0.0: return fdate(value) else: - return "-" + return '-' def ftime_or_dash(value): """Display value as time, eg 2h 30m or dash""" - return ftime(value) if value > 0 else "-" + return ftime(value) if value > 0 else '-' def fseed_rank_or_dash(seed_rank, seeding_time): @@ -55,11 +55,11 @@ def fseed_rank_or_dash(seed_rank, seeding_time): if seeding_time > 0: if seed_rank >= 1000: - return "%ik" % (seed_rank // 1000) + return '%ik' % (seed_rank // 1000) else: return str(seed_rank) else: - return "-" + return '-' def flast_active(time_since_download, time_since_upload): @@ -68,17 +68,17 @@ def flast_active(time_since_download, time_since_upload): try: last_time_since = min((x for x in (time_since_download, time_since_upload) if x != -1)) except ValueError: - return "-" + return '-' else: return ftime(last_time_since) def fpieces_num_size(num_pieces, piece_size): - return "%s (%s)" % (num_pieces, fsize(piece_size, precision=0)) + return '%s (%s)' % (num_pieces, fsize(piece_size, precision=0)) def fcount(value): - return "%s" % len(value) + return '%s' % len(value) def ftranslate(text): @@ -89,4 +89,4 @@ def ftranslate(text): def fyes_no(value): """Return Yes or No to bool value""" - return _("Yes") if value else _("No") + return _('Yes') if value else _('No') diff --git a/deluge/ui/gtkui/toolbar.py b/deluge/ui/gtkui/toolbar.py index 2a78f4b7f..ffde58ec4 100644 --- a/deluge/ui/gtkui/toolbar.py +++ b/deluge/ui/gtkui/toolbar.py @@ -23,39 +23,39 @@ log = logging.getLogger(__name__) class ToolBar(component.Component): def __init__(self): - component.Component.__init__(self, "ToolBar") - log.debug("ToolBar Init..") - self.window = component.get("MainWindow") - self.toolbar = self.window.get_builder().get_object("toolbar") - self.config = ConfigManager("gtkui.conf") + component.Component.__init__(self, 'ToolBar') + log.debug('ToolBar Init..') + self.window = component.get('MainWindow') + self.toolbar = self.window.get_builder().get_object('toolbar') + self.config = ConfigManager('gtkui.conf') # Connect main window Signals # self.window.connect_signals({ - "on_toolbutton_add_clicked": self.on_toolbutton_add_clicked, - "on_toolbutton_remove_clicked": self.on_toolbutton_remove_clicked, - "on_toolbutton_pause_clicked": self.on_toolbutton_pause_clicked, - "on_toolbutton_resume_clicked": self.on_toolbutton_resume_clicked, - "on_toolbutton_preferences_clicked": self.on_toolbutton_preferences_clicked, - "on_toolbutton_connectionmanager_clicked": self.on_toolbutton_connectionmanager_clicked, - "on_toolbutton_queue_up_clicked": self.on_toolbutton_queue_up_clicked, - "on_toolbutton_queue_down_clicked": self.on_toolbutton_queue_down_clicked + 'on_toolbutton_add_clicked': self.on_toolbutton_add_clicked, + 'on_toolbutton_remove_clicked': self.on_toolbutton_remove_clicked, + 'on_toolbutton_pause_clicked': self.on_toolbutton_pause_clicked, + 'on_toolbutton_resume_clicked': self.on_toolbutton_resume_clicked, + 'on_toolbutton_preferences_clicked': self.on_toolbutton_preferences_clicked, + 'on_toolbutton_connectionmanager_clicked': self.on_toolbutton_connectionmanager_clicked, + 'on_toolbutton_queue_up_clicked': self.on_toolbutton_queue_up_clicked, + 'on_toolbutton_queue_down_clicked': self.on_toolbutton_queue_down_clicked }) self.change_sensitivity = [ - "toolbutton_add", - "toolbutton_remove", - "toolbutton_pause", - "toolbutton_resume", - "toolbutton_queue_up", - "toolbutton_queue_down", - "toolbutton_filter", - "find_menuitem" + 'toolbutton_add', + 'toolbutton_remove', + 'toolbutton_pause', + 'toolbutton_resume', + 'toolbutton_queue_up', + 'toolbutton_queue_down', + 'toolbutton_filter', + 'find_menuitem' ] # Hide if necessary - self.visible(self.config["show_toolbar"]) + self.visible(self.config['show_toolbar']) def start(self): - self.window.get_builder().get_object("toolbutton_connectionmanager").set_visible( - not self.config["standalone"]) + self.window.get_builder().get_object('toolbutton_connectionmanager').set_visible( + not self.config['standalone']) for widget in self.change_sensitivity: self.window.get_builder().get_object(widget).set_sensitive(True) @@ -70,7 +70,7 @@ class ToolBar(component.Component): else: self.toolbar.hide() - self.config["show_toolbar"] = visible + self.config['show_toolbar'] = visible def add_toolbutton(self, callback, label=None, image=None, stock=None, tooltip=None): """Adds a toolbutton to the toolbar""" @@ -84,7 +84,7 @@ class ToolBar(component.Component): if tooltip is not None: toolbutton.set_tooltip_text(tooltip) - toolbutton.connect("clicked", callback) + toolbutton.connect('clicked', callback) self.toolbar.insert(toolbutton, -1) toolbutton.show_all() @@ -109,33 +109,33 @@ class ToolBar(component.Component): # Callbacks (Uses the menubar's callback) # def on_toolbutton_add_clicked(self, data): - log.debug("on_toolbutton_add_clicked") - component.get("MenuBar").on_menuitem_addtorrent_activate(data) + log.debug('on_toolbutton_add_clicked') + component.get('MenuBar').on_menuitem_addtorrent_activate(data) def on_toolbutton_remove_clicked(self, data): - log.debug("on_toolbutton_remove_clicked") - component.get("MenuBar").on_menuitem_remove_activate(data) + log.debug('on_toolbutton_remove_clicked') + component.get('MenuBar').on_menuitem_remove_activate(data) def on_toolbutton_pause_clicked(self, data): - log.debug("on_toolbutton_pause_clicked") - component.get("MenuBar").on_menuitem_pause_activate(data) + log.debug('on_toolbutton_pause_clicked') + component.get('MenuBar').on_menuitem_pause_activate(data) def on_toolbutton_resume_clicked(self, data): - log.debug("on_toolbutton_resume_clicked") - component.get("MenuBar").on_menuitem_resume_activate(data) + log.debug('on_toolbutton_resume_clicked') + component.get('MenuBar').on_menuitem_resume_activate(data) def on_toolbutton_preferences_clicked(self, data): - log.debug("on_toolbutton_preferences_clicked") - component.get("MenuBar").on_menuitem_preferences_activate(data) + log.debug('on_toolbutton_preferences_clicked') + component.get('MenuBar').on_menuitem_preferences_activate(data) def on_toolbutton_connectionmanager_clicked(self, data): - log.debug("on_toolbutton_connectionmanager_clicked") - component.get("MenuBar").on_menuitem_connectionmanager_activate(data) + log.debug('on_toolbutton_connectionmanager_clicked') + component.get('MenuBar').on_menuitem_connectionmanager_activate(data) def on_toolbutton_queue_up_clicked(self, data): - log.debug("on_toolbutton_queue_up_clicked") - component.get("MenuBar").on_menuitem_queue_up_activate(data) + log.debug('on_toolbutton_queue_up_clicked') + component.get('MenuBar').on_menuitem_queue_up_activate(data) def on_toolbutton_queue_down_clicked(self, data): - log.debug("on_toolbutton_queue_down_clicked") - component.get("MenuBar").on_menuitem_queue_down_activate(data) + log.debug('on_toolbutton_queue_down_clicked') + component.get('MenuBar').on_menuitem_queue_down_activate(data) diff --git a/deluge/ui/gtkui/torrentdetails.py b/deluge/ui/gtkui/torrentdetails.py index 0db1023cb..3082659e1 100644 --- a/deluge/ui/gtkui/torrentdetails.py +++ b/deluge/ui/gtkui/torrentdetails.py @@ -39,7 +39,7 @@ class Tab(object): def get_tab_label(self): parent = self._tab_label.get_parent() - log.debug("parent: %s", parent) + log.debug('parent: %s', parent) if parent is not None: parent.remove(self._tab_label) @@ -53,23 +53,23 @@ class Tab(object): args = [status[key] for key in widget[2]] txt = widget[1](*args) except KeyError as ex: - log.warn("Unable to get status value: %s", ex) - txt = "" + log.warn('Unable to get status value: %s', ex) + txt = '' return txt class TorrentDetails(component.Component): def __init__(self): - component.Component.__init__(self, "TorrentDetails", interval=2) - self.window = component.get("MainWindow") + component.Component.__init__(self, 'TorrentDetails', interval=2) + self.window = component.get('MainWindow') builder = self.window.get_builder() - self.notebook = builder.get_object("torrent_info") + self.notebook = builder.get_object('torrent_info') # This is the menu item we'll attach the tabs checklist menu to - self.menu_tabs = builder.get_object("menu_tabs") + self.menu_tabs = builder.get_object('menu_tabs') - self.notebook.connect("switch-page", self._on_switch_page) + self.notebook.connect('switch-page', self._on_switch_page) # Tabs holds references to the Tab objects by their name self.tabs = {} @@ -83,32 +83,32 @@ class TorrentDetails(component.Component): from deluge.ui.gtkui.trackers_tab import TrackersTab default_tabs = { - "Status": StatusTab, - "Details": DetailsTab, - "Files": FilesTab, - "Peers": PeersTab, - "Options": OptionsTab, - "Trackers": TrackersTab + 'Status': StatusTab, + 'Details': DetailsTab, + 'Files': FilesTab, + 'Peers': PeersTab, + 'Options': OptionsTab, + 'Trackers': TrackersTab } # tab_name, visible default_order = [ - ("Status", True), - ("Details", True), - ("Options", True), - ("Files", True), - ("Peers", True), - ("Trackers", True) + ('Status', True), + ('Details', True), + ('Options', True), + ('Files', True), + ('Peers', True), + ('Trackers', True) ] self.translate_tabs = { - "All": _("_All"), - "Status": _("_Status"), - "Details": _("_Details"), - "Files": _("_Files"), - "Peers": _("_Peers"), - "Options": _("_Options"), - "Trackers": _("_Trackers") + 'All': _('_All'), + 'Status': _('_Status'), + 'Details': _('_Details'), + 'Files': _('_Files'), + 'Peers': _('_Peers'), + 'Options': _('_Options'), + 'Trackers': _('_Trackers') } # Get the state from saved file @@ -117,7 +117,7 @@ class TorrentDetails(component.Component): if state: for item in state: if not isinstance(item, tuple): - log.debug("Old tabs.state, using default..") + log.debug('Old tabs.state, using default..') state = None break @@ -127,7 +127,7 @@ class TorrentDetails(component.Component): state = default_order # We need to rename the tab in the state for backwards compat - self.state = [(tab_name.replace("Statistics", "Status"), visible) for tab_name, visible in state] + self.state = [(tab_name.replace('Statistics', 'Status'), visible) for tab_name, visible in state] for tab in default_tabs.itervalues(): self.add_tab(tab(), generate_menu=False) @@ -142,14 +142,14 @@ class TorrentDetails(component.Component): weights = sorted([(tab.weight, name) for name, tab in self.tabs.iteritems() if tab.is_visible]) - log.debug("weights: %s", weights) - log.debug("weight of tab: %s", weight) + log.debug('weights: %s', weights) + log.debug('weight of tab: %s', weight) position = -1 for w, name in weights: if w >= weight: position = self.tabs[name].position - log.debug("Found pos %d", position) + log.debug('Found pos %d', position) break return position @@ -177,14 +177,14 @@ class TorrentDetails(component.Component): tab.is_visible = True # add the tab at position guided by the 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( tab.get_child_widget(), tab.get_tab_label(), insert_pos) - log.debug("Tab inserted at %d", pos) + log.debug('Tab inserted at %d', pos) tab.position = pos - if not self.notebook.get_property("visible"): + if not self.notebook.get_property('visible'): # If the notebook isn't visible, show it self.visible(True) else: @@ -218,13 +218,13 @@ class TorrentDetails(component.Component): def hide_all_tabs(self): """Hides all tabs""" - log.debug("n_pages: %s", self.notebook.get_n_pages()) + log.debug('n_pages: %s', self.notebook.get_n_pages()) for n in xrange(self.notebook.get_n_pages() - 1, -1, -1): self.notebook.remove_page(n) for tab in self.tabs: self.tabs[tab].is_visible = False - log.debug("n_pages: %s", self.notebook.get_n_pages()) + log.debug('n_pages: %s', self.notebook.get_n_pages()) self.generate_menu() self.visible(False) @@ -249,12 +249,12 @@ class TorrentDetails(component.Component): self.visible(show) def show_tab(self, tab_name, generate_menu=True): - log.debug("%s\n%s\n%s", self.tabs[tab_name].get_child_widget(), + log.debug('%s\n%s\n%s', self.tabs[tab_name].get_child_widget(), self.tabs[tab_name].get_tab_label(), self.tabs[tab_name].position) position = self.tab_insert_position(self.tabs[tab_name].weight) - log.debug("position: %s", position) + log.debug('position: %s', position) self.notebook.insert_page( self.tabs[tab_name].get_child_widget(), self.tabs[tab_name].get_tab_label(), @@ -269,8 +269,8 @@ class TorrentDetails(component.Component): """Generates the checklist menu for all the tabs and attaches it""" menu = gtk.Menu() # Create 'All' menuitem and a separator - menuitem = gtk.CheckMenuItem(self.translate_tabs["All"], True) - menuitem.set_name("All") + menuitem = gtk.CheckMenuItem(self.translate_tabs['All'], True) + menuitem.set_name('All') all_tabs = True for key in self.tabs: @@ -278,7 +278,7 @@ class TorrentDetails(component.Component): all_tabs = False break menuitem.set_active(all_tabs) - menuitem.connect("toggled", self._on_menuitem_toggled) + menuitem.connect('toggled', self._on_menuitem_toggled) menu.append(menuitem) @@ -295,7 +295,7 @@ class TorrentDetails(component.Component): menuitem = gtk.CheckMenuItem(self.translate_tabs[name], True) menuitem.set_name(name) menuitem.set_active(self.tabs[name].is_visible) - menuitem.connect("toggled", self._on_menuitem_toggled) + menuitem.connect('toggled', self._on_menuitem_toggled) menu.append(menuitem) self.menu_tabs.set_submenu(menu) @@ -310,7 +310,7 @@ class TorrentDetails(component.Component): def set_tab_visible(self, tab_name, visible): """Sets the tab to visible""" - log.debug("set_tab_visible name: %s visible: %s", tab_name, visible) + log.debug('set_tab_visible name: %s visible: %s', tab_name, visible) if visible and not self.tabs[tab_name].is_visible: self.show_tab(tab_name) elif not visible and self.tabs[tab_name].is_visible: @@ -343,11 +343,11 @@ class TorrentDetails(component.Component): self.save_state() def update(self, page_num=None): - if len(component.get("TorrentView").get_selected_torrents()) == 0: + if len(component.get('TorrentView').get_selected_torrents()) == 0: # No torrents selected, so just clear self.clear() - if self.notebook.get_property("visible"): + if self.notebook.get_property('visible'): if page_num is None: page_num = self.notebook.get_current_page() try: @@ -373,7 +373,7 @@ class TorrentDetails(component.Component): if name: self.tabs[name].clear() except Exception as ex: - log.debug("Unable to clear torrentdetails: %s", ex) + log.debug('Unable to clear torrentdetails: %s', ex) def _on_switch_page(self, notebook, page, page_num): self.update(page_num) @@ -382,7 +382,7 @@ class TorrentDetails(component.Component): def _on_menuitem_toggled(self, widget): # Get the tab name name = widget.get_name() - if name == "All": + if name == 'All': if widget.get_active(): self.show_all_tabs() else: @@ -397,13 +397,13 @@ class TorrentDetails(component.Component): # Leave tabs we dont know anything about it the state as they # might come from a plugin 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: self.state[i] = (name, self.tabs[name].is_visible) - log.debug("Set to %s", self.state[i]) + log.debug('Set to %s', self.state[i]) state = self.state - save_pickled_state_file("tabs.state", state) + save_pickled_state_file('tabs.state', state) def load_state(self): - return load_pickled_state_file("tabs.state") + return load_pickled_state_file('tabs.state') diff --git a/deluge/ui/gtkui/torrentview.py b/deluge/ui/gtkui/torrentview.py index e2b4def65..2b0afd6a2 100644 --- a/deluge/ui/gtkui/torrentview.py +++ b/deluge/ui/gtkui/torrentview.py @@ -101,10 +101,10 @@ class SearchBox(object): self.visible = False self.search_pending = self.prefiltered = None - self.search_box = self.window.main_builder.get_object("search_box") - self.search_torrents_entry = self.window.main_builder.get_object("search_torrents_entry") - self.close_search_button = self.window.main_builder.get_object("close_search_button") - self.match_search_button = self.window.main_builder.get_object("search_torrents_match") + self.search_box = self.window.main_builder.get_object('search_box') + self.search_torrents_entry = self.window.main_builder.get_object('search_torrents_entry') + self.close_search_button = self.window.main_builder.get_object('close_search_button') + self.match_search_button = self.window.main_builder.get_object('search_torrents_match') self.window.connect_signals(self) def show(self): @@ -123,8 +123,8 @@ class SearchBox(object): self.search_pending.cancel() if self.prefiltered: - filter_column = self.torrentview.columns["filter"].column_indices[0] - torrent_id_column = self.torrentview.columns["torrent_id"].column_indices[0] + filter_column = self.torrentview.columns['filter'].column_indices[0] + torrent_id_column = self.torrentview.columns['torrent_id'].column_indices[0] for row in self.torrentview.liststore: torrent_id = row[torrent_id_column] @@ -135,7 +135,7 @@ class SearchBox(object): self.prefiltered = None - self.search_torrents_entry.set_text("") + self.search_torrents_entry.set_text('') if self.torrentview.filter and 'name' in self.torrentview.filter: self.torrentview.filter.pop('name', None) self.search_pending = reactor.callLater(0.5, self.torrentview.update) @@ -160,9 +160,9 @@ class SearchBox(object): self.prefilter_torrentview() def prefilter_torrentview(self): - filter_column = self.torrentview.columns["filter"].column_indices[0] - torrent_id_column = self.torrentview.columns["torrent_id"].column_indices[0] - torrent_name_column = self.torrentview.columns[_("Name")].column_indices[1] + filter_column = self.torrentview.columns['filter'].column_indices[0] + torrent_id_column = self.torrentview.columns['torrent_id'].column_indices[0] + torrent_name_column = self.torrentview.columns[_('Name')].column_indices[1] match_case = self.match_search_button.get_active() if match_case: @@ -224,11 +224,11 @@ class SearchBox(object): class TorrentView(ListView, component.Component): """TorrentView handles the listing of torrents.""" def __init__(self): - component.Component.__init__(self, "TorrentView", interval=2, depend=["SessionProxy"]) - self.window = component.get("MainWindow") + component.Component.__init__(self, 'TorrentView', interval=2, depend=['SessionProxy']) + self.window = component.get('MainWindow') # Call the ListView constructor - ListView.__init__(self, self.window.main_builder.get_object("torrent_view"), "torrentview.state") - log.debug("TorrentView Init..") + ListView.__init__(self, self.window.main_builder.get_object('torrent_view'), 'torrentview.state') + log.debug('TorrentView Init..') # If we have gotten the state yet self.got_state = False @@ -240,68 +240,68 @@ class TorrentView(ListView, component.Component): self.prev_status = {} # Register the columns menu with the listview so it gets updated accordingly. - self.register_checklist_menu(self.window.main_builder.get_object("menu_columns")) + self.register_checklist_menu(self.window.main_builder.get_object('menu_columns')) # Add the columns to the listview - self.add_text_column("torrent_id", hidden=True, unique=True) - self.add_bool_column("dirty", hidden=True) - self.add_func_column("#", funcs.cell_data_queue, [int], - status_field=["queue"], + self.add_text_column('torrent_id', hidden=True, unique=True) + self.add_bool_column('dirty', hidden=True) + self.add_func_column('#', funcs.cell_data_queue, [int], + status_field=['queue'], sort_func=queue_column_sort) - self.add_texticon_column(_("Name"), - status_field=["state", "name"], + self.add_texticon_column(_('Name'), + status_field=['state', 'name'], function=funcs.cell_data_statusicon, default_sort=True) - self.add_func_column(_("Size"), funcs.cell_data_size, + self.add_func_column(_('Size'), funcs.cell_data_size, [gobject.TYPE_UINT64], - status_field=["total_wanted"]) - self.add_func_column(_("Downloaded"), funcs.cell_data_size, + status_field=['total_wanted']) + self.add_func_column(_('Downloaded'), funcs.cell_data_size, [gobject.TYPE_UINT64], - status_field=["all_time_download"], default=False) - self.add_func_column(_("Uploaded"), funcs.cell_data_size, + status_field=['all_time_download'], default=False) + self.add_func_column(_('Uploaded'), funcs.cell_data_size, [gobject.TYPE_UINT64], - status_field=["total_uploaded"], default=False) - self.add_func_column(_("Remaining"), funcs.cell_data_size, [gobject.TYPE_UINT64], - status_field=["total_remaining"], default=False) - self.add_progress_column(_("Progress"), - status_field=["progress", "state"], + status_field=['total_uploaded'], default=False) + self.add_func_column(_('Remaining'), funcs.cell_data_size, [gobject.TYPE_UINT64], + status_field=['total_remaining'], default=False) + self.add_progress_column(_('Progress'), + status_field=['progress', 'state'], col_types=[float, str], function=funcs.cell_data_progress, sort_func=progress_sort) - self.add_func_column(_("Seeds"), funcs.cell_data_peer, [int, int], - status_field=["num_seeds", "total_seeds"], + self.add_func_column(_('Seeds'), funcs.cell_data_peer, [int, int], + status_field=['num_seeds', 'total_seeds'], sort_func=seed_peer_column_sort, default=False) - self.add_func_column(_("Peers"), funcs.cell_data_peer, [int, int], - status_field=["num_peers", "total_peers"], + self.add_func_column(_('Peers'), funcs.cell_data_peer, [int, int], + status_field=['num_peers', 'total_peers'], sort_func=seed_peer_column_sort, default=False) - self.add_func_column(_("Seeds:Peers"), funcs.cell_data_ratio_seeds_peers, [float], - status_field=["seeds_peers_ratio"], default=False) - self.add_func_column(_("Down Speed"), funcs.cell_data_speed_down, [int], - status_field=["download_payload_rate"]) - self.add_func_column(_("Up Speed"), funcs.cell_data_speed_up, [int], - status_field=["upload_payload_rate"]) - self.add_func_column(_("Down Limit"), funcs.cell_data_speed_limit_down, [float], - status_field=["max_download_speed"], default=False) - self.add_func_column(_("Up Limit"), funcs.cell_data_speed_limit_up, [float], - status_field=["max_upload_speed"], default=False) - self.add_func_column(_("ETA"), funcs.cell_data_time, [int], - status_field=["eta"], sort_func=eta_column_sort) - self.add_func_column(_("Ratio"), funcs.cell_data_ratio_ratio, [float], - status_field=["ratio"], default=False) - self.add_func_column(_("Avail"), funcs.cell_data_ratio_avail, [float], - status_field=["distributed_copies"], default=False) - self.add_func_column(_("Added"), funcs.cell_data_date_added, [int], - status_field=["time_added"], default=False) - self.add_func_column(_("Completed"), funcs.cell_data_date_completed, [int], - status_field=["completed_time"], default=False) - self.add_func_column(_("Complete Seen"), funcs.cell_data_date_or_never, [int], - status_field=["last_seen_complete"], default=False) - self.add_texticon_column(_("Tracker"), function=funcs.cell_data_trackericon, - status_field=["tracker_host", "tracker_host"], default=False) - self.add_text_column(_("Download Folder"), status_field=["download_location"], default=False) - self.add_text_column(_("Owner"), status_field=["owner"], default=False) - self.add_bool_column(_("Shared"), status_field=["shared"], default=False, - tooltip=_("Torrent is shared between other Deluge users or not.")) + self.add_func_column(_('Seeds:Peers'), funcs.cell_data_ratio_seeds_peers, [float], + status_field=['seeds_peers_ratio'], default=False) + self.add_func_column(_('Down Speed'), funcs.cell_data_speed_down, [int], + status_field=['download_payload_rate']) + self.add_func_column(_('Up Speed'), funcs.cell_data_speed_up, [int], + status_field=['upload_payload_rate']) + self.add_func_column(_('Down Limit'), funcs.cell_data_speed_limit_down, [float], + status_field=['max_download_speed'], default=False) + self.add_func_column(_('Up Limit'), funcs.cell_data_speed_limit_up, [float], + status_field=['max_upload_speed'], default=False) + self.add_func_column(_('ETA'), funcs.cell_data_time, [int], + status_field=['eta'], sort_func=eta_column_sort) + self.add_func_column(_('Ratio'), funcs.cell_data_ratio_ratio, [float], + status_field=['ratio'], default=False) + self.add_func_column(_('Avail'), funcs.cell_data_ratio_avail, [float], + status_field=['distributed_copies'], default=False) + self.add_func_column(_('Added'), funcs.cell_data_date_added, [int], + status_field=['time_added'], default=False) + self.add_func_column(_('Completed'), funcs.cell_data_date_completed, [int], + status_field=['completed_time'], default=False) + self.add_func_column(_('Complete Seen'), funcs.cell_data_date_or_never, [int], + status_field=['last_seen_complete'], default=False) + self.add_texticon_column(_('Tracker'), function=funcs.cell_data_trackericon, + status_field=['tracker_host', 'tracker_host'], default=False) + self.add_text_column(_('Download Folder'), status_field=['download_location'], default=False) + self.add_text_column(_('Owner'), status_field=['owner'], default=False) + self.add_bool_column(_('Shared'), status_field=['shared'], default=False, + tooltip=_('Torrent is shared between other Deluge users or not.')) self.restore_columns_order_from_state() # Set filter to None for now @@ -310,21 +310,21 @@ class TorrentView(ListView, component.Component): # Connect Signals # # Connect to the 'button-press-event' to know when to bring up the # torrent menu popup. - self.treeview.connect("button-press-event", self.on_button_press_event) + self.treeview.connect('button-press-event', self.on_button_press_event) # Connect to the 'key-press-event' to know when the bring up the # torrent menu popup via keypress. - self.treeview.connect("key-release-event", self.on_key_press_event) + self.treeview.connect('key-release-event', self.on_key_press_event) # Connect to the 'changed' event of TreeViewSelection to get selection # changes. - self.treeview.get_selection().connect("changed", self.on_selection_changed) + self.treeview.get_selection().connect('changed', self.on_selection_changed) - self.treeview.connect("drag-drop", self.on_drag_drop) - self.treeview.connect("drag_data_received", self.on_drag_data_received) - self.treeview.connect("key-press-event", self.on_key_press_event) - self.treeview.connect("columns-changed", self.on_columns_changed_event) + self.treeview.connect('drag-drop', self.on_drag_drop) + self.treeview.connect('drag_data_received', self.on_drag_data_received) + self.treeview.connect('key-press-event', self.on_key_press_event) + self.treeview.connect('columns-changed', self.on_columns_changed_event) self.search_box = SearchBox(self) - self.permanent_status_keys = ["owner"] + self.permanent_status_keys = ['owner'] self.columns_to_update = [] def start(self): @@ -338,15 +338,15 @@ class TorrentView(ListView, component.Component): if not listview_column.status_field: continue status_fields.extend(listview_column.status_field) - component.get("SessionProxy").get_torrents_status( + component.get('SessionProxy').get_torrents_status( {}, status_fields).addCallback(self._on_session_state) - client.register_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event) - client.register_event_handler("TorrentAddedEvent", self.on_torrentadded_event) - client.register_event_handler("TorrentRemovedEvent", self.on_torrentremoved_event) - client.register_event_handler("SessionPausedEvent", self.on_sessionpaused_event) - client.register_event_handler("SessionResumedEvent", self.on_sessionresumed_event) - client.register_event_handler("TorrentQueueChangedEvent", self.on_torrentqueuechanged_event) + client.register_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event) + client.register_event_handler('TorrentAddedEvent', self.on_torrentadded_event) + client.register_event_handler('TorrentRemovedEvent', self.on_torrentremoved_event) + client.register_event_handler('SessionPausedEvent', self.on_sessionpaused_event) + client.register_event_handler('SessionResumedEvent', self.on_sessionresumed_event) + client.register_event_handler('TorrentQueueChangedEvent', self.on_torrentqueuechanged_event) def _on_session_state(self, state): self.add_rows(state) @@ -360,12 +360,12 @@ class TorrentView(ListView, component.Component): def stop(self): """Stops the torrentview""" # We need to clear the liststore - client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrentstatechanged_event) - client.deregister_event_handler("TorrentAddedEvent", self.on_torrentadded_event) - client.deregister_event_handler("TorrentRemovedEvent", self.on_torrentremoved_event) - client.deregister_event_handler("SessionPausedEvent", self.on_sessionpaused_event) - client.deregister_event_handler("SessionResumedEvent", self.on_sessionresumed_event) - client.deregister_event_handler("TorrentQueueChangedEvent", self.on_torrentqueuechanged_event) + client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrentstatechanged_event) + client.deregister_event_handler('TorrentAddedEvent', self.on_torrentadded_event) + client.deregister_event_handler('TorrentRemovedEvent', self.on_torrentremoved_event) + client.deregister_event_handler('SessionPausedEvent', self.on_sessionpaused_event) + client.deregister_event_handler('SessionResumedEvent', self.on_sessionresumed_event) + client.deregister_event_handler('TorrentQueueChangedEvent', self.on_torrentqueuechanged_event) if self.treeview.get_selection(): self.treeview.get_selection().unselect_all() @@ -383,7 +383,7 @@ class TorrentView(ListView, component.Component): Saves the state of the torrent view. """ if self.window.visible(): - ListView.save_state(self, "torrentview.state") + ListView.save_state(self, 'torrentview.state') def remove_column(self, header): """Removes the column with the name 'header' from the torrentview""" @@ -439,7 +439,7 @@ class TorrentView(ListView, component.Component): # Request the statuses for all these torrent_ids, this is async so we # will deal with the return in a signal callback. - d = component.get("SessionProxy").get_torrents_status( + d = component.get('SessionProxy').get_torrents_status( self.filter, status_keys).addCallback(self._on_get_torrents_status) if select_row: d.addCallback(self.select_first_row) @@ -472,7 +472,7 @@ class TorrentView(ListView, component.Component): def update_view(self, load_new_list=False): """Update the torrent view model with data we've received.""" - filter_column = self.columns["filter"].column_indices[0] + filter_column = self.columns['filter'].column_indices[0] status = self.status if not load_new_list: @@ -491,7 +491,7 @@ class TorrentView(ListView, component.Component): fields_to_update.append((column_index[i], status_field)) for row in self.liststore: - torrent_id = row[self.columns["torrent_id"].column_indices[0]] + torrent_id = row[self.columns['torrent_id'].column_indices[0]] # We expect the torrent_id to be in status and prev_status, # as it will be as long as the list isn't changed by the user @@ -529,7 +529,7 @@ class TorrentView(ListView, component.Component): else: self.treeview.thaw_child_notify() - component.get("MenuBar").update_menu() + component.get('MenuBar').update_menu() self.prev_status = status def _on_get_torrents_status(self, status, select_row=False): @@ -547,9 +547,9 @@ class TorrentView(ListView, component.Component): def add_rows(self, torrent_ids): """Accepts a list of torrent_ids to add to self.liststore""" - torrent_id_column = self.columns["torrent_id"].column_indices[0] - dirty_column = self.columns["dirty"].column_indices[0] - filter_column = self.columns["filter"].column_indices[0] + torrent_id_column = self.columns['torrent_id'].column_indices[0] + dirty_column = self.columns['dirty'].column_indices[0] + filter_column = self.columns['filter'].column_indices[0] for torrent_id in torrent_ids: # Insert a new row to the liststore row = self.liststore.append() @@ -558,7 +558,7 @@ class TorrentView(ListView, component.Component): def remove_row(self, torrent_id): """Removes a row with torrent_id""" for row in self.liststore: - if row[self.columns["torrent_id"].column_indices[0]] == torrent_id: + if row[self.columns['torrent_id'].column_indices[0]] == torrent_id: self.liststore.remove(row.iter) # Force an update of the torrentview self.update() @@ -566,9 +566,9 @@ class TorrentView(ListView, component.Component): def mark_dirty(self, torrent_id=None): for row in self.liststore: - if not torrent_id or row[self.columns["torrent_id"].column_indices[0]] == torrent_id: + if not torrent_id or row[self.columns['torrent_id'].column_indices[0]] == torrent_id: # log.debug("marking %s dirty", torrent_id) - row[self.columns["dirty"].column_indices[0]] = True + row[self.columns['dirty'].column_indices[0]] = True if torrent_id: break @@ -594,16 +594,16 @@ class TorrentView(ListView, component.Component): try: row = self.treeview.get_model().get_iter(path) except Exception as ex: - log.debug("Unable to get iter from path: %s", ex) + log.debug('Unable to get iter from path: %s', ex) continue child_row = self.treeview.get_model().convert_iter_to_child_iter(None, row) child_row = self.treeview.get_model().get_model().convert_iter_to_child_iter(child_row) if self.liststore.iter_is_valid(child_row): try: - value = self.liststore.get_value(child_row, self.columns["torrent_id"].column_indices[0]) + value = self.liststore.get_value(child_row, self.columns['torrent_id'].column_indices[0]) except Exception as ex: - log.debug("Unable to get value from row: %s", ex) + log.debug('Unable to get value from row: %s', ex) else: torrent_ids.append(value) if len(torrent_ids) == 0: @@ -626,7 +626,7 @@ class TorrentView(ListView, component.Component): # Callbacks # def on_button_press_event(self, widget, event): """This is a callback for showing the right-click context menu.""" - log.debug("on_button_press_event") + log.debug('on_button_press_event') # We only care about right-clicks if event.button == 3: x, y = event.get_coords() @@ -636,30 +636,30 @@ class TorrentView(ListView, component.Component): row = self.model_filter.get_iter(path[0]) if self.get_selected_torrents(): - if (self.model_filter.get_value(row, self.columns["torrent_id"].column_indices[0]) + if (self.model_filter.get_value(row, self.columns['torrent_id'].column_indices[0]) not in self.get_selected_torrents()): self.treeview.get_selection().unselect_all() self.treeview.get_selection().select_iter(row) else: self.treeview.get_selection().select_iter(row) - torrentmenu = component.get("MenuBar").torrentmenu + torrentmenu = component.get('MenuBar').torrentmenu torrentmenu.popup(None, None, None, event.button, event.time) return True def on_selection_changed(self, treeselection): """This callback is know when the selection has changed.""" - log.debug("on_selection_changed") - component.get("TorrentDetails").update() - component.get("MenuBar").update_menu() + log.debug('on_selection_changed') + component.get('TorrentDetails').update() + component.get('MenuBar').update_menu() def on_drag_drop(self, widget, drag_context, x, y, timestamp): - widget.stop_emission("drag-drop") + widget.stop_emission('drag-drop') def on_drag_data_received(self, widget, drag_context, x, y, selection_data, info, timestamp): - widget.stop_emission("drag_data_received") + widget.stop_emission('drag_data_received') def on_columns_changed_event(self, treeview): - log.debug("Treeview Columns Changed") + log.debug('Treeview Columns Changed') self.save_state() def on_torrentadded_event(self, torrent_id, from_state): @@ -672,7 +672,7 @@ class TorrentView(ListView, component.Component): def on_torrentstatechanged_event(self, torrent_id, state): # Update the torrents state for row in self.liststore: - if torrent_id != row[self.columns["torrent_id"].column_indices[0]]: + if torrent_id != row[self.columns['torrent_id'].column_indices[0]]: continue for name in self.columns_to_update: @@ -688,7 +688,7 @@ class TorrentView(ListView, component.Component): # We have a filter set, let's see if theres anything to hide # and remove from status if torrent_id in self.status and self.status[torrent_id]['state'] != state: - row[self.columns["filter"].column_indices[0]] = False + row[self.columns['filter'].column_indices[0]] = False del self.status[torrent_id] self.mark_dirty(torrent_id) @@ -714,7 +714,7 @@ class TorrentView(ListView, component.Component): return func(event) def keypress_delete(self, event): - log.debug("keypress_delete") + log.debug('keypress_delete') torrents = self.get_selected_torrents() if torrents: if event.state & gtk.gdk.SHIFT_MASK: @@ -723,10 +723,10 @@ class TorrentView(ListView, component.Component): RemoveTorrentDialog(torrents).run() def keypress_menu(self, event): - log.debug("keypress_menu") + log.debug('keypress_menu') if not self.get_selected_torrent(): return - torrentmenu = component.get("MenuBar").torrentmenu + torrentmenu = component.get('MenuBar').torrentmenu torrentmenu.popup(None, None, None, 3, event.time) return True diff --git a/deluge/ui/gtkui/torrentview_data_funcs.py b/deluge/ui/gtkui/torrentview_data_funcs.py index 55d36f644..1727ff392 100644 --- a/deluge/ui/gtkui/torrentview_data_funcs.py +++ b/deluge/ui/gtkui/torrentview_data_funcs.py @@ -20,44 +20,44 @@ import deluge.component as component # Status icons.. Create them from file only once to avoid constantly # re-creating them. -icon_downloading = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("downloading16.png")) -icon_seeding = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("seeding16.png")) -icon_inactive = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("inactive16.png")) -icon_alert = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("alert16.png")) -icon_queued = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("queued16.png")) -icon_checking = gtk.gdk.pixbuf_new_from_file(common.get_pixmap("checking16.png")) +icon_downloading = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('downloading16.png')) +icon_seeding = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('seeding16.png')) +icon_inactive = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('inactive16.png')) +icon_alert = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('alert16.png')) +icon_queued = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('queued16.png')) +icon_checking = gtk.gdk.pixbuf_new_from_file(common.get_pixmap('checking16.png')) # Holds the info for which status icon to display based on TORRENT_STATE ICON_STATE = { - "Allocating": icon_checking, - "Checking": icon_checking, - "Downloading": icon_downloading, - "Seeding": icon_seeding, - "Paused": icon_inactive, - "Error": icon_alert, - "Queued": icon_queued, - "Moving": icon_checking + 'Allocating': icon_checking, + 'Checking': icon_checking, + 'Downloading': icon_downloading, + 'Seeding': icon_seeding, + 'Paused': icon_inactive, + 'Error': icon_alert, + 'Queued': icon_queued, + 'Moving': icon_checking } # Cache the key used to calculate the current value set for the specific cell # renderer. This is much cheaper than fetch the current value and test if # it's equal. func_last_value = { - "cell_data_speed_down": None, - "cell_data_speed_up": None, - "cell_data_time": None, - "cell_data_ratio_seeds_peers": None, - "cell_data_ratio_ratio": None, - "cell_data_ratio_avail": None, - "cell_data_date_added": None, - "cell_data_date_completed": None, - "cell_data_date_or_never": None, - "cell_data_speed_limit_down": None, - "cell_data_speed_limit_up": None, - "cell_data_trackericon": None, - "cell_data_statusicon": None, - "cell_data_queue": None, - "cell_data_progress": [None, None], + 'cell_data_speed_down': None, + 'cell_data_speed_up': None, + 'cell_data_time': None, + 'cell_data_ratio_seeds_peers': None, + 'cell_data_ratio_ratio': None, + 'cell_data_ratio_avail': None, + 'cell_data_date_added': None, + 'cell_data_date_completed': None, + 'cell_data_date_or_never': None, + 'cell_data_speed_limit_down': None, + 'cell_data_speed_limit_up': None, + 'cell_data_trackericon': None, + 'cell_data_statusicon': None, + 'cell_data_queue': None, + 'cell_data_progress': [None, None], } @@ -66,17 +66,17 @@ def cell_data_statusicon(column, cell, model, row, data): try: state = model.get_value(row, data) - if func_last_value["cell_data_statusicon"] == state: + if func_last_value['cell_data_statusicon'] == state: return - func_last_value["cell_data_statusicon"] = state + func_last_value['cell_data_statusicon'] = state icon = ICON_STATE[state] # Supress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed original_filters = warnings.filters[:] - warnings.simplefilter("ignore") + warnings.simplefilter('ignore') try: - cell.set_property("pixbuf", icon) + cell.set_property('pixbuf', icon) finally: warnings.filters = original_filters @@ -106,58 +106,58 @@ def set_icon(icon, cell): # Suppress Warning: g_object_set_qdata: assertion `G_IS_OBJECT (object)' failed with warnings.catch_warnings(): - warnings.simplefilter("ignore") - cell.set_property("pixbuf", pixbuf) + warnings.simplefilter('ignore') + cell.set_property('pixbuf', pixbuf) def cell_data_trackericon(column, cell, model, row, data): host = model[row][data] - if func_last_value["cell_data_trackericon"] == host: + if func_last_value['cell_data_trackericon'] == host: return if host: - if not component.get("TrackerIcons").has(host): + if not component.get('TrackerIcons').has(host): # Set blank icon while waiting for the icon to be loaded set_icon(None, cell) - component.get("TrackerIcons").fetch(host) - func_last_value["cell_data_trackericon"] = None + component.get('TrackerIcons').fetch(host) + func_last_value['cell_data_trackericon'] = None else: - set_icon(component.get("TrackerIcons").get(host), cell) + set_icon(component.get('TrackerIcons').get(host), cell) # Only set the last value when we have found the icon - func_last_value["cell_data_trackericon"] = host + func_last_value['cell_data_trackericon'] = host else: set_icon(None, cell) - func_last_value["cell_data_trackericon"] = None + func_last_value['cell_data_trackericon'] = None def cell_data_progress(column, cell, model, row, data): """Display progress bar with text""" (value, state_str) = model.get(row, *data) - if func_last_value["cell_data_progress"][0] != value: - func_last_value["cell_data_progress"][0] = value - cell.set_property("value", value) + if func_last_value['cell_data_progress'][0] != value: + func_last_value['cell_data_progress'][0] = value + cell.set_property('value', value) # Marked for translate states text are in filtertreeview textstr = _(state_str) - if state_str not in ("Error", "Seeding") and value < 100: - textstr = "%s %i%%" % (textstr, value) + if state_str not in ('Error', 'Seeding') and value < 100: + textstr = '%s %i%%' % (textstr, value) - if func_last_value["cell_data_progress"][1] != textstr: - func_last_value["cell_data_progress"][1] = textstr - cell.set_property("text", textstr) + if func_last_value['cell_data_progress'][1] != textstr: + func_last_value['cell_data_progress'][1] = textstr + cell.set_property('text', textstr) def cell_data_queue(column, cell, model, row, data): value = model.get_value(row, data) - if func_last_value["cell_data_queue"] == value: + if func_last_value['cell_data_queue'] == value: return - func_last_value["cell_data_queue"] = value + func_last_value['cell_data_queue'] = value if value < 0: - cell.set_property("text", "") + cell.set_property('text', '') else: - cell.set_property("text", str(value + 1)) + cell.set_property('text', str(value + 1)) def cell_data_speed(cell, model, row, data, cache_key): @@ -165,7 +165,7 @@ def cell_data_speed(cell, model, row, data, cache_key): try: speed = model.get_value(row, data) except AttributeError: - print("AttributeError") + print('AttributeError') import traceback traceback.print_exc() if func_last_value[cache_key] == speed: @@ -174,19 +174,19 @@ def cell_data_speed(cell, model, row, data, cache_key): if speed > 0: speed_str = common.fspeed(speed, shortform=True) - cell.set_property("markup", "{0} <small>{1}</small>".format(*tuple(speed_str.split()))) + cell.set_property('markup', '{0} <small>{1}</small>'.format(*tuple(speed_str.split()))) else: - cell.set_property("text", "") + cell.set_property('text', '') def cell_data_speed_down(column, cell, model, row, data): """Display value as a speed, eg. 2 KiB/s""" - cell_data_speed(cell, model, row, data, "cell_data_speed_down") + cell_data_speed(cell, model, row, data, 'cell_data_speed_down') def cell_data_speed_up(column, cell, model, row, data): """Display value as a speed, eg. 2 KiB/s""" - cell_data_speed(cell, model, row, data, "cell_data_speed_up") + cell_data_speed(cell, model, row, data, 'cell_data_speed_up') def cell_data_speed_limit(cell, model, row, data, cache_key): @@ -199,17 +199,17 @@ def cell_data_speed_limit(cell, model, row, data, cache_key): if speed > 0: speed_str = common.fspeed(speed * 1024, shortform=True) - cell.set_property("markup", "{0} <small>{1}</small>".format(*tuple(speed_str.split()))) + cell.set_property('markup', '{0} <small>{1}</small>'.format(*tuple(speed_str.split()))) else: - cell.set_property("text", "") + cell.set_property('text', '') def cell_data_speed_limit_down(column, cell, model, row, data): - cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_down") + cell_data_speed_limit(cell, model, row, data, 'cell_data_speed_limit_down') def cell_data_speed_limit_up(column, cell, model, row, data): - cell_data_speed_limit(cell, model, row, data, "cell_data_speed_limit_up") + cell_data_speed_limit(cell, model, row, data, 'cell_data_speed_limit_up') def cell_data_size(column, cell, model, row, data): @@ -231,12 +231,12 @@ def cell_data_peer(column, cell, model, row, data): def cell_data_time(column, cell, model, row, data): """Display value as time, eg 1m10s""" time = model.get_value(row, data) - if func_last_value["cell_data_time"] == time: + if func_last_value['cell_data_time'] == time: return - func_last_value["cell_data_time"] = time + func_last_value['cell_data_time'] = time if time <= 0: - time_str = "" + time_str = '' else: time_str = common.ftime(time) cell.set_property('text', time_str) @@ -249,19 +249,19 @@ def cell_data_ratio(cell, model, row, data, cache_key): if func_last_value[cache_key] == ratio: return func_last_value[cache_key] = ratio - cell.set_property("text", "∞" if ratio < 0 else ("%.1f" % ratio).rstrip("0").rstrip(".")) + cell.set_property('text', '∞' if ratio < 0 else ('%.1f' % ratio).rstrip('0').rstrip('.')) def cell_data_ratio_seeds_peers(column, cell, model, row, data): - cell_data_ratio(cell, model, row, data, "cell_data_ratio_seeds_peers") + cell_data_ratio(cell, model, row, data, 'cell_data_ratio_seeds_peers') def cell_data_ratio_ratio(column, cell, model, row, data): - cell_data_ratio(cell, model, row, data, "cell_data_ratio_ratio") + cell_data_ratio(cell, model, row, data, 'cell_data_ratio_ratio') def cell_data_ratio_avail(column, cell, model, row, data): - cell_data_ratio(cell, model, row, data, "cell_data_ratio_avail") + cell_data_ratio(cell, model, row, data, 'cell_data_ratio_avail') def cell_data_date(column, cell, model, row, data, key): @@ -272,20 +272,20 @@ def cell_data_date(column, cell, model, row, data, key): return func_last_value[key] = date - date_str = common.fdate(date, date_only=True) if date > 0 else "" + date_str = common.fdate(date, date_only=True) if date > 0 else '' cell.set_property('text', date_str) -cell_data_date_added = partial(cell_data_date, key="cell_data_date_added") -cell_data_date_completed = partial(cell_data_date, key="cell_data_date_completed") +cell_data_date_added = partial(cell_data_date, key='cell_data_date_added') +cell_data_date_completed = partial(cell_data_date, key='cell_data_date_completed') def cell_data_date_or_never(column, cell, model, row, data): """Display value as date, eg 05/05/08 or Never""" value = model.get_value(row, data) - if func_last_value["cell_data_date_or_never"] == value: + if func_last_value['cell_data_date_or_never'] == value: return - func_last_value["cell_data_date_or_never"] = value + func_last_value['cell_data_date_or_never'] = value - date_str = common.fdate(value, date_only=True) if value > 0 else _("Never") + date_str = common.fdate(value, date_only=True) if value > 0 else _('Never') cell.set_property('text', date_str) diff --git a/deluge/ui/gtkui/trackers_tab.py b/deluge/ui/gtkui/trackers_tab.py index 36b4b9732..1b4ecb60c 100644 --- a/deluge/ui/gtkui/trackers_tab.py +++ b/deluge/ui/gtkui/trackers_tab.py @@ -22,29 +22,29 @@ class TrackersTab(Tab): Tab.__init__(self) # Get the labels we need to update. # widget name, modifier function, status keys - builder = component.get("MainWindow").get_builder() + builder = component.get('MainWindow').get_builder() - self._name = "Trackers" - self._child_widget = builder.get_object("trackers_tab") - self._tab_label = builder.get_object("trackers_tab_label") + self._name = 'Trackers' + self._child_widget = builder.get_object('trackers_tab') + self._tab_label = builder.get_object('trackers_tab_label') self.label_widgets = [ - (builder.get_object("summary_next_announce"), ftime, ("next_announce",)), - (builder.get_object("summary_tracker"), None, ("tracker_host",)), - (builder.get_object("summary_tracker_status"), ftranslate, ("tracker_status",)), - (builder.get_object("summary_tracker_total"), fcount, ("trackers",)), - (builder.get_object("summary_private"), fyes_no, ("private",)), + (builder.get_object('summary_next_announce'), ftime, ('next_announce',)), + (builder.get_object('summary_tracker'), None, ('tracker_host',)), + (builder.get_object('summary_tracker_status'), ftranslate, ('tracker_status',)), + (builder.get_object('summary_tracker_total'), fcount, ('trackers',)), + (builder.get_object('summary_private'), fyes_no, ('private',)), ] self.status_keys = [status for widget in self.label_widgets for status in widget[2]] - component.get("MainWindow").connect_signals({ - "on_button_edit_trackers_clicked": self._on_button_edit_trackers_clicked, + component.get('MainWindow').connect_signals({ + 'on_button_edit_trackers_clicked': self._on_button_edit_trackers_clicked, }) def update(self): # Get the first selected torrent - selected = component.get("TorrentView").get_selected_torrents() + selected = component.get('TorrentView').get_selected_torrents() # Only use the first torrent in the list or return if None selected if selected: @@ -53,7 +53,7 @@ class TrackersTab(Tab): self.clear() return - session = component.get("SessionProxy") + session = component.get('SessionProxy') session.get_torrent_status(selected, self.status_keys).addCallback(self._on_get_torrent_status) def _on_get_torrent_status(self, status): @@ -69,11 +69,11 @@ class TrackersTab(Tab): def clear(self): for widget in self.label_widgets: - widget[0].set_text("") + widget[0].set_text('') def _on_button_edit_trackers_clicked(self, button): - torrent_id = component.get("TorrentView").get_selected_torrent() + torrent_id = component.get('TorrentView').get_selected_torrent() if torrent_id: from deluge.ui.gtkui.edittrackersdialog import EditTrackersDialog - dialog = EditTrackersDialog(torrent_id, component.get("MainWindow").window) + dialog = EditTrackersDialog(torrent_id, component.get('MainWindow').window) dialog.run() diff --git a/deluge/ui/sessionproxy.py b/deluge/ui/sessionproxy.py index 882de9c19..86606caae 100644 --- a/deluge/ui/sessionproxy.py +++ b/deluge/ui/sessionproxy.py @@ -27,8 +27,8 @@ class SessionProxy(component.Component): """ def __init__(self): - log.debug("SessionProxy init..") - component.Component.__init__(self, "SessionProxy", interval=5) + log.debug('SessionProxy init..') + component.Component.__init__(self, 'SessionProxy', interval=5) # Set the cache time in seconds # This is how long data will be valid before re-fetching from the core @@ -41,9 +41,9 @@ class SessionProxy(component.Component): self.cache_times = {} def start(self): - client.register_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed) - client.register_event_handler("TorrentRemovedEvent", self.on_torrent_removed) - client.register_event_handler("TorrentAddedEvent", self.on_torrent_added) + client.register_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed) + client.register_event_handler('TorrentRemovedEvent', self.on_torrent_removed) + client.register_event_handler('TorrentAddedEvent', self.on_torrent_added) def on_get_session_state(torrent_ids): for torrent_id in torrent_ids: @@ -55,9 +55,9 @@ class SessionProxy(component.Component): return client.core.get_session_state().addCallback(on_get_session_state) def stop(self): - client.deregister_event_handler("TorrentStateChangedEvent", self.on_torrent_state_changed) - client.deregister_event_handler("TorrentRemovedEvent", self.on_torrent_removed) - client.deregister_event_handler("TorrentAddedEvent", self.on_torrent_added) + client.deregister_event_handler('TorrentStateChangedEvent', self.on_torrent_state_changed) + client.deregister_event_handler('TorrentRemovedEvent', self.on_torrent_removed) + client.deregister_event_handler('TorrentAddedEvent', self.on_torrent_added) self.torrents = {} def create_status_dict(self, torrent_ids, keys): @@ -216,21 +216,21 @@ class SessionProxy(component.Component): # We get a list of any torrent_ids with expired status dicts to_fetch = find_torrents_to_fetch(self.torrents.keys()) if to_fetch: - d = client.core.get_torrents_status({"id": to_fetch}, keys, True) + d = client.core.get_torrents_status({'id': to_fetch}, keys, True) return d.addCallback(on_status, self.torrents.keys(), keys) # Don't need to fetch anything return maybeDeferred(self.create_status_dict, self.torrents.keys(), keys) - if len(filter_dict) == 1 and "id" in filter_dict: + if len(filter_dict) == 1 and 'id' in filter_dict: # At this point we should have a filter with just "id" in it - to_fetch = find_torrents_to_fetch(filter_dict["id"]) + to_fetch = find_torrents_to_fetch(filter_dict['id']) if to_fetch: - d = client.core.get_torrents_status({"id": to_fetch}, keys, True) - return d.addCallback(on_status, filter_dict["id"], keys) + d = client.core.get_torrents_status({'id': to_fetch}, keys, True) + return d.addCallback(on_status, filter_dict['id'], keys) else: # Don't need to fetch anything, so just return data from the cache - return maybeDeferred(self.create_status_dict, filter_dict["id"], keys) + return maybeDeferred(self.create_status_dict, filter_dict['id'], keys) else: # This is a keyworded filter so lets just pass it onto the core # XXX: Add more caching here. @@ -239,7 +239,7 @@ class SessionProxy(component.Component): def on_torrent_state_changed(self, torrent_id, state): if torrent_id in self.torrents: - self.torrents[torrent_id][1].setdefault("state", state) + self.torrents[torrent_id][1].setdefault('state', state) self.cache_times.setdefault(torrent_id, {}).update(state=time()) def on_torrent_added(self, torrent_id, from_state): diff --git a/deluge/ui/tracker_icons.py b/deluge/ui/tracker_icons.py index a6ff56bf8..aff27f25c 100644 --- a/deluge/ui/tracker_icons.py +++ b/deluge/ui/tracker_icons.py @@ -45,7 +45,7 @@ class TrackerIcon(object): :type filename: string """ self.filename = os.path.abspath(filename) - self.mimetype = extension_to_mimetype(self.filename.rpartition(".")[2]) + self.mimetype = extension_to_mimetype(self.filename.rpartition('.')[2]) self.data = None self.icon_cache = None @@ -79,7 +79,7 @@ class TrackerIcon(object): :rtype: string """ if not self.data: - with open(self.filename, "rb") as _file: + with open(self.filename, 'rb') as _file: self.data = _file.read() return self.data @@ -124,9 +124,9 @@ class TrackerIcons(Component): can be fetched :type no_icon: string """ - Component.__init__(self, "TrackerIcons") + Component.__init__(self, 'TrackerIcons') if not icon_dir: - icon_dir = get_config_dir("icons") + icon_dir = get_config_dir('icons') self.dir = icon_dir if not os.path.isdir(self.dir): os.makedirs(self.dir) @@ -138,12 +138,12 @@ class TrackerIcons(Component): try: self.icons[host] = TrackerIcon(os.path.join(self.dir, icon)) except KeyError: - log.warning("invalid icon %s", icon) + log.warning('invalid icon %s', icon) if no_icon: self.icons[None] = TrackerIcon(no_icon) else: self.icons[None] = None - self.icons[""] = self.icons[None] + self.icons[''] = self.icons[None] self.pending = {} self.redirects = {} @@ -227,7 +227,7 @@ class TrackerIcons(Component): """ if not url: url = self.host_to_url(host) - log.debug("Downloading %s %s", host, url) + log.debug('Downloading %s %s', host, url) tmp_fd, tmp_file = mkstemp(prefix='deluge_ticon.') os.close(tmp_fd) return download_file(url, tmp_file, force_filename=True, handle_redirects=False) @@ -241,7 +241,7 @@ class TrackerIcons(Component): :returns: the page that finished downloading :rtype: string """ - log.debug("Finished downloading %s", page) + log.debug('Finished downloading %s', page) return page def on_download_page_fail(self, f, host): @@ -257,11 +257,11 @@ class TrackerIcons(Component): :rtype: Deferred or Failure """ error_msg = f.getErrorMessage() - log.debug("Error downloading page: %s", error_msg) + log.debug('Error downloading page: %s', error_msg) d = f if f.check(PageRedirect): # Handle redirect errors - location = urljoin(self.host_to_url(host), error_msg.split(" to ")[1]) + location = urljoin(self.host_to_url(host), error_msg.split(' to ')[1]) self.redirects[host] = url_to_host(location) d = self.download_page(host, url=location) d.addCallbacks(self.on_download_page_complete, self.on_download_page_fail, @@ -279,7 +279,7 @@ class TrackerIcons(Component): :returns: a Deferred which callbacks a list of available favicons (url, type) :rtype: Deferred """ - with open(page, "r") as _file: + with open(page, 'r') as _file: parser = FaviconParser() for line in _file: parser.feed(line) @@ -304,10 +304,10 @@ class TrackerIcons(Component): :returns: the icons that were extracted from the page :rtype: list """ - log.debug("Parse Complete, got icons for %s: %s", host, icons) + log.debug('Parse Complete, got icons for %s: %s', host, icons) url = self.host_to_url(host) icons = [(urljoin(url, icon), mimetype) for icon, mimetype in icons] - log.debug("Icon urls from %s: %s", host, icons) + log.debug('Icon urls from %s: %s', host, icons) return icons def on_parse_fail(self, f): @@ -320,7 +320,7 @@ class TrackerIcons(Component): else the original failure :rtype: Deferred or Failure """ - log.debug("Error parsing page: %s", f.getErrorMessage()) + log.debug('Error parsing page: %s', f.getErrorMessage()) return f def download_icon(self, icons, host): @@ -335,7 +335,7 @@ class TrackerIcons(Component): :rtype: Deferred """ if len(icons) == 0: - raise NoIconsError("empty icons list") + raise NoIconsError('empty icons list') (url, mimetype) = icons.pop(0) d = download_file(url, os.path.join(self.dir, host_to_icon_name(host, mimetype)), force_filename=True) @@ -364,7 +364,7 @@ class TrackerIcons(Component): raise InvalidIconError(ex) else: if os.stat(icon_name).st_size == 0: - raise InvalidIconError("empty icon") + raise InvalidIconError('empty icon') return icon_name @@ -379,7 +379,7 @@ class TrackerIcons(Component): :returns: the icon that finished downloading :rtype: TrackerIcon """ - log.debug("Successfully downloaded from %s: %s", host, icon_name) + log.debug('Successfully downloaded from %s: %s', host, icon_name) icon = TrackerIcon(icon_name) return icon @@ -400,12 +400,12 @@ class TrackerIcons(Component): if not icons: icons = [] error_msg = f.getErrorMessage() - log.debug("Error downloading icon from %s: %s", host, error_msg) + log.debug('Error downloading icon from %s: %s', host, error_msg) d = f if f.check(PageRedirect): # Handle redirect errors - location = urljoin(self.host_to_url(host), error_msg.split(" to ")[1]) - d = self.download_icon([(location, extension_to_mimetype(location.rpartition(".")[2]))] + icons, host) + location = urljoin(self.host_to_url(host), error_msg.split(' to ')[1]) + d = self.download_icon([(location, extension_to_mimetype(location.rpartition('.')[2]))] + icons, host) if not icons: d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail, callbackArgs=(host,), errbackArgs=(host,)) @@ -413,8 +413,8 @@ class TrackerIcons(Component): d = self.download_icon(icons, host) elif f.check(NoIconsError, HTMLParseError): # No icons, try favicon.ico as an act of desperation - d = self.download_icon([(urljoin(self.host_to_url(host), "favicon.ico"), - extension_to_mimetype("ico"))], host) + d = self.download_icon([(urljoin(self.host_to_url(host), 'favicon.ico'), + extension_to_mimetype('ico'))], host) d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail, callbackArgs=(host,), errbackArgs=(host,)) else: @@ -438,7 +438,7 @@ class TrackerIcons(Component): filename = icon.get_filename() with Image.open(filename) as img: if img.size > (16, 16): - new_filename = filename.rpartition(".")[0] + ".png" + new_filename = filename.rpartition('.')[0] + '.png' img = img.resize((16, 16), Image.ANTIALIAS) img.save(new_filename) if new_filename != filename: @@ -475,7 +475,7 @@ class TrackerIcons(Component): """ if host in self.redirects: host = self.redirects[host] - return "http://%s/" % host + return 'http://%s/' % host # ------- HELPER CLASSES ------ @@ -490,17 +490,17 @@ class FaviconParser(HTMLParser): HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): - if tag == "link" and ("rel", "icon") in attrs or ("rel", "shortcut icon") in attrs: + if tag == 'link' and ('rel', 'icon') in attrs or ('rel', 'shortcut icon') in attrs: href = None icon_type = None for attr, value in attrs: - if attr == "href": + if attr == 'href': href = value - elif attr == "type": + elif attr == 'type': icon_type = value if href: try: - mimetype = extension_to_mimetype(href.rpartition(".")[2]) + mimetype = extension_to_mimetype(href.rpartition('.')[2]) except KeyError: pass else: @@ -509,7 +509,7 @@ class FaviconParser(HTMLParser): self.icons.append((href, icon_type)) def handle_endtag(self, tag): - if tag == "head": + if tag == 'head': self.left_head = True def get_icons(self): @@ -548,7 +548,7 @@ def host_to_icon_name(host, mimetype): :rtype: string """ - return host + "." + mimetype_to_extension(mimetype) + return host + '.' + mimetype_to_extension(mimetype) def icon_name_to_host(icon): @@ -560,19 +560,19 @@ def icon_name_to_host(icon): :returns: the host name :rtype: string """ - return icon.rpartition(".")[0] + return icon.rpartition('.')[0] MIME_MAP = { - "image/gif": "gif", - "image/jpeg": "jpg", - "image/png": "png", - "image/vnd.microsoft.icon": "ico", - "image/x-icon": "ico", - "gif": "image/gif", - "jpg": "image/jpeg", - "jpeg": "image/jpeg", - "png": "image/png", - "ico": "image/vnd.microsoft.icon", + 'image/gif': 'gif', + 'image/jpeg': 'jpg', + 'image/png': 'png', + 'image/vnd.microsoft.icon': 'ico', + 'image/x-icon': 'ico', + 'gif': 'image/gif', + 'jpg': 'image/jpeg', + 'jpeg': 'image/jpeg', + 'png': 'image/png', + 'ico': 'image/vnd.microsoft.icon', } diff --git a/deluge/ui/ui.py b/deluge/ui/ui.py index 13334253e..cb7076098 100644 --- a/deluge/ui/ui.py +++ b/deluge/ui/ui.py @@ -33,13 +33,13 @@ class UI(object): def __init__(self, name, **kwargs): self.__name = name - self.ui_args = kwargs.pop("ui_args", None) + self.ui_args = kwargs.pop('ui_args', None) lang.setup_translations() self.__parser = BaseArgParser(**kwargs) def parse_args(self, parser, args=None): options = parser.parse_args(args) - if not hasattr(options, "remaining"): + if not hasattr(options, 'remaining'): options.remaining = [] return options @@ -61,8 +61,8 @@ class UI(object): parser = self.parser self.__options = self.parse_args(parser, args) - setproctitle("deluge-%s" % self.__name) + setproctitle('deluge-%s' % self.__name) - log.info("Deluge ui %s", deluge.common.get_version()) - log.debug("options: %s", self.__options) - log.info("Starting %s ui..", self.__name) + log.info('Deluge ui %s', deluge.common.get_version()) + log.debug('options: %s', self.__options) + log.info('Starting %s ui..', self.__name) diff --git a/deluge/ui/ui_entry.py b/deluge/ui/ui_entry.py index f99989662..6425e28b0 100644 --- a/deluge/ui/ui_entry.py +++ b/deluge/ui/ui_entry.py @@ -26,10 +26,10 @@ from deluge.ui.baseargparser import BaseArgParser from deluge.ui.util import lang DEFAULT_PREFS = { - "default_ui": "gtk" + 'default_ui': 'gtk' } -AMBIGUOUS_CMD_ARGS = ("-h", "--help", "-v", "-V", "--version") +AMBIGUOUS_CMD_ARGS = ('-h', '--help', '-v', '-V', '--version') def start_ui(): @@ -38,14 +38,14 @@ def start_ui(): # Get the registered UI entry points ui_entrypoints = dict([(entrypoint.name, entrypoint.load()) - for entrypoint in pkg_resources.iter_entry_points("deluge.ui")]) + for entrypoint in pkg_resources.iter_entry_points('deluge.ui')]) ui_titles = sorted(ui_entrypoints.keys()) def add_ui_options_group(_parser): """Function to enable reuse of UI Options group""" - group = _parser.add_argument_group(_("UI Options")) - group.add_argument("-s", "--set-default-ui", dest="default_ui", choices=ui_titles, - help=_("Set the default UI to be run, when no UI is specified")) + group = _parser.add_argument_group(_('UI Options')) + group.add_argument('-s', '--set-default-ui', dest='default_ui', choices=ui_titles, + help=_('Set the default UI to be run, when no UI is specified')) return _parser # Setup parser with Common Options and add UI Options group. @@ -54,17 +54,17 @@ def start_ui(): # Parse and handle common/process group options options = parser.parse_known_ui_args(sys.argv, withhold=AMBIGUOUS_CMD_ARGS) - config = deluge.configmanager.ConfigManager("ui.conf", DEFAULT_PREFS) + config = deluge.configmanager.ConfigManager('ui.conf', DEFAULT_PREFS) log = logging.getLogger(__name__) - log.info("Deluge ui %s", deluge.common.get_version()) + log.info('Deluge ui %s', deluge.common.get_version()) if options.default_ui: - config["default_ui"] = options.default_ui + config['default_ui'] = options.default_ui config.save() - log.info("The default UI has been changed to %s", options.default_ui) + log.info('The default UI has been changed to %s', options.default_ui) sys.exit(0) - default_ui = config["default_ui"] + default_ui = config['default_ui'] config.save() # Save in case config didn't already exist. del config @@ -74,16 +74,16 @@ def start_ui(): parser = add_ui_options_group(BaseArgParser(common_help=True)) # Create subparser for each registered UI. Empty title is used to remove unwanted positional text. - subparsers = parser.add_subparsers(dest="selected_ui", metavar="{%s} [UI args]" % ",".join(ui_titles), title=None, - help=_("Alternative UI to launch, with optional ui args \n (default UI: *)")) + subparsers = parser.add_subparsers(dest='selected_ui', metavar='{%s} [UI args]' % ','.join(ui_titles), title=None, + help=_('Alternative UI to launch, with optional ui args \n (default UI: *)')) for ui in ui_titles: parser_ui = subparsers.add_parser(ui, common_help=False, - help=getattr(ui_entrypoints[ui], "cmd_description", "")) - parser_ui.add_argument("ui_args", nargs=argparse.REMAINDER) + help=getattr(ui_entrypoints[ui], 'cmd_description', '')) + parser_ui.add_argument('ui_args', nargs=argparse.REMAINDER) # If the UI is set as default, indicate this in help by prefixing with a star. subactions = subparsers._get_subactions() - prefix = "*" if ui == default_ui else " " - subactions[-1].dest = "%s %s" % (prefix, ui) + prefix = '*' if ui == default_ui else ' ' + subactions[-1].dest = '%s %s' % (prefix, ui) # Insert a default UI subcommand unless one of the ambiguous_args are specified parser.set_default_subparser(default_ui, abort_opts=AMBIGUOUS_CMD_ARGS) @@ -97,7 +97,7 @@ def start_ui(): sys.argv.remove(selected_ui) try: - ui = ui_entrypoints[selected_ui](prog="%s %s" % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args) + ui = ui_entrypoints[selected_ui](prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args) except KeyError as ex: log.error("Unable to find chosen UI: '%s'. Please choose a different UI " "or use '--set-default-ui' to change default UI.", selected_ui) @@ -111,7 +111,7 @@ def start_ui(): "or use '--set-default-ui' to change default UI.", selected_ui) else: log.exception(ex) - log.error("Encountered an error launching the request UI: %s", selected_ui) + log.error('Encountered an error launching the request UI: %s', selected_ui) sys.exit(1) else: ui.start() diff --git a/deluge/ui/util/lang.py b/deluge/ui/util/lang.py index 307293c96..f37e5bf4e 100644 --- a/deluge/ui/util/lang.py +++ b/deluge/ui/util/lang.py @@ -26,13 +26,13 @@ def set_dummy_trans(warn_msg=None): if warn_msg: log.warn("'%s' has been marked for translation, but translation is unavailable.", txt[0]) return txt[0] - __builtin__.__dict__["_"] = _func - __builtin__.__dict__["_n"] = _func + __builtin__.__dict__['_'] = _func + __builtin__.__dict__['_n'] = _func def get_translations_path(): """Get the absolute path to the directory containing translation files""" - return deluge.common.resource_filename("deluge", "i18n") + return deluge.common.resource_filename('deluge', 'i18n') def get_languages(): @@ -49,7 +49,7 @@ def get_languages(): return lang for i, lang_code in enumerate(lang_dirs): - name = "%s (Language name missing)" % lang_code + name = '%s (Language name missing)' % lang_code if lang_code in languages.LANGUAGES: name = languages.LANGUAGES[lang_code] lang.append([lang_code, name]) @@ -75,28 +75,28 @@ def set_language(lang): translations_path = get_translations_path() try: - ro = gettext.translation("deluge", localedir=translations_path, languages=[lang]) + ro = gettext.translation('deluge', localedir=translations_path, languages=[lang]) ro.install() except IOError as ex: - log.warn("IOError when loading translations: %s", ex) + log.warn('IOError when loading translations: %s', ex) # Initialize gettext def setup_translations(setup_gettext=True, setup_pygtk=False): translations_path = get_translations_path() - domain = "deluge" - log.info("Setting up translations from %s", translations_path) + domain = 'deluge' + log.info('Setting up translations from %s', translations_path) if setup_pygtk: try: - log.info("Setting up GTK translations from %s", translations_path) + log.info('Setting up GTK translations from %s', translations_path) if deluge.common.windows_check(): import ctypes libintl = ctypes.cdll.intl libintl.bindtextdomain(domain, translations_path.encode(sys.getfilesystemencoding())) libintl.textdomain(domain) - libintl.bind_textdomain_codeset(domain, "UTF-8") + libintl.bind_textdomain_codeset(domain, 'UTF-8') libintl.gettext.restype = ctypes.c_char_p # Use glade for plugins that still uses it @@ -105,13 +105,13 @@ def setup_translations(setup_gettext=True, setup_pygtk=False): gtk.glade.bindtextdomain(domain, translations_path) gtk.glade.textdomain(domain) except Exception as ex: - log.error("Unable to initialize glade translation!") + log.error('Unable to initialize glade translation!') log.exception(ex) if setup_gettext: try: - if hasattr(locale, "bindtextdomain"): + if hasattr(locale, 'bindtextdomain'): locale.bindtextdomain(domain, translations_path) - if hasattr(locale, "textdomain"): + if hasattr(locale, 'textdomain'): locale.textdomain(domain) gettext.bindtextdomain(domain, translations_path) @@ -119,9 +119,9 @@ def setup_translations(setup_gettext=True, setup_pygtk=False): gettext.textdomain(domain) gettext.install(domain, translations_path, unicode=True) import __builtin__ - __builtin__.__dict__["_n"] = gettext.ngettext + __builtin__.__dict__['_n'] = gettext.ngettext except Exception as ex: - log.error("Unable to initialize gettext/locale!") + log.error('Unable to initialize gettext/locale!') log.exception(ex) set_dummy_trans() diff --git a/deluge/ui/web/auth.py b/deluge/ui/web/auth.py index 5ff450bf3..cc4350752 100644 --- a/deluge/ui/web/auth.py +++ b/deluge/ui/web/auth.py @@ -79,7 +79,7 @@ class Auth(JSONComponent): """ def __init__(self, config): - super(Auth, self).__init__("Auth") + super(Auth, self).__init__('Auth') self.worker = LoopingCall(self._clean_sessions) self.config = config @@ -90,18 +90,18 @@ class Auth(JSONComponent): self.worker.stop() def _clean_sessions(self): - session_ids = self.config["sessions"].keys() + session_ids = self.config['sessions'].keys() now = time.gmtime() for session_id in session_ids: - session = self.config["sessions"][session_id] + session = self.config['sessions'][session_id] - if "expires" not in session: - del self.config["sessions"][session_id] + if 'expires' not in session: + del self.config['sessions'][session_id] continue - if time.gmtime(session["expires"]) < now: - del self.config["sessions"][session_id] + if time.gmtime(session['expires']) < now: + del self.config['sessions'][session_id] continue def _create_session(self, request, login='admin'): @@ -116,75 +116,75 @@ class Auth(JSONComponent): m.update(os.urandom(32)) session_id = m.hexdigest() - expires, expires_str = make_expires(self.config["session_timeout"]) + expires, expires_str = make_expires(self.config['session_timeout']) checksum = str(make_checksum(session_id)) request.addCookie('_session_id', session_id + checksum, - path=request.base + "json", expires=expires_str) + path=request.base + 'json', expires=expires_str) - log.debug("Creating session for %s", login) + log.debug('Creating session for %s', login) - if isinstance(self.config["sessions"], list): - self.config["sessions"] = {} + if isinstance(self.config['sessions'], list): + self.config['sessions'] = {} - self.config["sessions"][session_id] = { - "login": login, - "level": AUTH_LEVEL_ADMIN, - "expires": expires + self.config['sessions'][session_id] = { + 'login': login, + 'level': AUTH_LEVEL_ADMIN, + 'expires': expires } return True def check_password(self, password): config = self.config - if "pwd_md5" in config.config: + if 'pwd_md5' in config.config: # We are using the 1.2-dev auth method - log.debug("Received a password via the 1.2-dev auth method") + log.debug('Received a password via the 1.2-dev auth method') m = hashlib.md5() - m.update(config["pwd_salt"]) + m.update(config['pwd_salt']) m.update(utf8_encoded(password)) if m.hexdigest() == config['pwd_md5']: # We want to move the password over to sha1 and remove # the old passwords from the config file. self._change_password(password) - del config.config["pwd_md5"] + del config.config['pwd_md5'] # Remove the older password if there is now. - if "old_pwd_md5" in config.config: - del config.config["old_pwd_salt"] - del config.config["old_pwd_md5"] + if 'old_pwd_md5' in config.config: + del config.config['old_pwd_salt'] + del config.config['old_pwd_md5'] return True - elif "old_pwd_md5" in config.config: + elif 'old_pwd_md5' in config.config: # We are using the 1.1 webui auth method - log.debug("Received a password via the 1.1 auth method") + log.debug('Received a password via the 1.1 auth method') from base64 import decodestring m = hashlib.md5() - m.update(decodestring(config["old_pwd_salt"])) + m.update(decodestring(config['old_pwd_salt'])) m.update(utf8_encoded(password)) - if m.digest() == decodestring(config["old_pwd_md5"]): + if m.digest() == decodestring(config['old_pwd_md5']): # We want to move the password over to sha1 and remove # the old passwords from the config file. self._change_password(password) - del config.config["old_pwd_salt"] - del config.config["old_pwd_md5"] + del config.config['old_pwd_salt'] + del config.config['old_pwd_md5'] return True - elif "pwd_sha1" in config.config: + elif 'pwd_sha1' in config.config: # We are using the 1.2 auth method - log.debug("Received a password via the 1.2 auth method") + log.debug('Received a password via the 1.2 auth method') s = hashlib.sha1() - s.update(config["pwd_salt"]) + s.update(config['pwd_salt']) s.update(utf8_encoded(password)) - if s.hexdigest() == config["pwd_sha1"]: + if s.hexdigest() == config['pwd_sha1']: return True else: # Can't detect which method we should be using so just deny # access. - log.debug("Failed to detect the login method") + log.debug('Failed to detect the login method') return False def check_request(self, request, method=None, level=None): @@ -202,39 +202,39 @@ class Auth(JSONComponent): :raises: Exception """ - session_id = get_session_id(request.getCookie("_session_id")) + session_id = get_session_id(request.getCookie('_session_id')) - if session_id not in self.config["sessions"]: + if session_id not in self.config['sessions']: auth_level = AUTH_LEVEL_NONE session_id = None else: - session = self.config["sessions"][session_id] - auth_level = session["level"] - expires, expires_str = make_expires(self.config["session_timeout"]) - session["expires"] = expires + session = self.config['sessions'][session_id] + auth_level = session['level'] + expires, expires_str = make_expires(self.config['session_timeout']) + session['expires'] = expires - _session_id = request.getCookie("_session_id") + _session_id = request.getCookie('_session_id') request.addCookie('_session_id', _session_id, - path=request.base + "json", expires=expires_str) + path=request.base + 'json', expires=expires_str) if method: - if not hasattr(method, "_json_export"): - raise Exception("Not an exported method") + if not hasattr(method, '_json_export'): + raise Exception('Not an exported method') - method_level = getattr(method, "_json_auth_level") + method_level = getattr(method, '_json_auth_level') if method_level is None: - raise Exception("Method has no auth level") + raise Exception('Method has no auth level') level = method_level if level is None: - raise Exception("No level specified to check against") + raise Exception('No level specified to check against') request.auth_level = auth_level request.session_id = session_id if auth_level < level: - raise AuthError("Not authenticated") + raise AuthError('Not authenticated') def _change_password(self, new_password): """ @@ -244,12 +244,12 @@ class Auth(JSONComponent): :param new_password: the password to change to :type new_password: string """ - log.debug("Changing password") + log.debug('Changing password') salt = hashlib.sha1(os.urandom(32)).hexdigest() s = hashlib.sha1(salt) s.update(utf8_encoded(new_password)) - self.config["pwd_salt"] = salt - self.config["pwd_sha1"] = s.hexdigest() + self.config['pwd_salt'] = salt + self.config['pwd_sha1'] = s.hexdigest() return True @export @@ -284,7 +284,7 @@ class Auth(JSONComponent): :param session_id: the id for the session to remove :type session_id: string """ - del self.config["sessions"][__request__.session_id] + del self.config['sessions'][__request__.session_id] return True @export(AUTH_LEVEL_NONE) diff --git a/deluge/ui/web/common.py b/deluge/ui/web/common.py index 41ad776c8..ede22767d 100644 --- a/deluge/ui/web/common.py +++ b/deluge/ui/web/common.py @@ -14,7 +14,7 @@ from deluge import common def _(text): - return gettext.gettext(text).decode("utf-8") + return gettext.gettext(text).decode('utf-8') def escape(text): @@ -30,7 +30,7 @@ def escape(text): def compress(contents, request): - request.setHeader("content-encoding", "gzip") + request.setHeader('content-encoding', 'gzip') compress_zlib = zlib.compressobj(6, zlib.DEFLATED, zlib.MAX_WBITS + 16, zlib.DEF_MEM_LEVEL, 0) contents = compress_zlib.compress(contents) contents += compress_zlib.flush() @@ -47,9 +47,9 @@ try: """ builtins = { - "_": _, - "escape": escape, - "version": common.get_version() + '_': _, + 'escape': escape, + 'version': common.get_version() } def render(self, *args, **data): @@ -58,11 +58,11 @@ try: return rendered.encode('utf-8', 'replace') except ImportError: import warnings - warnings.warn("The Mako library is required to run deluge.ui.web", + warnings.warn('The Mako library is required to run deluge.ui.web', RuntimeWarning) class Template(object): def __new__(cls, *args, **kwargs): raise RuntimeError( - "The Mako library is required to run deluge.ui.web" + 'The Mako library is required to run deluge.ui.web' ) diff --git a/deluge/ui/web/json_api.py b/deluge/ui/web/json_api.py index f7c370012..2599b7180 100644 --- a/deluge/ui/web/json_api.py +++ b/deluge/ui/web/json_api.py @@ -41,7 +41,7 @@ AuthError = None class JSONComponent(component.Component): def __init__(self, name, interval=1, depend=None): super(JSONComponent, self).__init__(name, interval, depend) - self._json = component.get("JSON") + self._json = component.get('JSON') self._json.register_object(self, name) @@ -87,7 +87,7 @@ class JSON(resource.Resource, component.Component): def __init__(self): resource.Resource.__init__(self) - component.Component.__init__(self, "JSON") + component.Component.__init__(self, 'JSON') self._remote_methods = [] self._local_methods = {} if client.is_standalone(): @@ -109,7 +109,7 @@ class JSON(resource.Resource, component.Component): """ Handles executing all local methods. """ - if method == "system.listMethods": + if method == 'system.listMethods': d = Deferred() methods = list(self._remote_methods) methods.extend(self._local_methods) @@ -120,16 +120,16 @@ class JSON(resource.Resource, component.Component): # and any plugins. meth = self._local_methods[method] meth.__globals__['__request__'] = request - component.get("Auth").check_request(request, meth) + component.get('Auth').check_request(request, meth) return meth(*params) - raise JSONException("Unknown system method") + raise JSONException('Unknown system method') def _exec_remote(self, method, params, request): """ Executes methods using the Deluge client. """ - component.get("Auth").check_request(request, level=AUTH_LEVEL_DEFAULT) - core_component, method = method.split(".") + component.get('Auth').check_request(request, level=AUTH_LEVEL_DEFAULT) + core_component, method = method.split('.') return getattr(getattr(client, core_component), method)(*params) def _handle_request(self, request): @@ -141,29 +141,29 @@ class JSON(resource.Resource, component.Component): try: request.json = json.loads(request.json) except (ValueError, TypeError): - raise JSONException("JSON not decodable") - if "method" not in request.json or "id" not in request.json or \ - "params" not in request.json: - raise JSONException("Invalid JSON request") + raise JSONException('JSON not decodable') + if 'method' not in request.json or 'id' not in request.json or \ + 'params' not in request.json: + raise JSONException('Invalid JSON request') - method, params = request.json["method"], request.json["params"] - request_id = request.json["id"] + method, params = request.json['method'], request.json['params'] + request_id = request.json['id'] result = None error = None try: - if method.startswith("system.") or method in self._local_methods: + if method.startswith('system.') or method in self._local_methods: result = self._exec_local(method, params, request) elif method in self._remote_methods: result = self._exec_remote(method, params, request) else: - error = {"message": "Unknown method", "code": 2} + error = {'message': 'Unknown method', 'code': 2} except AuthError: - error = {"message": "Not authenticated", "code": 1} + error = {'message': 'Not authenticated', 'code': 1} except Exception as ex: - log.error("Error calling method `%s`", method) + log.error('Error calling method `%s`', method) log.exception(ex) - error = {"message": "%s: %s" % (ex.__class__.__name__, str(ex)), "code": 3} + error = {'message': '%s: %s' % (ex.__class__.__name__, str(ex)), 'code': 3} return request_id, result, error @@ -171,7 +171,7 @@ class JSON(resource.Resource, component.Component): """ Sends the response of any rpc calls back to the json-rpc client. """ - response["result"] = result + response['result'] = result return self._send_response(request, response) def _on_rpc_request_failed(self, reason, response, request): @@ -179,7 +179,7 @@ class JSON(resource.Resource, component.Component): Handles any failures that occurred while making an rpc call. """ log.exception(reason) - response["error"] = {"message": "%s: %s" % (reason.__class__.__name__, str(reason)), "code": 4} + response['error'] = {'message': '%s: %s' % (reason.__class__.__name__, str(reason)), 'code': 4} return self._send_response(request, response) def _on_json_request(self, request): @@ -187,16 +187,16 @@ class JSON(resource.Resource, component.Component): Handler to take the json data as a string and pass it on to the _handle_request method for further processing. """ - log.debug("json-request: %s", request.json) - response = {"result": None, "error": None, "id": None} - response["id"], d, response["error"] = self._handle_request(request) + log.debug('json-request: %s', request.json) + response = {'result': None, 'error': None, 'id': None} + response['id'], d, response['error'] = self._handle_request(request) if isinstance(d, Deferred): d.addCallback(self._on_rpc_request_finished, response, request) d.addErrback(self._on_rpc_request_failed, response, request) return d else: - response["result"] = d + response['result'] = d return self._send_response(request, response) def _on_json_request_failed(self, reason, request): @@ -204,16 +204,16 @@ class JSON(resource.Resource, component.Component): Returns the error in json response. """ log.exception(reason) - response = {"result": None, "id": None, - "error": {"code": 5, - "message": "%s: %s" % (reason.__class__.__name__, str(reason))}} + response = {'result': None, 'id': None, + 'error': {'code': 5, + 'message': '%s: %s' % (reason.__class__.__name__, str(reason))}} return self._send_response(request, response) def _send_response(self, request, response): if request._disconnected: - return "" + return '' response = json.dumps(response) - request.setHeader("content-type", "application/x-json") + request.setHeader('content-type', 'application/x-json') request.write(compress(response, request)) request.finish() return server.NOT_DONE_YET @@ -222,7 +222,7 @@ class JSON(resource.Resource, component.Component): """ Handles all the POST requests made to the /json controller. """ - if request.method != "POST": + if request.method != 'POST': request.setResponseCode(http.NOT_ALLOWED) request.finish() return server.NOT_DONE_YET @@ -249,11 +249,11 @@ class JSON(resource.Resource, component.Component): name = name.lower() for d in dir(obj): - if d[0] == "_": + if d[0] == '_': continue if getattr(getattr(obj, d), '_json_export', False): - log.debug("Registering method: %s", name + "." + d) - self._local_methods[name + "." + d] = getattr(obj, d) + log.debug('Registering method: %s', name + '.' + d) + self._local_methods[name + '.' + d] = getattr(obj, d) HOSTLIST_ID = 0 @@ -269,7 +269,7 @@ HOSTS_USER = HOSTLIST_USER HOSTS_STATUS = 3 HOSTS_INFO = 4 -FILES_KEYS = ["files", "file_progress", "file_priorities"] +FILES_KEYS = ['files', 'file_progress', 'file_priorities'] class EventQueue(object): @@ -363,45 +363,45 @@ class WebApi(JSONComponent): """ def __init__(self): - super(WebApi, self).__init__("Web", depend=["SessionProxy"]) - self.host_list = ConfigManager("hostlist.conf.1.2", uicommon.DEFAULT_HOSTS) + super(WebApi, self).__init__('Web', depend=['SessionProxy']) + self.host_list = ConfigManager('hostlist.conf.1.2', uicommon.DEFAULT_HOSTS) if not os.path.isfile(self.host_list.config_file): self.host_list.save() self.core_config = CoreConfig() self.event_queue = EventQueue() try: - self.sessionproxy = component.get("SessionProxy") + self.sessionproxy = component.get('SessionProxy') except KeyError: self.sessionproxy = SessionProxy() def disable(self): - client.deregister_event_handler("PluginEnabledEvent", self._json.get_remote_methods) - client.deregister_event_handler("PluginDisabledEvent", self._json.get_remote_methods) + client.deregister_event_handler('PluginEnabledEvent', self._json.get_remote_methods) + client.deregister_event_handler('PluginDisabledEvent', self._json.get_remote_methods) if client.is_standalone(): - component.get("Web.PluginManager").stop() + component.get('Web.PluginManager').stop() else: client.disconnect() client.set_disconnect_callback(None) def enable(self): - client.register_event_handler("PluginEnabledEvent", self._json.get_remote_methods) - client.register_event_handler("PluginDisabledEvent", self._json.get_remote_methods) + client.register_event_handler('PluginEnabledEvent', self._json.get_remote_methods) + client.register_event_handler('PluginDisabledEvent', self._json.get_remote_methods) if client.is_standalone(): - component.get("Web.PluginManager").start() + component.get('Web.PluginManager').start() else: client.set_disconnect_callback(self._on_client_disconnect) - if component.get("DelugeWeb").config["default_daemon"]: + if component.get('DelugeWeb').config['default_daemon']: # Sort out getting the default daemon here - default_host_id = component.get("DelugeWeb").config["default_daemon"] - host_info = component.get("Web")._get_host(default_host_id) + default_host_id = component.get('DelugeWeb').config['default_daemon'] + host_info = component.get('Web')._get_host(default_host_id) return self._connect_daemon(*host_info[1:]) return defer.succeed(True) def _on_client_disconnect(self, *args): - component.get("Web.PluginManager").stop() + component.get('Web.PluginManager').stop() return self.stop() def _get_host(self, host_id): @@ -415,7 +415,7 @@ class WebApi(JSONComponent): """ host_info = [] - for host_entry in self.host_list["hosts"]: + for host_entry in self.host_list['hosts']: if host_entry[0] == host_id: host_info = host_entry break @@ -430,7 +430,7 @@ class WebApi(JSONComponent): self.sessionproxy.stop() return defer.succeed(True) - def _connect_daemon(self, host="localhost", port=58846, username="", password=""): + def _connect_daemon(self, host='localhost', port=58846, username='', password=''): """ Connects the client to a daemon """ @@ -442,7 +442,7 @@ class WebApi(JSONComponent): invokes retrieving the method names. """ d = self._json.get_remote_methods() - component.get("Web.PluginManager").start() + component.get('Web.PluginManager').start() self.start() return d @@ -461,7 +461,7 @@ class WebApi(JSONComponent): host = self._get_host(host_id) if host: return self._connect_daemon(*host[1:]) - return defer.fail(Exception("Bad host id")) + return defer.fail(Exception('Bad host id')) @export def connected(self): @@ -499,13 +499,13 @@ class WebApi(JSONComponent): """ d = Deferred() ui_info = { - "connected": client.connected(), - "torrents": None, - "filters": None, - "stats": { - "max_download": self.core_config.get("max_download_speed"), - "max_upload": self.core_config.get("max_upload_speed"), - "max_num_connections": self.core_config.get("max_connections_global") + 'connected': client.connected(), + 'torrents': None, + 'filters': None, + 'stats': { + 'max_download': self.core_config.get('max_download_speed'), + 'max_upload': self.core_config.get('max_upload_speed'), + 'max_num_connections': self.core_config.get('max_connections_global') } } @@ -514,47 +514,47 @@ class WebApi(JSONComponent): return d def got_stats(stats): - ui_info["stats"]["num_connections"] = stats["num_peers"] - ui_info["stats"]["upload_rate"] = stats["payload_upload_rate"] - ui_info["stats"]["download_rate"] = stats["payload_download_rate"] - ui_info["stats"]["download_protocol_rate"] = stats["download_rate"] - stats["payload_download_rate"] - ui_info["stats"]["upload_protocol_rate"] = stats["upload_rate"] - stats["payload_upload_rate"] - ui_info["stats"]["dht_nodes"] = stats["dht_nodes"] - ui_info["stats"]["has_incoming_connections"] = stats["has_incoming_connections"] + ui_info['stats']['num_connections'] = stats['num_peers'] + ui_info['stats']['upload_rate'] = stats['payload_upload_rate'] + ui_info['stats']['download_rate'] = stats['payload_download_rate'] + ui_info['stats']['download_protocol_rate'] = stats['download_rate'] - stats['payload_download_rate'] + ui_info['stats']['upload_protocol_rate'] = stats['upload_rate'] - stats['payload_upload_rate'] + ui_info['stats']['dht_nodes'] = stats['dht_nodes'] + ui_info['stats']['has_incoming_connections'] = stats['has_incoming_connections'] def got_filters(filters): - ui_info["filters"] = filters + ui_info['filters'] = filters def got_free_space(free_space): - ui_info["stats"]["free_space"] = free_space + ui_info['stats']['free_space'] = free_space def got_external_ip(external_ip): - ui_info["stats"]["external_ip"] = external_ip + ui_info['stats']['external_ip'] = external_ip def got_torrents(torrents): - ui_info["torrents"] = torrents + ui_info['torrents'] = torrents def on_complete(result): d.callback(ui_info) - d1 = component.get("SessionProxy").get_torrents_status(filter_dict, keys) + d1 = component.get('SessionProxy').get_torrents_status(filter_dict, keys) d1.addCallback(got_torrents) d2 = client.core.get_filter_tree() d2.addCallback(got_filters) d3 = client.core.get_session_status([ - "num_peers", - "payload_download_rate", - "payload_upload_rate", - "download_rate", - "upload_rate", - "dht_nodes", - "has_incoming_connections" + 'num_peers', + 'payload_download_rate', + 'payload_upload_rate', + 'download_rate', + 'upload_rate', + 'dht_nodes', + 'has_incoming_connections' ]) d3.addCallback(got_stats) - d4 = client.core.get_free_space(self.core_config.get("download_location")) + d4 = client.core.get_free_space(self.core_config.get('download_location')) d4.addCallback(got_free_space) d5 = client.core.get_external_ip() @@ -565,40 +565,40 @@ class WebApi(JSONComponent): return d def _on_got_files(self, torrent, d): - files = torrent.get("files") - file_progress = torrent.get("file_progress") - file_priorities = torrent.get("file_priorities") + files = torrent.get('files') + file_progress = torrent.get('file_progress') + file_priorities = torrent.get('file_priorities') paths = [] info = {} for index, torrent_file in enumerate(files): - path = torrent_file["path"] + path = torrent_file['path'] paths.append(path) - torrent_file["progress"] = file_progress[index] - torrent_file["priority"] = file_priorities[index] - torrent_file["index"] = index - torrent_file["path"] = path + torrent_file['progress'] = file_progress[index] + torrent_file['priority'] = file_priorities[index] + torrent_file['index'] = index + torrent_file['path'] = path info[path] = torrent_file # update the directory info dirname = os.path.dirname(path) while dirname: dirinfo = info.setdefault(dirname, {}) - dirinfo["size"] = dirinfo.get("size", 0) + torrent_file["size"] - if "priority" not in dirinfo: - dirinfo["priority"] = torrent_file["priority"] + dirinfo['size'] = dirinfo.get('size', 0) + torrent_file['size'] + if 'priority' not in dirinfo: + dirinfo['priority'] = torrent_file['priority'] else: - if dirinfo["priority"] != torrent_file["priority"]: - dirinfo["priority"] = 9 + if dirinfo['priority'] != torrent_file['priority']: + dirinfo['priority'] = 9 - progresses = dirinfo.setdefault("progresses", []) - progresses.append(torrent_file["size"] * torrent_file["progress"] / 100) - dirinfo["progress"] = sum(progresses) / dirinfo["size"] * 100 - dirinfo["path"] = dirname + progresses = dirinfo.setdefault('progresses', []) + progresses.append(torrent_file['size'] * torrent_file['progress'] / 100) + dirinfo['progress'] = sum(progresses) / dirinfo['size'] * 100 + dirinfo['path'] = dirname dirname = os.path.dirname(dirname) def walk(path, item): - if item["type"] == "dir": + if item['type'] == 'dir': item.update(info[path]) return item else: @@ -611,7 +611,7 @@ class WebApi(JSONComponent): @export def get_torrent_status(self, torrent_id, keys): - return component.get("SessionProxy").get_torrent_status(torrent_id, keys) + return component.get('SessionProxy').get_torrent_status(torrent_id, keys) @export def get_torrent_files(self, torrent_id): @@ -624,7 +624,7 @@ class WebApi(JSONComponent): :rtype: dictionary """ main_deferred = Deferred() - d = component.get("SessionProxy").get_torrent_status(torrent_id, FILES_KEYS) + d = component.get('SessionProxy').get_torrent_status(torrent_id, FILES_KEYS) d.addCallback(self._on_got_files, main_deferred) return main_deferred @@ -640,20 +640,20 @@ class WebApi(JSONComponent): """ def on_download_success(result): - log.debug("Successfully downloaded %s to %s", url, result) + log.debug('Successfully downloaded %s to %s', url, result) return result def on_download_fail(result): - log.error("Failed to add torrent from url %s", url) + log.error('Failed to add torrent from url %s', url) return result - tempdir = tempfile.mkdtemp(prefix="delugeweb-") - tmp_file = os.path.join(tempdir, url.split("/")[-1]) - log.debug("filename: %s", tmp_file) + tempdir = tempfile.mkdtemp(prefix='delugeweb-') + tmp_file = os.path.join(tempdir, url.split('/')[-1]) + log.debug('filename: %s', tmp_file) headers = {} if cookie: - headers["Cookie"] = cookie - log.debug("cookie: %s", cookie) + headers['Cookie'] = cookie + log.debug('cookie: %s', cookie) d = httpdownloader.download_file(url, tmp_file, headers=headers) d.addCallbacks(on_download_success, on_download_fail) return d @@ -680,7 +680,7 @@ class WebApi(JSONComponent): """ try: torrent_info = uicommon.TorrentInfo(filename.strip(), 2) - return torrent_info.as_dict("name", "info_hash", "files_tree") + return torrent_info.as_dict('name', 'info_hash', 'files_tree') except Exception as ex: log.exception(ex) return False @@ -709,18 +709,18 @@ class WebApi(JSONComponent): deferreds = [] for torrent in torrents: - if common.is_magnet(torrent["path"]): - log.info("Adding torrent from magnet uri `%s` with options `%r`", - torrent["path"], torrent["options"]) - d = client.core.add_torrent_magnet(torrent["path"], torrent["options"]) + if common.is_magnet(torrent['path']): + log.info('Adding torrent from magnet uri `%s` with options `%r`', + torrent['path'], torrent['options']) + d = client.core.add_torrent_magnet(torrent['path'], torrent['options']) deferreds.append(d) else: - filename = os.path.basename(torrent["path"]) - with open(torrent["path"], "rb") as _file: + filename = os.path.basename(torrent['path']) + with open(torrent['path'], 'rb') as _file: fdump = base64.encodestring(_file.read()) - log.info("Adding torrent from file `%s` with options `%r`", - filename, torrent["options"]) - d = client.core.add_torrent_file(filename, fdump, torrent["options"]) + log.info('Adding torrent from file `%s` with options `%r`', + filename, torrent['options']) + d = client.core.add_torrent_file(filename, fdump, torrent['options']) deferreds.append(d) return DeferredList(deferreds, consumeErrors=False) @@ -729,8 +729,8 @@ class WebApi(JSONComponent): """ Return the hosts in the hostlist. """ - log.debug("get_hosts called") - return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ("Offline",)) for host in self.host_list["hosts"]] + log.debug('get_hosts called') + return [(tuple(host[HOSTS_ID:HOSTS_USER + 1]) + ('Offline',)) for host in self.host_list['hosts']] @export def get_host_status(self, host_id): @@ -748,30 +748,30 @@ class WebApi(JSONComponent): except TypeError: host = None port = None - return response("Offline") + return response('Offline') def on_connect(connected, c, host_id): def on_info(info, c): c.disconnect() - return response("Online", info) + return response('Online', info) def on_info_fail(reason, c): c.disconnect() - return response("Offline") + return response('Offline') if not connected: - return response("Offline") + return response('Offline') return c.daemon.info().addCallback(on_info, c).addErrback(on_info_fail, c) def on_connect_failed(reason, host_id): - return response("Offline") + return response('Offline') - if client.connected() and (host, port, "localclient" if not - user and host in ("127.0.0.1", "localhost") else + if client.connected() and (host, port, 'localclient' if not + user and host in ('127.0.0.1', 'localhost') else user) == client.connection_info(): def on_info(info): - return response("Connected", info) + return response('Connected', info) return client.daemon.info().addCallback(on_info) else: @@ -804,7 +804,7 @@ class WebApi(JSONComponent): try: def on_connect(connected, c): if not connected: - main_deferred.callback((False, _("Daemon not running"))) + main_deferred.callback((False, _('Daemon not running'))) return c.daemon.shutdown() main_deferred.callback((True, )) @@ -818,11 +818,11 @@ class WebApi(JSONComponent): d.addCallback(on_connect, c) d.addErrback(on_connect_failed) except Exception: - main_deferred.callback((False, "An error occurred")) + main_deferred.callback((False, 'An error occurred')) return main_deferred @export - def add_host(self, host, port, username="", password=""): + def add_host(self, host, port, username='', password=''): """ Adds a host to the list. @@ -838,18 +838,18 @@ class WebApi(JSONComponent): """ # Check to see if there is already an entry for this host and return # if thats the case - for entry in self.host_list["hosts"]: + for entry in self.host_list['hosts']: if (entry[1], entry[2], entry[3]) == (host, port, username): - return (False, "Host already in the list") + return (False, 'Host already in the list') try: port = int(port) except ValueError: - return (False, "Port is invalid") + return (False, 'Port is invalid') # Host isn't in the list, so lets add it connection_id = hashlib.sha1(str(time.time())).hexdigest() - self.host_list["hosts"].append([connection_id, host, port, username, + self.host_list['hosts'].append([connection_id, host, port, username, password]) self.host_list.save() return True, connection_id @@ -866,7 +866,7 @@ class WebApi(JSONComponent): if not host: return False - self.host_list["hosts"].remove(host) + self.host_list['hosts'].remove(host) self.host_list.save() return True @@ -878,10 +878,10 @@ class WebApi(JSONComponent): :rtype: dictionary :returns: the configuration """ - config = component.get("DelugeWeb").config.config.copy() - del config["sessions"] - del config["pwd_salt"] - del config["pwd_sha1"] + config = component.get('DelugeWeb').config.config.copy() + del config['sessions'] + del config['pwd_salt'] + del config['pwd_sha1'] return config @export @@ -892,13 +892,13 @@ class WebApi(JSONComponent): :param config: The configuration options to update :type config: dictionary """ - web_config = component.get("DelugeWeb").config + web_config = component.get('DelugeWeb').config for key in config.keys(): - if key in ["sessions", "pwd_salt", "pwd_sha1"]: + if key in ['sessions', 'pwd_salt', 'pwd_sha1']: log.warn("Ignored attempt to overwrite web config key '%s'", key) continue if isinstance(config[key], basestring): - config[key] = config[key].encode("utf8") + config[key] = config[key].encode('utf8') web_config[key] = config[key] @export @@ -914,34 +914,34 @@ class WebApi(JSONComponent): """ return { - "enabled_plugins": component.get("Web.PluginManager").plugins.keys(), - "available_plugins": component.get("Web.PluginManager").available_plugins + 'enabled_plugins': component.get('Web.PluginManager').plugins.keys(), + 'available_plugins': component.get('Web.PluginManager').available_plugins } @export def get_plugin_info(self, name): - return component.get("Web.PluginManager").get_plugin_info(name) + return component.get('Web.PluginManager').get_plugin_info(name) @export def get_plugin_resources(self, name): - return component.get("Web.PluginManager").get_plugin_resources(name) + return component.get('Web.PluginManager').get_plugin_resources(name) @export def upload_plugin(self, filename, path): main_deferred = Deferred() - shutil.copyfile(path, os.path.join(get_config_dir(), "plugins", filename)) - component.get("Web.PluginManager").scan_for_plugins() + shutil.copyfile(path, os.path.join(get_config_dir(), 'plugins', filename)) + component.get('Web.PluginManager').scan_for_plugins() if client.is_localhost(): client.core.rescan_plugins() return True - with open(path, "rb") as _file: + with open(path, 'rb') as _file: plugin_data = base64.encodestring(_file.read()) def on_upload_complete(*args): client.core.rescan_plugins() - component.get("Web.PluginManager").scan_for_plugins() + component.get('Web.PluginManager').scan_for_plugins() main_deferred.callback(True) def on_upload_error(*args): @@ -985,7 +985,7 @@ class WebUtils(JSONComponent): Utility functions for the webui that do not fit in the WebApi. """ def __init__(self): - super(WebUtils, self).__init__("WebUtils") + super(WebUtils, self).__init__('WebUtils') @export def get_languages(self): diff --git a/deluge/ui/web/pluginmanager.py b/deluge/ui/web/pluginmanager.py index f5485cfea..f636db5d7 100644 --- a/deluge/ui/web/pluginmanager.py +++ b/deluge/ui/web/pluginmanager.py @@ -20,8 +20,8 @@ log = logging.getLogger(__name__) def gather_info(plugin): # Get the scripts for the plugin - scripts = getattr(plugin, "scripts", ()) - debug_scripts = getattr(plugin, "debug_scripts") or scripts + scripts = getattr(plugin, 'scripts', ()) + debug_scripts = getattr(plugin, 'debug_scripts') or scripts directories = [] for script in scripts + debug_scripts: @@ -29,20 +29,20 @@ def gather_info(plugin): directories.append(os.path.dirname(script)) return { - "scripts": scripts, - "debug_scripts": debug_scripts, - "script_directories": directories + 'scripts': scripts, + 'debug_scripts': debug_scripts, + 'script_directories': directories } class PluginManager(PluginManagerBase, component.Component): def __init__(self): - component.Component.__init__(self, "Web.PluginManager") - self.config = ConfigManager("web.conf") - PluginManagerBase.__init__(self, "web.conf", "deluge.plugin.web") + component.Component.__init__(self, 'Web.PluginManager') + self.config = ConfigManager('web.conf') + PluginManagerBase.__init__(self, 'web.conf', 'deluge.plugin.web') - client.register_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event) - client.register_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event) + client.register_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event) + client.register_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event) def _on_get_enabled_plugins(self, plugins): for plugin in plugins: @@ -57,20 +57,20 @@ class PluginManager(PluginManagerBase, component.Component): def disable_plugin(self, name): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: log.debug("'%s' plugin contains no WebUI code, ignoring WebUI disable call.", name) return info = gather_info(plugin) - scripts = component.get("Scripts") - for script in info["scripts"]: - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower())) + scripts = component.get('Scripts') + for script in info['scripts']: + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower())) - for script in info["debug_scripts"]: - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "debug") - scripts.remove_script("%s/%s" % (name.lower(), os.path.basename(script).lower()), "dev") + for script in info['debug_scripts']: + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'debug') + scripts.remove_script('%s/%s' % (name.lower(), os.path.basename(script).lower()), 'dev') super(PluginManager, self).disable_plugin(name) @@ -79,22 +79,22 @@ class PluginManager(PluginManagerBase, component.Component): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: log.info("'%s' plugin contains no WebUI code, ignoring WebUI enable call.", name) return info = gather_info(plugin) - scripts = component.get("Scripts") - for script in info["scripts"]: - log.debug("adding script %s for %s", name, os.path.basename(script)) - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script) + scripts = component.get('Scripts') + for script in info['scripts']: + log.debug('adding script %s for %s', name, os.path.basename(script)) + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script) - for script in info["debug_scripts"]: - log.debug("adding debug script %s for %s", name, os.path.basename(script)) - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "debug") - scripts.add_script("%s/%s" % (name.lower(), os.path.basename(script)), script, "dev") + for script in info['debug_scripts']: + log.debug('adding debug script %s for %s', name, os.path.basename(script)) + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'debug') + scripts.add_script('%s/%s' % (name.lower(), os.path.basename(script)), script, 'dev') def start(self): """ @@ -109,8 +109,8 @@ class PluginManager(PluginManagerBase, component.Component): Stop the plugin manager """ self.disable_plugins() - client.deregister_event_handler("PluginEnabledEvent", self._on_plugin_enabled_event) - client.deregister_event_handler("PluginDisabledEvent", self._on_plugin_disabled_event) + client.deregister_event_handler('PluginEnabledEvent', self._on_plugin_enabled_event) + client.deregister_event_handler('PluginDisabledEvent', self._on_plugin_disabled_event) def update(self): pass @@ -118,13 +118,13 @@ class PluginManager(PluginManagerBase, component.Component): def get_plugin_resources(self, name): # Get the plugin instance try: - plugin = component.get("WebPlugin." + name) + plugin = component.get('WebPlugin.' + name) except KeyError: - log.info("Plugin has no web ui") + log.info('Plugin has no web ui') return info = gather_info(plugin) - info["name"] = name - info["scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["scripts"]] - info["debug_scripts"] = ["js/%s/%s" % (name.lower(), os.path.basename(s)) for s in info["debug_scripts"]] - del info["script_directories"] + info['name'] = name + info['scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['scripts']] + info['debug_scripts'] = ['js/%s/%s' % (name.lower(), os.path.basename(s)) for s in info['debug_scripts']] + del info['script_directories'] return info diff --git a/deluge/ui/web/server.py b/deluge/ui/web/server.py index 3ec16f824..26a20e268 100644 --- a/deluge/ui/web/server.py +++ b/deluge/ui/web/server.py @@ -33,36 +33,36 @@ log = logging.getLogger(__name__) CONFIG_DEFAULTS = { # Misc Settings - "enabled_plugins": [], - "default_daemon": "", + 'enabled_plugins': [], + 'default_daemon': '', # Auth Settings - "pwd_salt": "c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad", - "pwd_sha1": "2ce1a410bcdcc53064129b6d950f2e9fee4edc1e", - "session_timeout": 3600, - "sessions": {}, + 'pwd_salt': 'c26ab3bbd8b137f99cd83c2c1c0963bcc1a35cad', + 'pwd_sha1': '2ce1a410bcdcc53064129b6d950f2e9fee4edc1e', + 'session_timeout': 3600, + 'sessions': {}, # UI Settings - "sidebar_show_zero": False, - "sidebar_multiple_filters": True, - "show_session_speed": False, - "show_sidebar": True, - "theme": "gray", - "first_login": True, - "language": "", + 'sidebar_show_zero': False, + 'sidebar_multiple_filters': True, + 'show_session_speed': False, + 'show_sidebar': True, + 'theme': 'gray', + 'first_login': True, + 'language': '', # Server Settings - "base": "/", - "interface": "0.0.0.0", - "port": 8112, - "https": False, - "pkey": "ssl/daemon.pkey", - "cert": "ssl/daemon.cert" + 'base': '/', + 'interface': '0.0.0.0', + 'port': 8112, + 'https': False, + 'pkey': 'ssl/daemon.pkey', + 'cert': 'ssl/daemon.cert' } UI_CONFIG_KEYS = ( - "theme", "sidebar_show_zero", "sidebar_multiple_filters", - "show_session_speed", "base", "first_login" + 'theme', 'sidebar_show_zero', 'sidebar_multiple_filters', + 'show_session_speed', 'base', 'first_login' ) @@ -70,13 +70,13 @@ def rpath(*paths): """Convert a relative path into an absolute path relative to the location of this script. """ - return common.resource_filename("deluge.ui.web", os.path.join(*paths)) + return common.resource_filename('deluge.ui.web', os.path.join(*paths)) class GetText(resource.Resource): def render(self, request): - request.setHeader("content-type", "text/javascript; encoding=utf-8") - template = Template(filename=rpath("js", "gettext.js")) + request.setHeader('content-type', 'text/javascript; encoding=utf-8') + template = Template(filename=rpath('js', 'gettext.js')) return compress(template.render(), request) @@ -92,29 +92,29 @@ class Upload(resource.Resource): """ # Block all other HTTP methods. - if request.method != "POST": + if request.method != 'POST': request.setResponseCode(http.NOT_ALLOWED) - return "" + return '' - if "file" not in request.args: + if 'file' not in request.args: request.setResponseCode(http.OK) return json.dumps({ 'success': True, 'files': [] }) - tempdir = tempfile.mkdtemp(prefix="delugeweb-") - log.debug("uploading files to %s", tempdir) + tempdir = tempfile.mkdtemp(prefix='delugeweb-') + log.debug('uploading files to %s', tempdir) filenames = [] - for upload in request.args.get("file"): + for upload in request.args.get('file'): fd, fn = tempfile.mkstemp('.torrent', dir=tempdir) os.write(fd, upload) os.close(fd) filenames.append(fn) - log.debug("uploaded %d file(s)", len(filenames)) + log.debug('uploaded %d file(s)', len(filenames)) - request.setHeader("content-type", "text/html") + request.setHeader('content-type', 'text/html') request.setResponseCode(http.OK) return compress(json.dumps({ 'success': True, @@ -129,13 +129,13 @@ class Render(resource.Resource): return self def render(self, request): - if not hasattr(request, "render_file"): + if not hasattr(request, 'render_file'): request.setResponseCode(http.INTERNAL_SERVER_ERROR) - return "" + return '' - filename = os.path.join("render", request.render_file) + filename = os.path.join('render', request.render_file) template = Template(filename=rpath(filename)) - request.setHeader("content-type", "text/html") + request.setHeader('content-type', 'text/html') request.setResponseCode(http.OK) return compress(template.render(), request) @@ -145,7 +145,7 @@ class Tracker(resource.Resource): def __init__(self): resource.Resource.__init__(self) try: - self.tracker_icons = component.get("TrackerIcons") + self.tracker_icons = component.get('TrackerIcons') except KeyError: self.tracker_icons = TrackerIcons() @@ -155,9 +155,9 @@ class Tracker(resource.Resource): def on_got_icon(self, icon, request): if icon: - request.setHeader("cache-control", - "public, must-revalidate, max-age=86400") - request.setHeader("content-type", icon.get_mimetype()) + request.setHeader('cache-control', + 'public, must-revalidate, max-age=86400') + request.setHeader('content-type', icon.get_mimetype()) request.setResponseCode(http.OK) request.write(icon.get_data()) request.finish() @@ -177,19 +177,19 @@ class Flag(resource.Resource): return self def render(self, request): - path = ("ui", "data", "pixmaps", "flags", request.country.lower() + ".png") - filename = common.resource_filename("deluge", os.path.join(*path)) + path = ('ui', 'data', 'pixmaps', 'flags', request.country.lower() + '.png') + filename = common.resource_filename('deluge', os.path.join(*path)) if os.path.exists(filename): - request.setHeader("cache-control", - "public, must-revalidate, max-age=86400") - request.setHeader("content-type", "image/png") - with open(filename, "rb") as _file: + request.setHeader('cache-control', + 'public, must-revalidate, max-age=86400') + request.setHeader('content-type', 'image/png') + with open(filename, 'rb') as _file: data = _file.read() request.setResponseCode(http.OK) return data else: request.setResponseCode(http.NOT_FOUND) - return "" + return '' class LookupResource(resource.Resource, component.Component): @@ -202,13 +202,13 @@ class LookupResource(resource.Resource, component.Component): for directory in directories: self.add_directory(directory) - def add_directory(self, directory, path=""): - log.debug("Adding directory `%s` with path `%s`", directory, path) + def add_directory(self, directory, path=''): + log.debug('Adding directory `%s` with path `%s`', directory, path) paths = self.__paths.setdefault(path, []) paths.append(directory) - def remove_directory(self, directory, path=""): - log.debug("Removing directory `%s`", directory) + def remove_directory(self, directory, path=''): + log.debug('Removing directory `%s`', directory) self.__paths[path].remove(directory) def getChild(self, path, request): # NOQA @@ -224,7 +224,7 @@ class LookupResource(resource.Resource, component.Component): if path not in self.__paths: request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' filename = os.path.basename(request.path) for directory in self.__paths[path]: @@ -232,23 +232,23 @@ class LookupResource(resource.Resource, component.Component): path = os.path.join(directory, filename) log.debug("Serving path: '%s'", path) mime_type = mimetypes.guess_type(path) - request.setHeader("content-type", mime_type[0]) - with open(path, "rb") as _file: + request.setHeader('content-type', mime_type[0]) + with open(path, 'rb') as _file: data = _file.read() return compress(data, request) request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' class ScriptResource(resource.Resource, component.Component): def __init__(self): resource.Resource.__init__(self) - component.Component.__init__(self, "Scripts") + component.Component.__init__(self, 'Scripts') self.__scripts = {} - for script_type in ["normal", "debug", "dev"]: - self.__scripts[script_type] = {"scripts": {}, "order": [], "files_exist": True} + for script_type in ['normal', 'debug', 'dev']: + self.__scripts[script_type] = {'scripts': {}, 'order': [], 'files_exist': True} def has_script_type_files(self, script_type): """Returns whether all the script files exist for this script type. @@ -260,7 +260,7 @@ class ScriptResource(resource.Resource, component.Component): bool: True if the files for this script type exist, otherwise False. """ - return self.__scripts[script_type]["files_exist"] + return self.__scripts[script_type]['files_exist'] def add_script(self, path, filepath, script_type=None): """ @@ -273,13 +273,13 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of script to add (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - self.__scripts[script_type]["scripts"][path] = filepath - self.__scripts[script_type]["order"].append(path) + self.__scripts[script_type]['scripts'][path] = filepath + self.__scripts[script_type]['order'].append(path) if not os.path.isfile(filepath): - self.__scripts[script_type]["files_exist"] = False + self.__scripts[script_type]['files_exist'] = False def add_script_folder(self, path, filepath, script_type=None, recurse=True): """ @@ -294,13 +294,13 @@ class ScriptResource(resource.Resource, component.Component): :keyword recurse: Whether or not to recurse into other folders :param recurse: bool """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - self.__scripts[script_type]["scripts"][path] = (filepath, recurse) - self.__scripts[script_type]["order"].append(path) + self.__scripts[script_type]['scripts'][path] = (filepath, recurse) + self.__scripts[script_type]['order'].append(path) if not os.path.isdir(filepath): - self.__scripts[script_type]["files_exist"] = False + self.__scripts[script_type]['files_exist'] = False def remove_script(self, path, script_type=None): """ @@ -311,11 +311,11 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of script to add (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): - script_type = "normal" + if script_type not in ('dev', 'debug', 'normal'): + script_type = 'normal' - del self.__scripts[script_type]["scripts"][path] - self.__scripts[script_type]["order"].remove(path) + del self.__scripts[script_type]['scripts'][path] + self.__scripts[script_type]['order'].remove(path) def get_scripts(self, script_type=None): """ @@ -325,11 +325,11 @@ class ScriptResource(resource.Resource, component.Component): :keyword script_type: The type of scripts to get (normal, debug, dev) :param script_type: string """ - if script_type not in ("dev", "debug", "normal"): + if script_type not in ('dev', 'debug', 'normal'): script_type = 'normal' - _scripts = self.__scripts[script_type]["scripts"] - _order = self.__scripts[script_type]["order"] + _scripts = self.__scripts[script_type]['scripts'] + _order = self.__scripts[script_type]['order'] scripts = [] for path in _order: @@ -340,34 +340,34 @@ class ScriptResource(resource.Resource, component.Component): filepath, recurse = _scripts[path] for root, dirnames, filenames in os.walk(filepath): dirnames.sort(reverse=True) - files = sorted(fnmatch.filter(filenames, "*.js")) + files = sorted(fnmatch.filter(filenames, '*.js')) - order_file = os.path.join(root, ".order") + order_file = os.path.join(root, '.order') if os.path.isfile(order_file): - with open(order_file, "r") as _file: + with open(order_file, 'r') as _file: for line in _file: - if line.startswith("+ "): + if line.startswith('+ '): order_filename = line.split()[1] files.pop(files.index(order_filename)) files.insert(0, order_filename) # Ensure sub-directory scripts are top of list with root directory scripts bottom. if dirnames: - scripts.extend(["js/" + os.path.basename(root) + "/" + f for f in files]) + scripts.extend(['js/' + os.path.basename(root) + '/' + f for f in files]) else: - dirpath = os.path.basename(os.path.dirname(root)) + "/" + os.path.basename(root) + dirpath = os.path.basename(os.path.dirname(root)) + '/' + os.path.basename(root) for filename in reversed(files): - scripts.insert(script_idx, "js/" + dirpath + "/" + filename) + scripts.insert(script_idx, 'js/' + dirpath + '/' + filename) if not recurse: break else: - scripts.append("js/" + path) + scripts.append('js/' + path) return scripts def getChild(self, path, request): # NOQA - if hasattr(request, "lookup_path"): - request.lookup_path += "/" + path + if hasattr(request, 'lookup_path'): + request.lookup_path += '/' + path else: request.lookup_path = path return self @@ -375,8 +375,8 @@ class ScriptResource(resource.Resource, component.Component): def render(self, request): log.debug("Requested path: '%s'", request.lookup_path) - for script_type in ("dev", "debug", "normal"): - scripts = self.__scripts[script_type]["scripts"] + for script_type in ('dev', 'debug', 'normal'): + scripts = self.__scripts[script_type]['scripts'] for pattern in scripts: if not request.lookup_path.startswith(pattern): continue @@ -392,64 +392,64 @@ class ScriptResource(resource.Resource, component.Component): log.debug("Serving path: '%s'", path) mime_type = mimetypes.guess_type(path) - request.setHeader("content-type", mime_type[0]) - with open(path, "rb") as _file: + request.setHeader('content-type', mime_type[0]) + with open(path, 'rb') as _file: data = _file.read() return compress(data, request) request.setResponseCode(http.NOT_FOUND) - return "<h1>404 - Not Found</h1>" + return '<h1>404 - Not Found</h1>' class TopLevel(resource.Resource): addSlash = True __stylesheets = [ - "css/ext-all-notheme.css", - "css/ext-extensions.css", - "css/deluge.css" + 'css/ext-all-notheme.css', + 'css/ext-extensions.css', + 'css/deluge.css' ] def __init__(self): resource.Resource.__init__(self) - self.putChild("css", LookupResource("Css", rpath("css"))) - self.putChild("gettext.js", GetText()) - self.putChild("flag", Flag()) - self.putChild("icons", LookupResource("Icons", rpath("icons"))) - self.putChild("images", LookupResource("Images", rpath("images"))) + self.putChild('css', LookupResource('Css', rpath('css'))) + self.putChild('gettext.js', GetText()) + self.putChild('flag', Flag()) + self.putChild('icons', LookupResource('Icons', rpath('icons'))) + self.putChild('images', LookupResource('Images', rpath('images'))) js = ScriptResource() # configure the dev scripts - js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "dev") - js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "dev") - js.add_script_folder("ext-extensions", rpath("js", "extjs", "ext-extensions"), "dev") - js.add_script_folder("deluge-all", rpath("js", "deluge-all"), "dev") + js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'dev') + js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'dev') + js.add_script_folder('ext-extensions', rpath('js', 'extjs', 'ext-extensions'), 'dev') + js.add_script_folder('deluge-all', rpath('js', 'deluge-all'), 'dev') # configure the debug scripts - js.add_script("ext-base-debug.js", rpath("js", "extjs", "ext-base-debug.js"), "debug") - js.add_script("ext-all-debug.js", rpath("js", "extjs", "ext-all-debug.js"), "debug") - js.add_script("ext-extensions-debug.js", rpath("js", "extjs", "ext-extensions-debug.js"), "debug") - js.add_script("deluge-all-debug.js", rpath("js", "deluge-all-debug.js"), "debug") + js.add_script('ext-base-debug.js', rpath('js', 'extjs', 'ext-base-debug.js'), 'debug') + js.add_script('ext-all-debug.js', rpath('js', 'extjs', 'ext-all-debug.js'), 'debug') + js.add_script('ext-extensions-debug.js', rpath('js', 'extjs', 'ext-extensions-debug.js'), 'debug') + js.add_script('deluge-all-debug.js', rpath('js', 'deluge-all-debug.js'), 'debug') # configure the normal scripts - js.add_script("ext-base.js", rpath("js", "extjs", "ext-base.js")) - js.add_script("ext-all.js", rpath("js", "extjs", "ext-all.js")) - js.add_script("ext-extensions.js", rpath("js", "extjs", "ext-extensions.js")) - js.add_script("deluge-all.js", rpath("js", "deluge-all.js")) + js.add_script('ext-base.js', rpath('js', 'extjs', 'ext-base.js')) + js.add_script('ext-all.js', rpath('js', 'extjs', 'ext-all.js')) + js.add_script('ext-extensions.js', rpath('js', 'extjs', 'ext-extensions.js')) + js.add_script('deluge-all.js', rpath('js', 'deluge-all.js')) self.js = js - self.putChild("js", js) - self.putChild("json", JSON()) - self.putChild("upload", Upload()) - self.putChild("render", Render()) - self.putChild("themes", static.File(rpath("themes"))) - self.putChild("tracker", Tracker()) - - theme = component.get("DelugeWeb").config["theme"] - if not os.path.isfile(rpath("themes", "css", "xtheme-%s.css" % theme)): - theme = CONFIG_DEFAULTS.get("theme") - self.__stylesheets.insert(1, "themes/css/xtheme-%s.css" % theme) + self.putChild('js', js) + self.putChild('json', JSON()) + self.putChild('upload', Upload()) + self.putChild('render', Render()) + self.putChild('themes', static.File(rpath('themes'))) + self.putChild('tracker', Tracker()) + + theme = component.get('DelugeWeb').config['theme'] + if not os.path.isfile(rpath('themes', 'css', 'xtheme-%s.css' % theme)): + theme = CONFIG_DEFAULTS.get('theme') + self.__stylesheets.insert(1, 'themes/css/xtheme-%s.css' % theme) @property def stylesheets(self): @@ -478,7 +478,7 @@ class TopLevel(resource.Resource): self.__debug_scripts.remove(script) def getChild(self, path, request): # NOQA - if path == "": + if path == '': return self else: return resource.Resource.getChild(self, path, request) @@ -486,7 +486,7 @@ class TopLevel(resource.Resource): def getChildWithDefault(self, path, request): # NOQA # Calculate the request base header = request.getHeader('x-deluge-base') - base = header if header else component.get("DelugeWeb").base + base = header if header else component.get('DelugeWeb').base # validate the base parameter if not base: @@ -503,37 +503,37 @@ class TopLevel(resource.Resource): return resource.Resource.getChildWithDefault(self, path, request) def render(self, request): - uri_true = ("true", "yes", "1") - debug_arg = request.args.get("debug", [""])[-1] in uri_true - dev_arg = request.args.get("dev", [""])[-1] in uri_true - dev_ver = "dev" in common.get_version() + uri_true = ('true', 'yes', '1') + debug_arg = request.args.get('debug', [''])[-1] in uri_true + dev_arg = request.args.get('dev', [''])[-1] in uri_true + dev_ver = 'dev' in common.get_version() - script_type = "normal" + script_type = 'normal' if debug_arg: - script_type = "debug" + script_type = 'debug' # Override debug if dev arg or version. if dev_arg or dev_ver: - script_type = "dev" + script_type = 'dev' if not self.js.has_script_type_files(script_type): if not dev_ver: log.warning("Failed to enable WebUI '%s' mode, script files are missing!", script_type) # Fallback to checking other types in order and selecting first with files available. - for alt_script_type in [x for x in ["normal", "debug", "dev"] if x != script_type]: + for alt_script_type in [x for x in ['normal', 'debug', 'dev'] if x != script_type]: if self.js.has_script_type_files(alt_script_type): script_type = alt_script_type if not dev_ver: log.warning("WebUI falling back to '%s' mode.", script_type) break - scripts = component.get("Scripts").get_scripts(script_type) - scripts.insert(0, "gettext.js") + scripts = component.get('Scripts').get_scripts(script_type) + scripts.insert(0, 'gettext.js') - template = Template(filename=rpath("index.html")) - request.setHeader("content-type", "text/html; charset=utf-8") + template = Template(filename=rpath('index.html')) + request.setHeader('content-type', 'text/html; charset=utf-8') - web_config = component.get("Web").get_config() - web_config["base"] = request.base + web_config = component.get('Web').get_config() + web_config['base'] = request.base config = dict([(key, web_config[key]) for key in UI_CONFIG_KEYS]) js_config = json.dumps(config) # Insert the values into 'index.html' and return. @@ -553,19 +553,19 @@ class DelugeWeb(component.Component): reactor). If False shares the process and twisted reactor from WebUI plugin or tests. """ - component.Component.__init__(self, "DelugeWeb", depend=["Web"]) - self.config = configmanager.ConfigManager("web.conf", defaults=CONFIG_DEFAULTS, file_version=2) + component.Component.__init__(self, 'DelugeWeb', depend=['Web']) + self.config = configmanager.ConfigManager('web.conf', defaults=CONFIG_DEFAULTS, file_version=2) self.config.run_converter((0, 1), 2, self._migrate_config_1_to_2) - self.config.register_set_function("language", self._on_language_changed) + self.config.register_set_function('language', self._on_language_changed) self.socket = None self.top_level = TopLevel() - self.interface = self.config["interface"] - self.port = self.config["port"] - self.https = self.config["https"] - self.pkey = self.config["pkey"] - self.cert = self.config["cert"] - self.base = self.config["base"] + self.interface = self.config['interface'] + self.port = self.config['port'] + self.https = self.config['https'] + self.pkey = self.config['pkey'] + self.cert = self.config['cert'] + self.base = self.config['base'] if options: self.interface = options.interface if options.interface else self.interface @@ -576,7 +576,7 @@ class DelugeWeb(component.Component): elif options.no_ssl: self.https = False - if self.base != "/": + if self.base != '/': # Strip away slashes and serve on the base path as well as root path self.top_level.putChild(self.base.strip('/'), self.top_level) @@ -598,7 +598,7 @@ class DelugeWeb(component.Component): def install_signal_handlers(self): # Since twisted assigns itself all the signals may as well make # use of it. - reactor.addSystemEventTrigger("after", "shutdown", self.shutdown) + reactor.addSystemEventTrigger('after', 'shutdown', self.shutdown) # Twisted doesn't handle windows specific signals so we still # need to attach to those to handle the close correctly. @@ -607,7 +607,7 @@ class DelugeWeb(component.Component): from win32con import CTRL_CLOSE_EVENT, CTRL_SHUTDOWN_EVENT def win_handler(ctrl_type): - log.debug("ctrl type: %s", ctrl_type) + log.debug('ctrl type: %s', ctrl_type) if ctrl_type == CTRL_CLOSE_EVENT or \ ctrl_type == CTRL_SHUTDOWN_EVENT: self.shutdown() @@ -619,27 +619,27 @@ class DelugeWeb(component.Component): Start the DelugeWeb server """ if self.socket: - log.warn("DelugeWeb is already running and cannot be started") + log.warn('DelugeWeb is already running and cannot be started') return - log.info("Starting webui server at PID %s", os.getpid()) + log.info('Starting webui server at PID %s', os.getpid()) if self.https: self.start_ssl() else: self.start_normal() - component.get("Web").enable() + component.get('Web').enable() if self.daemon: reactor.run() def start_normal(self): self.socket = reactor.listenTCP(self.port, self.site, interface=self.interface) - log.info("Serving at http://%s:%s%s", self.interface, self.port, self.base) + log.info('Serving at http://%s:%s%s', self.interface, self.port, self.base) def start_ssl(self): check_ssl_keys() - log.debug("Enabling SSL with PKey: %s, Cert: %s", self.pkey, self.cert) + log.debug('Enabling SSL with PKey: %s, Cert: %s', self.pkey, self.cert) with open(configmanager.get_config_dir(self.cert)) as cert: certificate = Certificate.loadPEM(cert.read()).original @@ -649,17 +649,17 @@ class DelugeWeb(component.Component): options.getContext().set_options(SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3) self.socket = reactor.listenSSL(self.port, self.site, options, interface=self.interface) - log.info("Serving at https://%s:%s%s", self.interface, self.port, self.base) + log.info('Serving at https://%s:%s%s', self.interface, self.port, self.base) def stop(self): - log.info("Shutting down webserver") + log.info('Shutting down webserver') try: - component.get("Web").disable() + component.get('Web').disable() except KeyError: pass self.plugins.disable_plugins() - log.debug("Saving configuration file") + log.debug('Saving configuration file') self.config.save() if self.socket: @@ -676,16 +676,16 @@ class DelugeWeb(component.Component): reactor.stop() def _migrate_config_1_to_2(self, config): - config["language"] = CONFIG_DEFAULTS["language"] + config['language'] = CONFIG_DEFAULTS['language'] return config -if __name__ == "__builtin__": +if __name__ == '__builtin__': deluge_web = DelugeWeb() - application = service.Application("DelugeWeb") + application = service.Application('DelugeWeb') sc = service.IServiceCollection(application) i = internet.TCPServer(deluge_web.port, deluge_web.site) i.setServiceParent(sc) -elif __name__ == "__main__": +elif __name__ == '__main__': deluge_web = DelugeWeb() deluge_web.start() diff --git a/deluge/ui/web/web.py b/deluge/ui/web/web.py index dd3aab5b7..38c725aed 100644 --- a/deluge/ui/web/web.py +++ b/deluge/ui/web/web.py @@ -24,18 +24,18 @@ class Web(UI): cmd_description = """Web-based user interface (http://localhost:8112)""" def __init__(self, *args, **kwargs): - super(Web, self).__init__("web", *args, description="Starts the Deluge Web interface", **kwargs) + super(Web, self).__init__('web', *args, description='Starts the Deluge Web interface', **kwargs) self.__server = None - group = self.parser.add_argument_group(_("Web Server Options")) - group.add_argument("-i", "--interface", metavar="<ip_address>", action="store", - help=_("IP address for web server to listen on")) - group.add_argument("-p", "--port", metavar="<port>", type=int, action="store", - help=_("Port for web server to listen on")) - group.add_argument("-b", "--base", metavar="<path>", action="store", - help=_("Set the base path that the ui is running on")) - group.add_argument("--ssl", action="store_true", help=_("Force the web server to use SSL")) - group.add_argument("--no-ssl", action="store_true", help=_("Force the web server to disable SSL")) + group = self.parser.add_argument_group(_('Web Server Options')) + group.add_argument('-i', '--interface', metavar='<ip_address>', action='store', + help=_('IP address for web server to listen on')) + group.add_argument('-p', '--port', metavar='<port>', type=int, action='store', + help=_('Port for web server to listen on')) + group.add_argument('-b', '--base', metavar='<path>', action='store', + help=_('Set the base path that the ui is running on')) + group.add_argument('--ssl', action='store_true', help=_('Force the web server to use SSL')) + group.add_argument('--no-ssl', action='store_true', help=_('Force the web server to disable SSL')) self.parser.add_process_arg_group() @property @@ -53,7 +53,7 @@ class Web(UI): self.server.install_signal_handlers() self.server.start() except CannotListenError as ex: - log.error("%s \nCheck that deluge-web or webui plugin is not already running.", ex) + log.error('%s \nCheck that deluge-web or webui plugin is not already running.', ex) except Exception as ex: log.exception(ex) raise |