/[schmitzm]/branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java
ViewVC logotype

Annotation of /branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java

Parent Directory Parent Directory | Revision Log Revision Log


Revision 580 - (hide annotations)
Wed Nov 25 20:30:02 2009 UTC (15 years, 3 months ago) by alfonx
File size: 72456 byte(s)
* Reeduced the flickering while zooming in/out
* scaled previews are not only used if the last rendering took quite long

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26