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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 644 - (show annotations)
Thu Jan 28 16:28:36 2010 UTC (15 years, 1 month ago) by alfonx
Original Path: branches/2.0-RC2/src/skrueger/geotools/XMapPane.java
File size: 79191 byte(s)


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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26