/[schmitzm]/trunk/src/skrueger/geotools/XMapPane.java
ViewVC logotype

Diff of /trunk/src/skrueger/geotools/XMapPane.java

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

branches/1.0-gt2-2.6/src/gtmig/org/geotools/swing/XMapPane.java revision 529 by alfonx, Wed Nov 18 20:47:00 2009 UTC branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java revision 553 by alfonx, Mon Nov 23 21:39:17 2009 UTC
# Line 1  Line 1 
1  /*  package skrueger.geotools;
  *    GeoTools - OpenSource mapping toolkit  
  *    http://geotools.org  
  *    (C) 2002-2006, GeoTools Project Managment Committee (PMC)  
  *  
  *    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.  
  */  
 package gtmig.org.geotools.swing;  
   
 /**  
  * This class is 50% copied from GeoTools 2.6.x JMapPane. GeoTools is LGPL, SCHMITZM also.<br/>  
  * In addition to  
  */  
2    
3  import java.awt.Color;  import java.awt.Color;
4  import java.awt.Cursor;  import java.awt.Cursor;
# Line 41  import java.awt.geom.NoninvertibleTransf Line 21  import java.awt.geom.NoninvertibleTransf
21  import java.awt.geom.Point2D;  import java.awt.geom.Point2D;
22  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
23  import java.io.IOException;  import java.io.IOException;
24    import java.util.ArrayList;
25  import java.util.HashMap;  import java.util.HashMap;
26  import java.util.Map;  import java.util.Map;
27  import java.util.Vector;  import java.util.Vector;
28    
 import javax.swing.JPanel;  
29  import javax.swing.Timer;  import javax.swing.Timer;
30    
31  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
# Line 63  import org.geotools.referencing.CRS; Line 43  import org.geotools.referencing.CRS;
43  import org.geotools.renderer.GTRenderer;  import org.geotools.renderer.GTRenderer;
44  import org.geotools.renderer.label.LabelCacheImpl;  import org.geotools.renderer.label.LabelCacheImpl;
45  import org.geotools.renderer.lite.LabelCache;  import org.geotools.renderer.lite.LabelCache;
46    import org.geotools.renderer.lite.RendererUtilities;
47  import org.geotools.renderer.lite.StreamingRenderer;  import org.geotools.renderer.lite.StreamingRenderer;
48  import org.geotools.swing.JMapPane;  import org.geotools.swing.JMapPane;
49  import org.geotools.swing.event.MapMouseEvent;  import org.geotools.swing.event.MapMouseEvent;
# Line 78  import org.opengis.referencing.operation Line 59  import org.opengis.referencing.operation
59  import schmitzm.geotools.GTUtil;  import schmitzm.geotools.GTUtil;
60  import schmitzm.geotools.JTSUtil;  import schmitzm.geotools.JTSUtil;
61  import schmitzm.geotools.gui.SelectableXMapPane;  import schmitzm.geotools.gui.SelectableXMapPane;
62    import schmitzm.geotools.io.GeoImportUtil;
63  import schmitzm.geotools.map.event.JMapPaneListener;  import schmitzm.geotools.map.event.JMapPaneListener;
64  import schmitzm.geotools.map.event.MapLayerAdapter;  import schmitzm.geotools.map.event.MapLayerAdapter;
65  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
66    import schmitzm.swing.JPanel;
67  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
 import skrueger.geotools.RenderingExecutor;  
 import skrueger.swing.formatter.MbDecimalFormatter;  
68    
69  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
70  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
71  import com.vividsolutions.jts.geom.Geometry;  import com.vividsolutions.jts.geom.Geometry;
72    
73    /**
74     * The {@link XMapPane} class uses a Geotools {@link GTRenderer} to paint up to
75     * two {@link MapContext}s: a "local" {@link MapContext} and a "background"
76     * {@link MapContext}. The idea is, that rendering a background layer made up of
77     * e.g. OSM data, may take much longer than rendering local data.<br>
78     * Every {@link MapContext} is rendered on a {@link Thread} of it's own.
79     * Starting/ cancelling these threads is done by the {@link RenderingExecutor}.<br>
80     * <br>
81     * While the renderers are rending the map, a <br>
82     * The {@link XMapPane} is based on schmitzm {@link JPanel}, so
83     * {@link #print(Graphics)} will automatically set the background of components
84     * to pure white.
85     *
86     * The XMapPane has a {@link MouseListener} that manages zooming.<br>
87     * A logo/icon to float in the lower left corner may be set with
88     * {@link #setMapImage(BufferedImage)}<br>
89     *
90     * @see SelectableXMapPane - an extension of {@link XMapPane} that supports
91     *      selecting features.
92     *
93     * @author stefan
94     *
95     */
96  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
97    
98            private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
99            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;
100    
101          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private static Logger LOGGER = Logger.getLogger(XMapPane.class);
102    
103            private boolean acceptsRepaintCalls = true;
104    
105          /**          /**
106           * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},           * Main {@link MapContext} that holds all layers that are rendered into the
107           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.           * {@link #localImage} by the {@link #localRenderer}
          *  
          * @param layer  
          *            a layer  
          * @param selectable  
          *            if {@code false} the layer is ignored during the upper  
          *            mentioned actions. If <code>null</code>, the default (true)  
          *            will be used.  
108           */           */
109          public void setMapLayerSelectable(MapLayer layer, Boolean selectable) {          MapContext localContext;
                 if (selectable == null)  
                         mapLayerSelectable.remove(layer);  
                 else  
                         mapLayerSelectable.put(layer, selectable);  
         }  
110    
111          /**          /**
112           * Holds a flag for each layer, whether it is regarded or ignored on           * {@link MapContext} holding the background layers. Use it for layers that
113           * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}           * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
114           * actions.           * OSM...<br>
115             * <code>null</code> by default.
116             *
117             * @see #setBgContext(MapContext)
118             * @see #getBgContext()
119           */           */
120          final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();          MapContext bgContext;
121    
122          /**          /**
123           * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},           * While threads are working, calls {@link XMapPane#updateFinalImage()}
124           * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
125           * <code>true</code> if the selectability has not been defined.           * renderers have finished.
126           *           *
127           * @param layer           * @see INITIAL_REPAINT_DELAYAL
128           *            a layer           * @see #REPEATING_REPAINT_DELAY
129           */           */
130          public boolean isMapLayerSelectable(MapLayer layer) {          final private Timer repaintTimer;
                 Boolean selectable = mapLayerSelectable.get(layer);  
                 return selectable == null ? true : selectable;  
         }  
131    
132          /**          /**
133           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl           * The initial delay in milliseconds until the {@link #finalImage} is
134           * moeglich!           * updated the first time.
          *  
          * @see #setState(int)  
135           */           */
136          public static final int PAN = 1;          public static final int INITIAL_REPAINT_DELAY = 1000;
137    
138          /**          /**
139           * Flag fuer Modus "Heran zoomen".           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
140           *           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
141           * @see #setState(int)           * with previews.
          * @see #setState(int)  
142           */           */
143          public static final int ZOOM_IN = 2;          public static final int REPEATING_REPAINT_DELAY = 500;
144    
145          /**          /**
146           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * Default delay (milliseconds) before the map will be redrawn when resizing
147             * the pane. This is to avoid flickering while drag-resizing.
148           *           *
149           * @see #setState(int)           * @see #resizeTimer
150           */           */
151          public static final int ZOOM_OUT = 3;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
152    
153            private final Timer resizeTimer;
154    
155            public static final int NONE = -123;
156    
157          /**          /**
158           * Flag fuer Modus           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
159           * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".           * moeglich!
160           *           *
161           * @see #setState(int)           * @see #setState(int)
          * @see #setState(int)  
162           */           */
163          public static final int SELECT_TOP = 4;          public static final int PAN = 1;
164    
165          /**          /**
166           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
167           *           *
# Line 173  public class XMapPane extends JPanel { Line 177  public class XMapPane extends JPanel {
177           * @see #setState(int)           * @see #setState(int)
178           */           */
179          public static final int SELECT_ONE_FROM_TOP = 104;          public static final int SELECT_ONE_FROM_TOP = 104;
   
180          /**          /**
181           * While threads are working, we call {@link XMapPane#updateFinalImage()}           * Flag fuer Modus
182           * regularly and repaint(). This {@link Timer} is stopped when all renderers           * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
183           * have finished.           *
184             * @see #setState(int)
185             * @see #setState(int)
186           */           */
187          final private Timer repainterTimer;          public static final int SELECT_TOP = 4;
188    
189          /**          public static final Cursor WAIT_CURSOR = Cursor
190           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,                          .getPredefinedCursor(Cursor.WAIT_CURSOR);
          * the {@link #repainterTimer} is regularly updating the {@link #finalImage}  
          * with previews.  
          */  
         public static final long REPEATING_REPAINT_DELAY = 500;  
191    
192          /**          /**
193           * The initial delay in milliseconds until the {@link #finalImage} is           * {@link Font} used to paint the wait messages into the map
194           * updated the first time.           *
195             * @see #addGadgets(Graphics2D, boolean)
196           */           */
197          public static final long INITIAL_REPAINT_DELAY = 1000;          final static Font waitFont = new Font("Arial", Font.BOLD, 30);
   
         protected RenderingExecutor bgExecuter;  
198    
199          /**          /**
200           * the map context to render           * {@link Font} used to paint error messages into the map
201           */           *
202          MapContext localContext;           * @see #addGadgets(Graphics2D, boolean)
         /**  
          * the map context to render  
203           */           */
204          MapContext bgContext;          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
205    
206          /**          /**
207           * the area of the map to draw           * The wait message painted into the map while rendering is going on on
208             * another thread.
209             *
210             * @see #addGadgets(Graphics2D, boolean)
211           */           */
212          protected Envelope mapArea = null;          final String waitMsg = SwingUtil.R("WaitMess");
         /**  
          * We store the old mapArea for a moment to use it for the  
          * "quick scaled preview" in case of ZoomOut  
          **/  
         protected Envelope oldMapArea = null;  
213    
214          /**          /**
215           * compass and icon are rendered into this image           * Flag fuer Modus "Heran zoomen".
216             *
217             * @see #setState(int)
218             * @see #setState(int)
219           */           */
220          // protected BufferedImage gadgetsImage;          public static final int ZOOM_IN = 2;
221    
222          /**          /**
223           * The default state is ZOOM_IN, hence by default the           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
224           * {@link #zoomMapPaneMouseListener} is also enabled.           *
225           **/           * @see #setState(int)
226          private int state = ZOOM_IN;           */
227            public static final int ZOOM_OUT = 3;
228    
229          /**          /**
230           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
# Line 233  public class XMapPane extends JPanel { Line 233  public class XMapPane extends JPanel {
233           * @param e           * @param e
234           *            Maus-Ereignis           *            Maus-Ereignis
235           */           */
236          public static Point2D getMapCoordinatesFromEvent(MouseEvent e) {          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {
237                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
238                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
239                          try {                          try {
240                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();
241                          } catch (Exception err) {                          } catch (final Exception err) {
242                                  LOGGER                                  LOGGER
243                                                  .error(                                                  .error(
244                                                                  "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",                                                                  "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
# Line 253  public class XMapPane extends JPanel { Line 253  public class XMapPane extends JPanel {
253                          if (!xMapPane.isWellDefined())                          if (!xMapPane.isWellDefined())
254                                  return null;                                  return null;
255    
256                          AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
257                          if (at != null)                          if (at != null)
258                                  return at.transform(e.getPoint(), null);                                  return at.transform(e.getPoint(), null);
259                          return null;                          return null;
# Line 263  public class XMapPane extends JPanel { Line 263  public class XMapPane extends JPanel {
263          }          }
264    
265          /**          /**
266             * Listens to changes of the "background" {@link MapContext} and triggers
267             * repaints where needed.
268             */
269            private final MapLayerListListener bgContextListener = new MapLayerListListener() {
270    
271                    @Override
272                    public void layerAdded(final MapLayerListEvent event) {
273                            MapLayer layer = event.getLayer();
274                            layer.addMapLayerListener(bgMapLayerListener);
275                            requestStartRendering();
276    
277                    }
278    
279                    @Override
280                    public void layerChanged(final MapLayerListEvent event) {
281                            requestStartRendering();
282                    }
283    
284                    @Override
285                    public void layerMoved(final MapLayerListEvent event) {
286                            requestStartRendering();
287                    }
288    
289                    @Override
290                    public void layerRemoved(final MapLayerListEvent event) {
291                            if (event.getLayer() != null)
292                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
293                            requestStartRendering();
294                    }
295            };
296    
297            /**
298             * This {@link RenderingExecutor} manages the creation and cancellation of
299             * up to one {@link Thread} for rendering the {@link #localContext}.
300             */
301            private final RenderingExecutor localExecuter = new RenderingExecutor(this);
302    
303            /**
304             * This {@link RenderingExecutor} manages the creation and cancellation of
305             * up to one {@link Thread} for rendering the {@link #bgContext}.
306             */
307            protected RenderingExecutor bgExecuter;
308    
309            /**
310             * The {@link #localRenderer} for the {@link #localContext} uses this
311             * {@link Image}.
312             */
313            private BufferedImage localImage;
314    
315            /**
316             * The {@link #bgRenderer} for the {@link #bgContext} uses this
317             * {@link Image}.
318             */
319            private BufferedImage bgImage;
320    
321            /**
322             * This {@link Image} is a merge of the {@link #bgImage},
323             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
324             * updated with {@link #updateFinalImage()} and used for painting in
325             * {@link #paintComponent(Graphics)}
326             */
327            private BufferedImage finalImage;
328    
329            /**
330             * Optionally a transparent image to paint over the map in the lower right
331             * corner.
332             *
333             * @see #addGadgets(Graphics2D)
334             * @see #setMapImage(BufferedImage)
335             **/
336            private BufferedImage mapImage = null;
337    
338            /**
339             * Listens to each layer in the local {@link MapContext} for changes and
340             * triggers repaints.
341             */
342            protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
343    
344                    @Override
345                    public void layerChanged(final MapLayerEvent event) {
346                            requestStartRendering();
347                    }
348    
349                    @Override
350                    public void layerHidden(final MapLayerEvent event) {
351                            requestStartRendering();
352                    }
353    
354                    @Override
355                    public void layerShown(final MapLayerEvent event) {
356                            requestStartRendering();
357                    }
358            };
359    
360            /**
361             * A flag indicating if dispose() was already called. If true, then further
362             * use of this {@link SelectableXMapPane} is undefined.
363             */
364            private boolean disposed = false;
365    
366            /**
367             * While dragging, the {@link #updateFinalImage()} method is translating the
368             * cached images while setting it together.
369             **/
370            Point imageOrigin = new Point(0, 0);
371            /**
372             * For every rendering thread started,
373             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
374             * renderer. These Java2D rendering hints are passed to the
375             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
376             * and local).
377             */
378            private RenderingHints java2dHints;
379    
380            protected LabelCache labelCache = new LabelCacheImpl();
381    
382            /**
383             * Listens to changes of the "local" {@link MapContext} and triggers
384             * repaints where needed.
385             */
386            private final MapLayerListListener localContextListener = new MapLayerListListener() {
387    
388                    @Override
389                    public void layerAdded(final MapLayerListEvent event) {
390                            event.getLayer().addMapLayerListener(localMapLayerListener);
391    
392                            localRenderer.setContext(getMapContext());
393                            requestStartRendering();
394    
395                    }
396    
397                    @Override
398                    public void layerChanged(final MapLayerListEvent event) {
399                            localRenderer.setContext(getMapContext());
400                            requestStartRendering();
401                    }
402    
403                    @Override
404                    public void layerMoved(final MapLayerListEvent event) {
405                            localRenderer.setContext(getMapContext());
406                            requestStartRendering();
407                    }
408    
409                    @Override
410                    public void layerRemoved(final MapLayerListEvent event) {
411                            if (event.getLayer() != null)
412                                    event.getLayer().removeMapLayerListener(localMapLayerListener);
413                            localRenderer.setContext(getMapContext());
414                            requestStartRendering();
415                    }
416            };
417    
418            /**
419             * Listens to each layer in the local {@link MapContext} for changes and
420             * triggers repaints.
421             */
422            protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
423    
424                    @Override
425                    public void layerChanged(final MapLayerEvent event) {
426                            localRenderer.setContext(getMapContext()); // betters for SLD changes?!
427                            requestStartRendering();
428                    }
429    
430                    @Override
431                    public void layerHidden(final MapLayerEvent event) {
432                            requestStartRendering();
433                    }
434    
435                    @Override
436                    public void layerShown(final MapLayerEvent event) {
437                            requestStartRendering();
438                    }
439            };
440    
441            private final GTRenderer localRenderer = GTUtil.createGTRenderer();
442    
443            private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
444    
445            /**
446             * the area of the map to draw
447             */
448            protected Envelope mapArea = null;
449    
450            /**
451             * A flag set it {@link #setMapArea(Envelope)} to indicated the
452             * {@link #paintComponent(Graphics)} method, that the image on-screen is
453             * associated with {@link #oldMapArea} and may hence be scaled for a quick
454             * preview.<br>
455             * The flag is reset
456             **/
457            private boolean mapAreaChanged = false;
458    
459            /**
460             * This color is used as the default background color when painting a map.
461             */
462            private Color mapBackgroundColor = Color.WHITE;
463    
464            /**
465           * A flag indicating that the shown image is invalid and needs to be           * A flag indicating that the shown image is invalid and needs to be
466           * re-rendered.           * re-rendered.
467           */           */
468          protected boolean mapImageInvalid = true;          protected boolean mapImageInvalid = true;
469    
470          protected LabelCache labelCache = new LabelCacheImpl();          /**
471             * Holds a flag for each layer, whether it is regarded or ignored on
472             * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
473             * actions.
474             */
475            final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
476    
477          /**          /**
478             * List of listeners of this {@link XMapPane}
479             */
480            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
481            /**
482           * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan           * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
483           * out of that area           * out of that area
484           **/           **/
485          private Envelope maxExtend = null;          private Envelope maxExtend = null;
   
486          private Double maxZoomScale = Double.MIN_VALUE;          private Double maxZoomScale = Double.MIN_VALUE;
487    
488          private Double minZoomScale = Double.MAX_VALUE;          private Double minZoomScale = Double.MAX_VALUE;
489    
490          /**          /**
491           * This color is used as the default background color when painting a map.           * We store the old mapArea for a moment to use it for the
492           */           * "quick scaled preview" in case of ZoomOut
493          private Color mapBackgroundColor = Color.WHITE;           **/
494            protected Envelope oldMapArea = null;
495    
496          /**          /**
497           * This {@link MouseListener} is managing all zoom related tasks           * We store the old transform for a moment to use it for the
498           */           * "quick scaled preview" in case of ZoomIn
499          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(           **/
500                          this);          protected AffineTransform oldScreenToWorld = null;
501    
502          /**          /**
503           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
# Line 296  public class XMapPane extends JPanel { Line 505  public class XMapPane extends JPanel {
505           **/           **/
506          protected boolean paneResized = false;          protected boolean paneResized = false;
507    
508            private BufferedImage preFinalImage;
509    
510            // if null, no quick preview will be shown
511            private int quickPreviewHint = 0;
512    
513            private Map<Object, Object> rendererHints = GTUtil
514                            .getDefaultGTRendererHints(localRenderer);
515    
516            /**
517             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
518             * start rendering {@link Thread}s
519             **/
520            private volatile Boolean requestStartRendering = false;
521    
522            /**
523             * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
524             * (lat/lon)
525             */
526            protected AffineTransform screenToWorld = null;
527    
528          /**          /**
529           * The flag {@link #requestStartRendering} can be set to true by events.           * The flag {@link #requestStartRendering} can be set to true by events.
530           * This {@link Timer} checks the flag regularly and starts one renderer           * This {@link Timer} checks the flag regularly and starts one renderer
# Line 303  public class XMapPane extends JPanel { Line 532  public class XMapPane extends JPanel {
532           */           */
533          final private Timer startRenderThreadsTimer;          final private Timer startRenderThreadsTimer;
534    
535          private Map<Object, Object> rendererHints;          /**
536             * The default state is ZOOM_IN, hence by default the
537             * {@link #zoomMapPaneMouseListener} is also enabled.
538             **/
539            private int state = ZOOM_IN;
540    
541          public Map<Object, Object> getRendererHints() {          /**
542                  return rendererHints;           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
543          }           * MapPane-Funktion
544             */
545            protected Cursor staticCursor = null;
546    
547            private AffineTransform worldToScreen;
548    
549          /**          /**
550           * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot gemacht           * This {@link MouseListener} is managing all zoom related tasks
          * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
551           */           */
552          @Override          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
553          public void print(Graphics g) {                          this);
                 Color orig = getBackground();  
                 setBackground(Color.WHITE);  
554    
555                  // wrap in try/finally so that we always restore the state          /** Is set if a renderer has an error **/
556                  try {          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
557                          super.print(g);          
558                  } finally {          /** If <code>true</code>, then rendering exceptions are rendererd into the map pane **/
559                          setBackground(orig);          private boolean showExceptions= false;
560                  }  
561            // /** If {@link #getVisibleRect()} of this {@link JPanel} is not yet
562            // defined, but we are **/
563            // private Envelope mapAreaCondidate = null;
564    
565            public XMapPane() {
566                    this(null, null);
567          }          }
568    
569          /**          /**
570           * full constructor extending JPanel           * full constructor extending JPanel
571           *           *
572           * @param rendererHints           * @param rendererHints
573             *            may be <code>null</code>. Otherwise a {@link Map<Object,
574             *            Object>} of {@link RenderingHints} to override the default
575             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
576           *           *
          * @param layout  
          *            - layout (probably shouldn't be set)  
          * @param isDoubleBuffered  
          *            - a Swing thing I don't really understand  
          * @param render  
          *            - what to draw the map with  
577           * @param localContext           * @param localContext
578           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
579             *            empty {@link DefaultMapContext} will be created.
580           */           */
581          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
582                          Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
583                  super(true);                  super(true);
584    
585                  setRendererHints(rendererHints);                  setRendererHints(rendererHints);
586    
587                  setOpaque(true);                  setOpaque(true);
588    
                 localRenderer = GTUtil.createGTRenderer();  
                 localRenderer.setJava2DHints(getJava2dHints());  
   
589                  if (localContext_ != null)                  if (localContext_ != null)
590                          setLocalContext(localContext_);                          setLocalContext(localContext_);
591    
# Line 371  public class XMapPane extends JPanel { Line 603  public class XMapPane extends JPanel {
603                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
604                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
605                   */                   */
606                  resizingPaintDelay = DEFAULT_RESIZING_PAINT_DELAY;                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
607                  resizeTimer = new Timer(resizingPaintDelay, new ActionListener() {                                  new ActionListener() {
   
                         public void actionPerformed(ActionEvent e) {  
                                 paneResized = true;  
   
                                 if (!isWellDefined())  
                                         return;  
   
                                 Rectangle bounds = getVisibleRect();  
   
                                 Envelope geoMapArea = tranformWindowToGeo(bounds.x, bounds.y,  
                                                 bounds.x + bounds.width, bounds.y + bounds.height);  
608    
609                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          public void actionPerformed(final ActionEvent e) {
610                          }                                                  if (!isWellDefined())
611                  });                                                          return;
612    
613                                                    final Rectangle bounds = getVisibleRect();
614                                                    //
615                                                    // System.out.println("\n\ntimer performs with bounds = "
616                                                    // + bounds);
617    
618                                                    final Envelope geoMapArea = tranformWindowToGeo(
619                                                                    bounds.x, bounds.y, bounds.x + bounds.width,
620                                                                    bounds.y + bounds.height);
621    
622                                                    if (setMapArea(geoMapArea))
623                                                            paneResized = true;
624                                                    // else
625                                                    // syso
626                                            }
627                                    });
628                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
629    
630                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
631    
632                          @Override                          @Override
633                          public void componentResized(ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
634    
635                                    // Already cancel the tasks...
636                                  if (bgExecuter != null)                                  if (bgExecuter != null)
637                                          bgExecuter.cancelTask();                                          bgExecuter.cancelTask();
638                                  if (localExecuter != null)                                  if (localExecuter != null)
639                                          localExecuter.cancelTask();                                          localExecuter.cancelTask();
640    
641                                  resizeTimer.restart();                                  resizeTimer.restart();
642                          }                          }
643    
644                  });                  });
645    
646                  repainterTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  /*
647                                  new ActionListener() {                   * Setting up the repaintTimer. Not started automatically.
648                     */
649                    repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
650    
651                                          @Override                          @Override
652                                          public void actionPerformed(ActionEvent e) {                          public void actionPerformed(final ActionEvent e) {
653                                                  updateFinalImage();                                  if ((localExecuter != null && !localExecuter.isRunning())
654                                                  XMapPane.this.repaint();                                                  && (bgExecuter != null && !bgExecuter.isRunning())) {
655                                          }                                          repaintTimer.stop();
656                                  });                                  } else {
657                  repainterTimer.setInitialDelay(300);                                          updateFinalImage();
658                  repainterTimer.setRepeats(true);                                          XMapPane.this.repaint(100);
659                                    }
660                            }
661                    });
662                    repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
663                    repaintTimer.setRepeats(true);
664    
665                    /*
666                     * Setting up the startRenderThreadsTimer. This Timer starts
667                     * automatically.
668                     */
669                  startRenderThreadsTimer = new Timer(100, new ActionListener() {                  startRenderThreadsTimer = new Timer(100, new ActionListener() {
670    
671                          @Override                          @Override
672                          public void actionPerformed(ActionEvent e) {                          public void actionPerformed(final ActionEvent e) {
673                                  synchronized (requestStartRendering) {                                  synchronized (requestStartRendering) {
674                                          if (requestStartRendering && isWellDefined()) {                                          if (requestStartRendering && isWellDefined()) {
675    
676                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
677                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
678                                                  } else {                                                  } else {
679    
680                                                            // Stupidly, but we have to recheck the
681                                                            setMapArea(getMapArea());
682                                                          requestStartRendering = false;                                                          requestStartRendering = false;
683                                                          startRendering();                                                          startRendering();
684                                                  }                                                  }
# Line 435  public class XMapPane extends JPanel { Line 690  public class XMapPane extends JPanel {
690    
691          }          }
692    
693          // TODO doku          /**
694          public XMapPane() {           * Fuegt der Map einen Listener hinzu.
695                  this(null, null);           *
696             * @param l
697             *            neuer Listener
698             */
699            public void addMapPaneListener(final JMapPaneListener l) {
700                    mapPaneListeners.add(l);
701          }          }
702    
703          /**          /**
704           * Sets the mapArea to best possibly present the given features. If only one           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
705           * single point is given, the window is moved over the point.           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
706           *           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
707           * Note: The method does not call {@link #repaint()} on the           * Since 21. April 09: Before thecalculation starts, the aspect ratio is
708           * {@link SelectableXMapPane} .           * corrected. This change implies, that setMapArea() will most of the time
709             * not allow setting to a wrong aspectRatio.
710           *           *
711           * @param features           * @author <a href="mailto:[email protected]">Stefan Alfons
712           *            if <code>null</code> or size==0, the function doesn nothing.           *         Kr&uuml;ger</a>
713           */           */
714          public void zoomTo(          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
                         FeatureCollection<SimpleFeatureType, SimpleFeature> features) {  
715    
716                  CoordinateReferenceSystem mapCRS = getContext()                  if (getWidth() == 0)
717                                  .getCoordinateReferenceSystem();                          return env;
                 CoordinateReferenceSystem fCRS = features.getSchema()  
                                 .getGeometryDescriptor().getCoordinateReferenceSystem();  
718    
719                  double width = mapArea.getWidth();                  if (env == null)
720                  double height = mapArea.getHeight();                          return null;
                 double ratio = height / width;  
721    
722                  if (features == null || features.size() == 0) {                  Envelope newArea = null;
                         // feature count == 0 Zoom to the full extend  
                         return;  
                 } else if (features.size() == 1) {  
723    
724                          // feature count == 1 Just move the window to the point and zoom 'a                  /**
725                          // bit'                   * Correct the aspect Ratio before we check the rest. Otherwise we might
726                          SimpleFeature singleFeature = (SimpleFeature) features.iterator()                   * easily fail. We allow to grow here, because we don't check against
727                                          .next();                   * the maxExtend
728                     */
729                    final Rectangle curPaintArea = getVisibleRect();
730    
731                          if (((Geometry) singleFeature.getDefaultGeometry())                  env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
732                                          .getCoordinates().length > 1) {  
733                                  // System.out.println("Zoomed to only pne poylgon");                  final double scale = env.getWidth() / getWidth();
734                                  // Poly                  final double centerX = env.getMinX() + env.getWidth() / 2.;
735                                  // TODO max width vs. height                  final double centerY = env.getMinY() + env.getHeight() / 2.;
736                                  width = features.getBounds().getWidth() * 3;                  double newWidth2 = 0;
737                                  height = ratio * width;                  double newHeight2 = 0;
738                          } else {                  if (scale < getMaxZoomScale()) {
739                                  // System.out.println("Zoomed in a bit becasue only one point");                          // ****************************************************************************
740                                  // width *= .9;                          // Wir zoomen weiter rein als erlaubt => Anpassen des envelope
741                                  // height *= .9;                          // ****************************************************************************
742                            newWidth2 = getMaxZoomScale() * getWidth() / 2.;
743                            newHeight2 = getMaxZoomScale() * getHeight() / 2.;
744                    } else if (scale > getMinZoomScale()) {
745                            // ****************************************************************************
746                            // Wir zoomen weiter raus als erlaubt => Anpassen des envelope
747                            // ****************************************************************************
748                            newWidth2 = getMinZoomScale() * getWidth() / 2.;
749                            newHeight2 = getMinZoomScale() * getHeight() / 2.;
750                    } else {
751                            // ****************************************************************************
752                            // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen
753                            // ****************************************************************************
754                            newArea = env;
755                    }
756    
757                    if (newArea == null) {
758    
759                            final Coordinate ll = new Coordinate(centerX - newWidth2, centerY
760                                            - newHeight2);
761                            final Coordinate ur = new Coordinate(centerX + newWidth2, centerY
762                                            + newHeight2);
763    
764                            newArea = new Envelope(ll, ur);
765                    }
766    
767                    final Envelope maxAllowedExtend = getMaxExtend();
768                    
769                    while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
770                                    && newArea != null && !newArea.isNull()
771                                    && !Double.isNaN(newArea.getMinX())
772                                    && !Double.isNaN(newArea.getMaxX())
773                                    && !Double.isNaN(newArea.getMinY())
774                                    && !Double.isNaN(newArea.getMaxY())) {
775                            /*
776                             * If a maxExtend is set, we have to honour that...
777                             */
778    
779                            // Exceeds top? Move down and maybe cut
780                            if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
781                                    final double divY = newArea.getMaxY()
782                                                    - maxAllowedExtend.getMaxY();
783                                    // LOGGER.debug("Moving area down by " + divY);
784    
785                                    newArea = new Envelope(new Coordinate(newArea.getMinX(),
786                                                    newArea.getMinY() - divY), new Coordinate(newArea
787                                                    .getMaxX(), newArea.getMaxY() - divY));
788    
789                                    if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
790                                            // LOGGER.debug("Now it exeeds the bottom border.. cut!");
791                                            // And cut the bottom if it moved out of the area
792                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
793                                                            maxAllowedExtend.getMinY()), new Coordinate(newArea
794                                                            .getMaxX(), newArea.getMaxY()));
795    
796                                            // LOGGER.debug("and fix aspect ratio");
797    
798                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
799                                                            new ReferencedEnvelope(newArea, env
800                                                                            .getCoordinateReferenceSystem()), false);
801                                    }
802                          }                          }
803    
804                          Coordinate centre = features.getBounds().centre();                          // Exceeds bottom? Move up and maybe cut
805                          if (!mapCRS.equals(fCRS)) {                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
806                                  // only to calculations if the CRS differ                                  final double divY = newArea.getMinY()
807                                  try {                                                  - maxAllowedExtend.getMinY();
808                                          MathTransform fToMap;                                  // LOGGER.debug("Moving area up by " + divY);
809                                          fToMap = CRS.findMathTransform(fCRS, mapCRS);  
810                                          // centre is transformed to the mapCRS                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
811                                          centre = JTS.transform(centre, null, fToMap);                                                  newArea.getMinY() - divY), new Coordinate(newArea
812                                  } catch (FactoryException e) {                                                  .getMaxX(), newArea.getMaxY() - divY));
813                                          LOGGER.error("Looking for a Math transform", e);  
814                                  } catch (TransformException e) {                                  if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
815                                          LOGGER.error("Looking for a Math transform", e);                                          // LOGGER.debug("Now it exeeds the top border.. cut!");
816                                            // And cut the bottom if it moved out of the area
817                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
818                                                            newArea.getMinY()), new Coordinate(newArea
819                                                            .getMaxX(), maxAllowedExtend.getMaxY()));
820    
821                                            // LOGGER.debug("and fix aspect ratio");
822    
823                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
824                                                            new ReferencedEnvelope(newArea, env
825                                                                            .getCoordinateReferenceSystem()), false);
826                                  }                                  }
827                          }                          }
828    
829                          Coordinate newLeftBottom = new Coordinate(centre.x - width / 2.,                          // Exceeds to the right? move and maybe cut
830                                          centre.y - height / 2.);                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
                         Coordinate newTopRight = new Coordinate(centre.x + width / 2.,  
                                         centre.y + height / 2.);  
831    
832                          Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);                                  // Move left..
833                                    final double divX = newArea.getMaxX()
834                                                    - maxAllowedExtend.getMaxX();
835                                    // LOGGER.debug("Moving area left by " + divX);
836    
837                          setMapArea(newMapArea);                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
838                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
839                                                    - divX, newArea.getMaxY()));
840    
841                  } else {                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
842                          ReferencedEnvelope fBounds = features.getBounds();                                          // LOGGER.debug("Now it exeeds the left border.. cut!");
843                                            // And cut the left if it moved out of the area
844                                            newArea = new Envelope(new Coordinate(maxAllowedExtend
845                                                            .getMinX(), newArea.getMinY()), new Coordinate(
846                                                            newArea.getMaxX(), newArea.getMaxY()));
847    
848                          Envelope bounds;                                          // LOGGER.debug("and fix aspect ratio");
849                          if (!mapCRS.equals(fCRS)) {  
850                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
851                          } else {                                                          new ReferencedEnvelope(newArea, env
852                                  bounds = fBounds;                                                                          .getCoordinateReferenceSystem()), false);
853                                    }
854                          }                          }
                         // BB umrechnen von Layer-CRS in Map-CRS  
855    
856                          // Expand a bit                          // Exceeds to the left? move and maybe cut
857                          bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
858    
859                          setMapArea(bounds);                                  // Move right..
860                                    final double divX = newArea.getMinX()
861                                                    - maxAllowedExtend.getMinX();
862                                    // LOGGER.debug("Moving area right by " + divX);
863    
864                                    newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
865                                                    newArea.getMinY()), new Coordinate(newArea.getMaxX()
866                                                    - divX, newArea.getMaxY()));
867    
868                                    if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
869                                            // LOGGER.debug("Now it exeeds the right border.. cut!");
870                                            // And cut the left if it moved out of the area
871                                            newArea = new Envelope(new Coordinate(newArea.getMinX(),
872                                                            newArea.getMinY()), new Coordinate(maxAllowedExtend
873                                                            .getMaxX(), newArea.getMaxY()));
874    
875                                            // LOGGER.debug("and fix aspect ratio");
876    
877                                            newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
878                                                            new ReferencedEnvelope(newArea, env
879                                                                            .getCoordinateReferenceSystem()), false);
880                                    }
881                            }
882                  }                  }
         }  
883    
884          private void setRendererHints(Map<Object, Object> rendererHints) {                  return new ReferencedEnvelope(newArea, env
885                  this.rendererHints = rendererHints;                                  .getCoordinateReferenceSystem());
886          }          }
887    
888          /**          /**
889           * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the           * Should be called when the {@link JMapPane} is not needed no more to help
890           * {@link XMapPane} is visible and has bounds set.           * the GarbageCollector
891             *
892             * Removes all {@link JMapPaneListener}s that are registered
893             *
894             * @author <a href="mailto:[email protected]">Stefan Alfons
895             *         Kr&uuml;ger</a>
896           */           */
897          public boolean isWellDefined() {          public void dispose() {
898                    if (isDisposed())
899                            return;
900    
901                  try {                  setPainting(false);
902    
903                          if (getContext() == null)                  resizeTimer.stop();
904                                  return false;                  startRenderThreadsTimer.stop();
905                          if (getContext().getLayerCount() <= 0)  
906                                  return false;                  disposed = true;
907                          if (getMapArea() == null)  
908                                  return false;                  if (bgExecuter != null) {
909                          if (getBounds().getWidth() == 0)                          bgExecuter.cancelTask();
910                                  return false;                          bgExecuter.dispose();
                         if (getBounds().getHeight() == 0)  
                                 return false;  
                 } catch (Exception e) {  
                         return false;  
911                  }                  }
                 return true;  
         }  
912    
913          /**                  if (localExecuter != null) {
914           * Default delay (milliseconds) before the map will be redrawn when resizing                          int i = 0;
915           * the pane. This is to avoid flickering while drag-resizing.                          localExecuter.cancelTask();
916           */                          while (i++ < 10 && localExecuter.isRunning()) {
917          public static final int DEFAULT_RESIZING_PAINT_DELAY = 500; // delay in                                  try {
918          // milliseconds                                          Thread.sleep(200);
919                                    } catch (final InterruptedException e) {
920                                            LOGGER
921                                                            .warn(
922                                                                            "while XMapPane we are waiting for the localExcutor to stop",
923                                                                            e);
924                                    }
925                            }
926                            if (localExecuter.isRunning()) {
927                                    LOGGER
928                                                    .warn("localExecutor Thread still running after 2s! Continuing anyways...");
929                            }
930                            localExecuter.dispose();
931                    }
932    
933          private Timer resizeTimer;                  disposeImages();
         private int resizingPaintDelay;  
         /**  
          * We store the old transform for a moment to use it for the  
          * "quick scaled preview" in case of ZoomIn  
          **/  
         protected AffineTransform oldScreenToWorld = null;  
934    
935          /**                  // Remove all mapPaneListeners that have registered with us
936           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen                  mapPaneListeners.clear();
          * MapPane-Funktion  
          */  
         protected Cursor staticCursor = null;  
937    
938          /**                  removeMouseMotionListener(zoomMapPaneMouseListener);
939           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,                  removeMouseListener(zoomMapPaneMouseListener);
          * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor  
          * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion  
          * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann  
          * {@code null} als Parameter uebergeben werden  
          *  
          * @param cursor  
          *            Cursor  
          */  
         public void setStaticCursor(Cursor cursor) {  
                 this.staticCursor = cursor;  
                 if (cursor != null)  
                         super.setCursor(cursor);  
         }  
940    
941          /**                  if (localContext != null)
942           * Liefert den statisch eingestellten Cursor, der unabhaengig von der                          getMapContext().clearLayerList();
943           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.                  if (bgContext != null)
944           *                          getBgContext().clearLayerList();
945           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der  
946           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.                  removeAll();
          */  
         public Cursor getStaticCursor() {  
                 return this.staticCursor;  
947          }          }
948    
949          /**          /**
950           * Abhaengig von selState wird der Cursor gesetzt           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
951             * given point. All in screen coordinates.
952           */           */
953          public void updateCursor() {          protected void drawRectangle(final Graphics graphics, final Point startPos,
954                            final Point e) {
955    
956                  if (bgExecuter != null && bgExecuter.isRunning()                  if (!isWellDefined())
                                 || localExecuter != null && localExecuter.isRunning()) {  
                         setCursor(WAIT_CURSOR);  
957                          return;                          return;
                 } else {  
                         // Allow one last rendering  
                         if (repainterTimer.isRunning()) {  
                                 repainterTimer.stop();  
                                 updateFinalImage();  
                                 repaint();  
                         }  
                 }  
958    
959                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig                  // undraw last box/draw new box
960                  // von der aktuellen Aktion                  final int left = Math.min(startPos.x, e.x);
961                  if (this.staticCursor != null) {                  final int right = Math.max(startPos.x, e.x);
962                          setCursor(staticCursor);                  final int top = Math.max(startPos.y, e.y);
963                          return;                  final int bottom = Math.min(startPos.y, e.y);
964                  }                  final int width = right - left;
965                  if (getCursor() == SwingUtil.PANNING_CURSOR) {                  final int height = top - bottom;
966                          // This cursor will reset itself  
967                    if (width == 0 && height == 0)
968                          return;                          return;
                 }  
969    
970                  // Je nach Aktion den Cursor umsetzen                  graphics.setXORMode(Color.WHITE);
971                  switch (state) {                  graphics.drawRect(left, bottom, width, height);
                 case SELECT_TOP:  
                 case SELECT_ONE_FROM_TOP:  
                 case SELECT_ALL:  
                         setCursor(SwingUtil.CROSSHAIR_CURSOR);  
                         break;  
                 case ZOOM_IN:  
                         setCursor(SwingUtil.ZOOMIN_CURSOR);  
                         break;  
                 case ZOOM_OUT:  
                         setCursor(SwingUtil.ZOOMOUT_CURSOR);  
                         break;  
                 case PAN:  
                         setCursor(SwingUtil.PAN_CURSOR);  
                         break;  
                 default:  
                         setCursor(normalCursor);  
                         break;  
                 }  
972          }          }
973    
         //  
         // /**  
         // * Gibt den "normalen" Cursor zurueck. Dieser kann neben dem "pointer"  
         // auch  
         // * ein Sanduhr-Wartecursor sein.  
         // *  
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
         // */  
         // public Cursor getNormalCursor() {  
         // return normalCursor;  
         // }  
         //  
         // /**  
         // * Setzt den "normalen" Cursor. Dieser kann neben dem default "pointer"  
         // z.B.  
         // * auch ein Sanduhr-Wartecursor sein.  
         // *  
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
         // */  
         // public void setNormalCursor(Cursor normalCursor) {  
         // this.normalCursor = normalCursor;  
         // }  
   
974          /**          /**
975           * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
976           * neu.           * to give the user something to look at while we are rendering. Method
977             * should be called after {@link #setMapArea(Envelope)} has been set to the
978             * new mapArea and transform has been reset.<br>
979             *
980             * @param g
981             *            Graphics2D to paint the preview into
982             *
983             * @param state
984             *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
985           */           */
986          protected void resetTransforms() {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
                 if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)  
                         return;  
987    
988                  // We store the last Transform                  // if (1 == 1)return false;
                 oldScreenToWorld = screenToWorld;  
989    
990                  this.screenToWorld = new AffineTransform(                  if (quickPreviewHint == 0)
991                  // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten                          return false;
                                 // nach rechts (Osten) hin groesser  
                                 // --> positive Verschiebung  
                                 getMapArea().getWidth() / getWidth(),  
                                 // keine Verzerrung  
                                 0.0, 0.0,  
                                 // Waehrend die Fenster-Koordinaten nach unten hin groesser  
                                 // werden,  
                                 // werden Latitude-Koordinaten nach Sueden hin keiner  
                                 // --> negative Verschiebung  
                                 -getMapArea().getHeight() / getHeight(),  
                                 // Die Longitude-Koordinaten werden nach Osten hin groesser  
                                 // --> obere linke Ecke des Fensters hat also den Minimalwert  
                                 getMapArea().getMinX(),  
                                 // Die Latitude-Koordinaten werden nach Norden hin groesser  
                                 // --> obere linke Ecke des Fensters hat also den Maximalwert  
                                 getMapArea().getMaxY());  
992    
993                  try {                  graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
994                          this.worldToScreen = screenToWorld.createInverse();                                  RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
995                  } catch (NoninvertibleTransformException e) {                  graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
996                          LOGGER.error(e);                                  RenderingHints.VALUE_ANTIALIAS_OFF);
997                  }                  graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
998          }                                  RenderingHints.VALUE_RENDER_SPEED);
999    
1000          /**                  if (oldMapArea == null)
1001           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten                          return false;
          * (lat/lon)  
          */  
         protected AffineTransform screenToWorld = null;  
1002    
1003          private AffineTransform worldToScreen;                  final Rectangle visibleArea = getVisibleRect();
1004    
1005          /**                  // Calculate the oldMapArea in the current WindowCoordinates:
1006           * Listens to changes of the "local" {@link MapContext} and triggers                  final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1007           * repaints where needed.                                  oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1008           */                                                  .getMaxY());
         private MapLayerListListener localContextListener = new MapLayerListListener() {  
1009    
1010                  @Override                  final int xx1 = (int) Math.round(oldMapWindow.getMinX());
1011                  public void layerAdded(final MapLayerListEvent event) {                  final int yy1 = (int) Math.round(oldMapWindow.getMinY());
1012                          event.getLayer().addMapLayerListener(localMapLayerListener);                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1013                    final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1014    
1015  //                      System.out.println("added a layer context, now it'S "                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1016  //                                      + getContext().getLayerCount() + " layers");                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1017  //                      ;                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1018                                    getMapBackgroundColor(), null);
1019    
1020                          localRenderer.setContext(getContext());                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1021                                    - yy1);
1022    
1023                          if (localContext.getLayers().length == 1) { // the first one                  SwingUtil.clearAround(graphics, painedArea, visibleArea);
                                 // if the Area of Interest is unset, the LayerBounds are used  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         repaint();  
1024    
1025                                  return;                  addGadgets(graphics, true);
                         }  
1026    
1027                          // We need to redraw, even in case that the mapArea didn't change                  quickPreviewHint = 0;
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
1028    
1029                  }                  repaintTimer.restart();
1030    
1031                  @Override                  graphics.dispose();
                 public void layerRemoved(final MapLayerListEvent event) {  
                         if (event.getLayer() != null)  
                                 event.getLayer().removeMapLayerListener(localMapLayerListener);  
                         // mapImageInvalid = true;  
                         // repaint();  
                         localRenderer.setContext(getContext());  
                         requestStartRendering();  
                 }  
1032    
1033                  @Override                  // Something has been drawn
1034                  public void layerChanged(final MapLayerListEvent event) {                  return true;
1035                          // mapImageInvalid = true;          }
1036                          // repaint();  
1037                          localRenderer.setContext(getContext());          public MapContext getBgContext() {
1038                          requestStartRendering();                  return bgContext;
1039            }
1040    
1041            /**
1042             * Lazyly initializes a {@link BufferedImage} for the background renderer.
1043             */
1044            private Image getBgImage() {
1045                    //
1046                    // if (bgImage == null) {
1047                    // bgImage = createImage(getBounds().width, getBounds().height);
1048                    // }
1049    
1050                    return bgImage;
1051            }
1052    
1053            public MapContext getMapContext() {
1054                    if (localContext == null) {
1055                            setLocalContext(new DefaultMapContext());
1056                  }                  }
1057                    return localContext;
1058            }
1059    
1060            private BufferedImage getFinalImage() {
1061                    //
1062                    if (finalImage == null) {
1063                            // Rectangle curPaintArea = getVisibleRect();
1064                            finalImage = new BufferedImage(getVisibleRect().width,
1065                                            getVisibleRect().height, IMAGETYPE);
1066    
                 @Override  
                 public void layerMoved(final MapLayerListEvent event) {  
                         // mapImageInvalid = true;  
                         // repaint();  
                         localRenderer.setContext(getContext());  
1067                          requestStartRendering();                          requestStartRendering();
1068                  }                  }
1069          };                  return finalImage;
1070            }
1071    
1072            public RenderingHints getJava2dHints() {
1073                    return java2dHints;
1074            }
1075    
1076          /**          /**
1077           * Listens to changes of the "background" {@link MapContext} and triggers           * Lazyly initializes a {@link BufferedImage} for the background renderer.
          * repaints where needed.  
1078           */           */
1079          private MapLayerListListener bgContextListener = new MapLayerListListener() {          private BufferedImage getLocalImage() {
1080    
1081                  @Override                  if (localImage == null) {
1082                  public void layerAdded(final MapLayerListEvent event) {                          localImage = new BufferedImage(getVisibleRect().width,
1083                          event.getLayer().addMapLayerListener(bgMapLayerListener);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1084                    }
1085    
1086                    return localImage;
1087            }
1088    
1089                          if (localContext.getLayers().length == 0          /**
1090                                          && bgContext.getLayers().length == 1) { // the first one and           * Returns a copy of the mapArea
1091                                  // localContext is           *
1092                                  // empty           * @return
1093                                  if (!setMapArea(localContext.getAreaOfInterest()))           */
1094                                          requestStartRendering();          public ReferencedEnvelope getMapArea() {
1095                                  return;                  if (mapArea == null) {
1096                            ReferencedEnvelope mapArea_ = null;
1097                            try {
1098                                    mapArea_ = localContext.getLayerBounds();
1099                            } catch (final IOException e) {
1100                                    LOGGER.warn("localContext.getLayerBounds()", e);
1101                          }                          }
1102    
1103                          // We need to redraw, even in case that the mapArea didn't change                          if (mapArea_ == null && bgContext != null) {
1104                          // mapImageInvalid = true;                                  try {
1105                          // repaint();                                          mapArea_ = bgContext.getLayerBounds();
1106                          requestStartRendering();                                  } catch (final IOException e) {
1107                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1108                                    }
1109                            }
1110    
1111                            if (mapArea_ != null) {
1112                                    mapArea = bestAllowedMapArea(mapArea_);
1113                                    requestStartRendering();
1114                            }
1115                  }                  }
1116    
1117                  @Override                  if (mapArea == null)
1118                  public void layerRemoved(final MapLayerListEvent event) {                          return null;
                         if (event.getLayer() != null)  
                                 event.getLayer().removeMapLayerListener(bgMapLayerListener);  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
1119    
1120                  @Override                  // TODO is needed at all, this should go to setMapArea maybe
1121                  public void layerChanged(final MapLayerListEvent event) {                  if (localContext.getCoordinateReferenceSystem() == null)
1122                          // mapImageInvalid = true;                          try {
1123                          // repaint();                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1124                          requestStartRendering();                                                  .getDefaultCRS());
1125                  }                          } catch (Exception e) {
1126                                    throw new RuntimeException("setting context CRS:", e);
1127                            }
1128    
1129                  @Override                  return new ReferencedEnvelope(mapArea, localContext
1130                  public void layerMoved(final MapLayerListEvent event) {                                  .getCoordinateReferenceSystem());
1131                          // mapImageInvalid = true;          }
                         // repaint();  
                         requestStartRendering();  
                 }  
         };  
1132    
1133          /**          /**
1134           * Listens to each layer in the local {@link MapContext} for changes and           * Returns the background {@link Color} of the map pane. Default is white.
1135           * triggers repaints.           **/
1136            public Color getMapBackgroundColor() {
1137                    return mapBackgroundColor;
1138            }
1139    
1140            /**
1141             * Get the BufferedImage to use as a flaoting icon in the lower right
1142             * corner.
1143             *
1144             * @return <code>null</code> if the feature is deactivated.
1145           */           */
1146          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          public BufferedImage getMapImage() {
1147                    return mapImage;
1148            }
1149    
1150                  @Override          /**
1151                  public void layerShown(MapLayerEvent event) {           * Returns the evelope of the viewable area. The JMapPane will never show
1152                          // mapImageInvalid = true;           * anything outside of this extend. If this has been set to
1153                          // repaint();           * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
1154                          requestStartRendering();           * quickly the context's bounds. It it takes to long to determine the
1155                  }           * context bounds, <code>null</code> is returned.
1156             *
1157             * @param maxExtend
1158             *            <code>null</code> to not have this restriction.
1159             */
1160    
1161                  @Override          public Envelope getMaxExtend() {
1162                  public void layerHidden(MapLayerEvent event) {                  if (maxExtend == null) {
1163                          // mapImageInvalid = true;                          // Commented-out because it takes soo much time!
1164                          // repaint();  //
1165                          requestStartRendering();  //                      long start = System.currentTimeMillis();
1166    //                      final ReferencedEnvelope layerBounds = GTUtil
1167    //                                      .getVisibleLayoutBounds(localContext);
1168    //                      
1169    //                      LOGGER.info( (System.currentTimeMillis()-start)+"m to get maxExtend");
1170    //                      
1171    //                      if (layerBounds == null) {
1172    //                              // TODO Last fallback could be the CRS valid area
1173    //                              return null;
1174    //                      }
1175    //
1176    //                      // Kartenbereich um 10% vergroessern
1177    //                      return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil
1178    //                                      .expandEnvelope(layerBounds, 0.1), true);
1179                  }                  }
1180                    return maxExtend;
1181            }
1182    
1183                  @Override          /**
1184                  public void layerChanged(MapLayerEvent event) {           * Retuns the maximum allowed zoom scale. This is the smaller number value
1185                          localRenderer.setContext(getContext()); // betters for SLD changes?!           * of the two. Defaults to {@link Double}.MIN_VALUE
1186                          // Change of SLD for example           *
1187                          // mapImageInvalid = true;           * @author <a href="mailto:[email protected]">Stefan Alfons
1188                          // repaint();           *         Kr&uuml;ger</a>
1189                          requestStartRendering();           */
1190                  }          public Double getMaxZoomScale() {
1191          };                  return maxZoomScale;
1192            }
1193    
1194          /**          /**
1195           * Listens to each layer in the local {@link MapContext} for changes and           * Retuns the minimum allowed zoom scale. This is the bigger number value of
1196           * triggers repaints.           * the two. Defaults to {@link Double}.MAX_VALUE
1197             *
1198             * @author <a href="mailto:[email protected]">Stefan Alfons
1199             *         Kr&uuml;ger</a>
1200           */           */
1201          protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {          public Double getMinZoomScale() {
1202                    return minZoomScale;
1203            }
1204    
1205                  @Override          private Image getPreFinalImage() {
1206                  public void layerShown(MapLayerEvent event) {                  // if (preFinalImage == null) {
1207                          // mapImageInvalid = true;                  //                      
1208                          // repaint();                  // // Rectangle curPaintArea = getVisibleRect();
1209                          requestStartRendering();                  // // preFinalImage = new BufferedImage(curPaintArea.width,
1210                  }                  // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1211                    //                      
1212                    // preFinalImage = createImage(getBounds().width, getBounds().height);
1213                    //
1214                    // requestStartRendering();
1215                    // }
1216                    return preFinalImage;
1217            }
1218    
1219                  @Override          public Map<Object, Object> getRendererHints() {
1220                  public void layerHidden(MapLayerEvent event) {                  // Clear label cache
1221                          // mapImageInvalid = true;                  labelCache.clear();
1222                          // repaint();                  rendererHints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
                         requestStartRendering();  
                 }  
1223    
1224                  @Override                  return rendererHints;
1225                  public void layerChanged(MapLayerEvent event) {          }
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
                         requestStartRendering();  
                 }  
         };  
1226    
1227          /**          /**
1228           * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die           * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
# Line 907  public class XMapPane extends JPanel { Line 1240  public class XMapPane extends JPanel {
1240                  return new AffineTransform(screenToWorld);                  return new AffineTransform(screenToWorld);
1241          }          }
1242    
1243            public int getState() {
1244                    return state;
1245            }
1246    
1247            /**
1248             * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1249             * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1250             *
1251             * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
1252             *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1253             */
1254            public Cursor getStaticCursor() {
1255                    return this.staticCursor;
1256            }
1257    
1258          public AffineTransform getWorldToScreenTransform() {          public AffineTransform getWorldToScreenTransform() {
1259                  if (worldToScreen == null) {                  if (worldToScreen == null) {
1260                          resetTransforms();                          resetTransforms();
# Line 915  public class XMapPane extends JPanel { Line 1263  public class XMapPane extends JPanel {
1263                  return new AffineTransform(worldToScreen);                  return new AffineTransform(worldToScreen);
1264          }          }
1265    
1266          public MapContext getContext() {          /**
1267                  if (localContext == null) {           * A flag indicating if dispose() has already been called. If true, then
1268                          setLocalContext(new DefaultMapContext());           * further use of this {@link SelectableXMapPane} is undefined.
1269             */
1270            private boolean isDisposed() {
1271                    return disposed;
1272            }
1273    
1274            /**
1275             * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
1276             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
1277             * <code>true</code> if the selectability has not been defined.
1278             *
1279             * @param layer
1280             *            a layer
1281             */
1282            public boolean isMapLayerSelectable(final MapLayer layer) {
1283                    final Boolean selectable = mapLayerSelectable.get(layer);
1284                    return selectable == null ? true : selectable;
1285            }
1286    
1287            /**
1288             * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
1289             * {@link XMapPane} is visible and has bounds set.
1290             */
1291            public boolean isWellDefined() {
1292                    try {
1293                            if (getMapContext() == null)
1294                                    return false;
1295                            if (getMapContext().getLayerCount() <= 0)
1296                                    return false;
1297                            if (getVisibleRect().getWidth() == 0)
1298                                    return false;
1299                            if (getVisibleRect().getHeight() == 0)
1300                                    return false;
1301                            // if (getMapArea() == null)
1302                            // return false;
1303                    } catch (final Exception e) {
1304                            return false;
1305                  }                  }
1306                  return localContext;                  return true;
1307          }          }
1308    
1309          public MapContext getBgContext() {          public void mouseDragged(final Point startPos, final Point lastPos,
1310                  return bgContext;                          final MouseEvent event) {
1311    
1312                    if ((getState() == XMapPane.PAN)
1313                                    || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
1314    
1315                            if (getCursor() != SwingUtil.PANNING_CURSOR) {
1316                                    setCursor(SwingUtil.PANNING_CURSOR);
1317    
1318                                    // While panning, we deactivate the rendering. So the tasts are
1319                                    // ready to start when the panning os done.
1320                                    if (bgExecuter != null)
1321                                            bgExecuter.cancelTask();
1322                                    if (localExecuter != null)
1323                                            localExecuter.cancelTask();
1324                            }
1325    
1326                            if (lastPos.x > 0 && lastPos.y > 0) {
1327                                    final int dx = event.getX() - lastPos.x;
1328                                    final int dy = event.getY() - lastPos.y;
1329    
1330                                    // TODO Stop dragging when the drag would not be valid...
1331                                    // boolean dragValid = true;
1332                                    // // check if this panning results in a valid mapArea
1333                                    // {
1334                                    // Rectangle winBounds = xMapPane.getBounds();
1335                                    // winBounds.translate(xMapPane.imageOrigin.x,
1336                                    // -xMapPane.imageOrigin.y);
1337                                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1338                                    // winBounds.x, winBounds.y, winBounds.x
1339                                    // + winBounds.width, winBounds.y
1340                                    // + winBounds.height);
1341                                    //                                      
1342                                    //
1343                                    // winBounds = xMapPane.getBounds();
1344                                    // Point testIng = new Point(xMapPane.imageOrigin);
1345                                    // testIng.translate(dx, dy);
1346                                    // winBounds.translate(testIng.x, -testIng.y);
1347                                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1348                                    // winBounds.x, winBounds.y, winBounds.x
1349                                    // + winBounds.width, winBounds.y
1350                                    // + winBounds.height);
1351                                    //
1352                                    // // If the last drag doesn't change the MapArea anymore cancel
1353                                    // it.
1354                                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1355                                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1356                                    // dragValid = false;
1357                                    // return;
1358                                    // }
1359                                    // }
1360    
1361                                    imageOrigin.translate(dx, dy);
1362                                    updateFinalImage();
1363                                    repaint();
1364                            }
1365    
1366                    } else if ((getState() == XMapPane.ZOOM_IN)
1367                                    || (getState() == XMapPane.ZOOM_OUT)
1368                                    || (getState() == XMapPane.SELECT_ALL)
1369                                    || (getState() == XMapPane.SELECT_TOP)
1370                    // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)
1371                    ) {
1372                            final Graphics graphics = getGraphics();
1373    
1374                            drawRectangle(graphics, startPos, event.getPoint());
1375    
1376                            if ((lastPos.x > 0) && (lastPos.y > 0)) {
1377                                    drawRectangle(graphics, startPos, lastPos);
1378                            }
1379    
1380                            graphics.dispose();
1381    
1382                    }
1383    
1384            }
1385    
1386            /**
1387             * Called by the {@link RenderingExecutor} when rendering was cancelled.
1388             */
1389            public void onRenderingCancelled() {
1390                    LOGGER.debug("Rendering cancelled");
1391                    repaintTimer.stop();
1392          }          }
1393    
1394          /**          /**
1395             * Called by the {@link RenderingExecutor} when rendering has been
1396             * completed.
1397             */
1398            public void onRenderingCompleted() {
1399                    repaintTimer.stop();
1400                    updateFinalImage();
1401                    repaint();
1402                    if (renderingErrors.size() > 0)
1403                            renderingErrors.remove(0);
1404            }
1405    
1406            /**
1407             * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1408             * Publishes a {@linkplain MapPaneEvent} of type {@code
1409             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1410             *
1411             * @param renderingError
1412             *            The error that occured during rendering
1413           *           *
1414           * @param context           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1415           */           */
1416          public void setLocalContext(final MapContext context) {          public void onRenderingFailed(final Exception renderingError) {
1417                  // Remove the default listener from the old context  
1418                  if (this.localContext != null) {                  // Store the exceptions so we can show it to the user:
1419                          this.localContext.removeMapLayerListListener(localContextListener);                  if (!(renderingError instanceof java.lang.IllegalArgumentException
1420                                    && renderingError.getMessage().equals(
1421                                                    "Argument \"sourceCRS\" should not be null.")))
1422                            this.renderingErrors.add(renderingError);
1423                    if (renderingErrors.size() > 3)
1424                            renderingErrors.remove(0);
1425                    
1426                    repaintTimer.stop();
1427                    LOGGER.warn("Rendering failed", renderingError);
1428                    updateFinalImage();
1429                    repaint();
1430    
1431            }
1432    
1433            public void onRenderingPending() {
1434                    // LOGGER.debug("Pending rendering updates the preview...");
1435                    updateFinalImage();
1436                    repaint();
1437            }
1438    
1439            @Override
1440            protected void paintComponent(final Graphics g) {
1441    
1442                    if (!acceptsRepaintCalls)
1443                            return;
1444    
1445                    // Maybe update the cursor and maybe stop the repainting timer
1446                    updateCursor();
1447    
1448                    // super.paintComponent(g); // candidate for removal
1449    
1450                    boolean paintedSomething = false;
1451    
1452                    if (mapImageInvalid) { /* if the map changed then redraw */
1453    
1454                            mapImageInvalid = false; // Reset for next round
1455    
1456                            // If the new mapArea and the oldMapArea intersect, we can draw some
1457                            // quick scaled preview to make the user feel that something is
1458                            // happening.
1459                            if (mapAreaChanged && oldMapArea != null
1460                                            && getMapArea().intersects(oldMapArea)
1461                                            & !getMapArea().equals(oldMapArea) && !paneResized) {
1462    
1463                                    mapAreaChanged = false;
1464    
1465                                    if (getMapArea().covers(oldMapArea)) {
1466                                            setQuickPreviewHint(ZOOM_OUT);
1467                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1468                                    } else if (oldMapArea.covers(getMapArea())) {
1469                                            setQuickPreviewHint(ZOOM_IN);
1470                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1471                                    }
1472    
                         // adding listener to all layers  
                         for (MapLayer mapLayer : localContext.getLayers()) {  
                                 mapLayer.removeMapLayerListener(localMapLayerListener);  
1473                          }                          }
1474    
1475                            // if (paneResized) {
1476                            // paneResized = false;
1477                            // disposeImages();
1478                            // }
1479                            //
1480                            // // Start the Threads and Timers to render the image
1481                            // requestStartRendering();
1482    
1483                  }                  }
1484    
1485                  this.localContext = context;                  if (!paintedSomething) {
1486    
1487                  if (context != null) {                          g.drawImage(getFinalImage(), 0, 0, null);
1488    
1489                          setMapArea(localContext.getAreaOfInterest());                          g.dispose(); // cand. for removal
1490    
1491                          localRenderer.setContext(localContext);                          paintedSomething = true; // cand. for removal
1492                    }
1493    
1494                          this.localContext.addMapLayerListListener(localContextListener);          }
1495    
1496                          // adding listener to all layers          /**
1497                          for (MapLayer mapLayer : localContext.getLayers()) {           * Heavily works on releasing all resources related to the four
1498                                  mapLayer.addMapLayerListener(localMapLayerListener);           * {@link Image}s used to cache the results of the different renderers.<br>
1499                          }           * In November 2009 i had some memory leaking problems with {@link XMapPane}
1500             * . The resources of the buffered images were never released. It seem to be
1501             * important to call the GC right after flushing the images.<br>
1502             * Hence this method may take a while, because it calls the GC up to four
1503             * times.
1504             */
1505            private void disposeImages() {
1506    
1507                    // System.out.println("vorher = "
1508                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1509                    // bi.flush();
1510                    // return bi = null;
1511                    // System.out.println("nacher = "
1512                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1513                    //
1514                    // System.out.println("\n");
1515    
1516                    if (preFinalImage != null) {
1517                            preFinalImage.flush();
1518                            preFinalImage = null;
1519                            LangUtil.gc();
1520                  }                  }
1521                    if (finalImage != null) {
1522                            finalImage.flush();
1523                            finalImage = null;
1524                            LangUtil.gc();
1525                    }
1526                    if (localImage != null) {
1527                            localImage.flush();
1528                            localImage = null;
1529                            LangUtil.gc();
1530                    }
1531                    if (bgImage != null) {
1532                            bgImage.flush();
1533                            bgImage = null;
1534                            LangUtil.gc();
1535                    }
1536    
1537            }
1538    
1539            /**
1540             * Performs a {@value #PAN} action. During panning, the displacement is
1541             * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will
1542             * reset the offset and call {@link #setMapArea(Envelope)}.
1543             */
1544            public void performPan() {
1545    
1546                    Rectangle winBounds = getVisibleRect();
1547    
1548                    winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1549                    final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1550                                    winBounds.y, winBounds.x + winBounds.width, winBounds.y
1551                                                    + winBounds.height);
1552    
1553                    imageOrigin.x = 0;
1554                    imageOrigin.y = 0;
1555    
1556                    if (!setMapArea(newMapArea)) {
1557                            /**
1558                             * If setMapArea returns true, the finalImage is updated anyways.
1559                             * This if-case exists to ensure that we repaint a correct image
1560                             * even if the new panning area has been denied.
1561                             */
1562                            updateFinalImage();
1563                            repaint();
1564                    }
1565    
1566                    if (getCursor() == SwingUtil.PANNING_CURSOR)
1567                            setCursor(SwingUtil.PAN_CURSOR);
1568            }
1569    
1570            //
1571            // /**
1572            // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot
1573            // gemacht
1574            // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.
1575            // *
1576            // * @author <a href="mailto:[email protected]">Stefan Alfons
1577            // * Kr&uuml;ger</a>
1578            // */
1579            // @Override
1580            // public void print(final Graphics g) {
1581            // final Color orig = getBackground();
1582            // setBackground(Color.WHITE);
1583            //
1584            // // wrap in try/finally so that we always restore the state
1585            // try {
1586            // super.print(g);
1587            // } finally {
1588            // setBackground(orig);
1589            // }
1590            // }
1591    
1592            /**
1593             * Entfernt einen Listener von der Map.
1594             *
1595             * @param l
1596             *            zu entfernender Listener
1597             */
1598            public void removeMapPaneListener(final JMapPaneListener l) {
1599                    mapPaneListeners.remove(l);
1600            }
1601    
1602            /**
1603             * Cancels all running renderers and sets the flag to start new ones. <br>
1604             *
1605             * @see #startRenderThreadsTimer
1606             */
1607            private void requestStartRendering() {
1608                    if (bgExecuter != null)
1609                            bgExecuter.cancelTask();
1610                    if (localExecuter != null)
1611                            localExecuter.cancelTask();
1612    
1613                  mapImageInvalid = true;                  mapImageInvalid = true;
1614                  repaint();                  if (paneResized) {
1615                            paneResized = false;
1616                            disposeImages();
1617                    }
1618                    requestStartRendering = true;
1619    
1620            }
1621    
1622            /**
1623             * Calculate the affine transforms used to convert between world and pixel
1624             * coordinates. The calculations here are very basic and assume a cartesian
1625             * reference system.
1626             * <p>
1627             * Tne transform is calculated such that {@code envelope} will be centred in
1628             * the display
1629             *
1630             * @param envelope
1631             *            the current map extent (world coordinates)
1632             * @param paintArea
1633             *            the current map pane extent (screen units)
1634             */
1635            private void resetTransforms() {
1636                    ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1637                                    getMapContext().getCoordinateReferenceSystem());
1638    
1639                    // System.out
1640                    // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1641                    if (!isWellDefined())
1642                            return;
1643    
1644                    worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1645                                    getVisibleRect());
1646    
1647                    try {
1648                            screenToWorld = worldToScreen.createInverse();
1649    
1650                    } catch (NoninvertibleTransformException ex) {
1651                            LOGGER
1652                                            .error("can't invert worldToScreen to get screenToWorld!",
1653                                                            ex);
1654                    }
1655          }          }
1656    
1657          public void setBgContext(final MapContext context) {          public void setBgContext(final MapContext context) {
# Line 968  public class XMapPane extends JPanel { Line 1661  public class XMapPane extends JPanel {
1661                          this.bgContext.removeMapLayerListListener(bgContextListener);                          this.bgContext.removeMapLayerListListener(bgContextListener);
1662    
1663                          // adding listener to all layers                          // adding listener to all layers
1664                          for (MapLayer mapLayer : bgContext.getLayers()) {                          for (final MapLayer mapLayer : bgContext.getLayers()) {
1665                                  mapLayer.removeMapLayerListener(bgMapLayerListener);                                  mapLayer.removeMapLayerListener(bgMapLayerListener);
1666                          }                          }
1667                  }                  }
# Line 976  public class XMapPane extends JPanel { Line 1669  public class XMapPane extends JPanel {
1669                  this.bgContext = context;                  this.bgContext = context;
1670    
1671                  if (context != null) {                  if (context != null) {
1672                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1673    
1674                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1675    
1676                          // adding listener to all layers                          // adding listener to all layers
1677                          for (MapLayer mapLayer : bgContext.getLayers()) {                          for (final MapLayer mapLayer : bgContext.getLayers()) {
1678                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1679                          }                          }
1680                  }                  }
1681                  mapImageInvalid = true;  
1682                  repaint();                  requestStartRendering();
1683          }          }
1684    
1685          /**          public void setJava2dHints(final RenderingHints java2dHints) {
1686           * Returns a copy of the mapArea                  this.java2dHints = java2dHints;
1687           *          }
1688           * @return  
1689           */          public void setLocalContext(final MapContext context) {
1690          public Envelope getMapArea() {                  // Remove the default listener from the old context
1691                  if (mapArea == null) {                  if (this.localContext != null) {
1692                          ReferencedEnvelope mapArea_ = null;                          this.localContext.removeMapLayerListListener(localContextListener);
1693                          try {  
1694                                  mapArea_ = localContext.getLayerBounds();                          // adding listener to all layers
1695                          } catch (final IOException e) {                          for (final MapLayer mapLayer : localContext.getLayers()) {
1696                                  LOGGER.warn("context.getLayerBounds()", e);                                  mapLayer.removeMapLayerListener(localMapLayerListener);
1697                          }                          }
1698                    }
1699    
1700                          if (mapArea_ != null) {                  this.localContext = context;
1701                                  mapImageInvalid = true; /* note we need to redraw */  
1702                                  setMapArea(mapArea_);                  if (context != null) {
1703    
1704                            // setMapArea(localContext.getAreaOfInterest());
1705    
1706                            localRenderer.setContext(localContext);
1707    
1708                            this.localContext.addMapLayerListListener(localContextListener);
1709    
1710                            // adding listener to all layers
1711                            for (final MapLayer mapLayer : localContext.getLayers()) {
1712                                    mapLayer.addMapLayerListener(localMapLayerListener);
1713                          }                          }
1714                  }                  }
1715    
1716                  if (mapArea == null)                  requestStartRendering();
                         return null;  
1717    
1718                  return new Envelope(mapArea);          }
1719    
1720            public boolean setMapArea(final Envelope newMapArea) {
1721                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1722                                    .getCoordinateReferenceSystem()));
1723          }          }
1724    
1725          /**          /**
# Line 1020  public class XMapPane extends JPanel { Line 1727  public class XMapPane extends JPanel {
1727           * @return <code>true</code> if the mapArea has been changed and a repaint           * @return <code>true</code> if the mapArea has been changed and a repaint
1728           *         has been triggered.           *         has been triggered.
1729           */           */
1730          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1731                    //              
1732                    // if (getVisibleRect().getWidth() == 0 || (!isVisible()) ||
1733                    // getVisibleRect().getHeight() == 0) {
1734                    // // The window is not yet defined.. so we can not really determine the
1735                    // asepect ratio for the mapPane. We store this as a candidate mappane
1736                    // and handle it when the component resizes or becomes visible)
1737                    // mapAreaCondidate = newMapArea;
1738                    // }
1739    
1740                  if (newMapArea == null                  if (newMapArea == null
1741                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1039  public class XMapPane extends JPanel { Line 1754  public class XMapPane extends JPanel {
1754                          return false;                          return false;
1755                  }                  }
1756    
1757                    final Envelope candNew = bestAllowedMapArea(newMapArea);
1758    
1759                  // Testing, whether the difference if just minimal                  // Testing, whether the difference if just minimal
1760                  if (mapArea != null) {                  if (mapArea != null) {
1761                          Envelope candNew = bestAllowedMapArea(newMapArea);                          final double tolX = mapArea.getWidth() / 1000.;
1762                          double tolX = mapArea.getWidth() / 1000.;                          final double tolY = mapArea.getHeight() / 1000.;
                         double tolY = mapArea.getHeight() / 1000.;  
1763                          if ((candNew.getMinX() - tolX < mapArea.getMinX())                          if ((candNew.getMinX() - tolX < mapArea.getMinX())
1764                                          && (mapArea.getMinX() < candNew.getMinX() + tolX)                                          && (mapArea.getMinX() < candNew.getMinX() + tolX)
1765                                          && (candNew.getMaxX() - tolX < mapArea.getMaxX())                                          && (candNew.getMaxX() - tolX < mapArea.getMaxX())
# Line 1061  public class XMapPane extends JPanel { Line 1777  public class XMapPane extends JPanel {
1777                          }                          }
1778                  }                  }
1779    
1780                    // New map are is accepted:
1781                  oldMapArea = mapArea;                  oldMapArea = mapArea;
1782                    mapArea = candNew;
1783                  this.mapArea = bestAllowedMapArea(newMapArea);                  resetTransforms();
1784    
1785                  if (localContext != null) {                  if (localContext != null) {
1786                          localContext.setAreaOfInterest(mapArea, localContext                          localContext.setAreaOfInterest(mapArea, localContext
# Line 1073  public class XMapPane extends JPanel { Line 1790  public class XMapPane extends JPanel {
1790                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1791                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1792                  }                  }
1793                  resetTransforms();  
                 mapImageInvalid = true;  
1794                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1795    
1796                  // LOGGER.debug("New maparea = " + mapArea);                  repaint(100);
                 return true;  
         }  
1797    
1798          public int getState() {                  requestStartRendering();
1799                  return state;  
1800                    return true;
1801          }          }
1802    
1803          /**          /**
1804           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the           * Set the background color of the map.
          * repaint Timer if  
1805           *           *
1806           * @param state           * @param if <code>null</code>, white is used.
1807           */           */
1808          public void setState(final int state) {          public void setMapBackgroundColor(Color bgColor) {
1809                  this.state = state;                  if (bgColor == null)
1810                            bgColor = Color.WHITE;
1811                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN                  this.mapBackgroundColor = bgColor;
                                 || state == ZOOM_OUT || state == PAN));  
   
                 // Je nach Aktion den Cursor umsetzen  
                 updateCursor();  
1812          }          }
1813    
         /** Cursor wenn kein Mausbutton gedrueckt wird. default oder SwingUtil.PAN **/  
         protected static Cursor normalCursor = Cursor  
                         .getPredefinedCursor(Cursor.DEFAULT_CURSOR);  
   
         public static final Cursor WAIT_CURSOR = Cursor  
                         .getPredefinedCursor(Cursor.WAIT_CURSOR);  
   
         public static final int NONE = -123;  
   
         private RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
         /**  
          * A flag set it {@link #setMapArea(Envelope)} to indicated the  
          * {@link #paintComponent(Graphics)} method, that the image on-screen is  
          * associated with {@link #oldMapArea} and may hence be scaled for a quick  
          * preview.<br/>  
          * The flag is reset  
          **/  
         private boolean mapAreaChanged = false;  
   
         private volatile Boolean requestStartRendering = false;  
   
1814          /**          /**
1815           * The Renderer for the Background uses this Image. When set to null, please           * Set the BufferedImage to use as a flaoting icon in the lower right corner
1816           * dispose the {@link Graphics2D}           *
1817           */           * @param mapImageIcon
1818          private BufferedImage bgImage;// = new           *            <code>null</code> is allowed and deactivates this icon.
         // BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);  
   
         private BufferedImage finalImage;  
   
         /**  
          * The Renderer for the LocalLayers uses this Image. When set to null,  
          * please dispose this {@link Graphics2D}  
1819           */           */
1820          private BufferedImage localImage;// = new          public void setMapImage(final BufferedImage mapImage) {
1821          // BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);                  this.mapImage = mapImage;
         private BufferedImage preFinalImage;// = new  
   
         // BufferedImage(600,600,BufferedImage.TYPE_INT_ARGB);  
   
         protected void paintComponent(final Graphics g) {  
                 if (!acceptsRepaintCalls)  
                         return;  
                   
                 // Maybe update the cursor  
                 updateCursor();  
                   
                 super.paintComponent(g);  
   
                 boolean paintedSomething = false;  
   
                 if (mapImageInvalid) { /* if the map changed then redraw */  
   
                         mapImageInvalid = false; // Reset for next round  
   
                         // If the new mapArea and the oldMapArea intersect, we can draw some  
                         // quick scaled preview to make the user feel that something is  
                         // happening.  
                         if (mapAreaChanged && oldMapArea != null  
                                         && getMapArea().intersects(oldMapArea)  
                                         & !getMapArea().equals(oldMapArea)) {  
   
                                 mapAreaChanged = false;  
   
                                 if (getMapArea().covers(oldMapArea)) {  
                                         setQuickPreviewHint(ZOOM_OUT);  
                                         paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);  
                                 } else if (oldMapArea.covers(getMapArea())) {  
                                         setQuickPreviewHint(ZOOM_IN);  
                                         paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);  
                                 }  
   
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
   
                                 // if (preFinalImage != null)  
                                 // preFinalImage.flush();  
                                 // preFinalImage = null;  
                                 // if (finalImage != null) {  
                                 // finalImage.flush();  
                                 // }  
                                 // finalImage = null;  
                                 // if (localImage != null)  
                                 // localImage.flush();  
                                 // localImage = null;  
                                 // if (bgImage != null)  
                                 // bgImage.flush();  
                                 // bgImage = null;  
   
                                 // gadgetsImage = null;  
                         }  
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
                 }  
   
                 if (!paintedSomething) {  
   
                         // TODO Should just paint the getFinalImage(). Update should be  
                         // called by timer every 300ms, and the repaint() until all threads  
                         // are done.  
                         g.drawImage(getFinalImage(), 0, 0, null);  
   
                         g.dispose();  
   
                         paintedSomething = true;  
                 }  
   
1822          }          }
1823    
1824          /**          /**
1825           * Cancels all running renderers and sets the flag to start new ones. <br/>           * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
1826             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
1827           *           *
1828           * @see #startRenderThreadsTimer           * @param layer
1829             *            a layer
1830             * @param selectable
1831             *            if {@code false} the layer is ignored during the upper
1832             *            mentioned actions. If <code>null</code>, the default (true)
1833             *            will be used.
1834           */           */
1835          private void requestStartRendering() {          public void setMapLayerSelectable(final MapLayer layer,
1836                  if (bgExecuter != null)                          final Boolean selectable) {
1837                          bgExecuter.cancelTask();                  if (selectable == null)
1838                  if (localExecuter != null)                          mapLayerSelectable.remove(layer);
1839                          localExecuter.cancelTask();                  else
1840                  requestStartRendering = true;                          mapLayerSelectable.put(layer, selectable);
   
1841          }          }
1842    
1843          /**          /**
1844           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.           * Defines an evelope of the viwable area. The JMapPane will never show
1845             * anything outside of this extend.
1846           *           *
1847           * @param ox           * @param maxExtend
1848           *            X-Koordinate der VON-Position           *            <code>null</code> to not have this restriction.
          * @param oy  
          *            Y-Koordinate der VON-Position  
          * @param px  
          *            X-Koordinate der BIS-Position  
          * @param py  
          *            Y-Koordinate der BIS-Position  
1849           */           */
1850          public Envelope tranformWindowToGeo(int ox, int oy, int px, int py) {          public void setMaxExtend(final Envelope maxExtend) {
1851                  AffineTransform at = getScreenToWorld();                  this.maxExtend = maxExtend;
                 Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);  
                 Point2D geoP = at.transform(new Point2D.Double(px, py), null);  
                 return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());  
1852          }          }
1853    
1854          /**          /**
1855           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Set the maximum allowed zoom scale. This is the smaller number value of
1856             * the two. If <code>null</code> is passed, Double.MINVALUE are used which
1857             * mean there is no restriction.
1858           *           *
1859           * @param ox           * @author <a href="mailto:[email protected]">Stefan Alfons
1860           *            X-Koordinate der VON-Position           *         Kr&uuml;ger</a>
          * @param oy  
          *            Y-Koordinate der VON-Position  
          * @param px  
          *            X-Koordinate der BIS-Position  
          * @param py  
          *            Y-Koordinate der BIS-Position  
          * @param winToGeotransform  
          *            Eine Window to Geo transform. If <code>null</code>,  
          *            {@link #getScreenToWorld()} is used.  
1861           */           */
1862          public Envelope tranformGeoToWindow(double ox, double oy, double px,          public void setMaxZoomScale(final Double maxZoomScale) {
1863                          double py, AffineTransform winToGeotransform) {                  this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
1864                  AffineTransform at = winToGeotransform == null ? getScreenToWorld()                                  : maxZoomScale;
                                 : winToGeotransform;  
                 Point2D geoO;  
                 try {  
                         geoO = at.inverseTransform(new Point2D.Double(ox, oy), null);  
                         Point2D geoP = at  
                                         .inverseTransform(new Point2D.Double(px, py), null);  
                         return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP  
                                         .getY());  
                 } catch (NoninvertibleTransformException e) {  
                         LOGGER.error(e);  
                         return new Envelope(ox, oy, px, py);  
                 }  
1865          }          }
1866    
1867            // /** Stored the time used for the last real rendering in ms. **/
1868            // private long lastRenderingDuration = Long.MAX_VALUE;
1869    
1870          /**          /**
1871           * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1872           * to give the user something to look at while we are rendering. Method           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
1873           * should be called after {@link #setMapArea(Envelope)} has been set to the           * used which mean there is no restriction.
          * new mapArea and transform has been reset.<br/>  
1874           *           *
          * @param g  
          *            Graphics2D to paint the preview into  
1875           *           *
1876           * @param state           * @author <a href="mailto:[email protected]">Stefan Alfons
1877           *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}           *         Kr&uuml;ger</a>
1878           */           */
1879          protected boolean drawScaledPreviewImage_Zoom(Graphics2D graphics) {          public void setMinZoomScale(final Double minZoomScale) {
1880                    this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
1881                  if (quickPreviewHint == 0)                                  : minZoomScale;
                         return false;  
   
                 graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
                                 RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);  
                 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                                 RenderingHints.VALUE_ANTIALIAS_OFF);  
                 graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
                                 RenderingHints.VALUE_RENDER_SPEED);  
   
                 if (oldMapArea == null)  
                         return false;  
   
                 Rectangle visibleArea = getVisibleRect();  
   
                 // Calculate the oldMapArea in the current WindowCoordinates:  
                 Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),  
                                 oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea  
                                                 .getMaxY(), null);  
   
                 int xx1 = (int) Math.round(oldMapWindow.getMinX());  
                 int yy1 = (int) Math.round(oldMapWindow.getMinY());  
                 int xx2 = (int) Math.round(oldMapWindow.getMaxX());  
                 int yy2 = (int) Math.round(oldMapWindow.getMaxY());  
   
                 graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,  
                                 (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),  
                                 (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),  
                                 getMapBackgroundColor(), null);  
   
                 Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2 - yy1);  
   
                 SwingUtil.clearAround(graphics, painedArea, visibleArea);  
   
                 addGadgets(graphics);  
   
                 quickPreviewHint = 0;  
   
                 graphics.dispose();  
   
                 // Something has been drawn  
                 return true;  
1882          }          }
1883    
         final static Font waitFont = new Font("Arial", Font.BOLD, 30);  
   
1884          /**          /**
1885           * Paints some optinal stuff into the given {@link Graphics2D}. Usually           *
1886           * called as the last paint on the mapImage.           * @param b
1887           */           */
1888          private void addGadgets(Graphics2D graphics) {          public void setPainting(final boolean b) {
1889                    acceptsRepaintCalls = b;
1890                  if (mapImage != null)          }
                         graphics.drawImage(mapImage, getBounds().width  
                                         - mapImage.getWidth() - 10, getBounds().height  
                                         - mapImage.getHeight() - 10, null);  
   
                 // If still rendering, paint a gray shadow or so...  
                 if (bgExecuter != null && bgExecuter.isRunning()  
                                 || localExecuter != null && localExecuter.isRunning()) {  
1891    
1892                          Color c = graphics.getColor();          // /**
1893                          graphics.setColor(Color.BLACK);          // * Returns in milli seconds the time the last rending of the
1894            // * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has
1895            // not
1896            // * been rendered yet.
1897            // */
1898            // public long getLastRenderingDuration() {
1899            // return lastRenderingDuration;
1900            // }
1901    
1902                          graphics.setFont(waitFont);          public void setQuickPreviewHint(final int quickPreviewHint) {
1903                          graphics.drawString("Wait...", 40, 70); // i8n                  this.quickPreviewHint = quickPreviewHint;
1904    
1905                          graphics.setColor(c);          }
                 }  
1906    
1907            private void setRendererHints(final Map<Object, Object> rendererHints) {
1908                    if (rendererHints != null)
1909                            this.rendererHints = rendererHints;
1910          }          }
1911    
1912          /**          /**
1913           * Accumulates all three images           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1914             * repaint Timer if
1915           *           *
1916           * @return           * @param state
1917           */           */
1918          synchronized protected Image updateFinalImage() {          public void setState(final int state) {
1919                    this.state = state;
                 // Render the two map images first, into the preFinalImage  
                 if (bgExecuter != null) {  
                         final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()  
                                         .getGraphics();  
                         preFinalG.setBackground(getMapBackgroundColor());  
   
                         preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),  
                                         null);  
   
                         // // Draw the local layers image  
                         preFinalG.drawImage(getLocalImage(), 0, 0, null);  
                         preFinalG.dispose();  
   
                 } else {  
                         preFinalImage = getLocalImage();  
                 }  
   
                 final Graphics2D finalG = getFinalImage().createGraphics();  
                 finalG.setBackground(getMapBackgroundColor());  
                 finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,  
                                 getMapBackgroundColor(), null);  
   
                 final int finalImageHeight = getFinalImage().getHeight(null);  
                 final int finalImageWidth = getFinalImage().getWidth(null);  
   
                 Rectangle painedArea = new Rectangle(imageOrigin.x, imageOrigin.y,  
                                 finalImageWidth, finalImageHeight);  
                 SwingUtil.clearAround(finalG, painedArea, getVisibleRect());  
   
                 addGadgets(finalG);  
   
                 finalG.dispose();  
   
                 return finalImage;  
         }  
   
         private BufferedImage getFinalImage() {  
                 //  
                 if (finalImage == null) {  
                         // Rectangle curPaintArea = getVisibleRect();  
                         finalImage = new BufferedImage(getBounds().width,  
                                         getBounds().height, BufferedImage.TYPE_INT_RGB);  
1920    
1921                          requestStartRendering();                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
1922                  }                                  || state == ZOOM_OUT || state == PAN));
                 return finalImage;  
         }  
1923    
1924          private Image getPreFinalImage() {                  // Je nach Aktion den Cursor umsetzen
1925                  // if (preFinalImage == null) {                  updateCursor();
                 //                        
                 // // Rectangle curPaintArea = getVisibleRect();  
                 // // preFinalImage = new BufferedImage(curPaintArea.width,  
                 // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);  
                 //                        
                 // preFinalImage = createImage(getBounds().width, getBounds().height);  
                 //  
                 // requestStartRendering();  
                 // }  
                 return preFinalImage;  
1926          }          }
1927    
1928          /**          /**
1929           * While dragging, the {@link #updateFinalImage()} method is translating the           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
1930           * cached images while setting it together.           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
1931           **/           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
1932          Point imageOrigin = new Point(0, 0);           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
1933          private final GTRenderer localRenderer;           * {@code null} als Parameter uebergeben werden
1934             *
1935             * @param cursor
1936             *            Cursor
1937             */
1938            public void setStaticCursor(final Cursor cursor) {
1939                    this.staticCursor = cursor;
1940                    if (cursor != null)
1941                            super.setCursor(cursor);
1942            }
1943    
1944          /**          /**
1945           * Starts rendering on one or two threads           * Starts rendering on one or two threads
1946           */           */
1947          private void startRendering() {          private void startRendering() {
1948    
1949                  if (!isWellDefined())                  if (!isWellDefined() || !acceptsRepaintCalls) {
1950                            requestStartRendering = true;
1951                          return;                          return;
1952                    }
1953    
1954                  if (bgExecuter != null) {                  if (bgExecuter != null) {
1955                          // Stop all renderers                          // Stop all renderers
# Line 1460  public class XMapPane extends JPanel { Line 1960  public class XMapPane extends JPanel {
1960                          localExecuter.cancelTask();                          localExecuter.cancelTask();
1961                  }                  }
1962    
1963                  Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
   
1964    
1965                  /**                  /**
1966                   * We have to set new renderer                   * We have to set new renderer
1967                   */                   */
1968    
1969                  if (getBgContext() != null) {                  if (getBgContext() != null) {
1970                            bgRenderer.setJava2DHints(getJava2dHints());
1971                            bgRenderer.setRendererHints(getRendererHints());
1972    
1973                          // bgExecuter = new RenderingExecutor();                          // bgExecuter = new RenderingExecutor();
1974                          // LOGGER.debug("starting bg renderer:");                          // LOGGER.debug("starting bg renderer:");
1975                          // // /* System.out.println("rendering"); */                          // // /* System.out.println("rendering"); */
# Line 1479  public class XMapPane extends JPanel { Line 1981  public class XMapPane extends JPanel {
1981                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1982                  }                  }
1983    
1984                  if (getContext() != null) {                  if (getMapContext() != null) {
1985                          // localExecuter = new RenderingExecutor(this, 150l);                          // localExecuter = new RenderingExecutor(this, 150l);
1986  //                      LOGGER.debug("starting local renderer:");                          // LOGGER.debug("starting local renderer:");
                           
                         // Clear label cache  
                         labelCache.clear();  
                         Map<Object, Object> rh = localRenderer.getRendererHints();  
                         rh.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);  
                         localRenderer.setRendererHints(rh);  
1987    
1988                          boolean submitted = localExecuter.submit(getContext().getAreaOfInterest(),                          localRenderer.setJava2DHints(getJava2dHints());
1989                            localRenderer.setRendererHints(getRendererHints());
1990    
1991                            final boolean submitted = localExecuter.submit(getMapArea(),
1992                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
1993                                          localRenderer, getWorldToScreenTransform());                                          localRenderer
1994                          if (submitted) repainterTimer.restart();                          // , getWorldToScreenTransform()
1995                          else requestStartRendering = true; // Try to start rendering again in a moment                                          );
1996                            if (submitted)
1997                                    repaintTimer.restart();
1998                            else
1999                                    requestStartRendering = true; // Try to start rendering
2000                            // again in
2001                            // a moment
2002                  }                  }
2003    
2004                  updateCursor();                  updateCursor();
   
2005          }          }
2006    
2007          /**          /**
2008           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
          */  
         private Image getBgImage() {  
                 //  
                 // if (bgImage == null) {  
                 // bgImage = createImage(getBounds().width, getBounds().height);  
                 // }  
   
                 return bgImage;  
         }  
   
         /** An (transparent) image to paint over the map in the lower right corner **/  
         private BufferedImage mapImage = null;  
   
         private boolean acceptsRepaintCalls = true;  
   
         /**  
          * Get the BufferedImage to use as a flaoting icon in the lower right  
          * corner.  
2009           *           *
2010           * @return <code>null</code> if the feature is deactivated.           * @param ox
2011             *            X-Koordinate der VON-Position
2012             * @param oy
2013             *            Y-Koordinate der VON-Position
2014             * @param px
2015             *            X-Koordinate der BIS-Position
2016             * @param py
2017             *            Y-Koordinate der BIS-Position
2018             * @param winToGeotransform
2019             *            Eine Window to Geo transform. If <code>null</code>,
2020             *            {@link #getScreenToWorld()} is used.
2021           */           */
2022          public BufferedImage getMapImage() {          public Envelope tranformGeoToWindow(final double ox, final double oy,
2023                  return mapImage;                          final double px, final double py) {
2024                    final AffineTransform at = getWorldToScreenTransform();
2025                    Point2D geoO;
2026                    // try {
2027                    geoO = at.transform(new Point2D.Double(ox, oy), null);
2028                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2029                    return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
2030                    // } catch (final NoninvertibleTransformException e) {
2031                    // LOGGER.error(e);
2032                    // return new Envelope(ox, oy, px, py);
2033                    // }
2034          }          }
2035    
2036          /**          /**
2037           * Set the BufferedImage to use as a flaoting icon in the lower right corner           * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
2038           *           *
2039           * @param mapImageIcon           * @param ox
2040           *            <code>null</code> is allowed and deactivates this icon.           *            X-Koordinate der VON-Position
2041             * @param oy
2042             *            Y-Koordinate der VON-Position
2043             * @param px
2044             *            X-Koordinate der BIS-Position
2045             * @param py
2046             *            Y-Koordinate der BIS-Position
2047           */           */
2048          public void setMapImage(BufferedImage mapImage) {          public Envelope tranformWindowToGeo(final int ox, final int oy,
2049                  this.mapImage = mapImage;                          final int px, final int py) {
2050                    final AffineTransform at = getScreenToWorld();
2051                    final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2052                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2053    
2054                    // Mmmmm... don't really understand why its x,x,y,y
2055                    // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2056                    // geoP.getY());
2057                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2058                                    new Coordinate(geoP.getX(), geoP.getY()));
2059          }          }
2060    
2061          /**          /**
2062           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Will update the cursor. If all rendering is finished also stops the
2063             * {@link #repaintTimer}
2064           */           */
2065          private BufferedImage getLocalImage() {          public void updateCursor() {
2066    
2067                  if (localImage == null) {                  // if the renderers have stopped, also stop the timer that is updating
2068                          localImage = new BufferedImage(getBounds().width,                  // the final image
2069                                          getBounds().height, BufferedImage.TYPE_INT_ARGB);                  if (bgExecuter != null && bgExecuter.isRunning()
2070                                    || localExecuter != null && localExecuter.isRunning()) {
2071                            setCursor(WAIT_CURSOR);
2072                            return;
2073                    } else {
2074                            // Allow one last rendering
2075                            if (repaintTimer.isRunning()) {
2076                                    // System.out.println("one last rendering....");
2077                                    repaintTimer.stop();
2078                                    updateFinalImage();
2079                                    repaint();
2080                            }
2081                  }                  }
2082    
2083                  return localImage;                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
2084          }                  // von der aktuellen Aktion
2085                    if (this.staticCursor != null) {
2086          /**                          setCursor(staticCursor);
2087           * Called by the {@linkplain XMapPane.RenderingTask} when rendering has been                          return;
2088           * completed Publishes a {@linkplain MapPaneEvent} of type {@code                  }
2089           * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.                  if (getCursor() == SwingUtil.PANNING_CURSOR) {
2090           *                          // This cursor will reset itself
2091           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)                          return;
2092           */                  }
         public void onRenderingCompleted() {  
                 repainterTimer.stop();  
                 updateFinalImage();  
                 repaint();  
         }  
   
         /**  
          * Called by the {@linkplain XMapPane.RenderingTask} when rendering was  
          * cancelled. Publishes a {@linkplain MapPaneEvent} of type {@code  
          * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.  
          *  
          * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)  
          */  
         public void onRenderingCancelled() {  
                 repainterTimer.stop();  
                 LOGGER.debug("Rendering cancelled");  
         }  
   
         /**  
          * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.  
          * Publishes a {@linkplain MapPaneEvent} of type {@code  
          * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.  
          *  
          * @param renderingError  
          *            The error that occured during rendering  
          *  
          * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)  
          */  
         public void onRenderingFailed(Exception renderingError) {  
                 repainterTimer.stop();  
                 LOGGER.warn("Rendering failed", renderingError);  
                 updateFinalImage();  
                 repaint();  
2093    
2094                    // Set the cursor depending on what tool is in use...
2095                    switch (state) {
2096                    case SELECT_TOP:
2097                    case SELECT_ONE_FROM_TOP:
2098                    case SELECT_ALL:
2099                            setCursor(SwingUtil.CROSSHAIR_CURSOR);
2100                            break;
2101                    case ZOOM_IN:
2102                            setCursor(SwingUtil.ZOOMIN_CURSOR);
2103                            break;
2104                    case ZOOM_OUT:
2105                            setCursor(SwingUtil.ZOOMOUT_CURSOR);
2106                            break;
2107                    case PAN:
2108                            setCursor(SwingUtil.PAN_CURSOR);
2109                            break;
2110                    default:
2111                            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2112                            break;
2113                    }
2114          }          }
2115    
2116          /**          /**
2117           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * The renderers are all rendering into their own {@link Image}s. This
2118           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * method combines all images to one {@link #finalImage}. The
2119           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>           * {@link #repaintTimer} is calling this method regularely to update the
2120           * Since 21. April 09: Before thecalculation starts, the aspect ratio is           * {@link #finalImage} even if the renderers are still working.
          * corrected. This change implies, that setMapArea() will most of the time  
          * not allow setting to a wrong aspectRatio.  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
2121           */           */
2122          public Envelope bestAllowedMapArea(Envelope env) {          synchronized protected Image updateFinalImage() {
                 if (getWidth() == 0)  
                         return env;  
                 if (env == null)  
                         return null;  
2123    
2124                  Envelope newArea = null;                  // Render the two map images first, into the preFinalImage
2125                    if (bgExecuter != null) {
2126                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
2127                                            .getGraphics();
2128                            preFinalG.setBackground(getMapBackgroundColor());
2129    
2130                  /**                          preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
2131                   * Correct the aspect Ratio before we check the rest. Otherwise we might                                          null);
                  * easily fail. We allow to grow here, because we don't check against  
                  * the maxExtend  
                  */  
                 Rectangle curPaintArea = getVisibleRect();  
2132    
2133                  env = JTSUtil.fixAspectRatio(curPaintArea, env, true);                          // // Draw the local layers image
2134                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
2135                            preFinalG.dispose();
2136    
                 final double scale = env.getWidth() / getWidth();  
                 final double centerX = env.getMinX() + env.getWidth() / 2.;  
                 final double centerY = env.getMinY() + env.getHeight() / 2.;  
                 double newWidth2 = 0;  
                 double newHeight2 = 0;  
                 if (scale < getMaxZoomScale()) {  
                         // ****************************************************************************  
                         // Wir zoomen weiter rein als erlaubt => Anpassen des envelope  
                         // ****************************************************************************  
                         newWidth2 = getMaxZoomScale() * getWidth() / 2.;  
                         newHeight2 = getMaxZoomScale() * getHeight() / 2.;  
                 } else if (scale > getMinZoomScale()) {  
                         // ****************************************************************************  
                         // Wir zoomen weiter raus als erlaubt => Anpassen des envelope  
                         // ****************************************************************************  
                         newWidth2 = getMinZoomScale() * getWidth() / 2.;  
                         newHeight2 = getMinZoomScale() * getHeight() / 2.;  
2137                  } else {                  } else {
2138                          // ****************************************************************************                          preFinalImage = getLocalImage();
                         // Die mapArea / der Envelope ist ist gueltig! Keine Aenderungen  
                         // ****************************************************************************  
                         newArea = env;  
                 }  
   
                 if (newArea == null) {  
   
                         final Coordinate ll = new Coordinate(centerX - newWidth2, centerY  
                                         - newHeight2);  
                         final Coordinate ur = new Coordinate(centerX + newWidth2, centerY  
                                         + newHeight2);  
   
                         newArea = new Envelope(ll, ur);  
2139                  }                  }
2140    
2141                  Envelope maxAllowedExtend = getMaxExtend();                  final Graphics2D finalG = getFinalImage().createGraphics();
2142                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  finalG.setBackground(getMapBackgroundColor());
2143                                  && newArea != null && !newArea.isNull()                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
2144                                  && !Double.isNaN(newArea.getMinX())                                  getMapBackgroundColor(), null);
                                 && !Double.isNaN(newArea.getMaxX())  
                                 && !Double.isNaN(newArea.getMinY())  
                                 && !Double.isNaN(newArea.getMaxY())) {  
                         /*  
                          * If a maxExtend is set, we have to honour that...  
                          */  
   
                         // Exceeds top? Move down and maybe cut  
                         if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {  
                                 double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();  
                                 // LOGGER.debug("Moving area down by " + divY);  
   
                                 newArea = new Envelope(new Coordinate(newArea.getMinX(),  
                                                 newArea.getMinY() - divY), new Coordinate(newArea  
                                                 .getMaxX(), newArea.getMaxY() - divY));  
   
                                 if (newArea.getMinY() < maxAllowedExtend.getMinY()) {  
                                         // LOGGER.debug("Now it exeeds the bottom border.. cut!");  
                                         // And cut the bottom if it moved out of the area  
                                         newArea = new Envelope(new Coordinate(newArea.getMinX(),  
                                                         maxAllowedExtend.getMinY()), new Coordinate(newArea  
                                                         .getMaxX(), newArea.getMaxY()));  
   
                                         // LOGGER.debug("and fix aspect ratio");  
   
                                         newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,  
                                                         false);  
                                 }  
                         }  
   
                         // Exceeds bottom? Move up and maybe cut  
                         if (newArea.getMinY() < maxAllowedExtend.getMinY()) {  
                                 double divY = newArea.getMinY() - maxAllowedExtend.getMinY();  
                                 // LOGGER.debug("Moving area up by " + divY);  
   
                                 newArea = new Envelope(new Coordinate(newArea.getMinX(),  
                                                 newArea.getMinY() - divY), new Coordinate(newArea  
                                                 .getMaxX(), newArea.getMaxY() - divY));  
   
                                 if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {  
                                         // LOGGER.debug("Now it exeeds the top border.. cut!");  
                                         // And cut the bottom if it moved out of the area  
                                         newArea = new Envelope(new Coordinate(newArea.getMinX(),  
                                                         newArea.getMinY()), new Coordinate(newArea  
                                                         .getMaxX(), maxAllowedExtend.getMaxY()));  
   
                                         // LOGGER.debug("and fix aspect ratio");  
2145    
2146                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                  final int finalImageHeight = getFinalImage().getHeight(null);
2147                                                          false);                  final int finalImageWidth = getFinalImage().getWidth(null);
                                 }  
                         }  
2148    
2149                          // Exceeds to the right? move and maybe cut                  final Rectangle painedArea = new Rectangle(imageOrigin.x,
2150                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                                  imageOrigin.y, finalImageWidth, finalImageHeight);
2151                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
2152    
2153                                  // Move left..                  addGadgets(finalG, false);
                                 double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();  
                                 // LOGGER.debug("Moving area left by " + divX);  
2154    
2155                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                  finalG.dispose();
                                                 newArea.getMinY()), new Coordinate(newArea.getMaxX()  
                                                 - divX, newArea.getMaxY()));  
2156    
2157                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                  return finalImage;
2158                                          // LOGGER.debug("Now it exeeds the left border.. cut!");          }
                                         // And cut the left if it moved out of the area  
                                         newArea = new Envelope(new Coordinate(maxAllowedExtend  
                                                         .getMinX(), newArea.getMinY()), new Coordinate(  
                                                         newArea.getMaxX(), newArea.getMaxY()));  
2159    
2160                                          // LOGGER.debug("and fix aspect ratio");          /**
2161             * Paints some optional stuff into the given {@link Graphics2D}. Usually
2162             * called as the last layer when {@link #updateFinalImage()}
2163             *
2164             * @param forceWait
2165             *            if <code>true</code>, a Wait-message will be painted even
2166             *            though the rendering threads may not yet have started. If
2167             *            <code>false</code>, it will only depend on
2168             *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2169             */
2170            private void addGadgets(final Graphics2D graphics, boolean forceWait) {
2171    
2172                    // Paint a logo to the bottom right if available
2173                    if (mapImage != null) {
2174                            Rectangle visibleRect = getVisibleRect();
2175                            graphics.drawImage(mapImage, visibleRect.width
2176                                            - mapImage.getWidth() - 10, getVisibleRect().height
2177                                            - mapImage.getHeight() - 10, null);
2178                    }
2179    
2180                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                  int y = 17;
                                                         false);  
                                 }  
                         }  
2181    
2182                          // Exceeds to the left? move and maybe cut                  // If the rendering process is still running, indicate this is the image
2183                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2184                                    || localExecuter != null && localExecuter.isRunning()) {
2185    
2186                                  // Move right..                          y += 8;
                                 double divX = newArea.getMinX() - maxAllowedExtend.getMinX();  
                                 // LOGGER.debug("Moving area right by " + divX);  
2187    
2188                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                          final Color c = graphics.getColor();
2189                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()                          graphics.setFont(waitFont);
                                                 - divX, newArea.getMaxY()));  
2190    
2191                                  if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                          graphics.setColor(getMapBackgroundColor());
2192                                          // LOGGER.debug("Now it exeeds the right border.. cut!");                          graphics.drawString(waitMsg, 5, y);
2193                                          // And cut the left if it moved out of the area                          graphics.setColor(getMapBackgroundColor());
2194                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                          graphics.drawString(waitMsg, 7, y + 2);
2195                                                          newArea.getMinY()), new Coordinate(maxAllowedExtend                          graphics.setColor(Color.BLACK);
2196                                                          .getMaxX(), newArea.getMaxY()));                          graphics.drawString(waitMsg, 6, y + 1);
2197    
2198                                          // LOGGER.debug("and fix aspect ratio");                          graphics.setColor(c);
2199    
2200                                          newArea = JTSUtil.fixAspectRatio(this.getBounds(), newArea,                          y += 24;
                                                         false);  
                                 }  
                         }  
2201                  }                  }
2202    
2203                  return newArea;                  if (renderingErrors != null && isShowExceptions()) {
         }  
2204    
2205          /**                          final Color c = graphics.getColor();
2206           * Retuns the minimum allowed zoom scale. This is the bigger number value of                          graphics.setFont(errorFont);
          * the two. Defaults to {@link Double}.MAX_VALUE  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         public Double getMinZoomScale() {  
                 return minZoomScale;  
         }  
2207    
2208          /**                          for (Exception ex : renderingErrors) {
          * Retuns the maximum allowed zoom scale. This is the smaller number value  
          * of the two. Defaults to {@link Double}.MIN_VALUE  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         public Double getMaxZoomScale() {  
                 return maxZoomScale;  
         }  
2209    
2210          /**                                  String errStr = ex.getLocalizedMessage();
          * Set the maximum allowed zoom scale. This is the smaller number value of  
          * the two. If <code>null</code> is passed, Double.MINVALUE are used which  
          * mean there is no restriction.  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         public void setMaxZoomScale(final Double maxZoomScale) {  
                 this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE  
                                 : maxZoomScale;  
         }  
2211    
2212          /**                                  if (errStr == null)
2213           * Set the minimum (nearest) allowed zoom scale. This is the bigger number                                          errStr = ex.getMessage();
2214           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are                                  if (errStr == null)
2215           * used which mean there is no restriction.                                          errStr = "unknown error: " + ex.getClass().getSimpleName();
          *  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         public void setMinZoomScale(final Double minZoomScale) {  
                 this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE  
                                 : minZoomScale;  
         }  
   
         /**  
          * Defines an evelope of the viwable area. The JMapPane will never show  
          * anything outside of this extend.  
          *  
          * @param maxExtend  
          *            <code>null</code> to not have this restriction.  
          */  
         public void setMaxExtend(Envelope maxExtend) {  
                 this.maxExtend = maxExtend;  
         }  
2216    
2217          /**                                  graphics.setColor(Color.WHITE);
2218           * Returns the evelope of the viewable area. The JMapPane will never show                                  graphics.drawString(errStr, 5, y);
2219           * anything outside of this extend. If this has been set to                                  graphics.setColor(Color.RED);
2220           * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return                                  graphics.drawString(errStr, 6, y + 1);
          * quickly the context's bounds. It it takes to long to determine the  
          * context bounds, <code>null</code> is returned.  
          *  
          * @param maxExtend  
          *            <code>null</code> to not have this restriction.  
          */  
2221    
2222          public Envelope getMaxExtend() {                                  y += 19;
                 if (maxExtend == null) {  
                         final ReferencedEnvelope layerBounds = GTUtil  
                                         .getVisibleLayoutBounds(localContext);  
                         if (layerBounds == null) {  
                                 // TODO Last fallback could be the CRS valid area  
                                 return null;  
2223                          }                          }
2224    
2225                          // Kartenbereich um 10% vergroessern                          graphics.setColor(c);
                         return JTSUtil.fixAspectRatio(this.getBounds(), JTSUtil  
                                         .expandEnvelope(layerBounds, 0.1), true);  
2226                  }                  }
                 return maxExtend;  
         }  
   
         /**  
          * Set the background color of the map.  
          *  
          * @param if <code>null</code>, white is used.  
          */  
         public void setMapBackgroundColor(Color bgColor) {  
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
                 this.mapBackgroundColor = bgColor;  
         }  
   
         /**  
          * Returns the background {@link Color} of the map pane. Default is white.  
          **/  
         public Color getMapBackgroundColor() {  
                 return mapBackgroundColor;  
         }  
   
         /**  
          *  
          * @param b  
          */  
         public void setPainting(boolean b) {  
                 acceptsRepaintCalls = b;  
         }  
2227    
         /**  
          * Fuegt der Map einen Listener hinzu.  
          *  
          * @param l  
          *            neuer Listener  
          */  
         public void addMapPaneListener(JMapPaneListener l) {  
                 mapPaneListeners.add(l);  
2228          }          }
2229    
2230          /**          /**
2231           * Liste der angeschlossenen Listener, die auf Aktionen des MapPanes           * Sets the {@link #mapArea} to best possibly present the given features. If
2232           * lauschen.           * only one single point is given, the window is moved over the point.
          */  
         protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();  
   
         /**  
          * A flag indicating if dispose() was already called. If true, then further  
          * use of this {@link SelectableXMapPane} is undefined.  
          */  
         private boolean disposed = false;  
   
         /**  
          * Entfernt einen Listener von der Map.  
2233           *           *
2234           * @param l           * @param features
2235           *            zu entfernender Listener           *            if <code>null</code> or size==0, the function doesn nothing.
2236           */           */
2237          public void removeMapPaneListener(JMapPaneListener l) {          public void zoomTo(
2238                  mapPaneListeners.remove(l);                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
         }  
2239    
2240  //      /** Stored the time used for the last real rendering in ms. **/                  // if (!isWellDefined()) return;
 //      private long lastRenderingDuration = Long.MAX_VALUE;  
2241    
2242          // if null, no quick preview will be shown                  final CoordinateReferenceSystem mapCRS = getMapContext()
2243          private int quickPreviewHint = 0;                                  .getCoordinateReferenceSystem();
2244                    final CoordinateReferenceSystem fCRS = features.getSchema()
2245          /**                                  .getGeometryDescriptor().getCoordinateReferenceSystem();
          * For every rendering thread started,  
          * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new  
          * renderer. These Java2D rendering hints are passed to the  
          * {@link GTRenderer}. The java2dHints are the same for all renderers (bg  
          * and local).  
          */  
         private RenderingHints java2dHints;  
2246    
2247  //      /**                  ReferencedEnvelope _mapArea;
2248  //       * Returns in milli seconds the time the last rending of the                  if (mapArea == null)
2249  //       * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has not                          _mapArea = features.getBounds();
2250  //       * been rendered yet.                  else _mapArea = getMapArea();
2251  //       */                  double width = _mapArea.getWidth();
2252  //      public long getLastRenderingDuration() {                  double height = _mapArea.getHeight();
2253  //              return lastRenderingDuration;                  final double ratio = height / width;
 //      }  
2254    
2255          /**                  if (features == null || features.size() == 0) {
2256           * Should be called when the {@link JMapPane} is not needed no more to help                          // feature count == 0 Zoom to the full extend
          * the GarbageCollector  
          *  
          * Removes all {@link JMapPaneListener}s that are registered  
          *  
          * @author <a href="mailto:[email protected]">Stefan Alfons  
          *         Kr&uuml;ger</a>  
          */  
         public void dispose() {  
                 if (isDisposed())  
2257                          return;                          return;
2258                    } else if (features.size() == 1) {
2259    
2260                  setPainting(false);                          // feature count == 1 Just move the window to the point and zoom 'a
2261                                            // bit'
2262                  resizeTimer.stop();                          final SimpleFeature singleFeature = features.iterator().next();
                 startRenderThreadsTimer.stop();  
   
                 disposed = true;  
2263    
2264                  if (bgExecuter != null) {                          if (((Geometry) singleFeature.getDefaultGeometry())
2265                          bgExecuter.cancelTask();                                          .getCoordinates().length > 1) {
2266                          bgExecuter.dispose();                                  // System.out.println("Zoomed to only pne poylgon");
2267                  }                                  // Poly
2268                                    // TODO max width vs. height
2269                                    width = features.getBounds().getWidth() * 3;
2270                                    height = ratio * width;
2271                            } else {
2272                                    // System.out.println("Zoomed in a bit becasue only one point");
2273                                    // width *= .9;
2274                                    // height *= .9;
2275                            }
2276    
2277                  if (localExecuter != null) {                          Coordinate centre = features.getBounds().centre();
2278                          int i = 0;                          if (!mapCRS.equals(fCRS)) {
2279                          localExecuter.cancelTask();                                  // only to calculations if the CRS differ
                         while (i++ < 10 && localExecuter.isRunning()){  
2280                                  try {                                  try {
2281                                          Thread.sleep(200);                                          MathTransform fToMap;
2282                                  } catch (InterruptedException e) {                                          fToMap = CRS.findMathTransform(fCRS, mapCRS);
2283                                          // TODO Auto-generated catch block                                          // centre is transformed to the mapCRS
2284                                          e.printStackTrace();                                          centre = JTS.transform(centre, null, fToMap);
2285                                    } catch (final FactoryException e) {
2286                                            LOGGER.error("Looking for a Math transform", e);
2287                                    } catch (final TransformException e) {
2288                                            LOGGER.error("Looking for a Math transform", e);
2289                                  }                                  }
2290                          }                          }
                         if (localExecuter.isRunning()) {  
                                 System.out.println("BAD BAD BAD... still running the thread....");  
                         }  
                         localExecuter.dispose();  
                 }  
   
   
                 if (bgImage != null) {  
                         bgImage = dispose(bgImage);  
                         bgImage = null;  
 //                      LangUtil.gcTotal();  
                 }  
   
                 if (localImage != null) {  
                         localImage = dispose(localImage);  
                         localImage = null;  
 //                      LangUtil.gcTotal();  
                 }  
2291    
2292                  if (finalImage != null) {                          final Coordinate newLeftBottom = new Coordinate(centre.x - width
2293                          finalImage = dispose(finalImage);                                          / 2., centre.y - height / 2.);
2294                          finalImage = null;                          final Coordinate newTopRight = new Coordinate(
2295  //                      LangUtil.gcTotal();                                          centre.x + width / 2., centre.y + height / 2.);
                 }  
   
                 if (preFinalImage != null) {  
                         preFinalImage = dispose(preFinalImage);  
                         preFinalImage=null;  
                 }  
                   
 //              LangUtil.gcTotal();  
2296    
2297                  // Alle mapPaneListener entfernen                          final Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
                 mapPaneListeners.clear();  
2298    
2299                  removeMouseMotionListener(zoomMapPaneMouseListener);                          setMapArea(newMapArea);
                 removeMouseListener(zoomMapPaneMouseListener);  
2300    
2301                  if (localContext != null)                  } else {
2302                          getContext().clearLayerList();                          final ReferencedEnvelope fBounds = features.getBounds();
                 if (bgContext != null)  
                         getBgContext().clearLayerList();  
2303    
2304                  removeAll();                          ReferencedEnvelope bounds;
2305          }                          if (!mapCRS.equals(fCRS)) {
2306                                    bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2307                            } else {
2308                                    bounds = fBounds;
2309                            }
2310                            // BB umrechnen von Layer-CRS in Map-CRS
2311    
2312          private BufferedImage dispose(BufferedImage bi) {                          // Expand a bit
2313                            bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
2314    
2315  //              System.out.println("vorher = "                          setMapArea(bounds);
2316  //                      + new MbDecimalFormatter().format(LangUtil.gcTotal()));                  }
                 bi.flush();  
                 return bi = null;  
 //              System.out.println("nacher = "  
 //                              + new MbDecimalFormatter().format(LangUtil.gcTotal()));  
 //  
 //              System.out.println("\n");  
2317          }          }
2318    
2319          /**          /**
2320           * A flag indicating if dispose() has already been called. If true, then           * Zooms towards a point.
2321           * further use of this {@link SelectableXMapPane} is undefined.           *
2322             * @param center
2323             *            position in window coordinates
2324             * @param zoomFactor
2325             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2326           */           */
2327          private boolean isDisposed() {          public void zoomTo(final Point center) {
2328                  return disposed;                  zoomTo(center, null);
         }  
   
         public void setQuickPreviewHint(int quickPreviewHint) {  
                 this.quickPreviewHint = quickPreviewHint;  
   
         }  
   
         public void setJava2dHints(RenderingHints java2dHints) {  
                 this.java2dHints = java2dHints;  
         }  
   
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
2329          }          }
2330    
2331          /**          /**
# Line 2062  public class XMapPane extends JPanel { Line 2340  public class XMapPane extends JPanel {
2340                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2341                          zoomFaktor = 2.;                          zoomFaktor = 2.;
2342    
2343                  Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2344                  center = null;                  center = null;
2345    
2346                  if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())                  if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
# Line 2076  public class XMapPane extends JPanel { Line 2354  public class XMapPane extends JPanel {
2354    
2355                  final Envelope mapArea = getMapArea();                  final Envelope mapArea = getMapArea();
2356    
2357                  Envelope newMapArea = new Envelope(mapArea);                  final Envelope newMapArea = new Envelope(mapArea);
2358                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2359                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2360                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2361    
2362                  // Move the newMapArea above the new center                  // TODO we actually want that
2363                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                  // // Move the newMapArea above the new center
2364                                  .getY()                  // newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2365                                  - mapArea.centre().y);                  // .getY()
2366                    // - mapArea.centre().y);
2367    
2368                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2369          }          }
2370    
2371          /**          /**
2372           * Zooms towards a point.           * Shall non-fatal rendering exceptions be reported in the mappane or be
2373           *           * dropped quitely.
          * @param center  
          *            position in window coordinates  
          * @param zoomFactor  
          *            > 1 for zoom in, < 1 for zoom out. Default is 1.33  
2374           */           */
2375          public void zoomTo(Point center) {          public void setShowExceptions(boolean showExceptions) {
2376                  zoomTo(center, null);                  this.showExceptions = showExceptions;
         }  
   
         public void mouseDragged(Point startPos, Point lastPos, MouseEvent event) {  
   
                 if ((getState() == XMapPane.PAN)  
                                 || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {  
   
                         if (getCursor() != SwingUtil.PANNING_CURSOR) {  
                                 setCursor(SwingUtil.PANNING_CURSOR);  
   
                                 // While panning, we deactivate the rendering. So the tasts are  
                                 // ready to start when the panning os done.  
                                 if (bgExecuter != null)  
                                         bgExecuter.cancelTask();  
                                 if (localExecuter != null)  
                                         localExecuter.cancelTask();  
                         }  
   
                         if (lastPos.x > 0 && lastPos.y > 0) {  
                                 final int dx = event.getX() - lastPos.x;  
                                 final int dy = event.getY() - lastPos.y;  
   
                                 // TODO Stop dragging when the drag would not be valid...  
                                 // boolean dragValid = true;  
                                 // // check if this panning results in a valid mapArea  
                                 // {  
                                 // Rectangle winBounds = xMapPane.getBounds();  
                                 // winBounds.translate(xMapPane.imageOrigin.x,  
                                 // -xMapPane.imageOrigin.y);  
                                 // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //                                        
                                 //  
                                 // winBounds = xMapPane.getBounds();  
                                 // Point testIng = new Point(xMapPane.imageOrigin);  
                                 // testIng.translate(dx, dy);  
                                 // winBounds.translate(testIng.x, -testIng.y);  
                                 // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //  
                                 // // If the last drag doesn't change the MapArea anymore cancel  
                                 // it.  
                                 // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(  
                                 // xMapPane.bestAllowedMapArea(newMapAreaBefore))){  
                                 // dragValid = false;  
                                 // return;  
                                 // }  
                                 // }  
   
                                 imageOrigin.translate(dx, dy);  
                                 updateFinalImage();  
                                 repaint();  
                         }  
   
                 } else if ((getState() == XMapPane.ZOOM_IN)  
                                 || (getState() == XMapPane.ZOOM_OUT)  
                                 || (getState() == XMapPane.SELECT_ALL)  
                                 || (getState() == XMapPane.SELECT_TOP)  
                 // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)  
                 ) {  
                         final Graphics graphics = getGraphics();  
   
                         drawRectangle(graphics, startPos, event.getPoint());  
   
                         if ((lastPos.x > 0) && (lastPos.y > 0)) {  
                                 drawRectangle(graphics, startPos, lastPos);  
                         }  
   
                         graphics.dispose();  
   
                 }  
   
         }  
   
         /**  
          * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the  
          * given point. All in screen coordinates.  
          */  
         protected void drawRectangle(final Graphics graphics, Point startPos,  
                         Point e) {  
   
                 if (!isWellDefined())  
                         return;  
   
                 // undraw last box/draw new box  
                 final int left = Math.min(startPos.x, e.x);  
                 final int right = Math.max(startPos.x, e.x);  
                 final int top = Math.max(startPos.y, e.y);  
                 final int bottom = Math.min(startPos.y, e.y);  
                 final int width = right - left;  
                 final int height = top - bottom;  
   
                 if (width == 0 && height == 0)  
                         return;  
   
                 graphics.setXORMode(Color.WHITE);  
                 graphics.drawRect(left, bottom, width, height);  
2377          }          }
2378    
2379          /**          /**
2380           * Finalizes a PAN action           * Shall exceptions be reported in the mappane?
2381           */           */
2382          public void performPan() {          public boolean isShowExceptions() {
2383                  Rectangle winBounds = getBounds();                  return showExceptions;
                 winBounds.translate(-imageOrigin.x, -imageOrigin.y);  
                 Envelope newMapArea = tranformWindowToGeo(winBounds.x, winBounds.y,  
                                 winBounds.x + winBounds.width, winBounds.y + winBounds.height);  
   
                 imageOrigin.x = 0;  
                 imageOrigin.y = 0;  
   
                 if (!setMapArea(newMapArea)) {  
                         updateFinalImage();  
                         repaint();  
                 }  
   
                 if (getCursor() == SwingUtil.PANNING_CURSOR)  
                         setCursor(SwingUtil.PAN_CURSOR);  
         }  
   
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
2384          }          }
2385    
2386  }  }

Legend:
Removed from v.529  
changed lines
  Added in v.553

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26