settings.py 5.13 KB
Newer Older
1 2 3 4 5 6
#
#    THIS FILE IS PART OF THE D-FEET PROJECT AND LICENSED UNDER THE GPL. SEE
#    THE 'COPYING' FILE FOR DETAILS
#
#   portions taken from the Jokosher project
#
7

8 9
import ConfigParser
import os
10 11
import re

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
class ConfigTokenizer():
    COMMA = re.compile(",")
    FALLTHROUGH = re.compile('(?:[^,.])+')
    # FIXME: String re does not ignore escaped quotes (e.g. \") correctly
    STRING = re.compile('"((?:[^\\"]|\\.)*)"' + "|'((?:[^\\']|\\.)*)'")
    NUMBER = re.compile('[+-]?[0-9]*\.?[0-9]+')
    WHITESPACE = re.compile('\s')

    _parse_order = [STRING, NUMBER, WHITESPACE, COMMA, FALLTHROUGH]

    class Match():
        ENDWHITESPACE=re.compile('\s$')
        UNESCAPE=re.compile('\\\(.)')

        def __init__(self, match, regex):
            self.match = match
            self.regex = regex

        def is_whitespace(self):
            if self.regex == ConfigTokenizer.WHITESPACE:
                return True
            return False

        def is_comma(self):
            if self.regex == ConfigTokenizer.COMMA:
                return True
            return False

        def is_value(self):
            if (self.regex == ConfigTokenizer.STRING or
                self.regex == ConfigTokenizer.NUMBER or
                self.regex == ConfigTokenizer.FALLTHROUGH):
                return True
            return False


        def strip(self, s):
            return self.ENDWHITESPACE.sub('', s)

        def unescape(self, s):
            return self.UNESCAPE.sub(r'\1', s)

        def __str__(self):
            result = ''
            groups = self.match.groups()
            if groups:
                for g in groups:
                    if g is not None:
                        result = g
            else:
                result = self.match.group(0)

            result = self.strip(result)
            if self.regex == ConfigTokenizer.STRING:
                result = self.unescape(result)

            return result

    def __init__(self, s):
        self._consumable = s

    def __iter__(self):
        return self

    def next(self):
        for r in self._parse_order:
            m = r.match(self._consumable)
            if m:
                self._consumable = self._consumable[len(m.group(0)):]
                return self.Match(m, r)

        raise StopIteration
84 85 86 87 88 89 90 91 92 93 94 95

class Settings:
    """
    Handles loading/saving settings from/to a file on disk.
    """

    instance = None

    # the different settings in each config block
    general =   {
                "windowheight" : 550,
                "windowwidth" : 900,
96
                "windowstate" : None,
97 98
                "bustabs_list" : [],
                "addbus_list" : []
99
                }
100

101 102 103
    def __init__(self, filename = None):
        """
        Creates a new instance of Settings.
104

105 106
        Parameters:
            filename -- path to the settings file.
William Jon McCann's avatar
William Jon McCann committed
107
                        If None, the default $XDG_CONFIG_HOME/d-feet/config will be used.
108 109
        """
        if not filename:
William Jon McCann's avatar
William Jon McCann committed
110 111 112 113
            if os.environ.has_key('XDG_CONFIG_HOME'):
                self.filename = os.path.join(os.environ['XDG_CONFIG_HOME'], 'd-feet', 'config')
            else:
                self.filename = os.path.join(os.environ['HOME'], '.config', 'd-feet', 'config')
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        else:
            self.filename = filename
        self.config = ConfigParser.ConfigParser()

        self.read()

    @classmethod
    def get_instance(cls):
        """ This class is a singlton so use this method to get it """
        if cls.instance:
            return cls.instance

        cls.instance = Settings()
        return cls.instance

129 130
    def decode_list(self, s):
        result = []
131 132 133 134 135
        lex = ConfigTokenizer(s);
        for item in lex:
            if item.is_value():
                result.append(str(item))

136 137
        return result

138 139 140 141 142 143
    def read(self):
        """
        Reads configuration settings from the config file and loads
        then into the Settings dictionaries.
        """
        self.config.read(self.filename)
144

145 146
        if not self.config.has_section("General"):
            self.config.add_section("General")
147

148
        for key, value in self.config.items("General"):
149
            if key.endswith('list'):
150
                value = self.decode_list(value)
151

152
            self.general[key] = value
153 154 155 156 157 158

    def quote(self, value):
        result = ''
        result = re.sub(r'([\\\"\'])', r'\\\1', value)
        return '"%s"' % result

159 160 161
    def write(self):
        """
        Writes configuration settings to the Settings config file.
162
        """
163
        for key in self.general:
164
            if key.endswith('list'):
165
                for i in range(0, len(self.general[key])):
166
                    self.general[key][i] = self.quote(self.general[key][i])
167
                self.general[key] = ','.join(self.general[key])
168

169 170 171
            if self.general[key] == None:
                self.general[key] = ''

172
            self.config.set("General", key, self.general[key])
173

174 175
        # make sure that the directory that the config file is in exists
        new_file_dir = os.path.split(self.filename)[0]
176
        if not os.path.isdir(new_file_dir):
177 178 179 180
            os.makedirs(new_file_dir)
        file = open(self.filename, 'w')
        self.config.write(file)
        file.close()