/[schmitzm]/branches/2.3.KECK/src/skrueger/geotools/RenderingExecutor.java
ViewVC logotype

Diff of /branches/2.3.KECK/src/skrueger/geotools/RenderingExecutor.java

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 513 by alfonx, Mon Nov 9 11:17:34 2009 UTC revision 531 by alfonx, Thu Nov 19 09:42:59 2009 UTC
# Line 1  Line 1 
1  package skrueger.geotools;  package skrueger.geotools;
2    
 /*  
  *    GeoTools - The Open Source Java GIS Toolkit  
  *    http://geotools.org  
  *  
  *    (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)  
  *  
  *    This library is free software; you can redistribute it and/or  
  *    modify it under the terms of the GNU Lesser General Public  
  *    License as published by the Free Software Foundation;  
  *    version 2.1 of the License.  
  *  
  *    This library is distributed in the hope that it will be useful,  
  *    but WITHOUT ANY WARRANTY; without even the implied warranty of  
  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU  
  *    Lesser General Public License for more details.  
  */  
   
   
 import gtmig.org.geotools.swing.XMapPane;  
   
 import java.awt.AlphaComposite;  
 import java.awt.Color;  
 import java.awt.Composite;  
3  import java.awt.Graphics2D;  import java.awt.Graphics2D;
4  import java.awt.Rectangle;  import java.awt.Rectangle;
5  import java.util.concurrent.Callable;  import java.awt.geom.AffineTransform;
 import java.util.concurrent.CountDownLatch;  
 import java.util.concurrent.ExecutorService;  
 import java.util.concurrent.Executors;  
 import java.util.concurrent.Future;  
 import java.util.concurrent.ScheduledExecutorService;  
 import java.util.concurrent.ScheduledFuture;  
 import java.util.concurrent.TimeUnit;  
 import java.util.concurrent.atomic.AtomicBoolean;  
6    
7  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
8  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
9  import org.geotools.renderer.RenderListener;  import org.geotools.renderer.RenderListener;
 import org.geotools.swing.JMapPane;  
10  import org.opengis.feature.simple.SimpleFeature;  import org.opengis.feature.simple.SimpleFeature;
11    
 /**  
  * This class is used by {@code JMapPane} to handle the scheduling and running of  
  * rendering tasks on a background thread. It functions as a single thread, non-  
  * queueing executor, ie. only one rendering task can run at any given time and,  
  * while it is running, any other submitted tasks will be rejected.  
  * <p>  
  * Whether a rendering task is accepted or rejected can be tested on submission:  
  * <pre><code>  
  *     ReferencedEnvelope areaToDraw = ...  
  *     Graphics2D graphicsToDrawInto = ...  
  *     boolean accepted = renderingExecutor.submit(areaToDraw, graphicsToDrawInto);  
  * </code></pre>  
  *  
  * The status of the executor can also be checked at any time like this:  
  * <pre><code>  
  *     boolean busy = renderingExecutor.isRunning();  
  * </code></pre>  
  *  
  * While a rendering task is running it is regularly polled to see if it has completed  
  * and, if so, whether it finished normally, was cancelled or failed. The interval between  
  * polling can be adjusted which might be useful to tune the executor for particular  
  * applications:  
  * <pre><code>  
  *     RenderingExecutor re = new RenderingExecutor( mapPane );  
  *     re.setPollingInterval( 150 );  // 150 milliseconds  
  * </code></pre>  
  *  
  * @author Michael Bedward  
  * @since 2.7  
  * @source $URL: http://svn.osgeo.org/geotools/branches/2.6.x/modules/unsupported/swing/src/main/java/org/geotools/swing/RenderingExecutor.java $  
  * @version $Id: RenderingExecutor.java 34285 2009-10-30 10:48:49Z mbedward $  
  *  
  * @see JMapPane  
  */  
12  public class RenderingExecutor {  public class RenderingExecutor {
13    
14      private final XMapPane mapPane;          private volatile RenderThread renderThread;
15      private final ExecutorService taskExecutor;          private final XMapPane mapPane;
16      private final ScheduledExecutorService watchExecutor;  
17            public RenderingExecutor(XMapPane mapPane) {
18  //    /** The default interval (milliseconds) for polling the result of a rendering task */                  this.mapPane = mapPane;
19  //    public static final long DEFAULT_POLLING_INTERVAL = 300L;          }
20    
21      private long pollingInterval;          /**
22             * Submit a new rendering task. If no rendering task is presently running
23      /*           * this new task will be accepted; otherwise it will be rejected (ie. there
24       * This latch is used to avoid a race between the cancellation of           * is no task queue).
25       * a current task and the submittal of a new task           *
26       */           * @param envelope
27      private CountDownLatch cancelLatch;           *            the map area (world coordinates) to be rendered
28             * @param graphics
29      /**           *            the graphics object to draw on
30       * Constants to indicate the result of a rendering task           *
31       */           * @return true if the rendering task was accepted; false if it was rejected
32      public enum TaskResult {           */
33          PENDING,          public synchronized boolean submit(ReferencedEnvelope envelope,
34          COMPLETED,                          Rectangle paintArea, Graphics2D graphics,
35          CANCELLED,                          final GTRenderer renderer, AffineTransform worldToScreen) {
36          FAILED;                  System.out.println("submit..:");
37      }                  if (renderThread == null || !renderThread.isAlive()) {
38                            System.out.println("is vacant... starting thread!");
39      private long numFeatures;  
40                            renderThread = new RenderThread(paintArea, graphics, renderer,
41      /**                                          worldToScreen);
42       * A rendering task                          renderThread.start();
43       */  
44      private class Task implements Callable<TaskResult>, RenderListener {                          return true;
45                    } else {
46          private final ReferencedEnvelope envelope;                          System.out.println("is busy... requesting stop!");
47          private final Rectangle paintArea;                          renderThread.getRenderer().stopRendering();
48          private final Graphics2D graphics;                  }
49    
50          private boolean cancelled;                  return false;
51          private boolean failed;          }
52                  final private GTRenderer renderer;  
53            class RenderThread extends Thread {
54          /**  
55           * Constructor. Creates a new rendering task                  private final GTRenderer renderer;
56           *  
57           * @param envelope map area to render (world coordinates)                  public RenderThread(final Rectangle paintArea,
58           * @param paintArea drawing area (image or display coordinates)a                                  final Graphics2D graphics, GTRenderer renderer,
59           * @param graphics graphics object used to draw into the image or display                                  AffineTransform worldToScreen) {
60           */                          super(new RenderRun(paintArea, graphics, renderer, worldToScreen));
61          public Task(final ReferencedEnvelope envelope, final Rectangle paintArea, final Graphics2D graphics, GTRenderer renderer) {                          this.renderer = renderer;
62              this.envelope = envelope;  
63              this.paintArea = paintArea;                          System.out.println("starting render thread " + getName());
64              this.graphics = graphics;                  }
65              this.cancelled = false;  
66              this.renderer = renderer;                  public GTRenderer getRenderer() {
67              failed = false;                          return renderer;
68          }                  }
69    
70          /**          }
71           * Called by the executor to run this rendering task.  
72           *          class RenderRun implements Runnable, RenderListener {
73           * @return result of the task: completed, cancelled or failed                  private final Rectangle paintArea;
74           * @throws Exception                  private final Graphics2D graphics;
75           */                  private final AffineTransform worldToScreen;
76          public TaskResult call() throws Exception {                  private final GTRenderer renderer;
77              if (!cancelled) {  
78                                    public RenderRun(Rectangle paintArea, Graphics2D graphics,
79                  try {                                  GTRenderer renderer, AffineTransform worldToScreen) {
80                      renderer.addRenderListener(this);                          this.paintArea = paintArea;
81                                                this.graphics = graphics;
82                      Composite composite = graphics.getComposite();                          this.renderer = renderer;
83                      //graphics.setComposite(AlphaComposite.Src);                          this.worldToScreen = worldToScreen;
84                      //graphics.setBackground(Color.WHITE);                  }
85                      graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));  
86                      graphics.fill(paintArea);                  @Override
87                      graphics.setComposite(composite);                  public void run() {
88                            try {
89                                    renderer.addRenderListener(this);
90                      numFeatures = 0;                                  System.out.println("start rendering...");
91                      renderer.paint(graphics, mapPane.getVisibleRect(), envelope, mapPane.getWorldToScreenTransform());                                  try {
92                                            Thread.sleep(1000);
93                  } finally {                                  } catch (InterruptedException e) {
94                      renderer.removeRenderListener(this);                                          // TODO Auto-generated catch block
95                  }                                          e.printStackTrace();
96              }                                  }
97                                    renderer.paint(graphics, paintArea, worldToScreen);
98              if (cancelled) {  
99                  return TaskResult.CANCELLED;                                  mapPane.onRenderingCompleted();
100              } else if (failed) {                          } finally {
101                  return TaskResult.FAILED;                                  renderer.removeRenderListener(this);
102              } else {                          }
103                  return TaskResult.COMPLETED;                  }
104              }  
105          }                  @Override
106                    public void errorOccurred(Exception e) {
107          /**                          // System.out.println("rendering error");
108           * Cancel the rendering task if it is running. If called before                          mapPane.onRenderingFailed(e);
109           * being run the task will be abandoned.                  }
110           */  
111          public synchronized void cancel() {                  @Override
112              if (isRunning()) {                  public void featureRenderer(SimpleFeature feature) {
113                  cancelled = true;                  }
114                  renderer.stopRendering();  
115              }          }
116          }  
117            public void cancelTask() {
118          /**                  if (renderThread != null && renderThread.isAlive()) {
119           * Called by the renderer when each feature is drawn.                          // System.out.println("request stop for thread " +task.getName());
120           *                          renderThread.getRenderer().stopRendering();
121           * @param feature the feature just drawn                  }
122           */          }
123          public void featureRenderer(SimpleFeature feature) {  
124              // @todo update a progress listener          public boolean isRunning() {
125              numFeatures++ ;                  // if (task != null)
126          }                  // System.out.println("is running "+task.getName()+" = true");
127                    return (renderThread != null && renderThread.isAlive());
128          /**          }
129           * Called by the renderer on error  
130           *          public void dispose() {
131           * @param e cause of the error                  if (renderThread != null) {
132           */                          renderThread.renderer.stopRendering();
133          public void errorOccurred(Exception e) {                          renderThread = null;
134                  renderingException = e;                  }
135                  graphics.setColor(Color.white);          }
                 graphics.drawString(e.getMessage(), 11, 11);  
                 graphics.drawString(e.getMessage(), 9, 9);  
                 graphics.setColor(Color.black);  
                 graphics.drawString(e.getMessage(), 10, 10);  
             failed = true;  
         }  
   
     }  
   
     private AtomicBoolean taskRunning;  
     private Task task;  
     private Future<TaskResult> taskResult;  
     private ScheduledFuture<?> watcher;  
         private Exception renderingException;  
   
     /**  
      * Constructor. Creates a new executor to service the specified map pane.  
      *  
      * @param mapPane the map pane to be serviced  
      * @param l  
      */  
         public RenderingExecutor(final XMapPane mapPane, long pollingInterval) {  
         taskRunning = new AtomicBoolean(false);  
         this.mapPane = mapPane;  
         taskExecutor = Executors.newSingleThreadExecutor();  
         watchExecutor = Executors.newSingleThreadScheduledExecutor();  
         this.pollingInterval = pollingInterval;  
         cancelLatch = new CountDownLatch(0);  
     }  
   
     /**  
      * Get the interval for polling the result of a rendering task  
      *  
      * @return polling interval in milliseconds  
      */  
     public long getPollingInterval() {  
         return pollingInterval;  
     }  
   
     /**  
      * Set the interval for polling the result of a rendering task  
      *  
      * @param interval interval in milliseconds (values {@code <=} 0 are ignored)  
      */  
     public void setPollingInterval(long interval) {  
         if (interval > 0) {  
             pollingInterval = interval;  
         }  
     }  
   
     /**  
      * Submit a new rendering task. If no rendering task is presently running  
      * this new task will be accepted; otherwise it will be rejected (ie. there  
      * is no task queue).  
      *  
      * @param envelope the map area (world coordinates) to be rendered  
      * @param graphics the graphics object to draw on  
      *  
      * @return true if the rendering task was accepted; false if it was  
      *         rejected  
      */  
     public synchronized boolean submit(ReferencedEnvelope envelope, Rectangle paintArea, Graphics2D graphics, final GTRenderer renderer) {  
         if (!isRunning() || cancelLatch.getCount() > 0) {  
             try {  
                 // wait for any cancelled task to finish its shutdown  
                 cancelLatch.await();  
             } catch (InterruptedException ex) {  
                 return false;  
             }  
   
             task = new Task(envelope, paintArea, graphics, renderer);  
             taskRunning.set(true);  
             taskResult = taskExecutor.submit(task);  
             watcher = watchExecutor.scheduleAtFixedRate(new Runnable() {  
   
                 public void run() {  
                     pollTaskResult();  
                 }  
             }, pollingInterval, pollingInterval, TimeUnit.MILLISECONDS);  
   
             return true;  
         }  
   
         return false;  
     }  
   
     /**  
      * Cancel the current rendering task if one is running  
      */  
     public synchronized void cancelTask() {  
         if (isRunning()) {  
             task.cancel();  
             cancelLatch = new CountDownLatch(1);  
         }  
     }  
   
     private void pollTaskResult() {  
         if (!taskResult.isDone()) {  
             return;  
         }  
   
         TaskResult result = TaskResult.PENDING;  
   
         try {  
             result = taskResult.get();  
         } catch (Exception ex) {  
             throw new IllegalStateException("When getting rendering result", ex);  
         }  
   
         watcher.cancel(false);  
         taskRunning.set(false);  
   
         switch (result) {  
             case CANCELLED:  
                 cancelLatch.countDown();  
                 mapPane.onRenderingCancelled();  
                 break;  
   
             case COMPLETED:  
                 mapPane.onRenderingCompleted();  
                 break;  
   
             case FAILED:  
                 mapPane.onRenderingFailed(renderingException);  
                 break;  
                   
             case PENDING:  
                 mapPane.onRenderingPending();  
                 break;  
                   
         }  
     }  
   
     public synchronized boolean isRunning() {  
         return taskRunning.get();  
     }  
   
     @Override  
     protected void finalize() throws Throwable {  
         if (this.isRunning()) {  
             taskExecutor.shutdownNow();  
             watchExecutor.shutdownNow();  
         }  
     }  
 }  
136    
137    }

Legend:
Removed from v.513  
changed lines
  Added in v.531

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26