1 module poison.ui.fonts; 2 3 import std.file : dirEntries, SpanMode; 4 import std.algorithm : filter, endsWith; 5 import std.string : toLower; 6 import std.path : stripExtension, baseName; 7 8 public import dsfml.graphics : Font; 9 10 /// The fonts. 11 private Font[string] _fonts; 12 13 /// Enumeration of font styles. 14 enum FontStyle { 15 /// Normal font style. 16 normal = "", 17 18 /// Bold font style. 19 bold = "b", 20 21 /// Italic font style. 22 italic = "i", 23 24 /// Bold & italic font style. 25 boldItalic = "z" 26 } 27 28 /** 29 * Loads all fonts within a specific path. 30 * Params: 31 * path = The path of the fonts. 32 */ 33 void loadFonts(string path) { 34 auto entries = dirEntries(path, SpanMode.depth).filter!(f => f.name.toLower().endsWith(".ttf")); 35 36 foreach (string filePath; entries) { 37 loadFont(filePath); 38 } 39 } 40 41 /** 42 * Loads a font by its path or retrieves it from the font cache. 43 * Params: 44 * path = The path of the font. Note: The path can be a name too, but is required with the font-style suffix. Use retrieveFont for easier access. 45 */ 46 Font loadFont(string path) { 47 auto font = _fonts.get(path, null); 48 49 if (font) { 50 return font; 51 } 52 53 font = new Font(); 54 font.loadFromFile(path); 55 56 auto name = stripExtension(baseName(path)); 57 58 _fonts[name] = font; 59 _fonts[path] = font; 60 return font; 61 } 62 63 /** 64 * Retrieves a font by a name and style. 65 * Params: 66 * fontName = The name of the font to retrieve. 67 * style = The style of the font. 68 */ 69 Font retrieveFont(string fontName, FontStyle style) { 70 return _fonts.get(fontName ~ style, null); 71 }