AnkiNoteTemplate/antp/common.py

62 lines
1.3 KiB
Python
Raw Normal View History

2021-11-27 11:54:42 +00:00
# Copyright: Ren Tatsumoto <tatsu at autistici.org>
# License: GNU GPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
2021-04-20 13:23:50 +00:00
import re
2021-11-27 11:54:42 +00:00
from dataclasses import dataclass
2021-04-20 10:27:47 +00:00
2021-11-27 11:54:42 +00:00
from .consts import *
class ANTPError(Exception):
pass
@dataclass(frozen=True)
class CardTemplate:
name: str
front: str
back: str
2021-04-20 13:23:50 +00:00
2021-11-27 11:54:42 +00:00
@dataclass(frozen=True)
class NoteType:
name: str
fields: list[str]
css: str
templates: list[CardTemplate]
2021-04-20 10:27:47 +00:00
def read_num(msg: str = "Input number: ", min_val: int = 0, max_val: int = None) -> int:
resp = int(input(msg))
if resp < min_val or (max_val and resp > max_val):
2021-11-27 11:54:42 +00:00
raise ANTPError("Value out of range.")
2021-04-20 10:27:47 +00:00
return resp
2021-12-25 19:38:09 +00:00
def select(items: list[str], msg: str = "Select item number: ") -> str | None:
2021-04-20 10:27:47 +00:00
if not items:
print("Nothing to show.")
return
2021-04-22 20:03:51 +00:00
2021-04-20 10:27:47 +00:00
for idx, model in enumerate(items):
print(f"{idx}: {model}")
2021-04-22 20:03:51 +00:00
print()
idx = read_num(msg, max_val=len(items) - 1)
return items[idx]
2021-04-20 13:23:50 +00:00
def get_used_fonts(template_css: str):
return re.findall(r"url\([\"'](\w+\.[ot]tf)[\"']\)", template_css, re.IGNORECASE)
2021-11-27 11:54:42 +00:00
def init():
from .consts import NOTE_TYPES_DIR, FONTS_DIR
for path in (NOTE_TYPES_DIR, FONTS_DIR):
if not os.path.isdir(path):
os.mkdir(path)
init()