File: options.py

package info (click to toggle)
fbless 0.2.3-7
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 520 kB
  • sloc: python: 1,726; makefile: 8
file content (156 lines) | stat: -rw-r--r-- 5,013 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# -*- mode: python; coding: utf-8; -*-
""" Default options dicts and config files parser
"""
import curses
import configparser
import os
from . import defaults
from . import const 
import sys
import argparse

paths = dict(defaults.paths)
general = dict(defaults.general)
keys = dict(defaults.keys)
styles = dict(defaults.styles)

try:
    from xdg.BaseDirectory import xdg_config_home
except ImportError:
    xdg_config_home = os.path.expanduser('~/.config')

CONFIG_FILES = [
    os.path.join(xdg_config_home, "fbless", "fblessrc"),
    os.path.expanduser("~/.fblessrc"),
]

def typed_get(config, section, sectiondict, key, value):
    """ Get config value with given type
    """
    if isinstance(sectiondict[section][key], bool):
        return config.getboolean(section, key)
    elif (
        isinstance(sectiondict[section][key], int)
        and key not in ('foreground', 'background')
    ):
        return config.getint(section, key)
    elif key in ('foreground', 'background'):
        # foreground and background are some integral constants, but
        # they're represented with string values in config file
        # we should make conversion
        if value in const.COLORS:
            return value
        else:
            return config.getint(section, key)
    elif section == 'keys':
        return tuple([keyname.strip() for keyname in value.split(',')])
    else:
        return config.get(section, key)


def convert_key(keyname):
    """ Curses needs codes, not actual symbols keys produce.
        Moreover, some keys are specified by the name like
        'space' or 'pgdn'. So we need some processing.
    """
    try:
        return const.SPECIAL_KEYS[keyname]
    except KeyError:
        return(ord(keyname))

def get_keys(keysgroup):
    """ Convert tuple or other iterable of keys
    """
    return tuple([convert_key(keyname) for keyname in keys[keysgroup]])

def convert_color(colorname):
    """ Convert color names to numeric codes
    """
    try:
        return const.COLORS[colorname]
    except KeyError:
        if colorname:
            return(int(colorname))
        else:
            return(colorname)

def parse_arguments():
    parser = argparse.ArgumentParser(description = 'fb2 console reader')
    parser.add_argument('file', nargs = '?',
                        help = 'fb2, zip, gzip or bzip2 file')
    parser.add_argument('-a', '--autoscroll', action = 'store_true',
                        help = 'enable auto-scroll')
    parser.add_argument('-t', '--scroll_type', choices = ['down', 'up', 
                        'page-down', 'page-up', 'fifo'],
                        help = 'auto-scroll type (down, up, page-down, page-up, fifo)')
    parser.add_argument('-i', '--interval', type = int, metavar = 'sec.',
                        help = 'auto-scroll time interval')
    parser.add_argument('-g', '--goto', type = int, metavar = '%',
                        help = 'go to the offset (in percent)')
    parser.add_argument('-e', '--edit', action = 'store_true',
                        help = 'open in the editor')
    parser.add_argument('-c', '--config', metavar = 'file',
                        help = 'use the specified configuration file')
    args = parser.parse_args()

    if args.file:
        general['filename'] = args.file
    else:
        general['filename'] = None

    if args.autoscroll:
        general['auto_scroll'] = True
    else:
        general['auto_scroll'] = False

    if args.scroll_type:
        if args.scroll_type == 'down':
           general['auto_scroll_type'] = const.SCROLL_DOWN
        elif args.scroll_type == 'up':
           general['auto_scroll_type'] = const.SCROLL_UP
        elif args.scroll_type == 'page-down':
            general['auto_scroll_type'] = const.NEXT_PAGE
        elif args.scroll_type == 'page-up':
            general['auto_scroll_type'] = const.PREV_PAGE
        elif args.scroll_type == 'fifo':
            general['auto_scroll_type'] = const.SCROLL_FIFO
    else:
        general['auto_scroll_type'] = const.NO_SCROLL

    if args.interval:
        general['auto_scroll_interval'] = args.interval

    if args.goto:
        general['percent'] = args.goto
    else:
        general['percent'] = None
    
    if args.edit:
        general['edit_xml'] = True
    else:
        general['edit_xml'] = False

    if args.config:
        CONFIG_FILES.append(args.config)

    parse_config()

def parse_config():
    """Load settings from config
    """
    config = configparser.RawConfigParser()
    config.read(CONFIG_FILES)

    for d, section in (
        [(globals(), section) for section in ['paths', 'general', 'keys']]
        + [(styles, style) for style in styles]
    ):
        if config.has_section(section):
            d[section].update([
                (
                    key,
                    typed_get(config, section, d, key, value),
                )   
                for (key, value) in config.items(section)
                if key in d[section]
            ])