Cleanups and bugfixes

This commit is contained in:
Florian Bruhin 2014-02-27 23:21:21 +01:00
parent 02b4f2fdda
commit 4ea77c7ec2
4 changed files with 191 additions and 191 deletions

View File

@ -52,8 +52,7 @@ def init(confdir):
class NewConfig: class NewConfig:
"""Contains the structure of the config file.""" """New configuration manager."""
def __init__(self): def __init__(self):
self.config = configdata.configdata() self.config = configdata.configdata()
@ -63,7 +62,6 @@ class NewConfig:
'break_long_words': False, 'break_long_words': False,
'break_on_hyphens': False, 'break_on_hyphens': False,
} }
print(str(self))
def __getitem__(self, key): def __getitem__(self, key):
"""Get a section from the config.""" """Get a section from the config."""
@ -80,6 +78,7 @@ class NewConfig:
return '\n'.join(lines) return '\n'.join(lines)
def _str_section_desc(self, secname): def _str_section_desc(self, secname):
"""Get the section description string for secname."""
wrapper = textwrap.TextWrapper(initial_indent='# ', wrapper = textwrap.TextWrapper(initial_indent='# ',
subsequent_indent='# ', subsequent_indent='# ',
**self._wrapper_args) **self._wrapper_args)
@ -93,6 +92,7 @@ class NewConfig:
return lines return lines
def _str_option_desc(self, secname, section): def _str_option_desc(self, secname, section):
"""Get the option description strings for section/secname."""
wrapper = textwrap.TextWrapper(initial_indent='#' + ' ' * 5, wrapper = textwrap.TextWrapper(initial_indent='#' + ' ' * 5,
subsequent_indent='#' + ' ' * 5, subsequent_indent='#' + ' ' * 5,
**self._wrapper_args) **self._wrapper_args)
@ -126,6 +126,7 @@ class NewConfig:
return lines return lines
def _str_items(self, section): def _str_items(self, section):
"""Get the option items as string for section."""
keyval_wrapper = textwrap.TextWrapper(initial_indent='', keyval_wrapper = textwrap.TextWrapper(initial_indent='',
subsequent_indent=' ' * 4, subsequent_indent=' ' * 4,
drop_whitespace=False, drop_whitespace=False,

View File

@ -94,6 +94,7 @@ SECTION_DESC = {
def configdata(): def configdata():
"""Get the config structure as an OrderedDict."""
MONOSPACE = ('Monospace, "DejaVu Sans Mono", Consolas, Monaco, ' MONOSPACE = ('Monospace, "DejaVu Sans Mono", Consolas, Monaco, '
'"Bitstream Vera Sans Mono", "Andale Mono", ' '"Bitstream Vera Sans Mono", "Andale Mono", '
'"Liberation Mono", "Courier New", Courier, monospace, ' '"Liberation Mono", "Courier New", Courier, monospace, '
@ -115,8 +116,7 @@ def configdata():
('wrapsearch', ('wrapsearch',
SettingValue(types.Bool, "true"), SettingValue(types.Bool, "true"),
"Whether to wrap search to the top when arriving at the " "Whether to wrap search to the top when arriving at the end."),
"end."),
('startpage', ('startpage',
SettingValue(types.List, "http://www.duckduckgo.com"), SettingValue(types.List, "http://www.duckduckgo.com"),
@ -125,12 +125,12 @@ def configdata():
('auto_search', ('auto_search',
SettingValue(types.AutoSearch, "naive"), SettingValue(types.AutoSearch, "naive"),
"Whether to start a search when something else than an URL " "Whether to start a search when something else than an URL is "
"is entered."), "entered."),
('zoomlevels', ('zoomlevels',
SettingValue(types.IntList, "25,33,50,67,75,90,100,110,125," SettingValue(types.IntList, "25,33,50,67,75,90,100,110,125,150,"
"150,175,200,250,300,400,500"), "175,200,250,300,400,500"),
"The available zoom levels, separated by commas."), "The available zoom levels, separated by commas."),
('defaultzoom', ('defaultzoom',
@ -149,8 +149,8 @@ def configdata():
('scrollbuttons', ('scrollbuttons',
SettingValue(types.Bool, "true"), SettingValue(types.Bool, "true"),
"Whether there should be scroll buttons if there are too " "Whether there should be scroll buttons if there are too many "
"many tabs."), "tabs."),
('position', ('position',
SettingValue(types.Position, "north"), SettingValue(types.Position, "north"),
@ -185,18 +185,15 @@ def configdata():
types.Color, types.Color,
"qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #e4e4e4, " "qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #e4e4e4, "
"stop:1 #dbdbdb)"), "stop:1 #dbdbdb)"),
"Background color of the completion widget category " "Background color of the completion widget category headers."),
"headers."),
('completion.category.border.top', ('completion.category.border.top',
SettingValue(types.Color, "#808080"), SettingValue(types.Color, "#808080"),
"Top border color of the completion widget category " "Top border color of the completion widget category headers."),
"headers."),
('completion.category.border.bottom', ('completion.category.border.bottom',
SettingValue(types.Color, "#bbbbbb"), SettingValue(types.Color, "#bbbbbb"),
"Bottom border color of the completion widget category " "Bottom border color of the completion widget category headers."),
"headers."),
('completion.item.selected.fg', ('completion.item.selected.fg',
SettingValue(types.Color, "#333333"), SettingValue(types.Color, "#333333"),
@ -208,8 +205,7 @@ def configdata():
('completion.item.selected.border.top', ('completion.item.selected.border.top',
SettingValue(types.Color, "#f2f2c0"), SettingValue(types.Color, "#f2f2c0"),
"Top border color of the completion widget category " "Top border color of the completion widget category headers."),
"headers."),
('completion.item.selected.border.bottom', ('completion.item.selected.border.bottom',
SettingValue(types.Color, "#ffec8b"), SettingValue(types.Color, "#ffec8b"),
@ -285,18 +281,15 @@ def configdata():
"Default monospace fonts."), "Default monospace fonts."),
('completion', ('completion',
SettingValue(types.Font, "8pt " + MONOSPACE, SettingValue(types.Font, "8pt " + MONOSPACE, "8pt ${_monospace}"),
"8pt ${_monospace}"),
"Font used in the completion widget."), "Font used in the completion widget."),
('tabbar', ('tabbar',
SettingValue(types.Font, "8pt " + MONOSPACE, SettingValue(types.Font, "8pt " + MONOSPACE, "8pt ${_monospace}"),
"8pt ${_monospace}"),
"Font used in the tabbar."), "Font used in the tabbar."),
('statusbar', ('statusbar',
SettingValue(types.Font, "8pt " + MONOSPACE, SettingValue(types.Font, "8pt " + MONOSPACE, "8pt ${_monospace}"),
"8pt ${_monospace}"),
"Font used in the statusbar."), "Font used in the statusbar."),
)), )),

View File

@ -29,7 +29,7 @@ class BaseType:
string. Either a list of strings, or a list of (value, string. Either a list of strings, or a list of (value,
desc) tuples. desc) tuples.
# FIXME actually handle tuples and stuff when validating # FIXME actually handle tuples and stuff when validating
show_valid_values; Whether to show valid values in config or not. show_valid_values" Whether to show valid values in config or not.
typestr: The name of the type to appear in the config. typestr: The name of the type to appear in the config.
""" """
@ -45,18 +45,24 @@ class BaseType:
The default implementation returns the original value. The default implementation returns the original value.
Args:
value: The original string value.
Return: Return:
The transformed value. The transformed value.
""" """
return value return value
def validate(self): def validate(self, value):
"""Validate value against possible values. """Validate value against possible values.
The default implementation checks the value against self.valid_values The default implementation checks the value against self.valid_values
if it was defined. if it was defined.
Args:
value: The value to validate.
Return: Return:
Ture if validation succeeded, False otherwise. Ture if validation succeeded, False otherwise.
@ -66,10 +72,11 @@ class BaseType:
""" """
if self.valid_values is not None: if self.valid_values is not None:
return self.value in self.valid_values return value in self.valid_values
else: else:
raise NotImplementedError raise NotImplementedError
class String(BaseType): class String(BaseType):
"""Base class for a string setting (case-insensitive).""" """Base class for a string setting (case-insensitive)."""
@ -95,8 +102,8 @@ class Bool(BaseType):
def transform(self, value): def transform(self, value):
return self._BOOLEAN_STATES[value.lower()] return self._BOOLEAN_STATES[value.lower()]
def validate(self): def validate(self, value):
return self.value.lower() in self._BOOLEAN_STATES return value.lower() in self._BOOLEAN_STATES
class Int(BaseType): class Int(BaseType):
@ -108,9 +115,9 @@ class Int(BaseType):
def transform(self, value): def transform(self, value):
return int(value) return int(value)
def validate(self): def validate(self, value):
try: try:
int(self.value) int(value)
except ValueError: except ValueError:
return False return False
else: else:
@ -126,7 +133,7 @@ class List(BaseType):
def transform(self, value): def transform(self, value):
return value.split(',') return value.split(',')
def validate(self): def validate(self, value):
return True return True
@ -140,9 +147,9 @@ class IntList(List):
vals = super().transform(value) vals = super().transform(value)
return map(int, vals) return map(int, vals)
def validate(self): def validate(self, value):
try: try:
self.transform(self.value) self.transform(value)
except ValueError: except ValueError:
return False return False
else: else:
@ -153,17 +160,17 @@ class PercOrInt(BaseType):
"""Percentage or integer.""" """Percentage or integer."""
def validate(self): def validate(self, value):
if self.value.endswith('%'): if value.endswith('%'):
try: try:
intval = int(self.value.rstrip('%')) intval = int(value.rstrip('%'))
except ValueError: except ValueError:
return False return False
else: else:
return 0 <= intval <= 100 return 0 <= intval <= 100
else: else:
try: try:
intval = int(self.value) intval = int(value)
except ValueError: except ValueError:
return False return False
else: else:
@ -178,13 +185,13 @@ class Command(BaseType):
valid_values = cmdutils.cmd_dict.items() valid_values = cmdutils.cmd_dict.items()
def validate(self): def validate(self, value):
# We need to import this here to avoid circular dependencies # We need to import this here to avoid circular dependencies
from qutebrowser.commands.parsers import (CommandParser, from qutebrowser.commands.parsers import (CommandParser,
NoSuchCommandError) NoSuchCommandError)
cp = CommandParser() cp = CommandParser()
try: try:
cp.parse(self.value) cp.parse(value)
except NoSuchCommandError: except NoSuchCommandError:
return False return False
else: else:
@ -197,7 +204,7 @@ class Color(BaseType):
typestr = 'color' typestr = 'color'
def validate(self): def validate(self, value):
# FIXME validate colors # FIXME validate colors
return True return True
@ -208,7 +215,7 @@ class Font(BaseType):
typestr = 'font' typestr = 'font'
def validate(self): def validate(self, value):
# FIXME validate fonts # FIXME validate fonts
return True return True
@ -217,7 +224,7 @@ class SearchEngineName(BaseType):
"""A search engine name.""" """A search engine name."""
def validate(self): def validate(self, value):
return True return True
@ -225,20 +232,19 @@ class SearchEngineUrl(BaseType):
"""A search engine URL.""" """A search engine URL."""
def validate(self): def validate(self, value):
return "{}" in self.value return "{}" in value
class KeyBindingName(BaseType): class KeyBindingName(BaseType):
"""The name (keys) of a keybinding.""" """The name (keys) of a keybinding."""
def validate(self): def validate(self, value):
# FIXME can we validate anything here? # FIXME can we validate anything here?
return True return True
class AutoSearch(BaseType): class AutoSearch(BaseType):
"""Whether to start a search when something else than an URL is entered.""" """Whether to start a search when something else than an URL is entered."""
@ -247,11 +253,11 @@ class AutoSearch(BaseType):
("dns", "Use DNS requests (might be slow!)."), ("dns", "Use DNS requests (might be slow!)."),
("false", "Never search automatically.")] ("false", "Never search automatically.")]
def validate(self): def validate(self, value):
if self.value.lower() in ["naive", "dns"]: if value.lower() in ["naive", "dns"]:
return True return True
else: else:
return Bool.validate(self, self.value) return Bool.validate(self, value)
def transform(self, value): def transform(self, value):
if value.lower() in ["naive", "dns"]: if value.lower() in ["naive", "dns"]:
@ -293,5 +299,3 @@ class KeyBinding(Command):
"""The command of a keybinding.""" """The command of a keybinding."""
pass pass

View File

@ -77,7 +77,7 @@ class KeyValue:
def __iter__(self): def __iter__(self):
"""Iterate over all set values.""" """Iterate over all set values."""
# FIXME using a custon iterator this could be done more efficiently # FIXME using a custom iterator this could be done more efficiently.
return self.values.__iter__() return self.values.__iter__()
def __bool__(self): def __bool__(self):
@ -124,9 +124,11 @@ class ValueList:
self.default = OrderedDict( self.default = OrderedDict(
[(keytype.transform(key), valtype.transform(value)) [(keytype.transform(key), valtype.transform(value))
for key, value in self.default.items()]) for key, value in self.default.items()])
self.valdict = OrderedDict()
def update_valdict(self): def update_valdict(self):
self.valdict = OrderedDict() """Update the global "true" value dict."""
self.valdict.clear()
self.valdict.update(self.default) self.valdict.update(self.default)
if self.values is not None: if self.values is not None:
self.valdict.update(self.values) self.valdict.update(self.values)