summaryrefslogtreecommitdiff
path: root/kberylsettings/contentframe.py
blob: 68e8582ff8723c78e42a2d2cf0f0c04674097b5e (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" kberylsettings.contentframe -> defines the right side about/setting views.

"""
from kdecore import KIcon, i18n
from kdeui import KMessageBox, KPassivePopup, KPushButton, \
     KSeparator, KStdGuiItem
from qt import Qt, QFrame, QHBoxLayout, QLabel, QScrollView, QSize, \
     QSizePolicy, QStringList, QToolTip, QVBoxLayout

from kberylsettings.lib import App, Signals, buildPart, icon, iconLoader, iconSet
from kberylsettings.widget import Frame, SmallPushButton, WidgetStack
from kberylsettings.settingwidget import settingWidget


class ContentFrame(WidgetStack):
    """ ContentFrame -> stack with About page, Settings Page.

    """
    aboutPageId = 0
    settingsPageId = 1
    
    def __init__(self, parent):
        WidgetStack.__init__(self, parent)
        self.loader = iconLoader()
        self.buildAboutPage()
        self.buildSettingsPage()
        self.buildConnections()

    def buildAboutPage(self):
        """ builds the About Plugin page

        @return None
        """
        self.aboutPage = Frame(self, margin=6, spacing=10)
        self.addWidget(self.aboutPage, self.aboutPageId)        
        self.infoHtml = buildPart(self.aboutPage, 'text/html',
                                   "Type == 'Service'", True)


    def buildSettingsPage(self):
        """ builds page for displaying one or more settings

        @return None
        """
        self.settingsPage = page = Frame(self, 6, 10)
        self.addWidget(page, self.settingsPageId)
        
        self.pluginHeader = header = QFrame(page)
        self.pluginIconLabel = QLabel(header)
        self.pluginNameLabel = QLabel(header)
        
        headerLayout = QHBoxLayout(header)
        headerLayout.addWidget(self.pluginIconLabel, 1)
        headerLayout.addWidget(self.pluginNameLabel, 10)
        
        self.settingsMain = main = SettingsContainer(page)
        self.scrollerWrap = wrap = Frame(page)
        self.settingsScroller = scroller = ContentScroll(wrap, main)

        KSeparator(KSeparator.Horizontal, page)
        self.settingsFooter = footer = QFrame(page)
        footerLayout = QHBoxLayout(footer)

        def contentButton(name):
            gui = getattr(KStdGuiItem, name)()
            button = KPushButton(gui.iconSet(), gui.text(), footer)
            footerLayout.addWidget(button)
            return button

        self.helpButton = contentButton('help')
        self.defaultsButton = contentButton('defaults')
        footerLayout.addStretch(2)
        self.applyButton = applyButton = contentButton('apply')
        applyButton.setEnabled(False)        
        self.resetButton = resetButton = contentButton('reset')
        resetButton.setEnabled(False)
        
    def buildConnections(self):
        """ build the connections for this instance

        @return None
        """
        connect = self.connect
        connect(self.helpButton, Signals.clicked, self.settingHelp)
        connect(self.defaultsButton, Signals.clicked, self.settingDefaults)
        connect(self.resetButton, Signals.clicked, self.settingsReset)
        connect(self.applyButton, Signals.clicked, self.settingApply)        
        root = self.topLevelWidget()
        connect(self, Signals.berylSettingChanged, root.onContextChanged)
        connect(self, Signals.statusMessage, root.showMessage)        
        connect(self.settingsMain, Signals.someChange,
                self.onSomethingChanged)

    def onSomethingChanged(self):
        self.applyButton.setEnabled(True)
        self.resetButton.setEnabled(True)        

    def showAbout(self, plugin):
        """ displays the About Plugin page with information from the plugin

        @param plugin berylsettings Plugin instance
        @return None
        """
        logofile = 'file://%s' % App.basedir + '/html/beryl-manager.png'
        htmlsrc = open(App.basedir + '/html/plugin.html').read()        
        if plugin is None:
            pluginname = 'Beryl Settings'
            plugindesc = 'Beryl Settings - Get Your Effects On!'
        else:
            #logofile = 'file://%s' % App.basedir + '/pixmaps/beryl-settings-section-%s.png' % plugin.Name
            pluginname = plugin.ShortDesc
            plugindesc = plugin.LongDesc
        self.infoHtml.begin()
        self.infoHtml.write(htmlsrc % locals())
        self.infoHtml.end()
        self.raiseWidget(self.aboutPageId)

    unsavedText = """There are unsaved changes in the active settings.

    Do you want to apply the changes before changing views or discard the changes?
    """
    
    def showSettings(self, plugin, arg):
        """ displays the settings page with individual setting frames

        @param plugin berylsettings Plugin instance
        @param arg setting name or setting section name
        @return None
        """
        if self.applyButton.isEnabled():
            msg = KMessageBox.warningYesNoCancel
            res = msg(self, self.unsavedText, i18n('Unsaved Changes'),
                      KStdGuiItem.apply(), KStdGuiItem.discard())
            if res == KMessageBox.Cancel:
                return
            elif res == KMessageBox.Yes:
                self.settingApply()
            #else it's no/discard so fall thru
        ico = plugin.icon(KIcon.SizeLarge, self.loader)
        self.pluginIconLabel.setPixmap(ico)
        if arg in plugin.settings:
            settings = plugin.settings[arg]
            extra = ' - %s' % (arg, )
        else:
            settings = [arg, ]
            extra = ''
        self.pluginNameLabel.setText('<b>%s%s</b>' % (plugin.ShortDesc, extra))
        self.settingsMain.addSettings(plugin, settings)
        self.applyButton.setEnabled(False)
        self.resetButton.setEnabled(False)
        self.raiseWidget(self.settingsPageId)        

    def settingHelp(self):
        """ not implemented

        """

    def settingDefaults(self):
        """ set each setting to its default value

        @return None
        """
        frame = self.settingsPage        
        widgets = frame.queryList('SettingFrame')
        for widget in widgets:
            try:
                widget.setDefault()
            except (Exception, ), exc:
                print 'reset exception:', exc
        self.applyButton.setEnabled(True)
        self.resetButton.setEnabled(True)

    def settingsReset(self):
        """ set each setting to its previous value

        @return None
        """
        frame = self.settingsPage        
        widgets = frame.queryList('SettingWidget')
        for widget in widgets:
            try:
                widget.reset()
            except (Exception, ), exc:
                print 'reset exception:', exc
        self.applyButton.setEnabled(True)
        self.resetButton.setEnabled(False)
        
    def settingApply(self):
        """ not final

        """
        excs = []
        for w in self.settingsPage.queryList('SettingWidget'):
            try:
                v = w.value()
                w.setting.set(v)
                w.initial = v
            except (Exception, ), exc:
                excs.append((w.plugin.Name, w.setting.Name, exc))
        if excs:
            excstrs = QStringList()
            for exc in excs:
                excstrs.append('Plugin:%s Setting:%s Exception:%s' % exc)
            KMessageBox.errorList(None, 'Exceptions Saving Settings',
                                         excstrs)
        self.applyButton.setEnabled(False)
        self.resetButton.setEnabled(False)
        self.emit(Signals.statusMessage, ('Saving settings...', ))
        self.emit(Signals.berylSettingChanged, ())


class SettingsContainer(QFrame):
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.settingFrames = []
        layout = QVBoxLayout(self, 5)

    def addSettings(self, plugin, settings):
        self.clearFrames()        
        layout = self.layout()
        changed = Signals.someChange
        for setting in settings:
            frame = SettingFrame(self, plugin, setting)
            self.settingFrames.append(frame)            
            layout.addWidget(frame, 0, Qt.AlignTop)
            self.connect(frame, changed, self, changed)
        layout.addStretch(5)
        for frame in self.settingFrames:
            frame.show()
        self.updateGeometry()

    def clearFrames(self):
        for widget in self.settingFrames:
            widget.close(True)
        self.layout().deleteAllItems()
        self.settingFrames = []


class SettingFrame(QFrame):
    """ SettingFrame -> displays editing widgets for a single Setting instance.

    """
    def __init__(self, parent, plugin, setting):
        QFrame.__init__(self, parent)
        mainLayout = QVBoxLayout(self)
        innerLayout = QHBoxLayout(mainLayout, 3)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.infoCaption = setting.ShortDesc
        self.infoText = setting.LongDesc
        self.infoButton = info = SmallPushButton(iconSet('help'), '', self)
        self.resetButton = reset = \
            SmallPushButton(iconSet('locationbar_erase'), '', self)
        QToolTip.add(reset, i18n('Reset to default value'))
        self.settingWidget = widget = settingWidget(self, plugin, setting)
        if isinstance(widget.layout(), QHBoxLayout):
            align = Qt.AlignLeft | Qt.AlignVCenter
        else:
            align = Qt.AlignLeft | Qt.AlignTop
        innerLayout.addWidget(info, 0, align)
        innerLayout.addWidget(reset, 0, align)
        innerLayout.addWidget(widget, 10)
        mainLayout.addSpacing(10)

        connect = self.connect
        connect(info, Signals.clicked, self.showInfo)
        connect(reset, Signals.clicked, self.setDefault)
        connect(widget, Signals.someChange,
                self, Signals.someChange)

    def setDefault(self):
        w = self.settingWidget
        curv = w.value()
        newv = w.initial = w.setting.ResetToDefault()
        w.setting.set(curv) # because it's not applied yet
        w.reset()

    def showInfo(self):
        """ show a balloon tip with the setting description

        @return None
        """
        parent = self.resetButton
        ico = icon('help', size=KIcon.SizeLarge)
        txt = self.infoText
        cap = self.infoCaption
        msg = KPassivePopup.message        
        pop = msg(KPassivePopup.Balloon, cap, txt, ico, parent)
        pos = pop.pos()
        pos.setY(pos.y() + (parent.height() / 2))
        pos.setX(pos.x() + (parent.width() * 2))
        pop.show()
        pop.move(pos)        


class ContentScroll(QScrollView):
    """ ContentScroll -> a scroll view fitted to a single child

    """
    def __init__(self, parent, child):
        QScrollView.__init__(self, parent)
        self.setResizePolicy(QScrollView.AutoOneFit)
        self.setFrameShape(self.NoFrame)
        self.addChild(child)