css_config.py 18.7 KB
Newer Older
Philipp Hörist's avatar
Philipp Hörist committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Copyright (C) 2018 Philipp Hörist <philipp AT hoerist.com>
#
# This file is part of Gajim.
#
# Gajim is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Gajim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.

import math
import logging

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Pango
24
import css_parser
Philipp Hörist's avatar
Philipp Hörist committed
25
26
27
28
29

from gajim.common import app
from gajim.common import configpaths
from gajim.common.const import StyleAttr, CSSPriority

Philipp Hörist's avatar
Philipp Hörist committed
30
from .const import Theme
Philipp Hörist's avatar
Philipp Hörist committed
31

Philipp Hörist's avatar
Philipp Hörist committed
32
log = logging.getLogger('gajim.gui.css')
Philipp Hörist's avatar
Philipp Hörist committed
33
settings = Gtk.Settings.get_default()
Philipp Hörist's avatar
Philipp Hörist committed
34
35
36
37


class CSSConfig():
    def __init__(self):
Philipp Hörist's avatar
Philipp Hörist committed
38
39
        """
        CSSConfig handles loading and storing of all relevant Gajim style files
Philipp Hörist's avatar
Philipp Hörist committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53

        The order in which CSSConfig loads the styles

        1. gajim.css
        2. gajim-dark.css (Only if gtk-application-prefer-dark-theme = True)
        3. default.css or default-dark.css (from gajim/data/style)
        4. user-theme.css (from ~/.config/Gajim/theme)

        # gajim.css:

        This is the main style and the application default

        # gajim-dark.css

54
        Has only entries which we want to override in gajim.css
Philipp Hörist's avatar
Philipp Hörist committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68

        # default.css or default-dark.css

        Has all the values that are changeable via UI (see themes.py).
        Depending on `gtk-application-prefer-dark-theme` either default.css or
        default-dark.css gets loaded

        # user-theme.css

        These are the themes the Themes Dialog stores. Because they are
        loaded at last they overwrite everything else. Users should add custom
        css here."""

        # Delete empty rules
69
        css_parser.ser.prefs.keepEmptyRules = False
Philipp Hörist's avatar
Philipp Hörist committed
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

        # Holds the currently selected theme in the Theme Editor
        self._pre_css = None
        self._pre_css_path = None

        # Holds the default theme, its used if values are not found
        # in the selected theme
        self._default_css = None
        self._default_css_path = None

        # Holds the currently selected theme
        self._css = None
        self._css_path = None

        # User Theme CSS Provider
        self._provider = Gtk.CssProvider()

87
88
89
90
91
92
93
94
95
96
        # Used for dynamic classes like account colors
        self._dynamic_provider = Gtk.CssProvider()
        self._dynamic_dict = {}
        self.refresh()

        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            self._dynamic_provider,
            CSSPriority.APPLICATION)

Philipp Hörist's avatar
Philipp Hörist committed
97
98
99
100
101
102
        # Cache of recently requested values
        self._cache = {}

        # Holds all currently available themes
        self.themes = []

Philipp Hörist's avatar
Philipp Hörist committed
103
        self.set_dark_theme()
Philipp Hörist's avatar
Philipp Hörist committed
104
105
106
107
108
        self._load_css()
        self._gather_available_themes()
        self._load_default()
        self._load_selected()
        self._activate_theme()
109

Philipp Hörist's avatar
Philipp Hörist committed
110
111
112
113
114
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            self._provider,
            CSSPriority.USER_THEME)

Philipp Hörist's avatar
Philipp Hörist committed
115
116
    @property
    def prefer_dark(self):
Philipp Hörist's avatar
Philipp Hörist committed
117
        setting = app.settings.get('dark_theme')
Philipp Hörist's avatar
Philipp Hörist committed
118
119
120
121
122
123
        if setting == Theme.SYSTEM:
            if settings is None:
                return False
            return settings.get_property('gtk-application-prefer-dark-theme')
        return setting == Theme.DARK

124
    def set_dark_theme(self, value=None):
Philipp Hörist's avatar
Philipp Hörist committed
125
        if value is None:
Philipp Hörist's avatar
Philipp Hörist committed
126
            value = app.settings.get('dark_theme')
Philipp Hörist's avatar
Philipp Hörist committed
127
        else:
Philipp Hörist's avatar
Philipp Hörist committed
128
            app.settings.set('dark_theme', value)
Philipp Hörist's avatar
Philipp Hörist committed
129
130
131
132
133
134
135

        if settings is None:
            return
        if value == Theme.SYSTEM:
            settings.reset_property('gtk-application-prefer-dark-theme')
            return
        settings.set_property('gtk-application-prefer-dark-theme', bool(value))
136
        self._load_css()
Philipp Hörist's avatar
Philipp Hörist committed
137

Philipp Hörist's avatar
Philipp Hörist committed
138
139
    def _load_css(self):
        self._load_css_from_file('gajim.css', CSSPriority.APPLICATION)
Philipp Hörist's avatar
Philipp Hörist committed
140
        if self.prefer_dark:
Philipp Hörist's avatar
Philipp Hörist committed
141
142
143
144
            self._load_css_from_file('gajim-dark.css',
                                     CSSPriority.APPLICATION_DARK)

        self._load_css_from_file('default.css', CSSPriority.DEFAULT_THEME)
Philipp Hörist's avatar
Philipp Hörist committed
145
        if self.prefer_dark:
Philipp Hörist's avatar
Philipp Hörist committed
146
147
148
149
            self._load_css_from_file('default-dark.css',
                                     CSSPriority.DEFAULT_THEME_DARK)

    def _load_css_from_file(self, filename, priority):
André's avatar
André committed
150
        path = configpaths.get('STYLE') / filename
Philipp Hörist's avatar
Philipp Hörist committed
151
        try:
Philipp Hörist's avatar
Philipp Hörist committed
152
153
            with open(path, "r") as file_:
                css = file_.read()
Philipp Hörist's avatar
Philipp Hörist committed
154
155
156
157
158
        except Exception as exc:
            log.error('Error loading css: %s', exc)
            return
        self._activate_css(css, priority)

159
    def _activate_css(self, css, priority):
Philipp Hörist's avatar
Philipp Hörist committed
160
161
162
163
164
165
        try:
            provider = Gtk.CssProvider()
            provider.load_from_data(bytes(css.encode('utf-8')))
            Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
                                                     provider,
                                                     priority)
166
167
168
            self._load_selected()
            self._activate_theme()

Philipp Hörist's avatar
Philipp Hörist committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        except Exception:
            log.exception('Error loading application css')

    @staticmethod
    def _pango_to_css_weight(number):
        # Pango allows for weight values between 100 and 1000
        # CSS allows only full hundred numbers like 100, 200 ..
        number = int(number)
        if number < 100:
            return 100
        if number > 900:
            return 900
        return int(math.ceil(number / 100.0)) * 100

    def _gather_available_themes(self):
André's avatar
André committed
184
        files = configpaths.get('MY_THEME').iterdir()
André's avatar
André committed
185
        self.themes = [file.stem for file in files if file.suffix == '.css']
Philipp Hörist's avatar
Philipp Hörist committed
186
187
188
189
        if 'default' in self.themes:
            # Ignore user created themes that are named 'default'
            self.themes.remove('default')

Philipp Hörist's avatar
Philipp Hörist committed
190
191
    def get_theme_path(self, theme, user=True):
        if theme == 'default' and self.prefer_dark:
Philipp Hörist's avatar
Philipp Hörist committed
192
193
194
            theme = 'default-dark'

        if user:
André's avatar
André committed
195
196
            return configpaths.get('MY_THEME') / f'{theme}.css'
        return configpaths.get('STYLE') / f'{theme}.css'
Philipp Hörist's avatar
Philipp Hörist committed
197
198
199
200

    def _determine_theme_path(self):
        # Gets the path of the currently active theme.
        # If it does not exist, it falls back to the default theme
Philipp Hörist's avatar
Philipp Hörist committed
201
        theme = app.settings.get('roster_theme')
Philipp Hörist's avatar
Philipp Hörist committed
202
203
204
205
        if theme == 'default':
            return self.get_theme_path(theme, user=False)

        theme_path = self.get_theme_path(theme)
André's avatar
André committed
206
        if not theme or not theme_path.exists():
Philipp Hörist's avatar
Philipp Hörist committed
207
            log.warning('Theme %s not found, fallback to default', theme)
Philipp Hörist's avatar
Philipp Hörist committed
208
            app.settings.set('roster_theme', 'default')
Philipp Hörist's avatar
Philipp Hörist committed
209
210
211
212
213
214
215
216
217
218
            log.info('Use Theme: default')
            return self.get_theme_path('default', user=False)
        log.info('Use Theme: %s', theme)
        return theme_path

    def _load_selected(self, new_path=None):
        if new_path is None:
            self._css_path = self._determine_theme_path()
        else:
            self._css_path = new_path
219
        self._css = css_parser.parseFile(self._css_path)
Philipp Hörist's avatar
Philipp Hörist committed
220
221
222

    def _load_default(self):
        self._default_css_path = self.get_theme_path('default', user=False)
223
        self._default_css = css_parser.parseFile(self._default_css_path)
Philipp Hörist's avatar
Philipp Hörist committed
224
225
226
227

    def _load_pre(self, theme):
        log.info('Preload theme %s', theme)
        self._pre_css_path = self.get_theme_path(theme)
228
        self._pre_css = css_parser.parseFile(self._pre_css_path)
Philipp Hörist's avatar
Philipp Hörist committed
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

    def _write(self, pre):
        path = self._css_path
        css = self._css
        if pre:
            path = self._pre_css_path
            css = self._pre_css
        with open(path, 'w', encoding='utf-8') as file:
            file.write(css.cssText.decode('utf-8'))

        active = self._pre_css_path == self._css_path
        if not pre or active:
            self._load_selected()
            self._activate_theme()

    def set_value(self, selector, attr, value, pre=False):
        if attr == StyleAttr.FONT:
            # forward to set_font() for convenience
            return self.set_font(selector, value, pre)

        if isinstance(attr, StyleAttr):
            attr = attr.value

        css = self._css
        if pre:
            css = self._pre_css
        for rule in css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Set %s %s %s', selector, attr, value)
                rule.style[attr] = value
                if not pre:
                    self._add_to_cache(selector, attr, value)
                self._write(pre)
Philipp Hörist's avatar
Philipp Hörist committed
264
                return None
Philipp Hörist's avatar
Philipp Hörist committed
265
266
267

        # The rule was not found, so we add it to this theme
        log.info('Set %s %s %s', selector, attr, value)
268
        rule = css_parser.css.CSSStyleRule(selectorText=selector)
Philipp Hörist's avatar
Philipp Hörist committed
269
270
271
        rule.style[attr] = value
        css.add(rule)
        self._write(pre)
Philipp Hörist's avatar
Philipp Hörist committed
272
        return None
Philipp Hörist's avatar
Philipp Hörist committed
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

    def set_font(self, selector, description, pre=False):
        css = self._css
        if pre:
            css = self._pre_css
        family, size, style, weight = self._get_attr_from_description(
            description)
        for rule in css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Set Font for: %s %s %s %s %s',
                         selector, family, size, style, weight)
                rule.style['font-family'] = family
                rule.style['font-style'] = style
                rule.style['font-size'] = '%spt' % size
                rule.style['font-weight'] = weight

                if not pre:
                    self._add_to_cache(
                        selector, 'fontdescription', description)
                self._write(pre)
                return

        # The rule was not found, so we add it to this theme
        log.info('Set Font for: %s %s %s %s %s',
                 selector, family, size, style, weight)
300
        rule = css_parser.css.CSSStyleRule(selectorText=selector)
Philipp Hörist's avatar
Philipp Hörist committed
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        rule.style['font-family'] = family
        rule.style['font-style'] = style
        rule.style['font-size'] = '%spt' % size
        rule.style['font-weight'] = weight
        css.add(rule)
        self._write(pre)

    def _get_attr_from_description(self, description):
        size = description.get_size() / Pango.SCALE
        style = self._get_string_from_pango_style(description.get_style())
        weight = self._pango_to_css_weight(int(description.get_weight()))
        family = description.get_family()
        return family, size, style, weight

Philipp Hörist's avatar
Philipp Hörist committed
315
    def _get_default_rule(self, selector, _attr):
Philipp Hörist's avatar
Philipp Hörist committed
316
317
318
319
320
321
        for rule in self._default_css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Get Default Rule %s', selector)
                return rule
Philipp Hörist's avatar
Philipp Hörist committed
322
        return None
Philipp Hörist's avatar
Philipp Hörist committed
323
324
325
326
327
328
329
330
331
332
333
334

    def get_font(self, selector, pre=False):
        if pre:
            css = self._pre_css
        else:
            css = self._css
            try:
                return self._get_from_cache(selector, 'fontdescription')
            except KeyError:
                pass

        if css is None:
Philipp Hörist's avatar
Philipp Hörist committed
335
            return None
Philipp Hörist's avatar
Philipp Hörist committed
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352

        for rule in css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Get Font for: %s', selector)
                style = rule.style.getPropertyValue('font-style') or None
                size = rule.style.getPropertyValue('font-size') or None
                weight = rule.style.getPropertyValue('font-weight') or None
                family = rule.style.getPropertyValue('font-family') or None

                desc = self._get_description_from_css(
                    family, size, style, weight)
                if not pre:
                    self._add_to_cache(selector, 'fontdescription', desc)
                return desc

353
        self._add_to_cache(selector, 'fontdescription', None)
Philipp Hörist's avatar
Philipp Hörist committed
354
        return None
355

Philipp Hörist's avatar
Philipp Hörist committed
356
357
    def _get_description_from_css(self, family, size, style, weight):
        if family is None:
Philipp Hörist's avatar
Philipp Hörist committed
358
            return None
Philipp Hörist's avatar
Philipp Hörist committed
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
        desc = Pango.FontDescription()
        desc.set_family(family)
        if weight is not None:
            desc.set_weight(Pango.Weight(int(weight)))
        if style is not None:
            desc.set_style(self._get_pango_style_from_string(style))
        if size is not None:
            desc.set_size(int(size[:-2]) * Pango.SCALE)
        return desc

    @staticmethod
    def _get_pango_style_from_string(style: str) -> int:
        if style == 'normal':
            return Pango.Style(0)
        if style == 'oblique':
            return Pango.Style(1)
        # Pango.Style.ITALIC:
        return Pango.Style(2)

    @staticmethod
    def _get_string_from_pango_style(style: Pango.Style) -> str:
        if style == Pango.Style.NORMAL:
            return 'normal'
        if style == Pango.Style.ITALIC:
            return 'italic'
        # Pango.Style.OBLIQUE:
        return 'oblique'

    def get_value(self, selector, attr, pre=False):
        if attr == StyleAttr.FONT:
            # forward to get_font() for convenience
            return self.get_font(selector, pre)

        if isinstance(attr, StyleAttr):
            attr = attr.value

        if pre:
            css = self._pre_css
        else:
            css = self._css
            try:
                return self._get_from_cache(selector, attr)
            except KeyError:
                pass

        if css is not None:
            for rule in css:
                if rule.type != rule.STYLE_RULE:
                    continue
                if rule.selectorText == selector:
                    log.info('Get %s %s: %s',
                             selector, attr, rule.style[attr] or None)
                    value = rule.style.getPropertyValue(attr) or None
                    if not pre:
                        self._add_to_cache(selector, attr, value)
                    return value

Emmanuel Gil Peyrot's avatar
Emmanuel Gil Peyrot committed
416
        # We didn’t find the selector in the selected theme
Philipp Hörist's avatar
Philipp Hörist committed
417
418
419
        # search in default theme
        if not pre:
            rule = self._get_default_rule(selector, attr)
420
421
422
            value = rule if rule is None else rule.style[attr]
            self._add_to_cache(selector, attr, value)
            return value
Philipp Hörist's avatar
Philipp Hörist committed
423
        return None
Philipp Hörist's avatar
Philipp Hörist committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443

    def remove_value(self, selector, attr, pre=False):
        if attr == StyleAttr.FONT:
            # forward to remove_font() for convenience
            return self.remove_font(selector, pre)

        if isinstance(attr, StyleAttr):
            attr = attr.value

        css = self._css
        if pre:
            css = self._pre_css
        for rule in css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Remove %s %s', selector, attr)
                rule.style.removeProperty(attr)
                break
        self._write(pre)
Philipp Hörist's avatar
Philipp Hörist committed
444
        return None
Philipp Hörist's avatar
Philipp Hörist committed
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465

    def remove_font(self, selector, pre=False):
        css = self._css
        if pre:
            css = self._pre_css

        for rule in css:
            if rule.type != rule.STYLE_RULE:
                continue
            if rule.selectorText == selector:
                log.info('Remove Font from: %s', selector)
                rule.style.removeProperty('font-family')
                rule.style.removeProperty('font-size')
                rule.style.removeProperty('font-style')
                rule.style.removeProperty('font-weight')
                break
        self._write(pre)

    def change_theme(self, theme):
        user = not theme == 'default'
        theme_path = self.get_theme_path(theme, user=user)
André's avatar
André committed
466
        if not theme_path.exists():
Philipp Hörist's avatar
Philipp Hörist committed
467
468
469
470
            log.error('Change Theme: Theme %s does not exist', theme_path)
            return False
        self._load_selected(theme_path)
        self._activate_theme()
Philipp Hörist's avatar
Philipp Hörist committed
471
        app.settings.set('roster_theme', theme)
Philipp Hörist's avatar
Philipp Hörist committed
472
473
474
475
476
        log.info('Change Theme: Successful switched to %s', theme)
        return True

    def change_preload_theme(self, theme):
        theme_path = self.get_theme_path(theme)
André's avatar
André committed
477
        if not theme_path.exists():
Philipp Hörist's avatar
Philipp Hörist committed
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
            log.error('Change Preload Theme: Theme %s does not exist',
                      theme_path)
            return False
        self._load_pre(theme)
        log.info('Successful switched to %s', theme)
        return True

    def rename_theme(self, old_theme, new_theme):
        if old_theme not in self.themes:
            log.error('Rename Theme: Old theme %s not found', old_theme)
            return False

        if new_theme in self.themes:
            log.error('Rename Theme: New theme %s exists already', new_theme)
            return False

        old_theme_path = self.get_theme_path(old_theme)
        new_theme_path = self.get_theme_path(new_theme)
André's avatar
André committed
496
        old_theme_path.rename(new_theme_path)
Philipp Hörist's avatar
Philipp Hörist committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
        self.themes.remove(old_theme)
        self.themes.append(new_theme)
        self._load_pre(new_theme)
        log.info('Rename Theme: Successful renamed theme from %s to %s',
                 old_theme, new_theme)
        return True

    def _activate_theme(self):
        log.info('Activate theme')
        self._invalidate_cache()
        self._provider.load_from_data(self._css.cssText)

    def add_new_theme(self, theme):
        theme_path = self.get_theme_path(theme)
André's avatar
André committed
511
        if theme_path.exists():
Philipp Hörist's avatar
Philipp Hörist committed
512
513
514
515
516
517
518
519
520
521
            log.error('Add Theme: %s exists already', theme_path)
            return False
        with open(theme_path, 'w', encoding='utf8'):
            pass
        self.themes.append(theme)
        log.info('Add Theme: Successful added theme %s', theme)
        return True

    def remove_theme(self, theme):
        theme_path = self.get_theme_path(theme)
André's avatar
André committed
522
523
        if theme_path.exists():
            theme_path.unlink()
Philipp Hörist's avatar
Philipp Hörist committed
524
525
526
527
528
529
530
531
532
533
534
            self.themes.remove(theme)
        log.info('Remove Theme: Successful removed theme %s', theme)

    def _add_to_cache(self, selector, attr, value):
        self._cache[selector + attr] = value

    def _get_from_cache(self, selector, attr):
        return self._cache[selector + attr]

    def _invalidate_cache(self):
        self._cache = {}
535
536
537

    def refresh(self):
        css = ''
538
        accounts = app.settings.get_accounts()
539
        for index, account in enumerate(accounts):
540
            color = app.settings.get_account_setting(account, 'account_color')
541
            css_class = 'gajim_class_%s' % index
542
            css += '.%s { background-color: %s }\n' % (css_class, color)
543
544
545
546
547
548
            self._dynamic_dict[account] = css_class

        self._dynamic_provider.load_from_data(css.encode())

    def get_dynamic_class(self, name):
        return self._dynamic_dict[name]