/[schmitzm]/branches/2.0-RC1/src/skrueger/geotools/XMapPane.java
ViewVC logotype

Annotation of /branches/2.0-RC1/src/skrueger/geotools/XMapPane.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 607 - (hide annotations)
Wed Dec 9 15:13:42 2009 UTC (15 years, 2 months ago) by alfonx
File size: 77979 byte(s)
Keine Ahnung was er da gebrancht hat.. der stand der dateien war weder trunk, noch der 1.0-gt26 branch... ich hab die dateien jetzt händisch auf den richtigen stand gebracht und comitte

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26