summaryrefslogtreecommitdiff
path: root/kberylsettings/main.py
blob: f28efe481c28236ebf3bdb262a6029a0970ddb42 (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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" kberylsettings.main -> defines KBerylSettings main window.

"""
from os import listdir
from os.path import abspath, dirname, exists, expanduser
from sys import argv

from kdecore import KApplication, KCmdLineArgs, KIcon, KGlobal, KWin, i18n, locate
from kdeui import KMainWindow, KStdGuiItem, KLineEdit, KSystemTray, KTipDialog, \
     KKeyDialog
from kio import KDirWatch
from kfile import KFileDialog
from qt import Qt, QWidget, QHBoxLayout, QLabel, QImage

from kberylsettings.aboutapp import about
from kberylsettings.beryl import Context
from kberylsettings.contentframe import ContentFrame
from kberylsettings.lib import Signals, Slots, action, stdAction, icon
from kberylsettings.plugindialog import PluginDialog
from kberylsettings.pluginframe import PluginFrame
from kberylsettings.widget import Frame, Popup, SmallPushButton, Splitter


class KBerylSettings(KMainWindow):
    """ The main window.

    """
    viewMode = PluginFrame.categoryPageId
    iconSize = KIcon.SizeMedium
    startDir = '::kberylsettings'
    berylDir = expanduser('~/.beryl/')
    
    def __init__(self):
        KMainWindow.__init__(self)
        self.buildWidgets()
        self.buildMenus()
        self.buildSystray()
        self.buildConnections()
        self.buildFinal()
        
    def buildWidgets(self):
        """ builds widgets on this instance

        @return None
        """
        actions = self.actionCollection()
        actions.setHighlightingEnabled(True)
        self.mainSplitter = splitter = Splitter(self, Qt.Horizontal)
        self.leftFrame = left = Frame(splitter)
        self.rightFrame = right = Frame(splitter)
        self.contentFrame = ContentFrame(right)
        self.searchWidget = search = QWidget(self.leftFrame)
        searchLayout = QHBoxLayout(search, 6, 6)
        searchLayout.setAutoAdd(True)
        clear = KStdGuiItem.clear()
        self.clearSearch = SmallPushButton(clear.iconSet(), '', search)
        self.labelSearch = QLabel(i18n('Search: '), search)
        self.inputSearch = KLineEdit(search)
        self.pluginList = PluginFrame(left)
        self.setCentralWidget(splitter)
        statusBar = self.statusBar()

    def buildMenus(self):
        """ builds the menus for this instance

        @return None
        """
        menu = self.menuBar()
        menu.insertItem(i18n('&File'), self.fileMenu())
        menu.insertItem(i18n('&View'), self.viewMenu())
        menu.insertItem(i18n('&Settings'), self.settingsMenu())        
        menu.insertItem(i18n('&Help'), self.helpMenu())

    def buildSystray(self):
        """ builds the system tray icon for this instance

        @return None
        """
        self.sysTray = KSystemTray(self)
        pixmap = icon(self.iconFile, size=KIcon.SizeSmallMedium)
        self.sysTray.setPixmap(pixmap)
        pop = self.sysTray.contextMenu()
        self.pluginsAction.plug(pop)
        cap = KApplication.kApplication().caption()
        pop.changeTitle(pop.idAt(0), pixmap, cap)
        pop.insertItem(i18n('Named &Profiles'), self.profileMenu())
        self.sysTray.show()

    def iconFile(self):
        """ names the default icon file

        @return icon filename 
        """
        return locate('icon', 'kberylsettings.svg')
    iconFile = property(iconFile)
    
    def buildConnections(self):
        """ builds the connections for this instance

        @return None
        """
        connect = self.connect
        connect(self, Signals.viewModeChanged, self.onMode)        
        connect(self, Signals.iconSizeChanged, self.onIconSize)
        connect(self.clearSearch, Signals.clicked, self.onClearSearch)        
        connect(self.inputSearch, Signals.textChanged, self.onInputSearch)
        connect(self.sysTray, Signals.quitSelected, self.close)
        statusBar = self.statusBar()
        actions = self.actionCollection()
        connect(actions, Signals.actionStatusText, self.statusBar(),
                Slots.messageText)
        connect(actions, Signals.clearStatusText, self.statusBar(),
                Slots.clear)

    def buildFinal(self):
        """ do everything else needed to create the widget

        @return None
        """
        self.context = context = Context()
        self.emit(Signals.berylContextChanged, (context, ))
        connect = self.connect
        connect(context, Signals.statusMessage, self.showMessage)
        self.setIcon(icon(self.iconFile, size=KIcon.SizeSmall))
        KWin.setIcons(self.winId(),
                      icon(self.iconFile, size=KIcon.SizeLarge),
                      icon(self.iconFile, size=KIcon.SizeSmall))
        config = self.config('mainwindow')
        self.restoreWindowSize(config)
        self.mainSplitter.setSizes([self.width()*0.25, self.width()*0.75])
        self.onIntro()
        config = self.config('mainview')
        emit = self.emit
        emit(Signals.iconSizeChanged,
             (config.readNumEntry('iconsize', self.iconSize), ))
        viewMode = config.readNumEntry('viewmode', self.viewMode)
        emit(Signals.viewModeChanged, (viewMode, ))
        actions = self.actionCollection()
        actions.readShortcutSettings('shortcuts', self.config())
        ## done after initial emit to prevent spurious context update
        connect(self, Signals.berylContextChanged, self.onContextChanged)
        self.tipDialog(force=False)

    def config(self, group=None):
        """ loads the general configuration object

        @keyparam group=None if provided, config group set to this value
        @return KConfig instance
        """
        config = KGlobal.instance().config()
        if group is not None:
            config.setGroup(group)
        return config

    def fileMenu(self):
        """ creates a new File menu

        @return KPopupMenu instance
        """
        pop = Popup(self)
        actions =  self.actionCollection()
        self.importAction = action('Import settings...', 'fileopen', 'Ctrl+O',
                                   self.onImport, actions, 'import_action',
                                   'Import settings from a file.',
                                   pop)
        self.exportAction = action('Export settings...', 'filesave', 'Ctrl+S',
                                   self.onExport, actions, 'export_action',
                                   'Export settings to a file.',
                                   pop)
        pop.insertSeparator()
        pop.insertItem(i18n('Named &Profiles'), self.profileMenu())
        self.quitAction = stdAction('quit', self.close, actions, '', pop)
        return pop

    def helpMenu(self):
        """ creates a new Help menu

        @return KPopupMenu instance
        """
        actions = self.actionCollection()        
        pop = KMainWindow.helpMenu(self)
        self.tipAction = stdAction('tipOfDay', self.tipDialog, actions,
                                   'tipOfDay', None)
        self.introAction = action('KDE Beryl Settings Introduction',
                                  'help', 'Ctrl+I', self.onIntro,
                                  actions, 'intro_action',
                                  'Show the introduction.', None)
        pop.insertSeparator(2)
        self.tipAction.plug(pop, 3)
        self.introAction.plug(pop, 4)
        return pop

    def profileMenu(self):
        """ creates a new Named Profiles menu

        """
        try:
            profileMap = self.profileMap
        except (AttributeError, ):
            profileMap = self.profileMap = {}
        try:
            watcher = self.watcher
        except (AttributeError, ):
            watcher = self.watcher = KDirWatch(self)
            self.connect(watcher, Signals.fileChanged, self.updatedFile)
            self.connect(watcher, Signals.fileCreated, self.newFile)
        
        berylDir = self.berylDir
        profFormat = 'settings%s.Profile'
        maybeProfiles = [profFormat % i for i in range(1, 6)]

        pop = Popup(self)
        for name in maybeProfiles:
            popid = pop.insertItem(name)
            path = berylDir + name
            index = hash(path)
            profileMap[index] = path
            pop.setItemParameter(popid, index)
            pop.setItemEnabled(popid, exists(path))
            pop.connectItem(popid, self.onProfileSelect)
            watcher.addFile(path)
        return pop

    def updatedFile(self, path):
        print '### updated file path:', path

    def newFile(self, path):
        print '### new file path:', path        
            
    def viewMenu(self):
        """ creates a new View menu

        @return KPopupMenu instance
        """
        pop = Popup(self)
        pop.insertItem(i18n('&Mode'), self.modeMenu())
        pop.insertItem(i18n('Icon &Size'), self.iconSizeMenu())
        return pop

    def settingsMenu(self):
        """ creates a new Settings menu

        @return KPopupMenu instance
        """
        actions = self.actionCollection()
        pop = Popup(self)
        self.pluginsAction = action('Select Plugins...', 'configure', 'Ctrl+P',
                                    self.onSelectPlugins,
                                    actions,
                                    'select_plugins',
                                    'Select Beryl plugins.',
                                    pop)
        pop.insertSeparator()
        self.toggleMenuBarAction  = action('Hide menubar',
                                           'showmenu', 'Ctrl+M',
                                           self.onMenuBar,
                                           actions,
                                           'toggle_menubar',
                                           'Hide menubar.',
                                           pop)
        self.toggleStatusBarAction = action('Hide statusbar',
                                            '', '',
                                            self.onStatusBar,
                                            actions,
                                            'toggle_statusbar',
                                            'Hide statusbar.',
                                            pop)
        self.keysAction = stdAction('keyBindings', self.onConfigKeys,
                                    actions, 'keyBindings', pop)
        return pop
        
    def modeMenu(self):
        """ creates a new View Mode menu

        @return KPopupMenu instance
        """
        pop = self.modePopup = Popup(self)
        ids = self.modePopupIds = {}
        for value, label in PluginFrame.modePages:
            modeid = ids[value] = pop.insertItem(i18n(label))
            pop.setItemParameter(modeid, value)
            pop.connectItem(modeid, self, Signals.viewModeChanged)
        return pop

    def iconSizeMenu(self):
        """ creates a new View Icon Size menu

        @return KPopupMenu instance
        """
        pop = self.iconSizePopup = Popup(self)
        ids = self.iconSizePopupIds = {}
        for size, label in iconSizes():
            sizeid = ids[size] = pop.insertItem(i18n(label))
            pop.setItemParameter(sizeid, size)
            pop.connectItem(sizeid, self, Signals.iconSizeChanged)
        pop.setItemChecked(sizeid, True)
        return pop

    def queryClose(self):
        """ abuse the queryClose method because other close methods are goofy

        This method may grow in the future to prompt the user for
        unsaved changes.
        
        @return True
        """
        if not self.sender():
            self.hide()
            return False
        if not self.contentFrame.queryClose():
            return False
        self.saveMainWindowSettings(self.config())
        self.saveWindowSize(self.config('mainwindow'))
        config = self.config('mainview')
        config.writeEntry('iconsize', self.iconSize)
        config.writeEntry('viewmode', self.viewMode)
        actions = self.actionCollection()
        actions.writeShortcutSettings('shortcuts', config)
        return True

    def onClearSearch(self):
        """ clears the search input, emits signal to set view mode

        @return None
        """
        self.inputSearch.clear()
        self.emit(Signals.viewModeChanged, (self.viewMode, ))

    def onConfigKeys(self):
        """ displays the kde shortcut key config dialog for our actions

        @return None
        """
        KKeyDialog.configure(self.actionCollection(), self)

    def onContextChanged(self):
        """ writes the beryl context and sends a reload message

        @return None
        """
        self.context.write()

    def onIconSize(self, value):
        """ changes the View Icon Size menu

        @param value new icon size
        @return None
        """
        self.iconSize = value
        for size, menuid in self.iconSizePopupIds.items():
            self.iconSizePopup.setItemChecked(menuid, size==value)

    def onInputSearch(self, value):
        """ emits signal to change view mode and signal to search for text

        """
        self.emit(Signals.searchInput, (value, ))
        self.emit(Signals.viewModeChanged, (PluginFrame.searchPageId, ))

    def onIntro(self):
        """ emits signal to show the introduction

        """
        self.emit(Signals.showAbout, (self.context, None))        

    def onPluginDialogOk(self):
        """ enables and disables plugins when plugin dialog accepted

        @return None
        """
        items = self.pluginDialogItems
        context = self.context
        for p in context.plugins:
            enable = items.get(p.Name, None)
            if enable is None:
                continue
            ## wtf? the extension raises and exception when we blindly
            ## set the enabled property.
            if (enable and not p.Enabled) or (not enable and p.Enabled):
                p.enabled = enable
            self.emit(Signals.berylPluginEnabled, (p, p.Enabled))
        self.emit(Signals.berylContextChanged, (context, ))

    def onProfileSelect(self, itemId):
        """ sets current profile

        @param itemId profile popup menu item id
        @return None
        """
        self.context.Profile = self.profileMap[itemId]
        self.emit(Signals.berylContextChanged, (self.context, ))
        
    def onSelectPlugins(self):
        """ shows dialog to enable/disable plugins

        @return None
        """
        self.pluginDialogItems = {}
        dialog =  PluginDialog(self, self.context, self.pluginDialogItems)
        self.connect(dialog, Signals.okClicked, self.onPluginDialogOk)
        dialog.exec_loop()

    def onMode(self, value):
        """ changes the View Mode menu, enables/disables Icon Size menu items

        @param value new view mode
        @return None
        """
        if value in PluginFrame.transitoryModes:
            return
        self.viewMode = value
        iconMode = value in PluginFrame.iconSizeModes
        for menuid in self.iconSizePopupIds.values():
            self.iconSizePopup.setItemEnabled(menuid, iconMode)
        for mode, menuid in self.modePopupIds.items():
            self.modePopup.setItemChecked(menuid, mode==value)
            
    def onImport(self):
        """ shows dialog to select profile for import

        @return None
        """
        filename = KFileDialog.getOpenFileName(self.startDir, '', None,
                                               'Select Profile to Import')
        if filename:
            self.context.Import(filename, True) # overwrite
            self.emit(Signals.berylContextChanged, (self.context, ))
            self.showMessage('Settings imported.')

    def onExport(self):
        """ shows dialog to select filename for profile export

        @return None
        """
        filename = KFileDialog.getSaveFileName(self.startDir, '', None,
                                               'Select File to Export Profile')
        if filename:
            print 'exporting file...', filename

    def onMenuBar(self):
        """ toggle the visibility of the menu bar and the related menu text

        """
        menuBar = self.menuBar()
        if menuBar.isVisible():
            menuBar.hide()
            self.toggleMenuBarAction.setText('Show menubar')
        else:
            menuBar.show()
            self.toggleMenuBarAction.setText('Hide menubar')            

    def onStatusBar(self):
        """ toggle the visibility of the menu bar and the related menu text        

        """
        statusBar = self.statusBar()
        if statusBar.isVisible():
            statusBar.hide()
            self.toggleStatusBarAction.setText('Show statusbar')
        else:
            statusBar.show()
            self.toggleStatusBarAction.setText('Hide statusbar')            
            
    def showMessage(self, text):
        """ show a message in the status bar

        @param text value to show
        @return None
        """
        self.statusBar().message(text, 3000)

    def tipDialog(self, force=True):
        """ show a KTipDialog

        @keyparam force=True if true, forces dialog display.  default
        is True for easy connection to the menu entry.
        @return None
        """
        KTipDialog.showTip(self, locate('data', 'tips'), force)


def iconSizes():
    """ creates list of KIcon sizes and their names

    @return sequence of two-tuples in the form of (size, name)
    """
    def sizeOk(attr):
        return attr.startswith('Size') and attr != 'SizeSmallMedium'
    names = [name for name in dir(KIcon) if sizeOk(name)]
    sizes = [getattr(KIcon, name) for name in names]
    names = [name.replace('Size', '') for name in names]
    sizenames = zip(sizes, names)
    sizenames.sort()
    return sizenames


def main():
    """ runs the KBerylSettings window with a KApplication

    @return None
    """
    aboutdata = about()
    KCmdLineArgs.init(argv, aboutdata)
    app = KApplication()
    dirs = app.dirs()
    basedir = abspath(dirname(__file__))    
    dirs.addResourceDir('data', basedir)
    dirs.addResourceDir('templates', basedir + '/html')    
    dirs.addResourceDir('icon', basedir + '/pixmaps')
    aboutdata.setProgramLogo(QImage(locate('icon', 'kberylsettings.png')))
    obj = KBerylSettings()    
    obj.show()
    app.exec_loop()


if __name__ == '__main__':
    main()