config.py 10.0 KB
Newer Older
之一Yo's avatar
之一Yo 已提交
1 2 3 4
# coding:utf-8
import json
from enum import Enum
from pathlib import Path
5
from typing import List
之一Yo's avatar
之一Yo 已提交
6 7

import darkdetect
之一Yo's avatar
之一Yo 已提交
8
from PyQt5.QtCore import QObject, pyqtSignal
之一Yo's avatar
之一Yo 已提交
9
from PyQt5.QtGui import QColor
10
from PyQt5.QtWidgets import qApp
之一Yo's avatar
之一Yo 已提交
11 12 13 14

from .exception_handler import exceptionHandler


15 16 17 18 19 20 21 22
class Theme(Enum):
    """ Theme enumeration """

    LIGHT = "Light"
    DARK = "Dark"
    AUTO = "Auto"


之一Yo's avatar
之一Yo 已提交
23 24 25
class ConfigValidator:
    """ Config validator """

之一Yo's avatar
之一Yo 已提交
26
    def validate(self, value):
之一Yo's avatar
之一Yo 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
        """ Verify whether the value is legal """
        return True

    def correct(self, value):
        """ correct illegal value """
        return value


class RangeValidator(ConfigValidator):
    """ Range validator """

    def __init__(self, min, max):
        self.min = min
        self.max = max
        self.range = (min, max)

之一Yo's avatar
之一Yo 已提交
43
    def validate(self, value):
之一Yo's avatar
之一Yo 已提交
44 45 46 47 48 49 50 51 52
        return self.min <= value <= self.max

    def correct(self, value):
        return min(max(self.min, value), self.max)


class OptionsValidator(ConfigValidator):
    """ Options validator """

之一Yo's avatar
之一Yo 已提交
53
    def __init__(self, options):
之一Yo's avatar
之一Yo 已提交
54 55 56 57 58 59 60 61
        if not options:
            raise ValueError("The `options` can't be empty.")

        if isinstance(options, Enum):
            options = options._member_map_.values()

        self.options = list(options)

之一Yo's avatar
之一Yo 已提交
62
    def validate(self, value):
之一Yo's avatar
之一Yo 已提交
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
        return value in self.options

    def correct(self, value):
        return value if self.validate(value) else self.options[0]


class BoolValidator(OptionsValidator):
    """ Boolean validator """

    def __init__(self):
        super().__init__([True, False])


class FolderValidator(ConfigValidator):
    """ Folder validator """

之一Yo's avatar
之一Yo 已提交
79
    def validate(self, value):
之一Yo's avatar
之一Yo 已提交
80 81
        return Path(value).exists()

之一Yo's avatar
之一Yo 已提交
82
    def correct(self, value):
之一Yo's avatar
之一Yo 已提交
83 84 85 86 87 88 89 90
        path = Path(value)
        path.mkdir(exist_ok=True, parents=True)
        return str(path.absolute()).replace("\\", "/")


class FolderListValidator(ConfigValidator):
    """ Folder list validator """

之一Yo's avatar
之一Yo 已提交
91
    def validate(self, value):
之一Yo's avatar
之一Yo 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        return all(Path(i).exists() for i in value)

    def correct(self, value: List[str]):
        folders = []
        for folder in value:
            path = Path(folder)
            if path.exists():
                folders.append(str(path.absolute()).replace("\\", "/"))

        return folders


class ColorValidator(ConfigValidator):
    """ RGB color validator """

    def __init__(self, default):
        self.default = QColor(default)

之一Yo's avatar
之一Yo 已提交
110
    def validate(self, color):
之一Yo's avatar
之一Yo 已提交
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
        try:
            return QColor(color).isValid()
        except:
            return False

    def correct(self, value):
        return QColor(value) if self.validate(value) else self.default


class ConfigSerializer:
    """ Config serializer """

    def serialize(self, value):
        """ serialize config value """
        return value

    def deserialize(self, value):
        """ deserialize config from config file's value """
        return value


class EnumSerializer(ConfigSerializer):
    """ enumeration class serializer """

    def __init__(self, enumClass):
        self.enumClass = enumClass

之一Yo's avatar
之一Yo 已提交
138
    def serialize(self, value):
之一Yo's avatar
之一Yo 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        return value.value

    def deserialize(self, value):
        return self.enumClass(value)


class ColorSerializer(ConfigSerializer):
    """ QColor serializer """

    def serialize(self, value: QColor):
        return value.name()

    def deserialize(self, value):
        if isinstance(value, list):
            return QColor(*value)

        return QColor(value)


之一Yo's avatar
之一Yo 已提交
158
class ConfigItem(QObject):
之一Yo's avatar
之一Yo 已提交
159 160
    """ Config item """

之一Yo's avatar
之一Yo 已提交
161 162
    valueChanged = pyqtSignal(object)

之一Yo's avatar
之一Yo 已提交
163
    def __init__(self, group, name, default, validator=None, serializer=None, restart=False):
之一Yo's avatar
之一Yo 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        """
        Parameters
        ----------
        group: str
            config group name

        name: str
            config item name, can be empty

        default:
            default value

        options: list
            options value

        serializer: ConfigSerializer
            config serializer
之一Yo's avatar
之一Yo 已提交
181 182 183

        restart: bool
            whether to restart the application after updating value
之一Yo's avatar
之一Yo 已提交
184
        """
之一Yo's avatar
之一Yo 已提交
185
        super().__init__()
之一Yo's avatar
之一Yo 已提交
186 187 188 189 190 191
        self.group = group
        self.name = name
        self.validator = validator or ConfigValidator()
        self.serializer = serializer or ConfigSerializer()
        self.__value = default
        self.value = default
之一Yo's avatar
之一Yo 已提交
192
        self.restart = restart
193
        self.defaultValue = self.validator.correct(default)
之一Yo's avatar
之一Yo 已提交
194 195 196 197 198 199 200 201

    @property
    def value(self):
        """ get the value of config item """
        return self.__value

    @value.setter
    def value(self, v):
之一Yo's avatar
之一Yo 已提交
202 203 204 205 206
        v = self.validator.correct(v)
        ov = self.__value
        self.__value = v
        if ov != v:
            self.valueChanged.emit(v)
之一Yo's avatar
之一Yo 已提交
207 208 209 210 211 212

    @property
    def key(self):
        """ get the config key separated by `.` """
        return self.group+"."+self.name if self.name else self.group

之一Yo's avatar
之一Yo 已提交
213
    def __str__(self):
之一Yo's avatar
之一Yo 已提交
214 215
        return f'{self.__class__.__name__}[value={self.value}]'

之一Yo's avatar
之一Yo 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
    def serialize(self):
        return self.serializer.serialize(self.value)

    def deserializeFrom(self, value):
        self.value = self.serializer.deserialize(value)


class RangeConfigItem(ConfigItem):
    """ Config item of range """

    @property
    def range(self):
        """ get the available range of config """
        return self.validator.range

之一Yo's avatar
之一Yo 已提交
231
    def __str__(self):
之一Yo's avatar
之一Yo 已提交
232 233
        return f'{self.__class__.__name__}[range={self.range}, value={self.value}]'

之一Yo's avatar
之一Yo 已提交
234 235 236 237 238 239 240 241

class OptionsConfigItem(ConfigItem):
    """ Config item with options """

    @property
    def options(self):
        return self.validator.options

之一Yo's avatar
之一Yo 已提交
242
    def __str__(self):
之一Yo's avatar
之一Yo 已提交
243 244
        return f'{self.__class__.__name__}[options={self.options}, value={self.value}]'

之一Yo's avatar
之一Yo 已提交
245 246 247 248

class ColorConfigItem(ConfigItem):
    """ Color config item """

之一Yo's avatar
之一Yo 已提交
249
    def __init__(self, group, name, default, restart=False):
之一Yo's avatar
之一Yo 已提交
250 251 252
        super().__init__(group, name, QColor(default), ColorValidator(default),
                         ColorSerializer(), restart)

之一Yo's avatar
之一Yo 已提交
253
    def __str__(self):
之一Yo's avatar
之一Yo 已提交
254
        return f'{self.__class__.__name__}[value={self.value.name()}]'
之一Yo's avatar
之一Yo 已提交
255 256


之一Yo's avatar
之一Yo 已提交
257
class QConfig(QObject):
之一Yo's avatar
之一Yo 已提交
258 259
    """ Config of app """

之一Yo's avatar
之一Yo 已提交
260
    appRestartSig = pyqtSignal()
261
    themeChanged = pyqtSignal(Theme)
之一Yo's avatar
之一Yo 已提交
262
    themeColorChanged = pyqtSignal(QColor)
之一Yo's avatar
之一Yo 已提交
263 264

    themeMode = OptionsConfigItem(
265
        "QFluentWidgets", "ThemeMode", Theme.AUTO, OptionsValidator(Theme), EnumSerializer(Theme))
之一Yo's avatar
之一Yo 已提交
266
    themeColor = ColorConfigItem("QFluentWidgets", "ThemeColor", '#009faa')
之一Yo's avatar
之一Yo 已提交
267 268

    def __init__(self):
之一Yo's avatar
之一Yo 已提交
269 270
        super().__init__()
        self.file = Path("config/config.json")
271
        self._theme = Theme.LIGHT
之一Yo's avatar
之一Yo 已提交
272
        self._cfg = self
之一Yo's avatar
之一Yo 已提交
273

之一Yo's avatar
之一Yo 已提交
274 275
    def get(self, item):
        """ get the value of config item """
之一Yo's avatar
之一Yo 已提交
276 277
        return item.value

278
    def set(self, item, value, save=True):
之一Yo's avatar
之一Yo 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291
        """ set the value of config item

        Parameters
        ----------
        item: ConfigItem
            config item

        value:
            the new value of config item

        save: bool
            whether to save the change to config file
        """
之一Yo's avatar
之一Yo 已提交
292 293 294 295
        if item.value == value:
            return

        item.value = value
296 297 298

        if save:
            self.save()
之一Yo's avatar
之一Yo 已提交
299 300 301

        if item.restart:
            self._cfg.appRestartSig.emit()
之一Yo's avatar
之一Yo 已提交
302

303
        if item is self._cfg.themeMode:
304
            self.theme = value
305 306
            self._cfg.themeChanged.emit(value)

之一Yo's avatar
之一Yo 已提交
307 308 309
        if item is self._cfg.themeColor:
            self._cfg.themeColorChanged.emit(value)

之一Yo's avatar
之一Yo 已提交
310
    def toDict(self, serialize=True):
之一Yo's avatar
之一Yo 已提交
311 312
        """ convert config items to `dict` """
        items = {}
之一Yo's avatar
之一Yo 已提交
313 314
        for name in dir(self._cfg.__class__):
            item = getattr(self._cfg.__class__, name)
之一Yo's avatar
之一Yo 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
            if not isinstance(item, ConfigItem):
                continue

            value = item.serialize() if serialize else item.value
            if not items.get(item.group):
                if not item.name:
                    items[item.group] = value
                else:
                    items[item.group] = {}

            if item.name:
                items[item.group][item.name] = value

        return items

之一Yo's avatar
之一Yo 已提交
330
    def save(self):
331
        """ save config """
之一Yo's avatar
之一Yo 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        self._cfg.file.parent.mkdir(parents=True, exist_ok=True)
        with open(self._cfg.file, "w", encoding="utf-8") as f:
            json.dump(self._cfg.toDict(), f, ensure_ascii=False, indent=4)

    @exceptionHandler()
    def load(self, file=None, config=None):
        """ load config

        Parameters
        ----------
        file: str or Path
            the path of json config file

        config: Config
            config object to be initialized
        """
        if isinstance(config, QConfig):
            self._cfg = config
之一Yo's avatar
之一Yo 已提交
350

之一Yo's avatar
之一Yo 已提交
351 352
        if isinstance(file, (str, Path)):
            self._cfg.file = Path(file)
之一Yo's avatar
之一Yo 已提交
353 354

        try:
之一Yo's avatar
之一Yo 已提交
355
            with open(self._cfg.file, encoding="utf-8") as f:
之一Yo's avatar
之一Yo 已提交
356 357 358 359 360 361
                cfg = json.load(f)
        except:
            cfg = {}

        # map config items'key to item
        items = {}
之一Yo's avatar
之一Yo 已提交
362 363
        for name in dir(self._cfg.__class__):
            item = getattr(self._cfg.__class__, name)
之一Yo's avatar
之一Yo 已提交
364 365 366 367 368 369 370 371 372 373 374 375 376
            if isinstance(item, ConfigItem):
                items[item.key] = item

        # update the value of config item
        for k, v in cfg.items():
            if not isinstance(v, dict) and items.get(k) is not None:
                items[k].deserializeFrom(v)
            elif isinstance(v, dict):
                for key, value in v.items():
                    key = k + "." + key
                    if items.get(key) is not None:
                        items[key].deserializeFrom(value)

377
        self.theme = self.get(self.themeMode)
之一Yo's avatar
之一Yo 已提交
378 379 380

    @property
    def theme(self):
381 382
        """ get theme mode, can be `Theme.Light` or `Theme.Dark` """
        return self._cfg._theme
之一Yo's avatar
之一Yo 已提交
383

384 385 386 387 388 389 390 391 392
    @theme.setter
    def theme(self, t):
        """ chaneg the theme without modifying the config file """
        if t == Theme.AUTO:
            t = darkdetect.theme()
            t = Theme(t) if t else Theme.LIGHT

        self._cfg._theme = t

之一Yo's avatar
之一Yo 已提交
393

之一Yo's avatar
之一Yo 已提交
394
qconfig = QConfig()
395 396 397 398


def isDarkTheme():
    """ whether the theme is dark mode """
之一Yo's avatar
之一Yo 已提交
399 400 401 402 403
    return qconfig.theme == Theme.DARK

def theme():
    """ get theme mode """
    return qconfig.theme