File: config.py

package info (click to toggle)
osdlyrics 0.5.15%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,616 kB
  • sloc: ansic: 19,458; python: 4,867; sh: 572; makefile: 366; sed: 16
file content (183 lines) | stat: -rw-r--r-- 5,746 bytes parent folder | download
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011  Tiger Soldier
#
# This file is part of OSD Lyrics.
#
# OSD Lyrics is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# OSD Lyrics is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with OSD Lyrics.  If not, see <https://www.gnu.org/licenses/>.
#

import logging

import dbus

from .consts import CONFIG_BUS_NAME, CONFIG_OBJECT_PATH

CONFIG_INTERFACE = 'org.osdlyrics.Config'


class Config:
    """ Helper class to retrive configs from OSD Lyrics through DBus

    It provides a set of get_<type> functions to get config values with default
    values. If the value with given key exists, return the value. Otherwise the value
    to the key is set to the default value, and returns it. If no default value
    specified and the key does not exist, raise an exception.

    Values can be monitored by connect_change function.
    """

    def __init__(self, conn, follow_name_owner_changes=True):
        """
        Arguments:
        - `conn`: DBus connection
        """
        self._conn = conn
        self._proxy = conn.get_object(CONFIG_BUS_NAME,
                                      CONFIG_OBJECT_PATH,
                                      follow_name_owner_changes=follow_name_owner_changes)
        self._proxy = dbus.Interface(self._proxy,
                                     CONFIG_INTERFACE)
        self._signals = {}
        self._proxy.connect_to_signal('ValueChanged',
                                      self._value_changed_cb)

    def get_bool(self, key, default=None):
        try:
            return self._proxy.GetBool(key)
        except Exception as e:
            if default is not None:
                try:
                    self._proxy.SetBool(key, default)
                except Exception:
                    pass
                return default
            raise e

    def set_bool(self, key, value):
        self._proxy.SetBool(key, value)

    def get_int(self, key, default=None):
        try:
            return self._proxy.GetInt(key)
        except Exception as e:
            if default is not None:
                try:
                    self._proxy.SetInt(key, default)
                except Exception:
                    pass
                return default
            raise e

    def set_int(self, key, value):
        self._proxy.SetInt(key, value)

    def get_double(self, key, default=None):
        try:
            return self._proxy.GetDouble(key)
        except Exception as e:
            if default is not None:
                try:
                    self._proxy.SetBool(key, default)
                except Exception:
                    pass
                return default
            raise e

    def set_double(self, key, value):
        self._proxy.SetDouble(key, value)

    def get_string(self, key, default=None):
        try:
            return self._proxy.GetString(key)
        except Exception as e:
            if default is not None:
                try:
                    self._proxy.SetString(key, default)
                except Exception:
                    pass
                return default
            raise e

    def set_string(self, key, value):
        self._proxy.SetString(key, value)

    def get_string_list(self, key, default=None):
        try:
            return self._proxy.GetStringList(key)
        except Exception as e:
            if default is not None:
                try:
                    self._proxy.SetStringList(key, default)
                except Exception:
                    pass
                return default
            raise e

    def set_string_list(self, key, value):
        self._proxy.SetStringList(key, value)

    def connect_change(self, key, func):
        """
        Calls func once a config value with specified key is changed

        The callback function `func` receives one argument, the key that
        has changed
        """
        if not callable(func):
            return
        self._signals.setdefault(key, []).append(func)

    def disconnect_change(self, key=None, func=None):
        if key is None:
            self._signals = {}
            return
        if key in self._signals:
            if func is None:
                del self._signals[key]
            else:
                self._signals[key].remove(func)

    def _value_changed_cb(self, name_list):
        for name in name_list:
            for handler in self._signals.get(name, []):
                handler(name)


def test():
    def value_changed(name):
        typename = name.split('/')[1]
        logging.debug('%s has been changed to %s', name, getattr(config, 'get_' + typename)(name))

    from gi.repository import GLib
    from dbus.mainloop.glib import DBusGMainLoop
    loop = GLib.MainLoop()
    dbus_mainloop = DBusGMainLoop()
    conn = dbus.SessionBus(mainloop=dbus_mainloop)
    config = Config(conn)
    testcase = {'bool': False,
                'int': 123,
                'double': 123.54,
                'string': 'Foobar',
                'string_list': ['Foo', 'bar'],
                }
    for k in testcase:
        config.connect_change('test/' + k, value_changed)
    for k, v in testcase.items():
        getattr(config, 'set_' + k)('test/' + k, v)
    loop.run()


if __name__ == '__main__':
    test()