Pass console config to torrentdetail and format_utils, add an option to disable three dots when trimming columns(they piss me off)

This commit is contained in:
Asmageddon 2012-02-29 20:33:58 +01:00
commit b1439274c6
4 changed files with 52 additions and 38 deletions

View file

@ -115,7 +115,7 @@ files in the torrent and the ability to set file priorities.
{!info!}Enter{!normal!} - Show torrent actions popup. Here you can do things like \ {!info!}Enter{!normal!} - Show torrent actions popup. Here you can do things like \
pause/resume, remove, recheck and so on. These actions \ pause/resume, remove, recheck and so on. These actions \
apply to all currently marked torrents. The currently \ apply to all currently marked torrents. The currently \
selected torrent is automatically marked when you press enter. selected torrent is automatically marked when you press enter.
{!info!}'q'/Esc{!normal!} - Close a popup (Note that Esc can take a moment to register \ {!info!}'q'/Esc{!normal!} - Close a popup (Note that Esc can take a moment to register \
as having been pressed. as having been pressed.
@ -168,6 +168,7 @@ DEFAULT_PREFS = {
"downloaded_width":13, "downloaded_width":13,
"uploaded_width":13, "uploaded_width":13,
"owner_width":10, "owner_width":10,
"disable_three_dots": False
} }
column_pref_names = ["queue","name","size","state", column_pref_names = ["queue","name","size","state",
@ -178,7 +179,7 @@ column_pref_names = ["queue","name","size","state",
"owner"] "owner"]
prefs_to_names = { prefs_to_names = {
"queue":"#", "queue":"#",
"name":"Name", "name":"Name",
"size":"Size", "size":"Size",
"state":"State", "state":"State",
@ -257,7 +258,7 @@ class AllTorrents(BaseMode, component.Component):
self.__status_keys = ["name","state","download_payload_rate","upload_payload_rate", self.__status_keys = ["name","state","download_payload_rate","upload_payload_rate",
"progress","eta","all_time_download","total_uploaded", "ratio", "progress","eta","all_time_download","total_uploaded", "ratio",
"num_seeds","total_seeds","num_peers","total_peers", "active_time", "num_seeds","total_seeds","num_peers","total_peers", "active_time",
"seeding_time","time_added","distributed_copies", "num_pieces", "seeding_time","time_added","distributed_copies", "num_pieces",
"piece_length","save_path"] "piece_length","save_path"]
# component start/update # component start/update
@ -285,7 +286,7 @@ class AllTorrents(BaseMode, component.Component):
self._go_top = True self._go_top = True
component.start(["AllTorrents"]) component.start(["AllTorrents"])
self.refresh() self.refresh()
def __update_columns(self): def __update_columns(self):
self.column_widths = [self.config["%s_width"%c] for c in self.__cols_to_show] self.column_widths = [self.config["%s_width"%c] for c in self.__cols_to_show]
req = sum(filter(lambda x:x >= 0,self.column_widths)) req = sum(filter(lambda x:x >= 0,self.column_widths))
@ -313,7 +314,7 @@ class AllTorrents(BaseMode, component.Component):
for torrent_id in self._sorted_ids: for torrent_id in self._sorted_ids:
ts = self.curstate[torrent_id] ts = self.curstate[torrent_id]
newnames.append(ts["name"]) newnames.append(ts["name"])
newrows.append((format_utils.format_row([column.get_column_value(name,ts) for name in self.__columns],self.column_widths),ts["state"])) newrows.append((format_utils.format_row([column.get_column_value(name,ts) for name in self.__columns],self.column_widths, self.config),ts["state"]))
self.numtorrents = len(state) self.numtorrents = len(state)
self.formatted_rows = newrows self.formatted_rows = newrows
@ -371,7 +372,7 @@ class AllTorrents(BaseMode, component.Component):
info = f[1](*args) info = f[1](*args)
else: else:
info = state[f[2][0]] info = state[f[2][0]]
nl = len(f[0])+4 nl = len(f[0])+4
if (nl+len(info))>self.popup.width: if (nl+len(info))>self.popup.width:
self.popup.add_line("{!info!}%s: {!input!}%s"%(f[0],info[:(self.popup.width - nl)])) self.popup.add_line("{!info!}%s: {!input!}%s"%(f[0],info[:(self.popup.width - nl)]))
@ -385,7 +386,7 @@ class AllTorrents(BaseMode, component.Component):
self.refresh() self.refresh()
else: else:
self.__torrent_info_id = None self.__torrent_info_id = None
def on_resize(self, *args): def on_resize(self, *args):
BaseMode.on_resize_norefresh(self, *args) BaseMode.on_resize_norefresh(self, *args)
@ -422,7 +423,7 @@ class AllTorrents(BaseMode, component.Component):
def dodeets(arg): def dodeets(arg):
if arg and True in arg[0]: if arg and True in arg[0]:
self.stdscr.clear() self.stdscr.clear()
component.get("ConsoleUI").set_mode(TorrentDetail(self,tid,self.stdscr,self.encoding)) component.get("ConsoleUI").set_mode(TorrentDetail(self,tid,self.stdscr, self.config, self.encoding))
else: else:
self.messages.append(("Error","An error occured trying to display torrent details")) self.messages.append(("Error","An error occured trying to display torrent details"))
component.stop(["AllTorrents"]).addCallback(dodeets) component.stop(["AllTorrents"]).addCallback(dodeets)
@ -444,7 +445,7 @@ class AllTorrents(BaseMode, component.Component):
component.stop(["AllTorrents"]).addCallback(doprefs) component.stop(["AllTorrents"]).addCallback(doprefs)
client.core.get_config().addCallback(_on_get_config) client.core.get_config().addCallback(_on_get_config)
def __show_events(self): def __show_events(self):
def doevents(arg): def doevents(arg):
@ -642,13 +643,13 @@ class AllTorrents(BaseMode, component.Component):
fg = "green" fg = "green"
elif row[1] == "Seeding": elif row[1] == "Seeding":
fg = "cyan" fg = "cyan"
elif row[1] == "Error": elif row[1] == "Error":
fg = "red" fg = "red"
elif row[1] == "Queued": elif row[1] == "Queued":
fg = "yellow" fg = "yellow"
elif row[1] == "Checking": elif row[1] == "Checking":
fg = "blue" fg = "blue"
if attr: if attr:
colorstr = "{!%s,%s,%s!}"%(fg,bg,attr) colorstr = "{!%s,%s,%s!}"%(fg,bg,attr)
else: else:
@ -656,7 +657,7 @@ class AllTorrents(BaseMode, component.Component):
self.add_string(currow,"%s%s"%(colorstr,row[0]),trim=False) self.add_string(currow,"%s%s"%(colorstr,row[0]),trim=False)
tidx += 1 tidx += 1
currow += 1 currow += 1
if (currow > (self.rows - 2)): if (currow > (self.rows - 2)):
break break
else: else:
@ -757,7 +758,7 @@ class AllTorrents(BaseMode, component.Component):
reactor.stop() reactor.stop()
client.disconnect().addCallback(on_disconnect) client.disconnect().addCallback(on_disconnect)
else: else:
reactor.stop() reactor.stop()
return return
if self.formatted_rows==None or self.popup: if self.formatted_rows==None or self.popup:
@ -771,7 +772,7 @@ class AllTorrents(BaseMode, component.Component):
#log.error("pressed key: %d\n",c) #log.error("pressed key: %d\n",c)
#if c == 27: # handle escape #if c == 27: # handle escape
# log.error("CANCEL") # log.error("CANCEL")
# Navigate the torrent list # Navigate the torrent list
if c == curses.KEY_UP: if c == curses.KEY_UP:
if self.cursel == 1: return if self.cursel == 1: return

View file

@ -80,11 +80,14 @@ def format_priority(prio):
else: else:
return pstring return pstring
def trim_string(string, w, have_dbls): def trim_string(string, w, have_dbls, console_config):
if w <= 0: if w <= 0:
return "" return ""
elif w == 1: elif w == 1:
return u"" if console_config["disable_three_dots"]:
return u" "
else:
return u""
elif have_dbls: elif have_dbls:
# have to do this the slow way # have to do this the slow way
chrs = [] chrs = []
@ -100,11 +103,17 @@ def trim_string(string, w, have_dbls):
if width != w: if width != w:
chrs.pop() chrs.pop()
chrs.append('.') chrs.append('.')
return u"%s"%("".join(chrs)) if console_config["disable_three_dots"]:
return u"%s "%("".join(chrs))
else:
return u"%s"%("".join(chrs))
else: else:
return u"%s"%(string[0:w-2]) if console_config["disable_three_dots"]:
return u"%s "%(string[0:w-1])
else:
return u"%s"%(string[0:w-2])
def format_column(col, lim): def format_column(col, lim, console_config):
dbls = 0 dbls = 0
if haveud and isinstance(col,unicode): if haveud and isinstance(col,unicode):
# might have some double width chars # might have some double width chars
@ -115,12 +124,12 @@ def format_column(col, lim):
dbls += 1 dbls += 1
size = len(col)+dbls size = len(col)+dbls
if (size >= lim - 1): if (size >= lim - 1):
return trim_string(col,lim,dbls>0) return trim_string(col,lim,dbls>0, console_config)
else: else:
return "%s%s"%(col," "*(lim-size)) return "%s%s"%(col," "*(lim-size))
def format_row(row,column_widths): def format_row(row,column_widths, console_config):
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], console_config) for i in range(0,len(row))])
import re import re
from collections import deque from collections import deque
@ -132,7 +141,7 @@ def wrap_string(string,width,min_lines=0,strip_colors=True):
:param string: str, the string to wrap :param string: str, the string to wrap
:param width: int, the maximum width of a line of text :param width: int, the maximum width of a line of text
:param min_lines: int, extra lines will be added so the output tuple contains at least min_lines lines :param min_lines: int, extra lines will be added so the output tuple contains at least min_lines lines
:param strip_colors: boolean, if True, text in {!!} blocks will not be considered as adding to the :param strip_colors: boolean, if True, text in {!!} blocks will not be considered as adding to the
width of the line. They will still be present in the output. width of the line. They will still be present in the output.
""" """
ret = [] ret = []

View file

@ -92,10 +92,10 @@ class BasePane:
self.width = width self.width = width
self.inputs = [] self.inputs = []
self.active_input = -1 self.active_input = -1
# have we scrolled down in the list # have we scrolled down in the list
self.input_offset = 0 self.input_offset = 0
def move(self,r,c): def move(self,r,c):
self._cursor_row = r self._cursor_row = r
self._cursor_col = c self._cursor_col = c
@ -109,7 +109,7 @@ class BasePane:
if ipt.name == "listen_ports_to": if ipt.name == "listen_ports_to":
conf_dict["listen_ports"] = (self.infrom.get_value(),self.into.get_value()) conf_dict["listen_ports"] = (self.infrom.get_value(),self.into.get_value())
if ipt.name == "out_ports_to": if ipt.name == "out_ports_to":
conf_dict["outgoing_ports"] = (self.outfrom.get_value(),self.outto.get_value()) conf_dict["outgoing_ports"] = (self.outfrom.get_value(),self.outto.get_value())
else: else:
conf_dict[ipt.name] = ipt.get_value() conf_dict[ipt.name] = ipt.get_value()
if hasattr(ipt,"get_child"): if hasattr(ipt,"get_child"):
@ -182,7 +182,7 @@ class BasePane:
nc = min(self.active_input+1,ilen-1) nc = min(self.active_input+1,ilen-1)
while isinstance(self.inputs[nc], NoInput) or self.inputs[nc].depend_skip(): while isinstance(self.inputs[nc], NoInput) or self.inputs[nc].depend_skip():
nc+=1 nc+=1
if nc >= ilen: if nc >= ilen:
nc-=1 nc-=1
break break
if not isinstance(self.inputs[nc], NoInput) or self.inputs[nc].depend_skip(): if not isinstance(self.inputs[nc], NoInput) or self.inputs[nc].depend_skip():
@ -287,7 +287,7 @@ class NetworkPane(BasePane):
self.add_select_input("enc_out_policy","Outbound:",["Forced","Enabled","Disabled"],[0,1,2],parent.core_config["enc_out_policy"]) self.add_select_input("enc_out_policy","Outbound:",["Forced","Enabled","Disabled"],[0,1,2],parent.core_config["enc_out_policy"])
self.add_select_input("enc_level","Level:",["Handshake","Full Stream","Either"],[0,1,2],parent.core_config["enc_level"]) self.add_select_input("enc_level","Level:",["Handshake","Full Stream","Either"],[0,1,2],parent.core_config["enc_level"])
self.add_checked_input("enc_prefer_rc4","Encrypt Entire Stream",parent.core_config["enc_prefer_rc4"]) self.add_checked_input("enc_prefer_rc4","Encrypt Entire Stream",parent.core_config["enc_prefer_rc4"])
class BandwidthPane(BasePane): class BandwidthPane(BasePane):
def __init__(self, offset, parent, width): def __init__(self, offset, parent, width):
@ -310,6 +310,8 @@ class BandwidthPane(BasePane):
class InterfacePane(BasePane): class InterfacePane(BasePane):
def __init__(self, offset, parent, width): def __init__(self, offset, parent, width):
BasePane.__init__(self,offset,parent,width) BasePane.__init__(self,offset,parent,width)
self.add_header("General")
self.add_checked_input("disable_three_dots","Do not append three dots symbol when trimming columns",parent.console_config["disable_three_dots"])
self.add_header("Columns To Display") self.add_header("Columns To Display")
for cpn in deluge.ui.console.modes.alltorrents.column_pref_names: for cpn in deluge.ui.console.modes.alltorrents.column_pref_names:
pn = "show_%s"%cpn pn = "show_%s"%cpn
@ -379,7 +381,7 @@ class CachePane(BasePane):
self.add_info_field(" Blocks Written:",self.parent.status["blocks_written"],"blocks_written") self.add_info_field(" Blocks Written:",self.parent.status["blocks_written"],"blocks_written")
self.add_info_field(" Writes:",self.parent.status["writes"],"writes") self.add_info_field(" Writes:",self.parent.status["writes"],"writes")
self.add_info_field(" Write Cache Hit Ratio:","%.2f"%self.parent.status["write_hit_ratio"],"write_hit_ratio") self.add_info_field(" Write Cache Hit Ratio:","%.2f"%self.parent.status["write_hit_ratio"],"write_hit_ratio")
self.add_header(" Read") self.add_header(" Read")
self.add_info_field(" Blocks Read:",self.parent.status["blocks_read"],"blocks_read") self.add_info_field(" Blocks Read:",self.parent.status["blocks_read"],"blocks_read")
self.add_info_field(" Blocks Read hit:",self.parent.status["blocks_read_hit"],"blocks_read_hit") self.add_info_field(" Blocks Read hit:",self.parent.status["blocks_read_hit"],"blocks_read_hit")
self.add_info_field(" Reads:",self.parent.status["reads"],"reads") self.add_info_field(" Reads:",self.parent.status["reads"],"reads")

View file

@ -89,7 +89,9 @@ download priority of selected files.
""" """
class TorrentDetail(BaseMode, component.Component): class TorrentDetail(BaseMode, component.Component):
def __init__(self, alltorrentmode, torrentid, stdscr, encoding=None): def __init__(self, alltorrentmode, torrentid, stdscr, console_config, encoding=None):
self.console_config = console_config
self.alltorrentmode = alltorrentmode self.alltorrentmode = alltorrentmode
self.torrentid = torrentid self.torrentid = torrentid
self.torrent_state = None self.torrent_state = None
@ -98,7 +100,7 @@ class TorrentDetail(BaseMode, component.Component):
self._status_keys = ["files", "name","state","download_payload_rate","upload_payload_rate", self._status_keys = ["files", "name","state","download_payload_rate","upload_payload_rate",
"progress","eta","all_time_download","total_uploaded", "ratio", "progress","eta","all_time_download","total_uploaded", "ratio",
"num_seeds","total_seeds","num_peers","total_peers", "active_time", "num_seeds","total_seeds","num_peers","total_peers", "active_time",
"seeding_time","time_added","distributed_copies", "num_pieces", "seeding_time","time_added","distributed_copies", "num_pieces",
"piece_length","save_path","file_progress","file_priorities","message"] "piece_length","save_path","file_progress","file_priorities","message"]
self._info_fields = [ self._info_fields = [
("Name",None,("name",)), ("Name",None,("name",)),
@ -181,7 +183,7 @@ class TorrentDetail(BaseMode, component.Component):
# particular directory are returned together. it won't work otherwise. # particular directory are returned together. it won't work otherwise.
# returned list is a list of lists of the form: # returned list is a list of lists of the form:
# [file/dir_name,index,size,children,expanded,progress,priority] # [file/dir_name,index,size,children,expanded,progress,priority]
# for directories index values count down from maxint (for marking usage), # for directories index values count down from maxint (for marking usage),
# for files the index is the value returned in the # for files the index is the value returned in the
# state object for use with other libtorrent calls (i.e. setting prio) # state object for use with other libtorrent calls (i.e. setting prio)
# #
@ -280,11 +282,11 @@ class TorrentDetail(BaseMode, component.Component):
self.popup = pu self.popup = pu
self.refresh() self.refresh()
def draw_files(self,files,depth,off,idx): def draw_files(self,files,depth,off,idx):
for fl in files: for fl in files:
# kick out if we're going to draw too low on the screen # kick out if we're going to draw too low on the screen
if (off >= self.rows-1): if (off >= self.rows-1):
self.more_to_draw = True self.more_to_draw = True
return -1,-1 return -1,-1
@ -321,8 +323,8 @@ class TorrentDetail(BaseMode, component.Component):
r = format_utils.format_row(["%s%s %s"%(" "*depth,xchar,fl[0]), r = format_utils.format_row(["%s%s %s"%(" "*depth,xchar,fl[0]),
deluge.common.fsize(fl[2]),fl[5], deluge.common.fsize(fl[2]),fl[5],
format_utils.format_priority(fl[6])], format_utils.format_priority(fl[6])],
self.column_widths) self.column_widths, self.console_config)
self.add_string(off,"%s%s"%(color_string,r),trim=False) self.add_string(off,"%s%s"%(color_string,r),trim=False)
off += 1 off += 1
@ -373,7 +375,7 @@ class TorrentDetail(BaseMode, component.Component):
info = f[1](*args) info = f[1](*args)
else: else:
info = self.torrent_state[f[2][0]] info = self.torrent_state[f[2][0]]
self.add_string(off,"{!info!}%s: {!input!}%s"%(f[0],info)) self.add_string(off,"{!info!}%s: {!input!}%s"%(f[0],info))
off += 1 off += 1
else: else:
@ -488,7 +490,7 @@ class TorrentDetail(BaseMode, component.Component):
reactor.stop() reactor.stop()
client.disconnect().addCallback(on_disconnect) client.disconnect().addCallback(on_disconnect)
else: else:
reactor.stop() reactor.stop()
return return
elif chr(c) == 'q': elif chr(c) == 'q':
self.back_to_overview() self.back_to_overview()