changeset 105:24e98602b37e

Use Guava MapMaker to cache text layouts.
author Mikhail Kryshen <mikhail@kryshen.net>
date Tue, 24 May 2011 18:43:49 +0400
parents 9b81174f0511
children f42e2b9e1ad9
files src/net/kryshen/indyvon/layers.clj
diffstat 1 files changed, 16 insertions(+), 14 deletions(-) [+]
line diff
     1.1 --- a/src/net/kryshen/indyvon/layers.clj	Thu May 19 17:01:46 2011 +0400
     1.2 +++ b/src/net/kryshen/indyvon/layers.clj	Tue May 24 18:43:49 2011 +0400
     1.3 @@ -27,7 +27,10 @@
     1.4     (java.awt Font Cursor Image Toolkit Point)
     1.5     java.awt.image.ImageObserver
     1.6     (java.awt.geom AffineTransform Point2D$Double)
     1.7 -   (java.awt.font FontRenderContext TextLayout)))
     1.8 +   (java.awt.font FontRenderContext TextLayout)
     1.9 +   java.util.concurrent.TimeUnit
    1.10 +   com.google.common.collect.MapMaker
    1.11 +   com.google.common.base.Function))
    1.12    
    1.13  ;; Define as macro to avoid unnecessary calculation of inner and outer
    1.14  ;; sizes in the first case.
    1.15 @@ -172,24 +175,23 @@
    1.16  (defn- re-split [^java.util.regex.Pattern re s]
    1.17    (seq (.split re s)))
    1.18  
    1.19 -(def ^:private text-layout-cache (atom {}))
    1.20 +(def ^{:private true} text-layout-cache
    1.21 +  (-> (MapMaker.)
    1.22 +      (.softValues)
    1.23 +      (.expireAfterAccess (long 1) TimeUnit/SECONDS)
    1.24 +      (.makeComputingMap
    1.25 +       (reify Function
    1.26 +         (apply [_ k]
    1.27 +           (TextLayout. ^String (k 0)
    1.28 +                        ^Font (k 1)
    1.29 +                        ^FontRenderContext (k 2)))))))
    1.30  
    1.31 -(defn- get-text-layout
    1.32 -  [^String line ^Font font ^FontRenderContext font-context]
    1.33 -  (let [key [line font font-context]]
    1.34 -    (or (if-let [^SoftReference softref (@text-layout-cache key)]
    1.35 -          (.get softref)
    1.36 -          (do (swap! text-layout-cache dissoc key)
    1.37 -              false))
    1.38 -        (let [layout (TextLayout. line font font-context)]
    1.39 -          ;;(println "text-layout-cache miss" line)
    1.40 -          (swap! text-layout-cache assoc key (SoftReference. layout))
    1.41 -          layout))))
    1.42 +(defn- get-text-layout [line font font-context]
    1.43 +  (get text-layout-cache [line font font-context]))
    1.44  
    1.45  (defn- layout-text
    1.46    [lines ^Font font ^FontRenderContext font-context]
    1.47    (map #(get-text-layout % font font-context) lines))
    1.48 -  ;;(map #(TextLayout. ^String % font font-context) lines))
    1.49  
    1.50  (defn- text-width [layouts]
    1.51    (reduce (fn [w ^TextLayout tl] (max w (.getAdvance tl))) 0 layouts))