summaryrefslogtreecommitdiff
path: root/lib/lettering/utils.py
blob: 4c9822ea5bbdb0930f1bf5625eb14447dca26d14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Authors: see git history
#
# Copyright (c) 2024 Authors
# Licensed under the GNU GPL version 3.0 or later.  See the file LICENSE for details.

import os

from ..extensions.lettering_custom_font_dir import get_custom_font_dir
from ..lettering import Font
from ..utils import get_bundled_dir, get_user_dir


def get_font_list(show_font_path_warning=True):
    font_paths = get_font_paths()

    fonts = []
    for font_path in font_paths:
        try:
            font_dirs = os.listdir(font_path)
        except OSError:
            continue

        for font_dir in font_dirs:
            font = _get_font_from_path(font_path, font_dir, show_font_path_warning)
            if not font or font.marked_custom_font_name == "" or font.marked_custom_font_id == "":
                continue
            fonts.append(font)
    return fonts


def get_font_paths():
    font_paths = {
        get_bundled_dir("fonts"),
        os.path.expanduser("~/.inkstitch/fonts"),
        get_user_dir('fonts'),
        get_custom_font_dir()
    }
    return font_paths


def get_font_by_id(font_id, show_font_path_warning=True):
    font_paths = get_font_paths()
    for font_path in font_paths:
        try:
            font_dirs = os.listdir(font_path)
        except OSError:
            continue
        for font_dir in font_dirs:
            font = _get_font_from_path(font_path, font_dir, show_font_path_warning)
            if font and font_id in [font.id, font.marked_custom_font_id]:
                return font
    return None


def get_font_by_name(font_name):
    font_paths = get_font_paths()
    for font_path in font_paths:
        try:
            font_dirs = os.listdir(font_path)
        except OSError:
            continue
        for font_dir in font_dirs:
            font = _get_font_from_path(font_path, font_dir)
            if font and font_name in [font.name, font.marked_custom_font_name]:
                return font
    return None


def _get_font_from_path(font_path, font_dir, show_font_path_warning=True):
    if not os.path.isdir(os.path.join(font_path, font_dir)) or font_dir.startswith('.'):
        return
    return Font(os.path.join(font_path, font_dir), show_font_path_warning)