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

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

Parent Directory Parent Directory | Revision Log Revision Log


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26