blob: da3f9351da3d120681ad692bb2403b4c818822c2 [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
Philipp Lecefab922022-04-26 22:06:33 +020013from .num_widget import NumWidget
Philipp Lecfb6d2a2022-04-26 22:08:48 +020014from .str_widget import StrWidget
Philipp Lee93a2c42022-04-26 22:11:14 +020015from .enum_widget import EnumDropdownWidget
Philipp Le4071d912022-04-26 22:02:43 +020016
17
18_CLASS_REGISTRY: List[Type[ConfigWidget]] = [
Philipp Lecefab922022-04-26 22:06:33 +020019 NumWidget,
Philipp Lecfb6d2a2022-04-26 22:08:48 +020020 StrWidget,
Philipp Lee93a2c42022-04-26 22:11:14 +020021 EnumDropdownWidget,
Philipp Le4071d912022-04-26 22:02:43 +020022]
23
24
25def _find_widget_classes(tp: Type, is_list: bool = False) -> Dict[Optional[str], Type[ConfigWidget]]:
26 widget_classes: Dict[Optional[str], Type[ConfigWidget]] = {}
27 if is_list:
28 raise NotImplementedError
29 else:
30 for cls in _CLASS_REGISTRY:
31 if issubclass(tp, cls.MODEL_TYPE):
32 widget_classes[cls.FLAVOUR] = cls
33 if len(widget_classes) == 0:
34 raise TypeError(f'No widget class for {repr(tp)} found.')
35 return widget_classes
36
37
38def _add_ui_create(model_cls: BaseModel, tp: Type[int], name: str, widget_type: Type[ConfigWidget],
39 flavour: Optional[str]):
40 suffix = f'_{flavour}' if flavour is not None else ''
41 setattr(model_cls, f'ui_create_{name}{suffix}', widget_type.make_ui_create_method(tp, name))
42
43
44def ui_create(cls: BaseModel):
45 for field in cls.__fields__.values():
46 name = field.name
47 tp = field.type_
48 is_list = isinstance(field.default, list)
49 try:
50 widget_classes = _find_widget_classes(tp, is_list)
51 for flavour, wgd_cls in widget_classes.items():
52 _add_ui_create(cls, tp, name, wgd_cls, flavour)
53 except TypeError as e:
54 print(e)
55 return cls