1 /**
2 * Copyright © Novelate 2020
3 * License: MIT (https://github.com/Novelate/NovelateEngine/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 * Website: https://novelate.com/
6 * ------
7 * Novelate is a free and open-source visual novel engine and framework written in the D programming language.
8 * It can be used freely for both personal and commercial projects.
9 * ------
10 * Module Description:
11 * This module handles fonts.
12 */
13 module novelate.fonts;
14 
15 import std.file : dirEntries, SpanMode;
16 import std.algorithm : filter, endsWith;
17 import std..string : toLower;
18 import std.path : stripExtension, baseName;
19 import std.array : replace;
20 import std.conv : to;
21 
22 public import novelate.external : ExternalFont;
23 
24 /// The font collection.
25 private ExternalFont[string] _fonts;
26 
27 /// Enumeration of font styles.
28 enum FontStyle : string
29 {
30   /// Normal font style.
31   normal = "",
32   /// The bold font style.
33   bold = "b",
34   /// The italic font style.
35   italic = "i",
36   /// The bold italic font style.
37   boldItalic = "z"
38 }
39 
40 /**
41 * Loads fonts within a specific folder. Supports .ttf and .ttc file extensions. It also looks through sub-folders.
42 * Params:
43 *   path = The path of the folder that contains the fonts.
44 */
45 void loadFonts(string path)
46 {
47   auto entries = dirEntries(to!string(path), SpanMode.depth).filter!(f => f.name.toLower().endsWith(".ttf") || f.name.toLower().endsWith(".ttc"));
48 
49   foreach (string filePath; entries)
50   {
51     loadFont(filePath);
52   }
53 }
54 
55 /**
56 * Loads a font from a specific file. Supports .ttf and .ttc file extensions.
57 * Params:
58 *   path = The path of the font file.
59 * Returns:
60 *   The loaded font.
61 */
62 ExternalFont loadFont(string path)
63 {
64   auto font = _fonts.get(path, null);
65 
66   if (font)
67   {
68     return font;
69   }
70 
71   font = new ExternalFont;
72   font.loadFromFile(path);
73 
74   auto name = stripExtension(baseName(path));
75 
76   _fonts[name.toLower] = font;
77   _fonts[path.replace("\\", "/")] = font;
78   _fonts[path.replace("/", "\\")] = font;
79 
80   return font;
81 }
82 
83 /**
84 * Retrieves a font by its name and font style.
85 * Params:
86 *   fontName = The name of the font to retrieve.
87 *   style = The style of the font to retrieve.
88 * Returns:
89 *   The retrieved font if found, null otherwise.
90 */
91 ExternalFont retrieveFont(string fontName, FontStyle style)
92 {
93   return _fonts.get(fontName ~ style, null);
94 }