From f214b4f404623bec831f3cbc20b58c1c80f6b42b Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Fri, 18 Sep 2020 18:29:36 +0100 Subject: [PATCH] Add FontCacheImpl --- .../net/kemitix/fontface/FontCacheImpl.java | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 src/main/java/net/kemitix/fontface/FontCacheImpl.java diff --git a/src/main/java/net/kemitix/fontface/FontCacheImpl.java b/src/main/java/net/kemitix/fontface/FontCacheImpl.java new file mode 100644 index 0000000..1133843 --- /dev/null +++ b/src/main/java/net/kemitix/fontface/FontCacheImpl.java @@ -0,0 +1,74 @@ +package net.kemitix.fontface; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + +import java.awt.*; +import java.net.URI; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import java.util.logging.Logger; + +@RequiredArgsConstructor +public class FontCacheImpl implements FontCache { + + private static final Logger LOGGER = + Logger.getLogger( + FontCacheImpl.class.getName()); + + private final Map fileCache = new HashMap<>(); + + private final Map fontCache = new HashMap<>(); + + private final FontLoader fontLoader; + + @Override + public Font loadFont(final FontFace fontFace) { + LOGGER.finest(String.format("Requesting %s %d", + fontFace.getFontLocation(), fontFace.getSize())); + final Font baseFont = + fileCache.computeIfAbsent( + fontFace.getFontLocation(), + loadNewFontFile(fontFace)); + return fontCache.computeIfAbsent( + FontAndSize.of(baseFont, fontFace.getSize()), + resizeFont()); + } + + private Function loadNewFontFile( + final FontFace fontFace + ) { + return uri -> { + LOGGER.fine(String.format("Loading %s", uri)); + return fontLoader.loadFont(fontFace); + }; + } + + + private Function resizeFont() { + return fontAndSize -> { + LOGGER.finer(String.format("Resizing %s to %d", + fontAndSize.getFont().getName(), fontAndSize.getSize())); + return fontAndSize.font + .deriveFont(Font.PLAIN, fontAndSize.getSize()); + }; + } + + @Getter + @EqualsAndHashCode + private static class FontAndSize { + private final Font font; + private final int size; + + private FontAndSize(final Font font, final int size) { + this.font = font; + this.size = size; + } + + static FontAndSize of(final Font font, final int size) { + return new FontAndSize(font, size); + } + } +}