Colors are user configurable

- Colors are mapped on to a dictionary using abstract names (e.g., text_success)
- Add `colors` option under `ui` to allow users to choose their own color scheme
- Move configuration option `color` from top-level to `ui`
- Show deprecation warning if top-level `color` configuration is used (but respect it)

Fix #1238
This commit is contained in:
Tom Jaspers 2015-01-26 17:24:32 +01:00
parent 67e1065229
commit d3fce35481
5 changed files with 60 additions and 26 deletions

View file

@ -41,7 +41,6 @@ max_filename_length: 0
plugins: []
pluginpath: []
threaded: yes
color: yes
timeout: 5.0
per_disc_numbering: no
verbose: no
@ -52,6 +51,15 @@ id3v23: no
ui:
terminal_width: 80
length_diff_thresh: 10.0
color: yes
colors:
text_success: green
text_warning: yellow
text_error: red
text_highlight: red
text_highlight_minor: lightgray
action_default: turquoise
action: blue
list_format_item: $artist - $album - $title
list_format_album: $albumartist - $album

View file

@ -191,7 +191,9 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None,
is_default = False
# Colorize the letter shortcut.
show_letter = colorize('turquoise' if is_default else 'blue',
show_letter = colorize(COLORS['action_default']
if is_default
else COLORS['action'],
show_letter)
# Insert the highlighted letter back into the word.
@ -218,7 +220,7 @@ def input_options(options, require=False, prompt=None, fallback_prompt=None,
if numrange:
if isinstance(default, int):
default_name = str(default)
default_name = colorize('turquoise', default_name)
default_name = colorize(COLORS['action_default'], default_name)
tmpl = '# selection (default %s)'
prompt_parts.append(tmpl % default_name)
prompt_part_lengths.append(len(tmpl % str(default)))
@ -357,6 +359,13 @@ LIGHT_COLORS = ["darkgray", "red", "green", "yellow", "blue",
"fuchsia", "turquoise", "white"]
RESET_COLOR = COLOR_ESCAPE + "39;49;00m"
# Map the color names to the configured colors in a dict
COLOR_NAMES = ['text_success', 'text_warning', 'text_error', 'text_highlight',
'text_highlight_minor', 'action_default', 'action']
COLORS = dict(zip(COLOR_NAMES,
map(lambda x: config['ui']['colors'][x].get(str),
COLOR_NAMES)))
def _colorize(color, text):
"""Returns a string that prints the given text in the given color
@ -376,13 +385,14 @@ def colorize(color, text):
"""Colorize text if colored output is enabled. (Like _colorize but
conditional.)
"""
if config['color']:
if config['ui']['color']:
return _colorize(color, text)
else:
return text
def _colordiff(a, b, highlight='red', minor_highlight='lightgray'):
def _colordiff(a, b, highlight=COLORS['text_highlight'],
minor_highlight=COLORS['text_highlight_minor']):
"""Given two values, return the same pair of strings except with
their differences highlighted in the specified color. Strings are
highlighted intelligently to show differences; other values are
@ -432,11 +442,11 @@ def _colordiff(a, b, highlight='red', minor_highlight='lightgray'):
return u''.join(a_out), u''.join(b_out)
def colordiff(a, b, highlight='red'):
def colordiff(a, b, highlight=COLORS['text_highlight']):
"""Colorize differences between two values if color is enabled.
(Like _colordiff but conditional.)
"""
if config['color']:
if config['ui']['color']:
return _colordiff(a, b, highlight)
else:
return unicode(a), unicode(b)
@ -546,7 +556,8 @@ def _field_diff(field, old, new):
if isinstance(oldval, basestring):
oldstr, newstr = colordiff(oldval, newstr)
else:
oldstr, newstr = colorize('red', oldstr), colorize('red', newstr)
oldstr = colorize(COLORS['text_error'], oldstr)
newstr = colorize(COLORS['text_error'], newstr)
return u'{0} -> {1}'.format(oldstr, newstr)
@ -582,7 +593,7 @@ def show_model_changes(new, old=None, fields=None, always=False):
changes.append(u' {0}: {1}'.format(
field,
colorize('red', new.formatted()[field])
colorize(COLORS['text_highlight'], new.formatted()[field])
))
# Print changes.
@ -865,6 +876,14 @@ def _configure(options):
else:
log.setLevel(logging.INFO)
# Ensure compatibility with old (top-level) color configuration.
# Deprecation msg to motivate user to switch to config['ui']['color].
if config['color'].exists():
log.warning(u'Warning: top-level configuration of `color` '
u'is deprecated. Configure color use under `ui`. '
u'See documentation for more info.')
config['ui']['color'].set(config['color'].get(bool))
config_path = config.user_config_path()
if os.path.isfile(config_path):
log.debug(u'user configuration: {0}',

View file

@ -175,11 +175,11 @@ def dist_string(dist):
"""
out = '%.1f%%' % ((1 - dist) * 100)
if dist <= config['match']['strong_rec_thresh'].as_number():
out = ui.colorize('green', out)
out = ui.colorize(ui.COLORS['text_success'], out)
elif dist <= config['match']['medium_rec_thresh'].as_number():
out = ui.colorize('yellow', out)
out = ui.colorize(ui.COLORS['text_warning'], out)
else:
out = ui.colorize('red', out)
out = ui.colorize(ui.COLORS['text_error'], out)
return out
@ -196,7 +196,8 @@ def penalty_string(distance, limit=None):
if penalties:
if limit and len(penalties) > limit:
penalties = penalties[:limit] + ['...']
return ui.colorize('yellow', '(%s)' % ', '.join(penalties))
return ui.colorize(ui.COLORS['text_warning'],
'(%s)' % ', '.join(penalties))
def show_change(cur_artist, cur_album, match):
@ -269,7 +270,8 @@ def show_change(cur_artist, cur_album, match):
# Disambiguation.
disambig = disambig_string(match.info)
if disambig:
info.append(ui.colorize('lightgray', '(%s)' % disambig))
info.append(ui.colorize(ui.COLORS['text_highlight_minor'],
'(%s)' % disambig))
print_(' '.join(info))
# Tracks.
@ -314,9 +316,9 @@ def show_change(cur_artist, cur_album, match):
cur_track, new_track = format_index(item), format_index(track_info)
if cur_track != new_track:
if item.track in (track_info.index, track_info.medium_index):
color = 'lightgray'
color = ui.COLORS['text_highlight_minor']
else:
color = 'red'
color = ui.COLORS['text_highlight']
templ = ui.colorize(color, u' (#{0})')
lhs += templ.format(cur_track)
rhs += templ.format(new_track)
@ -328,7 +330,7 @@ def show_change(cur_artist, cur_album, match):
config['ui']['length_diff_thresh'].as_number():
cur_length = ui.human_seconds_short(item.length)
new_length = ui.human_seconds_short(track_info.length)
templ = ui.colorize('red', u' ({0})')
templ = ui.colorize(ui.COLORS['text_highlight'], u' ({0})')
lhs += templ.format(cur_length)
rhs += templ.format(new_length)
lhs_width += len(cur_length) + 3
@ -363,14 +365,14 @@ def show_change(cur_artist, cur_album, match):
line = ' ! %s (#%s)' % (track_info.title, format_index(track_info))
if track_info.length:
line += ' (%s)' % ui.human_seconds_short(track_info.length)
print_(ui.colorize('yellow', line))
print_(ui.colorize(ui.COLORS['text_warning'], line))
if match.extra_items:
print_('Unmatched tracks:')
for item in match.extra_items:
line = ' ! %s (#%s)' % (item.title, format_index(item))
if item.length:
line += ' (%s)' % ui.human_seconds_short(item.length)
print_(ui.colorize('yellow', line))
print_(ui.colorize(ui.COLORS['text_warning'], line))
def show_item_change(item, match):
@ -407,7 +409,8 @@ def show_item_change(item, match):
# Disambiguation.
disambig = disambig_string(match.info)
if disambig:
info.append(ui.colorize('lightgray', '(%s)' % disambig))
info.append(ui.colorize(ui.COLORS['text_highlight_minor'],
'(%s)' % disambig))
print_(' '.join(info))
@ -566,7 +569,8 @@ def choose_candidate(candidates, singleton, rec, cur_artist=None,
# Disambiguation
disambig = disambig_string(match.info)
if disambig:
line.append(ui.colorize('lightgray', '(%s)' % disambig))
line.append(ui.colorize(ui.COLORS['text_highlight_minor'],
'(%s)' % disambig))
print_(' '.join(line))
@ -1000,7 +1004,7 @@ def update_items(lib, query, album, move, pretend):
# Item deleted?
if not os.path.exists(syspath(item.path)):
ui.print_obj(item, lib)
ui.print_(ui.colorize('red', u' deleted'))
ui.print_(ui.colorize(ui.COLORS['text_error'], u' deleted'))
if not pretend:
item.remove(True)
affected_albums.add(item.album_id)

View file

@ -444,9 +444,11 @@ class FetchArtPlugin(plugins.BeetsPlugin):
if path:
album.set_art(path, False)
album.store()
message = ui.colorize('green', 'found album art')
message = ui.colorize(ui.COLORS['text_success'],
'found album art')
else:
message = ui.colorize('red', 'no art found')
message = ui.colorize(ui.COLORS['text_error'],
'no art found')
self._log.info(u'{0.albumartist} - {0.album}: {1}', album, message)

View file

@ -73,13 +73,14 @@ def play_music(lib, opts, args, log):
item_type += 's' if len(selection) > 1 else ''
if not selection:
ui.print_(ui.colorize('yellow', 'No {0} to play.'.format(item_type)))
ui.print_(ui.colorize(ui.COLORS['text_warning'],
'No {0} to play.'.format(item_type)))
return
# Warn user before playing any huge playlists.
if len(selection) > 100:
ui.print_(ui.colorize(
'yellow',
ui.COLORS['text_warning'],
'You are about to queue {0} {1}.'.format(len(selection), item_type)
))