blob: 1bff4993decf926d15513ce0144aa091f4f26638 [file] [log] [blame]
Philipp Le4071d912022-04-26 22:02:43 +02001# SPDX-License-Identifier: MPL-2.0
2# Copyright (c) 2022 Philipp Le <philipp@philipple.de>.
3# This Source Code Form is subject to the terms of the Mozilla Public
4# License, v. 2.0. If a copy of the MPL was not distributed with this
5# file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
7from __future__ import annotations
8
9from typing import Type, List, Dict, Optional
10from pydantic import BaseModel
11
12from .base import ConfigWidget
13
14
15_CLASS_REGISTRY: List[Type[ConfigWidget]] = [
16]
17
18
19def _find_widget_classes(tp: Type, is_list: bool = False) -> Dict[Optional[str], Type[ConfigWidget]]:
20 widget_classes: Dict[Optional[str], Type[ConfigWidget]] = {}
21 if is_list:
22 raise NotImplementedError
23 else:
24 for cls in _CLASS_REGISTRY:
25 if issubclass(tp, cls.MODEL_TYPE):
26 widget_classes[cls.FLAVOUR] = cls
27 if len(widget_classes) == 0:
28 raise TypeError(f'No widget class for {repr(tp)} found.')
29 return widget_classes
30
31
32def _add_ui_create(model_cls: BaseModel, tp: Type[int], name: str, widget_type: Type[ConfigWidget],
33 flavour: Optional[str]):
34 suffix = f'_{flavour}' if flavour is not None else ''
35 setattr(model_cls, f'ui_create_{name}{suffix}', widget_type.make_ui_create_method(tp, name))
36
37
38def ui_create(cls: BaseModel):
39 for field in cls.__fields__.values():
40 name = field.name
41 tp = field.type_
42 is_list = isinstance(field.default, list)
43 try:
44 widget_classes = _find_widget_classes(tp, is_list)
45 for flavour, wgd_cls in widget_classes.items():
46 _add_ui_create(cls, tp, name, wgd_cls, flavour)
47 except TypeError as e:
48 print(e)
49 return cls