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

Legend:
Removed from v.341  
changed lines
  Added in v.544

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26