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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

branches/1.0-gt2-2.6/src/skrueger/geotools/XMapPane.java revision 540 by alfonx, Fri Nov 20 19:34:50 2009 UTC branches/2.0-RC2/src/skrueger/geotools/XMapPane.java revision 660 by alfonx, Wed Feb 3 16:10:12 2010 UTC
# Line 13  import java.awt.event.ActionEvent; Line 13  import java.awt.event.ActionEvent;
13  import java.awt.event.ActionListener;  import java.awt.event.ActionListener;
14  import java.awt.event.ComponentAdapter;  import java.awt.event.ComponentAdapter;
15  import java.awt.event.ComponentEvent;  import java.awt.event.ComponentEvent;
 import java.awt.event.InputEvent;  
16  import java.awt.event.MouseEvent;  import java.awt.event.MouseEvent;
17  import java.awt.event.MouseListener;  import java.awt.event.MouseListener;
18  import java.awt.geom.AffineTransform;  import java.awt.geom.AffineTransform;
# Line 26  import java.util.HashMap; Line 25  import java.util.HashMap;
25  import java.util.Map;  import java.util.Map;
26  import java.util.Vector;  import java.util.Vector;
27    
28    import javax.swing.JList;
29  import javax.swing.Timer;  import javax.swing.Timer;
30    import javax.swing.border.Border;
31    
32  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
33    import org.geotools.factory.GeoTools;
34  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
35  import org.geotools.geometry.Envelope2D;  import org.geotools.geometry.DirectPosition2D;
36  import org.geotools.geometry.jts.JTS;  import org.geotools.geometry.jts.JTS;
37  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
38  import org.geotools.map.DefaultMapContext;  import org.geotools.map.DefaultMapContext;
# Line 66  import schmitzm.geotools.map.event.MapLa Line 68  import schmitzm.geotools.map.event.MapLa
68  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
69  import schmitzm.swing.JPanel;  import schmitzm.swing.JPanel;
70  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
71    import schmitzm.swing.event.MouseInputType;
72    
73  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
74  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
# Line 96  import com.vividsolutions.jts.geom.Geome Line 99  import com.vividsolutions.jts.geom.Geome
99   */   */
100  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
101    
102          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;          /**
103          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;           * If {@link #maxExtend} is <code>null</code> the following rules are used
104             * to create a default maximum.
105             * <ul>
106             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
107             * margin</li>
108             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
109             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
110             * relative margin</li>
111             * </ul>
112             * **/
113            private double defaultMaxMapExtendMode = .05;
114    
115            // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
116            // private static final int IMAGETYPE_withAlpha =
117            // BufferedImage.TYPE_INT_ARGB;
118            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
119    
120            public XMapPaneTool getTool() {
121                    return tool;
122            }
123    
124          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
125    
126            private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
127    
128            /**
129             * A flag indicating whether the {@link XMapPane} is accepting repaints from
130             * the EDT. @see {@link XMapPane#setPainting(boolean))
131             **/
132          private boolean acceptsRepaintCalls = true;          private boolean acceptsRepaintCalls = true;
133    
134          /**          /**
# Line 125  public class XMapPane extends JPanel { Line 153  public class XMapPane extends JPanel {
153           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
154           * renderers have finished.           * renderers have finished.
155           *           *
156           * @see #INITIAL_REPAINT_DELAYAL           * @see INITIAL_REPAINT_DELAYAL
157           * @see #REPEATING_REPAINT_DELAY           * @see #REPEATING_REPAINT_DELAY
158           */           */
159          final private Timer repaintTimer;          final private Timer repaintTimer;
# Line 134  public class XMapPane extends JPanel { Line 162  public class XMapPane extends JPanel {
162           * The initial delay in milliseconds until the {@link #finalImage} is           * The initial delay in milliseconds until the {@link #finalImage} is
163           * updated the first time.           * updated the first time.
164           */           */
165          public static final int INITIAL_REPAINT_DELAY = 1000;          public static final int INITIAL_REPAINT_DELAY = 900;
166    
167          /**          /**
168           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
169           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
170           * with previews.           * with previews.
171           */           */
172          public static final long REPEATING_REPAINT_DELAY = 500;          public static final int REPEATING_REPAINT_DELAY = 500;
173    
174          /**          /**
175           * Default delay (milliseconds) before the map will be redrawn when resizing           * Default delay (milliseconds) before the map will be redrawn when resizing
176           * the pane. This is to avoid flickering while drag-resizing.           * the pane. This is to avoid flickering while drag-resizing.
177             *
178             * @see #resizeTimer
179           */           */
180          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
181    
         public static final int NONE = -123;  
   
182          /**          /**
183           * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl           * This not-repeating {@link Timer} is re-started whenever the component is
184           * moeglich!           * resized. That means => only if the component is not resizing for
185           *           * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
186           * @see #setState(int)           * {@link XMapPane} react.
187           */           */
188          public static final int PAN = 1;          private final Timer resizeTimer;
189    
190          /**          /**
191           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag for no-tool.
          *  
          * @see #setState(int)  
          * @see #setState(int)  
192           */           */
193          public static final int SELECT_ALL = 103;          public static final int NONE = -123;
194            //
195            // /**
196            // * Flag fuer Modus "Kartenausschnitt bewegen". Nicht fuer Window-Auswahl
197            // * moeglich!
198            // *
199            // * @see #setState(int)
200            // */
201            // public static final int PAN = 1;
202            //
203            // /**
204            // * Flag fuer Modus "Heran zoomen".
205            // *
206            // * @see #setState(int)
207            // * @see #setState(int)
208            // */
209            // public static final int ZOOM_IN = 2;
210            //
211            // /**
212            // * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
213            // *
214            // * @see #setState(int)
215            // */
216            // public static final int ZOOM_OUT = 3;
217    
218          /**          /**
219           * Flag fuer Modus           * {@link Font} used to paint the wait messages into the map
          * "Auswahl nur eines Features, das erste sichtbare von Oben".  
220           *           *
221           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
222           */           */
223          public static final int SELECT_ONE_FROM_TOP = 104;          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
224    
225          /**          /**
226           * Flag fuer Modus           * {@link Font} used to paint error messages into the map
          * "SimpleFeature-Auswahl auf dem obersten (sichtbaren) Layer".  
227           *           *
228           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
229           */           */
         public static final int SELECT_TOP = 4;  
   
         public static final Cursor WAIT_CURSOR = Cursor  
                         .getPredefinedCursor(Cursor.WAIT_CURSOR);  
   
         final static Font waitFont = new Font("Arial", Font.BOLD, 30);  
         final String waitMsg = SwingUtil.R("WaitMess");  
230          final static Font errorFont = new Font("Arial", Font.BOLD, 13);          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
231    
232          /**          /**
233           * Flag fuer Modus "Heran zoomen".           * If last average last two renderings took more than that many ms, show the
234           *           * user a scaled preview
235           * @see #setState(int)           **/
236           * @see #setState(int)          private static final long PRESCALE_MINTIME = 230;
          */  
         public static final int ZOOM_IN = 2;  
237    
238          /**          /**
239           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * The wait message painted into the map while rendering is going on on
240             * another thread.
241           *           *
242           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
243           */           */
244          public static final int ZOOM_OUT = 3;          final String waitMsg = SwingUtil.R("WaitMess");
245    
246          /**          /**
247           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in           * Konvertiert die Maus-Koordinaten (relativ zum <code>JMapPane</code>) in
# Line 212  public class XMapPane extends JPanel { Line 250  public class XMapPane extends JPanel {
250           * @param e           * @param e
251           *            Maus-Ereignis           *            Maus-Ereignis
252           */           */
253          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
254                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
255                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
256                          try {                          try {
257                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition();
258                          } catch (final Exception err) {                          } catch (final Exception err) {
259                                  LOGGER                                  LOGGER
260                                                  .error(                                                  .error(
# Line 233  public class XMapPane extends JPanel { Line 271  public class XMapPane extends JPanel {
271                                  return null;                                  return null;
272    
273                          final AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
274                          if (at != null)                          if (at != null) {
275                                  return at.transform(e.getPoint(), null);                                  Point2D transformed = at.transform(e.getPoint(), null);
276                                    return new DirectPosition2D(xMapPane.getMapContext()
277                                                    .getCoordinateReferenceSystem(), transformed.getX(),
278                                                    transformed.getY());
279                            }
280                          return null;                          return null;
281                  }                  }
282                  throw new IllegalArgumentException(                  throw new IllegalArgumentException(
# Line 249  public class XMapPane extends JPanel { Line 291  public class XMapPane extends JPanel {
291    
292                  @Override                  @Override
293                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
294                            final MapLayer layer = event.getLayer();
                         MapLayer layer = event.getLayer();  
   
295                          layer.addMapLayerListener(bgMapLayerListener);                          layer.addMapLayerListener(bgMapLayerListener);
   
                         if (localContext.getLayers().length == 0  
                                         && bgContext.getLayers().length == 1) { // the first one and  
                                 // localContext is  
                                 // empty  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         requestStartRendering();  
                                 return;  
                         }  
   
                         // We need to redraw, even in case that the mapArea didn't change  
                         // mapImageInvalid = true;  
                         // repaint();  
296                          requestStartRendering();                          requestStartRendering();
   
297                  }                  }
298    
299                  @Override                  @Override
300                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
301                          requestStartRendering();                          requestStartRendering();
302                  }                  }
303    
304                  @Override                  @Override
305                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
306                          requestStartRendering();                          requestStartRendering();
307                  }                  }
308    
# Line 288  public class XMapPane extends JPanel { Line 310  public class XMapPane extends JPanel {
310                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
311                          if (event.getLayer() != null)                          if (event.getLayer() != null)
312                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
313                          requestStartRendering();                          requestStartRendering();
314                  }                  }
315          };          };
316    
317          /**          /**
318           * compass and icon are rendered into this image           * This {@link RenderingExecutor} manages the creation and cancellation of
319             * up to one {@link Thread} for rendering the {@link #localContext}.
320           */           */
321          // protected BufferedImage gadgetsImage;          private final RenderingExecutor localExecuter = new RenderingExecutor(this);
322    
323            /**
324             * This {@link RenderingExecutor} manages the creation and cancellation of
325             * up to one {@link Thread} for rendering the {@link #bgContext}.
326             */
327          protected RenderingExecutor bgExecuter;          protected RenderingExecutor bgExecuter;
328    
329          /**          /**
330           * The Renderer for the LocalLayers uses this Image. When set to null,           * The {@link #localRenderer} for the {@link #localContext} uses this
331           * please dispose this {@link Graphics2D}           * {@link Image}.
332           */           */
333          private BufferedImage localImage;          private BufferedImage localImage;
334    
         private BufferedImage finalImage;  
335          /**          /**
336           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background           * The {@link #bgRenderer} for the {@link #bgContext} uses this
337           * uses this Image. When set to null, please dispose the {@link Graphics2D}           * {@link Image}.
338           */           */
339          private BufferedImage bgImage;          private BufferedImage bgImage;
340    
341          /**          /**
342             * This {@link Image} is a merge of the {@link #bgImage},
343             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
344             * updated with {@link #updateFinalImage()} and used for painting in
345             * {@link #paintComponent(Graphics)}
346             */
347            private BufferedImage finalImage;
348    
349            /**
350           * Optionally a transparent image to paint over the map in the lower right           * Optionally a transparent image to paint over the map in the lower right
351           * corner.           * corner.
352           *           *
# Line 331  public class XMapPane extends JPanel { Line 363  public class XMapPane extends JPanel {
363    
364                  @Override                  @Override
365                  public void layerChanged(final MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
366                          requestStartRendering();                          requestStartRendering();
367                  }                  }
368    
369                  @Override                  @Override
370                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
371                          requestStartRendering();                          requestStartRendering();
372                  }                  }
373    
374                  @Override                  @Override
375                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
376                          requestStartRendering();                          requestStartRendering();
377                  }                  }
378          };          };
# Line 362  public class XMapPane extends JPanel { Line 387  public class XMapPane extends JPanel {
387           * While dragging, the {@link #updateFinalImage()} method is translating the           * While dragging, the {@link #updateFinalImage()} method is translating the
388           * cached images while setting it together.           * cached images while setting it together.
389           **/           **/
390          Point imageOrigin = new Point(0, 0);          private final Point imageOrigin = new Point(0, 0);
391          /**          /**
392           * For every rendering thread started,           * For every rendering thread started,
393           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new           * {@link GTUtil#createGTRenderer(MapContext)} is called to create a new
# Line 384  public class XMapPane extends JPanel { Line 409  public class XMapPane extends JPanel {
409                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
410                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
411    
412                          localRenderer.setContext(getContext());                          getLocalRenderer().setContext(getMapContext());
   
                         if (localContext.getLayers().length == 1) { // the first one  
   
                                 // if the Area of Interest is unset, the LayerBounds are used  
                                 if (!setMapArea(localContext.getAreaOfInterest()))  
                                         repaint();  
   
                                 return;  
                         }  
   
                         // We need to redraw, even in case that the mapArea didn't change  
                         // mapImageInvalid = true;  
                         // repaint();  
413                          requestStartRendering();                          requestStartRendering();
414    
415                  }                  }
416    
417                  @Override                  @Override
418                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
419                          // mapImageInvalid = true;                          // getLocalRenderer().setContext(getMapContext()); geht doch auch
420                          // repaint();                          // ohne?!?!? wow...
                         localRenderer.setContext(getContext());  
421                          requestStartRendering();                          requestStartRendering();
422                  }                  }
423    
424                  @Override                  @Override
425                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
426                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
427                          requestStartRendering();                          requestStartRendering();
428                  }                  }
429    
# Line 422  public class XMapPane extends JPanel { Line 431  public class XMapPane extends JPanel {
431                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
432                          if (event.getLayer() != null)                          if (event.getLayer() != null)
433                                  event.getLayer().removeMapLayerListener(localMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
434                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
435                          requestStartRendering();                          requestStartRendering();
436                  }                  }
437          };          };
438    
         private final RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
439          /**          /**
440           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
441           * triggers repaints.           * triggers repaints. We don't have to listen layerChanged, because that is
442             * already done in {@link #localContextListener}
443           */           */
444          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
445    
446                  @Override                  // @Override
447                  public void layerChanged(final MapLayerEvent event) {                  // public void layerChanged(final MapLayerEvent event) {
448                          localRenderer.setContext(getContext()); // betters for SLD changes?!                  // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
449                          // Change of SLD for example                  // // // changes?!
450                          // mapImageInvalid = true;                  // // requestStartRendering();
451                          // repaint();                  // }
                         requestStartRendering();  
                 }  
452    
453                  @Override                  @Override
454                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
455                          requestStartRendering();                          requestStartRendering();
456                  }                  }
457    
458                  @Override                  @Override
459                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
460                          requestStartRendering();                          requestStartRendering();
461                  }                  }
462          };          };
463    
464          private final GTRenderer localRenderer = GTUtil.createGTRenderer();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
465    
466          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
467    
# Line 482  public class XMapPane extends JPanel { Line 482  public class XMapPane extends JPanel {
482          /**          /**
483           * This color is used as the default background color when painting a map.           * This color is used as the default background color when painting a map.
484           */           */
485          private Color mapBackgroundColor = Color.WHITE;          private Color mapBackgroundColor = null;
486    
487          /**          /**
488           * A flag indicating that the shown image is invalid and needs to be           * A flag indicating that the shown image is invalid and needs to be
# Line 526  public class XMapPane extends JPanel { Line 526  public class XMapPane extends JPanel {
526           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
527           * images are not big enough any more           * images are not big enough any more
528           **/           **/
529          protected boolean paneResized = false;          protected boolean paneResized = true;
530    
531          private BufferedImage preFinalImage;          private BufferedImage preFinalImage;
532    
533          // if null, no quick preview will be shown          // ** if 0, no quick preview will be shown **/
534          private int quickPreviewHint = 0;          // private int quickPreviewHint = 0;
535    
536          private Map<Object, Object> rendererHints = GTUtil          private Map<Object, Object> rendererHints = GTUtil
537                          .getDefaultGTRendererHints(localRenderer);                          .getDefaultGTRendererHints(getLocalRenderer());
538    
539            /**
540             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
541             * start rendering {@link Thread}s
542             **/
543          private volatile Boolean requestStartRendering = false;          private volatile Boolean requestStartRendering = false;
544    
         private final Timer resizeTimer;  
   
545          /**          /**
546           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
547           * (lat/lon)           * (lat/lon)
# Line 552  public class XMapPane extends JPanel { Line 554  public class XMapPane extends JPanel {
554           * thread.           * thread.
555           */           */
556          final private Timer startRenderThreadsTimer;          final private Timer startRenderThreadsTimer;
557            //
558          /**          // /**
559           * The default state is ZOOM_IN, hence by default the          // * The default state is ZOOM_IN, hence by default the
560           * {@link #zoomMapPaneMouseListener} is also enabled.          // * {@link #xMapPaneMouseListener} is also enabled.
561           **/          // **/
562          private int state = ZOOM_IN;          // private int state = ZOOM_IN;
563            //
564          /**          // /**
565           * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen          // * Manuell gesetzter statischer Cursor, unabhaengig von der aktuellen
566           * MapPane-Funktion          // * MapPane-Funktion
567           */          // */
568          protected Cursor staticCursor = null;          // protected Cursor staticCursor = null;
569    
570          private AffineTransform worldToScreen;          private AffineTransform worldToScreen;
571    
572            // /**
573            // * This {@link MouseListener} is managing all zoom related tasks
574            // */
575            // private final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new
576            // ZoomXMapPaneMouseListener(
577            // this);
578    
579          /**          /**
580           * This {@link MouseListener} is managing all zoom related tasks           * This {@link MouseListener} is managing all zoom related tasks
581           */           */
582          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(          private final XMapPaneMouseListener xMapPaneMouseListener = new XMapPaneMouseListener(
583                          this);                          this);
584    
585          /** Is set if a renderer has an error **/          /** Is set if a renderer has an error **/
586          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
587    
588          // TODO doku          /**
589             * If <code>true</code>, then rendering exceptions are rendererd into the
590             * map pane
591             **/
592            private boolean showExceptions = false;
593    
594          public XMapPane() {          public XMapPane() {
595                  this(null, null);                  this(null, null);
596          }          }
# Line 585  public class XMapPane extends JPanel { Line 599  public class XMapPane extends JPanel {
599           * full constructor extending JPanel           * full constructor extending JPanel
600           *           *
601           * @param rendererHints           * @param rendererHints
602             *            may be <code>null</code>. Otherwise a {@link Map<Object,
603             *            Object>} of {@link RenderingHints} to override the default
604             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
605           *           *
          * @param layout  
          *            - layout (probably shouldn't be set)  
          * @param isDoubleBuffered  
          *            - a Swing thing I don't really understand  
          * @param render  
          *            - what to draw the map with  
606           * @param localContext           * @param localContext
607           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
608             *            empty {@link DefaultMapContext} will be created.
609           */           */
610          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
611                          final Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
# Line 609  public class XMapPane extends JPanel { Line 621  public class XMapPane extends JPanel {
621                  /**                  /**
622                   * Adding the #zoomMapPaneMouseListener                   * Adding the #zoomMapPaneMouseListener
623                   */                   */
624                  this.addMouseListener(zoomMapPaneMouseListener);                  this.addMouseListener(xMapPaneMouseListener);
625                  this.addMouseMotionListener(zoomMapPaneMouseListener);                  this.addMouseMotionListener(xMapPaneMouseListener);
626                  this.addMouseWheelListener(zoomMapPaneMouseListener);                  this.addMouseWheelListener(xMapPaneMouseListener);
627    
628                    // By default the XMapPAne uses the ZOOM_IN tool.
629                    setTool(XMapPaneTool.ZOOM_IN);
630    
631                  /*                  /*
632                   * We use a Timer object to avoid rendering delays and flickering when                   * We use a Timer object to avoid rendering delays and flickering when
# Line 620  public class XMapPane extends JPanel { Line 635  public class XMapPane extends JPanel {
635                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
636                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
637                   */                   */
638                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY, new ActionListener() {                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
639                                    new ActionListener() {
                         public void actionPerformed(final ActionEvent e) {  
                                 paneResized = true;  
640    
641                                  if (!isWellDefined())                                          public void actionPerformed(final ActionEvent e) {
642                                          return;                                                  if (!isWellDefined())
643                                                            return;
644    
645                                  final Rectangle bounds = getVisibleRect();                                                  // LOGGER.debug("resizeTimer performed");
646    
647                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,                                                  // final Rectangle bounds = getVisibleRect();
648                                                  bounds.y, bounds.x + bounds.width, bounds.y                                                  //
649                                                                  + bounds.height);                                                  // System.out.println("\n\ntimer performs with bounds = "
650                                                    // + bounds);
651    
652                                                    // final Envelope geoMapArea = tranformWindowToGeo(
653                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
654                                                    // bounds.y + bounds.height);
655    
656                                                    paneResized = true;
657                                                    if (!setMapArea(getMapArea())) {
658                                                            // It's important to request new rendering here.
659                                                            // setMapArea only returns true and only calls
660                                                            // requestStartRendering if the maparea has changed.
661                                                            // But if the component is resized, the maparea
662                                                            // doesn't have to change.
663                                                            requestStartRendering();
664                                                    }
665    
666                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          }
667                          }                                  });
                 });  
668                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
669    
670                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
671    
672                            private Rectangle oldVisibleRect;
673    
674                          @Override                          @Override
675                          public void componentResized(final ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
676                                  if (bgExecuter != null)  
677                                          bgExecuter.cancelTask();                                  // Seems to be called twice with the same size..
678                                  if (localExecuter != null)                                  if (oldVisibleRect != null
679                                          localExecuter.cancelTask();                                                  && oldVisibleRect.equals(getVisibleRect())) {
680                                            // LOGGER.debug("skipping resize.");
681                                            return;
682                                    }
683    
684                                    // LOGGER.debug("resized: " + getVisibleRect());
685                                  resizeTimer.restart();                                  resizeTimer.restart();
686                                    oldVisibleRect = getVisibleRect();
687                          }                          }
688    
689                  });                  });
# Line 654  public class XMapPane extends JPanel { Line 691  public class XMapPane extends JPanel {
691                  /*                  /*
692                   * Setting up the repaintTimer. Not started automatically.                   * Setting up the repaintTimer. Not started automatically.
693                   */                   */
694                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
695                                  new ActionListener() {  
696                            @Override
697                            public void actionPerformed(final ActionEvent e) {
698                                    if ((!localExecuter.isRunning())
699                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
700                                            repaintTimer.stop();
701                                    } else {
702                                            updateFinalImage();
703                                            XMapPane.this.repaint(100);
704    
705                                    }
706                            }
707                    });
708    
                                         @Override  
                                         public void actionPerformed(final ActionEvent e) {  
                                                 updateFinalImage();  
                                                 XMapPane.this.repaint();  
                                         }  
                                 });  
709                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
710                  repaintTimer.setRepeats(true);                  repaintTimer.setRepeats(true);
711    
# Line 680  public class XMapPane extends JPanel { Line 723  public class XMapPane extends JPanel {
723                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
724                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
725                                                  } else {                                                  } else {
726                                                            // Stupidly, but we have to recheck the
727                                                            setMapArea(getMapArea());
728                                                          requestStartRendering = false;                                                          requestStartRendering = false;
729                                                          startRendering();                                                          startRendering();
730                                                  }                                                  }
# Line 712  public class XMapPane extends JPanel { Line 757  public class XMapPane extends JPanel {
757           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
758           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
759           */           */
760          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
761                  // return env;  
762                  if (getWidth() == 0)                  if (getWidth() == 0)
763                          return env;                          return env;
764    
765                  if (env == null)                  if (env == null)
766                          return null;                          return null;
767    
# Line 765  public class XMapPane extends JPanel { Line 811  public class XMapPane extends JPanel {
811                  }                  }
812    
813                  final Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
814    
815                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
816                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
817                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
# Line 794  public class XMapPane extends JPanel { Line 841  public class XMapPane extends JPanel {
841    
842                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
843    
844                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
845                                                          false);                                                          new ReferencedEnvelope(newArea, env
846                                                                            .getCoordinateReferenceSystem()), false);
847                                  }                                  }
848                          }                          }
849    
# Line 818  public class XMapPane extends JPanel { Line 866  public class XMapPane extends JPanel {
866    
867                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
868    
869                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
870                                                          false);                                                          new ReferencedEnvelope(newArea, env
871                                                                            .getCoordinateReferenceSystem()), false);
872                                  }                                  }
873                          }                          }
874    
# Line 844  public class XMapPane extends JPanel { Line 893  public class XMapPane extends JPanel {
893    
894                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
895    
896                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
897                                                          false);                                                          new ReferencedEnvelope(newArea, env
898                                                                            .getCoordinateReferenceSystem()), false);
899                                  }                                  }
900                          }                          }
901    
# Line 870  public class XMapPane extends JPanel { Line 920  public class XMapPane extends JPanel {
920    
921                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
922    
923                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
924                                                          false);                                                          new ReferencedEnvelope(newArea, env
925                                                                            .getCoordinateReferenceSystem()), false);
926                                  }                                  }
927                          }                          }
928                  }                  }
929    
930                  return newArea;                  return new ReferencedEnvelope(newArea, env
931                                    .getCoordinateReferenceSystem());
932          }          }
933    
934          /**          /**
# Line 904  public class XMapPane extends JPanel { Line 956  public class XMapPane extends JPanel {
956                          bgExecuter.dispose();                          bgExecuter.dispose();
957                  }                  }
958    
959                  if (localExecuter != null) {                  if (localExecuter.isRunning()) {
960                          int i = 0;                          int i = 0;
961                          localExecuter.cancelTask();                          localExecuter.cancelTask();
962                          while (i++ < 10 && localExecuter.isRunning()) {                          while (i++ < 10 && localExecuter.isRunning()) {
963                                  try {                                  try {
964                                          Thread.sleep(100);                                          Thread.sleep(200);
965                                  } catch (final InterruptedException e) {                                  } catch (final InterruptedException e) {
966                                          // TODO Auto-generated catch block                                          LOGGER
967                                          e.printStackTrace();                                                          .warn(
968                                                                            "while XMapPane we are waiting for the localExcutor to stop",
969                                                                            e);
970                                  }                                  }
971                          }                          }
972                          if (localExecuter.isRunning()) {                          if (localExecuter.isRunning()) {
973                                  System.out                                  LOGGER
974                                                  .println("BAD BAD BAD... still running the thread....");                                                  .warn("localExecutor Thread still running after 2s! Continuing anyways...");
975                          }                          }
976                          localExecuter.dispose();                          localExecuter.dispose();
977                  }                  }
978    
979                  disposeImages();                  disposeImages();
980    
981                  // LangUtil.gcTotal();                  // Remove all mapPaneListeners that have registered with us
   
                 // Alle mapPaneListener entfernen  
982                  mapPaneListeners.clear();                  mapPaneListeners.clear();
983    
984                  removeMouseMotionListener(zoomMapPaneMouseListener);                  removeMouseMotionListener(xMapPaneMouseListener);
985                  removeMouseListener(zoomMapPaneMouseListener);                  removeMouseListener(xMapPaneMouseListener);
986    
987                  if (localContext != null)                  if (localContext != null)
988                          getContext().clearLayerList();                          getMapContext().clearLayerList();
989                  if (bgContext != null)                  if (bgContext != null)
990                          getBgContext().clearLayerList();                          getBgContext().clearLayerList();
991    
# Line 946  public class XMapPane extends JPanel { Line 998  public class XMapPane extends JPanel {
998           */           */
999          protected void drawRectangle(final Graphics graphics, final Point startPos,          protected void drawRectangle(final Graphics graphics, final Point startPos,
1000                          final Point e) {                          final Point e) {
1001                    drawRectangle(graphics, startPos, e, Color.WHITE, false);
1002            }
1003    
1004            /**
1005             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1006             * given point. All in screen coordinates.
1007             */
1008            protected void drawRectangle(final Graphics graphics, final Point startPos,
1009                            final Point e, Color color, boolean fill) {
1010    
1011                  if (!isWellDefined())                  if (!isWellDefined())
1012                          return;                          return;
# Line 961  public class XMapPane extends JPanel { Line 1022  public class XMapPane extends JPanel {
1022                  if (width == 0 && height == 0)                  if (width == 0 && height == 0)
1023                          return;                          return;
1024    
1025                  graphics.setXORMode(Color.WHITE);                  graphics.setXORMode(color);
1026    
1027                    if (fill) {
1028                            graphics.fillRect(left, bottom, width, height);
1029                            graphics.setXORMode(Color.WHITE);
1030                    }
1031    
1032                  graphics.drawRect(left, bottom, width, height);                  graphics.drawRect(left, bottom, width, height);
1033          }          }
1034    
# Line 973  public class XMapPane extends JPanel { Line 1040  public class XMapPane extends JPanel {
1040           *           *
1041           * @param g           * @param g
1042           *            Graphics2D to paint the preview into           *            Graphics2D to paint the preview into
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
1043           */           */
1044          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1045    
1046  //              if (1 == 1)return false;                  // if (1 == 1)return false;
1047                                    // if (quickPreviewHint == 0)
1048                  if (quickPreviewHint == 0)                  // return false;
                         return false;  
   
                 graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,  
                                 RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);  
                 graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,  
                                 RenderingHints.VALUE_ANTIALIAS_OFF);  
                 graphics.setRenderingHint(RenderingHints.KEY_RENDERING,  
                                 RenderingHints.VALUE_RENDER_SPEED);  
1049    
1050                  if (oldMapArea == null)                  if (oldMapArea == null)
1051                          return false;                          return false;
1052    
1053                    if (getPreFinalImage() == null)
1054                            return false;
1055    
1056                  final Rectangle visibleArea = getVisibleRect();                  final Rectangle visibleArea = getVisibleRect();
1057    
1058                  // Calculate the oldMapArea in the current WindowCoordinates:                  // Calculate the oldMapArea in the current WindowCoordinates:
# Line 1006  public class XMapPane extends JPanel { Line 1065  public class XMapPane extends JPanel {
1065                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1066                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1067    
1068                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1069                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1070                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1071                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1072                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1073                                    RenderingHints.VALUE_RENDER_SPEED);
1074    
1075                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1076                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1077                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
# Line 1014  public class XMapPane extends JPanel { Line 1080  public class XMapPane extends JPanel {
1080                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1081                                  - yy1);                                  - yy1);
1082    
1083                  SwingUtil.clearAround(graphics, painedArea, visibleArea);                  SwingUtil.clearAround(graphics, painedArea, visibleArea,
1084                                    getMapBackgroundColor());
1085    
1086                  addGadgets(graphics, true);                  addGadgets(graphics, true);
1087    
1088                  quickPreviewHint = 0;                  // quickPreviewHint = 0;
1089    
1090                  repaintTimer.restart();                  repaintTimer.restart();
1091    
                 graphics.dispose();  
   
1092                  // Something has been drawn                  // Something has been drawn
1093                  return true;                  return true;
1094          }          }
# Line 1036  public class XMapPane extends JPanel { Line 1101  public class XMapPane extends JPanel {
1101           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1102           */           */
1103          private Image getBgImage() {          private Image getBgImage() {
1104                  //                  if (bgImage == null) {
1105                  // if (bgImage == null) {                          bgImage = new BufferedImage(getVisibleRect().width,
1106                  // bgImage = createImage(getBounds().width, getBounds().height);                                          getVisibleRect().height, IMAGETYPE);
1107                  // }                          SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1108                    }
1109    
1110                  return bgImage;                  return bgImage;
1111          }          }
1112    
1113          public MapContext getContext() {          public MapContext getMapContext() {
1114                  if (localContext == null) {                  if (localContext == null) {
1115                          setLocalContext(new DefaultMapContext());                          setLocalContext(new DefaultMapContext());
1116                  }                  }
# Line 1057  public class XMapPane extends JPanel { Line 1123  public class XMapPane extends JPanel {
1123                          // Rectangle curPaintArea = getVisibleRect();                          // Rectangle curPaintArea = getVisibleRect();
1124                          finalImage = new BufferedImage(getVisibleRect().width,                          finalImage = new BufferedImage(getVisibleRect().width,
1125                                          getVisibleRect().height, IMAGETYPE);                                          getVisibleRect().height, IMAGETYPE);
1126                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1127    
1128                          requestStartRendering();                          // requestStartRendering();
1129                  }                  }
1130                  return finalImage;                  return finalImage;
1131          }          }
1132    
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1133          /**          /**
1134           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1135           */           */
# Line 1075  public class XMapPane extends JPanel { Line 1138  public class XMapPane extends JPanel {
1138                  if (localImage == null) {                  if (localImage == null) {
1139                          localImage = new BufferedImage(getVisibleRect().width,                          localImage = new BufferedImage(getVisibleRect().width,
1140                                          getVisibleRect().height, IMAGETYPE_withAlpha);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1141                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1142                  }                  }
1143    
1144                  return localImage;                  return localImage;
# Line 1090  public class XMapPane extends JPanel { Line 1154  public class XMapPane extends JPanel {
1154                          ReferencedEnvelope mapArea_ = null;                          ReferencedEnvelope mapArea_ = null;
1155                          try {                          try {
1156                                  mapArea_ = localContext.getLayerBounds();                                  mapArea_ = localContext.getLayerBounds();
1157                          } catch (final IOException e) {                          } catch (final Exception e) {
1158                                  LOGGER.warn("context.getLayerBounds()", e);                                  LOGGER.warn("localContext.getLayerBounds()", e);
1159                            }
1160    
1161                            if (mapArea_ == null && bgContext != null) {
1162                                    try {
1163                                            mapArea_ = bgContext.getLayerBounds();
1164                                    } catch (final IOException e) {
1165                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1166                                    }
1167                          }                          }
1168    
1169                          if (mapArea_ != null) {                          if (mapArea_ != null) {
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 // setMapArea(mapArea_); // results in a loop  
1170                                  mapArea = bestAllowedMapArea(mapArea_);                                  mapArea = bestAllowedMapArea(mapArea_);
1171                                    requestStartRendering();
1172                          }                          }
1173                  }                  }
1174    
# Line 1109  public class XMapPane extends JPanel { Line 1180  public class XMapPane extends JPanel {
1180                          try {                          try {
1181                                  localContext.setCoordinateReferenceSystem(GeoImportUtil                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1182                                                  .getDefaultCRS());                                                  .getDefaultCRS());
1183                          } catch (Exception e) {                          } catch (final Exception e) {
1184                                  throw new RuntimeException("setting context CRS:", e);                                  throw new RuntimeException("setting context CRS:", e);
1185                          }                          }
1186    
# Line 1118  public class XMapPane extends JPanel { Line 1189  public class XMapPane extends JPanel {
1189          }          }
1190    
1191          /**          /**
1192           * Returns the background {@link Color} of the map pane. Default is white.           * Returns the background {@link Color} of the map pane. If not set, the
1193             * methods looks for a parent component and will use its background color.
1194             * If no parent component is available, WHITE is returned.
1195           **/           **/
1196          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1197                    if (mapBackgroundColor == null) {
1198                            if (getParent() != null)
1199                                    return getParent().getBackground();
1200                            else
1201                                    return Color.WHITE;
1202                    }
1203                  return mapBackgroundColor;                  return mapBackgroundColor;
1204          }          }
1205    
# Line 1147  public class XMapPane extends JPanel { Line 1226  public class XMapPane extends JPanel {
1226    
1227          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1228                  if (maxExtend == null) {                  if (maxExtend == null) {
1229    
1230                            // The next command may take long time!
1231                            // long start = System.currentTimeMillis();
1232                          final ReferencedEnvelope layerBounds = GTUtil                          final ReferencedEnvelope layerBounds = GTUtil
1233                                          .getVisibleLayoutBounds(localContext);                                          .getVisibleLayoutBounds(localContext);
1234                            //                      
1235                            // LOGGER.info(
1236                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1237                            //                      
1238                          if (layerBounds == null) {                          if (layerBounds == null) {
1239                                  // TODO Last fallback could be the CRS valid area                                  // // TODO Last fallback could be the CRS valid area
1240                                  return null;                                  return null;
1241                          }                          }
1242    
1243                          // Kartenbereich um 10% vergroessern                          return JTSUtil
1244                          return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil                                          .fixAspectRatio(getVisibleRect(), addDefaultMargin(layerBounds), true);
1245                                          .expandEnvelope(layerBounds, 0.1), true);  
1246                  }                  }
1247                  return maxExtend;                  return maxExtend;
1248          }          }
# Line 1184  public class XMapPane extends JPanel { Line 1270  public class XMapPane extends JPanel {
1270          }          }
1271    
1272          private Image getPreFinalImage() {          private Image getPreFinalImage() {
                 // if (preFinalImage == null) {  
                 //                        
                 // // Rectangle curPaintArea = getVisibleRect();  
                 // // preFinalImage = new BufferedImage(curPaintArea.width,  
                 // // curPaintArea.height, BufferedImage.TYPE_INT_RGB);  
                 //                        
                 // preFinalImage = createImage(getBounds().width, getBounds().height);  
                 //  
                 // requestStartRendering();  
                 // }  
1273                  return preFinalImage;                  return preFinalImage;
1274          }          }
1275    
# Line 1221  public class XMapPane extends JPanel { Line 1297  public class XMapPane extends JPanel {
1297                  return new AffineTransform(screenToWorld);                  return new AffineTransform(screenToWorld);
1298          }          }
1299    
1300          public int getState() {          // public int getState() {
1301                  return state;          // return state;
1302          }          // }
1303            //
1304          /**          // /**
1305           * Liefert den statisch eingestellten Cursor, der unabhaengig von der          // * Liefert den statisch eingestellten Cursor, der unabhaengig von der
1306           * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.          // * eingestellten MapPane-Aktion (Zoom, Auswahl, ...) verwendet wird.
1307           *          // *
1308           * @return {@code null}, wenn kein statischer Cursor verwendet, sondern der          // * @return {@code null}, wenn kein statischer Cursor verwendet, sondern
1309           *         Cursor automatisch je nach MapPane-Aktion eingestellt wird.          // der
1310           */          // * Cursor automatisch je nach MapPane-Aktion eingestellt wird.
1311          public Cursor getStaticCursor() {          // */
1312                  return this.staticCursor;          // public Cursor getStaticCursor() {
1313          }          // return this.staticCursor;
1314            // }
1315    
1316          public AffineTransform getWorldToScreenTransform() {          public AffineTransform getWorldToScreenTransform() {
1317                  if (worldToScreen == null) {                  if (worldToScreen == null) {
# Line 1270  public class XMapPane extends JPanel { Line 1347  public class XMapPane extends JPanel {
1347           * {@link XMapPane} is visible and has bounds set.           * {@link XMapPane} is visible and has bounds set.
1348           */           */
1349          public boolean isWellDefined() {          public boolean isWellDefined() {
   
1350                  try {                  try {
1351                            if (getMapContext() == null)
                         if (getContext() == null)  
                                 return false;  
                         if (getContext().getLayerCount() <= 0)  
1352                                  return false;                                  return false;
1353                          if (getMapArea() == null)                          if (getMapContext().getLayerCount() <= 0)
1354                                  return false;                                  return false;
1355                          if (getBounds().getWidth() == 0)                          if (getVisibleRect().getWidth() == 0)
1356                                  return false;                                  return false;
1357                          if (getBounds().getHeight() == 0)                          if (getVisibleRect().getHeight() == 0)
1358                                  return false;                                  return false;
1359                            // if (getMapArea() == null)
1360                            // return false;
1361                  } catch (final Exception e) {                  } catch (final Exception e) {
1362                          return false;                          return false;
1363                  }                  }
1364                  return true;                  return true;
1365          }          }
1366    
1367          public void mouseDragged(final Point startPos, final Point lastPos,          /**
1368                          final MouseEvent event) {           * Usually called from {@link XMapPaneAction_Pan} to pan the image.
1369             *
1370                  if ((getState() == XMapPane.PAN)           * @param startPos
1371                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {           *            in screen coordinates
1372             * @param lastPos
1373                          if (getCursor() != SwingUtil.PANNING_CURSOR) {           *            in screen coordinates
1374                                  setCursor(SwingUtil.PANNING_CURSOR);           */
1375            public void pan(final int dX, final int dY) {
1376                                  // While panning, we deactivate the rendering. So the tasts are  
1377                                  // ready to start when the panning os done.                  // Panning needs a panning coursor
1378                                  if (bgExecuter != null)                  if (getCursor() != SwingUtil.PANNING_CURSOR) {
1379                                          bgExecuter.cancelTask();                          setCursor(SwingUtil.PANNING_CURSOR);
1380                                  if (localExecuter != null)  
1381                                          localExecuter.cancelTask();                          // While panning, we deactivate the rendering. So the tasks are
1382                          }                          // ready to start when the panning is finished.
1383                            if (bgExecuter != null && bgExecuter.isRunning())
1384                          if (lastPos.x > 0 && lastPos.y > 0) {                                  bgExecuter.cancelTask();
1385                                  final int dx = event.getX() - lastPos.x;                          if (localExecuter.isRunning())
1386                                  final int dy = event.getY() - lastPos.y;                                  localExecuter.cancelTask();
   
                                 // TODO Stop dragging when the drag would not be valid...  
                                 // boolean dragValid = true;  
                                 // // check if this panning results in a valid mapArea  
                                 // {  
                                 // Rectangle winBounds = xMapPane.getBounds();  
                                 // winBounds.translate(xMapPane.imageOrigin.x,  
                                 // -xMapPane.imageOrigin.y);  
                                 // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //                                        
                                 //  
                                 // winBounds = xMapPane.getBounds();  
                                 // Point testIng = new Point(xMapPane.imageOrigin);  
                                 // testIng.translate(dx, dy);  
                                 // winBounds.translate(testIng.x, -testIng.y);  
                                 // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(  
                                 // winBounds.x, winBounds.y, winBounds.x  
                                 // + winBounds.width, winBounds.y  
                                 // + winBounds.height);  
                                 //  
                                 // // If the last drag doesn't change the MapArea anymore cancel  
                                 // it.  
                                 // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(  
                                 // xMapPane.bestAllowedMapArea(newMapAreaBefore))){  
                                 // dragValid = false;  
                                 // return;  
                                 // }  
                                 // }  
   
                                 imageOrigin.translate(dx, dy);  
                                 updateFinalImage();  
                                 repaint();  
                         }  
   
                 } else if ((getState() == XMapPane.ZOOM_IN)  
                                 || (getState() == XMapPane.ZOOM_OUT)  
                                 || (getState() == XMapPane.SELECT_ALL)  
                                 || (getState() == XMapPane.SELECT_TOP)  
                 // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)  
                 ) {  
                         final Graphics graphics = getGraphics();  
   
                         drawRectangle(graphics, startPos, event.getPoint());  
   
                         if ((lastPos.x > 0) && (lastPos.y > 0)) {  
                                 drawRectangle(graphics, startPos, lastPos);  
                         }  
   
                         graphics.dispose();  
   
1387                  }                  }
1388                    //
1389                    // if (lastPos.x > 0 && lastPos.y > 0) {
1390                    // final int dx = event.getX() - lastPos.x;
1391                    // final int dy = event.getY() - lastPos.y;
1392    
1393                    // TODO Stop dragging when the drag would not be valid...
1394                    // boolean dragValid = true;
1395                    // // check if this panning results in a valid mapArea
1396                    // {
1397                    // Rectangle winBounds = xMapPane.getBounds();
1398                    // winBounds.translate(xMapPane.imageOrigin.x,
1399                    // -xMapPane.imageOrigin.y);
1400                    // Envelope newMapAreaBefore = xMapPane.tranformWindowToGeo(
1401                    // winBounds.x, winBounds.y, winBounds.x
1402                    // + winBounds.width, winBounds.y
1403                    // + winBounds.height);
1404                    //                                      
1405                    //
1406                    // winBounds = xMapPane.getBounds();
1407                    // Point testIng = new Point(xMapPane.imageOrigin);
1408                    // testIng.translate(dx, dy);
1409                    // winBounds.translate(testIng.x, -testIng.y);
1410                    // Envelope newMapAreaAfter = xMapPane.tranformWindowToGeo(
1411                    // winBounds.x, winBounds.y, winBounds.x
1412                    // + winBounds.width, winBounds.y
1413                    // + winBounds.height);
1414                    //
1415                    // // If the last drag doesn't change the MapArea anymore cancel
1416                    // it.
1417                    // if (xMapPane.bestAllowedMapArea(newMapAreaAfter).equals(
1418                    // xMapPane.bestAllowedMapArea(newMapAreaBefore))){
1419                    // dragValid = false;
1420                    // return;
1421                    // }
1422                    // }
1423    
1424                    getImageOrigin().translate(dX, dY);
1425                    updateFinalImage();
1426                    repaint();
1427                    // }
1428    
1429                    // } else if ((getState() == XMapPane.ZOOM_IN)
1430                    // || (getState() == XMapPane.ZOOM_OUT)
1431                    // || (getState() == XMapPane.SELECT_ALL)
1432                    // || (getState() == XMapPane.SELECT_TOP)) {
1433                    //
1434                    // // Draws a rectangle
1435                    // final Graphics2D graphics = (Graphics2D) getGraphics();
1436                    // drawRectangle(graphics, startPos, event.getPoint());
1437                    // if ((lastPos.x > 0) && (lastPos.y > 0))
1438                    // drawRectangle(graphics, startPos, lastPos);
1439                    // graphics.dispose();
1440                    // }
1441          }          }
1442    
1443          /**          /**
1444           * Called by the {@link RenderingExecutor} when rendering was cancelled.           * Called by the {@link RenderingExecutor} when rendering was cancelled.
1445           */           */
1446          public void onRenderingCancelled() {          public void onRenderingCancelled() {
1447                    // LOGGER.debug("Rendering cancelled");
1448                  repaintTimer.stop();                  repaintTimer.stop();
                 LOGGER.debug("Rendering cancelled");  
1449          }          }
1450    
1451          /**          /**
1452           * Called by the {@link RenderingExecutor} when rendering has been           * Called by the {@link RenderingExecutor} when rendering has been
1453           * completed.           * completed.
1454             *
1455             * @param l
1456             *            long ms the rendering took
1457           */           */
1458          public void onRenderingCompleted() {          public void onRenderingCompleted(final long l) {
1459                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1460                    // LOGGER
1461                    // .debug("complete rendering after " + lastRenderingDuration
1462                    // + "ms");
1463    
1464                  repaintTimer.stop();                  repaintTimer.stop();
1465                  updateFinalImage();  
1466                  repaint();                  // We "forget" about an exception every time we complete a rendering
1467                    // thread successfully
1468                  if (renderingErrors.size() > 0)                  if (renderingErrors.size() > 0)
1469                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1470    
1471                    updateFinalImage();
1472                    repaint();
1473          }          }
1474    
1475          /**          /**
# Line 1397  public class XMapPane extends JPanel { Line 1483  public class XMapPane extends JPanel {
1483           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1484           */           */
1485          public void onRenderingFailed(final Exception renderingError) {          public void onRenderingFailed(final Exception renderingError) {
1486                  this.renderingErrors.add(renderingError);  
1487                    // Store the exceptions so we can show it to the user:
1488                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1489                                    .getMessage().equals(
1490                                                    "Argument \"sourceCRS\" should not be null.")))
1491                            this.renderingErrors.add(renderingError);
1492                  if (renderingErrors.size() > 3)                  if (renderingErrors.size() > 3)
1493                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1494    
1495                  repaintTimer.stop();                  repaintTimer.stop();
1496    
1497                  LOGGER.warn("Rendering failed", renderingError);                  LOGGER.warn("Rendering failed", renderingError);
1498                  updateFinalImage();                  updateFinalImage();
1499                  repaint();                  repaint();
1500    
1501          }          }
1502    
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
         }  
   
1503          @Override          @Override
1504          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
                 if (!acceptsRepaintCalls)  
                         return;  
1505    
1506                  // Maybe update the cursor and maybe stop the repainting timer                  // Maybe update the cursor and maybe stop the repainting timer
1507                  updateCursor();                  updateCursor();
1508    
1509                    if (!acceptsRepaintCalls)
1510                            return;
1511    
1512                    if (!isWellDefined())
1513                            return;
1514                    //
1515                    // if (paneResized) {
1516                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1517                    // // g.clearRect(0, 0, getVisibleRect().width,
1518                    // getVisibleRect().height);
1519                    // return;
1520                    // }
1521    
1522                  // super.paintComponent(g); // candidate for removal                  // super.paintComponent(g); // candidate for removal
1523    
1524                  boolean paintedSomething = false;                  boolean paintedSomething = false;
# Line 1432  public class XMapPane extends JPanel { Line 1530  public class XMapPane extends JPanel {
1530                          // If the new mapArea and the oldMapArea intersect, we can draw some                          // If the new mapArea and the oldMapArea intersect, we can draw some
1531                          // quick scaled preview to make the user feel that something is                          // quick scaled preview to make the user feel that something is
1532                          // happening.                          // happening.
1533                          if (mapAreaChanged && oldMapArea != null                          if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1534                                            && oldMapArea != null
1535                                          && getMapArea().intersects(oldMapArea)                                          && getMapArea().intersects(oldMapArea)
1536                                          & !getMapArea().equals(oldMapArea)) {                                          && !getMapArea().equals(oldMapArea) && !paneResized) {
1537    
1538                                  mapAreaChanged = false;                                  mapAreaChanged = false;
1539    
1540                                  if (getMapArea().covers(oldMapArea)) {                                  // if (getMapArea().covers(oldMapArea)) {
1541                                          setQuickPreviewHint(ZOOM_OUT);                                  // // quickPreviewHint = ZOOM_OUT;
1542                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1543                                  } else if (oldMapArea.covers(getMapArea())) {                                  // g);
1544                                          setQuickPreviewHint(ZOOM_IN);                                  // } else if (oldMapArea.covers(getMapArea())) {
1545                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // quickPreviewHint = ZOOM_IN;
1546                                  }                                  paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1547                                    // }
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 disposeImages();  
1548                          }                          }
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
1549                  }                  }
1550    
1551                  if (!paintedSomething) {                  if (!paintedSomething) {
1552    
1553                          g.drawImage(getFinalImage(), 0, 0, null);                          g.drawImage(getFinalImage(), 0, 0, null);
1554    
                         g.dispose(); // cand. for removal  
   
1555                          paintedSomething = true; // cand. for removal                          paintedSomething = true; // cand. for removal
1556                  }                  }
1557    
# Line 1512  public class XMapPane extends JPanel { Line 1600  public class XMapPane extends JPanel {
1600    
1601          }          }
1602    
         /**  
          * Performs a {@value #PAN} action. During panning, the displacement is  
          * stored in {@link #imageOrigin} object. Calling {@link #performPan()} will  
          * reset the offset and call {@link #setMapArea(Envelope)}.  
          */  
         public void performPan() {  
   
                 Rectangle winBounds = getVisibleRect();  
                   
                 winBounds.translate(-imageOrigin.x, -imageOrigin.y);  
                 final Envelope newMapArea = tranformWindowToGeo(winBounds.x,  
                                 winBounds.y, winBounds.x + winBounds.width, winBounds.y  
                                                 + winBounds.height);  
   
                 imageOrigin.x = 0;  
                 imageOrigin.y = 0;  
   
                 if (!setMapArea(newMapArea)) {  
                         /**  
                          * If setMapArea returns true, the finalImage is updated anyways.  
                          * This if-case exists to ensure that we repaint a correct image  
                          * even if the new panning area has been denied.  
                          */  
                         updateFinalImage();  
                         repaint();  
                 }  
   
                 if (getCursor() == SwingUtil.PANNING_CURSOR)  
                         setCursor(SwingUtil.PAN_CURSOR);  
         }  
   
1603          //          //
1604          // /**          // /**
1605          // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot          // * Performs a {@value #PAN} action. During panning, the displacement is
1606          // gemacht          // * stored in {@link #imageOrigin} object. Calling {@link #performPan()}
1607          // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.          // will
1608          // *          // * reset the offset and call {@link #setMapArea(Envelope)}.
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
1609          // */          // */
1610          // @Override          // public void performPan() {
         // public void print(final Graphics g) {  
         // final Color orig = getBackground();  
         // setBackground(Color.WHITE);  
1611          //          //
1612          // // wrap in try/finally so that we always restore the state          // final Rectangle winBounds = getVisibleRect();
1613          // try {          //
1614          // super.print(g);          // winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1615          // } finally {          // final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1616          // setBackground(orig);          // winBounds.y, winBounds.x + winBounds.width, winBounds.y
1617            // + winBounds.height);
1618            //
1619            // imageOrigin.x = 0;
1620            // imageOrigin.y = 0;
1621            //
1622            // if (!setMapArea(newMapArea)) {
1623            // /**
1624            // * If setMapArea returns true, the finalImage is updated anyways.
1625            // * This if-case exists to ensure that we repaint a correct image
1626            // * even if the new panning area has been denied.
1627            // */
1628            // updateFinalImage();
1629            // repaint();
1630          // }          // }
1631            //
1632            // if (getCursor() == SwingUtil.PANNING_CURSOR)
1633            // setCursor(SwingUtil.PAN_CURSOR);
1634          // }          // }
1635    
1636          /**          /**
# Line 1583  public class XMapPane extends JPanel { Line 1651  public class XMapPane extends JPanel {
1651          private void requestStartRendering() {          private void requestStartRendering() {
1652                  if (bgExecuter != null)                  if (bgExecuter != null)
1653                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
1654                  if (localExecuter != null)  
1655                          localExecuter.cancelTask();                  localExecuter.cancelTask();
1656    
1657                    mapImageInvalid = true;
1658                    if (paneResized) {
1659                            paneResized = false;
1660                            disposeImages();
1661                    }
1662                  requestStartRendering = true;                  requestStartRendering = true;
1663    
1664          }          }
1665    
         //  
         // /**  
         // * Berechnet die Transformation zwischen Fenster- und Karten-Koordinaten  
         // * neu.  
         // */  
         // protected void resetTransforms() {  
         // if (getMapArea() == null || getWidth() == 0 || getHeight() == 0)  
         // return;  
         //  
         // // We store the last Transform  
         // oldScreenToWorld = screenToWorld;  
         //  
         // this.screenToWorld = new AffineTransform(  
         // // Genauso wie die Fenster-Koordinaten, werden die Longitude-Koordinaten  
         // // nach rechts (Osten) hin groesser  
         // // --> positive Verschiebung  
         // getMapArea().getWidth() / getWidth(),  
         // // keine Verzerrung  
         // 0.0, 0.0,  
         // // Waehrend die Fenster-Koordinaten nach unten hin groesser  
         // // werden,  
         // // werden Latitude-Koordinaten nach Sueden hin keiner  
         // // --> negative Verschiebung  
         // -getMapArea().getHeight() / getHeight(),  
         // // Die Longitude-Koordinaten werden nach Osten hin groesser  
         // // --> obere linke Ecke des Fensters hat also den Minimalwert  
         // getMapArea().getMinX(),  
         // // Die Latitude-Koordinaten werden nach Norden hin groesser  
         // // --> obere linke Ecke des Fensters hat also den Maximalwert  
         // getMapArea().getMaxY());  
         //  
         // try {  
         // this.worldToScreen = screenToWorld.createInverse();  
         // } catch (final NoninvertibleTransformException e) {  
         // LOGGER.error(e);  
         // }  
         // }  
   
1666          /**          /**
1667           * Calculate the affine transforms used to convert between world and pixel           * Calculate the affine transforms used to convert between world and pixel
1668           * coordinates. The calculations here are very basic and assume a cartesian           * coordinates. The calculations here are very basic and assume a cartesian
# Line 1641  public class XMapPane extends JPanel { Line 1677  public class XMapPane extends JPanel {
1677           *            the current map pane extent (screen units)           *            the current map pane extent (screen units)
1678           */           */
1679          private void resetTransforms() {          private void resetTransforms() {
1680                  ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,                  // System.out
1681                                  getContext().getCoordinateReferenceSystem());                  // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1682                    if (!isWellDefined())
1683                            return;
1684    
1685                  Rectangle paintArea = getVisibleRect(); // NOT USE GET BOUNDS!                  if (mapArea == null)
1686                                            return;
1687                  //          
1688                  // double xscale = paintArea.getWidth() / refEnv.getWidth();                  final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1689                  // double yscale = paintArea.getHeight() / refEnv.getHeight();                                  getMapContext().getCoordinateReferenceSystem());
                 //  
                 // double scale = Math.min(xscale, yscale);  
                 //  
                 // double xoff = refEnv.getMedian(0) * scale - paintArea.getCenterX();  
                 // double yoff = refEnv.getMedian(1) * scale + paintArea.getCenterY();  
1690    
1691                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1692                                  paintArea);                                  getVisibleRect());
1693    
                 // worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff,  
                 // yoff);  
1694                  try {                  try {
1695                          screenToWorld = worldToScreen.createInverse();                          screenToWorld = worldToScreen.createInverse();
1696    
1697                  } catch (NoninvertibleTransformException ex) {                  } catch (final NoninvertibleTransformException ex) {
1698                          ex.printStackTrace();                          LOGGER
1699                                            .error("can't invert worldToScreen to get screenToWorld!",
1700                                                            ex);
1701                  }                  }
1702          }          }
1703    
# Line 1683  public class XMapPane extends JPanel { Line 1716  public class XMapPane extends JPanel {
1716                  this.bgContext = context;                  this.bgContext = context;
1717    
1718                  if (context != null) {                  if (context != null) {
1719                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1720    
1721                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1722    
# Line 1692  public class XMapPane extends JPanel { Line 1725  public class XMapPane extends JPanel {
1725                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1726                          }                          }
1727                  }                  }
1728                  mapImageInvalid = true;  
1729                  repaint();                  requestStartRendering();
1730          }          }
1731    
1732          public void setJava2dHints(final RenderingHints java2dHints) {          public void setJava2dHints(final RenderingHints java2dHints) {
1733                  this.java2dHints = java2dHints;                  this.java2dHints = java2dHints;
1734          }          }
1735    
         /**  
          *  
          * @param context  
          */  
1736          public void setLocalContext(final MapContext context) {          public void setLocalContext(final MapContext context) {
1737                  // Remove the default listener from the old context                  // Remove the default listener from the old context
1738                  if (this.localContext != null) {                  if (this.localContext != null) {
# Line 1719  public class XMapPane extends JPanel { Line 1748  public class XMapPane extends JPanel {
1748    
1749                  if (context != null) {                  if (context != null) {
1750    
1751                          setMapArea(localContext.getAreaOfInterest());                          // setMapArea(localContext.getAreaOfInterest());
1752    
1753                          localRenderer.setContext(localContext);                          getLocalRenderer().setContext(localContext);
1754    
1755                          this.localContext.addMapLayerListListener(localContextListener);                          this.localContext.addMapLayerListListener(localContextListener);
1756    
# Line 1731  public class XMapPane extends JPanel { Line 1760  public class XMapPane extends JPanel {
1760                          }                          }
1761                  }                  }
1762    
1763                    requestStartRendering();
1764    
1765            }
1766    
1767            public void setBorder(final Border b) {
1768                    super.setBorder(b);
1769            }
1770    
1771            /**
1772             * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1773             */
1774            public void refresh() {
1775                  mapImageInvalid = true;                  mapImageInvalid = true;
1776                  repaint();                  repaint();
1777          }          }
1778    
1779            // /**
1780            // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1781            // * called after {@link Style}s have been changed because GTRenderer is
1782            // * otherwise not working well.
1783            // */
1784            // public void refreshRenderers() {
1785            // localRenderer = GTUtil.createGTRenderer();
1786            // setLocalContext(getMapContext());
1787            // mapImageInvalid = true;
1788            // repaint();
1789            // }
1790    
1791          /**          /**
1792             * Set the new map area.
1793             *
1794           * @param newMapArea           * @param newMapArea
1795           * @return <code>true</code> if the mapArea has been changed and a repaint           * @return <code>true</code> if the mapArea has been changed and a repaint
1796           *         has been triggered.           *         has been triggered.
1797           */           */
1798          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final Envelope newMapArea) {
1799                    if (newMapArea == null)
1800                            return false;
1801                    if (getMapContext().getCoordinateReferenceSystem() == null)
1802                            return false;
1803                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1804                                    .getCoordinateReferenceSystem()));
1805            }
1806    
1807            /**
1808             * Set the new map area.
1809             *
1810             * @param newMapArea
1811             * @return <code>true</code> if the mapArea has been changed and a repaint
1812             *         has been triggered.
1813             */
1814            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1815    
1816                  if (newMapArea == null                  if (newMapArea == null
1817                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1795  public class XMapPane extends JPanel { Line 1866  public class XMapPane extends JPanel {
1866                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1867                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1868                  }                  }
1869                  mapImageInvalid = true;  
1870                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1871    
1872                  LOGGER.debug("New maparea = " + mapArea);                  repaint(200); // Do not remove it!
1873    
1874                    requestStartRendering();
1875    
1876                  return true;                  return true;
1877          }          }
1878    
# Line 1808  public class XMapPane extends JPanel { Line 1881  public class XMapPane extends JPanel {
1881           *           *
1882           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1883           */           */
1884          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(final Color bgColor) {
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
1885                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1886          }          }
1887    
# Line 1868  public class XMapPane extends JPanel { Line 1939  public class XMapPane extends JPanel {
1939          }          }
1940    
1941          // /** Stored the time used for the last real rendering in ms. **/          // /** Stored the time used for the last real rendering in ms. **/
1942          // private long lastRenderingDuration = Long.MAX_VALUE;          private long lastRenderingDuration = 1000;
1943            private XMapPaneTool tool = null;
1944    
1945          /**          /**
1946           * Set the minimum (nearest) allowed zoom scale. This is the bigger number           * Set the minimum (nearest) allowed zoom scale. This is the bigger number
# Line 1885  public class XMapPane extends JPanel { Line 1957  public class XMapPane extends JPanel {
1957          }          }
1958    
1959          /**          /**
1960           *           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1961           * @param b           * requests. Otherwise the map will not paint anything and not start any
1962             * rendering {@link Thread}s.
1963           */           */
1964          public void setPainting(final boolean b) {          public void setPainting(final boolean b) {
1965                  acceptsRepaintCalls = b;                  acceptsRepaintCalls = b;
1966          }                  if (acceptsRepaintCalls == true)
1967                            repaint();
         // /**  
         // * Returns in milli seconds the time the last rending of the  
         // * {@link SelectableXMapPane} took. #Long.MAX_VALUE if the JMapPane has  
         // not  
         // * been rendered yet.  
         // */  
         // public long getLastRenderingDuration() {  
         // return lastRenderingDuration;  
         // }  
   
         public void setQuickPreviewHint(final int quickPreviewHint) {  
                 this.quickPreviewHint = quickPreviewHint;  
   
1968          }          }
1969    
1970          private void setRendererHints(final Map<Object, Object> rendererHints) {          private void setRendererHints(final Map<Object, Object> rendererHints) {
# Line 1912  public class XMapPane extends JPanel { Line 1972  public class XMapPane extends JPanel {
1972                          this.rendererHints = rendererHints;                          this.rendererHints = rendererHints;
1973          }          }
1974    
1975          /**          // @Deprecated
1976           * Enables/Disables the ZOOM Mouse Listener. Upates the Cursor and stops the          // public void setState(final int state) {
1977           * repaint Timer if          // this.state = state;
1978           *          //
1979           * @param state          // // throw new RuntimeException("Old concept.. migrate to new concept!");
1980           */          //
1981          public void setState(final int state) {          // // xMapPaneMouseListener.setEnabled((state == ZOOM_IN
1982                  this.state = state;          // // || state == ZOOM_OUT || state == PAN));
1983            //
1984                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN          // // Je nach Aktion den Cursor umsetzen
1985                                  || state == ZOOM_OUT || state == PAN));          // updateCursor();
1986            // }
1987    
1988                  // Je nach Aktion den Cursor umsetzen          public void configureMouse(MouseInputType type, XMapPaneAction action) {
1989                  updateCursor();                  xMapPaneMouseListener.actions.put(type, action);
1990          }          }
1991    
1992          /**          /**
1993           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,           * Configure the {@link XMapPaneTool} that active on the map. Passing
1994           * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor           * <code>null</code> will set the NO_ACTION tool.
1995           * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion           */
1996           * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann          public void setTool(XMapPaneTool tool) {
1997           * {@code null} als Parameter uebergeben werden                  if (tool == null)
1998           *                          tool = XMapPaneTool.NO_ACTION;
1999           * @param cursor                  this.tool = tool;
2000           *            Cursor                  xMapPaneMouseListener.configure(tool);
2001           */                  setCursor(tool.getCursor());
         public void setStaticCursor(final Cursor cursor) {  
                 this.staticCursor = cursor;  
                 if (cursor != null)  
                         super.setCursor(cursor);  
2002          }          }
2003    
2004            // /**
2005            // * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion
2006            // (Zoom,
2007            // * Auswahl, ...) gesetzt. Mit dieser Methode kann ein statischer Cursor
2008            // * gesetzt werden, der unabhaengig von der aktuellen MapPanes-Aktion
2009            // * beibehalten wird. Um diesen statischen Cursor wieder zu entfernen, kann
2010            // * {@code null} als Parameter uebergeben werden
2011            // *
2012            // * @param cursor
2013            // * Cursor
2014            // */
2015            // public void setStaticCursor(final Cursor cursor) {
2016            // this.staticCursor = cursor;
2017            // if (cursor != null)
2018            // super.setCursor(cursor);
2019            // }
2020    
2021          /**          /**
2022           * Starts rendering on one or two threads           * Starts rendering on one or two threads
2023           */           */
2024          private void startRendering() {          private void startRendering() {
2025    
2026                  if (!isWellDefined())                  if (!isWellDefined() || !acceptsRepaintCalls) {
2027                            // if we are not ready to start rendering, try it again the next
2028                            // time the timer is chacking the flag.
2029                            requestStartRendering = true;
2030                          return;                          return;
2031                    }
2032    
2033                  if (bgExecuter != null) {                  if (bgExecuter != null) {
2034                          // Stop all renderers                          // Stop all renderers
2035                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
2036                  }                  }
2037    
2038                  if (localExecuter != null) {                  localExecuter.cancelTask();
                         localExecuter.cancelTask();  
                 }  
2039    
2040                  final Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
2041    
# Line 1982  public class XMapPane extends JPanel { Line 2058  public class XMapPane extends JPanel {
2058                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
2059                  }                  }
2060    
2061                  if (getContext() != null) {                  if (getMapContext() != null) {
2062                          // localExecuter = new RenderingExecutor(this, 150l);                          // localExecuter = new RenderingExecutor(this, 150l);
2063                          // LOGGER.debug("starting local renderer:");                          // LOGGER.debug("starting local renderer:");
2064    
2065                          localRenderer.setJava2DHints(getJava2dHints());                          getLocalRenderer().setJava2DHints(getJava2dHints());
2066                          localRenderer.setRendererHints(getRendererHints());                          getLocalRenderer().setRendererHints(getRendererHints());
2067    
2068                          ReferencedEnvelope areaOfInterest = getMapArea();                          final boolean submitted = localExecuter.submit(getMapArea(),
                         final boolean submitted = localExecuter.submit(areaOfInterest,  
2069                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2070                                          localRenderer, getWorldToScreenTransform());                                          getLocalRenderer());
2071                          if (submitted)                          if (submitted)
2072                                  repaintTimer.restart();                                  repaintTimer.restart();
2073                          else                          else
2074                                  requestStartRendering = true; // Try to start rendering again in                                  requestStartRendering = true; // Try to start rendering
2075                            // again in
2076                          // a moment                          // a moment
2077                  }                  }
2078    
2079                  updateCursor();                  updateCursor();
2080          }          }
2081    
2082            private RenderingHints getJava2dHints() {
2083                    return java2dHints;
2084            }
2085    
2086          /**          /**
2087           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2088           *           *
# Line 2049  public class XMapPane extends JPanel { Line 2129  public class XMapPane extends JPanel {
2129                  final AffineTransform at = getScreenToWorld();                  final AffineTransform at = getScreenToWorld();
2130                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2131                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2132                    
2133                  // Mmmmm... don't really understand why its x,x,y,y                  // Mmmmm... don't really understand why its x,x,y,y
2134  //              return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());                  // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2135                  return new Envelope( new Coordinate(geoO.getX(), geoO.getY()), new Coordinate(geoP.getX(), geoP.getY()));                  // geoP.getY());
2136                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2137                                    new Coordinate(geoP.getX(), geoP.getY()));
2138          }          }
2139    
2140          /**          /**
# Line 2064  public class XMapPane extends JPanel { Line 2146  public class XMapPane extends JPanel {
2146                  // if the renderers have stopped, also stop the timer that is updating                  // if the renderers have stopped, also stop the timer that is updating
2147                  // the final image                  // the final image
2148                  if (bgExecuter != null && bgExecuter.isRunning()                  if (bgExecuter != null && bgExecuter.isRunning()
2149                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2150                          setCursor(WAIT_CURSOR);                          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2151                          return;                          return;
2152                  } else {                  } else {
2153                          // Allow one last rendering                          // Allow one last rendering
2154                          if (repaintTimer.isRunning()) {                          if (repaintTimer.isRunning()) {
2155                                  System.out.println("one last rendering....");                                  // System.out.println("one last rendering....");
2156                                  repaintTimer.stop();                                  repaintTimer.stop();
2157                                  updateFinalImage();                                  updateFinalImage();
2158                                  repaint();                                  repaint();
2159                          }                          }
2160                  }                  }
2161                    //              
2162                  // wenn manueller Cursor gesetzt ist, dann diesen verwenden (unabhaengig                  // //
2163                  // von der aktuellen Aktion                  // // wenn manueller Cursor gesetzt ist, dann diesen verwenden
2164                  if (this.staticCursor != null) {                  // (unabhaengig
2165                          setCursor(staticCursor);                  // // von der aktuellen Aktion
2166                          return;                  // if (this.staticCursor != null) {
2167                  }                  // setCursor(staticCursor);
2168                    // return;
2169                    // }
2170                    //              
2171                  if (getCursor() == SwingUtil.PANNING_CURSOR) {                  if (getCursor() == SwingUtil.PANNING_CURSOR) {
2172                          // This cursor will reset itself                          // This cursor will reset itself
2173                          return;                          return;
2174                  }                  }
2175    
2176                  // Set the cursor depending on what tool is in use...                  setCursor(tool.getCursor());
2177                  switch (state) {  
2178                  case SELECT_TOP:                  //
2179                  case SELECT_ONE_FROM_TOP:                  // // Set the cursor depending on what tool is in use...
2180                  case SELECT_ALL:                  // switch (state) {
2181                          setCursor(SwingUtil.CROSSHAIR_CURSOR);                  // case SELECT_TOP:
2182                          break;                  // case SELECT_ONE_FROM_TOP:
2183                  case ZOOM_IN:                  // case SELECT_ALL:
2184                          setCursor(SwingUtil.ZOOMIN_CURSOR);                  // setCursor(SwingUtil.CROSSHAIR_CURSOR);
2185                          break;                  // break;
2186                  case ZOOM_OUT:                  // case ZOOM_IN:
2187                          setCursor(SwingUtil.ZOOMOUT_CURSOR);                  // setCursor(SwingUtil.ZOOMIN_CURSOR);
2188                          break;                  // break;
2189                  case PAN:                  // case ZOOM_OUT:
2190                          setCursor(SwingUtil.PAN_CURSOR);                  // setCursor(SwingUtil.ZOOMOUT_CURSOR);
2191                          break;                  // break;
2192                  default:                  // case PAN:
2193                          setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));                  // setCursor(SwingUtil.PAN_CURSOR);
2194                          break;                  // break;
2195                  }                  // default:
2196                    // setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
2197                    // break;
2198                    // }
2199          }          }
2200    
2201          /**          /**
# Line 2137  public class XMapPane extends JPanel { Line 2225  public class XMapPane extends JPanel {
2225    
2226                  final Graphics2D finalG = getFinalImage().createGraphics();                  final Graphics2D finalG = getFinalImage().createGraphics();
2227                  finalG.setBackground(getMapBackgroundColor());                  finalG.setBackground(getMapBackgroundColor());
2228                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,                  finalG.drawImage(getPreFinalImage(), getImageOrigin().x,
2229                                  getMapBackgroundColor(), null);                                  getImageOrigin().y, getMapBackgroundColor(), null);
2230    
2231                  final int finalImageHeight = getFinalImage().getHeight(null);                  // When panning, we have to clear the area around the image
2232                  final int finalImageWidth = getFinalImage().getWidth(null);                  final Rectangle painedArea = new Rectangle(getImageOrigin().x,
2233                                    getImageOrigin().y, getFinalImage().getWidth(), getFinalImage()
2234                                                    .getHeight());
2235                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2236                                    getMapBackgroundColor());
2237    
2238                  final Rectangle painedArea = new Rectangle(imageOrigin.x,                  // addGadgets(finalG, false);
                                 imageOrigin.y, finalImageWidth, finalImageHeight);  
                 SwingUtil.clearAround(finalG, painedArea, getVisibleRect());  
   
                 addGadgets(finalG, false);  
2239    
2240                  finalG.dispose();                  finalG.dispose();
2241    
# Line 2164  public class XMapPane extends JPanel { Line 2252  public class XMapPane extends JPanel {
2252           *            <code>false</code>, it will only depend on           *            <code>false</code>, it will only depend on
2253           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2254           */           */
2255          private void addGadgets(final Graphics2D graphics, boolean forceWait) {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2256    
2257                  // Paint a logo to the bottom right if available                  // Paint a logo to the bottom right if available
2258                  if (mapImage != null) {                  if (mapImage != null) {
2259                          Rectangle visibleRect = getVisibleRect();                          final Rectangle visibleRect = getVisibleRect();
2260                          graphics.drawImage(mapImage, visibleRect.width                          graphics.drawImage(mapImage, visibleRect.width
2261                                          - mapImage.getWidth() - 10, getVisibleRect().height                                          - mapImage.getWidth() - 10, getVisibleRect().height
2262                                          - mapImage.getHeight() - 10, null);                                          - mapImage.getHeight() - 10, null);
# Line 2178  public class XMapPane extends JPanel { Line 2266  public class XMapPane extends JPanel {
2266    
2267                  // If the rendering process is still running, indicate this is the image                  // If the rendering process is still running, indicate this is the image
2268                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2269                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2270    
2271                          y += 8;                          y += 8;
2272    
# Line 2194  public class XMapPane extends JPanel { Line 2282  public class XMapPane extends JPanel {
2282    
2283                          graphics.setColor(c);                          graphics.setColor(c);
2284    
2285                          y += 24;                          y += 21;
2286                  }                  }
2287    
2288                  if (renderingErrors != null) {                  if (!renderingErrors.isEmpty() && isShowExceptions()) {
2289    
2290                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2291                          graphics.setFont(errorFont);                          graphics.setFont(errorFont);
2292    
2293                          for (Exception ex : renderingErrors) {                          for (final Exception ex : renderingErrors) {
   
                                 if (ex instanceof java.lang.IllegalArgumentException  
                                                 && ex.getMessage().equals(  
                                                                 "Argument \"sourceCRS\" should not be null."))  
                                         continue;  
2294    
2295                                  String errStr = ex.getLocalizedMessage();                                  String errStr = ex.getLocalizedMessage();
2296    
2297                                  graphics.setColor(Color.WHITE);                                  if (errStr == null)
2298                                            errStr = ex.getMessage();
2299                                    if (errStr == null)
2300                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2301    
2302                                    graphics.setColor(getMapBackgroundColor());
2303                                  graphics.drawString(errStr, 5, y);                                  graphics.drawString(errStr, 5, y);
2304                                  graphics.setColor(Color.RED);                                  graphics.setColor(Color.RED);
2305                                  graphics.drawString(errStr, 6, y + 1);                                  graphics.drawString(errStr, 6, y + 1);
# Line 2234  public class XMapPane extends JPanel { Line 2322  public class XMapPane extends JPanel {
2322          public void zoomTo(          public void zoomTo(
2323                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2324    
2325                  final CoordinateReferenceSystem mapCRS = getContext()                  // if (!isWellDefined()) return;
2326    
2327                    final CoordinateReferenceSystem mapCRS = getMapContext()
2328                                  .getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2329                  final CoordinateReferenceSystem fCRS = features.getSchema()                  final CoordinateReferenceSystem fCRS = features.getSchema()
2330                                  .getGeometryDescriptor().getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2331    
2332                  double width = mapArea.getWidth();                  ReferencedEnvelope _mapArea;
2333                  double height = mapArea.getHeight();                  if (mapArea == null)
2334                            _mapArea = features.getBounds();
2335                    else
2336                            _mapArea = getMapArea();
2337                    double width = _mapArea.getWidth();
2338                    double height = _mapArea.getHeight();
2339                  final double ratio = height / width;                  final double ratio = height / width;
2340    
2341                  if (features == null || features.size() == 0) {                  if (features == null || features.size() == 0) {
# Line 2292  public class XMapPane extends JPanel { Line 2387  public class XMapPane extends JPanel {
2387                  } else {                  } else {
2388                          final ReferencedEnvelope fBounds = features.getBounds();                          final ReferencedEnvelope fBounds = features.getBounds();
2389    
2390                          Envelope bounds;                          ReferencedEnvelope bounds;
2391                          if (!mapCRS.equals(fCRS)) {                          if (!mapCRS.equals(fCRS)) {
2392                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2393                          } else {                          } else {
2394                                  bounds = fBounds;                                  bounds = fBounds;
2395                          }                          }
2396                          // BB umrechnen von Layer-CRS in Map-CRS                          // BB umrechnen von Layer-CRS in Map-CRS
2397    
2398                          // Expand a bit                          // Expand a bit
2399                          bounds.expandBy(bounds.getWidth() / 6., bounds.getHeight() / 6.);                          addDefaultMargin(bounds);
2400    
2401                          setMapArea(bounds);                          setMapArea(bounds);
2402                  }                  }
2403          }          }
2404    
2405            private ReferencedEnvelope addDefaultMargin(ReferencedEnvelope bounds) {
2406                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2407                                    defaultMaxMapExtendMode));
2408            }
2409    
2410            private Envelope addDefaultMargin(Envelope bounds) {
2411                    return JTSUtil.expandEnvelope(bounds, Math.max(0,
2412                                    defaultMaxMapExtendMode));
2413            }
2414    
2415          /**          /**
2416           * Zooms towards a point.           * Zooms towards a point.
2417           *           *
# Line 2325  public class XMapPane extends JPanel { Line 2430  public class XMapPane extends JPanel {
2430           * @param center           * @param center
2431           *            position in window coordinates           *            position in window coordinates
2432           * @param zoomFaktor           * @param zoomFaktor
2433           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.           *            > 1 for zoom out, < 1 for zoom in. Default is .5
2434           */           */
2435          public void zoomTo(Point center, Double zoomFaktor) {          public void zoomTo(Point center, Double zoomFaktor) {
2436                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2437                          zoomFaktor = 2.;                          zoomFaktor = .5;
2438    
2439                  final Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2440                  center = null;                  center = null;
# Line 2349  public class XMapPane extends JPanel { Line 2454  public class XMapPane extends JPanel {
2454                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2455                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2456                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2457                    
2458  // TODO we actually want that                  // // Move the newMapArea above the new center if we zoom in:
2459  //              // Move the newMapArea above the new center                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2460  //              newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                                  .getY()
2461  //                              .getY()                                  - mapArea.centre().y);
 //                              - mapArea.centre().y);  
2462    
2463                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2464          }          }
2465    
2466            /**
2467             * Shall non-fatal rendering exceptions be reported in the mappane or be
2468             * dropped quitely.
2469             */
2470            public void setShowExceptions(final boolean showExceptions) {
2471                    this.showExceptions = showExceptions;
2472            }
2473    
2474            /**
2475             * Shall exceptions be reported in the mappane?
2476             */
2477            public boolean isShowExceptions() {
2478                    return showExceptions;
2479            }
2480    
2481            public GTRenderer getLocalRenderer() {
2482                    return localRenderer;
2483            }
2484    
2485            /**
2486             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2487             * Macht nichts, wenn {@code null} uebergeben wird.
2488             *
2489             * <br>
2490             *
2491             * @param layer
2492             *            ein Layer
2493             */
2494            public void zoomToLayer(MapLayer layer) {
2495                    if (layer == null)
2496                            return;
2497                    try {
2498    
2499                            // BB umrechnen von Layer-CRS in Map-CRS
2500                            final CoordinateReferenceSystem targetCRS = getMapContext()
2501                                            .getCoordinateReferenceSystem();
2502                            final CoordinateReferenceSystem sourceCRS = layer
2503                                            .getFeatureSource().getSchema()
2504                                            .getCoordinateReferenceSystem();
2505    
2506                            Envelope mapAreaNew;
2507                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2508                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2509                                                    .getBounds(), sourceCRS, targetCRS);
2510                            } else {
2511                                    try {
2512                                            mapAreaNew = layer.getFeatureSource().getBounds();
2513                                    } catch (java.lang.IllegalArgumentException e) {
2514                                            LOGGER.error("Can't calc layers bounds...", e);
2515                                            mapAreaNew = null;
2516    
2517                                            /**
2518                                             *
2519                                             23.10.2009 11:20:50
2520                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2521                                             * WARNUNG: only one hole in this polygon record ERROR
2522                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2523                                             * correctly java.lang.IllegalArgumentException: Points of
2524                                             * LinearRing do not form a closed linestring at
2525                                             * com.vividsolutions
2526                                             * .jts.geom.LinearRing.validateConstruction
2527                                             * (LinearRing.java:105) at
2528                                             * com.vividsolutions.jts.geom.LinearRing
2529                                             * .<init>(LinearRing.java:100) at
2530                                             * com.vividsolutions.jts.geom
2531                                             * .GeometryFactory.createLinearRing
2532                                             * (GeometryFactory.java:339) at
2533                                             * org.geotools.data.shapefile.
2534                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2535                                             * org.geotools
2536                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2537                                             * (ShapefileReader.java:106) at
2538                                             * org.geotools.data.shapefile.
2539                                             * ShapefileAttributeReader.next(
2540                                             * ShapefileAttributeReader.java:157) at
2541                                             * org.geotools.data.shapefile
2542                                             * .indexed.IndexedShapefileAttributeReader
2543                                             * .next(IndexedShapefileAttributeReader.java:122) at
2544                                             * org.geotools
2545                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2546                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2547                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2548                                             * MaxFeatureReader.java:61) at
2549                                             * org.geotools.data.MaxFeatureReader
2550                                             * .next(MaxFeatureReader.java:61)
2551                                             **/
2552                                    }
2553                            }
2554    
2555                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2556                            // Punkt-Layer,
2557                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2558                            // sonst
2559                            // genau auf dem Rand der angezeigten Flaeche)
2560    
2561                            if (mapAreaNew != null) {
2562    
2563                                    mapAreaNew = addDefaultMargin(mapAreaNew);
2564                                    setMapArea(mapAreaNew);
2565                            } else {
2566                                    LOGGER
2567                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2568                            }
2569                    } catch (Exception err) {
2570                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2571                    }
2572            }
2573    
2574            /**
2575             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2576             *
2577             * <br>
2578             * A refresh of the map is not done automatically
2579             *
2580             * @param index
2581             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2582             *            back to top)
2583             *
2584             * @author <a href="mailto:[email protected]">Stefan Alfons
2585             *         Kr&uuml;ger</a>
2586             */
2587            public void zoomToLayer(int index) {
2588                    final MapContext context = getMapContext();
2589                    if (context != null)
2590                            zoomToLayer(context.getLayer(index));
2591            }
2592    
2593            /**
2594             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2595             * selected layer. The layer is selected by the idx, counting from front to
2596             * back, like humans would expect in a {@link JList}
2597             *
2598             * <br>
2599             * A refresh of the map is not done automatically
2600             *
2601             *
2602             *
2603             * @param index
2604             *            Reverse index of the {@link MapLayer} in the
2605             *            {@link MapContext}
2606             *
2607             * @author <a href="mailto:[email protected]">Stefan Alfons
2608             *         Kr&uuml;ger</a>
2609             */
2610            public void zoomToLayerIdxReverse(int index) {
2611                    zoomToLayer(getMapContext().getLayerCount() - 1 - index);
2612            }
2613    
2614            /**
2615             * Aktiviert oder deaktiviert das AntiAliasing for diese
2616             * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2617             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2618             *
2619             * @author <a href="mailto:[email protected]">Stefan Alfons
2620             *         Kr&uuml;ger</a>
2621             */
2622            public void setAntiAliasing(final boolean aa) {
2623                    // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2624                    RenderingHints java2DHints = java2dHints;
2625                    if (java2DHints == null) {
2626                            java2DHints = GeoTools.getDefaultHints();
2627                    }
2628    
2629                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2630                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2631                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2632                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2633                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2634                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2635                    java2DHints.put(RenderingHints.KEY_RENDERING,
2636                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2637                                                    : RenderingHints.VALUE_RENDER_SPEED);
2638    
2639            }
2640    
2641            public Point getImageOrigin() {
2642                    return imageOrigin;
2643            }
2644    
2645            /**
2646             * If {@link #maxExtend} is <code>null</code> the following rules are used
2647             * to create a default maximum.
2648             * <ul>
2649             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2650             * margin</li>
2651             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2652             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2653             * relative margin</li>
2654             * </ul>
2655             * **/
2656            public void setDefaultMaxMapExtendMode(double defaultMaxMapExtendMode) {
2657                    this.defaultMaxMapExtendMode = defaultMaxMapExtendMode;
2658            }
2659    
2660            /**
2661             * If {@link #maxExtend} is <code>null</code> the following rules are used
2662             * to create a default maximum.
2663             * <ul>
2664             * <li>Values &lt; 0 : don't grow to fit the monitors aspect ratio, no
2665             * margin</li>
2666             * <li>Values 0 : grow to fit the monitors aspect ratio, no margin</li>
2667             * <li>Values &gt; 0 : grow to fit the monitors aspect ratio, and add a
2668             * relative margin</li>
2669             * </ul>
2670             * **/
2671            public double getDefaultMaxMapExtendMode() {
2672                    return defaultMaxMapExtendMode;
2673            }
2674    
2675  }  }

Legend:
Removed from v.540  
changed lines
  Added in v.660

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26