Mercurial > system76-keyboard-colors
diff 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 diff
--- a/keyboard_colors/color_profile.py Tue Feb 02 19:46:01 2021 -0500 +++ b/keyboard_colors/color_profile.py Tue Mar 02 20:17:36 2021 -0500 @@ -6,6 +6,7 @@ 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 @@ -17,7 +18,7 @@ def __init__(self): self.name = '' - self.id = uuid.uuid4().hex + self.id = str(uuid.uuid4()) def build_settings_ui(self): glade_file = sys.modules[self.__module__].__file__.replace('.py', '.glade') @@ -25,12 +26,25 @@ 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): - self.profiles = self.load_profiles() - self.save_profiles() + profile_list = self.load_profiles() + self.profiles = {p.id: p for p in profile_list} def get_types(self): types = [] @@ -55,15 +69,18 @@ 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: types.SimpleNamespace(**d)) + 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.__dict__) + 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]