View Javadoc
1   /*
2    * Copyright (c) 2005, The JUNG Authors
3    * All rights reserved.
4    *
5    * This software is open-source under the BSD license; see either "license.txt"
6    * or https://github.com/jrtom/jung/blob/master/LICENSE for a description.
7    *
8    * Created on Aug 23, 2005
9    */
10  
11  package edu.uci.ics.jung.visualization.layout;
12  
13  import java.awt.geom.Point2D;
14  
15  import com.google.common.base.Function;
16  import com.google.common.base.Functions;
17  import com.google.common.cache.CacheBuilder;
18  import com.google.common.cache.CacheLoader;
19  import com.google.common.cache.LoadingCache;
20  
21  import edu.uci.ics.jung.algorithms.layout.Layout;
22  import edu.uci.ics.jung.algorithms.layout.LayoutDecorator;
23  import edu.uci.ics.jung.graph.Graph;
24  import edu.uci.ics.jung.visualization.util.Caching;
25  
26  /**
27   * A LayoutDecorator that caches locations in a clearable Map. This can be used to ensure that
28   * edge endpoints are always the same as vertex locations when they are drawn in the render loop 
29   * during the time that the layout's relaxer thread is changing the locations.
30   * 
31   * @see LayoutDecorator
32   * @author Tom Nelson 
33   *
34   */
35  public class CachingLayout<V, E> extends LayoutDecorator<V,E> implements Caching {
36      
37      protected LoadingCache<V, Point2D> locations;
38  
39      public CachingLayout(Layout<V, E> delegate) {
40      	super(delegate);
41      	Function<V, Point2D> chain = Functions.<V,Point2D,Point2D>compose(
42      		new Function<Point2D,Point2D>() {
43      			public Point2D apply(Point2D p) {
44      				return (Point2D)p.clone();
45      		}}, 
46      		delegate);
47      	this.locations = CacheBuilder.newBuilder().build(CacheLoader.from(chain));
48      }
49      
50      @Override
51      public void setGraph(Graph<V, E> graph) {
52          delegate.setGraph(graph);
53      }
54  
55  	public void clear() {
56  	    this.locations = CacheBuilder.newBuilder().build(new CacheLoader<V, Point2D>() {
57  	    	public Point2D load(V vertex) {
58  	    		return new Point2D.Double();
59  	    	}
60  	    });
61  	}
62  
63  	public void init() {
64  	}
65  
66  	public Point2D apply(V v) {
67  		return locations.getUnchecked(v);
68  	}
69  }