dcs-retribution/game/settings/choicesoption.py
Dan Albert 7bec4c62f7 Generate settings pages automatically.
This adds metadata to settings fields that can be used to automatically
generate the settings window. For now I have replaced the Difficulty
page. Will follow up to replace the others.
2021-10-21 18:30:56 -07:00

42 lines
1.1 KiB
Python

from dataclasses import dataclass, field
from typing import Any, Generic, Iterable, Mapping, Optional, TypeVar, Union
from .optiondescription import OptionDescription, SETTING_DESCRIPTION_KEY
ValueT = TypeVar("ValueT")
@dataclass(frozen=True)
class ChoicesOption(OptionDescription, Generic[ValueT]):
choices: dict[str, ValueT]
def text_for_value(self, value: ValueT) -> str:
for text, _value in self.choices.items():
if value == _value:
return text
raise ValueError(f"{self} does not contain {value}")
def choices_option(
text: str,
page: str,
section: str,
choices: Union[Iterable[str], Mapping[str, ValueT]],
detail: Optional[str] = None,
**kwargs: Any,
) -> ValueT:
if not isinstance(choices, Mapping):
choices = {c: c for c in choices}
return field(
metadata={
SETTING_DESCRIPTION_KEY: ChoicesOption(
page,
section,
text,
detail,
dict(choices),
)
},
**kwargs,
)