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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 679 - (show annotations)
Fri Feb 5 15:25:25 2010 UTC (15 years ago) by alfonx
File size: 78484 byte(s)
backported a bug that could leed to an infinite loop when finding the best map extend due to double precision problems

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26