/[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/JMapPane.java revision 431 by alfonx, Sun Oct 4 16:55:52 2009 UTC branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java revision 558 by alfonx, Tue Nov 24 13:01:09 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;  
   
 /**  
  * <b>Xulu:<br>  
  *    Code taken from gt-2.4.5 to make some changes (marked with {@code xulu}),  
  *    which can not be realized in a subclass:</b>  
  *    <ul>  
  *       <li>{@link #getMapArea()} declared as {@code final}<li>  
  *       <li>some variables declared as {@code protected}</li>  
  *       <li>minimal/maximal zoom scale</li>  
  *       <li>zoom in and zoom out via mouse click realized by setMapArea(..)</li>  
  *    </ul>  
  * <br><br>  
  * A simple map container that is a JPanel with a map in. provides simple  
  * pan,zoom, highlight and selection The mappane stores an image of the map  
  * (drawn from the context) and an image of the slected feature(s) to speed up  
  * rendering of the highlights. Thus the whole map is only redrawn when the bbox  
  * changes, selection is only redrawn when the selected feature changes.  
  *  
  *  
  * @author Ian Turton  
  *  
  */  
2    
3  import java.awt.Color;  import java.awt.Color;
4  import java.awt.Cursor;  import java.awt.Cursor;
5    import java.awt.Font;
6  import java.awt.Graphics;  import java.awt.Graphics;
7  import java.awt.Graphics2D;  import java.awt.Graphics2D;
8  import java.awt.LayoutManager;  import java.awt.Image;
9    import java.awt.Point;
10  import java.awt.Rectangle;  import java.awt.Rectangle;
11    import java.awt.RenderingHints;
12    import java.awt.event.ActionEvent;
13    import java.awt.event.ActionListener;
14    import java.awt.event.ComponentAdapter;
15    import java.awt.event.ComponentEvent;
16  import java.awt.event.InputEvent;  import java.awt.event.InputEvent;
17  import java.awt.event.MouseEvent;  import java.awt.event.MouseEvent;
18  import java.awt.event.MouseListener;  import java.awt.event.MouseListener;
19  import java.awt.event.MouseMotionListener;  import java.awt.geom.AffineTransform;
20    import java.awt.geom.NoninvertibleTransformException;
21    import java.awt.geom.Point2D;
22  import java.awt.image.BufferedImage;  import java.awt.image.BufferedImage;
 import java.beans.PropertyChangeEvent;  
 import java.beans.PropertyChangeListener;  
23  import java.io.IOException;  import java.io.IOException;
24  import java.util.Date;  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;
28    
29  import javax.swing.JPanel;  import javax.swing.Timer;
30    
31  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
32    import org.geotools.feature.FeatureCollection;
33    import org.geotools.geometry.jts.JTS;
34    import org.geotools.geometry.jts.ReferencedEnvelope;
35    import org.geotools.map.DefaultMapContext;
36  import org.geotools.map.MapContext;  import org.geotools.map.MapContext;
37    import org.geotools.map.MapLayer;
38    import org.geotools.map.event.MapLayerEvent;
39  import org.geotools.map.event.MapLayerListEvent;  import org.geotools.map.event.MapLayerListEvent;
40  import org.geotools.map.event.MapLayerListListener;  import org.geotools.map.event.MapLayerListListener;
41    import org.geotools.map.event.MapLayerListener;
42    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.renderer.shape.ShapefileRenderer;  import org.geotools.swing.JMapPane;
49  import org.opengis.filter.FilterFactory2;  import org.geotools.swing.event.MapMouseEvent;
50    import org.geotools.swing.event.MapPaneEvent;
51    import org.geotools.swing.event.MapPaneListener;
52    import org.opengis.feature.simple.SimpleFeature;
53    import org.opengis.feature.simple.SimpleFeatureType;
54    import org.opengis.referencing.FactoryException;
55  import org.opengis.referencing.crs.CoordinateReferenceSystem;  import org.opengis.referencing.crs.CoordinateReferenceSystem;
56    import org.opengis.referencing.operation.MathTransform;
57    import org.opengis.referencing.operation.TransformException;
58    
59    import schmitzm.geotools.GTUtil;
60    import schmitzm.geotools.JTSUtil;
61    import schmitzm.geotools.gui.SelectableXMapPane;
62    import schmitzm.geotools.io.GeoImportUtil;
63    import schmitzm.geotools.map.event.JMapPaneListener;
64    import schmitzm.geotools.map.event.MapLayerAdapter;
65    import schmitzm.lang.LangUtil;
66    import schmitzm.swing.JPanel;
67  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
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.GeometryFactory;  import com.vividsolutions.jts.geom.Geometry;
   
 public class JMapPane extends JPanel implements MouseListener,  
                 MouseMotionListener, PropertyChangeListener, MapLayerListListener {  
         private static Logger LOGGER = Logger.getLogger(JMapPane.class.getName());  
   
         private static final long serialVersionUID = -8647971481359690499L;  
   
         public static final int Reset = 0;  
72    
73          public static final int ZoomIn = 1;  /**
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 {
97    
98          public static final int ZoomOut = 2;          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
99            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;
100    
101          public static final int Pan = 3;          private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
102    
103          public static final int Select = 4;          private boolean acceptsRepaintCalls = true;
104    
105          /**          /**
106           * what renders the map           * Main {@link MapContext} that holds all layers that are rendered into the
107             * {@link #localImage} by the {@link #localRenderer}
108           */           */
109          GTRenderer renderer;          MapContext localContext;
110    
111          /**          /**
112           * the map context to render           * {@link MapContext} holding the background layers. Use it for layers that
113             * CAN take very long for rendering, like layer from the Internet: WMS, WFS,
114             * OSM...<br>
115             * <code>null</code> by default.
116             *
117             * @see #setBgContext(MapContext)
118             * @see #getBgContext()
119           */           */
120          MapContext context;          MapContext bgContext;
121    
122          /**          /**
123           * the area of the map to draw           * While threads are working, calls {@link XMapPane#updateFinalImage()}
124             * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
125             * renderers have finished.
126             *
127             * @see INITIAL_REPAINT_DELAYAL
128             * @see #REPEATING_REPAINT_DELAY
129           */           */
130          protected Envelope mapArea;          final private Timer repaintTimer;
131    
132          /**          /**
133           * the size of the pane last time we drew           * The initial delay in milliseconds until the {@link #finalImage} is
134             * updated the first time.
135           */           */
136          protected Rectangle oldRect = null;          public static final int INITIAL_REPAINT_DELAY = 900;
137    
138          /**          /**
139           * the last map area drawn.           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
140             * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
141             * with previews.
142           */           */
143          protected Envelope oldMapArea = null;          public static final int REPEATING_REPAINT_DELAY = 600;
144    
145          /**          /**
146           * the base image of the map           * 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 #resizeTimer
150           */           */
151          protected BufferedImage baseImage, panningImage;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
152    
153          /**          /**
154           * a factory for filters           * This not-repeating {@link Timer} is re-started whenever the component is
155             * resized. That means => only if the component is not resizing for
156             * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
157             * {@link XMapPane} react.
158           */           */
159          FilterFactory2 ff;          private final Timer resizeTimer;
160    
161          /**          /**
162           * a factory for geometries           * Flag for no-tool.
163           */           */
164          GeometryFactory gf = new GeometryFactory(); // FactoryFinder.getGeometryFactory(null);          public static final int NONE = -123;
   
         private int state = ZoomIn;  
165    
166          /**          /**
167           * how far to zoom in or out           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
168             * moeglich!
169             *
170             * @see #setState(int)
171           */           */
172          private double zoomFactor = 2.0;          public static final int PAN = 1;
   
         boolean changed = true;  
   
         LabelCache labelCache = new LabelCacheImpl();  
   
         protected boolean reset = false;  
   
         int startX;  
   
         int startY;  
173    
174          /**          /**
175           * If not <code>null</code>, the {@link JMapPane} will not allow to zoom/pan           * Flag fuer Modus "Heran zoomen".
176           * out of that area           *
177           **/           * @see #setState(int)
178          private Envelope maxExtend = null;           * @see #setState(int)
179             */
180          // /**          public static final int ZOOM_IN = 2;
         // * Is max. 1 or 0 of the 2 axised allowed to extend the maxExtend? If  
         // * <code>true</code> the extends has to be fully inside maxExtend  
         // **/  
         // boolean maxExtendForceMode = true;  
   
         private boolean clickable;  
   
         int lastX;  
181    
182          int lastY;          /**
183             * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
184             *
185             * @see #setState(int)
186             */
187            public static final int ZOOM_OUT = 3;
188    
189          private Double maxZoomScale = Double.MIN_VALUE;          /**
190          private Double minZoomScale = Double.MAX_VALUE;           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
191             *
192             * @see #setState(int)
193             * @see #setState(int)
194             */
195            public static final int SELECT_ALL = 103;
196            /**
197             * Flag fuer Modus
198             * "Auswahl nur eines Features, das erste sichtbare von Oben".
199             *
200             * @see #setState(int)
201             * @see #setState(int)
202             */
203            public static final int SELECT_ONE_FROM_TOP = 104;
204            /**
205             * Flag fuer Modus
206             * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".
207             *
208             * @see #setState(int)
209             * @see #setState(int)
210             */
211            public static final int SELECT_TOP = 4;
212    
213          /**          /**
214           * Wenn true, dann wurde PANNING via mouseDraged-Events begonnen. Dieses           * {@link Font} used to paint the wait messages into the map
215           * Flag wird benutzt um nur einmal den passenden Cursor nur einmal zu           *
216           * setzen.           * @see #addGadgets(Graphics2D, boolean)
217           */           */
218          private boolean panning_started = false;          final static Font waitFont = new Font("Arial", Font.BOLD, 30);
219    
220          public JMapPane() {          /**
221                  this(null, true, null, null);           * {@link Font} used to paint error messages into the map
222          }           *
223             * @see #addGadgets(Graphics2D, boolean)
224             */
225            final static Font errorFont = new Font("Arial", Font.BOLD, 13);
226    
227          /**          /**
228           * create a basic JMapPane           * The wait message painted into the map while rendering is going on on
229             * another thread.
230           *           *
231           * @param render           * @see #addGadgets(Graphics2D, boolean)
          *            - how to draw the map  
          * @param context  
          *            - the map context to display  
232           */           */
233          public JMapPane(final GTRenderer render, final MapContext context) {          final String waitMsg = SwingUtil.R("WaitMess");
                 this(null, true, render, context);  
         }  
234    
235          /**          /**
236           * full constructor extending JPanel           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
237             * Karten-Koordinaten.
238           *           *
239           * @param layout           * @param e
240           *            - layout (probably shouldn't be set)           *            Maus-Ereignis
          * @param isDoubleBuffered  
          *            - a Swing thing I don't really understand  
          * @param render  
          *            - what to draw the map with  
          * @param context  
          *            - what to draw  
241           */           */
242          public JMapPane(final LayoutManager layout, final boolean isDoubleBuffered,          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {
243                          final GTRenderer render, final MapContext context) {                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
244                  super(layout, isDoubleBuffered);                  if (e != null && e instanceof MapMouseEvent)
245                            try {
246                                    return ((MapMouseEvent) e).getMapPosition().toPoint2D();
247                            } catch (final Exception err) {
248                                    LOGGER
249                                                    .error(
250                                                                    "return ((GeoMouseEvent) e).getMapCoordinate(null).toPoint2D();",
251                                                                    err);
252                            }
253    
254                    // aktuelle Geo-Position ueber Transformation des JMapPane berechnen
255                    if (e != null && e.getSource() instanceof XMapPane) {
256    
257                  ff = (FilterFactory2) org.geotools.factory.CommonFactoryFinder                          final XMapPane xMapPane = (XMapPane) e.getSource();
                                 .getFilterFactory(null);  
                 setRenderer(render);  
258    
259                  setContext(context);                          if (!xMapPane.isWellDefined())
260                                    return null;
261    
262                  this.addMouseListener(this);                          final AffineTransform at = xMapPane.getScreenToWorld();
263                  this.addMouseMotionListener(this);                          if (at != null)
264                  setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));                                  return at.transform(e.getPoint(), null);
265                            return null;
266                    }
267                    throw new IllegalArgumentException(
268                                    "MouseEvent has to be of instance MapMouseEvent or come from an XMapPane");
269          }          }
270    
271          /**          /**
272           * get the renderer           * Listens to changes of the "background" {@link MapContext} and triggers
273             * repaints where needed.
274           */           */
275          public GTRenderer getRenderer() {          private final MapLayerListListener bgContextListener = new MapLayerListListener() {
                 return renderer;  
         }  
276    
277          public void setRenderer(final GTRenderer renderer) {                  @Override
278                  Map<Object, Object> hints = new HashMap<Object, Object>();                  public void layerAdded(final MapLayerListEvent event) {
279                            MapLayer layer = event.getLayer();
280                            layer.addMapLayerListener(bgMapLayerListener);
281                            requestStartRendering();
282    
283                  this.renderer = renderer;                  }
284    
285                  if (renderer instanceof StreamingRenderer                  @Override
286                                  || renderer instanceof ShapefileRenderer) {                  public void layerChanged(final MapLayerListEvent event) {
287                          hints = renderer.getRendererHints();                          requestStartRendering();
288                          if (hints == null) {                  }
                                 hints = new HashMap<Object, Object>();  
                         }  
                         if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) {  
                                 labelCache = (LabelCache) hints  
                                                 .get(StreamingRenderer.LABEL_CACHE_KEY);  
                         } else {  
                                 hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);  
                         }  
289    
290                          hints.put("memoryPreloadingEnabled", Boolean.TRUE);                  @Override
291                    public void layerMoved(final MapLayerListEvent event) {
292                            requestStartRendering();
293                    }
294    
295                          renderer.setRendererHints(hints);                  @Override
296                    public void layerRemoved(final MapLayerListEvent event) {
297                            if (event.getLayer() != null)
298                                    event.getLayer().removeMapLayerListener(bgMapLayerListener);
299                            requestStartRendering();
300                  }                  }
301            };
302    
303                  // this.highlightRenderer = new StreamingRenderer();          /**
304                  // this.selectionRenderer = new StreamingRenderer();           * This {@link RenderingExecutor} manages the creation and cancellation of
305             * up to one {@link Thread} for rendering the {@link #localContext}.
306             */
307            private final RenderingExecutor localExecuter = new RenderingExecutor(this);
308    
309                  // highlightRenderer.setRendererHints(hints);          /**
310                  // selectionRenderer.setRendererHints(hints);           * This {@link RenderingExecutor} manages the creation and cancellation of
311             * up to one {@link Thread} for rendering the {@link #bgContext}.
312             */
313            protected RenderingExecutor bgExecuter;
314    
315                  // renderer.setRendererHints(hints);          /**
316             * The {@link #localRenderer} for the {@link #localContext} uses this
317             * {@link Image}.
318             */
319            private BufferedImage localImage;
320    
321                  if (this.context != null) {          /**
322                          this.renderer.setContext(this.context);           * The {@link #bgRenderer} for the {@link #bgContext} uses this
323                  }           * {@link Image}.
324          }           */
325            private BufferedImage bgImage;
326    
327          public MapContext getContext() {          /**
328                  return context;           * This {@link Image} is a merge of the {@link #bgImage},
329          }           * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
330             * updated with {@link #updateFinalImage()} and used for painting in
331             * {@link #paintComponent(Graphics)}
332             */
333            private BufferedImage finalImage;
334    
335          public void setContext(final MapContext context) {          /**
336                  if (this.context != null) {           * Optionally a transparent image to paint over the map in the lower right
337                          this.context.removeMapLayerListListener(this);           * corner.
338                  }           *
339             * @see #addGadgets(Graphics2D)
340             * @see #setMapImage(BufferedImage)
341             **/
342            private BufferedImage mapImage = null;
343    
344                  this.context = context;          /**
345             * Listens to each layer in the local {@link MapContext} for changes and
346             * triggers repaints.
347             */
348            protected MapLayerListener bgMapLayerListener = new MapLayerAdapter() {
349    
350                  if (context != null) {                  @Override
351                          this.context.addMapLayerListListener(this);                  public void layerChanged(final MapLayerEvent event) {
352                            requestStartRendering();
353                  }                  }
354    
355                  if (renderer != null) {                  @Override
356                          renderer.setContext(this.context);                  public void layerHidden(final MapLayerEvent event) {
357                            requestStartRendering();
358                  }                  }
         }  
359    
360          public Envelope getMapArea() {                  @Override
361                  return mapArea;                  public void layerShown(final MapLayerEvent event) {
362          }                          requestStartRendering();
363                    }
364            };
365    
366          public void setMapArea(final Envelope mapArea) {          /**
367                  this.mapArea = mapArea;           * A flag indicating if dispose() was already called. If true, then further
368          }           * use of this {@link SelectableXMapPane} is undefined.
369             */
370            private boolean disposed = false;
371    
372          public int getState() {          /**
373                  return state;           * While dragging, the {@link #updateFinalImage()} method is translating the
374          }           * cached images while setting it together.
375             **/
376            Point imageOrigin = new Point(0, 0);
377            /**
378             * For every rendering thread started,
379             * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
380             * renderer. These Java2D rendering hints are passed to the
381             * {@link GTRenderer}. The java2dHints are the same for all renderers (bg
382             * and local).
383             */
384            private RenderingHints java2dHints;
385    
386          public void setState(final int state) {          protected LabelCache labelCache = new LabelCacheImpl();
                 this.state = state;  
387    
388                  // System.out.println("State: " + state);          /**
389          }           * Listens to changes of the "local" {@link MapContext} and triggers
390             * repaints where needed.
391             */
392            private final MapLayerListListener localContextListener = new MapLayerListListener() {
393    
394          public double getZoomFactor() {                  @Override
395                  return zoomFactor;                  public void layerAdded(final MapLayerListEvent event) {
396          }                          event.getLayer().addMapLayerListener(localMapLayerListener);
397    
398          public void setZoomFactor(final double zoomFactor) {                          localRenderer.setContext(getMapContext());
399                  this.zoomFactor = zoomFactor;                          requestStartRendering();
         }  
400    
401          protected void paintComponent(final Graphics g) {                  }
                 super.paintComponent(g);  
402    
403                  if ((renderer == null) || (mapArea == null)) {                  @Override
404                          return;                  public void layerChanged(final MapLayerListEvent event) {
405                            localRenderer.setContext(getMapContext());
406                            requestStartRendering();
407                  }                  }
408    
409                  final Rectangle r = getBounds();                  @Override
410                  final Rectangle dr = new Rectangle(r.width, r.height);                  public void layerMoved(final MapLayerListEvent event) {
411                            localRenderer.setContext(getMapContext());
412                            requestStartRendering();
413                    }
414    
415                  if (!r.equals(oldRect) || reset) {                  @Override
416                          if (!r.equals(oldRect) && (mapArea == null)) {                  public void layerRemoved(final MapLayerListEvent event) {
417                                  try {                          if (event.getLayer() != null)
418                                          mapArea = context.getLayerBounds();                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
419                                  } catch (final IOException e) {                          localRenderer.setContext(getMapContext());
420                                          LOGGER.warn("context.getLayerBounds()", e);                          requestStartRendering();
421                                  }                  }
422                          }          };
423    
424                          if (mapArea != null) {          /**
425                                  /* either the viewer size has changed or we've done a reset */           * Listens to each layer in the local {@link MapContext} for changes and
426                                  changed = true; /* note we need to redraw */           * triggers repaints.
427                                  reset = false; /* forget about the reset */           */
428                                  oldRect = r; /* store what the current size is */          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
429    
430                                  mapArea = fixAspectRatio(r, mapArea, false);                  @Override
431                          }                  public void layerChanged(final MapLayerEvent event) {
432                            localRenderer.setContext(getMapContext()); // betters for SLD
433                            // changes?!
434                            requestStartRendering();
435                  }                  }
436    
437                  if (!mapArea.equals(oldMapArea)) { /* did the map extent change? */                  @Override
438                          changed = true;                  public void layerHidden(final MapLayerEvent event) {
439                          oldMapArea = mapArea;                          requestStartRendering();
                         // when we tell the context that the bounds have changed WMSLayers  
                         // can refresh them selves  
                         context.setAreaOfInterest(mapArea, context  
                                         .getCoordinateReferenceSystem());  
440                  }                  }
441    
442                  if (changed) { /* if the map changed then redraw */                  @Override
443                          changed = false;                  public void layerShown(final MapLayerEvent event) {
444                          baseImage = new BufferedImage(dr.width, dr.height,                          requestStartRendering();
445                                          BufferedImage.TYPE_INT_ARGB);                  }
446            };
447    
448                          final Graphics2D ig = baseImage.createGraphics();          private final GTRenderer localRenderer = GTUtil.createGTRenderer();
                         /* System.out.println("rendering"); */  
                         if (renderer.getContext() != null)  
                                 renderer.setContext(context);  
                         labelCache.clear(); // work around anoying labelcache bug  
449    
450                          // draw the map          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
                         renderer.paint((Graphics2D) ig, dr, mapArea);  
451    
452                          // TODO nur machen, wenn panning beginnt          /**
453                          panningImage = new BufferedImage(dr.width, dr.height,           * the area of the map to draw
454                                          BufferedImage.TYPE_INT_RGB);           */
455            protected Envelope mapArea = null;
456    
457                  }          /**
458             * A flag set it {@link #setMapArea(Envelope)} to indicated the
459             * {@link #paintComponent(Graphics)} method, that the image on-screen is
460             * associated with {@link #oldMapArea} and may hence be scaled for a quick
461             * preview.<br>
462             * The flag is reset
463             **/
464            private boolean mapAreaChanged = false;
465    
466                  ((Graphics2D) g).drawImage(baseImage, 0, 0, this);          /**
467          }           * This color is used as the default background color when painting a map.
468             */
469            private Color mapBackgroundColor = null;
470    
471          /**          /**
472           * Returns an {@link Envelope} that has the same aspect ratio as the given rectangle           * A flag indicating that the shown image is invalid and needs to be
473           * @param grow           * re-rendered.
          *            If <code>true</code>, than the area will be enlarged to match  
          *            the aspect ratio. If <code>false</code>, it will only shrink.  
474           */           */
475          private Envelope fixAspectRatio(final Rectangle r, final Envelope mapArea,          protected boolean mapImageInvalid = true;
                         boolean grow) {  
                   
                 if (mapArea == null) {  
                         LOGGER.warn("mapArea has been null in method fixAspectRatio, returning an unmodified ");  
                 }  
476    
477                  final double mapWidth = mapArea.getWidth(); /* get the extent of the map */          /**
478                  final double mapHeight = mapArea.getHeight();           * Holds a flag for each layer, whether it is regarded or ignored on
479                  final double scaleX = r.getWidth() / mapArea.getWidth(); /*           * {@link #SELECT_TOP}, {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP}
480                                                                                                                                   * calculate the           * actions.
481                                                                                                                                   * new scale           */
482                                                                                                                                   */          final protected HashMap<MapLayer, Boolean> mapLayerSelectable = new HashMap<MapLayer, Boolean>();
483    
484                  final double scaleY = r.getHeight() / mapArea.getHeight();          /**
485                  double scale = 1.0; // stupid compiler!           * List of listeners of this {@link XMapPane}
486             */
487            protected Vector<JMapPaneListener> mapPaneListeners = new Vector<JMapPaneListener>();
488            /**
489             * If not <code>null</code>, the {@link XMapPane} will not allow to zoom/pan
490             * out of that area
491             **/
492            private Envelope maxExtend = null;
493            private Double maxZoomScale = Double.MIN_VALUE;
494    
495                  if ((grow && scaleX < scaleY) || (!grow && scaleX > scaleY)) {          private Double minZoomScale = Double.MAX_VALUE;
                         scale = scaleX;  
                 } else {  
                         scale = scaleY;  
                 }  
496    
497                  /* calculate the difference in width and height of the new extent */          /**
498                  final double deltaX = /* Math.abs */((r.getWidth() / scale) - mapWidth);           * We store the old mapArea for a moment to use it for the
499                  final double deltaY = /* Math.abs */((r.getHeight() / scale) - mapHeight);           * "quick scaled preview" in case of ZoomOut
500             **/
501            protected Envelope oldMapArea = null;
502    
503                  /*          /**
504                   * System.out.println("delta x " + deltaX);           * We store the old transform for a moment to use it for the
505                   * System.out.println("delta y " + deltaY);           * "quick scaled preview" in case of ZoomIn
506                   */           **/
507            protected AffineTransform oldScreenToWorld = null;
508    
509                  /* create the new extent */          /**
510                  final Coordinate ll = new Coordinate(           * A flag indicating, that the image size has changed and the buffered
511                                  mapArea.getMinX() - (deltaX / 2.0), mapArea.getMinY()           * images are not big enough any more
512                                                  - (deltaY / 2.0));           **/
513                  final Coordinate ur = new Coordinate(          protected boolean paneResized = true;
                                 mapArea.getMaxX() + (deltaX / 2.0), mapArea.getMaxY()  
                                                 + (deltaY / 2.0));  
514    
515                  return new Envelope(ll, ur);          private BufferedImage preFinalImage;
         }  
516    
517          public void mouseClicked(final MouseEvent e) {          // ** if 0, no quick preview will be shown **/
518                  if (mapArea == null)          private int quickPreviewHint = 0;
                         return;  
                 // System.out.println("before area "+mapArea+"\nw:"+mapArea.getWidth()+"  
                 // h:"+mapArea.getHeight());  
                 final Rectangle bounds = this.getBounds();  
                 final double x = (double) (e.getX());  
                 final double y = (double) (e.getY());  
                 final double width = mapArea.getWidth();  
                 final double height = mapArea.getHeight();  
                 // xulu.sc  
                 // double width2 = mapArea.getWidth() / 2.0;  
                 // double height2 = mapArea.getHeight() / 2.0;  
                 final double width2 = width / 2.0;  
                 final double height2 = height / 2.0;  
                 // xulu.ec  
                 final double mapX = ((x * width) / (double) bounds.width)  
                                 + mapArea.getMinX();  
                 final double mapY = (((bounds.getHeight() - y) * height) / (double) bounds.height)  
                                 + mapArea.getMinY();  
519    
520                  /*          private Map<Object, Object> rendererHints = GTUtil
521                   * System.out.println(""+x+"->"+mapX);                          .getDefaultGTRendererHints(localRenderer);
                  * System.out.println(""+y+"->"+mapY);  
                  */  
522    
523                  /*          /**
524                   * Coordinate ll = new Coordinate(mapArea.getMinX(), mapArea.getMinY());           * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
525                   * Coordinate ur = new Coordinate(mapArea.getMaxX(), mapArea.getMaxY());           * start rendering {@link Thread}s
526                   */           **/
527                  double zlevel = 1.0;          private volatile Boolean requestStartRendering = false;
528    
529                  switch (state) {          /**
530                  case Pan:           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
531                          zlevel = 1.0;           * (lat/lon)
532                          // xulu.sc SK: return here.. a mouselistener is managing the PANNING           */
533                          // break;          protected AffineTransform screenToWorld = null;
                         return;  
                         // xulu.ec  
                 case ZoomIn:  
                         zlevel = zoomFactor;  
534    
535                          break;          /**
536             * The flag {@link #requestStartRendering} can be set to true by events.
537             * This {@link Timer} checks the flag regularly and starts one renderer
538             * thread.
539             */
540            final private Timer startRenderThreadsTimer;
541    
542                  case ZoomOut:          /**
543                          zlevel = 1.0 / zoomFactor;           * The default state is ZOOM_IN, hence by default the
544             * {@link #zoomMapPaneMouseListener} is also enabled.
545             **/
546            private int state = ZOOM_IN;
547    
548                          break;          /**
549                  //           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
550                  // case Select:           * MapPane-Funktion
551                  // doSelection(mapX, mapY, selectionLayer);           */
552                  //          protected Cursor staticCursor = null;
                 // return;  
553    
554                  default:          private AffineTransform worldToScreen;
                         return;  
                 }  
555    
556                  final Coordinate ll = new Coordinate(mapX - (width2 / zlevel), mapY          /**
557                                  - (height2 / zlevel));           * This {@link MouseListener} is managing all zoom related tasks
558                  final Coordinate ur = new Coordinate(mapX + (width2 / zlevel), mapY           */
559                                  + (height2 / zlevel));          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
560                  // xulu.sc SK: Check for min/max scale                          this);
                 // mapArea = new Envelope(ll, ur);  
                 final Envelope newMapArea = new Envelope(ll, ur);  
                 setMapArea(bestAllowedMapArea(newMapArea));  
                 // xulu.ec  
561    
562                  // sk.ec          /** Is set if a renderer has an error **/
563            protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
564    
565                  // System.out.println("after area "+mapArea+"\nw:"+mapArea.getWidth()+"          /**
566                  // h:"+mapArea.getHeight());           * If <code>true</code>, then rendering exceptions are rendererd into the
567                  repaint();           * map pane
568          }           **/
569            private boolean showExceptions = false;
570    
571          public void mouseEntered(final MouseEvent e) {          public XMapPane() {
572                    this(null, null);
573          }          }
574    
575          public void mouseExited(final MouseEvent e) {          /**
576          }           * full constructor extending JPanel
577             *
578             * @param rendererHints
579             *            may be <code>null</code>. Otherwise a {@link Map<Object,
580             *            Object>} of {@link RenderingHints} to override the default
581             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
582             *
583             * @param localContext
584             *            The main {@link MapContext} to use. If <code>null</code>, an
585             *            empty {@link DefaultMapContext} will be created.
586             */
587            public XMapPane(final MapContext localContext_,
588                            final Map<Object, Object> rendererHints) {
589                    super(true);
590    
591          public void mousePressed(final MouseEvent e) {                  setRendererHints(rendererHints);
                 startX = e.getX();  
                 startY = e.getY();  
                 lastX = 0;  
                 lastY = 0;  
         }  
592    
593          public void mouseReleased(final MouseEvent e) {                  setOpaque(true);
                 final int endX = e.getX();  
                 final int endY = e.getY();  
594    
595                  processDrag(startX, startY, endX, endY, e);                  if (localContext_ != null)
596                  lastX = 0;                          setLocalContext(localContext_);
                 lastY = 0;  
597    
598                  /**                  /**
599                   * Es wird nicht (mehr) gepannt!                   * Adding the #zoomMapPaneMouseListener
600                   */                   */
601                  panning_started = false;                  this.addMouseListener(zoomMapPaneMouseListener);
602          }                  this.addMouseMotionListener(zoomMapPaneMouseListener);
603                    this.addMouseWheelListener(zoomMapPaneMouseListener);
         public void mouseDragged(final MouseEvent e) {  
                 final Graphics graphics = this.getGraphics();  
                 final int x = e.getX();  
                 final int y = e.getY();  
604    
605                  if ((state == JMapPane.Pan)                  /*
606                                  || ((e.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {                   * We use a Timer object to avoid rendering delays and flickering when
607                          /**                   * the user is drag-resizing the parent container of this map pane.
608                           * SK: Der Cursor wird auf PANNING gesetzt.                   *
609                           */                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
610                          if (panning_started == false) {                   * pane receives a stream of events during drag-resizing.
611                                  panning_started = true;                   */
612                                  setCursor(SwingUtil.PANNING_CURSOR);                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
613                          }                                  new ActionListener() {
614    
615                          // move the image with the mouse                                          public void actionPerformed(final ActionEvent e) {
616                          if ((lastX > 0) && (lastY > 0)) {                                                  if (!isWellDefined())
617                                  final int dx = lastX - startX;                                                          return;
618                                  final int dy = lastY - startY;  
619                                  // System.out.println("translate "+dx+","+dy);                                                  LOGGER.debug("resizeTimer performed");
620                                  final Graphics2D g2 = panningImage.createGraphics();  
621                                  g2.setBackground(new Color(240, 240, 240)); // TODO richtige                                                  final Rectangle bounds = getVisibleRect();
622                                  // farbe? am besten                                                  //
623                                  // vom L&F die                                                  // System.out.println("\n\ntimer performs with bounds = "
624                                  // hintergrundfarbe                                                  // + bounds);
625                                  // auslesen...  
626                                                    final Envelope geoMapArea = tranformWindowToGeo(
627                                                                    bounds.x, bounds.y, bounds.x + bounds.width,
628                                                                    bounds.y + bounds.height);
629    
630                                                    if (setMapArea(geoMapArea)) {
631                                                            LOGGER.debug("  maparea changed");
632                                                            paneResized = true;
633                                                    } else
634                                                            LOGGER.debug("  maparea NOT changed");
635                                            }
636                                    });
637                    resizeTimer.setRepeats(false);
638    
639                    this.addComponentListener(new ComponentAdapter() {
640    
641                            private Rectangle oldVisibleRect;
642    
643                            @Override
644                            public void componentResized(final ComponentEvent e) {
645    
646                                    // Seems to be called twice with the same size..
647                                    if (oldVisibleRect != null
648                                                    && oldVisibleRect.equals(getVisibleRect())) {
649                                            LOGGER.debug("skipping resize.");
650                                            return;
651                                    }
652    
653                                  g2.clearRect(0, 0, this.getWidth(), this.getHeight());                                  LOGGER.debug("resized: " + getVisibleRect());
654                                  g2.drawImage(baseImage, dx, dy, this);                                  resizeTimer.restart();
655                                  graphics.drawImage(panningImage, 0, 0, this);                                  oldVisibleRect = getVisibleRect();
656                          }                          }
657    
658                          lastX = x;                  });
                         lastY = y;  
                 } else  
659    
660                  if ((state == JMapPane.ZoomIn) || (state == JMapPane.ZoomOut)) {                  /*
661                     * Setting up the repaintTimer. Not started automatically.
662                     */
663                    repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
664    
665                          graphics.setXORMode(Color.WHITE);                          @Override
666                            public void actionPerformed(final ActionEvent e) {
667                                    if ((!localExecuter.isRunning())
668                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
669                                            repaintTimer.stop();
670                                    } else {
671                                            updateFinalImage();
672                                            XMapPane.this.repaint(100);
673    
674                          if ((lastX > 0) && (lastY > 0)) {                                  }
                                 drawRectangle(graphics);  
675                          }                          }
676                    });
677    
678                          // draw new box                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
679                          lastX = x;                  repaintTimer.setRepeats(true);
                         lastY = y;  
                         drawRectangle(graphics);  
                 }  
                 // else if (state == JMapPane.Select && selectionLayer != null) {  
                 //  
                 // // construct a new bbox filter  
                 // final Rectangle bounds = this.getBounds();  
                 //  
                 // final double mapWidth = mapArea.getWidth();  
                 // final double mapHeight = mapArea.getHeight();  
                 //  
                 // final double x1 = ((this.startX * mapWidth) / (double) bounds.width)  
                 // + mapArea.getMinX();  
                 // final double y1 = (((bounds.getHeight() - this.startY) * mapHeight) /  
                 // (double) bounds.height)  
                 // + mapArea.getMinY();  
                 // final double x2 = ((x * mapWidth) / (double) bounds.width)  
                 // + mapArea.getMinX();  
                 // final double y2 = (((bounds.getHeight() - y) * mapHeight) / (double)  
                 // bounds.height)  
                 // + mapArea.getMinY();  
                 // final double left = Math.min(x1, x2);  
                 // final double right = Math.max(x1, x2);  
                 // final double bottom = Math.min(y1, y2);  
                 // final double top = Math.max(y1, y2);  
                 //  
                 // String name = selectionLayer.getFeatureSource().getSchema()  
                 // .getDefaultGeometry().getName();  
                 //  
                 // if (name == "") {  
                 // name = "the_geom";  
                 // }  
                 // final Filter bb = ff.bbox(ff.property(name), left, bottom, right,  
                 // top,  
                 // getContext().getCoordinateReferenceSystem().toString());  
                 // if (selectionManager != null) {  
                 // selectionManager.selectionChanged(this, bb);  
                 // }  
                 //  
                 // graphics.setXORMode(Color.green);  
                 //  
                 // /*  
                 // * if ((lastX > 0) && (lastY > 0)) { drawRectangle(graphics); }  
                 // */  
                 //  
                 // // draw new box  
                 // lastX = x;  
                 // lastY = y;  
                 // drawRectangle(graphics);  
                 // }  
680    
681          }                  /*
682                     * Setting up the startRenderThreadsTimer. This Timer starts
683          // sk.cs                   * automatically.
         // private void processDrag(int x1, int y1, int x2, int y2) {  
         // sk.ce  
         protected void processDrag(final int x1, final int y1, final int x2,  
                         final int y2, final MouseEvent e) {  
   
   
                 /****  
                  * If no layers exist, we ignore the drag.  
684                   */                   */
685                  if (context.getLayerCount() <= 0) {                  startRenderThreadsTimer = new Timer(100, new ActionListener() {
                         return;  
                 }  
                   
                 // System.out.println("processing drag from " + x1 + "," + y1 + " -> "  
                 // + x2 + "," + y2);  
                 if ((x1 == x2) && (y1 == y2)) {  
                         if (isClickable()) {  
                                 mouseClicked(new MouseEvent(this, 0, new Date().getTime(), 0,  
                                                 x1, y1, y2, false));  
                         }  
   
                         return;  
                 }  
   
                 final Rectangle bounds = this.getBounds();  
   
                 final double mapWidth = mapArea.getWidth();  
                 final double mapHeight = mapArea.getHeight();  
   
                 final double startX = ((x1 * mapWidth) / (double) bounds.width)  
                                 + mapArea.getMinX();  
                 final double startY = (((bounds.getHeight() - y1) * mapHeight) / (double) bounds.height)  
                                 + mapArea.getMinY();  
                 final double endX = ((x2 * mapWidth) / (double) bounds.width)  
                                 + mapArea.getMinX();  
                 final double endY = (((bounds.getHeight() - y2) * mapHeight) / (double) bounds.height)  
                                 + mapArea.getMinY();  
   
                 if ((state == JMapPane.Pan) || (e.getButton() == MouseEvent.BUTTON3)) {  
                         // move the image with the mouse  
                         // calculate X offsets from start point to the end Point  
                         final double deltaX1 = endX - startX;  
   
                         // System.out.println("deltaX " + deltaX1);  
                         // new edges  
                         final double left = mapArea.getMinX() - deltaX1;  
                         final double right = mapArea.getMaxX() - deltaX1;  
   
                         // now for Y  
                         final double deltaY1 = endY - startY;  
   
                         // System.out.println("deltaY " + deltaY1);  
                         final double bottom = mapArea.getMinY() - deltaY1;  
                         final double top = mapArea.getMaxY() - deltaY1;  
                         final Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                           
   
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
                         // xulu.ec  
                 } else if (state == JMapPane.ZoomIn) {  
   
                         // Zu kleine Flächen sollen nicht gezoomt werden.  
                         // sk.bc  
                         if ((Math.abs(x1 - x2) * Math.abs(y2 - y1)) < 150)  
                                 return;  
                         // sk.ec  
   
                         drawRectangle(this.getGraphics());  
                         // make the dragged rectangle (in map coords) the new BBOX  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
                         final Coordinate ll = new Coordinate(left, bottom);  
                         final Coordinate ur = new Coordinate(right, top);  
                         // xulu.sc  
   
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // sk.sc  
                         // {  
                         // // SK tries to paint a preview of the zoom ;-9 aha.... well  
                         // Graphics2D graphics = (Graphics2D) JMapPane.this.getGraphics();  
                         // 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);  
                         // graphics.drawImage(baseImage, 0, 0, JMapPane.this.getWidth(),  
                         // JMapPane.this.getHeight(), x1, y1, x2, y2, null);  
                         // }  
                         // xulu.ec  
                 } else if (state == JMapPane.ZoomOut) {  
                         drawRectangle(this.getGraphics());  
   
                         // make the dragged rectangle in screen coords the new map size?  
                         final double left = Math.min(startX, endX);  
                         final double right = Math.max(startX, endX);  
                         final double bottom = Math.min(startY, endY);  
                         final double top = Math.max(startY, endY);  
                         final double nWidth = (mapWidth * mapWidth) / (right - left);  
                         final double nHeight = (mapHeight * mapHeight) / (top - bottom);  
                         final double deltaX1 = left - mapArea.getMinX();  
                         final double nDeltaX1 = (deltaX1 * nWidth) / mapWidth;  
                         final double deltaY1 = bottom - mapArea.getMinY();  
                         final double nDeltaY1 = (deltaY1 * nHeight) / mapHeight;  
                         final Coordinate ll = new Coordinate(mapArea.getMinX() - nDeltaX1,  
                                         mapArea.getMinY() - nDeltaY1);  
                         final double deltaX2 = mapArea.getMaxX() - right;  
                         final double nDeltaX2 = (deltaX2 * nWidth) / mapWidth;  
                         final double deltaY2 = mapArea.getMaxY() - top;  
                         final double nDeltaY2 = (deltaY2 * nHeight) / mapHeight;  
                         final Coordinate ur = new Coordinate(mapArea.getMaxX() + nDeltaX2,  
                                         mapArea.getMaxY() + nDeltaY2);  
                         // xulu.sc  
                         // mapArea = fixAspectRatio(this.getBounds(), new Envelope(ll, ur));  
                         setMapArea(bestAllowedMapArea(new Envelope(ll, ur)));  
   
                         // xulu.ec  
                 }  
                 // else if (state == JMapPane.Select && selectionLayer != null) {  
                 // final double left = Math.min(startX, endX);  
                 // final double right = Math.max(startX, endX);  
                 // final double bottom = Math.min(startY, endY);  
                 // final double top = Math.max(startY, endY);  
                 //  
                 // String name = selectionLayer.getFeatureSource().getSchema()  
                 // .getDefaultGeometry().getLocalName();  
                 //  
                 // if (name == "") {  
                 // name = "the_geom";  
                 // }  
                 // final Filter bb = ff.bbox(ff.property(name), left, bottom, right,  
                 // top,  
                 // getContext().getCoordinateReferenceSystem().toString());  
                 // // System.out.println(bb.toString());  
                 // if (selectionManager != null) {  
                 // selectionManager.selectionChanged(this, bb);  
                 // }  
                 // /*  
                 // * FeatureCollection fc; selection = null; try { fc =  
                 // * selectionLayer.getFeatureSource().getFeatures(bb); selection =  
                 // * fc; } catch (IOException e) { e.printStackTrace(); }  
                 // */  
                 // }  
686    
687                  // xulu.so                          @Override
688                  // setMapArea(mapArea);                          public void actionPerformed(final ActionEvent e) {
689                  // xulu.eo                                  synchronized (requestStartRendering) {
690                  repaint();                                          if (requestStartRendering && isWellDefined()) {
691          }  
692                                                    if (localExecuter.isRunning()) {
693          private boolean isClickable() {                                                          localExecuter.cancelTask();
694                  return clickable;                                                  } else {
695          }                                                          // Stupidly, but we have to recheck the
696                                                            setMapArea(getMapArea());
697          //                                                          requestStartRendering = false;
698          // private org.geotools.styling.Style setupStyle(final int type, final Color                                                          startRendering();
699          // color) {                                                  }
700          // final StyleFactory sf = org.geotools.factory.CommonFactoryFinder                                          }
701          // .getStyleFactory(null);                                  }
         // final StyleBuilder sb = new StyleBuilder();  
         //  
         // org.geotools.styling.Style s = sf.createStyle();  
         // s.setTitle("selection");  
         //  
         // // TODO parameterise the color  
         // final PolygonSymbolizer ps = sb.createPolygonSymbolizer(color);  
         // ps.setStroke(sb.createStroke(color));  
         //  
         // final LineSymbolizer ls = sb.createLineSymbolizer(color);  
         // final Graphic h = sb.createGraphic();  
         // h.setMarks(new Mark[] { sb.createMark("square", color) });  
         //  
         // final PointSymbolizer pts = sb.createPointSymbolizer(h);  
         //  
         // // Rule r = sb.createRule(new Symbolizer[]{ps,ls,pts});  
         // switch (type) {  
         // case POLYGON:  
         // s = sb.createStyle(ps);  
         //  
         // break;  
         //  
         // case POINT:  
         // s = sb.createStyle(pts);  
         //  
         // break;  
         //  
         // case LINE:  
         // s = sb.createStyle(ls);  
         // }  
         //  
         // return s;  
         // }  
   
         public void propertyChange(final PropertyChangeEvent evt) {  
                 final String prop = evt.getPropertyName();  
   
                 if (prop.equalsIgnoreCase("crs")) {  
                         context.setAreaOfInterest(context.getAreaOfInterest(),  
                                         (CoordinateReferenceSystem) evt.getNewValue());  
                 }  
         }  
   
         public boolean isReset() {  
                 return reset;  
         }  
   
         public void setReset(final boolean reset) {  
                 this.reset = reset;  
         }  
   
         public void layerAdded(final MapLayerListEvent event) {  
                 changed = true;  
   
                 if (context.getLayers().length == 1) { // the first one  
   
                         try {  
                                 // xulu.sc  
                                 // mapArea = context.getLayerBounds();  
                                 mapArea = context.getAreaOfInterest();  
                                 if (mapArea == null)  
                                         mapArea = context.getLayerBounds();  
                                 // xulu.ec  
                         } catch (final IOException e) {  
                                 // TODO Auto-generated catch block  
                                 e.printStackTrace();  
702                          }                          }
703                    });
704                    startRenderThreadsTimer.start();
705    
                         reset = true;  
                 }  
   
                 repaint();  
         }  
   
         public void layerRemoved(final MapLayerListEvent event) {  
                 changed = true;  
                 repaint();  
         }  
   
         public void layerChanged(final MapLayerListEvent event) {  
                 changed = true;  
                 // System.out.println("layer changed - repaint");  
                 repaint();  
         }  
   
         public void layerMoved(final MapLayerListEvent event) {  
                 changed = true;  
                 repaint();  
         }  
   
         protected void drawRectangle(final Graphics graphics) {  
                 // undraw last box/draw new box  
                 final int left = Math.min(startX, lastX);  
                 final int right = Math.max(startX, lastX);  
                 final int top = Math.max(startY, lastY);  
                 final int bottom = Math.min(startY, lastY);  
                 final int width = right - left;  
                 final int height = top - bottom;  
                 // System.out.println("drawing rect("+left+","+bottom+","+ width+","+  
                 // height+")");  
                 graphics.drawRect(left, bottom, width, height);  
706          }          }
707    
708          /**          /**
709           * if clickable is set to true then a single click on the map pane will zoom           * Fuegt der Map einen Listener hinzu.
          * or pan the map.  
710           *           *
711           * @param clickable           * @param l
712             *            neuer Listener
713           */           */
714          public void setClickable(final boolean clickable) {          public void addMapPaneListener(final JMapPaneListener l) {
715                  this.clickable = clickable;                  mapPaneListeners.add(l);
716          }          }
717    
         public void mouseMoved(final MouseEvent e) {  
         }  
   
         // xulu.sn  
718          /**          /**
719           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste           * Korrigiert den {@link Envelope} aka {@code mapArea} auf die beste
720           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten           * erlaubte Flaeche damit die Massstabsbeschaenkungen noch eingehalten
721           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br/>           * werden, FALLS der uebergeben Envelope nicht schon gueltig sein sollte.<br>
722           * Since 21. April 09: Before thecalculation starts, the aspect ratio is           * Since 21. April 09: Before thecalculation starts, the aspect ratio is
723           * corrected. This change implies, that setMapArea() will most of the time           * corrected. This change implies, that setMapArea() will most of the time
724           * not allow setting to a wrong aspectRatio.           * not allow setting to a wrong aspectRatio.
# Line 914  public class JMapPane extends JPanel imp Line 726  public class JMapPane extends JPanel imp
726           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
727           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
728           */           */
729          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
730    
731                  if (getWidth() == 0)                  if (getWidth() == 0)
732                          return env;                          return env;
733    
734                  if (env == null)                  if (env == null)
735                          return env;                          return null;
736    
737                  Envelope newArea = null;                  Envelope newArea = null;
738    
739                  /**                  /**
740                   * Correct the aspect Ratio before we check the rest. Otherwise we might                   * Correct the aspect Ratio before we check the rest. Otherwise we might
741                   * easily fail.                   * easily fail. We allow to grow here, because we don't check against
742                     * the maxExtend
743                   */                   */
744                  env = fixAspectRatio(this.getBounds(), env, false);                  final Rectangle curPaintArea = getVisibleRect();
745    
746                    env = JTSUtil.fixAspectRatio(curPaintArea, env, true);
747    
748                  final double scale = env.getWidth() / getWidth();                  final double scale = env.getWidth() / getWidth();
749                  final double centerX = env.getMinX() + env.getWidth() / 2.;                  final double centerX = env.getMinX() + env.getWidth() / 2.;
# Line 962  public class JMapPane extends JPanel imp Line 779  public class JMapPane extends JPanel imp
779                          newArea = new Envelope(ll, ur);                          newArea = new Envelope(ll, ur);
780                  }                  }
781    
782                  Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
783                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)) {  
784                    while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
785                                    && newArea != null && !newArea.isNull()
786                                    && !Double.isNaN(newArea.getMinX())
787                                    && !Double.isNaN(newArea.getMaxX())
788                                    && !Double.isNaN(newArea.getMinY())
789                                    && !Double.isNaN(newArea.getMaxY())) {
790                          /*                          /*
791                           * If a maxExtend is set, we have to honour that...                           * If a maxExtend is set, we have to honour that...
792                           */                           */
793    
794                          // Exceeds top? Move down and maybe cut                          // Exceeds top? Move down and maybe cut
795                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                          if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
796                                  double divY = newArea.getMaxY() - maxAllowedExtend.getMaxY();                                  final double divY = newArea.getMaxY()
797                                  LOGGER.debug("Moving area down by " + divY);                                                  - maxAllowedExtend.getMaxY();
798                                    // LOGGER.debug("Moving area down by " + divY);
799    
800                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
801                                                  newArea.getMinY() - divY), new Coordinate(newArea                                                  newArea.getMinY() - divY), new Coordinate(newArea
802                                                  .getMaxX(), newArea.getMaxY() - divY));                                                  .getMaxX(), newArea.getMaxY() - divY));
803    
804                                  if (newArea.getMinY() < maxAllowedExtend.getMinY()) {                                  if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
805                                          LOGGER.debug("Now it exeeds the bottom border.. cut!");                                          // LOGGER.debug("Now it exeeds the bottom border.. cut!");
806                                          // And cut the bottom if it moved out of the area                                          // And cut the bottom if it moved out of the area
807                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
808                                                          maxAllowedExtend.getMinY()), new Coordinate(newArea                                                          maxAllowedExtend.getMinY()), new Coordinate(newArea
809                                                          .getMaxX(), newArea.getMaxY()));                                                          .getMaxX(), newArea.getMaxY()));
810    
811                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
812    
813                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
814                                                            new ReferencedEnvelope(newArea, env
815                                                                            .getCoordinateReferenceSystem()), false);
816                                  }                                  }
817                          }                          }
818    
819                          // Exceeds bottom? Move up and maybe cut                          // Exceeds bottom? Move up and maybe cut
820                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {                          if (newArea.getMinY() < maxAllowedExtend.getMinY()) {
821                                  double divY = newArea.getMinY() - maxAllowedExtend.getMinY();                                  final double divY = newArea.getMinY()
822                                  LOGGER.debug("Moving area up by " + divY);                                                  - maxAllowedExtend.getMinY();
823                                    // LOGGER.debug("Moving area up by " + divY);
824    
825                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),                                  newArea = new Envelope(new Coordinate(newArea.getMinX(),
826                                                  newArea.getMinY() - divY), new Coordinate(newArea                                                  newArea.getMinY() - divY), new Coordinate(newArea
827                                                  .getMaxX(), newArea.getMaxY() - divY));                                                  .getMaxX(), newArea.getMaxY() - divY));
828    
829                                  if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {                                  if (newArea.getMaxY() > maxAllowedExtend.getMaxY()) {
830                                          LOGGER.debug("Now it exeeds the top border.. cut!");                                          // LOGGER.debug("Now it exeeds the top border.. cut!");
831                                          // And cut the bottom if it moved out of the area                                          // And cut the bottom if it moved out of the area
832                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
833                                                          newArea.getMinY()), new Coordinate(newArea                                                          newArea.getMinY()), new Coordinate(newArea
834                                                          .getMaxX(), maxAllowedExtend.getMaxY()));                                                          .getMaxX(), maxAllowedExtend.getMaxY()));
835    
836                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
837    
838                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
839                                                            new ReferencedEnvelope(newArea, env
840                                                                            .getCoordinateReferenceSystem()), false);
841                                  }                                  }
842                          }                          }
843    
# Line 1016  public class JMapPane extends JPanel imp Line 845  public class JMapPane extends JPanel imp
845                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                          if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
846    
847                                  // Move left..                                  // Move left..
848                                  double divX = newArea.getMaxX() - maxAllowedExtend.getMaxX();                                  final double divX = newArea.getMaxX()
849                                  LOGGER.debug("Moving area left by " + divX);                                                  - maxAllowedExtend.getMaxX();
850                                    // LOGGER.debug("Moving area left by " + divX);
851    
852                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
853                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()
854                                                  - divX, newArea.getMaxY()));                                                  - divX, newArea.getMaxY()));
855    
856                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                                  if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
857                                          LOGGER.debug("Now it exeeds the left border.. cut!");                                          // LOGGER.debug("Now it exeeds the left border.. cut!");
858                                          // And cut the left if it moved out of the area                                          // And cut the left if it moved out of the area
859                                          newArea = new Envelope(new Coordinate(maxAllowedExtend.getMinX(),                                          newArea = new Envelope(new Coordinate(maxAllowedExtend
860                                                          newArea.getMinY()), new Coordinate(newArea                                                          .getMinX(), newArea.getMinY()), new Coordinate(
861                                                          .getMaxX(), newArea.getMaxY()));                                                          newArea.getMaxX(), newArea.getMaxY()));
862    
863                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
864    
865                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
866                                                            new ReferencedEnvelope(newArea, env
867                                                                            .getCoordinateReferenceSystem()), false);
868                                  }                                  }
869                          }                          }
870    
# Line 1040  public class JMapPane extends JPanel imp Line 872  public class JMapPane extends JPanel imp
872                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {                          if (newArea.getMinX() < maxAllowedExtend.getMinX()) {
873    
874                                  // Move right..                                  // Move right..
875                                  double divX = newArea.getMinX() - maxAllowedExtend.getMinX();                                  final double divX = newArea.getMinX()
876                                  LOGGER.debug("Moving area right by " + divX);                                                  - maxAllowedExtend.getMinX();
877                                    // LOGGER.debug("Moving area right by " + divX);
878    
879                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,                                  newArea = new Envelope(new Coordinate(newArea.getMinX() - divX,
880                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()                                                  newArea.getMinY()), new Coordinate(newArea.getMaxX()
881                                                  - divX, newArea.getMaxY()));                                                  - divX, newArea.getMaxY()));
882    
883                                  if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {                                  if (newArea.getMaxX() > maxAllowedExtend.getMaxX()) {
884                                          LOGGER.debug("Now it exeeds the right border.. cut!");                                          // LOGGER.debug("Now it exeeds the right border.. cut!");
885                                          // And cut the left if it moved out of the area                                          // And cut the left if it moved out of the area
886                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),                                          newArea = new Envelope(new Coordinate(newArea.getMinX(),
887                                                          newArea.getMinY()), new Coordinate(maxAllowedExtend                                                          newArea.getMinY()), new Coordinate(maxAllowedExtend
888                                                          .getMaxX(), newArea.getMaxY()));                                                          .getMaxX(), newArea.getMaxY()));
889    
890                                          LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
891    
892                                          newArea = fixAspectRatio(this.getBounds(), newArea, false);                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
893                                                            new ReferencedEnvelope(newArea, env
894                                                                            .getCoordinateReferenceSystem()), false);
895                                  }                                  }
896                          }                          }
   
897                  }                  }
898    
899                  return newArea;                  return new ReferencedEnvelope(newArea, env
900                                    .getCoordinateReferenceSystem());
901          }          }
902    
903          /**          /**
904           * Retuns the minimum allowed zoom scale. This is the bigger number value of           * Should be called when the {@link JMapPane} is not needed no more to help
905           * the two. Defaults to {@link Double}.MAX_VALUE           * the GarbageCollector
906             *
907             * Removes all {@link JMapPaneListener}s that are registered
908           *           *
909           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
910           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
911           */           */
912          public Double getMinZoomScale() {          public void dispose() {
913                  return minZoomScale;                  if (isDisposed())
914                            return;
915    
916                    setPainting(false);
917    
918                    resizeTimer.stop();
919                    startRenderThreadsTimer.stop();
920    
921                    disposed = true;
922    
923                    if (bgExecuter != null) {
924                            bgExecuter.cancelTask();
925                            bgExecuter.dispose();
926                    }
927    
928                    if (localExecuter.isRunning()) {
929                            int i = 0;
930                            localExecuter.cancelTask();
931                            while (i++ < 10 && localExecuter.isRunning()) {
932                                    try {
933                                            Thread.sleep(200);
934                                    } catch (final InterruptedException e) {
935                                            LOGGER
936                                                            .warn(
937                                                                            "while XMapPane we are waiting for the localExcutor to stop",
938                                                                            e);
939                                    }
940                            }
941                            if (localExecuter.isRunning()) {
942                                    LOGGER
943                                                    .warn("localExecutor Thread still running after 2s! Continuing anyways...");
944                            }
945                            localExecuter.dispose();
946                    }
947    
948                    disposeImages();
949    
950                    // Remove all mapPaneListeners that have registered with us
951                    mapPaneListeners.clear();
952    
953                    removeMouseMotionListener(zoomMapPaneMouseListener);
954                    removeMouseListener(zoomMapPaneMouseListener);
955    
956                    if (localContext != null)
957                            getMapContext().clearLayerList();
958                    if (bgContext != null)
959                            getBgContext().clearLayerList();
960    
961                    removeAll();
962            }
963    
964            /**
965             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
966             * given point. All in screen coordinates.
967             */
968            protected void drawRectangle(final Graphics graphics, final Point startPos,
969                            final Point e) {
970    
971                    if (!isWellDefined())
972                            return;
973    
974                    // undraw last box/draw new box
975                    final int left = Math.min(startPos.x, e.x);
976                    final int right = Math.max(startPos.x, e.x);
977                    final int top = Math.max(startPos.y, e.y);
978                    final int bottom = Math.min(startPos.y, e.y);
979                    final int width = right - left;
980                    final int height = top - bottom;
981    
982                    if (width == 0 && height == 0)
983                            return;
984    
985                    graphics.setXORMode(Color.WHITE);
986                    graphics.drawRect(left, bottom, width, height);
987            }
988    
989            /**
990             * Diretly paints scaled preview into the {@link SelectableXMapPane}. Used
991             * to give the user something to look at while we are rendering. Method
992             * should be called after {@link #setMapArea(Envelope)} has been set to the
993             * new mapArea and transform has been reset.<br>
994             *
995             * @param g
996             *            Graphics2D to paint the preview into
997             *
998             * @param state
999             *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}
1000             */
1001            protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1002    
1003                    // if (1 == 1)return false;
1004    
1005                    if (quickPreviewHint == 0)
1006                            return false;
1007    
1008                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1009                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1010                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1011                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1012                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1013                                    RenderingHints.VALUE_RENDER_SPEED);
1014    
1015                    if (oldMapArea == null)
1016                            return false;
1017    
1018                    final Rectangle visibleArea = getVisibleRect();
1019    
1020                    // Calculate the oldMapArea in the current WindowCoordinates:
1021                    final Envelope oldMapWindow = tranformGeoToWindow(oldMapArea.getMinX(),
1022                                    oldMapArea.getMinY(), oldMapArea.getMaxX(), oldMapArea
1023                                                    .getMaxY());
1024    
1025                    final int xx1 = (int) Math.round(oldMapWindow.getMinX());
1026                    final int yy1 = (int) Math.round(oldMapWindow.getMinY());
1027                    final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1028                    final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1029    
1030                    graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1031                                    (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1032                                    (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
1033                                    getMapBackgroundColor(), null);
1034    
1035                    final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1036                                    - yy1);
1037    
1038                    SwingUtil.clearAround(graphics, painedArea, visibleArea);
1039    
1040                    addGadgets(graphics, true);
1041    
1042                    quickPreviewHint = 0;
1043    
1044                    repaintTimer.restart();
1045    
1046                    graphics.dispose();
1047    
1048                    // Something has been drawn
1049                    return true;
1050            }
1051    
1052            public MapContext getBgContext() {
1053                    return bgContext;
1054            }
1055    
1056            /**
1057             * Lazyly initializes a {@link BufferedImage} for the background renderer.
1058             */
1059            private Image getBgImage() {
1060                    //
1061                    // if (bgImage == null) {
1062                    // bgImage = createImage(getBounds().width, getBounds().height);
1063                    // }
1064    
1065                    return bgImage;
1066            }
1067    
1068            public MapContext getMapContext() {
1069                    if (localContext == null) {
1070                            setLocalContext(new DefaultMapContext());
1071                    }
1072                    return localContext;
1073            }
1074    
1075            private BufferedImage getFinalImage() {
1076                    //
1077                    if (finalImage == null) {
1078                            // Rectangle curPaintArea = getVisibleRect();
1079                            finalImage = new BufferedImage(getVisibleRect().width,
1080                                            getVisibleRect().height, IMAGETYPE);
1081    
1082                            requestStartRendering();
1083                    }
1084                    return finalImage;
1085            }
1086    
1087            public RenderingHints getJava2dHints() {
1088                    return java2dHints;
1089            }
1090    
1091            /**
1092             * Lazyly initializes a {@link BufferedImage} for the background renderer.
1093             */
1094            private BufferedImage getLocalImage() {
1095    
1096                    if (localImage == null) {
1097                            localImage = new BufferedImage(getVisibleRect().width,
1098                                            getVisibleRect().height, IMAGETYPE_withAlpha);
1099                    }
1100    
1101                    return localImage;
1102            }
1103    
1104            /**
1105             * Returns a copy of the mapArea
1106             *
1107             * @return
1108             */
1109            public ReferencedEnvelope getMapArea() {
1110                    if (mapArea == null) {
1111                            ReferencedEnvelope mapArea_ = null;
1112                            try {
1113                                    mapArea_ = localContext.getLayerBounds();
1114                            } catch (final IOException e) {
1115                                    LOGGER.warn("localContext.getLayerBounds()", e);
1116                            }
1117    
1118                            if (mapArea_ == null && bgContext != null) {
1119                                    try {
1120                                            mapArea_ = bgContext.getLayerBounds();
1121                                    } catch (final IOException e) {
1122                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1123                                    }
1124                            }
1125    
1126                            if (mapArea_ != null) {
1127                                    mapArea = bestAllowedMapArea(mapArea_);
1128                                    requestStartRendering();
1129                            }
1130                    }
1131    
1132                    if (mapArea == null)
1133                            return null;
1134    
1135                    // TODO is needed at all, this should go to setMapArea maybe
1136                    if (localContext.getCoordinateReferenceSystem() == null)
1137                            try {
1138                                    localContext.setCoordinateReferenceSystem(GeoImportUtil
1139                                                    .getDefaultCRS());
1140                            } catch (Exception e) {
1141                                    throw new RuntimeException("setting context CRS:", e);
1142                            }
1143    
1144                    return new ReferencedEnvelope(mapArea, localContext
1145                                    .getCoordinateReferenceSystem());
1146            }
1147    
1148            /**
1149             * Returns the background {@link Color} of the map pane. If not set, the
1150             * methods looks for a parent component and will use its background color.
1151             * If no parent component is available, WHITE is returned.
1152             **/
1153            public Color getMapBackgroundColor() {
1154                    if (mapBackgroundColor == null){
1155                            if (getParent() != null) return getParent().getBackground();
1156                            else return Color.WHITE;
1157                    }
1158                    return mapBackgroundColor;
1159            }
1160    
1161            /**
1162             * Get the BufferedImage to use as a flaoting icon in the lower right
1163             * corner.
1164             *
1165             * @return <code>null</code> if the feature is deactivated.
1166             */
1167            public BufferedImage getMapImage() {
1168                    return mapImage;
1169            }
1170    
1171            /**
1172             * Returns the evelope of the viewable area. The JMapPane will never show
1173             * anything outside of this extend. If this has been set to
1174             * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return
1175             * quickly the context's bounds. It it takes to long to determine the
1176             * context bounds, <code>null</code> is returned.
1177             *
1178             * @param maxExtend
1179             *            <code>null</code> to not have this restriction.
1180             */
1181    
1182            public Envelope getMaxExtend() {
1183                    if (maxExtend == null) {
1184                            // Commented-out because it takes soo much time!
1185                            //
1186                            // long start = System.currentTimeMillis();
1187                            // final ReferencedEnvelope layerBounds = GTUtil
1188                            // .getVisibleLayoutBounds(localContext);
1189                            //                      
1190                            // LOGGER.info(
1191                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1192                            //                      
1193                            // if (layerBounds == null) {
1194                            // // TODO Last fallback could be the CRS valid area
1195                            // return null;
1196                            // }
1197                            //
1198                            // // Kartenbereich um 10% vergroessern
1199                            // return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil
1200                            // .expandEnvelope(layerBounds, 0.1), true);
1201                    }
1202                    return maxExtend;
1203          }          }
1204    
1205          /**          /**
# Line 1088  public class JMapPane extends JPanel imp Line 1214  public class JMapPane extends JPanel imp
1214          }          }
1215    
1216          /**          /**
1217             * Retuns the minimum allowed zoom scale. This is the bigger number value of
1218             * the two. Defaults to {@link Double}.MAX_VALUE
1219             *
1220             * @author <a href="mailto:[email protected]">Stefan Alfons
1221             *         Kr&uuml;ger</a>
1222             */
1223            public Double getMinZoomScale() {
1224                    return minZoomScale;
1225            }
1226    
1227            private Image getPreFinalImage() {
1228                    // if (preFinalImage == null) {
1229                    //                      
1230                    // // Rectangle curPaintArea = getVisibleRect();
1231                    // // preFinalImage = new BufferedImage(curPaintArea.width,
1232                    // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);
1233                    //                      
1234                    // preFinalImage = createImage(getBounds().width, getBounds().height);
1235                    //
1236                    // requestStartRendering();
1237                    // }
1238                    return preFinalImage;
1239            }
1240    
1241            public Map<Object, Object> getRendererHints() {
1242                    // Clear label cache
1243                    labelCache.clear();
1244                    rendererHints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache);
1245    
1246                    return rendererHints;
1247            }
1248    
1249            /**
1250             * Liefert eine affine Transformation, um von den Fenster-Koordinaten in die
1251             * Karten-Koordinaten (Lat/Lon) umzurechnen.
1252             *
1253             * @return eine Kopie der aktuellen Transformation; <code>null</code> wenn
1254             *         noch keine Karte angezeigt wird
1255             */
1256            public AffineTransform getScreenToWorld() {
1257                    if (screenToWorld == null)
1258                            resetTransforms();
1259                    // nur Kopie der Transformation zurueckgeben!
1260                    if (screenToWorld == null)
1261                            return null;
1262                    return new AffineTransform(screenToWorld);
1263            }
1264    
1265            public int getState() {
1266                    return state;
1267            }
1268    
1269            /**
1270             * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1271             * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1272             *
1273             * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der
1274             *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1275             */
1276            public Cursor getStaticCursor() {
1277                    return this.staticCursor;
1278            }
1279    
1280            public AffineTransform getWorldToScreenTransform() {
1281                    if (worldToScreen == null) {
1282                            resetTransforms();
1283                    }
1284                    // nur Kopie der Transformation zurueckgeben!
1285                    return new AffineTransform(worldToScreen);
1286            }
1287    
1288            /**
1289             * A flag indicating if dispose() has already been called. If true, then
1290             * further use of this {@link SelectableXMapPane} is undefined.
1291             */
1292            private boolean isDisposed() {
1293                    return disposed;
1294            }
1295    
1296            /**
1297             * Returns whether a layer is regarded or ignored on {@link #SELECT_TOP},
1298             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions. Returns
1299             * <code>true</code> if the selectability has not been defined.
1300             *
1301             * @param layer
1302             *            a layer
1303             */
1304            public boolean isMapLayerSelectable(final MapLayer layer) {
1305                    final Boolean selectable = mapLayerSelectable.get(layer);
1306                    return selectable == null ? true : selectable;
1307            }
1308    
1309            /**
1310             * Return <code>true</code> if a CRS and a {@link #mapArea} are set and the
1311             * {@link XMapPane} is visible and has bounds set.
1312             */
1313            public boolean isWellDefined() {
1314                    try {
1315                            if (getMapContext() == null)
1316                                    return false;
1317                            if (getMapContext().getLayerCount() <= 0)
1318                                    return false;
1319                            if (getVisibleRect().getWidth() == 0)
1320                                    return false;
1321                            if (getVisibleRect().getHeight() == 0)
1322                                    return false;
1323                            // if (getMapArea() == null)
1324                            // return false;
1325                    } catch (final Exception e) {
1326                            return false;
1327                    }
1328                    return true;
1329            }
1330    
1331            /**
1332             * Called from the listeners while the mouse is dragging, this method either
1333             * paints a translated (moved/panned) version of the image, or a rectangle.
1334             *
1335             * @param startPos
1336             *            in screen coordinates
1337             * @param lastPos
1338             *            in screen coordinates
1339             * @param event
1340             *            the {@link MouseEvent} to read the mouse buttons from
1341             */
1342            public void mouseDragged(final Point startPos, final Point lastPos,
1343                            final MouseEvent event) {
1344    
1345                    if ((getState() == XMapPane.PAN)
1346                                    || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
1347    
1348                            // Panning needs a panning coursor
1349                            if (getCursor() != SwingUtil.PANNING_CURSOR) {
1350                                    setCursor(SwingUtil.PANNING_CURSOR);
1351    
1352                                    // While panning, we deactivate the rendering. So the tasks are
1353                                    // ready to start when the panning is finished.
1354                                    if (bgExecuter != null && bgExecuter.isRunning())
1355                                            bgExecuter.cancelTask();
1356                                    if (localExecuter.isRunning())
1357                                            localExecuter.cancelTask();
1358                            }
1359    
1360                            if (lastPos.x > 0 && lastPos.y > 0) {
1361                                    final int dx = event.getX() - lastPos.x;
1362                                    final int dy = event.getY() - lastPos.y;
1363    
1364                                    // TODO Stop dragging when the drag would not be valid...
1365                                    // boolean dragValid = true;
1366                                    // // check if this panning results in a valid mapArea
1367                                    // {
1368                                    // Rectangle winBounds = xMapPane.getBounds();
1369                                    // winBounds.translate(xMapPane.imageOrigin.x,
1370                                    // -xMapPane.imageOrigin.y);
1371                                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1372                                    // winBounds.x, winBounds.y, winBounds.x
1373                                    // + winBounds.width, winBounds.y
1374                                    // + winBounds.height);
1375                                    //                                      
1376                                    //
1377                                    // winBounds = xMapPane.getBounds();
1378                                    // Point testIng = new Point(xMapPane.imageOrigin);
1379                                    // testIng.translate(dx, dy);
1380                                    // winBounds.translate(testIng.x, -testIng.y);
1381                                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1382                                    // winBounds.x, winBounds.y, winBounds.x
1383                                    // + winBounds.width, winBounds.y
1384                                    // + winBounds.height);
1385                                    //
1386                                    // // If the last drag doesn't change the MapArea anymore cancel
1387                                    // it.
1388                                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1389                                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1390                                    // dragValid = false;
1391                                    // return;
1392                                    // }
1393                                    // }
1394    
1395                                    imageOrigin.translate(dx, dy);
1396                                    updateFinalImage();
1397                                    repaint();
1398                            }
1399    
1400                    } else if ((getState() == XMapPane.ZOOM_IN)
1401                                    || (getState() == XMapPane.ZOOM_OUT)
1402                                    || (getState() == XMapPane.SELECT_ALL)
1403                                    || (getState() == XMapPane.SELECT_TOP)) {
1404    
1405                            // Draws a rectangle
1406                            final Graphics graphics = getGraphics();
1407                            drawRectangle(graphics, startPos, event.getPoint());
1408                            if ((lastPos.x > 0) && (lastPos.y > 0))
1409                                    drawRectangle(graphics, startPos, lastPos);
1410                            graphics.dispose();
1411                    }
1412            }
1413    
1414            /**
1415             * Called by the {@link RenderingExecutor} when rendering was cancelled.
1416             */
1417            public void onRenderingCancelled() {
1418                    LOGGER.debug("Rendering cancelled");
1419                    repaintTimer.stop();
1420            }
1421    
1422            /**
1423             * Called by the {@link RenderingExecutor} when rendering has been
1424             * completed.
1425             */
1426            public void onRenderingCompleted() {
1427                    LOGGER.debug("complete");
1428    
1429                    repaintTimer.stop();
1430    
1431                    // We "forget" about an exception every time we complete a rendering
1432                    // thread successfully
1433                    if (renderingErrors.size() > 0)
1434                            renderingErrors.remove(0);
1435    
1436                    updateFinalImage();
1437                    repaint();
1438            }
1439    
1440            /**
1441             * Called by the {@linkplain XMapPane.RenderingTask} when rendering failed.
1442             * Publishes a {@linkplain MapPaneEvent} of type {@code
1443             * MapPaneEvent.Type.RENDERING_STOPPED} to listeners.
1444             *
1445             * @param renderingError
1446             *            The error that occured during rendering
1447             *
1448             * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1449             */
1450            public void onRenderingFailed(final Exception renderingError) {
1451    
1452                    // Store the exceptions so we can show it to the user:
1453                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1454                                    .getMessage().equals(
1455                                                    "Argument \"sourceCRS\" should not be null.")))
1456                            this.renderingErrors.add(renderingError);
1457                    if (renderingErrors.size() > 3)
1458                            renderingErrors.remove(0);
1459    
1460                    repaintTimer.stop();
1461    
1462                    LOGGER.warn("Rendering failed", renderingError);
1463                    updateFinalImage();
1464                    repaint();
1465    
1466            }
1467    
1468            @Override
1469            protected void paintComponent(final Graphics g) {
1470    
1471                    // Maybe update the cursor and maybe stop the repainting timer
1472                    updateCursor();
1473    
1474                    if (!acceptsRepaintCalls)
1475                            return;
1476    
1477                    if (!isWellDefined())
1478                            return;
1479    
1480                    // super.paintComponent(g); // candidate for removal
1481    
1482                    boolean paintedSomething = false;
1483    
1484                    if (mapImageInvalid) { /* if the map changed then redraw */
1485    
1486                            mapImageInvalid = false; // Reset for next round
1487    
1488                            // If the new mapArea and the oldMapArea intersect, we can draw some
1489                            // quick scaled preview to make the user feel that something is
1490                            // happening.
1491                            if (mapAreaChanged && oldMapArea != null
1492                                            && getMapArea().intersects(oldMapArea)
1493                                            & !getMapArea().equals(oldMapArea) && !paneResized) {
1494    
1495                                    mapAreaChanged = false;
1496    
1497                                    if (getMapArea().covers(oldMapArea)) {
1498                                            quickPreviewHint = ZOOM_OUT;
1499                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1500                                    } else if (oldMapArea.covers(getMapArea())) {
1501                                            quickPreviewHint = ZOOM_IN;
1502                                            paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1503                                    }
1504                            }
1505                    }
1506    
1507                    if (!paintedSomething) {
1508    
1509                            g.drawImage(getFinalImage(), 0, 0, null);
1510    
1511                            g.dispose(); // cand. for removal
1512    
1513                            paintedSomething = true; // cand. for removal
1514                    }
1515    
1516            }
1517    
1518            /**
1519             * Heavily works on releasing all resources related to the four
1520             * {@link Image}s used to cache the results of the different renderers.<br>
1521             * In November 2009 i had some memory leaking problems with {@link XMapPane}
1522             * . The resources of the buffered images were never released. It seem to be
1523             * important to call the GC right after flushing the images.<br>
1524             * Hence this method may take a while, because it calls the GC up to four
1525             * times.
1526             */
1527            private void disposeImages() {
1528    
1529                    // System.out.println("vorher = "
1530                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1531                    // bi.flush();
1532                    // return bi = null;
1533                    // System.out.println("nacher = "
1534                    // + new MbDecimalFormatter().format(LangUtil.gcTotal()));
1535                    //
1536                    // System.out.println("\n");
1537    
1538                    if (preFinalImage != null) {
1539                            preFinalImage.flush();
1540                            preFinalImage = null;
1541                            LangUtil.gc();
1542                    }
1543                    if (finalImage != null) {
1544                            finalImage.flush();
1545                            finalImage = null;
1546                            LangUtil.gc();
1547                    }
1548                    if (localImage != null) {
1549                            localImage.flush();
1550                            localImage = null;
1551                            LangUtil.gc();
1552                    }
1553                    if (bgImage != null) {
1554                            bgImage.flush();
1555                            bgImage = null;
1556                            LangUtil.gc();
1557                    }
1558    
1559            }
1560    
1561            /**
1562             * Performs a {@value #PAN} action. During panning, the displacement is
1563             * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will
1564             * reset the offset and call {@link #setMapArea(Envelope)}.
1565             */
1566            public void performPan() {
1567    
1568                    Rectangle winBounds = getVisibleRect();
1569    
1570                    winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1571                    final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1572                                    winBounds.y, winBounds.x + winBounds.width, winBounds.y
1573                                                    + winBounds.height);
1574    
1575                    imageOrigin.x = 0;
1576                    imageOrigin.y = 0;
1577    
1578                    if (!setMapArea(newMapArea)) {
1579                            /**
1580                             * If setMapArea returns true, the finalImage is updated anyways.
1581                             * This if-case exists to ensure that we repaint a correct image
1582                             * even if the new panning area has been denied.
1583                             */
1584                            updateFinalImage();
1585                            repaint();
1586                    }
1587    
1588                    if (getCursor() == SwingUtil.PANNING_CURSOR)
1589                            setCursor(SwingUtil.PAN_CURSOR);
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    
1611                    localExecuter.cancelTask();
1612    
1613                    mapImageInvalid = true;
1614                    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) {
1658    
1659                    // Remove the default listener from the old context
1660                    if (this.bgContext != null) {
1661                            this.bgContext.removeMapLayerListListener(bgContextListener);
1662    
1663                            // adding listener to all layers
1664                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1665                                    mapLayer.removeMapLayerListener(bgMapLayerListener);
1666                            }
1667                    }
1668    
1669                    this.bgContext = context;
1670    
1671                    if (context != null) {
1672                            // setMapArea(bgContext.getAreaOfInterest());
1673    
1674                            this.bgContext.addMapLayerListListener(bgContextListener);
1675    
1676                            // adding listener to all layers
1677                            for (final MapLayer mapLayer : bgContext.getLayers()) {
1678                                    mapLayer.addMapLayerListener(bgMapLayerListener);
1679                            }
1680                    }
1681    
1682                    requestStartRendering();
1683            }
1684    
1685            public void setJava2dHints(final RenderingHints java2dHints) {
1686                    this.java2dHints = java2dHints;
1687            }
1688    
1689            public void setLocalContext(final MapContext context) {
1690                    // Remove the default listener from the old context
1691                    if (this.localContext != null) {
1692                            this.localContext.removeMapLayerListListener(localContextListener);
1693    
1694                            // adding listener to all layers
1695                            for (final MapLayer mapLayer : localContext.getLayers()) {
1696                                    mapLayer.removeMapLayerListener(localMapLayerListener);
1697                            }
1698                    }
1699    
1700                    this.localContext = context;
1701    
1702                    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                    requestStartRendering();
1717    
1718            }
1719    
1720            public boolean setMapArea(final Envelope newMapArea) {
1721                    if (newMapArea == null)
1722                            return false;
1723                    if (getMapContext()
1724                                    .getCoordinateReferenceSystem() == null) return false;
1725                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1726                                    .getCoordinateReferenceSystem()));
1727            }
1728    
1729            /**
1730             * @param newMapArea
1731             * @return <code>true</code> if the mapArea has been changed and a repaint
1732             *         has been triggered.
1733             */
1734            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1735    
1736                    if (newMapArea == null
1737                                    || bestAllowedMapArea(newMapArea).equals(mapArea)) {
1738                            // No change.. no need to repaint
1739                            return false;
1740                    }
1741    
1742                    // Testing, whether NaN or Infinity are used in the newMapArea
1743                    if (newMapArea.isNull() || Double.isInfinite(newMapArea.getMaxX())
1744                                    || Double.isInfinite(newMapArea.getMaxY())
1745                                    || Double.isInfinite(newMapArea.getMinX())
1746                                    || Double.isInfinite(newMapArea.getMinY())) {
1747                            // No change.. ugly new values
1748                            LOGGER.warn("setMapArea has been called with newArea = "
1749                                            + newMapArea);
1750                            return false;
1751                    }
1752    
1753                    final Envelope candNew = bestAllowedMapArea(newMapArea);
1754    
1755                    // Testing, whether the difference if just minimal
1756                    if (mapArea != null) {
1757                            final double tolX = mapArea.getWidth() / 1000.;
1758                            final double tolY = mapArea.getHeight() / 1000.;
1759                            if ((candNew.getMinX() - tolX < mapArea.getMinX())
1760                                            && (mapArea.getMinX() < candNew.getMinX() + tolX)
1761                                            && (candNew.getMaxX() - tolX < mapArea.getMaxX())
1762                                            && (mapArea.getMaxX() < candNew.getMaxX() + tolX)
1763    
1764                                            && (candNew.getMinY() - tolY < mapArea.getMinY())
1765                                            && (mapArea.getMinY() < candNew.getMinY() + tolY)
1766                                            && (candNew.getMaxY() - tolY < mapArea.getMaxY())
1767                                            && (mapArea.getMaxY() < candNew.getMaxY() + tolY)
1768    
1769                            ) {
1770                                    // The two mapAreas only differ my 1/1000th.. ignore
1771    
1772                                    return false;
1773                            }
1774                    }
1775    
1776                    // New map are is accepted:
1777                    oldMapArea = mapArea;
1778                    mapArea = candNew;
1779                    resetTransforms();
1780    
1781                    if (localContext != null) {
1782                            localContext.setAreaOfInterest(mapArea, localContext
1783                                            .getCoordinateReferenceSystem());
1784                    }
1785                    if (bgContext != null) {
1786                            bgContext.setAreaOfInterest(mapArea, localContext
1787                                            .getCoordinateReferenceSystem());
1788                    }
1789    
1790                    mapAreaChanged = true;
1791    
1792                    repaint(200); // Do not remove it!
1793    
1794                    requestStartRendering();
1795    
1796                    return true;
1797            }
1798    
1799            /**
1800             * Set the background color of the map.
1801             *
1802             * @param if <code>null</code>, white is used.
1803             */
1804            public void setMapBackgroundColor(Color bgColor) {
1805                    this.mapBackgroundColor = bgColor;
1806            }
1807    
1808            /**
1809             * Set the BufferedImage to use as a flaoting icon in the lower right corner
1810             *
1811             * @param mapImageIcon
1812             *            <code>null</code> is allowed and deactivates this icon.
1813             */
1814            public void setMapImage(final BufferedImage mapImage) {
1815                    this.mapImage = mapImage;
1816            }
1817    
1818            /**
1819             * Sets whether a layer is regarded or ignored on {@link #SELECT_TOP},
1820             * {@link #SELECT_ALL} and {@link #SELECT_ONE_FROM_TOP} actions.
1821             *
1822             * @param layer
1823             *            a layer
1824             * @param selectable
1825             *            if {@code false} the layer is ignored during the upper
1826             *            mentioned actions. If <code>null</code>, the default (true)
1827             *            will be used.
1828             */
1829            public void setMapLayerSelectable(final MapLayer layer,
1830                            final Boolean selectable) {
1831                    if (selectable == null)
1832                            mapLayerSelectable.remove(layer);
1833                    else
1834                            mapLayerSelectable.put(layer, selectable);
1835            }
1836    
1837            /**
1838             * Defines an evelope of the viwable area. The JMapPane will never show
1839             * anything outside of this extend.
1840             *
1841             * @param maxExtend
1842             *            <code>null</code> to not have this restriction.
1843             */
1844            public void setMaxExtend(final Envelope maxExtend) {
1845                    this.maxExtend = maxExtend;
1846            }
1847    
1848            /**
1849           * Set the maximum allowed zoom scale. This is the smaller number value of           * Set the maximum allowed zoom scale. This is the smaller number value of
1850           * the two.           * the two. If <code>null</code> is passed, Double.MINVALUE are used which
1851             * mean there is no restriction.
1852           *           *
1853           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
1854           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
1855           */           */
1856          public void setMaxZoomScale(final Double maxZoomScale) {          public void setMaxZoomScale(final Double maxZoomScale) {
1857                  this.maxZoomScale = maxZoomScale;                  this.maxZoomScale = maxZoomScale == null ? Double.MIN_VALUE
1858                                    : maxZoomScale;
1859          }          }
1860    
1861            // /** Stored the time used for the last real rendering in ms. **/
1862            // private long lastRenderingDuration = Long.MAX_VALUE;
1863    
1864          /**          /**
1865           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
1866           * value of the two.           * value of the two. If <code>null</code> is passed, Double.MAXVALUE are
1867             * used which mean there is no restriction.
1868             *
1869           *           *
1870           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
1871           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
1872           */           */
1873          public void setMinZoomScale(final Double minZoomScale) {          public void setMinZoomScale(final Double minZoomScale) {
1874                  this.minZoomScale = minZoomScale;                  this.minZoomScale = minZoomScale == null ? Double.MAX_VALUE
1875                                    : minZoomScale;
1876          }          }
1877    
1878          /**          /**
1879           * Defines an evelope of the viwable area. The JMapPane will never show           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1880           * anything outside of this extend.           * requests. Otherwise the map will not paint anything and not start any
1881             * rendering {@link Thread}s.
1882             */
1883            public void setPainting(final boolean b) {
1884                    acceptsRepaintCalls = b;
1885                    if (acceptsRepaintCalls == true)
1886                            repaint();
1887            }
1888    
1889            private void setRendererHints(final Map<Object, Object> rendererHints) {
1890                    if (rendererHints != null)
1891                            this.rendererHints = rendererHints;
1892            }
1893    
1894            /**
1895             * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the
1896             * repaint Timer if
1897           *           *
1898           * @param maxExtend           * @param state
          *            <code>null</code> to not have this restriction.  
1899           */           */
1900          public void setMaxExtend(Envelope maxExtend) {          public void setState(final int state) {
1901                  this.maxExtend = maxExtend;                  this.state = state;
1902    
1903                    zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN
1904                                    || state == ZOOM_OUT || state == PAN));
1905    
1906                    // Je nach Aktion den Cursor umsetzen
1907                    updateCursor();
1908          }          }
1909    
1910          /**          /**
1911           * Returns the evelope of the viewable area. The JMapPane will never show           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
1912           * anything outside of this extend. If this has been set to           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
1913           * <code>null</code> via {@link #setMaxExtend(Envelope)}, it tries to return           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
1914           * quickly the context's bounds. It it takes to long to determine the           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
1915           * context bounds, <code>null</code> is returned.           * {@code null} als Parameter uebergeben werden
1916           *           *
1917           * @param maxExtend           * @param cursor
1918           *            <code>null</code> to not have this restriction.           *            Cursor
1919           */           */
1920            public void setStaticCursor(final Cursor cursor) {
1921                    this.staticCursor = cursor;
1922                    if (cursor != null)
1923                            super.setCursor(cursor);
1924            }
1925    
1926          public Envelope getMaxExtend() {          /**
1927                  if (maxExtend == null) {           * Starts rendering on one or two threads
1928                          try {           */
1929                                  return fixAspectRatio(this.getBounds(), context.getLayerBounds(), true);          private void startRendering() {
1930                          } catch (IOException e) {  
1931                                  LOGGER                  if (!isWellDefined() || !acceptsRepaintCalls) {
1932                                                  .warn(                          // if we are not ready to start rendering, try it again the next
1933                                                                  "maxExtend == null; faild to getLayerBounds of context",                          // time the timer is chacking the flag.
1934                                                                  e);                          requestStartRendering = true;
1935                            return;
1936                    }
1937    
1938                    if (bgExecuter != null) {
1939                            // Stop all renderers
1940                            bgExecuter.cancelTask();
1941                    }
1942    
1943                    localExecuter.cancelTask();
1944    
1945                    final Rectangle curPaintArea = getVisibleRect();
1946    
1947                    /**
1948                     * We have to set new renderer
1949                     */
1950    
1951                    if (getBgContext() != null) {
1952                            bgRenderer.setJava2DHints(getJava2dHints());
1953                            bgRenderer.setRendererHints(getRendererHints());
1954    
1955                            // bgExecuter = new RenderingExecutor();
1956                            // LOGGER.debug("starting bg renderer:");
1957                            // // /* System.out.println("rendering"); */
1958                            // final GTRenderer createGTRenderer = GTUtil.createGTRenderer(
1959                            // bgContext, getRendererHints());
1960                            // createGTRenderer.setJava2DHints(getJava2dHints());
1961                            // bgExecuter.submit(getBgContext().getAreaOfInterest(),
1962                            // curPaintArea,
1963                            // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
1964                    }
1965    
1966                    if (getMapContext() != null) {
1967                            // localExecuter = new RenderingExecutor(this, 150l);
1968                            // LOGGER.debug("starting local renderer:");
1969    
1970                            localRenderer.setJava2DHints(getJava2dHints());
1971                            localRenderer.setRendererHints(getRendererHints());
1972    
1973                            final boolean submitted = localExecuter.submit(getMapArea(),
1974                                            curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
1975                                            localRenderer);
1976                            if (submitted)
1977                                    repaintTimer.restart();
1978                            else
1979                                    requestStartRendering = true; // Try to start rendering
1980                            // again in
1981                            // a moment
1982                    }
1983    
1984                    updateCursor();
1985            }
1986    
1987            /**
1988             * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
1989             *
1990             * @param ox
1991             *            X-Koordinate der VON-Position
1992             * @param oy
1993             *            Y-Koordinate der VON-Position
1994             * @param px
1995             *            X-Koordinate der BIS-Position
1996             * @param py
1997             *            Y-Koordinate der BIS-Position
1998             * @param winToGeotransform
1999             *            Eine Window to Geo transform. If <code>null</code>,
2000             *            {@link #getScreenToWorld()} is used.
2001             */
2002            public Envelope tranformGeoToWindow(final double ox, final double oy,
2003                            final double px, final double py) {
2004                    final AffineTransform at = getWorldToScreenTransform();
2005                    Point2D geoO;
2006                    // try {
2007                    geoO = at.transform(new Point2D.Double(ox, oy), null);
2008                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2009                    return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());
2010                    // } catch (final NoninvertibleTransformException e) {
2011                    // LOGGER.error(e);
2012                    // return new Envelope(ox, oy, px, py);
2013                    // }
2014            }
2015    
2016            /**
2017             * Transformiert einen Fenster-Koordinaten-Bereich in Geo-Koordinaten.
2018             *
2019             * @param ox
2020             *            X-Koordinate der VON-Position
2021             * @param oy
2022             *            Y-Koordinate der VON-Position
2023             * @param px
2024             *            X-Koordinate der BIS-Position
2025             * @param py
2026             *            Y-Koordinate der BIS-Position
2027             */
2028            public Envelope tranformWindowToGeo(final int ox, final int oy,
2029                            final int px, final int py) {
2030                    final AffineTransform at = getScreenToWorld();
2031                    final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2032                    final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2033    
2034                    // Mmmmm... don't really understand why its x,x,y,y
2035                    // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2036                    // geoP.getY());
2037                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2038                                    new Coordinate(geoP.getX(), geoP.getY()));
2039            }
2040    
2041            /**
2042             * Will update the cursor. If all rendering is finished also stops the
2043             * {@link #repaintTimer}
2044             */
2045            public void updateCursor() {
2046    
2047                    // if the renderers have stopped, also stop the timer that is updating
2048                    // the final image
2049                    if (bgExecuter != null && bgExecuter.isRunning()
2050                                    || localExecuter.isRunning()) {
2051                            setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2052                            return;
2053                    } else {
2054                            // Allow one last rendering
2055                            if (repaintTimer.isRunning()) {
2056                                    // System.out.println("one last rendering....");
2057                                    repaintTimer.stop();
2058                                    updateFinalImage();
2059                                    repaint();
2060                          }                          }
2061                  }                  }
2062                  return maxExtend;  
2063                    // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig
2064                    // von der aktuellen Aktion
2065                    if (this.staticCursor != null) {
2066                            setCursor(staticCursor);
2067                            return;
2068                    }
2069                    if (getCursor() == SwingUtil.PANNING_CURSOR) {
2070                            // This cursor will reset itself
2071                            return;
2072                    }
2073    
2074                    // Set the cursor depending on what tool is in use...
2075                    switch (state) {
2076                    case SELECT_TOP:
2077                    case SELECT_ONE_FROM_TOP:
2078                    case SELECT_ALL:
2079                            setCursor(SwingUtil.CROSSHAIR_CURSOR);
2080                            break;
2081                    case ZOOM_IN:
2082                            setCursor(SwingUtil.ZOOMIN_CURSOR);
2083                            break;
2084                    case ZOOM_OUT:
2085                            setCursor(SwingUtil.ZOOMOUT_CURSOR);
2086                            break;
2087                    case PAN:
2088                            setCursor(SwingUtil.PAN_CURSOR);
2089                            break;
2090                    default:
2091                            setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2092                            break;
2093                    }
2094            }
2095    
2096            /**
2097             * The renderers are all rendering into their own {@link Image}s. This
2098             * method combines all images to one {@link #finalImage}. The
2099             * {@link #repaintTimer} is calling this method regularely to update the
2100             * {@link #finalImage} even if the renderers are still working.
2101             */
2102            synchronized protected Image updateFinalImage() {
2103    
2104                    // Render the two map images first, into the preFinalImage
2105                    if (bgExecuter != null) {
2106                            final Graphics2D preFinalG = (Graphics2D) getPreFinalImage()
2107                                            .getGraphics();
2108                            preFinalG.setBackground(getMapBackgroundColor());
2109    
2110                            preFinalG.drawImage(getBgImage(), 0, 0, getMapBackgroundColor(),
2111                                            null);
2112    
2113                            // // Draw the local layers image
2114                            preFinalG.drawImage(getLocalImage(), 0, 0, null);
2115                            preFinalG.dispose();
2116    
2117                    } else {
2118                            preFinalImage = getLocalImage();
2119                    }
2120    
2121                    final Graphics2D finalG = getFinalImage().createGraphics();
2122                    finalG.setBackground(getMapBackgroundColor());
2123                    finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
2124                                    getMapBackgroundColor(), null);
2125    
2126                    final int finalImageHeight = getFinalImage().getHeight(null);
2127                    final int finalImageWidth = getFinalImage().getWidth(null);
2128    
2129                    final Rectangle painedArea = new Rectangle(imageOrigin.x,
2130                                    imageOrigin.y, finalImageWidth, finalImageHeight);
2131                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect());
2132    
2133                    addGadgets(finalG, false);
2134    
2135                    finalG.dispose();
2136    
2137                    return finalImage;
2138            }
2139    
2140            /**
2141             * Paints some optional stuff into the given {@link Graphics2D}. Usually
2142             * called as the last layer when {@link #updateFinalImage()}
2143             *
2144             * @param forceWait
2145             *            if <code>true</code>, a Wait-message will be painted even
2146             *            though the rendering threads may not yet have started. If
2147             *            <code>false</code>, it will only depend on
2148             *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2149             */
2150            private void addGadgets(final Graphics2D graphics, boolean forceWait) {
2151    
2152                    // Paint a logo to the bottom right if available
2153                    if (mapImage != null) {
2154                            Rectangle visibleRect = getVisibleRect();
2155                            graphics.drawImage(mapImage, visibleRect.width
2156                                            - mapImage.getWidth() - 10, getVisibleRect().height
2157                                            - mapImage.getHeight() - 10, null);
2158                    }
2159    
2160                    int y = 17;
2161    
2162                    // If the rendering process is still running, indicate this is the image
2163                    if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2164                                    || localExecuter.isRunning()) {
2165    
2166                            y += 8;
2167    
2168                            final Color c = graphics.getColor();
2169                            graphics.setFont(waitFont);
2170    
2171                            graphics.setColor(getMapBackgroundColor());
2172                            graphics.drawString(waitMsg, 5, y);
2173                            graphics.setColor(getMapBackgroundColor());
2174                            graphics.drawString(waitMsg, 7, y + 2);
2175                            graphics.setColor(Color.BLACK);
2176                            graphics.drawString(waitMsg, 6, y + 1);
2177    
2178                            graphics.setColor(c);
2179    
2180                            y += 24;
2181                    }
2182    
2183                    if (!renderingErrors.isEmpty() && isShowExceptions()) {
2184    
2185                            final Color c = graphics.getColor();
2186                            graphics.setFont(errorFont);
2187    
2188                            for (Exception ex : renderingErrors) {
2189    
2190                                    String errStr = ex.getLocalizedMessage();
2191    
2192                                    if (errStr == null)
2193                                            errStr = ex.getMessage();
2194                                    if (errStr == null)
2195                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2196    
2197                                    graphics.setColor(Color.WHITE);
2198                                    graphics.drawString(errStr, 5, y);
2199                                    graphics.setColor(Color.RED);
2200                                    graphics.drawString(errStr, 6, y + 1);
2201    
2202                                    y += 19;
2203                            }
2204    
2205                            graphics.setColor(c);
2206                    }
2207    
2208            }
2209    
2210            /**
2211             * Sets the {@link #mapArea} to best possibly present the given features. If
2212             * only one single point is given, the window is moved over the point.
2213             *
2214             * @param features
2215             *            if <code>null</code> or size==0, the function doesn nothing.
2216             */
2217            public void zoomTo(
2218                            final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2219    
2220                    // if (!isWellDefined()) return;
2221    
2222                    final CoordinateReferenceSystem mapCRS = getMapContext()
2223                                    .getCoordinateReferenceSystem();
2224                    final CoordinateReferenceSystem fCRS = features.getSchema()
2225                                    .getGeometryDescriptor().getCoordinateReferenceSystem();
2226    
2227                    ReferencedEnvelope _mapArea;
2228                    if (mapArea == null)
2229                            _mapArea = features.getBounds();
2230                    else
2231                            _mapArea = getMapArea();
2232                    double width = _mapArea.getWidth();
2233                    double height = _mapArea.getHeight();
2234                    final double ratio = height / width;
2235    
2236                    if (features == null || features.size() == 0) {
2237                            // feature count == 0 Zoom to the full extend
2238                            return;
2239                    } else if (features.size() == 1) {
2240    
2241                            // feature count == 1 Just move the window to the point and zoom 'a
2242                            // bit'
2243                            final SimpleFeature singleFeature = features.iterator().next();
2244    
2245                            if (((Geometry) singleFeature.getDefaultGeometry())
2246                                            .getCoordinates().length > 1) {
2247                                    // System.out.println("Zoomed to only pne poylgon");
2248                                    // Poly
2249                                    // TODO max width vs. height
2250                                    width = features.getBounds().getWidth() * 3;
2251                                    height = ratio * width;
2252                            } else {
2253                                    // System.out.println("Zoomed in a bit becasue only one point");
2254                                    // width *= .9;
2255                                    // height *= .9;
2256                            }
2257    
2258                            Coordinate centre = features.getBounds().centre();
2259                            if (!mapCRS.equals(fCRS)) {
2260                                    // only to calculations if the CRS differ
2261                                    try {
2262                                            MathTransform fToMap;
2263                                            fToMap = CRS.findMathTransform(fCRS, mapCRS);
2264                                            // centre is transformed to the mapCRS
2265                                            centre = JTS.transform(centre, null, fToMap);
2266                                    } catch (final FactoryException e) {
2267                                            LOGGER.error("Looking for a Math transform", e);
2268                                    } catch (final TransformException e) {
2269                                            LOGGER.error("Looking for a Math transform", e);
2270                                    }
2271                            }
2272    
2273                            final Coordinate newLeftBottom = new Coordinate(centre.x - width
2274                                            / 2., centre.y - height / 2.);
2275                            final Coordinate newTopRight = new Coordinate(
2276                                            centre.x + width / 2., centre.y + height / 2.);
2277    
2278                            final Envelope newMapArea = new Envelope(newLeftBottom, newTopRight);
2279    
2280                            setMapArea(newMapArea);
2281    
2282                    } else {
2283                            final ReferencedEnvelope fBounds = features.getBounds();
2284    
2285                            ReferencedEnvelope bounds;
2286                            if (!mapCRS.equals(fCRS)) {
2287                                    bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2288                            } else {
2289                                    bounds = fBounds;
2290                            }
2291                            // BB umrechnen von Layer-CRS in Map-CRS
2292    
2293                            // Expand a bit
2294                            bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);
2295    
2296                            setMapArea(bounds);
2297                    }
2298            }
2299    
2300            /**
2301             * Zooms towards a point.
2302             *
2303             * @param center
2304             *            position in window coordinates
2305             * @param zoomFactor
2306             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33
2307             */
2308            public void zoomTo(final Point center) {
2309                    zoomTo(center, null);
2310            }
2311    
2312            /**
2313             * Zooms towards a point.
2314             *
2315             * @param center
2316             *            position in window coordinates
2317             * @param zoomFaktor
2318             *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.
2319             */
2320            public void zoomTo(Point center, Double zoomFaktor) {
2321                    if (zoomFaktor == null || zoomFaktor == 0.)
2322                            zoomFaktor = 2.;
2323    
2324                    final Point2D gcenter = getScreenToWorld().transform(center, null);
2325                    center = null;
2326    
2327                    if (Double.isNaN(gcenter.getX()) || Double.isNaN(gcenter.getY())
2328                                    || Double.isInfinite(gcenter.getX())
2329                                    || Double.isInfinite(gcenter.getY())
2330    
2331                    ) {
2332                            // Not inside valid CRS area! cancel
2333                            return;
2334                    }
2335    
2336                    final Envelope mapArea = getMapArea();
2337    
2338                    final Envelope newMapArea = new Envelope(mapArea);
2339                    newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2340                                    .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2341                                    .getHeight()) / 2.);
2342    
2343                    // TODO we actually want that
2344                    // // Move the newMapArea above the new center
2345                    // newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2346                    // .getY()
2347                    // - mapArea.centre().y);
2348    
2349                    setMapArea(newMapArea);
2350            }
2351    
2352            /**
2353             * Shall non-fatal rendering exceptions be reported in the mappane or be
2354             * dropped quitely.
2355             */
2356            public void setShowExceptions(boolean showExceptions) {
2357                    this.showExceptions = showExceptions;
2358            }
2359    
2360            /**
2361             * Shall exceptions be reported in the mappane?
2362             */
2363            public boolean isShowExceptions() {
2364                    return showExceptions;
2365          }          }
2366    
2367  }  }

Legend:
Removed from v.431  
changed lines
  Added in v.558

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26