package edu.stanford.bmir.styledstring;

import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.text.AttributedString;

/**
 * Matthew Horridge
 * Stanford University
 * Bio-Medical Informatics Research Group
 * Date: 5th December 2014
 * <p>
 * A simple first in first out cache for TextLayout objects of AttributedStrings.
 * </p>
 */
public class TextLayoutCache {

    private AttributedString attributedString;

    private FontRenderContext cachedFontRenderContext;

    private TextLayout cachedLayout;

    public TextLayoutCache(AttributedString attributedString) {
        this.attributedString = attributedString;
    }

    public AttributedString getAttributedString() {
        return attributedString;
    }

    public TextLayout getTextLayout(FontRenderContext fontRenderContext) {
        if (!isCachedFontRenderContext(fontRenderContext)) {
            cachedLayout = new TextLayout(attributedString.getIterator(), fontRenderContext);
            cachedFontRenderContext = fontRenderContext;
        }
        return cachedLayout;
    }

    public float getHeight(FontRenderContext fontRenderContext) {
        TextLayout tl = getTextLayout(fontRenderContext);
        return tl.getLeading() + tl.getAscent() + tl.getDescent();
    }

    public float getVisibleAdvance(FontRenderContext fontRenderContext) {
        TextLayout tl = getTextLayout(fontRenderContext);
        return tl.getVisibleAdvance();
    }

    public float getBaseline(FontRenderContext fontRenderContext) {
        TextLayout tl = getTextLayout(fontRenderContext);
        return tl.getLeading() + tl.getAscent();

    }


    private boolean isCachedFontRenderContext(FontRenderContext fontRenderContext) {
        return cachedFontRenderContext != null && cachedFontRenderContext.equals(fontRenderContext);
    }
}

@@ -143,16 +143,82 @@
 tring;%0A%0A
+import static com.google.common.base.Preconditions.checkNotNull;%0A%0A
 /**%0A * M
@@ -470,16 +470,22 @@
 private 
+final 
 Attribut
@@ -702,16 +702,29 @@
 tring = 
+checkNotNull(
 attribut
@@ -723,32 +723,33 @@
 attributedString
+)
 ;%0A    %7D%0A%0A    pub

Tidy of TextLayoutCache