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