aboutsummaryrefslogtreecommitdiff
path: root/ayatana-settings
blob: 3ee11a2c5b3972a2ff25982286aa0c4bd90150b7 (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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

try:

    import devpath
    from ayatanasettings.appdata import APPDEBUG
    APPDEBUG.append(True)

except:

    pass

import gi

gi.require_version('Gtk', '3.0')

from gi.repository import Gtk, Gio
from ayatanasettings.appdata import APPNAME
from ayatanasettings.logger import logger
from ayatanasettings.psutil import isRunning, isSystemd
from ayatanasettings.builder import buildApp
import configparser
import gettext
import os
import pathlib
import shutil
import subprocess

m_pTranslation = None

try:
    m_pTranslation = gettext.translation(APPNAME)
except IOError:
    m_pTranslation = gettext.NullTranslations()

m_pTranslation.install()

class AyatanaSettings:

    def __init__(self):

        if isRunning():

            sys.exit(1)

        buildApp(self)
        pSource = Gio.SettingsSchemaSource.get_default ()
        pSchema = pSource.lookup ('org.gnome.desktop.interface', False);

        if pSchema:

            bFound = pSchema.has_key ('color-scheme')

            if bFound:

                self.pGnomeSettings = Gio.Settings.new ('org.gnome.desktop.interface')
                self.pGnomeSettings.connect ('changed::color-scheme', self.onColorSchemeChanged)
                self.onColorSchemeChanged (self.pGnomeSettings, 'color-scheme')

        self.bSystemd = isSystemd()
        self.bInit = False

        try:
            self.sDesktop = os.environ['XDG_CURRENT_DESKTOP']
        except KeyError:
            self.sDesktop = ""

        # Session
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.session', False):

            self.pSettingsSession = Gio.Settings.new('org.ayatana.indicator.session')
            self.pSettingsSession.bind('show-real-name-on-panel', self.pSwitchSessionShowName, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsSession.bind('suppress-logout-menuitem', self.pSwitchSessionRemoveLogOut, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsSession.bind('suppress-logout-restart-shutdown', self.pSwitchSessionSuppressConfirmation, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsSession.bind('suppress-restart-menuitem', self.pSwitchSessionRemoveRestart, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsSession.bind('suppress-shutdown-menuitem', self.pSwitchSessionRemoveShutDown, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsSession.bind('user-show-menu', self.pSwitchSessionShowUsers, 'active', Gio.SettingsBindFlags.DEFAULT)
            bEnabled = self.isEnabled('session')
            self.pCheckButtonSessionEnable.set_active(bEnabled)

        else:

            self.pLabelSession.set_sensitive(False)

        # Date/Time
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.datetime', False):

            self.pSettingsDateTime = Gio.Settings.new('org.ayatana.indicator.datetime')
            self.pSettingsDateTime.bind('show-calendar', self.pSwitchDatetimeShowCalendar, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-date', self.pSwitchDatetimeShowDate, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-day', self.pSwitchDatetimeShowDay, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-events', self.pSwitchDatetimeShowEvents, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-seconds', self.pSwitchDatetimeShowSeconds, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-week-numbers', self.pSwitchDatetimeShowWeekNumbers, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsDateTime.bind('show-year', self.pSwitchDatetimeShowYear, 'active', Gio.SettingsBindFlags.DEFAULT)
            bEnabled = self.isEnabled('datetime')
            self.pCheckButtonDatetimeEnable.set_active(bEnabled)

        else:

            self.pLabelDatetime.set_sensitive(False)

        # Sound
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.sound', False):

            self.pSettingsSound = Gio.Settings.new('org.ayatana.indicator.sound')
            self.pSettingsSound.bind('allow-amplified-volume', self.pSwitchSoundAllowAmplified, 'active', Gio.SettingsBindFlags.DEFAULT)
            bEnabled = self.isEnabled('sound')
            self.pCheckButtonSoundEnable.set_active(bEnabled)

        else:

            self.pLabelSound.set_sensitive(False)

        # Power
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.power', False):

            self.pSettingsPower = Gio.Settings.new('org.ayatana.indicator.power')
            self.pSettingsPower.bind('show-percentage', self.pSwitchPowerShowPercentage, 'active', Gio.SettingsBindFlags.DEFAULT)
            self.pSettingsPower.bind('show-time', self.pSwitchPowerShowTime, 'active', Gio.SettingsBindFlags.DEFAULT)
            bEnabled = self.isEnabled('power')
            self.pCheckButtonPowerEnable.set_active(bEnabled)

        else:

            self.pLabelPower.set_sensitive(False)

        # Messages
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.messages', False):

            bEnabled = self.isEnabled('messages')
            self.pCheckButtonMessagesEnable.set_active(bEnabled)

        else:

            self.pLabelMessages.set_sensitive(False)

        # Bluetooth
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.bluetooth', False):

            bEnabled = self.isEnabled('bluetooth')
            self.pCheckButtonBluetoothEnable.set_active(bEnabled)

        else:

            self.pLabelBluetooth.set_sensitive(False)

        # Notifications
        if Gio.SettingsSchemaSource.get_default().lookup('org.ayatana.indicator.notifications', False):

            self.pSettingsNotifications = Gio.Settings.new('org.ayatana.indicator.notifications')
            nMaxItems = self.pSettingsNotifications.get_int('max-items')
            self.pSpinButtonNotifications.set_value(nMaxItems)

            for sFilter in self.pSettingsNotifications.get_strv('filter-list'):

                self.pListStoreNotificationsFilters.append([sFilter]);

            for sHint in self.pSettingsNotifications.get_strv('filter-list-hints'):

                self.pListStoreNotificationsHints.append([sHint]);

            self.pEntryCompletionNotifications = Gtk.EntryCompletion()
            self.pEntryCompletionNotifications.set_model(self.pListStoreNotificationsHints)
            self.pEntryCompletionNotifications.set_text_column(0)
            self.pEntryCompletionNotifications.set_minimum_key_length(0)
            self.pEntryNotifications.set_completion(self.pEntryCompletionNotifications)
            bEnabled = self.isEnabled('notifications')
            self.pCheckButtonNotificationsEnable.set_active(bEnabled)

        else:

            self.pLabelNotifications.set_sensitive(False)

        # Keyboard
        if pathlib.Path('/etc/xdg/autostart/ayatana-indicator-keyboard.desktop').exists():

            bEnabled = self.isEnabled('keyboard')
            self.pCheckButtonKeyboardEnable.set_active(bEnabled)

        else:

            self.pLabelKeyboard.set_sensitive(False)

        self.bInit = True

        Gtk.main()

    def isEnabled(self, sIndicator):

        bEnabled = True

        '''
        TODO: Fix systemd autostart first
        if self.bSystemd:

            bEnabled = subprocess.Popen('systemctl --user is-enabled ayatana-indicator-{}'.format(sIndicator), stdout = subprocess.PIPE, shell = True).communicate()[0].decode().strip() == 'enabled'

        else:
        '''

        sPath = '~/.config/autostart/ayatana-indicator-{}.desktop'.format(sIndicator)
        pPath = pathlib.Path(sPath).expanduser()

        if pPath.exists():

            pFile = pPath.open('r')
            pParser = configparser.ConfigParser()
            pParser.read_file(pFile)

            if 'X-MATE-Autostart-enabled' in pParser['Desktop Entry']:

                bEnabled = (pParser['Desktop Entry']['X-MATE-Autostart-enabled'] != 'false')

            elif 'X-GNOME-Autostart-enabled' in pParser['Desktop Entry']:

                bEnabled = (pParser['Desktop Entry']['X-GNOME-Autostart-enabled'] != 'false')

            pFile.close()

        return bEnabled

    def onCheckButtonEnableToggled(self, pCheckButton):

        if not self.bInit:

            return

        sIndicator = pCheckButton.get_name()

        '''
        TODO: Fix systemd autostart first
        if self.bSystemd:

            sAction = 'enable' if pCheckButton.get_active() else 'disable'
            subprocess.Popen('systemctl --quiet --user {} ayatana-indicator-{}'.format(sAction, sIndicator), stdout = subprocess.PIPE, shell = True).communicate()

        else:
        '''

        sAutostartFolder = '~/.config/autostart'
        pAutostartFolder = pathlib.Path(sAutostartFolder).expanduser()
        if not pAutostartFolder.exists():
            pAutostartFolder.mkdir(parents=True)

        sPath = '{autostart}/ayatana-indicator-{indicator}.desktop'.format(autostart=sAutostartFolder, indicator=sIndicator)
        pPath = pathlib.Path(sPath).expanduser()

        if not pPath.exists():

            sPathIn = '/etc/xdg/autostart/ayatana-indicator-{}.desktop'.format(sIndicator)
            shutil.copy(sPathIn, pPath)

        pFile = pPath.open('r+')
        pParser = configparser.ConfigParser()
        pParser.optionxform = str
        pParser.read_file(pFile)
        sEnabled = 'true' if pCheckButton.get_active() else 'false'

        if self.sDesktop == 'MATE':

            pParser['Desktop Entry']['X-MATE-Autostart-enabled'] = sEnabled

        else:

            pParser['Desktop Entry']['X-GNOME-Autostart-enabled'] = sEnabled

        pFile.seek(0)
        pParser.write(pFile, False)
        pFile.truncate()
        pFile.close()

    def onWindowDestroy(self, pWidget, pData = None):

        Gtk.main_quit()

    def onSpinButtonNotificationsValueChanged(self, pSpinButton):

        nValue = pSpinButton.get_value_as_int()
        self.pSettingsNotifications.set_int('max-items', nValue)

    def onSpinButtonNotificationsChanged(self, pSpinButton):

        sText = pSpinButton.get_text()

        if not sText:

            return

        nNum = int(sText)
        nNum = max(1, nNum)
        nNum = min(nNum, 10)

        if str(nNum) != sText:

            pSpinButton.set_text(str(nNum))

    def onButtonNotificationsAddClicked(self, pButton):

        sText = self.pEntryNotifications.get_text().strip()

        if sText:

            bDuplicate = False;

            for pRow in self.pListStoreNotificationsFilters:

                if pRow[0] == sText:

                    bDuplicate = True

                    break

            if not bDuplicate:

                self.pListStoreNotificationsFilters.append([sText])
                self.saveFilterList()

        self.pEntryNotifications.set_text('')

    def onButtonNotificationsRemoveClicked(self, pButton):

        pSelection = self.pTreeViewNotifications.get_selection()
        pIter = pSelection.get_selected()[1]

        if pIter is not None:

            self.pListStoreNotificationsFilters.remove(pIter)
            self.saveFilterList()

    def onEntryNotificationsFocusInEvent(self, pEntry, pEvent):

        self.pListStoreNotificationsHints.clear()

        for sHint in self.pSettingsNotifications.get_strv('filter-list-hints'):

            self.pListStoreNotificationsHints.append([sHint])

        pEntry.emit('changed')

        return False

    def saveFilterList(self):

        lItems = []

        for lRow in self.pListStoreNotificationsFilters:

            lItems.append(lRow[0])

        self.pSettingsNotifications.set_strv('filter-list', lItems)

    def onColorSchemeChanged (self, pSettings, sKey):

        sColorScheme = pSettings.get_string (sKey)
        bDark = (sColorScheme == 'prefer-dark')
        Gtk.Settings.get_default().props.gtk_application_prefer_dark_theme = bDark

if __name__ == "__main__":

    AyatanaSettings()