Mercurial > system76-keyboard-colors
view keyboard_colors/color_profile.py @ 2:091a1f59a79c
Load profiles into list view
author | Brad Greco <brad@bgreco.net> |
---|---|
date | Tue, 02 Mar 2021 20:17:36 -0500 |
parents | b6d0a1e6ba3a |
children | eb2aa09653bd |
line wrap: on
line source
import gi import importlib import json import os import pathlib import sys import types import uuid from types import SimpleNamespace gi.require_version("Gtk", "3.0") from gi.repository import Gtk # noqa: E402 from gi.repository import GLib # noqa: E402 class ColorProfileBase: type_name = '(no name)' def __init__(self): self.name = '' self.id = str(uuid.uuid4()) def build_settings_ui(self): glade_file = sys.modules[self.__module__].__file__.replace('.py', '.glade') builder = Gtk.Builder() builder.add_from_file(glade_file) return builder.get_object('edit_profile_container') def serialize(self): properties = self.__dict__ properties['module'] = self.__class__.__module__ return properties @staticmethod def unserialize(data): profile_module = importlib.import_module(data['module']) profile_class = getattr(profile_module, 'ColorProfile') profile = profile_class() profile.__dict__.update(data) return profile class ProfileManager: def __init__(self): profile_list = self.load_profiles() self.profiles = {p.id: p for p in profile_list} def get_types(self): types = [] profile_directory = os.path.dirname(os.path.realpath(__file__)) (_, dirnames, _) = next(os.walk(profile_directory)) for dirname in dirnames: module_file = os.path.join(profile_directory, dirname, dirname + '.py') if os.path.isfile(module_file): module_name = 'keyboard_colors.' + dirname + '.' + dirname profile_module = importlib.import_module(module_name) profile_class = getattr(profile_module, 'ColorProfile') types.append(profile_class) return types def config_path(self): dir = GLib.get_user_config_dir() if not os.path.isdir(dir): os.mkdir(dir) return os.path.join(dir, 'keyboard-color-profiles.conf') def load_profiles(self): if os.path.isfile(self.config_path()): data = pathlib.Path(self.config_path()).read_text('utf-8') try: return json.loads(data, object_hook=lambda d: ColorProfileBase.unserialize(d)) except json.decoder.JSONDecodeError: return [] else: return [] def save_profiles(self): data = json.dumps(self.profiles, default=lambda o: o.serialize()) pathlib.Path(self.config_path()).write_text(data, 'utf-8') def get_profiles(self): return self.profiles def get_profile(self, profile_id): return self.get_profiles()[profile_id]