summaryrefslogtreecommitdiff
path: root/kberylsettings/settingwidget.py
blob: 570bd9c526169213994f53161e847866ed107f79 (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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" kberylsettings.settingwidget -> defines widgets for displaying and
editing berylsettings.Setting instances.

"""
from re import match

from kdecore import KShortcut, i18n
from kdeui import KIntNumInput, KDialogBase, KDoubleNumInput, KComboBox, KLineEdit, \
     KColorButton, KEditListBox, KPushButton, KKeyButton, KShortcutDialog
from kfile import KURLRequester, KURLComboBox, KURLComboRequester
from qt import QCheckBox, QFrame, QLabel, QObject, QWidget, QHBoxLayout, \
     QVBoxLayout, QGridLayout, QColor, qRgba, Qt, QCheckListItem, \
     QSizePolicy, QSpacerItem, QHButtonGroup, QRadioButton, QPushButton
from sip import wrappertype

from kberylsettings.lib import Signals, Slots
from kberylsettings.widget import GroupBox, ShortListView


def settingWidget(parent, plugin, setting):
    """ create display and edit widgets for setting

    This is the client interface to this module; no other methods or
    classes are needed.

    @param parent parent of setting widget
    @param plugin berylsettings Plugin instance
    @param setting berylsettings Setting instance
    @return new widget suitable for display and edit of setting
    """
    for typ in SettingWidgetDetector.types:
        call = typ.query(plugin, setting)
        if call:
            return call(parent, plugin, setting)


class SettingWidgetDetector(wrappertype):
    """ Small metaclass to gather subclasses of SettingWidget as
    they're created.

    """
    types = []

    def __init__(cls, name, bases, ns):
        super(SettingWidgetDetector, cls).__init__(name, bases, ns)
        types = SettingWidgetDetector.types
        if name != 'SettingWidget' and cls not in types:
            types.append(cls)


class SettingWidget(QFrame):
    """ Base class for setting widgets.

    Subclasses must define a 'build' method to construct their
    widgets.  This method must return a tuple of:

        (primary widget, change signal, value method, reset method)

    If both the primary widget and the change signal are not None,
    they're used to relay the 'something changed' signal.  In this
    manner, subclass build methods can indicate which widget/signal
    combination should indicate that the setting is changed and may be
    applied.

    Setting Widget classes inherit this class to participate in
    automatic discovery.  They also recieve a default implementation
    for 'query', which is quite handy.
    """
    __metaclass__ = SettingWidgetDetector

    def __init__(self, parent, plugin, setting):
        QFrame.__init__(self, parent)
        self.plugin = plugin
        self.setting = setting
        self.initial = setting.Value
        self.primaryWidget, self.changeSignal, self.value, self.reset = \
            self.build(parent, plugin, setting)
        try:
            self.reset()
        except (ValueError, ):
            pass
        if self.changeSignal and self.primaryWidget:
            self.connect(self.primaryWidget, self.changeSignal,
                         self, Signals.someChange)

    def labeledLayout(self, setting, stretch=1, layoutType=QVBoxLayout):
        """ create a layout object and a label for the setting

        @param setting berylsetting Setting instance
        @keyparam stretch=1 label layout stretch factor
        @keyparam layoutType=QVBoxLayout layout type
        @return layoutType instance with QLabel added
        """
        layout = layoutType(self)
        label = self.label = QLabel(setting.ShortDesc, self)
        layout.addWidget(label, stretch)
        return layout
        
    ##
    # subclasses can redefine this attribute to make use of the
    # default query method below.
    queryTypes = ()

    def query(cls, plugin, setting):
        """ determines if this class can be used to display plugin setting

        The default implementation checks for inclusion of the
        setting.Type in the queryTypes sequence.  Subclasses can
        override queryTypes, or override this method completely.
        
        @param cls class object
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return truth value if this type can build a widget for
        specified plugin and setting, false value otherwise.
        """
        return (setting.Type in cls.queryTypes) and cls
    query = classmethod(query)

    def setFromValue(self):
        """ set the setting value to the value of this widget

        @return None
        """
        value = self.value()
        self.setting.set(value)
        self.initial = value

    def setDefault(self):
        """ set the setting value to its default

        The berylsettings extension module performs the reset directly
        on the setting object.  In this method, we save the current
        value as defined by the widget and set that value again after
        the reset.
        """
        current = self.value()
        self.initial = self.setting.ResetToDefault()
        self.setting.set(current)
        self.reset()
        self.initial = current

    def cbText(self, widget):
        """ gets the text of a checkbox widget (minus amperstands)

        @return widget text
        """
        return str(widget.text()).replace('&', '')

    ##
    # Subclasses specify their value and reset methods when they build
    # their widgets.  We get a bit of reuse and a bit more clarity by
    # grouping these methods here.
    
    def checkBoxValue(self):
        """ checked state of our checkbox widget

        """
        return self.checkBox.isChecked()

    def checkBoxReset(self):
        """ reset checked state of our checkbox widget

        """
        self.checkBox.setChecked(self.initial)

    def comboText(self):
        """ current text of our combo widget

        """
        return str(self.combo.currentText())

    def comboTextReset(self):
        """ reset our combo widget text

        """
        combo = self.combo
        combo.clear()
        for r in self.setting.Restrictions:
            combo.insertItem(r)
        combo.setCurrentItem(self.initial)

    def comboIndex(self):
        """ index of our combo widget current item

        """
        return self.combo.currentItem()

    def comboIndexReset(self):
        """ sets our current combo widget item by index

        This method does not clear the combo, it only sets the current
        item.
        """
        self.combo.setCurrentItem(self.setting.Value)

    def numInputValue(self):
        """ current value of our numeric input widget

        """
        return self.numInput.value()

    def numInputReset(self):
        """ reset value of our numeric input widget

        """
        self.numInput.setValue(self.initial)

    def lineText(self):
        """ current value of our line edit widget

        """
        return str(self.line.text())

    def lineTextReset(self):
        """ resets value of our line edit widget

        """
        self.line.setText(self.initial)

    def checkBoxesValue(self):
        """ list of strings for all checked checkboxs

        """
        boxes = self.queryList('QCheckBox')
        return [self.cbText(box) for box in boxes if box.isChecked()]

    def checkBoxesReset(self):
        """ checks checkboxes for each string in our value

        """
        initial = self.initial
        for cb in self.queryList('QCheckBox'):
            cb.setChecked(self.cbText(cb) in initial)

    def listEditorValue(self):
        """ list of strings in our listEditor widget

        """
        box = self.listEditor.listBox()
        return [str(box.text(i)) for i in range(box.count())]

    def listEditorReset(self):
        """ clears and sets our listEditor widget

        """
        self.listEditor.clear()
        for value in self.initial:
            self.listEditor.insertItem(value)

    def radioGroupValue(self):
        """ index of selected radio item

        """
        radioId = self.radioGroup.selectedId()
        return self.setting.Restrictions[radioId]
    
    def radioGroupReset(self):
        """ sets or radio item

        """
        group = self.radioGroup
        initial = self.initial
        restrictions = self.setting.Restrictions
        for idx, value in enumerate(restrictions):
            button = group.find(idx)
            if not button:
                button = QRadioButton(value, group)
                group.insert(button, idx)
        group.setButton(restrictions.index(value))

    def requesterValue(self):
        """ current value of our requester widget

        """
        return str(self.requester.url())

    def requesterReset(self):
        """ sets url in our requester widget

        """
        self.requester.clear()
        self.requester.setURL(self.initial)

    def noOp(self):
        """ does nothing

        """


class SpecificNames(SettingWidget):
    """ Setting widget for specific named settings.

    Method names are in the form 'pluginname_settingname'.
    """
    iconCorners = 'BottomRight', 'BottomLeft', 'TopRight', 'TopLeft', 'Center'
    
    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        return self.lookup(plugin, setting)(self, parent, plugin, setting)

    def lookup(cls, plugin, setting):
        name = '%s_%s' % (plugin.Name, setting.Name, )
        alt = '_%s' % (setting.Name, )
        return getattr(cls, name, getattr(cls, alt, None))
    lookup = classmethod(lookup)
    
    def query(cls, plugin, setting):
        """ matches plugin and setting names to local method names

        @param cls class object
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return unbound method if found on class, None otherwise
        """
        return cls.lookup(plugin, setting) and cls
    query = classmethod(query)

    def switcher_icon_corner(self, parent, plugin, setting):
        """ creates a combo box for the Switcher Icon Corner setting

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting better be a icon_corner setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.combo = KComboBox(self)
        for index, text in enumerate(self.iconCorners):
            self.combo.insertItem(text, index)
        layout = self.labeledLayout(setting)        
        layout.addWidget(self.combo, 2)
        return (self.combo, Signals.activatedIndex,
                self.comboIndex, self.comboIndexReset)

    noActiveText = ('Active Plugins should not be edited directly.\n'
                    'Use the Plugin dialog from the Settings menu instead.')
    
    def _active_plugins(self, parent, plugin, setting):
        """ creates a non-editable widget for the Active Plugin setting

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting better be a icon_corner setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        layout = QVBoxLayout(self)
        self.groupBox = GroupBox(1, Qt.Vertical, setting.ShortDesc, self, 10, 10)
        self.groupBox.setFlat(False)
        layout.addWidget(self.groupBox)
        self.noActiveLabel = QLabel(self.noActiveText, self.groupBox)
        self.setFromValue = self.setDefault = self.noOp
        return (None, None, self.noOp, self.noOp)

                
class MatchNames(SettingWidget):
    """ Setting widget for settings with matching names.

    """
    lookups = (
       #((plugin name re, setting name re), method name)
        (('.*', '.*_file'), 'fileSelector'),
        (('annotate', 'tool'), 'fileSelector'),
        (('.*', 'skydome_image'), 'fileSelector'),
        (('.*', 'default_icon'), 'fileSelector'),
        (('.*', '(.*_)?window_types'), 'wmTypeSelector'),
        (('.*', 'images_top|images_bottom'), 'filesSelector'),
    )

    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        meth = self.lookup(plugin, setting)
        return meth(self, parent, plugin, setting)

    def lookup(cls, plugin, setting):
        for (plugpat, setpat), callname in cls.lookups:
            if match(plugpat, plugin.Name) and match(setpat, setting.Name):
                return getattr(cls, callname, None)
    lookup = classmethod(lookup)
    
    def query(cls, plugin, setting):
        """ matches plugin and setting names to local method names

        @param cls class object
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return unbound method if found on class, None otherwise
        """
        return cls.lookup(plugin, setting) and cls
    query = classmethod(query)
    
    def fileSelector(self, parent, plugin, setting):
        """ create a file selector widget

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.requester = KURLRequester(self)
        layout = self.labeledLayout(setting)        
        layout.addWidget(self.requester, 2)
        return (self.requester, Signals.textChanged,
                self.requesterValue, self.requesterReset)
    
    def filesSelector(self, parent, plugin, setting):
        """ create a multiple file selector widget

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.requester = urlreq = KURLRequester(self)
        editor = KEditListBox.CustomEditor(urlreq, urlreq.lineEdit())
        self.listEditor = KEditListBox(setting.ShortDesc, editor, self)
        layout = QVBoxLayout(self)
        layout.addWidget(self.listEditor, 2)
        return (self.listEditor, Signals.changed,
                self.listEditorValue, self.listEditorReset)
    
    def wmTypeSelector(self, parent, plugin, setting):
        """ create a widget for selecting window types

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.group = GroupBox(3, Qt.Horizontal, setting.ShortDesc, self)
        for text in setting.Restrictions:
            checkBox = QCheckBox(text, self.group)
            self.connect(checkBox, Signals.clicked,
                         self, Signals.someChange)
        layout = QVBoxLayout(self)
        layout.addWidget(self.group, 2)
        return (self.group, None, self.checkBoxesValue, self.checkBoxesReset)


class Choice(SettingWidget):
    """ Setting widget for true/false values.

    """
    queryTypes = ('Bool', )
    
    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        layout = QHBoxLayout(self)
        self.checkBox = QCheckBox(self)
        layout.addWidget(self.checkBox)
        label = QLabel(setting.ShortDesc, self)        
        layout.addWidget(label, 100)
        return (self.checkBox, Signals.toggled,
                self.checkBoxValue, self.checkBoxReset)


class Color(SettingWidget):
    """ Setting widget for colors.

    """
    queryTypes = ('Color', )
    
    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        group = GroupBox(1, Qt.Vertical, setting.ShortDesc, self)
        layout = QVBoxLayout(self)
        layout.addWidget(group)
        
        frame = QFrame(group)
        self.colorLabel = colorLabel = QLabel(i18n('Select Color:'), frame)
        self.colorButton = colorButton = KColorButton(frame)
        self.opacityInput = opacityInput = KIntNumInput(frame)

        opacityInput.setRange(0, 255)
        opacityInput.setSteps(1, 10)
        opacityInput.setLabel(i18n('Select Opacity:'),
                              Qt.AlignVCenter|Qt.AlignLeft)
        opacityInput.setSpecialValueText(i18n('Clear'))

        layout = QHBoxLayout(frame)
        layout.addWidget(colorLabel, 2)
        layout.addWidget(colorButton, 1)
        layout.addStretch(2)
        layout.addWidget(opacityInput, 10)

        self.connect(colorButton, Signals.colorChanged,
                     self, Signals.someChange)
        self.connect(colorButton, Signals.colorChanged,
                     self.updateColor)
        self.connect(opacityInput, Signals.intValueChanged,
                     self, Signals.someChange)
        return (colorButton, None, self.colorValue, self.colorReset)

    def updateColor(self, color):
        """ slot for receiving new color

        @param color QColor instance
        @return None
        """
        self.color = color

    def colorValue(self):
        """ color value of this widget

        @return four-item tuple of (r, g, b, a)
        """
        c = self.color
        rgba = (c.red(), c.green(), c.blue(), self.opacityInput.value())
        return tuple([v*256 for v in rgba])

    def colorReset(self):
        """ resets color to initial value

        @return None
        """
        self.color = color = QColor()
        color.setRgb(*[a/256 for a in self.setting.Value[0:3]])
        self.colorButton.setColor(color)
        v = (self.setting.Value[3] / 256)
        self.opacityInput.setValue(v)


class Number(SettingWidget):
    """ Setting widget for numeric ranges.  Integers and floats supported.

    """
    queryTypes = {
        'Int' : KIntNumInput,
        'Float' : KDoubleNumInput,
        }

    changeSignals = {
        'Int' :  Signals.intValueChanged,
        'Float' : Signals.doubleValueChanged,
        }
    
    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.numInput = self.queryTypes[setting.Type](self)        
        try:
            minvalue, maxvalue, stepvalue = setting.Restrictions
        except (ValueError, ):
            minvalue, maxvalue  = setting.Restrictions
            stepvalue = 1
        self.numInput.setRange(minvalue, maxvalue, stepvalue, True)
        layout = self.labeledLayout(setting, layoutType=QHBoxLayout)
        layout.addWidget(self.numInput, 2)
        return (self.numInput, self.changeSignals[setting.Type],
                self.numInputValue, self.numInputReset)


class FewChoices(SettingWidget):
    """ Radio group widget for choosing among just a few items.

    """
    queryTypes = ('String', )
    maxRestrictions = 5
    
    def query(cls, plugin, setting):
        """ matches string types with fewer than max restrictions

        @param cls class object
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return unbound method if found on class, None otherwise
        """
        if setting.Type in cls.queryTypes and setting.Restrictions:
            return (len(setting.Restrictions) < cls.maxRestrictions) and cls
    query = classmethod(query)

    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.radioGroup = QHButtonGroup(setting.ShortDesc, self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.radioGroup, 1)
        layout.addStretch(2)
        return (self.radioGroup, Signals.clickedId,
                self.radioGroupValue, self.radioGroupReset)


class String(SettingWidget):
    """ Setting widget for strings.

    """
    queryTypes = ('String', )

    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        if setting.Restrictions:
            self.combo = KComboBox(self)
            res = (self.combo, Signals.activatedIndex,
                   self.comboText, self.comboTextReset)
        else:
            self.line = KLineEdit(self)
            res = (self.line, Signals.textChanged,
                   self.lineText, self.lineTextReset)
        layout = self.labeledLayout(setting, layoutType=QHBoxLayout)
        layout.addWidget(res[0], 2)
        return res


class StringList(SettingWidget):
    """ Setting widget for lists of strings.

    """
    queryTypes = ('List of String', )

    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.listEditor = KEditListBox(setting.ShortDesc, self)
        layout = QVBoxLayout(self)
        layout.addWidget(self.listEditor, 2)
        return (self.listEditor, Signals.changed,
                self.listEditorValue, self.listEditorReset)


class Binding(SettingWidget):
    """ Setting widget for keyboard/pointer/edge bindings.

    restrictions example:
        [1, 1, 0, 1]
    decoded:
        [can set key, can set button, can set bell, can set edge]

    value example:
        ('<Alt>F2', 'Disabled', False, [])    
    decoded:
        [key string, button string, bell enabled, edge list]

    """
    queryTypes = ('Binding', )

    edges = (
        'Left', 'Right', 'Top', 'Bottom',
        'Top-Left', 'Top-Right',
        'Bottom-Left', 'Bottom-Right',
    )

    modifiers = (
        'Shift', 'Control', 'Alt', 'Super', 'Hyper', 'Meta', 'Mode',
        'Mod1', 'Mod2', 'Mod3', 'Mod4', 'Mod5',
    )

    pointerButtons = (
        '1 (primary)',
        '2 (middle)',
        '3 (secondary)',        
        '4 (often wheel up)',
        '5 (often wheel down)',
        '6 (if available)',
        '7 (if available)',
        '8 (if available)',
        '9 (if available)',        
    )

    idxKey, idxPointer, idxBell, idxEdge = idxs = range(4)
    
    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        self.controls = [None, None, None, None]        
        self.label = QLabel(setting.ShortDesc, self)
        layout = QGridLayout(self, 4, 4, 0, 10)        
        layout.addMultiCellWidget(self.label, 0, 0, 0, 3, Qt.AlignTop|Qt.AlignLeft)
        restrictions = setting.Restrictions
        if restrictions[self.idxBell]:
            self.controls[self.idxBell] = control = \
                self.bellWidget('Bell')
            layout.addMultiCellWidget(control.bellFrame, 1, 1, 0, 3)
        if restrictions[self.idxKey]:
            self.controls[self.idxKey] = control = \
                self.bindingWidget('Key', self.idxKey)
            layout.addLayout(control.headerLayout, 2, 1)
            layout.addWidget(control.modifierList, 3, 1)
        if restrictions[self.idxPointer]:
            self.controls[self.idxPointer] = control = \
                self.bindingWidget('Pointer Button', self.idxPointer)
            layout.addLayout(control.headerLayout, 2, 2)
            layout.addWidget(control.modifierList, 3, 2)
        if restrictions[self.idxEdge]:
            self.controls[self.idxEdge] = control = \
                self.edgeBindingWidget('Edge')
            layout.addWidget(control.typeLabel, 2, 3)
            layout.addWidget(control.edgeList, 3, 3)
        else:
            layout.addItem(self.spacer(), 2, 3)
            layout.addItem(self.spacer(), 3, 3)            
        return (None, None, self.bindingValue, self.bindingReset)

    def bindingValue(self):
        """ gets value of this widet

        """
        val = ['Disabled', 'Disabled', False, []]        
        res = self.setting.Restrictions
        idxKey, idxPointer, idxBell, idxEdge = self.idxs
        if res[idxKey]:
            if self.controls[idxKey].enableCheck.isChecked():
                key = self.controls[idxKey].keyLine.text()
                mods = [i.text(0) for i in self.controls[idxKey].modifierList
                        if i.state()==i.On]
                mods = str.join('', ['<%s>' % m for m in mods])
                val[idxKey] = '%s%s' % (mods, key)
        if res[idxPointer]:
            if self.controls[idxPointer].enableCheck.isChecked():
                button = self.controls[idxPointer].buttonList.currentItem()
                mods = [i.text(0) for i in self.controls[idxPointer].modifierList
                        if i.state()==i.On]
                mods = str.join('', ['<%s>' % m for m in mods])
                val[idxPointer] = '%sButton%s' % (mods, button+1)
        if res[idxBell]:
            val[idxBell] = self.controls[idxBell].bellCheck.isChecked()
        if res[idxEdge]:
            ctl = self.controls[idxEdge].edgeList
            edges = val[idxEdge]
            edges.extend([str(i.text(0)) for i in ctl if i.state()==i.On])
        return tuple(val)

    def bindingReset(self):
        """ resets this widget

        """
        value = self.initial
        
        def reset(index):
            enabled = value[index] != 'Disabled'            
            control = self.controls[index]
            def valuenomod():
                return value[index].split('>')[-1]
            try:
                control.keyLine.setText(enabled and valuenomod() or '')
            except (AttributeError, ): pass
            try:
                buttonList = control.buttonList
            except (AttributeError, ): pass
            else:
                buttonList.clear()
                for text in self.pointerButtons:
                    buttonList.insertItem(text)
                if enabled:
                    try:
                        buttonNo = valuenomod().replace('Button', '')
                        buttonList.setCurrentItem(int(buttonNo) - 1)
                    except (Exception, ), exc:
                        pass
            def resetView(v, s):
                v.clear()
                for t in s[::-1]:
                    i = QCheckListItem(v, t, QCheckListItem.CheckBox)
                    i.setState(t in value[index] and i.On or i.Off)
            try:
                resetView(control.modifierList, self.modifiers)
            except (AttributeError, ): pass
            try:
                resetView(control.edgeList, self.edges)
            except (AttributeError, ): pass
            try:
                checkBox = control.enableCheck
                checkBox.setChecked(enabled)                    
                checkBox.emit(Signals.toggled, (enabled,))
            except (AttributeError, ): pass
            try:
                checkBox = control.bellCheck
                checkBox.setChecked(value[index])
                checkBox.emit(Signals.toggled, (value[index], ))
            except (AttributeError, ): pass
                    
        ## use the closure
        restrictions = self.setting.Restrictions
        for key in self.idxs:
            if restrictions[key]:
                reset(key)

    def bindingWidget(self, text, which):
        """ create a key or mouse binding widget

        @param text value for binding type label
        @param which binding type; see 'idxs' attribute
        @return object with binding widget attributes
        """
        connect = self.connect
        ctl = self.control()
        toggled = Signals.toggled
        someChange = Signals.someChange

        ctl.headerLayout = headerLayout = QVBoxLayout()
        ctl.enableCheck = enableCheck = QCheckBox('', self)
        headerLayout.addWidget(enableCheck)        

        ctl.lineLayout = lineLayout = QHBoxLayout(headerLayout)        
        connect(enableCheck, Signals.clicked, self, someChange)
        ctl.typeLabel = typeLabel = QLabel(text, self)
        lineLayout.addWidget(typeLabel)
        connect(enableCheck, toggled, typeLabel.setEnabled)

        if which == self.idxKey:
            enableCheck.setText(i18n('Enable Key'))
            ctl.keyLine = keyLine = KLineEdit(self)
            lineLayout.addWidget(keyLine)
            ctl.keyButton = keyButton = GrabKeyButton(self)
            lineLayout.addWidget(keyButton)
            connect(keyLine, Signals.textChanged, self, someChange)
            connect(keyButton, Signals.capturedShortcut, self.onKeyCapture)
            connect(keyButton, Signals.capturedShortcut, self, someChange)
            connect(enableCheck, toggled, keyLine.setEnabled)
            connect(enableCheck, toggled, keyButton.setEnabled)            
        elif which == self.idxPointer:
            enableCheck.setText(i18n('Enable Button'))            
            ctl.buttonList = buttonList = KComboBox(self)
            lineLayout.addWidget(buttonList)
            connect(buttonList, Signals.activatedIndex, self, someChange)
            connect(enableCheck, toggled, buttonList.setEnabled)

        ctl.modifierList = ShortListView(self, i18n('Modifiers'), 5)
        connect(ctl.modifierList, Signals.itemSelected, self, someChange)        
        connect(enableCheck, toggled, ctl.modifierList.setEnabled)
        return ctl
        
    def edgeBindingWidget(self, text):
        """ create an edge binding widget

        @param text value for binding type label
        @return object with binding widget attributes
        """
        connect = self.connect        
        ctl = self.control()
        ctl.typeLabel = QLabel(text, self)
        ctl.edgeList = edgeList = ShortListView(self, i18n('Edges'), 5)
        connect(edgeList, Signals.itemSelected, self, Signals.someChange)
        return ctl

    def bellWidget(self, text):
        """ create a bell binding widget

        @param text value for binding type label
        @return object with binding widget attributes
        """
        ctl = self.control()
        ctl.bellFrame = QFrame(self)
        layout = QHBoxLayout(ctl.bellFrame)
        ctl.bellCheck = QCheckBox(i18n('Enable Bell'), ctl.bellFrame)
        layout.addWidget(ctl.bellCheck)
        self.connect(ctl.bellCheck, Signals.toggled, self, Signals.someChange)
        return ctl

    def onKeyCapture(self, key):
        """ slot to receive changed key binding

        @param key KKey instance with new key binding
        @return None
        """
        skey = str(key.toString())        
        skey = skey.replace('Win', 'Super')
        skey = skey.replace('Ctl', 'Control')        
        skey = skey.split('+')
        if len(skey) == 1:
            skey = skey[0]
        else:
            skey = str.join('', ['<%s>' % i for i in skey[:-1]]) + skey[-1]
        init = list(self.initial)
        init[self.idxKey] = skey
        self.initial = tuple(init)
        self.reset()
        
    class control(object):
        """ add attributes to instances of this handy-and-empty class

        """

    def spacer(self):
        """ creates and returns a new QSpacerItem

        @return QSpacerItem instance
        """
        return QSpacerItem(1, 1, QSizePolicy.Expanding, QSizePolicy.Expanding)


class Unknown(SettingWidget):
    """ Setting widget for unknown values.

    Because this class is defined last, it's caught by the metaclass
    last and therefore put into the list of types at the end.
    Whenever a setting object cannot be otherwise matched to a
    SettingWidget, this class will be called.
    """    

    def build(self, parent, plugin, setting):
        """ create widget(s) for setting display and edit

        @param parent parent object of this widget
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return four-item tuple of (widget, signal, valuemethod, resetmethod)
        """
        layout = self.labeledLayout(setting, layoutType=QHBoxLayout)
        text = '%s (Unknown Type %s)' % (setting.ShortDesc, setting.Type, )
        self.label.setText(text)
        return (self.label, Signals.clicked, None, None)

    def query(cls, plugin, setting):
        """ matches plugin and setting names to local method names

        @param cls class object
        @param plugin berylsettings Plugin instance
        @param setting berylsettings Setting instance
        @return True
        """
        return cls
    query = classmethod(query)


class GrabKeyButton(KKeyButton):
    """ GrabKeyButton -> KKeyButton without extra painting or dialog buttons

    """
    def __init__(self, parent):
        KKeyButton.__init__(self, parent)
        self.setText(i18n('Grab'))
        self.disconnect(self, Signals.clicked, self, Slots.captureShortcut)
        self.connect(self, Signals.clicked, self.captureShortcut)
        
    def drawButton(self, painter):
        """ draw the face of this button

        This implementation skips the KKeyButton drawButton method and instead
        defers painting directly to the QPushButton ancestor class.

        @param painter QPainter instance
        @return None
        """
        QPushButton.drawButton(self, painter)

    def setText(self, text):
        """ set the button text 

        Like the drawButton method, we skip over the KKeyButton
        implementation so that this button size can be set like other
        buttons.
        
        @param text value for button
        @return None
        """
        QPushButton.setText(self, text)
        self.setFixedSize(self.sizeHint().width(), self.sizeHint().height())

    def captureShortcut(self):
        """ shows a simplified KShortcutDialog for shortcut capture

        @return None
        """
        dlg = KShortcutDialog(self.shortcut(), True, self)
        dlg.showButton(KShortcutDialog.Details, False)        
        res = dlg.exec_loop()
        if res == KShortcutDialog.Accepted:
            self.emit(Signals.capturedShortcut, (dlg.shortcut(), ))