summaryrefslogtreecommitdiff
path: root/kberylsettings/beryl.py
blob: d07d89a30cc3fbd07804232f25b372f4be02defc (plain)
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" kberylsettings.beryl -> wrappers around berylsettings objects.

"""
import berylsettings

from os.path import abspath, exists
from re import sub

from qt import QImage, QPixmap, QObject
from kdecore import KIcon
from kberylsettings.lib import App, Signals, icon


class Context(QObject):
    """ Context -> wraps berylsetting.Context instances with extra
    methods and properties.

    """
    activePluginsSettingName = 'active_plugins'

    def __init__(self, context=None):
        QObject.__init__(self)
        if context is None:
            context = berylsettings.Context()
            context.Read()
        self.context = context

    def __repr__(self):
        args = (self.__module__, self.__class__.__name__, hex(abs(id(self))))
        return "<%s.%s instance at %s>" % args
    
    def getCategories(self):
        seq = [Category(c) for c in self.context.Categories]
        seq.sort()
        return seq
    categories = property(getCategories)

    def getPlugins(self):
        """ sorted plugin sequence

        @return sequence of Plugin wrapper instances
        """
        seq = [Plugin(p) for p in self.context.Plugins]
        seq.sort()
        return seq
    plugins = property(getPlugins)

    def plugin(self, value):
        """ locates plugin by name, description, or index

        @param value plugin name, short description, or index
        @return Plugin wrapper instance
        """
        try:
            value + 0
        except (TypeError, ):
            for plugin in self.plugins:
                if value == plugin.ShortDesc:
                    return Plugin(plugin)
                if value == plugin.Name:
                    return Plugin(plugin)
        else:
            return list(self.plugins)[value]

    def getActive(self):
        """ sequence of active plugin names

        @return sequence of active plugin names
        """
        act = self.general.Setting(self.activePluginsSettingName).Value
        return act + [Plugin.generalName, ]

    def setActive(self, active):
        """ sets active plugins

        @param active sequence of plugin names to set as active
        @return None
        """
        self.general.Setting(self.activePluginsSettingName).Value = active
    active = property(getActive, setActive)

    def getGeneral(self):
        """ general plugin instance

        @return Plugin wrapper instance
        """
        return Plugin(self.context.Plugin(Plugin.generalName))
    general = property(getGeneral)

    def write(self):
        """ saves the beryl context

        @return None
        """
        self.emit(Signals.statusMessage, ('Saving Beryl settings....', ))
        self.context.Write()
        self.reload()

    def reload(self):
        """ messages the extension to reload the new settings

        @return None
        """
        berylsettings.send_reload()
        self.emit(Signals.statusMessage, ('Beryl settings reloaded.', ))    


class Category:
    def __init__(self, category):
        self.category = category

    def __cmp__(self, other):
        return cmp(self.ShortDesc, other.ShortDesc)

    def __getattr__(self, value):
        return getattr(self.category, value)

    def icon(self, size, loader):
        return loader.loadIcon('unknown', KIcon.NoGroup, size)

    def plugins(self):
        seq = [Plugin(p) for p in self.category.Plugins]
        seq.sort()
        return seq
    plugins = property(plugins)


class Plugin:
    generalName = '_'
    iconCache = {}
    
    def __init__(self, plugin):
        self.plugin = plugin

    def __cmp__(self, other):
        if other is None:
            return -1
        if not isinstance(other, Plugin):
            other = Plugin(other)
        if self.isGeneral:
            return -1
        if other.isGeneral:
            return 1
        return cmp(self.plugin.ShortDesc, other.plugin.ShortDesc)

    def __getattr__(self, value):
        return getattr(self.plugin, value)

    def __repr__(self):
        args = (self.__module__, self.__class__.__name__,
                self.Name,
                hex(abs(id(self))))
        return "<%s.%s instance name='%s' at %s>" % args

    def isGeneral(self):
        return self.plugin.Name == self.generalName
    isGeneral = property(isGeneral)

    def icon(self, size, loader):
        if App.debug:
            return loader.loadIcon('empty', KIcon.NoGroup, size)
        name = self.plugin.Name
        try:
            pix = self.iconCache[(name, size)]
        except (KeyError, ):
            path = abspath(App.basedir + '/pixmaps/beryl-settings-section-%s.svg' % name)
            if not exists(path):
                path = 'unknown'
            ico = loader.loadIcon(path, KIcon.NoGroup)
            img = ico.convertToImage()
            pix = self.iconCache[(name, size)] = QPixmap()
            pix.convertFromImage(img.smoothScale(size, size, QImage.ScaleMin))
        return pix

    def nativeSettingsGroups(self):
        settingsMap = {}
        for setting in self.plugin.Settings:
            seq = settingsMap.setdefault(setting.Type, [])
            seq.append(setting)
        return settingsMap

    def regroupSettings(self):
        mapping = self.nativeSettingsGroups()
        remap = {}
        for typ, values in mapping.items():
            other = self.alternateGroup(typ, values, mapping)
            seq = remap.setdefault(other, [])
            values.sort()
            seq.extend(values)
        return remap

    def alternateGroup(self, typ, val, mapping):
        if typ in ('Int', 'Float'):
            return 'Numeric Values'
        if typ in ('Bool', 'String'):
            return 'Choices'
        if typ in ('Binding', ):
            return 'Bindings'
        return typ

    def settings(self):
        mapping = {}
        settings = [Setting(s) for s in self.plugin.Settings]
        for setting in settings:
            key = self.alternateGroup(setting.Type, None, None)
            seq = mapping.setdefault(key, [])
            seq.append(setting)
        for seq in mapping.values():
            seq.sort()
        return mapping
    settings = property(settings)

    def groups(self):
        groups = [Group(g) for g in self.plugin.Groups]
        groups.sort()
        return groups
    groups = property(groups)


class Group:
    def __init__(self, group):
        self.group = group

    def __getattr__(self, value):
        return getattr(self.group, value)

    def __cmp__(self, other):
        if not isinstance(other, Group):
            other = Group(other)
        return cmp(self.label, other.label)

    def label(self):
        return self.Name or self.Desc or 'Uncategorized'
    label = property(label)

    def settings(self, plugin):
        if not isinstance(plugin, Plugin):
            plugin = Plugin(plugin)
        group = self.Name
        settings = [Setting(s) for s in plugin.Settings if s.Group==group]
        settings.sort()
        return settings


class Setting:
    iconNameMap = {
        'Binding' : 'mouse',
        'Bool' : 'apply',
        'Int' : 'configure',
        'List of String' : 'view_text',
        'String' : 'view_detailed',
        'Back':'back',
    }

    labelMap = {
        'Binding' : 'Keyboard/Mouse',
        'Bool' : 'Choices',
        'Int' : 'Values',
        'List of String' : 'Files',
        'String' : 'Values',
    }

    def __init__(self, setting):
        self.setting = setting

    def __cmp__(self, other):
        try:
            a = int(self.ShortDesc.split()[-1])
        except:
            a = self.ShortDesc
        try:
            b = int(other.ShortDesc.split()[-1])
        except:
            b = getattr(other, 'ShortDesc', None)
        return cmp(a, b)
    
    def __getattr__(self, value):
        return getattr(self.setting, value)

    def __repr__(self):
        args = (self.__module__, self.__class__.__name__,
                self.Name,
                hex(abs(id(self))))
        return "<%s.%s instance name='%s' at %s>" % args

    def set(self, value):
        self.setting.Value = value
        
    def icon(cls, value, size):
        name = cls.iconNameMap.get(str(value), cls.iconNameMap['Bool'])
        return icon(name, size=size)
    icon = classmethod(icon)
    
    def label(self):
        value = self.ShortDesc
        value = value.title()
        for pattern, repl in self.fixes:
            value = sub(pattern, repl, value)
        return value
        return settingLabelMap.get(value, value)
    label = property(label)

    def getValue(self):
        try:
            return self.setting.Value
        except (IndexError, ):
            return ''

    def setValue(self, value):
        self.set(value)
    Value = property(getValue, setValue)

    
    fixes = [
        (' A ', ' a '),
        (' And ', ' and '),
        (' For ', ' for '),        
        (' In ', ' in '),
        (' The ', ' the '),        
        (' To ', ' to '),
        (' Of ', ' of '),
        (' On ', ' on '),        
        (' Fsp', ' FSP'),
        (' Svg', ' SVG'),        
        (' Vblank', ' VBlank'),        
        ]