/[schmitzm]/branches/2.4.x/src/skrueger/geotools/RenderingExecutor.java
ViewVC logotype

Diff of /branches/2.4.x/src/skrueger/geotools/RenderingExecutor.java

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

revision 510 by alfonx, Thu Nov 5 17:39:37 2009 UTC revision 539 by alfonx, Fri Nov 20 19:10:05 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    
12  /**  /**
13   * This class is used by {@code JMapPane} to handle the scheduling and running of   * This class is used by {@link XMapPane} to start and stop the rendering a
14   * rendering tasks on a background thread. It functions as a single thread, non-   * {@link Thread} for rendering.
  * 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  
15   */   */
16  public class RenderingExecutor {  class RenderingExecutor {
17    
18      private final XMapPane mapPane;          /**
19      private final ExecutorService taskExecutor;           * Instance to a {@link RenderThread} doing any work. It's volatile so the
20      private final ScheduledExecutorService watchExecutor;           * correct value will always be visible to any {@link Thread}
21             **/
22      /** The default interval (milliseconds) for polling the result of a rendering task */          private volatile RenderThread renderThread;
23      public static final long DEFAULT_POLLING_INTERVAL = 100L;  
24            private final XMapPane mapPane;
25      private long pollingInterval;  
26            public RenderingExecutor(XMapPane mapPane) {
27      /*                  this.mapPane = mapPane;
28       * This latch is used to avoid a race between the cancellation of          }
29       * a current task and the submittal of a new task  
30       */          /**
31      private CountDownLatch cancelLatch;           * Submit a new rendering task. If no rendering task is presently running
32             * this new job will be accepted; otherwise it will be rejected and it
33      /**           * returns <code>false</code>.
34       * Constants to indicate the result of a rendering task           *
35       */           * @param envelope
36      public enum TaskResult {           *            the map area (world coordinates) to be rendered.
37          PENDING,           * @param graphics
38          COMPLETED,           *            the graphics object to draw on.
39          CANCELLED,           * @param paintArea
40          FAILED;           *            size of the area to paint the world into.
41      }           * @param worldToScreen
42             *            the {@link AffineTransform} from world coordinates to screen
43      private long numFeatures;           *            coordinates.
44             * @param renderer
45      /**           *            the {@link GTRenderer} to use.
46       * A rendering task           *
47       */           * @return true if the rendering task was accepted; false if it was rejected
48      private class Task implements Callable<TaskResult>, RenderListener {           */
49            public synchronized boolean submit(ReferencedEnvelope envelope,
50          private final ReferencedEnvelope envelope;                          Rectangle paintArea, Graphics2D graphics,
51          private final Rectangle paintArea;                          final GTRenderer renderer, AffineTransform worldToScreen) {
52          private final Graphics2D graphics;                  if (renderThread == null || !renderThread.isAlive()) {
53                            // System.out.println("is vacant... starting thread!");
54          private boolean cancelled;                          renderThread = null;
55          private boolean failed;  
56                  final private GTRenderer renderer;                          renderThread = new RenderThread(paintArea, graphics, renderer,
57                                            worldToScreen, envelope);
58          /**                          renderThread.start();
59           * Constructor. Creates a new rendering task  
60           *                          return true;
61           * @param envelope map area to render (world coordinates)                  } else {
62           * @param paintArea drawing area (image or display coordinates)a                          // System.out.println("is busy... requesting stop!");
63           * @param graphics graphics object used to draw into the image or display                          renderThread.getRenderer().stopRendering();
64           */                          return false;
65          public Task(final ReferencedEnvelope envelope, final Rectangle paintArea, final Graphics2D graphics, GTRenderer renderer) {                  }
66              this.envelope = envelope;          }
67              this.paintArea = paintArea;  
68              this.graphics = graphics;          /**
69              this.cancelled = false;           * For every new rendering job submitted and accepted, an instance of this
70              this.renderer = renderer;           * {@link Thread} will be started.
71              failed = false;           *
72          }           */
73            class RenderThread extends Thread {
74          /**  
75           * Called by the executor to run this rendering task.                  private final GTRenderer renderer;
76           *  
77           * @return result of the task: completed, cancelled or failed                  public RenderThread(final Rectangle paintArea,
78           * @throws Exception                                  final Graphics2D graphics, GTRenderer renderer,
79           */                                  AffineTransform worldToScreen, ReferencedEnvelope mapEnv) {
80          public TaskResult call() throws Exception {                          super(new RenderRun(paintArea, graphics, renderer, mapEnv,
81              if (!cancelled) {                                          worldToScreen));
82                                            this.renderer = renderer;
83                  try {  
84                      renderer.addRenderListener(this);                          setName("Render" + getName());
85                        
86                      Composite composite = graphics.getComposite();                          // System.out.println("starting render thread " + getName());
87                      //graphics.setComposite(AlphaComposite.Src);                  }
88                      //graphics.setBackground(Color.WHITE);  
89                      graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));                  public GTRenderer getRenderer() {
90                      graphics.fill(paintArea);                          return renderer;
91                      graphics.setComposite(composite);                  }
92    
93            }
94                      numFeatures = 0;  
95                      renderer.paint(graphics, mapPane.getVisibleRect(), envelope, mapPane.getWorldToScreenTransform());          /**
96             * This {@link Runnable} will actually start the rendering
97                  } finally {           */
98                      renderer.removeRenderListener(this);          class RenderRun implements Runnable, RenderListener {
99                  }                  private final Rectangle paintArea;
100              }                  private final Graphics2D graphics;
101                    private final AffineTransform worldToScreen;
102              if (cancelled) {                  private final GTRenderer renderer;
103                  return TaskResult.CANCELLED;                  private final ReferencedEnvelope mapEnv;
104              } else if (failed) {  
105                  return TaskResult.FAILED;                  public RenderRun(Rectangle paintArea, Graphics2D graphics,
106              } else {                                  GTRenderer renderer, ReferencedEnvelope mapEnv,
107                  return TaskResult.COMPLETED;                                  AffineTransform worldToScreen) {
108              }                          this.paintArea = paintArea;
109          }                          this.graphics = graphics;
110                            this.renderer = renderer;
111          /**                          this.mapEnv = mapEnv;
112           * Cancel the rendering task if it is running. If called before                          this.worldToScreen = worldToScreen;
113           * being run the task will be abandoned.                  }
114           */  
115          public synchronized void cancel() {                  @Override
116              if (isRunning()) {                  public void run() {
117                  cancelled = true;                          try {
118                  renderer.stopRendering();                                  renderer.addRenderListener(this);
119              }                                  System.out.println("start rendering...");
120          }                                  // try {
121                                    // Thread.sleep(1000);
122          /**                                  // } catch (InterruptedException e) {
123           * Called by the renderer when each feature is drawn.                                  // e.printStackTrace();
124           *                                  // }
125           * @param feature the feature just drawn  
126           */                                  // Clear the graphics context
127          public void featureRenderer(SimpleFeature feature) {                                  graphics.setBackground(mapPane.getMapBackgroundColor());
128              // @todo update a progress listener                                  graphics.clearRect(paintArea.x, paintArea.y, paintArea.width,
129              numFeatures++ ;                                                  paintArea.height);
130          }  
131                                    renderer.paint(graphics, paintArea, worldToScreen);
132          /**  
133           * Called by the renderer on error                                  // Kill the reference to this Thread so #isRunning will say
134           *                                  // false directly
135           * @param e cause of the error                                  renderThread = null;
136           */                                  mapPane.onRenderingCompleted();
137          public void errorOccurred(Exception e) {                          } catch (Exception e) {
138                  renderingException = e;                                  mapPane.onRenderingFailed(e);
139                  graphics.setColor(Color.white);                          } finally {
140                  graphics.drawString(e.getMessage(), 11, 11);                                  renderer.removeRenderListener(this);
141                  graphics.drawString(e.getMessage(), 9, 9);                          }
142                  graphics.setColor(Color.black);                  }
143                  graphics.drawString(e.getMessage(), 10, 10);  
144              failed = true;                  @Override
145          }                  public void errorOccurred(Exception e) {
146                            mapPane.onRenderingFailed(e);
147      }                  }
148    
149      private AtomicBoolean taskRunning;                  @Override
150      private Task task;                  public void featureRenderer(SimpleFeature feature) {
151      private Future<TaskResult> taskResult;                  }
152      private ScheduledFuture<?> watcher;  
153          private Exception renderingException;          }
154    
155      /**          /**
156       * Constructor. Creates a new executor to service the specified map pane.           * Ask to stop the rendering. May be called often.
157       *           */
158       * @param mapPane the map pane to be serviced          public void cancelTask() {
159       */                  if (renderThread != null && renderThread.isAlive()) {
160      public RenderingExecutor(final XMapPane mapPane) {                          // System.out.println("request stop for thread " +task.getName());
161          taskRunning = new AtomicBoolean(false);                          renderThread.getRenderer().stopRendering();
162          this.mapPane = mapPane;                  }
163          taskExecutor = Executors.newSingleThreadExecutor();          }
164          watchExecutor = Executors.newSingleThreadScheduledExecutor();  
165          pollingInterval = DEFAULT_POLLING_INTERVAL;          /**
166          cancelLatch = new CountDownLatch(0);           * @return <code>true</code> if the {@link Thread} is busy rendering.
167      }           */
168            public boolean isRunning() {
169      /**                  // if (task != null)
170       * Get the interval for polling the result of a rendering task                  // System.out.println("is running "+task.getName()+" = true");
171       *                  return (renderThread != null && renderThread.isAlive());
172       * @return polling interval in milliseconds          }
173       */  
174      public long getPollingInterval() {          /**
175          return pollingInterval;           * Will stop rendering and remove the reference to the {@link Thread}.
176      }           */
177            public void dispose() {
178      /**                  if (renderThread != null) {
179       * Set the interval for polling the result of a rendering task                          renderThread.renderer.stopRendering();
180       *                          renderThread = null;
181       * @param interval interval in milliseconds (values {@code <=} 0 are ignored)                  }
182       */          }
     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();  
                 }  
             }, DEFAULT_POLLING_INTERVAL, DEFAULT_POLLING_INTERVAL, 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;  
         }  
     }  
   
     public synchronized boolean isRunning() {  
         return taskRunning.get();  
     }  
   
     @Override  
     protected void finalize() throws Throwable {  
         if (this.isRunning()) {  
             taskExecutor.shutdownNow();  
             watchExecutor.shutdownNow();  
         }  
     }  
 }  
183    
184    }

Legend:
Removed from v.510  
changed lines
  Added in v.539

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26