|
| 1 | +package com.sentropic.guiapi.gui; |
| 2 | + |
| 3 | +import javax.annotation.Nullable; |
| 4 | +import java.util.HashMap; |
| 5 | +import java.util.Map; |
| 6 | + |
| 7 | +public class Font { |
| 8 | + |
| 9 | + // Static code |
| 10 | + |
| 11 | + public static final Font DEFAULT = new Font("minecraft:default", 8); |
| 12 | + private static final Map<String,Font> registeredFonts = new HashMap<>(); |
| 13 | + |
| 14 | + static { |
| 15 | + DEFAULT.registerWidth('I', 4); |
| 16 | + DEFAULT.registerWidth('f', 5); |
| 17 | + DEFAULT.registerWidth('i', 2); |
| 18 | + DEFAULT.registerWidth('k', 5); |
| 19 | + DEFAULT.registerWidth('l', 3); |
| 20 | + DEFAULT.registerWidth('t', 4); |
| 21 | + DEFAULT.registerWidth(' ', 4); |
| 22 | + DEFAULT.registerWidth('.', 2); |
| 23 | + |
| 24 | + register(DEFAULT); |
| 25 | + } |
| 26 | + |
| 27 | + @Nullable |
| 28 | + public static Font ofName(String name) { return registeredFonts.get(name); } |
| 29 | + |
| 30 | + public static void register(Font font) { |
| 31 | + String name = font.getName(); |
| 32 | + if (registeredFonts.containsKey(name)) { |
| 33 | + throw new IllegalArgumentException("Font \""+name+"\" already exists"); |
| 34 | + } |
| 35 | + registeredFonts.put(name, font); |
| 36 | + } |
| 37 | + |
| 38 | + public static boolean unregister(Font font) { |
| 39 | + boolean success = false; |
| 40 | + if (registeredFonts != null) { success = registeredFonts.remove(font.toString()) != null; } |
| 41 | + return success; |
| 42 | + } |
| 43 | + |
| 44 | + // Instance code |
| 45 | + |
| 46 | + private final String name; |
| 47 | + private final int height; |
| 48 | + private Map<Character,Integer> widths; |
| 49 | + |
| 50 | + public Font(String name, int height) { |
| 51 | + this.name = name; |
| 52 | + if (height < 5) { height += 1; } // Correction necessary for some reason |
| 53 | + this.height = height; |
| 54 | + } |
| 55 | + |
| 56 | + public void registerWidth(char character, int width) { |
| 57 | + if (widths == null) { widths = new HashMap<>(); } |
| 58 | + widths.put(character, width); |
| 59 | + } |
| 60 | + |
| 61 | + public int getWidth(char character, boolean custom) { |
| 62 | + int result = this == DEFAULT ? |
| 63 | + widths.getOrDefault(character, 6) : |
| 64 | + widths.getOrDefault(character, DEFAULT.getWidth(character, custom)); |
| 65 | + if (!custom) { |
| 66 | + result = Math.round(result*height/8f); // Scale |
| 67 | + } |
| 68 | + return result; |
| 69 | + } |
| 70 | + |
| 71 | + public int getWidth(String text) { |
| 72 | + if (text.equals("")) { return 0; } |
| 73 | + int total = 0; |
| 74 | + for (char character : text.toCharArray()) { total += getWidth(character, false); } |
| 75 | + return total; |
| 76 | + } |
| 77 | + |
| 78 | + @Override |
| 79 | + public String toString() { return name; } |
| 80 | + |
| 81 | + public String getName() { return name; } |
| 82 | + |
| 83 | + public int getHeight() { return height; } |
| 84 | +} |
0 commit comments