/[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 612 - (hide annotations)
Sat Dec 12 17:14:17 2009 UTC (15 years, 2 months ago) by alfonx
Original Path: branches/2.0-RC1/src/skrueger/geotools/XMapPane.java
File size: 78183 byte(s)
Label und Tooltip der Maus KoordinatenAnzeige rechts verändert. Zeit im TT jetzt das CRS der Koordinaten an.

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26