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