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