summaryrefslogtreecommitdiff
path: root/kberylsettings/pluginframe.py
blob: a93fc4f97d9135f86698410551613ca3f2b5c7bf (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" kberylsettings.pluginframe -> defines the left side plugin views
and search view.

"""
from re import sub

from qt import QLabel, QListViewItem
from kdecore import KIcon, i18n

from kberylsettings.beryl import Setting
from kberylsettings.lib import Signals, icon, iconLoader
from kberylsettings.widget import BasicListView, Frame, ValueListViewItem, \
     WidgetStack


class PluginFrame(WidgetStack):
    """ PluginFrame -> stack with various plugin views and search widget.

    """
    iconPageId, treePageId, searchPageId, categoryPageId = pageIds = range(4)
    iconSizeModes = (iconPageId, categoryPageId)
    transitoryModes = (searchPageId, )
    modePages = (
        (iconPageId, '&Icon View'),
        (treePageId, '&Tree View'),
        ## search does not have a mode menu
        ## entry selectable by the user.
        (categoryPageId, '&Category View')
    )
    relatedModes = {
        iconPageId : (treePageId, categoryPageId),
        treePageId : (iconPageId, categoryPageId),
        categoryPageId : (iconPageId, treePageId),
    }
    
    def __init__(self, parent):
        WidgetStack.__init__(self, parent)
        pages = (IconView(self), TreeView(self), SearchView(self),
                 CategoryView(self))
        addWidget = self.addWidget
        for pageId, page in zip(self.pageIds, pages):
            addWidget(page, pageId)
        connect = self.connect
        root = self.topLevelWidget()        
        connect(root, Signals.viewModeChanged, self.raiseWidget)

        for pageId, others in self.relatedModes.items():
            for otherId in others:
                connect(pages[pageId], Signals.selectItem,
                        pages[otherId].otherSelected)
        
        for page in pages:
            connect(page, Signals.berylSettingChanged, root.onContextChanged)
            connect(page, Signals.showAbout, root, Signals.showAbout)
            connect(page, Signals.showSettings, root, Signals.showSettings)            
            connect(page, Signals.showGroups, root, Signals.showGroups)
            connect(page, Signals.statusMessage, root.showMessage)
            try:
                connect(root, Signals.berylContextChanged, page.onBerylContext)
                connect(root, Signals.berylPluginEnabled, page.enablePluginItem)
                connect(root, Signals.selectPrevious, page.selectPluginItem)
            except (AttributeError, ):
                pass


class SearchView(Frame):
    """ SearchView -> a frame to display found keywords and their results

    """
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.index = {}
        self.loader = iconLoader()
        self.keywordLabel = QLabel(i18n('Keywords:'), self)
        self.keywordsList = keywordsList = BasicListView(self)
        self.resultsLabel = QLabel(i18n('Results:'), self)
        self.resultsList = resultsList = BasicListView(self)
        connect = self.connect
        connect(keywordsList, Signals.itemSelected, self.showResults)
        connect(resultsList, Signals.itemSelected, self.emitResult)
        root = self.topLevelWidget()
        connect(root, Signals.searchInput, self.showKeywords)
        connect(root, Signals.berylContextChanged, self.rebuildIndex)

    def rebuildIndex(self, context):
        """ reconstructs the search 'index' given a berylsetting context

        This might look slow at first glance, but my machine, this
        function takes less than 0.1 second.

        @param context berylsetting.Context instance
        @return None
        """
        self.context = context
        index = self.index
        index.clear()
        itemKeywords = self.itemKeywords
        for p in context.plugins[::-1]:
            for key in itemKeywords(p):
                seq = index.setdefault(key, [])
                seq.append((p, None))
            for s in p.Settings:
                for key in itemKeywords(s):
                    seq = index.setdefault(key, [])
                    seq.append((p, s))

    def itemKeywords(self, obj):
        """ creates a list of keywords for the given berylsettings object

        @param obj berylsettings Plugin or Setting instance
        @return list of keywords
        """
        values = [obj.ShortDesc, obj.LongDesc, ] + \
                     obj.ShortDesc.split() + \
                     obj.LongDesc.split()
        return [sub('\W|_', ' ', v) for v in values]

    def showKeywords(self, text):
        """ displays keywords from the index that match the given text

        @param text search value
        @return None
        """
        text = str(text)        
        if not text:
            return
        searchtext = text.lower()
        index = self.index
        parent = self.keywordsList
        parent.clear()
        for keyword in self.index:
            if searchtext in keyword.lower():
                plugin, setting = index[keyword][0]
                if plugin.Enabled:
                    item = ValueListViewItem(parent, keyword, index[keyword])

    def showResults(self, item):
        """ displays plugin/setting items from the selected keyword

        @return None
        """
        parent = self.resultsList
        parent.clear()
        cache = {}
        for plugin, setting in item.value:
            desc = plugin.ShortDesc
            item = cache.get(plugin)
            if item is None:
                value = (plugin, None)
                item = cache[plugin] = ValueListViewItem(parent, desc, value)
                item.setPixmap(0, plugin.icon(KIcon.SizeSmall, self.loader))
            if setting:
                desc = setting.ShortDesc
                sub = cache.get((plugin, setting))
                if sub is None:
                    sub = cache[(plugin, setting)] = \
                          ValueListViewItem(item, desc, (plugin, setting))
            item.setOpen(True)

    def emitResult(self, item):
        """ emits signal to show a plugin or a setting

        @param item result list view item
        @return None
        """
        plugin, setting = item.value
        if setting is None:
            self.emit(Signals.showAbout, (self.context, plugin, ))
        else:
            self.emit(Signals.showSettings, (plugin, Setting(setting), ))


class BasicPluginView(BasicListView):
    """ BasicPluginView -> mixin for shared view functionality

    """
    def __init__(self, parent):
        BasicListView.__init__(self, parent)
        self.loader = iconLoader()
        self.connect(self, Signals.itemClicked, self.onItemClick)

    def selectPluginItem(self, plugin, setting, activate=False):
        """ locate and set current item given plugin and setting

        @param plugin beryl settings Plugin object
        @param setting any object
        @return None
        """
        def match(a):
            return a.plugin and \
                   a.plugin.Name == plugin.Name and \
                   a.setting == setting
        for item in self:
            if match(item):
                self.setCurrentEnsureVisible(item)
                if activate:
                    self.onItemClick(item)
                break
        
    def addItems(self):
        """ adds list view items for every plugin in context

        @return None
        """
        for plugin in self.context.plugins[::-1]:
            self.listItem(plugin)

    def listItem(self, plugin):
        """ create a list view item for a plugin

        @param plugin beryl settings Plugin object
        @return QListViewItem instance
        """
        item = None
        for i in self:
            if i.plugin and i.plugin.Name == plugin.Name and not i.setting:
                item = i
                break
        if not item:
            item = ViewItem(self, plugin.ShortDesc)
        item.plugin = plugin
        item.setVisible(plugin.Enabled)
        item.setPixmap(0, plugin.icon(self.iconSize, self.loader))
        return item

    def onBerylContext(self, context):
        """ beryl settings context has changed

        @param context
        @return None
        """
        self.context = context
        self.addItems()

    def enablePluginItem(self, plugin, enable):
        """ toggle the enabled state of a plugin list view item

        @param index position of plugin within plugins list
        @return None
        """
        for item in self:
            if item.plugin == plugin and not item.setting:
                item.setVisible(enable)

    def setCurrentEnsureVisible(self, item):
        """ set current item and ensure it's visible

        @param QListViewItem instance
        @return None
        """
        self.setCurrentItem(item)
        self.ensureItemVisible(item)


class IconView(BasicPluginView):
    """ IconView -> icon list view of plugins

    """
    iconSize = KIcon.SizeMedium

    def __init__(self, parent):
        BasicPluginView.__init__(self, parent)
        root = self.topLevelWidget()        
        self.connect(root, Signals.iconSizeChanged, self.onIconSize)
        
    def onIconSize(self, size):
        """ update the icon size

        @param size icon size as integer
        @return None
        """
        self.iconSize = size
        for item in self:
            if item.setting or not item.plugin:
                item.setPixmap(0, Setting.icon(item.setting, size))                
            else:
                item.setPixmap(0, item.plugin.icon(size, self.loader))

    def onItemClick(self, item):
        """ emit a signal if a plugin item is selected

        @param item QListViewItem instance
        @return None
        """
        if not item:
            return
        if item.plugin and not item.setting:
            self.showSettingItems(item.plugin)
            if self.sender() is self or self.isVisible():
                self.emit(Signals.showAbout, (self.context, item.plugin, ))
        elif item == self.firstChild():
            self.showPlugins()
        else:
            self.emit(Signals.showSettings, (item.plugin, item.setting))
        self.emit(Signals.selectItem, (item, ))

    def showPlugins(self):
        """ sets all enabled plugin items visible

        @return None
        """
        for item in self:
            if item.plugin and item.plugin.Enabled and not item.setting:
                item.setVisible(True)
            else:
                item.setVisible(False)

    def backItem(self):
        """ locates or creates the 'Back' item

        @return ViewItem instance
        """
        back = self.findItem(i18n('Back'), 0)        
        if back is None:
            back = ViewItem(self, i18n('Back'))
            back.setPixmap(0, icon('back', size=self.iconSize))
        return back
    
    def showSettingItems(self, plugin):
        """ displays setting icons for given plugin

        @param plugin beryl settings Plugin object        
        @return None
        """
        keys = plugin.settings.keys()
        keys.sort()
        back = self.backItem()
        back.setVisible(True)
        settings = []
        for item in self:
            p, s = item.plugin, item.setting
            if p and s:
                if s in keys:
                    item.setVisible(True)
                    item.plugin = plugin
                    item.setting = s
                    settings.append(s)
                else:
                    item.setVisible(False)
            elif p and not s:
                item.setVisible(False)
        for key in keys[::-1]:
            if key not in settings:
                sub = ViewItem(self, key, plugin=plugin, setting=key)
                sub.setPixmap(0, Setting.icon(key, self.iconSize))
                sub.moveItem(back)                

    def otherSelected(self, other):
        """ set current item when other item is selected elsewhere

        @param other ViewItem instance
        @return None
        """
        if other.plugin and other.setting:
            self.showSettingItems(other.plugin)            
            for i in self:
                if i.plugin and \
                       i.plugin.Name == other.plugin.Name and \
                       i.setting == other.setting:
                   self.setCurrentEnsureVisible(i)
                   break
        elif other.plugin:
            self.showPlugins()
            for i in self:
                if i.plugin and i.plugin.Name == other.plugin.Name:
                    self.setCurrentEnsureVisible(i)


class TreeView(BasicPluginView):
    """ TreeView -> tree list view of plugins

    """
    iconSize = KIcon.SizeSmall

    def __init__(self, parent):
        BasicPluginView.__init__(self, parent)
        self.setRootIsDecorated(True)        
        
    def listItem(self, plugin):
        """ create an item for the plugin and sub items for its settings

        @param plugin beryl settings Plugin object
        @param size icon size
        @return QListViewItem instance with children
        """
        item = BasicPluginView.listItem(self, plugin)
        groups = plugin.settings
        keys = groups.keys()
        keys.sort()
        child = item.firstChild()
        while child:
            item.takeItem(child)
            child = item.firstChild()
        for key in keys[::-1]:
            sub = ViewItem(item, key, plugin=plugin, setting=key)
            sub.setPixmap(0, Setting.icon(key, self.iconSize))
        return item

    def onItemClick(self, item):
        """ emit a signal if a plugin item is selected

        @param item QListViewItem instance
        @return None
        """
        if not item:
            return
        plugin, setting = item.plugin, item.setting
        if plugin and setting:
            self.emit(Signals.showSettings, (plugin, setting))            
        elif self.sender() is self or self.isVisible():
            self.emit(Signals.showAbout, (self.context, plugin, ))            
        self.emit(Signals.selectItem, (item, ))

    def otherSelected(self, other):
        """ set current item when other item is selected elsewhere

        @param other ViewItem instance
        @return None
        """
        if other.category:
            for i in self:
                if i.plugin == other.plugin and not i.setting:
                    self.setCurrentEnsureVisible(i)
                    break
        elif other.plugin and not other.setting:
            for i in self:
                if i.plugin == other.plugin and not i.setting:
                    self.setCurrentEnsureVisible(i)
                    break
        elif other.plugin and other.setting:
            for i in self:
                if i.plugin == other.plugin and i.setting == other.setting:
                    i.parent().setOpen(True)
                    self.setCurrentEnsureVisible(i)
                    break
            

class CategoryView(BasicPluginView):
    """ CategoryView -> tree list view of plugins by category

    """
    iconSize = KIcon.SizeMedium

    def __init__(self, parent):
        BasicPluginView.__init__(self, parent)
        self.setRootIsDecorated(True)
        root = self.topLevelWidget()        
        self.connect(root, Signals.iconSizeChanged, self.onIconSize)
        
    def onIconSize(self, size):
        """ update the icon size

        @param size icon size as integer
        @return None
        """
        self.iconSize = size
        for i in self:
            if i.category:
                i.setPixmap(0, i.category.icon(size))
            elif i.plugin:
                i.setPixmap(0, i.plugin.icon(size, self.loader))

    def onItemClick(self, item):
        """ emit appropriate signal when plugin or category selected

        @param item QListViewItem instance
        @return None
        """
        if not item:
            return
        if item.plugin:
            self.emit(Signals.showGroups, (item.plugin, ))
            self.emit(Signals.selectItem, (item, ))

    def addItems(self):
        """ adds list view items for each category and plugin in context

        @return None
        """
        seen = []
        for category in self.context.categories[::-1]:
            plugins = [p for p in category.plugins[::-1] if p.Enabled]
            if not category.Name:
                ## general plugin(s)
                for plugin in category.plugins:
                    if plugin.Enabled:
                        item = self.pluginItem(plugin, self)
                        seen.append(item)
            else:
                catitem = self.categoryItem(category)
                catitem.setVisible(bool(plugins))
                seen.append(catitem)
                for plugin in plugins:
                    if plugin.Enabled:
                        item = self.pluginItem(plugin, catitem)
                        seen.append(item)
        for item in self:
            if item.isVisible():
                item.setVisible(item in seen)
        self.setSorting(1)                        
        self.sort()
        self.setSorting(-1)
        
    def categoryItem(self, category):
        """ create a list view item for a category

        @param category
        @return QListViewItem instance
        """
        desc = category.ShortDesc
        item = self.findItem(desc, 0)
        if not item:
            item = CategoryViewItem(self, desc, category=category)
        item.setPixmap(0, category.icon(self.iconSize))
        return item

    def pluginItem(self, plugin, parent):
        """ create a list view item for a plugin

        @param category
        @return QListViewItem instance
        """
        for item in [i for i in self if i.parent() in (parent, 0)]:
            if item.plugin.Name == plugin.Name:
                item.plugin = plugin
                return item
        if parent is self:
            item = self.findItem(plugin.ShortDesc, 0)
            if item:
                item.plugin = plugin
                return item
        item = CategoryViewItem(parent, plugin.ShortDesc, plugin=plugin)
        item.setPixmap(0, plugin.icon(self.iconSize, self.loader))
        return item

    def otherSelected(self, other):
        """ set current item when other item is selected elsewhere

        @param other ViewItem instance
        @return None
        """
        for i in self:
            if i.plugin and i.plugin == other.plugin and i.parent():
                i.parent().setOpen(True)
                self.setCurrentEnsureVisible(i)                
                break


class ViewItem(QListViewItem):
    """ ViewItem -> QListViewItem with attributes common to local view classes

    """
    def __init__(self, parent, text, category=None, plugin=None, setting=None):
        QListViewItem.__init__(self, parent, text)
        self.category = category        
        self.plugin = plugin
        self.setting = setting


class CategoryViewItem(ViewItem):
    """ Sortable items for the category list view

    """
    def compare(self, other, column, ascending):
        """ compare this item to another

        @param other QListViewItem instance to compare against
        @param column ignored
        @param ascending ignored
        @return -1 if this item is less than other, 1 if greater, 0 if equal
        """
        for (obj, val) in ((self, -1), (other, 1)):
            if obj.plugin and obj.plugin.isGeneral:
                return val
        return cmp(self.text(0), other.text(0))