/[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 648 by alfonx, Thu Jan 28 16:51:55 2010 UTC
# Line 26  import java.util.HashMap; Line 26  import java.util.HashMap;
26  import java.util.Map;  import java.util.Map;
27  import java.util.Vector;  import java.util.Vector;
28    
29    import javax.swing.JList;
30  import javax.swing.Timer;  import javax.swing.Timer;
31    import javax.swing.border.Border;
32    
33  import org.apache.log4j.Logger;  import org.apache.log4j.Logger;
34    import org.geotools.factory.GeoTools;
35  import org.geotools.feature.FeatureCollection;  import org.geotools.feature.FeatureCollection;
36  import org.geotools.geometry.Envelope2D;  import org.geotools.geometry.DirectPosition2D;
37  import org.geotools.geometry.jts.JTS;  import org.geotools.geometry.jts.JTS;
38  import org.geotools.geometry.jts.ReferencedEnvelope;  import org.geotools.geometry.jts.ReferencedEnvelope;
39  import org.geotools.map.DefaultMapContext;  import org.geotools.map.DefaultMapContext;
# Line 66  import schmitzm.geotools.map.event.MapLa Line 69  import schmitzm.geotools.map.event.MapLa
69  import schmitzm.lang.LangUtil;  import schmitzm.lang.LangUtil;
70  import schmitzm.swing.JPanel;  import schmitzm.swing.JPanel;
71  import schmitzm.swing.SwingUtil;  import schmitzm.swing.SwingUtil;
72    import schmitzm.swing.event.MouseInputType;
73    
74  import com.vividsolutions.jts.geom.Coordinate;  import com.vividsolutions.jts.geom.Coordinate;
75  import com.vividsolutions.jts.geom.Envelope;  import com.vividsolutions.jts.geom.Envelope;
# Line 96  import com.vividsolutions.jts.geom.Geome Line 100  import com.vividsolutions.jts.geom.Geome
100   */   */
101  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
102    
103          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;          // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
104          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;          // private static final int IMAGETYPE_withAlpha =
105            // BufferedImage.TYPE_INT_ARGB;
106            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
107            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
108    
109          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
110    
111            /** A flag indicating whether the {@link XMapPane} is accepting repaints from the EDT. @see {@link XMapPane#setPainting(boolean)) **/
112          private boolean acceptsRepaintCalls = true;          private boolean acceptsRepaintCalls = true;
113    
114          /**          /**
# Line 125  public class XMapPane extends JPanel { Line 133  public class XMapPane extends JPanel {
133           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
134           * renderers have finished.           * renderers have finished.
135           *           *
136           * @see #INITIAL_REPAINT_DELAYAL           * @see INITIAL_REPAINT_DELAYAL
137           * @see #REPEATING_REPAINT_DELAY           * @see #REPEATING_REPAINT_DELAY
138           */           */
139          final private Timer repaintTimer;          final private Timer repaintTimer;
# Line 134  public class XMapPane extends JPanel { Line 142  public class XMapPane extends JPanel {
142           * The initial delay in milliseconds until the {@link #finalImage} is           * The initial delay in milliseconds until the {@link #finalImage} is
143           * updated the first time.           * updated the first time.
144           */           */
145          public static final int INITIAL_REPAINT_DELAY = 1000;          public static final int INITIAL_REPAINT_DELAY = 900;
146    
147          /**          /**
148           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
149           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
150           * with previews.           * with previews.
151           */           */
152          public static final long REPEATING_REPAINT_DELAY = 500;          public static final int REPEATING_REPAINT_DELAY = 500;
153    
154          /**          /**
155           * Default delay (milliseconds) before the map will be redrawn when resizing           * Default delay (milliseconds) before the map will be redrawn when resizing
156           * the pane. This is to avoid flickering while drag-resizing.           * the pane. This is to avoid flickering while drag-resizing.
157             *
158             * @see #resizeTimer
159           */           */
160          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
161    
162            /**
163             * This not-repeating {@link Timer} is re-started whenever the component is
164             * resized. That means => only if the component is not resizing for
165             * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
166             * {@link XMapPane} react.
167             */
168            private final Timer resizeTimer;
169    
170            /**
171             * Flag for no-tool.
172             */
173          public static final int NONE = -123;          public static final int NONE = -123;
174    
175          /**          /**
# Line 160  public class XMapPane extends JPanel { Line 181  public class XMapPane extends JPanel {
181          public static final int PAN = 1;          public static final int PAN = 1;
182    
183          /**          /**
184             * Flag fuer Modus "Heran zoomen".
185             *
186             * @see #setState(int)
187             * @see #setState(int)
188             */
189            public static final int ZOOM_IN = 2;
190    
191            /**
192             * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
193             *
194             * @see #setState(int)
195             */
196            public static final int ZOOM_OUT = 3;
197    
198            /**
199           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
200           *           *
201           * @see #setState(int)           * @see #setState(int)
# Line 183  public class XMapPane extends JPanel { Line 219  public class XMapPane extends JPanel {
219           */           */
220          public static final int SELECT_TOP = 4;          public static final int SELECT_TOP = 4;
221    
222          public static final Cursor WAIT_CURSOR = Cursor          /**
223                          .getPredefinedCursor(Cursor.WAIT_CURSOR);           * {@link Font} used to paint the wait messages into the map
224             *
225          final static Font waitFont = new Font("Arial", Font.BOLD, 30);           * @see #addGadgets(Graphics2D, boolean)
226          final String waitMsg = SwingUtil.R("WaitMess");           */
227          final static Font errorFont = new Font("Arial", Font.BOLD, 13);          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
228    
229          /**          /**
230           * Flag fuer Modus "Heran zoomen".           * {@link Font} used to paint error messages into the map
231           *           *
232           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
233           */           */
234          public static final int ZOOM_IN = 2;          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
235    
236          /**          /**
237           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * If last average last two renderings took more than that many ms, show the
238             * user a scaled preview
239             **/
240            private static final long PRESCALE_MINTIME = 230;
241    
242            /**
243             * The wait message painted into the map while rendering is going on on
244             * another thread.
245           *           *
246           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
247           */           */
248          public static final int ZOOM_OUT = 3;          final String waitMsg = SwingUtil.R("WaitMess");
249    
250          /**          /**
251           * 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 254  public class XMapPane extends JPanel {
254           * @param e           * @param e
255           *            Maus-Ereignis           *            Maus-Ereignis
256           */           */
257          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
258                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
259                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
260                          try {                          try {
261                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition();
262                          } catch (final Exception err) {                          } catch (final Exception err) {
263                                  LOGGER                                  LOGGER
264                                                  .error(                                                  .error(
# Line 233  public class XMapPane extends JPanel { Line 275  public class XMapPane extends JPanel {
275                                  return null;                                  return null;
276    
277                          final AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
278                          if (at != null)                          if (at != null) {
279                                  return at.transform(e.getPoint(), null);                                  Point2D transformed = at.transform(e.getPoint(), null);
280                                    return new DirectPosition2D(xMapPane.getMapContext()
281                                                    .getCoordinateReferenceSystem(), transformed.getX(),
282                                                    transformed.getY());
283                            }
284                          return null;                          return null;
285                  }                  }
286                  throw new IllegalArgumentException(                  throw new IllegalArgumentException(
# Line 249  public class XMapPane extends JPanel { Line 295  public class XMapPane extends JPanel {
295    
296                  @Override                  @Override
297                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
298                            final MapLayer layer = event.getLayer();
                         MapLayer layer = event.getLayer();  
   
299                          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();  
300                          requestStartRendering();                          requestStartRendering();
301    
302                  }                  }
303    
304                  @Override                  @Override
305                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
306                          requestStartRendering();                          requestStartRendering();
307                  }                  }
308    
309                  @Override                  @Override
310                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
311                          requestStartRendering();                          requestStartRendering();
312                  }                  }
313    
# Line 288  public class XMapPane extends JPanel { Line 315  public class XMapPane extends JPanel {
315                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
316                          if (event.getLayer() != null)                          if (event.getLayer() != null)
317                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
318                          requestStartRendering();                          requestStartRendering();
319                  }                  }
320          };          };
321    
322          /**          /**
323           * compass and icon are rendered into this image           * This {@link RenderingExecutor} manages the creation and cancellation of
324             * up to one {@link Thread} for rendering the {@link #localContext}.
325           */           */
326          // protected BufferedImage gadgetsImage;          private final RenderingExecutor localExecuter = new RenderingExecutor(this);
327    
328            /**
329             * This {@link RenderingExecutor} manages the creation and cancellation of
330             * up to one {@link Thread} for rendering the {@link #bgContext}.
331             */
332          protected RenderingExecutor bgExecuter;          protected RenderingExecutor bgExecuter;
333    
334          /**          /**
335           * The Renderer for the LocalLayers uses this Image. When set to null,           * The {@link #localRenderer} for the {@link #localContext} uses this
336           * please dispose this {@link Graphics2D}           * {@link Image}.
337           */           */
338          private BufferedImage localImage;          private BufferedImage localImage;
339    
         private BufferedImage finalImage;  
340          /**          /**
341           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background           * The {@link #bgRenderer} for the {@link #bgContext} uses this
342           * uses this Image. When set to null, please dispose the {@link Graphics2D}           * {@link Image}.
343           */           */
344          private BufferedImage bgImage;          private BufferedImage bgImage;
345    
346          /**          /**
347             * This {@link Image} is a merge of the {@link #bgImage},
348             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
349             * updated with {@link #updateFinalImage()} and used for painting in
350             * {@link #paintComponent(Graphics)}
351             */
352            private BufferedImage finalImage;
353    
354            /**
355           * Optionally a transparent image to paint over the map in the lower right           * Optionally a transparent image to paint over the map in the lower right
356           * corner.           * corner.
357           *           *
# Line 331  public class XMapPane extends JPanel { Line 368  public class XMapPane extends JPanel {
368    
369                  @Override                  @Override
370                  public void layerChanged(final MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
371                          requestStartRendering();                          requestStartRendering();
372                  }                  }
373    
374                  @Override                  @Override
375                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
376                          requestStartRendering();                          requestStartRendering();
377                  }                  }
378    
379                  @Override                  @Override
380                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
381                          requestStartRendering();                          requestStartRendering();
382                  }                  }
383          };          };
# Line 384  public class XMapPane extends JPanel { Line 414  public class XMapPane extends JPanel {
414                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
415                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
416    
417                          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();  
418                          requestStartRendering();                          requestStartRendering();
419    
420                  }                  }
421    
422                  @Override                  @Override
423                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
424                          // mapImageInvalid = true;                          // getLocalRenderer().setContext(getMapContext()); geht doch auch
425                          // repaint();                          // ohne?!?!? wow...
                         localRenderer.setContext(getContext());  
426                          requestStartRendering();                          requestStartRendering();
427                  }                  }
428    
429                  @Override                  @Override
430                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
431                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
432                          requestStartRendering();                          requestStartRendering();
433                  }                  }
434    
# Line 422  public class XMapPane extends JPanel { Line 436  public class XMapPane extends JPanel {
436                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
437                          if (event.getLayer() != null)                          if (event.getLayer() != null)
438                                  event.getLayer().removeMapLayerListener(localMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
439                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
440                          requestStartRendering();                          requestStartRendering();
441                  }                  }
442          };          };
443    
         private final RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
444          /**          /**
445           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
446           * triggers repaints.           * triggers repaints. We don't have to listen layerChanged, because that is
447             * already done in {@link #localContextListener}
448           */           */
449          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
450    
451                  @Override                  // @Override
452                  public void layerChanged(final MapLayerEvent event) {                  // public void layerChanged(final MapLayerEvent event) {
453                          localRenderer.setContext(getContext()); // betters for SLD changes?!                  // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
454                          // Change of SLD for example                  // // // changes?!
455                          // mapImageInvalid = true;                  // // requestStartRendering();
456                          // repaint();                  // }
                         requestStartRendering();  
                 }  
457    
458                  @Override                  @Override
459                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
460                          requestStartRendering();                          requestStartRendering();
461                  }                  }
462    
463                  @Override                  @Override
464                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
465                          requestStartRendering();                          requestStartRendering();
466                  }                  }
467          };          };
468    
469          private final GTRenderer localRenderer = GTUtil.createGTRenderer();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
470    
471          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
472    
# Line 482  public class XMapPane extends JPanel { Line 487  public class XMapPane extends JPanel {
487          /**          /**
488           * 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.
489           */           */
490          private Color mapBackgroundColor = Color.WHITE;          private Color mapBackgroundColor = null;
491    
492          /**          /**
493           * 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 531  public class XMapPane extends JPanel {
531           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
532           * images are not big enough any more           * images are not big enough any more
533           **/           **/
534          protected boolean paneResized = false;          protected boolean paneResized = true;
535    
536          private BufferedImage preFinalImage;          private BufferedImage preFinalImage;
537    
538          // if null, no quick preview will be shown          // ** if 0, no quick preview will be shown **/
539          private int quickPreviewHint = 0;          // private int quickPreviewHint = 0;
540    
541          private Map<Object, Object> rendererHints = GTUtil          private Map<Object, Object> rendererHints = GTUtil
542                          .getDefaultGTRendererHints(localRenderer);                          .getDefaultGTRendererHints(getLocalRenderer());
543    
544            /**
545             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
546             * start rendering {@link Thread}s
547             **/
548          private volatile Boolean requestStartRendering = false;          private volatile Boolean requestStartRendering = false;
549    
         private final Timer resizeTimer;  
   
550          /**          /**
551           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
552           * (lat/lon)           * (lat/lon)
# Line 555  public class XMapPane extends JPanel { Line 562  public class XMapPane extends JPanel {
562    
563          /**          /**
564           * The default state is ZOOM_IN, hence by default the           * The default state is ZOOM_IN, hence by default the
565           * {@link #zoomMapPaneMouseListener} is also enabled.           * {@link #xMapPaneMouseListener} is also enabled.
566           **/           **/
567          private int state = ZOOM_IN;          private int state = ZOOM_IN;
568    
# Line 567  public class XMapPane extends JPanel { Line 574  public class XMapPane extends JPanel {
574    
575          private AffineTransform worldToScreen;          private AffineTransform worldToScreen;
576    
577    //      /**
578    //       * This {@link MouseListener} is managing all zoom related tasks
579    //       */
580    //      private final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(
581    //                      this);
582            
583          /**          /**
584           * This {@link MouseListener} is managing all zoom related tasks           * This {@link MouseListener} is managing all zoom related tasks
585           */           */
586          public final ZoomXMapPaneMouseListener zoomMapPaneMouseListener = new ZoomXMapPaneMouseListener(          private final XMapPaneMouseListener xMapPaneMouseListener = new XMapPaneMouseListener(this);
587                          this);          
588    
589          /** Is set if a renderer has an error **/          /** Is set if a renderer has an error **/
590          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
591    
592          // TODO doku          /**
593             * If <code>true</code>, then rendering exceptions are rendererd into the
594             * map pane
595             **/
596            private boolean showExceptions = false;
597    
598          public XMapPane() {          public XMapPane() {
599                  this(null, null);                  this(null, null);
600          }          }
# Line 585  public class XMapPane extends JPanel { Line 603  public class XMapPane extends JPanel {
603           * full constructor extending JPanel           * full constructor extending JPanel
604           *           *
605           * @param rendererHints           * @param rendererHints
606             *            may be <code>null</code>. Otherwise a {@link Map<Object,
607             *            Object>} of {@link RenderingHints} to override the default
608             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
609           *           *
          * @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  
610           * @param localContext           * @param localContext
611           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
612             *            empty {@link DefaultMapContext} will be created.
613           */           */
614          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
615                          final Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
# Line 609  public class XMapPane extends JPanel { Line 625  public class XMapPane extends JPanel {
625                  /**                  /**
626                   * Adding the #zoomMapPaneMouseListener                   * Adding the #zoomMapPaneMouseListener
627                   */                   */
628                  this.addMouseListener(zoomMapPaneMouseListener);                  this.addMouseListener(xMapPaneMouseListener);
629                  this.addMouseMotionListener(zoomMapPaneMouseListener);                  this.addMouseMotionListener(xMapPaneMouseListener);
630                  this.addMouseWheelListener(zoomMapPaneMouseListener);                  this.addMouseWheelListener(xMapPaneMouseListener);
631                    xMapPaneMouseListener.actions.put(MouseInputType.RClick, XMapPaneAction.ZOOM_IN);
632                    xMapPaneMouseListener.actions.put(MouseInputType.RDrag, XMapPaneAction.ZOOM_IN);
633                    
634                    xMapPaneMouseListener.actions.put(MouseInputType.LClick, XMapPaneAction.ZOOM_OUT);
635                    xMapPaneMouseListener.actions.put(MouseInputType.LDrag, XMapPaneAction.ZOOM_OUT);
636                    
637    
638                  /*                  /*
639                   * 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 642  public class XMapPane extends JPanel {
642                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
643                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
644                   */                   */
645                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY, new ActionListener() {                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
646                                    new ActionListener() {
                         public void actionPerformed(final ActionEvent e) {  
                                 paneResized = true;  
647    
648                                  if (!isWellDefined())                                          public void actionPerformed(final ActionEvent e) {
649                                          return;                                                  if (!isWellDefined())
650                                                            return;
651    
652                                  final Rectangle bounds = getVisibleRect();                                                  // LOGGER.debug("resizeTimer performed");
653    
654                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,                                                  // final Rectangle bounds = getVisibleRect();
655                                                  bounds.y, bounds.x + bounds.width, bounds.y                                                  //
656                                                                  + bounds.height);                                                  // System.out.println("\n\ntimer performs with bounds = "
657                                                    // + bounds);
658    
659                                                    // final Envelope geoMapArea = tranformWindowToGeo(
660                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
661                                                    // bounds.y + bounds.height);
662    
663                                                    paneResized = true;
664                                                    if (!setMapArea(getMapArea())) {
665                                                            // It's important to request new rendering here.
666                                                            // setMapArea only returns true and only calls
667                                                            // requestStartRendering if the maparea has changed.
668                                                            // But if the component is resized, the maparea
669                                                            // doesn't have to change.
670                                                            requestStartRendering();
671                                                    }
672    
673                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          }
674                          }                                  });
                 });  
675                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
676    
677                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
678    
679                            private Rectangle oldVisibleRect;
680    
681                          @Override                          @Override
682                          public void componentResized(final ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
683                                  if (bgExecuter != null)  
684                                          bgExecuter.cancelTask();                                  // Seems to be called twice with the same size..
685                                  if (localExecuter != null)                                  if (oldVisibleRect != null
686                                          localExecuter.cancelTask();                                                  && oldVisibleRect.equals(getVisibleRect())) {
687                                            // LOGGER.debug("skipping resize.");
688                                            return;
689                                    }
690    
691                                    // LOGGER.debug("resized: " + getVisibleRect());
692                                  resizeTimer.restart();                                  resizeTimer.restart();
693                                    oldVisibleRect = getVisibleRect();
694                          }                          }
695    
696                  });                  });
# Line 654  public class XMapPane extends JPanel { Line 698  public class XMapPane extends JPanel {
698                  /*                  /*
699                   * Setting up the repaintTimer. Not started automatically.                   * Setting up the repaintTimer. Not started automatically.
700                   */                   */
701                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
702                                  new ActionListener() {  
703                            @Override
704                            public void actionPerformed(final ActionEvent e) {
705                                    if ((!localExecuter.isRunning())
706                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
707                                            repaintTimer.stop();
708                                    } else {
709                                            updateFinalImage();
710                                            XMapPane.this.repaint(100);
711    
712                                    }
713                            }
714                    });
715    
                                         @Override  
                                         public void actionPerformed(final ActionEvent e) {  
                                                 updateFinalImage();  
                                                 XMapPane.this.repaint();  
                                         }  
                                 });  
716                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
717                  repaintTimer.setRepeats(true);                  repaintTimer.setRepeats(true);
718    
# Line 680  public class XMapPane extends JPanel { Line 730  public class XMapPane extends JPanel {
730                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
731                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
732                                                  } else {                                                  } else {
733                                                            // Stupidly, but we have to recheck the
734                                                            setMapArea(getMapArea());
735                                                          requestStartRendering = false;                                                          requestStartRendering = false;
736                                                          startRendering();                                                          startRendering();
737                                                  }                                                  }
# Line 712  public class XMapPane extends JPanel { Line 764  public class XMapPane extends JPanel {
764           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
765           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
766           */           */
767          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
768                  // return env;  
769                  if (getWidth() == 0)                  if (getWidth() == 0)
770                          return env;                          return env;
771    
772                  if (env == null)                  if (env == null)
773                          return null;                          return null;
774    
# Line 765  public class XMapPane extends JPanel { Line 818  public class XMapPane extends JPanel {
818                  }                  }
819    
820                  final Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
821    
822                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
823                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
824                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
# Line 794  public class XMapPane extends JPanel { Line 848  public class XMapPane extends JPanel {
848    
849                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
850    
851                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
852                                                          false);                                                          new ReferencedEnvelope(newArea, env
853                                                                            .getCoordinateReferenceSystem()), false);
854                                  }                                  }
855                          }                          }
856    
# Line 818  public class XMapPane extends JPanel { Line 873  public class XMapPane extends JPanel {
873    
874                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
875    
876                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
877                                                          false);                                                          new ReferencedEnvelope(newArea, env
878                                                                            .getCoordinateReferenceSystem()), false);
879                                  }                                  }
880                          }                          }
881    
# Line 844  public class XMapPane extends JPanel { Line 900  public class XMapPane extends JPanel {
900    
901                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
902    
903                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
904                                                          false);                                                          new ReferencedEnvelope(newArea, env
905                                                                            .getCoordinateReferenceSystem()), false);
906                                  }                                  }
907                          }                          }
908    
# Line 870  public class XMapPane extends JPanel { Line 927  public class XMapPane extends JPanel {
927    
928                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
929    
930                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
931                                                          false);                                                          new ReferencedEnvelope(newArea, env
932                                                                            .getCoordinateReferenceSystem()), false);
933                                  }                                  }
934                          }                          }
935                  }                  }
936    
937                  return newArea;                  return new ReferencedEnvelope(newArea, env
938                                    .getCoordinateReferenceSystem());
939          }          }
940    
941          /**          /**
# Line 904  public class XMapPane extends JPanel { Line 963  public class XMapPane extends JPanel {
963                          bgExecuter.dispose();                          bgExecuter.dispose();
964                  }                  }
965    
966                  if (localExecuter != null) {                  if (localExecuter.isRunning()) {
967                          int i = 0;                          int i = 0;
968                          localExecuter.cancelTask();                          localExecuter.cancelTask();
969                          while (i++ < 10 && localExecuter.isRunning()) {                          while (i++ < 10 && localExecuter.isRunning()) {
970                                  try {                                  try {
971                                          Thread.sleep(100);                                          Thread.sleep(200);
972                                  } catch (final InterruptedException e) {                                  } catch (final InterruptedException e) {
973                                          // TODO Auto-generated catch block                                          LOGGER
974                                          e.printStackTrace();                                                          .warn(
975                                                                            "while XMapPane we are waiting for the localExcutor to stop",
976                                                                            e);
977                                  }                                  }
978                          }                          }
979                          if (localExecuter.isRunning()) {                          if (localExecuter.isRunning()) {
980                                  System.out                                  LOGGER
981                                                  .println("BAD BAD BAD... still running the thread....");                                                  .warn("localExecutor Thread still running after 2s! Continuing anyways...");
982                          }                          }
983                          localExecuter.dispose();                          localExecuter.dispose();
984                  }                  }
985    
986                  disposeImages();                  disposeImages();
987    
988                  // LangUtil.gcTotal();                  // Remove all mapPaneListeners that have registered with us
   
                 // Alle mapPaneListener entfernen  
989                  mapPaneListeners.clear();                  mapPaneListeners.clear();
990    
991                  removeMouseMotionListener(zoomMapPaneMouseListener);                  removeMouseMotionListener(xMapPaneMouseListener);
992                  removeMouseListener(zoomMapPaneMouseListener);                  removeMouseListener(xMapPaneMouseListener);
993    
994                  if (localContext != null)                  if (localContext != null)
995                          getContext().clearLayerList();                          getMapContext().clearLayerList();
996                  if (bgContext != null)                  if (bgContext != null)
997                          getBgContext().clearLayerList();                          getBgContext().clearLayerList();
998    
999                  removeAll();                  removeAll();
1000          }          }
1001            
1002          /**          /**
1003           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the           * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1004           * given point. All in screen coordinates.           * given point. All in screen coordinates.
1005           */           */
1006          protected void drawRectangle(final Graphics graphics, final Point startPos,          protected void drawRectangle(final Graphics graphics, final Point startPos,
1007                          final Point e) {                          final Point e) {
1008                    drawRectangle(graphics, startPos, e, Color.WHITE);
1009            }
1010    
1011            /**
1012             * Draws a rectangle in XOR mode from the origin at {@link #startPos} to the
1013             * given point. All in screen coordinates.
1014             */
1015            protected void drawRectangle(final Graphics graphics, final Point startPos,
1016                            final Point e, Color color) {
1017    
1018                  if (!isWellDefined())                  if (!isWellDefined())
1019                          return;                          return;
# Line 961  public class XMapPane extends JPanel { Line 1029  public class XMapPane extends JPanel {
1029                  if (width == 0 && height == 0)                  if (width == 0 && height == 0)
1030                          return;                          return;
1031    
1032                  graphics.setXORMode(Color.WHITE);                  graphics.setXORMode(color);
1033                  graphics.drawRect(left, bottom, width, height);                  graphics.drawRect(left, bottom, width, height);
1034          }          }
1035    
# Line 973  public class XMapPane extends JPanel { Line 1041  public class XMapPane extends JPanel {
1041           *           *
1042           * @param g           * @param g
1043           *            Graphics2D to paint the preview into           *            Graphics2D to paint the preview into
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
1044           */           */
1045          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1046    
1047  //              if (1 == 1)return false;                  // if (1 == 1)return false;
1048                                    // if (quickPreviewHint == 0)
1049                  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);  
1050    
1051                  if (oldMapArea == null)                  if (oldMapArea == null)
1052                          return false;                          return false;
1053    
1054                    if (getPreFinalImage() == null)
1055                            return false;
1056    
1057                  final Rectangle visibleArea = getVisibleRect();                  final Rectangle visibleArea = getVisibleRect();
1058    
1059                  // Calculate the oldMapArea in the current WindowCoordinates:                  // Calculate the oldMapArea in the current WindowCoordinates:
# Line 1006  public class XMapPane extends JPanel { Line 1066  public class XMapPane extends JPanel {
1066                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1067                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1068    
1069                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1070                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1071                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1072                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1073                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1074                                    RenderingHints.VALUE_RENDER_SPEED);
1075    
1076                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1077                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1078                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
# Line 1014  public class XMapPane extends JPanel { Line 1081  public class XMapPane extends JPanel {
1081                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1082                                  - yy1);                                  - yy1);
1083    
1084                  SwingUtil.clearAround(graphics, painedArea, visibleArea);                  SwingUtil.clearAround(graphics, painedArea, visibleArea,
1085                                    getMapBackgroundColor());
1086    
1087                  addGadgets(graphics, true);                  addGadgets(graphics, true);
1088    
1089                  quickPreviewHint = 0;                  // quickPreviewHint = 0;
1090    
1091                  repaintTimer.restart();                  repaintTimer.restart();
1092    
                 graphics.dispose();  
   
1093                  // Something has been drawn                  // Something has been drawn
1094                  return true;                  return true;
1095          }          }
# Line 1036  public class XMapPane extends JPanel { Line 1102  public class XMapPane extends JPanel {
1102           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1103           */           */
1104          private Image getBgImage() {          private Image getBgImage() {
1105                  //                  if (bgImage == null) {
1106                  // if (bgImage == null) {                          bgImage = new BufferedImage(getVisibleRect().width,
1107                  // bgImage = createImage(getBounds().width, getBounds().height);                                          getVisibleRect().height, IMAGETYPE);
1108                  // }                          SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1109                    }
1110    
1111                  return bgImage;                  return bgImage;
1112          }          }
1113    
1114          public MapContext getContext() {          public MapContext getMapContext() {
1115                  if (localContext == null) {                  if (localContext == null) {
1116                          setLocalContext(new DefaultMapContext());                          setLocalContext(new DefaultMapContext());
1117                  }                  }
# Line 1057  public class XMapPane extends JPanel { Line 1124  public class XMapPane extends JPanel {
1124                          // Rectangle curPaintArea = getVisibleRect();                          // Rectangle curPaintArea = getVisibleRect();
1125                          finalImage = new BufferedImage(getVisibleRect().width,                          finalImage = new BufferedImage(getVisibleRect().width,
1126                                          getVisibleRect().height, IMAGETYPE);                                          getVisibleRect().height, IMAGETYPE);
1127                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1128    
1129                          requestStartRendering();                          // requestStartRendering();
1130                  }                  }
1131                  return finalImage;                  return finalImage;
1132          }          }
1133    
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1134          /**          /**
1135           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1136           */           */
# Line 1075  public class XMapPane extends JPanel { Line 1139  public class XMapPane extends JPanel {
1139                  if (localImage == null) {                  if (localImage == null) {
1140                          localImage = new BufferedImage(getVisibleRect().width,                          localImage = new BufferedImage(getVisibleRect().width,
1141                                          getVisibleRect().height, IMAGETYPE_withAlpha);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1142                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1143                  }                  }
1144    
1145                  return localImage;                  return localImage;
# Line 1090  public class XMapPane extends JPanel { Line 1155  public class XMapPane extends JPanel {
1155                          ReferencedEnvelope mapArea_ = null;                          ReferencedEnvelope mapArea_ = null;
1156                          try {                          try {
1157                                  mapArea_ = localContext.getLayerBounds();                                  mapArea_ = localContext.getLayerBounds();
1158                          } catch (final IOException e) {                          } catch (final Exception e) {
1159                                  LOGGER.warn("context.getLayerBounds()", e);                                  LOGGER.warn("localContext.getLayerBounds()", e);
1160                            }
1161    
1162                            if (mapArea_ == null && bgContext != null) {
1163                                    try {
1164                                            mapArea_ = bgContext.getLayerBounds();
1165                                    } catch (final IOException e) {
1166                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1167                                    }
1168                          }                          }
1169    
1170                          if (mapArea_ != null) {                          if (mapArea_ != null) {
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 // setMapArea(mapArea_); // results in a loop  
1171                                  mapArea = bestAllowedMapArea(mapArea_);                                  mapArea = bestAllowedMapArea(mapArea_);
1172                                    requestStartRendering();
1173                          }                          }
1174                  }                  }
1175    
# Line 1109  public class XMapPane extends JPanel { Line 1181  public class XMapPane extends JPanel {
1181                          try {                          try {
1182                                  localContext.setCoordinateReferenceSystem(GeoImportUtil                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1183                                                  .getDefaultCRS());                                                  .getDefaultCRS());
1184                          } catch (Exception e) {                          } catch (final Exception e) {
1185                                  throw new RuntimeException("setting context CRS:", e);                                  throw new RuntimeException("setting context CRS:", e);
1186                          }                          }
1187    
# Line 1118  public class XMapPane extends JPanel { Line 1190  public class XMapPane extends JPanel {
1190          }          }
1191    
1192          /**          /**
1193           * 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
1194             * methods looks for a parent component and will use its background color.
1195             * If no parent component is available, WHITE is returned.
1196           **/           **/
1197          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1198                    if (mapBackgroundColor == null) {
1199                            if (getParent() != null)
1200                                    return getParent().getBackground();
1201                            else
1202                                    return Color.WHITE;
1203                    }
1204                  return mapBackgroundColor;                  return mapBackgroundColor;
1205          }          }
1206    
# Line 1147  public class XMapPane extends JPanel { Line 1227  public class XMapPane extends JPanel {
1227    
1228          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1229                  if (maxExtend == null) {                  if (maxExtend == null) {
1230    
1231                            // The next command may take long time!
1232                            // long start = System.currentTimeMillis();
1233                          final ReferencedEnvelope layerBounds = GTUtil                          final ReferencedEnvelope layerBounds = GTUtil
1234                                          .getVisibleLayoutBounds(localContext);                                          .getVisibleLayoutBounds(localContext);
1235                            //                      
1236                            // LOGGER.info(
1237                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1238                            //                      
1239                          if (layerBounds == null) {                          if (layerBounds == null) {
1240                                  // TODO Last fallback could be the CRS valid area                                  // // TODO Last fallback could be the CRS valid area
1241                                  return null;                                  return null;
1242                          }                          }
1243    
1244                          // Kartenbereich um 10% vergroessern                          // Vergrößerung um 10% nochmal rausgenommen
1245                          return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil                          // // // Kartenbereich um 10% vergroessern
1246                                          .expandEnvelope(layerBounds, 0.1), true);                          // return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil
1247                            // .expandEnvelope(layerBounds, 0.1), true);
1248    
1249                            return JTSUtil.fixAspectRatio(getVisibleRect(), layerBounds, true);
1250                  }                  }
1251                  return maxExtend;                  return maxExtend;
1252          }          }
# Line 1184  public class XMapPane extends JPanel { Line 1274  public class XMapPane extends JPanel {
1274          }          }
1275    
1276          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();  
                 // }  
1277                  return preFinalImage;                  return preFinalImage;
1278          }          }
1279    
# Line 1270  public class XMapPane extends JPanel { Line 1350  public class XMapPane extends JPanel {
1350           * {@link XMapPane} is visible and has bounds set.           * {@link XMapPane} is visible and has bounds set.
1351           */           */
1352          public boolean isWellDefined() {          public boolean isWellDefined() {
   
1353                  try {                  try {
1354                            if (getMapContext() == null)
                         if (getContext() == null)  
1355                                  return false;                                  return false;
1356                          if (getContext().getLayerCount() <= 0)                          if (getMapContext().getLayerCount() <= 0)
1357                                  return false;                                  return false;
1358                          if (getMapArea() == null)                          if (getVisibleRect().getWidth() == 0)
1359                                  return false;                                  return false;
1360                          if (getBounds().getWidth() == 0)                          if (getVisibleRect().getHeight() == 0)
                                 return false;  
                         if (getBounds().getHeight() == 0)  
1361                                  return false;                                  return false;
1362                            // if (getMapArea() == null)
1363                            // return false;
1364                  } catch (final Exception e) {                  } catch (final Exception e) {
1365                          return false;                          return false;
1366                  }                  }
1367                  return true;                  return true;
1368          }          }
1369    
1370            /**
1371             * Called from the listeners while the mouse is dragging, this method either
1372             * paints a translated (moved/panned) version of the image, or a rectangle.
1373             *
1374             * @param startPos
1375             *            in screen coordinates
1376             * @param lastPos
1377             *            in screen coordinates
1378             * @param event
1379             *            the {@link MouseEvent} to read the mouse buttons from
1380             */
1381          public void mouseDragged(final Point startPos, final Point lastPos,          public void mouseDragged(final Point startPos, final Point lastPos,
1382                          final MouseEvent event) {                          final MouseEvent event) {
1383    
1384                  if ((getState() == XMapPane.PAN)                  if ((getState() == XMapPane.PAN)
1385                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
1386    
1387                            // Panning needs a panning coursor
1388                          if (getCursor() != SwingUtil.PANNING_CURSOR) {                          if (getCursor() != SwingUtil.PANNING_CURSOR) {
1389                                  setCursor(SwingUtil.PANNING_CURSOR);                                  setCursor(SwingUtil.PANNING_CURSOR);
1390    
1391                                  // While panning, we deactivate the rendering. So the tasts are                                  // While panning, we deactivate the rendering. So the tasks are
1392                                  // ready to start when the panning os done.                                  // ready to start when the panning is finished.
1393                                  if (bgExecuter != null)                                  if (bgExecuter != null && bgExecuter.isRunning())
1394                                          bgExecuter.cancelTask();                                          bgExecuter.cancelTask();
1395                                  if (localExecuter != null)                                  if (localExecuter.isRunning())
1396                                          localExecuter.cancelTask();                                          localExecuter.cancelTask();
1397                          }                          }
1398    
# Line 1349  public class XMapPane extends JPanel { Line 1439  public class XMapPane extends JPanel {
1439                  } else if ((getState() == XMapPane.ZOOM_IN)                  } else if ((getState() == XMapPane.ZOOM_IN)
1440                                  || (getState() == XMapPane.ZOOM_OUT)                                  || (getState() == XMapPane.ZOOM_OUT)
1441                                  || (getState() == XMapPane.SELECT_ALL)                                  || (getState() == XMapPane.SELECT_ALL)
1442                                  || (getState() == XMapPane.SELECT_TOP)                                  || (getState() == XMapPane.SELECT_TOP)) {
                 // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)  
                 ) {  
                         final Graphics graphics = getGraphics();  
1443    
1444                            // Draws a rectangle
1445                            final Graphics2D graphics = (Graphics2D) getGraphics();
1446                          drawRectangle(graphics, startPos, event.getPoint());                          drawRectangle(graphics, startPos, event.getPoint());
1447                            if ((lastPos.x > 0) && (lastPos.y > 0))
                         if ((lastPos.x > 0) && (lastPos.y > 0)) {  
1448                                  drawRectangle(graphics, startPos, lastPos);                                  drawRectangle(graphics, startPos, lastPos);
                         }  
   
1449                          graphics.dispose();                          graphics.dispose();
   
1450                  }                  }
   
1451          }          }
1452    
1453          /**          /**
1454           * Called by the {@link RenderingExecutor} when rendering was cancelled.           * Called by the {@link RenderingExecutor} when rendering was cancelled.
1455           */           */
1456          public void onRenderingCancelled() {          public void onRenderingCancelled() {
1457                    // LOGGER.debug("Rendering cancelled");
1458                  repaintTimer.stop();                  repaintTimer.stop();
                 LOGGER.debug("Rendering cancelled");  
1459          }          }
1460    
1461          /**          /**
1462           * Called by the {@link RenderingExecutor} when rendering has been           * Called by the {@link RenderingExecutor} when rendering has been
1463           * completed.           * completed.
1464             *
1465             * @param l
1466             *            long ms the rendering took
1467           */           */
1468          public void onRenderingCompleted() {          public void onRenderingCompleted(final long l) {
1469                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1470                    // LOGGER
1471                    // .debug("complete rendering after " + lastRenderingDuration
1472                    // + "ms");
1473    
1474                  repaintTimer.stop();                  repaintTimer.stop();
1475                  updateFinalImage();  
1476                  repaint();                  // We "forget" about an exception every time we complete a rendering
1477                    // thread successfully
1478                  if (renderingErrors.size() > 0)                  if (renderingErrors.size() > 0)
1479                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1480    
1481                    updateFinalImage();
1482                    repaint();
1483          }          }
1484    
1485          /**          /**
# Line 1397  public class XMapPane extends JPanel { Line 1493  public class XMapPane extends JPanel {
1493           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1494           */           */
1495          public void onRenderingFailed(final Exception renderingError) {          public void onRenderingFailed(final Exception renderingError) {
1496                  this.renderingErrors.add(renderingError);  
1497                    // Store the exceptions so we can show it to the user:
1498                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1499                                    .getMessage().equals(
1500                                                    "Argument \"sourceCRS\" should not be null.")))
1501                            this.renderingErrors.add(renderingError);
1502                  if (renderingErrors.size() > 3)                  if (renderingErrors.size() > 3)
1503                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1504    
1505                  repaintTimer.stop();                  repaintTimer.stop();
1506    
1507                  LOGGER.warn("Rendering failed", renderingError);                  LOGGER.warn("Rendering failed", renderingError);
1508                  updateFinalImage();                  updateFinalImage();
1509                  repaint();                  repaint();
1510    
1511          }          }
1512    
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
         }  
   
1513          @Override          @Override
1514          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
                 if (!acceptsRepaintCalls)  
                         return;  
1515    
1516                  // Maybe update the cursor and maybe stop the repainting timer                  // Maybe update the cursor and maybe stop the repainting timer
1517                  updateCursor();                  updateCursor();
1518    
1519                    if (!acceptsRepaintCalls)
1520                            return;
1521    
1522                    if (!isWellDefined())
1523                            return;
1524                    //
1525                    // if (paneResized) {
1526                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1527                    // // g.clearRect(0, 0, getVisibleRect().width,
1528                    // getVisibleRect().height);
1529                    // return;
1530                    // }
1531    
1532                  // super.paintComponent(g); // candidate for removal                  // super.paintComponent(g); // candidate for removal
1533    
1534                  boolean paintedSomething = false;                  boolean paintedSomething = false;
# Line 1432  public class XMapPane extends JPanel { Line 1540  public class XMapPane extends JPanel {
1540                          // If the new mapArea and the oldMapArea intersect, we can draw some                          // If the new mapArea and the oldMapArea intersect, we can draw some
1541                          // quick scaled preview to make the user feel that something is                          // quick scaled preview to make the user feel that something is
1542                          // happening.                          // happening.
1543                          if (mapAreaChanged && oldMapArea != null                          if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1544                                            && oldMapArea != null
1545                                          && getMapArea().intersects(oldMapArea)                                          && getMapArea().intersects(oldMapArea)
1546                                          & !getMapArea().equals(oldMapArea)) {                                          && !getMapArea().equals(oldMapArea) && !paneResized) {
1547    
1548                                  mapAreaChanged = false;                                  mapAreaChanged = false;
1549    
1550                                  if (getMapArea().covers(oldMapArea)) {                                  // if (getMapArea().covers(oldMapArea)) {
1551                                          setQuickPreviewHint(ZOOM_OUT);                                  // // quickPreviewHint = ZOOM_OUT;
1552                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1553                                  } else if (oldMapArea.covers(getMapArea())) {                                  // g);
1554                                          setQuickPreviewHint(ZOOM_IN);                                  // } else if (oldMapArea.covers(getMapArea())) {
1555                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // quickPreviewHint = ZOOM_IN;
1556                                  }                                  paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1557                                    // }
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 disposeImages();  
1558                          }                          }
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
1559                  }                  }
1560    
1561                  if (!paintedSomething) {                  if (!paintedSomething) {
1562    
1563                          g.drawImage(getFinalImage(), 0, 0, null);                          g.drawImage(getFinalImage(), 0, 0, null);
1564    
                         g.dispose(); // cand. for removal  
   
1565                          paintedSomething = true; // cand. for removal                          paintedSomething = true; // cand. for removal
1566                  }                  }
1567    
# Line 1519  public class XMapPane extends JPanel { Line 1617  public class XMapPane extends JPanel {
1617           */           */
1618          public void performPan() {          public void performPan() {
1619    
1620                  Rectangle winBounds = getVisibleRect();                  final Rectangle winBounds = getVisibleRect();
1621                    
1622                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1623                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1624                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y
# Line 1543  public class XMapPane extends JPanel { Line 1641  public class XMapPane extends JPanel {
1641                          setCursor(SwingUtil.PAN_CURSOR);                          setCursor(SwingUtil.PAN_CURSOR);
1642          }          }
1643    
         //  
         // /**  
         // * Nuetzlich wenn die Componente gedruckt (z.B. wenn ein Screenshot  
         // gemacht  
         // * wird) wird. Dann werden wird der Hintergrund auf WEISS gesetzt.  
         // *  
         // * @author <a href="mailto:[email protected]">Stefan Alfons  
         // * Kr&uuml;ger</a>  
         // */  
         // @Override  
         // public void print(final Graphics g) {  
         // final Color orig = getBackground();  
         // setBackground(Color.WHITE);  
         //  
         // // wrap in try/finally so that we always restore the state  
         // try {  
         // super.print(g);  
         // } finally {  
         // setBackground(orig);  
         // }  
         // }  
   
1644          /**          /**
1645           * Entfernt einen Listener von der Map.           * Entfernt einen Listener von der Map.
1646           *           *
# Line 1583  public class XMapPane extends JPanel { Line 1659  public class XMapPane extends JPanel {
1659          private void requestStartRendering() {          private void requestStartRendering() {
1660                  if (bgExecuter != null)                  if (bgExecuter != null)
1661                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
1662                  if (localExecuter != null)  
1663                          localExecuter.cancelTask();                  localExecuter.cancelTask();
1664    
1665                    mapImageInvalid = true;
1666                    if (paneResized) {
1667                            paneResized = false;
1668                            disposeImages();
1669                    }
1670                  requestStartRendering = true;                  requestStartRendering = true;
1671    
1672          }          }
1673    
         //  
         // /**  
         // * 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);  
         // }  
         // }  
   
1674          /**          /**
1675           * Calculate the affine transforms used to convert between world and pixel           * Calculate the affine transforms used to convert between world and pixel
1676           * 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 1685  public class XMapPane extends JPanel {
1685           *            the current map pane extent (screen units)           *            the current map pane extent (screen units)
1686           */           */
1687          private void resetTransforms() {          private void resetTransforms() {
1688                  ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,                  // System.out
1689                                  getContext().getCoordinateReferenceSystem());                  // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1690                    if (!isWellDefined())
1691                            return;
1692    
1693                  Rectangle paintArea = getVisibleRect(); // NOT USE GET BOUNDS!                  if (mapArea == null)
1694                            return;
1695                                    
1696                  //                          final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1697                  // double xscale = paintArea.getWidth() / refEnv.getWidth();                                  getMapContext().getCoordinateReferenceSystem());
                 // double yscale = paintArea.getHeight() / refEnv.getHeight();  
                 //  
                 // double scale = Math.min(xscale, yscale);  
                 //  
                 // double xoff = refEnv.getMedian(0) * scale - paintArea.getCenterX();  
                 // double yoff = refEnv.getMedian(1) * scale + paintArea.getCenterY();  
1698    
1699                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1700                                  paintArea);                                  getVisibleRect());
1701    
                 // worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff,  
                 // yoff);  
1702                  try {                  try {
1703                          screenToWorld = worldToScreen.createInverse();                          screenToWorld = worldToScreen.createInverse();
1704    
1705                  } catch (NoninvertibleTransformException ex) {                  } catch (final NoninvertibleTransformException ex) {
1706                          ex.printStackTrace();                          LOGGER
1707                                            .error("can't invert worldToScreen to get screenToWorld!",
1708                                                            ex);
1709                  }                  }
1710          }          }
1711    
# Line 1683  public class XMapPane extends JPanel { Line 1724  public class XMapPane extends JPanel {
1724                  this.bgContext = context;                  this.bgContext = context;
1725    
1726                  if (context != null) {                  if (context != null) {
1727                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1728    
1729                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1730    
# Line 1692  public class XMapPane extends JPanel { Line 1733  public class XMapPane extends JPanel {
1733                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1734                          }                          }
1735                  }                  }
1736                  mapImageInvalid = true;  
1737                  repaint();                  requestStartRendering();
1738          }          }
1739    
1740          public void setJava2dHints(final RenderingHints java2dHints) {          public void setJava2dHints(final RenderingHints java2dHints) {
1741                  this.java2dHints = java2dHints;                  this.java2dHints = java2dHints;
1742          }          }
1743    
         /**  
          *  
          * @param context  
          */  
1744          public void setLocalContext(final MapContext context) {          public void setLocalContext(final MapContext context) {
1745                  // Remove the default listener from the old context                  // Remove the default listener from the old context
1746                  if (this.localContext != null) {                  if (this.localContext != null) {
# Line 1719  public class XMapPane extends JPanel { Line 1756  public class XMapPane extends JPanel {
1756    
1757                  if (context != null) {                  if (context != null) {
1758    
1759                          setMapArea(localContext.getAreaOfInterest());                          // setMapArea(localContext.getAreaOfInterest());
1760    
1761                          localRenderer.setContext(localContext);                          getLocalRenderer().setContext(localContext);
1762    
1763                          this.localContext.addMapLayerListListener(localContextListener);                          this.localContext.addMapLayerListListener(localContextListener);
1764    
# Line 1731  public class XMapPane extends JPanel { Line 1768  public class XMapPane extends JPanel {
1768                          }                          }
1769                  }                  }
1770    
1771                    requestStartRendering();
1772    
1773            }
1774    
1775            public void setBorder(final Border b) {
1776                    super.setBorder(b);
1777            }
1778    
1779            /**
1780             * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1781             */
1782            public void refresh() {
1783                  mapImageInvalid = true;                  mapImageInvalid = true;
1784                  repaint();                  repaint();
1785          }          }
1786    
1787            // /**
1788            // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1789            // * called after {@link Style}s have been changed because GTRenderer is
1790            // * otherwise not working well.
1791            // */
1792            // public void refreshRenderers() {
1793            // localRenderer = GTUtil.createGTRenderer();
1794            // setLocalContext(getMapContext());
1795            // mapImageInvalid = true;
1796            // repaint();
1797            // }
1798    
1799          /**          /**
1800             * Set the new map area.
1801             *
1802           * @param newMapArea           * @param newMapArea
1803           * @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
1804           *         has been triggered.           *         has been triggered.
1805           */           */
1806          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final Envelope newMapArea) {
1807                    if (newMapArea == null)
1808                            return false;
1809                    if (getMapContext().getCoordinateReferenceSystem() == null)
1810                            return false;
1811                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1812                                    .getCoordinateReferenceSystem()));
1813            }
1814    
1815            /**
1816             * Set the new map area.
1817             *
1818             * @param newMapArea
1819             * @return <code>true</code> if the mapArea has been changed and a repaint
1820             *         has been triggered.
1821             */
1822            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1823    
1824                  if (newMapArea == null                  if (newMapArea == null
1825                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1795  public class XMapPane extends JPanel { Line 1874  public class XMapPane extends JPanel {
1874                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1875                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1876                  }                  }
1877                  mapImageInvalid = true;  
1878                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1879    
1880                  LOGGER.debug("New maparea = " + mapArea);                  repaint(200); // Do not remove it!
1881    
1882                    requestStartRendering();
1883    
1884                  return true;                  return true;
1885          }          }
1886    
# Line 1808  public class XMapPane extends JPanel { Line 1889  public class XMapPane extends JPanel {
1889           *           *
1890           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1891           */           */
1892          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(final Color bgColor) {
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
1893                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1894          }          }
1895    
# Line 1868  public class XMapPane extends JPanel { Line 1947  public class XMapPane extends JPanel {
1947          }          }
1948    
1949          // /** Stored the time used for the last real rendering in ms. **/          // /** Stored the time used for the last real rendering in ms. **/
1950          // private long lastRenderingDuration = Long.MAX_VALUE;          private long lastRenderingDuration = 1000;
1951    
1952          /**          /**
1953           * 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 1964  public class XMapPane extends JPanel {
1964          }          }
1965    
1966          /**          /**
1967           *           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1968           * @param b           * requests. Otherwise the map will not paint anything and not start any
1969             * rendering {@link Thread}s.
1970           */           */
1971          public void setPainting(final boolean b) {          public void setPainting(final boolean b) {
1972                  acceptsRepaintCalls = b;                  acceptsRepaintCalls = b;
1973          }                  if (acceptsRepaintCalls == true)
1974                            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;  
   
1975          }          }
1976    
1977          private void setRendererHints(final Map<Object, Object> rendererHints) {          private void setRendererHints(final Map<Object, Object> rendererHints) {
# Line 1918  public class XMapPane extends JPanel { Line 1985  public class XMapPane extends JPanel {
1985           *           *
1986           * @param state           * @param state
1987           */           */
1988            @Deprecated
1989          public void setState(final int state) {          public void setState(final int state) {
1990                  this.state = state;                  this.state = state;
1991                    
1992    //              throw new RuntimeException("Old concept.. migrate to new concept!");
1993    
1994                  zoomMapPaneMouseListener.setEnabled((state == ZOOM_IN  //              xMapPaneMouseListener.setEnabled((state == ZOOM_IN
1995                                  || state == ZOOM_OUT || state == PAN));  //                              || state == ZOOM_OUT || state == PAN));
1996    
1997                  // Je nach Aktion den Cursor umsetzen                  // Je nach Aktion den Cursor umsetzen
1998                  updateCursor();                  updateCursor();
1999          }          }
2000            
2001            public void configureMouse(MouseInputType type, XMapPaneAction action){
2002                    
2003            }
2004    
2005          /**          /**
2006           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,           * Standardmaessig wird der Cursor automatisch je nach MapPane-Aktion (Zoom,
# Line 1949  public class XMapPane extends JPanel { Line 2023  public class XMapPane extends JPanel {
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();
# Line 2140  public class XMapPane extends JPanel { Line 2222  public class XMapPane extends JPanel {
2222                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
2223                                  getMapBackgroundColor(), null);                                  getMapBackgroundColor(), null);
2224    
2225                  final int finalImageHeight = getFinalImage().getHeight(null);                  // When panning, we have to clear the area around the image
                 final int finalImageWidth = getFinalImage().getWidth(null);  
   
2226                  final Rectangle painedArea = new Rectangle(imageOrigin.x,                  final Rectangle painedArea = new Rectangle(imageOrigin.x,
2227                                  imageOrigin.y, finalImageWidth, finalImageHeight);                                  imageOrigin.y, getFinalImage().getWidth(), getFinalImage()
2228                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect());                                                  .getHeight());
2229                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2230                                    getMapBackgroundColor());
2231    
2232                  addGadgets(finalG, false);                  addGadgets(finalG, false);
2233    
# Line 2164  public class XMapPane extends JPanel { Line 2246  public class XMapPane extends JPanel {
2246           *            <code>false</code>, it will only depend on           *            <code>false</code>, it will only depend on
2247           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2248           */           */
2249          private void addGadgets(final Graphics2D graphics, boolean forceWait) {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2250    
2251                  // Paint a logo to the bottom right if available                  // Paint a logo to the bottom right if available
2252                  if (mapImage != null) {                  if (mapImage != null) {
2253                          Rectangle visibleRect = getVisibleRect();                          final Rectangle visibleRect = getVisibleRect();
2254                          graphics.drawImage(mapImage, visibleRect.width                          graphics.drawImage(mapImage, visibleRect.width
2255                                          - mapImage.getWidth() - 10, getVisibleRect().height                                          - mapImage.getWidth() - 10, getVisibleRect().height
2256                                          - mapImage.getHeight() - 10, null);                                          - mapImage.getHeight() - 10, null);
# Line 2178  public class XMapPane extends JPanel { Line 2260  public class XMapPane extends JPanel {
2260    
2261                  // If the rendering process is still running, indicate this is the image                  // If the rendering process is still running, indicate this is the image
2262                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2263                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2264    
2265                          y += 8;                          y += 8;
2266    
# Line 2194  public class XMapPane extends JPanel { Line 2276  public class XMapPane extends JPanel {
2276    
2277                          graphics.setColor(c);                          graphics.setColor(c);
2278    
2279                          y += 24;                          y += 21;
2280                  }                  }
2281    
2282                  if (renderingErrors != null) {                  if (!renderingErrors.isEmpty() && isShowExceptions()) {
2283    
2284                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2285                          graphics.setFont(errorFont);                          graphics.setFont(errorFont);
2286    
2287                          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;  
2288    
2289                                  String errStr = ex.getLocalizedMessage();                                  String errStr = ex.getLocalizedMessage();
2290    
2291                                  graphics.setColor(Color.WHITE);                                  if (errStr == null)
2292                                            errStr = ex.getMessage();
2293                                    if (errStr == null)
2294                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2295    
2296                                    graphics.setColor(getMapBackgroundColor());
2297                                  graphics.drawString(errStr, 5, y);                                  graphics.drawString(errStr, 5, y);
2298                                  graphics.setColor(Color.RED);                                  graphics.setColor(Color.RED);
2299                                  graphics.drawString(errStr, 6, y + 1);                                  graphics.drawString(errStr, 6, y + 1);
# Line 2234  public class XMapPane extends JPanel { Line 2316  public class XMapPane extends JPanel {
2316          public void zoomTo(          public void zoomTo(
2317                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2318    
2319                  final CoordinateReferenceSystem mapCRS = getContext()                  // if (!isWellDefined()) return;
2320    
2321                    final CoordinateReferenceSystem mapCRS = getMapContext()
2322                                  .getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2323                  final CoordinateReferenceSystem fCRS = features.getSchema()                  final CoordinateReferenceSystem fCRS = features.getSchema()
2324                                  .getGeometryDescriptor().getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2325    
2326                  double width = mapArea.getWidth();                  ReferencedEnvelope _mapArea;
2327                  double height = mapArea.getHeight();                  if (mapArea == null)
2328                            _mapArea = features.getBounds();
2329                    else
2330                            _mapArea = getMapArea();
2331                    double width = _mapArea.getWidth();
2332                    double height = _mapArea.getHeight();
2333                  final double ratio = height / width;                  final double ratio = height / width;
2334    
2335                  if (features == null || features.size() == 0) {                  if (features == null || features.size() == 0) {
# Line 2292  public class XMapPane extends JPanel { Line 2381  public class XMapPane extends JPanel {
2381                  } else {                  } else {
2382                          final ReferencedEnvelope fBounds = features.getBounds();                          final ReferencedEnvelope fBounds = features.getBounds();
2383    
2384                          Envelope bounds;                          ReferencedEnvelope bounds;
2385                          if (!mapCRS.equals(fCRS)) {                          if (!mapCRS.equals(fCRS)) {
2386                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2387                          } else {                          } else {
2388                                  bounds = fBounds;                                  bounds = fBounds;
2389                          }                          }
# Line 2325  public class XMapPane extends JPanel { Line 2414  public class XMapPane extends JPanel {
2414           * @param center           * @param center
2415           *            position in window coordinates           *            position in window coordinates
2416           * @param zoomFaktor           * @param zoomFaktor
2417           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.           *            > 1 for zoom out, < 1 for zoom in. Default is .5
2418           */           */
2419          public void zoomTo(Point center, Double zoomFaktor) {          public void zoomTo(Point center, Double zoomFaktor) {
2420                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2421                          zoomFaktor = 2.;                          zoomFaktor = .5;
2422    
2423                  final Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2424                  center = null;                  center = null;
# Line 2349  public class XMapPane extends JPanel { Line 2438  public class XMapPane extends JPanel {
2438                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2439                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2440                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2441                    
2442  // TODO we actually want that                  // // Move the newMapArea above the new center if we zoom in:
2443  //              // Move the newMapArea above the new center                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2444  //              newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                                  .getY()
2445  //                              .getY()                                  - mapArea.centre().y);
 //                              - mapArea.centre().y);  
2446    
2447                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2448          }          }
2449    
2450            /**
2451             * Shall non-fatal rendering exceptions be reported in the mappane or be
2452             * dropped quitely.
2453             */
2454            public void setShowExceptions(final boolean showExceptions) {
2455                    this.showExceptions = showExceptions;
2456            }
2457    
2458            /**
2459             * Shall exceptions be reported in the mappane?
2460             */
2461            public boolean isShowExceptions() {
2462                    return showExceptions;
2463            }
2464    
2465            public GTRenderer getLocalRenderer() {
2466                    return localRenderer;
2467            }
2468    
2469            /**
2470             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2471             * Macht nichts, wenn {@code null} uebergeben wird.
2472             *
2473             * <br>
2474             *
2475             * @param layer
2476             *            ein Layer
2477             */
2478            public void zoomToLayer(MapLayer layer) {
2479                    if (layer == null)
2480                            return;
2481                    try {
2482    
2483                            // BB umrechnen von Layer-CRS in Map-CRS
2484                            final CoordinateReferenceSystem targetCRS = getMapContext()
2485                                            .getCoordinateReferenceSystem();
2486                            final CoordinateReferenceSystem sourceCRS = layer
2487                                            .getFeatureSource().getSchema()
2488                                            .getCoordinateReferenceSystem();
2489    
2490                            Envelope mapAreaNew;
2491                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2492                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2493                                                    .getBounds(), sourceCRS, targetCRS);
2494                            } else {
2495                                    try {
2496                                            mapAreaNew = layer.getFeatureSource().getBounds();
2497                                    } catch (java.lang.IllegalArgumentException e) {
2498                                            LOGGER.error("Can't calc layers bounds...", e);
2499                                            mapAreaNew = null;
2500    
2501                                            /**
2502                                             *
2503                                             23.10.2009 11:20:50
2504                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2505                                             * WARNUNG: only one hole in this polygon record ERROR
2506                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2507                                             * correctly java.lang.IllegalArgumentException: Points of
2508                                             * LinearRing do not form a closed linestring at
2509                                             * com.vividsolutions
2510                                             * .jts.geom.LinearRing.validateConstruction
2511                                             * (LinearRing.java:105) at
2512                                             * com.vividsolutions.jts.geom.LinearRing
2513                                             * .<init>(LinearRing.java:100) at
2514                                             * com.vividsolutions.jts.geom
2515                                             * .GeometryFactory.createLinearRing
2516                                             * (GeometryFactory.java:339) at
2517                                             * org.geotools.data.shapefile.
2518                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2519                                             * org.geotools
2520                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2521                                             * (ShapefileReader.java:106) at
2522                                             * org.geotools.data.shapefile.
2523                                             * ShapefileAttributeReader.next(
2524                                             * ShapefileAttributeReader.java:157) at
2525                                             * org.geotools.data.shapefile
2526                                             * .indexed.IndexedShapefileAttributeReader
2527                                             * .next(IndexedShapefileAttributeReader.java:122) at
2528                                             * org.geotools
2529                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2530                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2531                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2532                                             * MaxFeatureReader.java:61) at
2533                                             * org.geotools.data.MaxFeatureReader
2534                                             * .next(MaxFeatureReader.java:61)
2535                                             **/
2536                                    }
2537                            }
2538    
2539                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2540                            // Punkt-Layer,
2541                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2542                            // sonst
2543                            // genau auf dem Rand der angezeigten Flaeche)
2544    
2545                            if (mapAreaNew != null) {
2546                                    mapAreaNew.expandBy(mapAreaNew.getWidth() * 0.1, mapAreaNew
2547                                                    .getHeight() * 0.1);
2548                                    setMapArea(mapAreaNew);
2549                            } else {
2550                                    LOGGER
2551                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2552                            }
2553                    } catch (Exception err) {
2554                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2555                    }
2556            }
2557    
2558            /**
2559             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2560             *
2561             * <br>
2562             * A refresh of the map is not done automatically
2563             *
2564             * @param index
2565             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2566             *            back to top)
2567             *
2568             * @author <a href="mailto:[email protected]">Stefan Alfons
2569             *         Kr&uuml;ger</a>
2570             */
2571            public void zoomToLayer(int index) {
2572                    final MapContext context = getMapContext();
2573                    if (context != null)
2574                            zoomToLayer(context.getLayer(index));
2575            }
2576    
2577            /**
2578             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2579             * selected layer. The layer is selected by the idx, counting from front to
2580             * back, like humans would expect in a {@link JList}
2581             *
2582             * <br>
2583             * A refresh of the map is not done automatically
2584             *
2585             *
2586             *
2587             * @param index
2588             *            Reverse index of the {@link MapLayer} in the
2589             *            {@link MapContext}
2590             *
2591             * @author <a href="mailto:[email protected]">Stefan Alfons
2592             *         Kr&uuml;ger</a>
2593             */
2594            public void zoomToLayerIdxReverse(int index) {
2595                    zoomToLayer(getMapContext().getLayerCount() - 1 - index);
2596            }
2597    
2598            /**
2599             * Aktiviert oder deaktiviert das AntiAliasing for diese
2600             * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2601             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2602             *
2603             * @author <a href="mailto:[email protected]">Stefan Alfons
2604             *         Kr&uuml;ger</a>
2605             */
2606            public void setAntiAliasing(final boolean aa) {
2607                    // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2608                    RenderingHints java2DHints = java2dHints;
2609                    if (java2DHints == null) {
2610                            java2DHints = GeoTools.getDefaultHints();
2611                    }
2612    
2613                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2614                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2615                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2616                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2617                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2618                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2619                    java2DHints.put(RenderingHints.KEY_RENDERING,
2620                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2621                                                    : RenderingHints.VALUE_RENDER_SPEED);
2622    
2623            }
2624    
2625  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26