/[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-RC1/src/skrueger/geotools/XMapPane.java revision 620 by alfonx, Mon Jan 25 17:46:06 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 96  import com.vividsolutions.jts.geom.Geome Line 99  import com.vividsolutions.jts.geom.Geome
99   */   */
100  public class XMapPane extends JPanel {  public class XMapPane extends JPanel {
101    
102          private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;          // private static final int IMAGETYPE = BufferedImage.TYPE_INT_RGB;
103          private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_INT_ARGB;          // private static final int IMAGETYPE_withAlpha =
104            // BufferedImage.TYPE_INT_ARGB;
105            private static final int IMAGETYPE = BufferedImage.TYPE_3BYTE_BGR;
106            private static final int IMAGETYPE_withAlpha = BufferedImage.TYPE_4BYTE_ABGR;
107    
108          private static Logger LOGGER = Logger.getLogger(XMapPane.class);          private final static Logger LOGGER = Logger.getLogger(XMapPane.class);
109    
110          private boolean acceptsRepaintCalls = true;          private boolean acceptsRepaintCalls = true;
111    
# Line 125  public class XMapPane extends JPanel { Line 131  public class XMapPane extends JPanel {
131           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all           * regularly and {@link #repaint()}. This {@link Timer} is stopped when all
132           * renderers have finished.           * renderers have finished.
133           *           *
134           * @see #INITIAL_REPAINT_DELAYAL           * @see INITIAL_REPAINT_DELAYAL
135           * @see #REPEATING_REPAINT_DELAY           * @see #REPEATING_REPAINT_DELAY
136           */           */
137          final private Timer repaintTimer;          final private Timer repaintTimer;
# Line 134  public class XMapPane extends JPanel { Line 140  public class XMapPane extends JPanel {
140           * The initial delay in milliseconds until the {@link #finalImage} is           * The initial delay in milliseconds until the {@link #finalImage} is
141           * updated the first time.           * updated the first time.
142           */           */
143          public static final int INITIAL_REPAINT_DELAY = 1000;          public static final int INITIAL_REPAINT_DELAY = 900;
144    
145          /**          /**
146           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,           * While the {@link #bgExecuter} and {@link #localExecuter} are rendering,
147           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}           * the {@link #repaintTimer} is regularly updating the {@link #finalImage}
148           * with previews.           * with previews.
149           */           */
150          public static final long REPEATING_REPAINT_DELAY = 500;          public static final int REPEATING_REPAINT_DELAY = 500;
151    
152          /**          /**
153           * Default delay (milliseconds) before the map will be redrawn when resizing           * Default delay (milliseconds) before the map will be redrawn when resizing
154           * the pane. This is to avoid flickering while drag-resizing.           * the pane. This is to avoid flickering while drag-resizing.
155             *
156             * @see #resizeTimer
157           */           */
158          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;          public static final int DEFAULT_RESIZING_PAINT_DELAY = 600;
159    
160            /**
161             * This not-repeating {@link Timer} is re-started whenever the component is
162             * resized. That means => only if the component is not resizing for
163             * {@link #DEFAULT_RESIZING_PAINT_DELAY} milliseconds, does the
164             * {@link XMapPane} react.
165             */
166            private final Timer resizeTimer;
167    
168            /**
169             * Flag for no-tool.
170             */
171          public static final int NONE = -123;          public static final int NONE = -123;
172    
173          /**          /**
# Line 160  public class XMapPane extends JPanel { Line 179  public class XMapPane extends JPanel {
179          public static final int PAN = 1;          public static final int PAN = 1;
180    
181          /**          /**
182             * Flag fuer Modus "Heran zoomen".
183             *
184             * @see #setState(int)
185             * @see #setState(int)
186             */
187            public static final int ZOOM_IN = 2;
188    
189            /**
190             * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!
191             *
192             * @see #setState(int)
193             */
194            public static final int ZOOM_OUT = 3;
195    
196            /**
197           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".           * Flag fuer Modus "SimpleFeature-Auswahl auf allen (sichtbaren) Layern".
198           *           *
199           * @see #setState(int)           * @see #setState(int)
# Line 183  public class XMapPane extends JPanel { Line 217  public class XMapPane extends JPanel {
217           */           */
218          public static final int SELECT_TOP = 4;          public static final int SELECT_TOP = 4;
219    
220          public static final Cursor WAIT_CURSOR = Cursor          /**
221                          .getPredefinedCursor(Cursor.WAIT_CURSOR);           * {@link Font} used to paint the wait messages into the map
222             *
223          final static Font waitFont = new Font("Arial", Font.BOLD, 30);           * @see #addGadgets(Graphics2D, boolean)
224          final String waitMsg = SwingUtil.R("WaitMess");           */
225          final static Font errorFont = new Font("Arial", Font.BOLD, 13);          final static Font waitFont = new Font("Arial", Font.BOLD, 28);
226    
227          /**          /**
228           * Flag fuer Modus "Heran zoomen".           * {@link Font} used to paint error messages into the map
229           *           *
230           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
          * @see #setState(int)  
231           */           */
232          public static final int ZOOM_IN = 2;          final static Font errorFont = new Font("Arial", Font.BOLD, 13);
233    
234          /**          /**
235           * Flag fuer Modus "Heraus zoomen". Nicht fuer Window-Auswahl moeglich!           * If last average last two renderings took more than that many ms, show the
236             * user a scaled preview
237             **/
238            private static final long PRESCALE_MINTIME = 230;
239    
240            /**
241             * The wait message painted into the map while rendering is going on on
242             * another thread.
243           *           *
244           * @see #setState(int)           * @see #addGadgets(Graphics2D, boolean)
245           */           */
246          public static final int ZOOM_OUT = 3;          final String waitMsg = SwingUtil.R("WaitMess");
247    
248          /**          /**
249           * 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 252  public class XMapPane extends JPanel {
252           * @param e           * @param e
253           *            Maus-Ereignis           *            Maus-Ereignis
254           */           */
255          public static Point2D getMapCoordinatesFromEvent(final MouseEvent e) {          public static DirectPosition2D getMapCoordinatesFromEvent(final MouseEvent e) {
256                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln                  // aktuelle Geo-Position aus GeoMouseEvent ermitteln
257                  if (e != null && e instanceof MapMouseEvent)                  if (e != null && e instanceof MapMouseEvent)
258                          try {                          try {
259                                  return ((MapMouseEvent) e).getMapPosition().toPoint2D();                                  return ((MapMouseEvent) e).getMapPosition();
260                          } catch (final Exception err) {                          } catch (final Exception err) {
261                                  LOGGER                                  LOGGER
262                                                  .error(                                                  .error(
# Line 233  public class XMapPane extends JPanel { Line 273  public class XMapPane extends JPanel {
273                                  return null;                                  return null;
274    
275                          final AffineTransform at = xMapPane.getScreenToWorld();                          final AffineTransform at = xMapPane.getScreenToWorld();
276                          if (at != null)                          if (at != null) {
277                                  return at.transform(e.getPoint(), null);                                  Point2D transformed = at.transform(e.getPoint(), null);
278                                    return new DirectPosition2D(xMapPane.getMapContext()
279                                                    .getCoordinateReferenceSystem(), transformed.getX(),
280                                                    transformed.getY());
281                            }
282                          return null;                          return null;
283                  }                  }
284                  throw new IllegalArgumentException(                  throw new IllegalArgumentException(
# Line 249  public class XMapPane extends JPanel { Line 293  public class XMapPane extends JPanel {
293    
294                  @Override                  @Override
295                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
296                            final MapLayer layer = event.getLayer();
                         MapLayer layer = event.getLayer();  
   
297                          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();  
298                          requestStartRendering();                          requestStartRendering();
299    
300                  }                  }
301    
302                  @Override                  @Override
303                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
304                          requestStartRendering();                          requestStartRendering();
305                  }                  }
306    
307                  @Override                  @Override
308                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
309                          requestStartRendering();                          requestStartRendering();
310                  }                  }
311    
# Line 288  public class XMapPane extends JPanel { Line 313  public class XMapPane extends JPanel {
313                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
314                          if (event.getLayer() != null)                          if (event.getLayer() != null)
315                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);                                  event.getLayer().removeMapLayerListener(bgMapLayerListener);
                         // mapImageInvalid = true;  
                         // repaint();  
316                          requestStartRendering();                          requestStartRendering();
317                  }                  }
318          };          };
319    
320          /**          /**
321           * compass and icon are rendered into this image           * This {@link RenderingExecutor} manages the creation and cancellation of
322             * up to one {@link Thread} for rendering the {@link #localContext}.
323           */           */
324          // protected BufferedImage gadgetsImage;          private final RenderingExecutor localExecuter = new RenderingExecutor(this);
325    
326            /**
327             * This {@link RenderingExecutor} manages the creation and cancellation of
328             * up to one {@link Thread} for rendering the {@link #bgContext}.
329             */
330          protected RenderingExecutor bgExecuter;          protected RenderingExecutor bgExecuter;
331    
332          /**          /**
333           * The Renderer for the LocalLayers uses this Image. When set to null,           * The {@link #localRenderer} for the {@link #localContext} uses this
334           * please dispose this {@link Graphics2D}           * {@link Image}.
335           */           */
336          private BufferedImage localImage;          private BufferedImage localImage;
337    
         private BufferedImage finalImage;  
338          /**          /**
339           * If # {@link #bgExecuter} is using {@link #bgRenderer} for the Background           * The {@link #bgRenderer} for the {@link #bgContext} uses this
340           * uses this Image. When set to null, please dispose the {@link Graphics2D}           * {@link Image}.
341           */           */
342          private BufferedImage bgImage;          private BufferedImage bgImage;
343    
344          /**          /**
345             * This {@link Image} is a merge of the {@link #bgImage},
346             * {@link #localImage} and {@link #addGadgets(Graphics2D, boolean)}. It is
347             * updated with {@link #updateFinalImage()} and used for painting in
348             * {@link #paintComponent(Graphics)}
349             */
350            private BufferedImage finalImage;
351    
352            /**
353           * Optionally a transparent image to paint over the map in the lower right           * Optionally a transparent image to paint over the map in the lower right
354           * corner.           * corner.
355           *           *
# Line 331  public class XMapPane extends JPanel { Line 366  public class XMapPane extends JPanel {
366    
367                  @Override                  @Override
368                  public void layerChanged(final MapLayerEvent event) {                  public void layerChanged(final MapLayerEvent event) {
                         // Change of SLD for example  
                         // mapImageInvalid = true;  
                         // repaint();  
369                          requestStartRendering();                          requestStartRendering();
370                  }                  }
371    
372                  @Override                  @Override
373                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
374                          requestStartRendering();                          requestStartRendering();
375                  }                  }
376    
377                  @Override                  @Override
378                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
379                          requestStartRendering();                          requestStartRendering();
380                  }                  }
381          };          };
# Line 384  public class XMapPane extends JPanel { Line 412  public class XMapPane extends JPanel {
412                  public void layerAdded(final MapLayerListEvent event) {                  public void layerAdded(final MapLayerListEvent event) {
413                          event.getLayer().addMapLayerListener(localMapLayerListener);                          event.getLayer().addMapLayerListener(localMapLayerListener);
414    
415                          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();  
416                          requestStartRendering();                          requestStartRendering();
417    
418                  }                  }
419    
420                  @Override                  @Override
421                  public void layerChanged(final MapLayerListEvent event) {                  public void layerChanged(final MapLayerListEvent event) {
422                          // mapImageInvalid = true;                          // getLocalRenderer().setContext(getMapContext()); geht doch auch
423                          // repaint();                          // ohne?!?!? wow...
                         localRenderer.setContext(getContext());  
424                          requestStartRendering();                          requestStartRendering();
425                  }                  }
426    
427                  @Override                  @Override
428                  public void layerMoved(final MapLayerListEvent event) {                  public void layerMoved(final MapLayerListEvent event) {
429                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
430                          requestStartRendering();                          requestStartRendering();
431                  }                  }
432    
# Line 422  public class XMapPane extends JPanel { Line 434  public class XMapPane extends JPanel {
434                  public void layerRemoved(final MapLayerListEvent event) {                  public void layerRemoved(final MapLayerListEvent event) {
435                          if (event.getLayer() != null)                          if (event.getLayer() != null)
436                                  event.getLayer().removeMapLayerListener(localMapLayerListener);                                  event.getLayer().removeMapLayerListener(localMapLayerListener);
437                          // mapImageInvalid = true;                          getLocalRenderer().setContext(getMapContext());
                         // repaint();  
                         localRenderer.setContext(getContext());  
438                          requestStartRendering();                          requestStartRendering();
439                  }                  }
440          };          };
441    
         private final RenderingExecutor localExecuter = new RenderingExecutor(this);  
   
442          /**          /**
443           * Listens to each layer in the local {@link MapContext} for changes and           * Listens to each layer in the local {@link MapContext} for changes and
444           * triggers repaints.           * triggers repaints. We don't have to listen layerChanged, because that is
445             * already done in {@link #localContextListener}
446           */           */
447          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {          protected MapLayerListener localMapLayerListener = new MapLayerAdapter() {
448    
449                  @Override                  // @Override
450                  public void layerChanged(final MapLayerEvent event) {                  // public void layerChanged(final MapLayerEvent event) {
451                          localRenderer.setContext(getContext()); // betters for SLD changes?!                  // // getLocalRenderer().setContext(getMapContext()); // betters for SLD
452                          // Change of SLD for example                  // // // changes?!
453                          // mapImageInvalid = true;                  // // requestStartRendering();
454                          // repaint();                  // }
                         requestStartRendering();  
                 }  
455    
456                  @Override                  @Override
457                  public void layerHidden(final MapLayerEvent event) {                  public void layerHidden(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
458                          requestStartRendering();                          requestStartRendering();
459                  }                  }
460    
461                  @Override                  @Override
462                  public void layerShown(final MapLayerEvent event) {                  public void layerShown(final MapLayerEvent event) {
                         // mapImageInvalid = true;  
                         // repaint();  
463                          requestStartRendering();                          requestStartRendering();
464                  }                  }
465          };          };
466    
467          private final GTRenderer localRenderer = GTUtil.createGTRenderer();          final private GTRenderer localRenderer = GTUtil.createGTRenderer();
468    
469          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();          private final GTRenderer bgRenderer = GTUtil.createGTRenderer();
470    
# Line 482  public class XMapPane extends JPanel { Line 485  public class XMapPane extends JPanel {
485          /**          /**
486           * 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.
487           */           */
488          private Color mapBackgroundColor = Color.WHITE;          private Color mapBackgroundColor = null;
489    
490          /**          /**
491           * 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 529  public class XMapPane extends JPanel {
529           * A flag indicating, that the image size has changed and the buffered           * A flag indicating, that the image size has changed and the buffered
530           * images are not big enough any more           * images are not big enough any more
531           **/           **/
532          protected boolean paneResized = false;          protected boolean paneResized = true;
533    
534          private BufferedImage preFinalImage;          private BufferedImage preFinalImage;
535    
536          // if null, no quick preview will be shown          // ** if 0, no quick preview will be shown **/
537          private int quickPreviewHint = 0;          // private int quickPreviewHint = 0;
538    
539          private Map<Object, Object> rendererHints = GTUtil          private Map<Object, Object> rendererHints = GTUtil
540                          .getDefaultGTRendererHints(localRenderer);                          .getDefaultGTRendererHints(getLocalRenderer());
541    
542            /**
543             * If set to <code>true</code>, the {@link #startRenderThreadsTimer} will
544             * start rendering {@link Thread}s
545             **/
546          private volatile Boolean requestStartRendering = false;          private volatile Boolean requestStartRendering = false;
547    
         private final Timer resizeTimer;  
   
548          /**          /**
549           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten           * Transformation zwischen Fenster-Koordinaten und Karten-Koordinaten
550           * (lat/lon)           * (lat/lon)
# Line 576  public class XMapPane extends JPanel { Line 581  public class XMapPane extends JPanel {
581          /** Is set if a renderer has an error **/          /** Is set if a renderer has an error **/
582          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();          protected ArrayList<Exception> renderingErrors = new ArrayList<Exception>();
583    
584          // TODO doku          /**
585             * If <code>true</code>, then rendering exceptions are rendererd into the
586             * map pane
587             **/
588            private boolean showExceptions = false;
589    
590          public XMapPane() {          public XMapPane() {
591                  this(null, null);                  this(null, null);
592          }          }
# Line 585  public class XMapPane extends JPanel { Line 595  public class XMapPane extends JPanel {
595           * full constructor extending JPanel           * full constructor extending JPanel
596           *           *
597           * @param rendererHints           * @param rendererHints
598             *            may be <code>null</code>. Otherwise a {@link Map<Object,
599             *            Object>} of {@link RenderingHints} to override the default
600             *            from {@link GTUtil#getDefaultGTRendererHints(GTRenderer)}
601           *           *
          * @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  
602           * @param localContext           * @param localContext
603           *            - {@link MapContext} of layer to render.           *            The main {@link MapContext} to use. If <code>null</code>, an
604             *            empty {@link DefaultMapContext} will be created.
605           */           */
606          public XMapPane(final MapContext localContext_,          public XMapPane(final MapContext localContext_,
607                          final Map<Object, Object> rendererHints) {                          final Map<Object, Object> rendererHints) {
# Line 620  public class XMapPane extends JPanel { Line 628  public class XMapPane extends JPanel {
628                   * Using a ComponentListener doesn't work because, unlike a JFrame, the                   * Using a ComponentListener doesn't work because, unlike a JFrame, the
629                   * pane receives a stream of events during drag-resizing.                   * pane receives a stream of events during drag-resizing.
630                   */                   */
631                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY, new ActionListener() {                  resizeTimer = new Timer(DEFAULT_RESIZING_PAINT_DELAY,
632                                    new ActionListener() {
                         public void actionPerformed(final ActionEvent e) {  
                                 paneResized = true;  
633    
634                                  if (!isWellDefined())                                          public void actionPerformed(final ActionEvent e) {
635                                          return;                                                  if (!isWellDefined())
636                                                            return;
637    
638                                  final Rectangle bounds = getVisibleRect();                                                  // LOGGER.debug("resizeTimer performed");
639    
640                                  final Envelope geoMapArea = tranformWindowToGeo(bounds.x,                                                  // final Rectangle bounds = getVisibleRect();
641                                                  bounds.y, bounds.x + bounds.width, bounds.y                                                  //
642                                                                  + bounds.height);                                                  // System.out.println("\n\ntimer performs with bounds = "
643                                                    // + bounds);
644    
645                                                    // final Envelope geoMapArea = tranformWindowToGeo(
646                                                    // bounds.x, bounds.y, bounds.x + bounds.width,
647                                                    // bounds.y + bounds.height);
648    
649                                                    paneResized = true;
650                                                    if (!setMapArea(getMapArea())) {
651                                                            // It's important to request new rendering here.
652                                                            // setMapArea only returns true and only calls
653                                                            // requestStartRendering if the maparea has changed.
654                                                            // But if the component is resized, the maparea
655                                                            // doesn't have to change.
656                                                            requestStartRendering();
657                                                    }
658    
659                                  setMapArea(bestAllowedMapArea(geoMapArea));                                          }
660                          }                                  });
                 });  
661                  resizeTimer.setRepeats(false);                  resizeTimer.setRepeats(false);
662    
663                  this.addComponentListener(new ComponentAdapter() {                  this.addComponentListener(new ComponentAdapter() {
664    
665                            private Rectangle oldVisibleRect;
666    
667                          @Override                          @Override
668                          public void componentResized(final ComponentEvent e) {                          public void componentResized(final ComponentEvent e) {
669                                  if (bgExecuter != null)  
670                                          bgExecuter.cancelTask();                                  // Seems to be called twice with the same size..
671                                  if (localExecuter != null)                                  if (oldVisibleRect != null
672                                          localExecuter.cancelTask();                                                  && oldVisibleRect.equals(getVisibleRect())) {
673                                            // LOGGER.debug("skipping resize.");
674                                            return;
675                                    }
676    
677                                    // LOGGER.debug("resized: " + getVisibleRect());
678                                  resizeTimer.restart();                                  resizeTimer.restart();
679                                    oldVisibleRect = getVisibleRect();
680                          }                          }
681    
682                  });                  });
# Line 654  public class XMapPane extends JPanel { Line 684  public class XMapPane extends JPanel {
684                  /*                  /*
685                   * Setting up the repaintTimer. Not started automatically.                   * Setting up the repaintTimer. Not started automatically.
686                   */                   */
687                  repaintTimer = new Timer((int) REPEATING_REPAINT_DELAY,                  repaintTimer = new Timer(REPEATING_REPAINT_DELAY, new ActionListener() {
688                                  new ActionListener() {  
689                            @Override
690                            public void actionPerformed(final ActionEvent e) {
691                                    if ((!localExecuter.isRunning())
692                                                    && (bgExecuter != null && !bgExecuter.isRunning())) {
693                                            repaintTimer.stop();
694                                    } else {
695                                            updateFinalImage();
696                                            XMapPane.this.repaint(100);
697    
698                                    }
699                            }
700                    });
701    
                                         @Override  
                                         public void actionPerformed(final ActionEvent e) {  
                                                 updateFinalImage();  
                                                 XMapPane.this.repaint();  
                                         }  
                                 });  
702                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);                  repaintTimer.setInitialDelay(INITIAL_REPAINT_DELAY);
703                  repaintTimer.setRepeats(true);                  repaintTimer.setRepeats(true);
704    
# Line 680  public class XMapPane extends JPanel { Line 716  public class XMapPane extends JPanel {
716                                                  if (localExecuter.isRunning()) {                                                  if (localExecuter.isRunning()) {
717                                                          localExecuter.cancelTask();                                                          localExecuter.cancelTask();
718                                                  } else {                                                  } else {
719                                                            // Stupidly, but we have to recheck the
720                                                            setMapArea(getMapArea());
721                                                          requestStartRendering = false;                                                          requestStartRendering = false;
722                                                          startRendering();                                                          startRendering();
723                                                  }                                                  }
# Line 712  public class XMapPane extends JPanel { Line 750  public class XMapPane extends JPanel {
750           * @author <a href="mailto:[email protected]">Stefan Alfons           * @author <a href="mailto:[email protected]">Stefan Alfons
751           *         Kr&uuml;ger</a>           *         Kr&uuml;ger</a>
752           */           */
753          public Envelope bestAllowedMapArea(Envelope env) {          public ReferencedEnvelope bestAllowedMapArea(ReferencedEnvelope env) {
754                  // return env;  
755                  if (getWidth() == 0)                  if (getWidth() == 0)
756                          return env;                          return env;
757    
758                  if (env == null)                  if (env == null)
759                          return null;                          return null;
760    
# Line 765  public class XMapPane extends JPanel { Line 804  public class XMapPane extends JPanel {
804                  }                  }
805    
806                  final Envelope maxAllowedExtend = getMaxExtend();                  final Envelope maxAllowedExtend = getMaxExtend();
807    
808                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)                  while (maxAllowedExtend != null && !maxAllowedExtend.contains(newArea)
809                                  && newArea != null && !newArea.isNull()                                  && newArea != null && !newArea.isNull()
810                                  && !Double.isNaN(newArea.getMinX())                                  && !Double.isNaN(newArea.getMinX())
# Line 794  public class XMapPane extends JPanel { Line 834  public class XMapPane extends JPanel {
834    
835                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
836    
837                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
838                                                          false);                                                          new ReferencedEnvelope(newArea, env
839                                                                            .getCoordinateReferenceSystem()), false);
840                                  }                                  }
841                          }                          }
842    
# Line 818  public class XMapPane extends JPanel { Line 859  public class XMapPane extends JPanel {
859    
860                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
861    
862                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
863                                                          false);                                                          new ReferencedEnvelope(newArea, env
864                                                                            .getCoordinateReferenceSystem()), false);
865                                  }                                  }
866                          }                          }
867    
# Line 844  public class XMapPane extends JPanel { Line 886  public class XMapPane extends JPanel {
886    
887                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
888    
889                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
890                                                          false);                                                          new ReferencedEnvelope(newArea, env
891                                                                            .getCoordinateReferenceSystem()), false);
892                                  }                                  }
893                          }                          }
894    
# Line 870  public class XMapPane extends JPanel { Line 913  public class XMapPane extends JPanel {
913    
914                                          // LOGGER.debug("and fix aspect ratio");                                          // LOGGER.debug("and fix aspect ratio");
915    
916                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(), newArea,                                          newArea = JTSUtil.fixAspectRatio(getVisibleRect(),
917                                                          false);                                                          new ReferencedEnvelope(newArea, env
918                                                                            .getCoordinateReferenceSystem()), false);
919                                  }                                  }
920                          }                          }
921                  }                  }
922    
923                  return newArea;                  return new ReferencedEnvelope(newArea, env
924                                    .getCoordinateReferenceSystem());
925          }          }
926    
927          /**          /**
# Line 904  public class XMapPane extends JPanel { Line 949  public class XMapPane extends JPanel {
949                          bgExecuter.dispose();                          bgExecuter.dispose();
950                  }                  }
951    
952                  if (localExecuter != null) {                  if (localExecuter.isRunning()) {
953                          int i = 0;                          int i = 0;
954                          localExecuter.cancelTask();                          localExecuter.cancelTask();
955                          while (i++ < 10 && localExecuter.isRunning()) {                          while (i++ < 10 && localExecuter.isRunning()) {
956                                  try {                                  try {
957                                          Thread.sleep(100);                                          Thread.sleep(200);
958                                  } catch (final InterruptedException e) {                                  } catch (final InterruptedException e) {
959                                          // TODO Auto-generated catch block                                          LOGGER
960                                          e.printStackTrace();                                                          .warn(
961                                                                            "while XMapPane we are waiting for the localExcutor to stop",
962                                                                            e);
963                                  }                                  }
964                          }                          }
965                          if (localExecuter.isRunning()) {                          if (localExecuter.isRunning()) {
966                                  System.out                                  LOGGER
967                                                  .println("BAD BAD BAD... still running the thread....");                                                  .warn("localExecutor Thread still running after 2s! Continuing anyways...");
968                          }                          }
969                          localExecuter.dispose();                          localExecuter.dispose();
970                  }                  }
971    
972                  disposeImages();                  disposeImages();
973    
974                  // LangUtil.gcTotal();                  // Remove all mapPaneListeners that have registered with us
   
                 // Alle mapPaneListener entfernen  
975                  mapPaneListeners.clear();                  mapPaneListeners.clear();
976    
977                  removeMouseMotionListener(zoomMapPaneMouseListener);                  removeMouseMotionListener(zoomMapPaneMouseListener);
978                  removeMouseListener(zoomMapPaneMouseListener);                  removeMouseListener(zoomMapPaneMouseListener);
979    
980                  if (localContext != null)                  if (localContext != null)
981                          getContext().clearLayerList();                          getMapContext().clearLayerList();
982                  if (bgContext != null)                  if (bgContext != null)
983                          getBgContext().clearLayerList();                          getBgContext().clearLayerList();
984    
# Line 973  public class XMapPane extends JPanel { Line 1018  public class XMapPane extends JPanel {
1018           *           *
1019           * @param g           * @param g
1020           *            Graphics2D to paint the preview into           *            Graphics2D to paint the preview into
          *  
          * @param state  
          *            Max be {@link #ZOOM_IN} or {@link #ZOOM_OUT}  
1021           */           */
1022          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {          protected boolean drawScaledPreviewImage_Zoom(final Graphics2D graphics) {
1023    
1024  //              if (1 == 1)return false;                  // if (1 == 1)return false;
1025                                    // if (quickPreviewHint == 0)
1026                  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);  
1027    
1028                  if (oldMapArea == null)                  if (oldMapArea == null)
1029                          return false;                          return false;
1030    
1031                    if (getPreFinalImage() == null)
1032                            return false;
1033    
1034                  final Rectangle visibleArea = getVisibleRect();                  final Rectangle visibleArea = getVisibleRect();
1035    
1036                  // Calculate the oldMapArea in the current WindowCoordinates:                  // Calculate the oldMapArea in the current WindowCoordinates:
# Line 1006  public class XMapPane extends JPanel { Line 1043  public class XMapPane extends JPanel {
1043                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());                  final int xx2 = (int) Math.round(oldMapWindow.getMaxX());
1044                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());                  final int yy2 = (int) Math.round(oldMapWindow.getMaxY());
1045    
1046                    graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
1047                                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
1048                    graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
1049                                    RenderingHints.VALUE_ANTIALIAS_OFF);
1050                    graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
1051                                    RenderingHints.VALUE_RENDER_SPEED);
1052    
1053                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,                  graphics.drawImage(getPreFinalImage(), xx1, yy1, xx2, yy2,
1054                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),                                  (int) visibleArea.getMinX(), (int) visibleArea.getMinY(),
1055                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),                                  (int) visibleArea.getMaxX(), (int) visibleArea.getMaxY(),
# Line 1014  public class XMapPane extends JPanel { Line 1058  public class XMapPane extends JPanel {
1058                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2                  final Rectangle painedArea = new Rectangle(xx1, yy1, xx2 - xx1, yy2
1059                                  - yy1);                                  - yy1);
1060    
1061                  SwingUtil.clearAround(graphics, painedArea, visibleArea);                  SwingUtil.clearAround(graphics, painedArea, visibleArea,
1062                                    getMapBackgroundColor());
1063    
1064                  addGadgets(graphics, true);                  addGadgets(graphics, true);
1065    
1066                  quickPreviewHint = 0;                  // quickPreviewHint = 0;
1067    
1068                  repaintTimer.restart();                  repaintTimer.restart();
1069    
                 graphics.dispose();  
   
1070                  // Something has been drawn                  // Something has been drawn
1071                  return true;                  return true;
1072          }          }
# Line 1036  public class XMapPane extends JPanel { Line 1079  public class XMapPane extends JPanel {
1079           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1080           */           */
1081          private Image getBgImage() {          private Image getBgImage() {
1082                  //                  if (bgImage == null) {
1083                  // if (bgImage == null) {                          bgImage = new BufferedImage(getVisibleRect().width,
1084                  // bgImage = createImage(getBounds().width, getBounds().height);                                          getVisibleRect().height, IMAGETYPE);
1085                  // }                          SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1086                    }
1087    
1088                  return bgImage;                  return bgImage;
1089          }          }
1090    
1091          public MapContext getContext() {          public MapContext getMapContext() {
1092                  if (localContext == null) {                  if (localContext == null) {
1093                          setLocalContext(new DefaultMapContext());                          setLocalContext(new DefaultMapContext());
1094                  }                  }
# Line 1057  public class XMapPane extends JPanel { Line 1101  public class XMapPane extends JPanel {
1101                          // Rectangle curPaintArea = getVisibleRect();                          // Rectangle curPaintArea = getVisibleRect();
1102                          finalImage = new BufferedImage(getVisibleRect().width,                          finalImage = new BufferedImage(getVisibleRect().width,
1103                                          getVisibleRect().height, IMAGETYPE);                                          getVisibleRect().height, IMAGETYPE);
1104                            SwingUtil.clearImage(finalImage, getMapBackgroundColor());
1105    
1106                          requestStartRendering();                          // requestStartRendering();
1107                  }                  }
1108                  return finalImage;                  return finalImage;
1109          }          }
1110    
         public RenderingHints getJava2dHints() {  
                 return java2dHints;  
         }  
   
1111          /**          /**
1112           * Lazyly initializes a {@link BufferedImage} for the background renderer.           * Lazyly initializes a {@link BufferedImage} for the background renderer.
1113           */           */
# Line 1075  public class XMapPane extends JPanel { Line 1116  public class XMapPane extends JPanel {
1116                  if (localImage == null) {                  if (localImage == null) {
1117                          localImage = new BufferedImage(getVisibleRect().width,                          localImage = new BufferedImage(getVisibleRect().width,
1118                                          getVisibleRect().height, IMAGETYPE_withAlpha);                                          getVisibleRect().height, IMAGETYPE_withAlpha);
1119                            SwingUtil.clearImage(localImage, getMapBackgroundColor());
1120                  }                  }
1121    
1122                  return localImage;                  return localImage;
# Line 1090  public class XMapPane extends JPanel { Line 1132  public class XMapPane extends JPanel {
1132                          ReferencedEnvelope mapArea_ = null;                          ReferencedEnvelope mapArea_ = null;
1133                          try {                          try {
1134                                  mapArea_ = localContext.getLayerBounds();                                  mapArea_ = localContext.getLayerBounds();
1135                          } catch (final IOException e) {                          } catch (final Exception e) {
1136                                  LOGGER.warn("context.getLayerBounds()", e);                                  LOGGER.warn("localContext.getLayerBounds()", e);
1137                            }
1138    
1139                            if (mapArea_ == null && bgContext != null) {
1140                                    try {
1141                                            mapArea_ = bgContext.getLayerBounds();
1142                                    } catch (final IOException e) {
1143                                            LOGGER.warn("bgContext.getLayerBounds()", e);
1144                                    }
1145                          }                          }
1146    
1147                          if (mapArea_ != null) {                          if (mapArea_ != null) {
                                 mapImageInvalid = true; /* note we need to redraw */  
                                 // setMapArea(mapArea_); // results in a loop  
1148                                  mapArea = bestAllowedMapArea(mapArea_);                                  mapArea = bestAllowedMapArea(mapArea_);
1149                                    requestStartRendering();
1150                          }                          }
1151                  }                  }
1152    
# Line 1109  public class XMapPane extends JPanel { Line 1158  public class XMapPane extends JPanel {
1158                          try {                          try {
1159                                  localContext.setCoordinateReferenceSystem(GeoImportUtil                                  localContext.setCoordinateReferenceSystem(GeoImportUtil
1160                                                  .getDefaultCRS());                                                  .getDefaultCRS());
1161                          } catch (Exception e) {                          } catch (final Exception e) {
1162                                  throw new RuntimeException("setting context CRS:", e);                                  throw new RuntimeException("setting context CRS:", e);
1163                          }                          }
1164    
# Line 1118  public class XMapPane extends JPanel { Line 1167  public class XMapPane extends JPanel {
1167          }          }
1168    
1169          /**          /**
1170           * 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
1171             * methods looks for a parent component and will use its background color.
1172             * If no parent component is available, WHITE is returned.
1173           **/           **/
1174          public Color getMapBackgroundColor() {          public Color getMapBackgroundColor() {
1175                    if (mapBackgroundColor == null) {
1176                            if (getParent() != null)
1177                                    return getParent().getBackground();
1178                            else
1179                                    return Color.WHITE;
1180                    }
1181                  return mapBackgroundColor;                  return mapBackgroundColor;
1182          }          }
1183    
# Line 1147  public class XMapPane extends JPanel { Line 1204  public class XMapPane extends JPanel {
1204    
1205          public Envelope getMaxExtend() {          public Envelope getMaxExtend() {
1206                  if (maxExtend == null) {                  if (maxExtend == null) {
1207    
1208                            // The next command may take long time!
1209                            // long start = System.currentTimeMillis();
1210                          final ReferencedEnvelope layerBounds = GTUtil                          final ReferencedEnvelope layerBounds = GTUtil
1211                                          .getVisibleLayoutBounds(localContext);                                          .getVisibleLayoutBounds(localContext);
1212                            //                      
1213                            // LOGGER.info(
1214                            // (System.currentTimeMillis()-start)+"m to get maxExtend");
1215                            //                      
1216                          if (layerBounds == null) {                          if (layerBounds == null) {
1217                                  // TODO Last fallback could be the CRS valid area                                  // // TODO Last fallback could be the CRS valid area
1218                                  return null;                                  return null;
1219                          }                          }
1220    
1221                          // Kartenbereich um 10% vergroessern                          // Vergrößerung um 10% nochmal rausgenommen
1222                          return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil                          // // // Kartenbereich um 10% vergroessern
1223                                          .expandEnvelope(layerBounds, 0.1), true);                          // return JTSUtil.fixAspectRatio(getVisibleRect(), JTSUtil
1224                            // .expandEnvelope(layerBounds, 0.1), true);
1225    
1226                            return JTSUtil.fixAspectRatio(getVisibleRect(), layerBounds, true);
1227                  }                  }
1228                  return maxExtend;                  return maxExtend;
1229          }          }
# Line 1184  public class XMapPane extends JPanel { Line 1251  public class XMapPane extends JPanel {
1251          }          }
1252    
1253          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();  
                 // }  
1254                  return preFinalImage;                  return preFinalImage;
1255          }          }
1256    
# Line 1270  public class XMapPane extends JPanel { Line 1327  public class XMapPane extends JPanel {
1327           * {@link XMapPane} is visible and has bounds set.           * {@link XMapPane} is visible and has bounds set.
1328           */           */
1329          public boolean isWellDefined() {          public boolean isWellDefined() {
   
1330                  try {                  try {
1331                            if (getMapContext() == null)
                         if (getContext() == null)  
1332                                  return false;                                  return false;
1333                          if (getContext().getLayerCount() <= 0)                          if (getMapContext().getLayerCount() <= 0)
1334                                  return false;                                  return false;
1335                          if (getMapArea() == null)                          if (getVisibleRect().getWidth() == 0)
1336                                  return false;                                  return false;
1337                          if (getBounds().getWidth() == 0)                          if (getVisibleRect().getHeight() == 0)
                                 return false;  
                         if (getBounds().getHeight() == 0)  
1338                                  return false;                                  return false;
1339                            // if (getMapArea() == null)
1340                            // return false;
1341                  } catch (final Exception e) {                  } catch (final Exception e) {
1342                          return false;                          return false;
1343                  }                  }
1344                  return true;                  return true;
1345          }          }
1346    
1347            /**
1348             * Called from the listeners while the mouse is dragging, this method either
1349             * paints a translated (moved/panned) version of the image, or a rectangle.
1350             *
1351             * @param startPos
1352             *            in screen coordinates
1353             * @param lastPos
1354             *            in screen coordinates
1355             * @param event
1356             *            the {@link MouseEvent} to read the mouse buttons from
1357             */
1358          public void mouseDragged(final Point startPos, final Point lastPos,          public void mouseDragged(final Point startPos, final Point lastPos,
1359                          final MouseEvent event) {                          final MouseEvent event) {
1360    
1361                  if ((getState() == XMapPane.PAN)                  if ((getState() == XMapPane.PAN)
1362                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {                                  || ((event.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) != 0)) {
1363    
1364                            // Panning needs a panning coursor
1365                          if (getCursor() != SwingUtil.PANNING_CURSOR) {                          if (getCursor() != SwingUtil.PANNING_CURSOR) {
1366                                  setCursor(SwingUtil.PANNING_CURSOR);                                  setCursor(SwingUtil.PANNING_CURSOR);
1367    
1368                                  // While panning, we deactivate the rendering. So the tasts are                                  // While panning, we deactivate the rendering. So the tasks are
1369                                  // ready to start when the panning os done.                                  // ready to start when the panning is finished.
1370                                  if (bgExecuter != null)                                  if (bgExecuter != null && bgExecuter.isRunning())
1371                                          bgExecuter.cancelTask();                                          bgExecuter.cancelTask();
1372                                  if (localExecuter != null)                                  if (localExecuter.isRunning())
1373                                          localExecuter.cancelTask();                                          localExecuter.cancelTask();
1374                          }                          }
1375    
# Line 1349  public class XMapPane extends JPanel { Line 1416  public class XMapPane extends JPanel {
1416                  } else if ((getState() == XMapPane.ZOOM_IN)                  } else if ((getState() == XMapPane.ZOOM_IN)
1417                                  || (getState() == XMapPane.ZOOM_OUT)                                  || (getState() == XMapPane.ZOOM_OUT)
1418                                  || (getState() == XMapPane.SELECT_ALL)                                  || (getState() == XMapPane.SELECT_ALL)
1419                                  || (getState() == XMapPane.SELECT_TOP)                                  || (getState() == XMapPane.SELECT_TOP)) {
                 // || (getState() == XMapPane.SELECT_ONE_FROM_TOP)  
                 ) {  
                         final Graphics graphics = getGraphics();  
1420    
1421                            // Draws a rectangle
1422                            final Graphics2D graphics = (Graphics2D) getGraphics();
1423                          drawRectangle(graphics, startPos, event.getPoint());                          drawRectangle(graphics, startPos, event.getPoint());
1424                            if ((lastPos.x > 0) && (lastPos.y > 0))
                         if ((lastPos.x > 0) && (lastPos.y > 0)) {  
1425                                  drawRectangle(graphics, startPos, lastPos);                                  drawRectangle(graphics, startPos, lastPos);
                         }  
   
1426                          graphics.dispose();                          graphics.dispose();
   
1427                  }                  }
   
1428          }          }
1429    
1430          /**          /**
1431           * Called by the {@link RenderingExecutor} when rendering was cancelled.           * Called by the {@link RenderingExecutor} when rendering was cancelled.
1432           */           */
1433          public void onRenderingCancelled() {          public void onRenderingCancelled() {
1434                    // LOGGER.debug("Rendering cancelled");
1435                  repaintTimer.stop();                  repaintTimer.stop();
                 LOGGER.debug("Rendering cancelled");  
1436          }          }
1437    
1438          /**          /**
1439           * Called by the {@link RenderingExecutor} when rendering has been           * Called by the {@link RenderingExecutor} when rendering has been
1440           * completed.           * completed.
1441             *
1442             * @param l
1443             *            long ms the rendering took
1444           */           */
1445          public void onRenderingCompleted() {          public void onRenderingCompleted(final long l) {
1446                    lastRenderingDuration = (lastRenderingDuration + l) / 2;
1447                    // LOGGER
1448                    // .debug("complete rendering after " + lastRenderingDuration
1449                    // + "ms");
1450    
1451                  repaintTimer.stop();                  repaintTimer.stop();
1452                  updateFinalImage();  
1453                  repaint();                  // We "forget" about an exception every time we complete a rendering
1454                    // thread successfully
1455                  if (renderingErrors.size() > 0)                  if (renderingErrors.size() > 0)
1456                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1457    
1458                    updateFinalImage();
1459                    repaint();
1460          }          }
1461    
1462          /**          /**
# Line 1397  public class XMapPane extends JPanel { Line 1470  public class XMapPane extends JPanel {
1470           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)           * @see MapPaneListener#onRenderingStopped(org.geotools.swing.event.MapPaneEvent)
1471           */           */
1472          public void onRenderingFailed(final Exception renderingError) {          public void onRenderingFailed(final Exception renderingError) {
1473                  this.renderingErrors.add(renderingError);  
1474                    // Store the exceptions so we can show it to the user:
1475                    if (!(renderingError instanceof java.lang.IllegalArgumentException && renderingError
1476                                    .getMessage().equals(
1477                                                    "Argument \"sourceCRS\" should not be null.")))
1478                            this.renderingErrors.add(renderingError);
1479                  if (renderingErrors.size() > 3)                  if (renderingErrors.size() > 3)
1480                          renderingErrors.remove(0);                          renderingErrors.remove(0);
1481    
1482                  repaintTimer.stop();                  repaintTimer.stop();
1483    
1484                  LOGGER.warn("Rendering failed", renderingError);                  LOGGER.warn("Rendering failed", renderingError);
1485                  updateFinalImage();                  updateFinalImage();
1486                  repaint();                  repaint();
1487    
1488          }          }
1489    
         public void onRenderingPending() {  
                 // LOGGER.debug("Pending rendering updates the preview...");  
                 updateFinalImage();  
                 repaint();  
         }  
   
1490          @Override          @Override
1491          protected void paintComponent(final Graphics g) {          protected void paintComponent(final Graphics g) {
                 if (!acceptsRepaintCalls)  
                         return;  
1492    
1493                  // Maybe update the cursor and maybe stop the repainting timer                  // Maybe update the cursor and maybe stop the repainting timer
1494                  updateCursor();                  updateCursor();
1495    
1496                    if (!acceptsRepaintCalls)
1497                            return;
1498    
1499                    if (!isWellDefined())
1500                            return;
1501                    //
1502                    // if (paneResized) {
1503                    // // ((Graphics2D) g).setBackground(getMapBackgroundColor());
1504                    // // g.clearRect(0, 0, getVisibleRect().width,
1505                    // getVisibleRect().height);
1506                    // return;
1507                    // }
1508    
1509                  // super.paintComponent(g); // candidate for removal                  // super.paintComponent(g); // candidate for removal
1510    
1511                  boolean paintedSomething = false;                  boolean paintedSomething = false;
# Line 1432  public class XMapPane extends JPanel { Line 1517  public class XMapPane extends JPanel {
1517                          // If the new mapArea and the oldMapArea intersect, we can draw some                          // If the new mapArea and the oldMapArea intersect, we can draw some
1518                          // quick scaled preview to make the user feel that something is                          // quick scaled preview to make the user feel that something is
1519                          // happening.                          // happening.
1520                          if (mapAreaChanged && oldMapArea != null                          if (lastRenderingDuration > PRESCALE_MINTIME && mapAreaChanged
1521                                            && oldMapArea != null
1522                                          && getMapArea().intersects(oldMapArea)                                          && getMapArea().intersects(oldMapArea)
1523                                          & !getMapArea().equals(oldMapArea)) {                                          && !getMapArea().equals(oldMapArea) && !paneResized) {
1524    
1525                                  mapAreaChanged = false;                                  mapAreaChanged = false;
1526    
1527                                  if (getMapArea().covers(oldMapArea)) {                                  // if (getMapArea().covers(oldMapArea)) {
1528                                          setQuickPreviewHint(ZOOM_OUT);                                  // // quickPreviewHint = ZOOM_OUT;
1529                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D)
1530                                  } else if (oldMapArea.covers(getMapArea())) {                                  // g);
1531                                          setQuickPreviewHint(ZOOM_IN);                                  // } else if (oldMapArea.covers(getMapArea())) {
1532                                          paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);                                  // quickPreviewHint = ZOOM_IN;
1533                                  }                                  paintedSomething = drawScaledPreviewImage_Zoom((Graphics2D) g);
1534                                    // }
                         }  
   
                         if (paneResized) {  
                                 paneResized = false;  
                                 disposeImages();  
1535                          }                          }
   
                         // Start the Threads and Timers to render the image  
                         requestStartRendering();  
   
1536                  }                  }
1537    
1538                  if (!paintedSomething) {                  if (!paintedSomething) {
1539    
1540                          g.drawImage(getFinalImage(), 0, 0, null);                          g.drawImage(getFinalImage(), 0, 0, null);
1541    
                         g.dispose(); // cand. for removal  
   
1542                          paintedSomething = true; // cand. for removal                          paintedSomething = true; // cand. for removal
1543                  }                  }
1544    
# Line 1519  public class XMapPane extends JPanel { Line 1594  public class XMapPane extends JPanel {
1594           */           */
1595          public void performPan() {          public void performPan() {
1596    
1597                  Rectangle winBounds = getVisibleRect();                  final Rectangle winBounds = getVisibleRect();
1598                    
1599                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);                  winBounds.translate(-imageOrigin.x, -imageOrigin.y);
1600                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,                  final Envelope newMapArea = tranformWindowToGeo(winBounds.x,
1601                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y                                  winBounds.y, winBounds.x + winBounds.width, winBounds.y
# Line 1543  public class XMapPane extends JPanel { Line 1618  public class XMapPane extends JPanel {
1618                          setCursor(SwingUtil.PAN_CURSOR);                          setCursor(SwingUtil.PAN_CURSOR);
1619          }          }
1620    
         //  
         // /**  
         // * 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);  
         // }  
         // }  
   
1621          /**          /**
1622           * Entfernt einen Listener von der Map.           * Entfernt einen Listener von der Map.
1623           *           *
# Line 1583  public class XMapPane extends JPanel { Line 1636  public class XMapPane extends JPanel {
1636          private void requestStartRendering() {          private void requestStartRendering() {
1637                  if (bgExecuter != null)                  if (bgExecuter != null)
1638                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
1639                  if (localExecuter != null)  
1640                          localExecuter.cancelTask();                  localExecuter.cancelTask();
1641    
1642                    mapImageInvalid = true;
1643                    if (paneResized) {
1644                            paneResized = false;
1645                            disposeImages();
1646                    }
1647                  requestStartRendering = true;                  requestStartRendering = true;
1648    
1649          }          }
1650    
         //  
         // /**  
         // * 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);  
         // }  
         // }  
   
1651          /**          /**
1652           * Calculate the affine transforms used to convert between world and pixel           * Calculate the affine transforms used to convert between world and pixel
1653           * 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 1662  public class XMapPane extends JPanel {
1662           *            the current map pane extent (screen units)           *            the current map pane extent (screen units)
1663           */           */
1664          private void resetTransforms() {          private void resetTransforms() {
1665                  ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,                  // System.out
1666                                  getContext().getCoordinateReferenceSystem());                  // .println("paintArea in resetTeansofrms = " + getVisibleRect());
1667                    if (!isWellDefined())
1668                            return;
1669    
1670                  Rectangle paintArea = getVisibleRect(); // NOT USE GET BOUNDS!                  if (mapArea == null)
1671                            return;
1672                                    
1673                  //                          final ReferencedEnvelope refMapEnv = new ReferencedEnvelope(mapArea,
1674                  // 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();  
1675    
1676                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,                  worldToScreen = RendererUtilities.worldToScreenTransform(refMapEnv,
1677                                  paintArea);                                  getVisibleRect());
1678    
                 // worldToScreen = new AffineTransform(scale, 0, 0, -scale, -xoff,  
                 // yoff);  
1679                  try {                  try {
1680                          screenToWorld = worldToScreen.createInverse();                          screenToWorld = worldToScreen.createInverse();
1681    
1682                  } catch (NoninvertibleTransformException ex) {                  } catch (final NoninvertibleTransformException ex) {
1683                          ex.printStackTrace();                          LOGGER
1684                                            .error("can't invert worldToScreen to get screenToWorld!",
1685                                                            ex);
1686                  }                  }
1687          }          }
1688    
# Line 1683  public class XMapPane extends JPanel { Line 1701  public class XMapPane extends JPanel {
1701                  this.bgContext = context;                  this.bgContext = context;
1702    
1703                  if (context != null) {                  if (context != null) {
1704                          setMapArea(bgContext.getAreaOfInterest());                          // setMapArea(bgContext.getAreaOfInterest());
1705    
1706                          this.bgContext.addMapLayerListListener(bgContextListener);                          this.bgContext.addMapLayerListListener(bgContextListener);
1707    
# Line 1692  public class XMapPane extends JPanel { Line 1710  public class XMapPane extends JPanel {
1710                                  mapLayer.addMapLayerListener(bgMapLayerListener);                                  mapLayer.addMapLayerListener(bgMapLayerListener);
1711                          }                          }
1712                  }                  }
1713                  mapImageInvalid = true;  
1714                  repaint();                  requestStartRendering();
1715          }          }
1716    
1717          public void setJava2dHints(final RenderingHints java2dHints) {          public void setJava2dHints(final RenderingHints java2dHints) {
1718                  this.java2dHints = java2dHints;                  this.java2dHints = java2dHints;
1719          }          }
1720    
         /**  
          *  
          * @param context  
          */  
1721          public void setLocalContext(final MapContext context) {          public void setLocalContext(final MapContext context) {
1722                  // Remove the default listener from the old context                  // Remove the default listener from the old context
1723                  if (this.localContext != null) {                  if (this.localContext != null) {
# Line 1719  public class XMapPane extends JPanel { Line 1733  public class XMapPane extends JPanel {
1733    
1734                  if (context != null) {                  if (context != null) {
1735    
1736                          setMapArea(localContext.getAreaOfInterest());                          // setMapArea(localContext.getAreaOfInterest());
1737    
1738                          localRenderer.setContext(localContext);                          getLocalRenderer().setContext(localContext);
1739    
1740                          this.localContext.addMapLayerListListener(localContextListener);                          this.localContext.addMapLayerListListener(localContextListener);
1741    
# Line 1731  public class XMapPane extends JPanel { Line 1745  public class XMapPane extends JPanel {
1745                          }                          }
1746                  }                  }
1747    
1748                    requestStartRendering();
1749    
1750            }
1751    
1752            public void setBorder(final Border b) {
1753                    super.setBorder(b);
1754            }
1755    
1756            /**
1757             * Triggers to repaint (fast) and re-render (slow) the JMapPane.
1758             */
1759            public void refresh() {
1760                  mapImageInvalid = true;                  mapImageInvalid = true;
1761                  repaint();                  repaint();
1762          }          }
1763    
1764            // /**
1765            // * Triggers to use new {@link GTRenderer} and refresh the map. Should be
1766            // * called after {@link Style}s have been changed because GTRenderer is
1767            // * otherwise not working well.
1768            // */
1769            // public void refreshRenderers() {
1770            // localRenderer = GTUtil.createGTRenderer();
1771            // setLocalContext(getMapContext());
1772            // mapImageInvalid = true;
1773            // repaint();
1774            // }
1775    
1776          /**          /**
1777             * Set the new map area.
1778             *
1779           * @param newMapArea           * @param newMapArea
1780           * @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
1781           *         has been triggered.           *         has been triggered.
1782           */           */
1783          public boolean setMapArea(final Envelope newMapArea) {          public boolean setMapArea(final Envelope newMapArea) {
1784                    if (newMapArea == null)
1785                            return false;
1786                    if (getMapContext().getCoordinateReferenceSystem() == null)
1787                            return false;
1788                    return setMapArea(new ReferencedEnvelope(newMapArea, getMapContext()
1789                                    .getCoordinateReferenceSystem()));
1790            }
1791    
1792            /**
1793             * Set the new map area.
1794             *
1795             * @param newMapArea
1796             * @return <code>true</code> if the mapArea has been changed and a repaint
1797             *         has been triggered.
1798             */
1799            public boolean setMapArea(final ReferencedEnvelope newMapArea) {
1800    
1801                  if (newMapArea == null                  if (newMapArea == null
1802                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {                                  || bestAllowedMapArea(newMapArea).equals(mapArea)) {
# Line 1795  public class XMapPane extends JPanel { Line 1851  public class XMapPane extends JPanel {
1851                          bgContext.setAreaOfInterest(mapArea, localContext                          bgContext.setAreaOfInterest(mapArea, localContext
1852                                          .getCoordinateReferenceSystem());                                          .getCoordinateReferenceSystem());
1853                  }                  }
1854                  mapImageInvalid = true;  
1855                  mapAreaChanged = true;                  mapAreaChanged = true;
                 repaint();  
1856    
1857                  LOGGER.debug("New maparea = " + mapArea);                  repaint(200); // Do not remove it!
1858    
1859                    requestStartRendering();
1860    
1861                  return true;                  return true;
1862          }          }
1863    
# Line 1808  public class XMapPane extends JPanel { Line 1866  public class XMapPane extends JPanel {
1866           *           *
1867           * @param if <code>null</code>, white is used.           * @param if <code>null</code>, white is used.
1868           */           */
1869          public void setMapBackgroundColor(Color bgColor) {          public void setMapBackgroundColor(final Color bgColor) {
                 if (bgColor == null)  
                         bgColor = Color.WHITE;  
1870                  this.mapBackgroundColor = bgColor;                  this.mapBackgroundColor = bgColor;
1871          }          }
1872    
# Line 1868  public class XMapPane extends JPanel { Line 1924  public class XMapPane extends JPanel {
1924          }          }
1925    
1926          // /** Stored the time used for the last real rendering in ms. **/          // /** Stored the time used for the last real rendering in ms. **/
1927          // private long lastRenderingDuration = Long.MAX_VALUE;          private long lastRenderingDuration = 1000;
1928    
1929          /**          /**
1930           * 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 1941  public class XMapPane extends JPanel {
1941          }          }
1942    
1943          /**          /**
1944           *           * If <code>true</code>, allow the {@link XMapPane} to process #repaint()
1945           * @param b           * requests. Otherwise the map will not paint anything and not start any
1946             * rendering {@link Thread}s.
1947           */           */
1948          public void setPainting(final boolean b) {          public void setPainting(final boolean b) {
1949                  acceptsRepaintCalls = b;                  acceptsRepaintCalls = b;
1950          }                  if (acceptsRepaintCalls == true)
1951                            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;  
   
1952          }          }
1953    
1954          private void setRendererHints(final Map<Object, Object> rendererHints) {          private void setRendererHints(final Map<Object, Object> rendererHints) {
# Line 1949  public class XMapPane extends JPanel { Line 1993  public class XMapPane extends JPanel {
1993           */           */
1994          private void startRendering() {          private void startRendering() {
1995    
1996                  if (!isWellDefined())                  if (!isWellDefined() || !acceptsRepaintCalls) {
1997                            // if we are not ready to start rendering, try it again the next
1998                            // time the timer is chacking the flag.
1999                            requestStartRendering = true;
2000                          return;                          return;
2001                    }
2002    
2003                  if (bgExecuter != null) {                  if (bgExecuter != null) {
2004                          // Stop all renderers                          // Stop all renderers
2005                          bgExecuter.cancelTask();                          bgExecuter.cancelTask();
2006                  }                  }
2007    
2008                  if (localExecuter != null) {                  localExecuter.cancelTask();
                         localExecuter.cancelTask();  
                 }  
2009    
2010                  final Rectangle curPaintArea = getVisibleRect();                  final Rectangle curPaintArea = getVisibleRect();
2011    
# Line 1982  public class XMapPane extends JPanel { Line 2028  public class XMapPane extends JPanel {
2028                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);                          // (Graphics2D) getBgImage().getGraphics(), createGTRenderer);
2029                  }                  }
2030    
2031                  if (getContext() != null) {                  if (getMapContext() != null) {
2032                          // localExecuter = new RenderingExecutor(this, 150l);                          // localExecuter = new RenderingExecutor(this, 150l);
2033                          // LOGGER.debug("starting local renderer:");                          // LOGGER.debug("starting local renderer:");
2034    
2035                          localRenderer.setJava2DHints(getJava2dHints());                          getLocalRenderer().setJava2DHints(getJava2dHints());
2036                          localRenderer.setRendererHints(getRendererHints());                          getLocalRenderer().setRendererHints(getRendererHints());
2037    
2038                          ReferencedEnvelope areaOfInterest = getMapArea();                          final boolean submitted = localExecuter.submit(getMapArea(),
                         final boolean submitted = localExecuter.submit(areaOfInterest,  
2039                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),                                          curPaintArea, (Graphics2D) getLocalImage().getGraphics(),
2040                                          localRenderer, getWorldToScreenTransform());                                          getLocalRenderer());
2041                          if (submitted)                          if (submitted)
2042                                  repaintTimer.restart();                                  repaintTimer.restart();
2043                          else                          else
2044                                  requestStartRendering = true; // Try to start rendering again in                                  requestStartRendering = true; // Try to start rendering
2045                            // again in
2046                          // a moment                          // a moment
2047                  }                  }
2048    
2049                  updateCursor();                  updateCursor();
2050          }          }
2051    
2052            private RenderingHints getJava2dHints() {
2053                    return java2dHints;
2054            }
2055    
2056          /**          /**
2057           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.           * Transformiert einen Geo-Koordinaten-Bereich in Fenster-Koordinaten.
2058           *           *
# Line 2049  public class XMapPane extends JPanel { Line 2099  public class XMapPane extends JPanel {
2099                  final AffineTransform at = getScreenToWorld();                  final AffineTransform at = getScreenToWorld();
2100                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);                  final Point2D geoO = at.transform(new Point2D.Double(ox, oy), null);
2101                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);                  final Point2D geoP = at.transform(new Point2D.Double(px, py), null);
2102                    
2103                  // Mmmmm... don't really understand why its x,x,y,y                  // Mmmmm... don't really understand why its x,x,y,y
2104  //              return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(), geoP.getY());                  // return new Envelope(geoO.getX(), geoP.getX(), geoO.getY(),
2105                  return new Envelope( new Coordinate(geoO.getX(), geoO.getY()), new Coordinate(geoP.getX(), geoP.getY()));                  // geoP.getY());
2106                    return new Envelope(new Coordinate(geoO.getX(), geoO.getY()),
2107                                    new Coordinate(geoP.getX(), geoP.getY()));
2108          }          }
2109    
2110          /**          /**
# Line 2064  public class XMapPane extends JPanel { Line 2116  public class XMapPane extends JPanel {
2116                  // if the renderers have stopped, also stop the timer that is updating                  // if the renderers have stopped, also stop the timer that is updating
2117                  // the final image                  // the final image
2118                  if (bgExecuter != null && bgExecuter.isRunning()                  if (bgExecuter != null && bgExecuter.isRunning()
2119                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2120                          setCursor(WAIT_CURSOR);                          setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
2121                          return;                          return;
2122                  } else {                  } else {
2123                          // Allow one last rendering                          // Allow one last rendering
2124                          if (repaintTimer.isRunning()) {                          if (repaintTimer.isRunning()) {
2125                                  System.out.println("one last rendering....");                                  // System.out.println("one last rendering....");
2126                                  repaintTimer.stop();                                  repaintTimer.stop();
2127                                  updateFinalImage();                                  updateFinalImage();
2128                                  repaint();                                  repaint();
# Line 2140  public class XMapPane extends JPanel { Line 2192  public class XMapPane extends JPanel {
2192                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,                  finalG.drawImage(getPreFinalImage(), imageOrigin.x, imageOrigin.y,
2193                                  getMapBackgroundColor(), null);                                  getMapBackgroundColor(), null);
2194    
2195                  final int finalImageHeight = getFinalImage().getHeight(null);                  // When panning, we have to clear the area around the image
                 final int finalImageWidth = getFinalImage().getWidth(null);  
   
2196                  final Rectangle painedArea = new Rectangle(imageOrigin.x,                  final Rectangle painedArea = new Rectangle(imageOrigin.x,
2197                                  imageOrigin.y, finalImageWidth, finalImageHeight);                                  imageOrigin.y, getFinalImage().getWidth(), getFinalImage()
2198                  SwingUtil.clearAround(finalG, painedArea, getVisibleRect());                                                  .getHeight());
2199                    SwingUtil.clearAround(finalG, painedArea, getVisibleRect(),
2200                                    getMapBackgroundColor());
2201    
2202                  addGadgets(finalG, false);                  addGadgets(finalG, false);
2203    
# Line 2164  public class XMapPane extends JPanel { Line 2216  public class XMapPane extends JPanel {
2216           *            <code>false</code>, it will only depend on           *            <code>false</code>, it will only depend on
2217           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning           *            {@link #localExecuter.isRunning} and #bgExecuter.isRunning
2218           */           */
2219          private void addGadgets(final Graphics2D graphics, boolean forceWait) {          private void addGadgets(final Graphics2D graphics, final boolean forceWait) {
2220    
2221                  // Paint a logo to the bottom right if available                  // Paint a logo to the bottom right if available
2222                  if (mapImage != null) {                  if (mapImage != null) {
2223                          Rectangle visibleRect = getVisibleRect();                          final Rectangle visibleRect = getVisibleRect();
2224                          graphics.drawImage(mapImage, visibleRect.width                          graphics.drawImage(mapImage, visibleRect.width
2225                                          - mapImage.getWidth() - 10, getVisibleRect().height                                          - mapImage.getWidth() - 10, getVisibleRect().height
2226                                          - mapImage.getHeight() - 10, null);                                          - mapImage.getHeight() - 10, null);
# Line 2178  public class XMapPane extends JPanel { Line 2230  public class XMapPane extends JPanel {
2230    
2231                  // If the rendering process is still running, indicate this is the image                  // If the rendering process is still running, indicate this is the image
2232                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()                  if (forceWait || bgExecuter != null && bgExecuter.isRunning()
2233                                  || localExecuter != null && localExecuter.isRunning()) {                                  || localExecuter.isRunning()) {
2234    
2235                          y += 8;                          y += 8;
2236    
# Line 2194  public class XMapPane extends JPanel { Line 2246  public class XMapPane extends JPanel {
2246    
2247                          graphics.setColor(c);                          graphics.setColor(c);
2248    
2249                          y += 24;                          y += 21;
2250                  }                  }
2251    
2252                  if (renderingErrors != null) {                  if (!renderingErrors.isEmpty() && isShowExceptions()) {
2253    
2254                          final Color c = graphics.getColor();                          final Color c = graphics.getColor();
2255                          graphics.setFont(errorFont);                          graphics.setFont(errorFont);
2256    
2257                          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;  
2258    
2259                                  String errStr = ex.getLocalizedMessage();                                  String errStr = ex.getLocalizedMessage();
2260    
2261                                  graphics.setColor(Color.WHITE);                                  if (errStr == null)
2262                                            errStr = ex.getMessage();
2263                                    if (errStr == null)
2264                                            errStr = "unknown error: " + ex.getClass().getSimpleName();
2265    
2266                                    graphics.setColor(getMapBackgroundColor());
2267                                  graphics.drawString(errStr, 5, y);                                  graphics.drawString(errStr, 5, y);
2268                                  graphics.setColor(Color.RED);                                  graphics.setColor(Color.RED);
2269                                  graphics.drawString(errStr, 6, y + 1);                                  graphics.drawString(errStr, 6, y + 1);
# Line 2234  public class XMapPane extends JPanel { Line 2286  public class XMapPane extends JPanel {
2286          public void zoomTo(          public void zoomTo(
2287                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {                          final FeatureCollection<SimpleFeatureType, SimpleFeature> features) {
2288    
2289                  final CoordinateReferenceSystem mapCRS = getContext()                  // if (!isWellDefined()) return;
2290    
2291                    final CoordinateReferenceSystem mapCRS = getMapContext()
2292                                  .getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2293                  final CoordinateReferenceSystem fCRS = features.getSchema()                  final CoordinateReferenceSystem fCRS = features.getSchema()
2294                                  .getGeometryDescriptor().getCoordinateReferenceSystem();                                  .getCoordinateReferenceSystem();
2295    
2296                  double width = mapArea.getWidth();                  ReferencedEnvelope _mapArea;
2297                  double height = mapArea.getHeight();                  if (mapArea == null)
2298                            _mapArea = features.getBounds();
2299                    else
2300                            _mapArea = getMapArea();
2301                    double width = _mapArea.getWidth();
2302                    double height = _mapArea.getHeight();
2303                  final double ratio = height / width;                  final double ratio = height / width;
2304    
2305                  if (features == null || features.size() == 0) {                  if (features == null || features.size() == 0) {
# Line 2292  public class XMapPane extends JPanel { Line 2351  public class XMapPane extends JPanel {
2351                  } else {                  } else {
2352                          final ReferencedEnvelope fBounds = features.getBounds();                          final ReferencedEnvelope fBounds = features.getBounds();
2353    
2354                          Envelope bounds;                          ReferencedEnvelope bounds;
2355                          if (!mapCRS.equals(fCRS)) {                          if (!mapCRS.equals(fCRS)) {
2356                                  bounds = JTSUtil.transformEnvelope(fBounds, fCRS, mapCRS);                                  bounds = JTSUtil.transformEnvelope(fBounds, mapCRS);
2357                          } else {                          } else {
2358                                  bounds = fBounds;                                  bounds = fBounds;
2359                          }                          }
# Line 2325  public class XMapPane extends JPanel { Line 2384  public class XMapPane extends JPanel {
2384           * @param center           * @param center
2385           *            position in window coordinates           *            position in window coordinates
2386           * @param zoomFaktor           * @param zoomFaktor
2387           *            > 1 for zoom in, < 1 for zoom out. Default is 1.33.           *            > 1 for zoom out, < 1 for zoom in. Default is .5
2388           */           */
2389          public void zoomTo(Point center, Double zoomFaktor) {          public void zoomTo(Point center, Double zoomFaktor) {
2390                  if (zoomFaktor == null || zoomFaktor == 0.)                  if (zoomFaktor == null || zoomFaktor == 0.)
2391                          zoomFaktor = 2.;                          zoomFaktor = .5;
2392    
2393                  final Point2D gcenter = getScreenToWorld().transform(center, null);                  final Point2D gcenter = getScreenToWorld().transform(center, null);
2394                  center = null;                  center = null;
# Line 2349  public class XMapPane extends JPanel { Line 2408  public class XMapPane extends JPanel {
2408                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea                  newMapArea.expandBy((mapArea.getWidth() * zoomFaktor - mapArea
2409                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea                                  .getWidth()) / 2., (mapArea.getHeight() * zoomFaktor - mapArea
2410                                  .getHeight()) / 2.);                                  .getHeight()) / 2.);
2411                    
2412  // TODO we actually want that                  // // Move the newMapArea above the new center if we zoom in:
2413  //              // Move the newMapArea above the new center                  newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter
2414  //              newMapArea.translate(gcenter.getX() - mapArea.centre().x, gcenter                                  .getY()
2415  //                              .getY()                                  - mapArea.centre().y);
 //                              - mapArea.centre().y);  
2416    
2417                  setMapArea(newMapArea);                  setMapArea(newMapArea);
2418          }          }
2419    
2420            /**
2421             * Shall non-fatal rendering exceptions be reported in the mappane or be
2422             * dropped quitely.
2423             */
2424            public void setShowExceptions(final boolean showExceptions) {
2425                    this.showExceptions = showExceptions;
2426            }
2427    
2428            /**
2429             * Shall exceptions be reported in the mappane?
2430             */
2431            public boolean isShowExceptions() {
2432                    return showExceptions;
2433            }
2434    
2435            public GTRenderer getLocalRenderer() {
2436                    return localRenderer;
2437            }
2438    
2439            /**
2440             * Setzt den Kartenausschnitt auf die Ausdehnung eines bestimmten Layers.
2441             * Macht nichts, wenn {@code null} uebergeben wird.
2442             *
2443             * <br>
2444             *
2445             * @param layer
2446             *            ein Layer
2447             */
2448            public void zoomToLayer(MapLayer layer) {
2449                    if (layer == null)
2450                            return;
2451                    try {
2452    
2453                            // BB umrechnen von Layer-CRS in Map-CRS
2454                            final CoordinateReferenceSystem targetCRS = getMapContext()
2455                                            .getCoordinateReferenceSystem();
2456                            final CoordinateReferenceSystem sourceCRS = layer
2457                                            .getFeatureSource().getSchema()
2458                                            .getCoordinateReferenceSystem();
2459    
2460                            Envelope mapAreaNew;
2461                            if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) {
2462                                    mapAreaNew = JTSUtil.transformEnvelope(layer.getFeatureSource()
2463                                                    .getBounds(), sourceCRS, targetCRS);
2464                            } else {
2465                                    try {
2466                                            mapAreaNew = layer.getFeatureSource().getBounds();
2467                                    } catch (java.lang.IllegalArgumentException e) {
2468                                            LOGGER.error("Can't calc layers bounds...", e);
2469                                            mapAreaNew = null;
2470    
2471                                            /**
2472                                             *
2473                                             23.10.2009 11:20:50
2474                                             * org.geotools.data.shapefile.shp.PolygonHandler read
2475                                             * WARNUNG: only one hole in this polygon record ERROR
2476                                             * JMapPane zoomToLayer Zoom to layer did not terminate
2477                                             * correctly java.lang.IllegalArgumentException: Points of
2478                                             * LinearRing do not form a closed linestring at
2479                                             * com.vividsolutions
2480                                             * .jts.geom.LinearRing.validateConstruction
2481                                             * (LinearRing.java:105) at
2482                                             * com.vividsolutions.jts.geom.LinearRing
2483                                             * .<init>(LinearRing.java:100) at
2484                                             * com.vividsolutions.jts.geom
2485                                             * .GeometryFactory.createLinearRing
2486                                             * (GeometryFactory.java:339) at
2487                                             * org.geotools.data.shapefile.
2488                                             * shp.PolygonHandler.read(PolygonHandler.java:188) at
2489                                             * org.geotools
2490                                             * .data.shapefile.shp.ShapefileReader$Record.shape
2491                                             * (ShapefileReader.java:106) at
2492                                             * org.geotools.data.shapefile.
2493                                             * ShapefileAttributeReader.next(
2494                                             * ShapefileAttributeReader.java:157) at
2495                                             * org.geotools.data.shapefile
2496                                             * .indexed.IndexedShapefileAttributeReader
2497                                             * .next(IndexedShapefileAttributeReader.java:122) at
2498                                             * org.geotools
2499                                             * .data.FIDFeatureReader.next(FIDFeatureReader.java:96) at
2500                                             * org.geotools.data.FIDFeatureReader.next(FIDFeatureReader.
2501                                             * java:55) at org.geotools.data.MaxFeatureReader.next(
2502                                             * MaxFeatureReader.java:61) at
2503                                             * org.geotools.data.MaxFeatureReader
2504                                             * .next(MaxFeatureReader.java:61)
2505                                             **/
2506                                    }
2507                            }
2508    
2509                            // Kartenbereich um 10% vergroessern, damit z.B. auch ein
2510                            // Punkt-Layer,
2511                            // welches nur aus 2 Punnkten besteht, sichtbar ist (Punkte liegen
2512                            // sonst
2513                            // genau auf dem Rand der angezeigten Flaeche)
2514    
2515                            if (mapAreaNew != null) {
2516                                    mapAreaNew.expandBy(mapAreaNew.getWidth() * 0.1, mapAreaNew
2517                                                    .getHeight() * 0.1);
2518                                    setMapArea(mapAreaNew);
2519                            } else {
2520                                    LOGGER
2521                                                    .warn("Couldn't transformEnvelope when zooming to the layer");
2522                            }
2523                    } catch (Exception err) {
2524                            LOGGER.error("Zoom to layer did not terminate correctly", err);
2525                    }
2526            }
2527    
2528            /**
2529             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of a layer.
2530             *
2531             * <br>
2532             * A refresh of the map is not done automatically
2533             *
2534             * @param index
2535             *            Index of the {@link MapLayer} in the {@link MapContext} (from
2536             *            back to top)
2537             *
2538             * @author <a href="mailto:[email protected]">Stefan Alfons
2539             *         Kr&uuml;ger</a>
2540             */
2541            public void zoomToLayer(int index) {
2542                    final MapContext context = getMapContext();
2543                    if (context != null)
2544                            zoomToLayer(context.getLayer(index));
2545            }
2546    
2547            /**
2548             * Zooms the {@link SelectableXMapPane} to the {@link Envelope} of the
2549             * selected layer. The layer is selected by the idx, counting from front to
2550             * back, like humans would expect in a {@link JList}
2551             *
2552             * <br>
2553             * A refresh of the map is not done automatically
2554             *
2555             *
2556             *
2557             * @param index
2558             *            Reverse index of the {@link MapLayer} in the
2559             *            {@link MapContext}
2560             *
2561             * @author <a href="mailto:[email protected]">Stefan Alfons
2562             *         Kr&uuml;ger</a>
2563             */
2564            public void zoomToLayerIdxReverse(int index) {
2565                    zoomToLayer(getMapContext().getLayerCount() - 1 - index);
2566            }
2567    
2568            /**
2569             * Aktiviert oder deaktiviert das AntiAliasing for diese
2570             * {@link SelectableXMapPane}. AntiALiasing ist besonders fuer
2571             * Textbeschriftung sehr schoen, verbraucht aber auch mehr Performance.
2572             *
2573             * @author <a href="mailto:[email protected]">Stefan Alfons
2574             *         Kr&uuml;ger</a>
2575             */
2576            public void setAntiAliasing(final boolean aa) {
2577                    // LOGGER.info("Setting AntiAliasing for this JMapPane to " + aa);
2578                    RenderingHints java2DHints = java2dHints;
2579                    if (java2DHints == null) {
2580                            java2DHints = GeoTools.getDefaultHints();
2581                    }
2582    
2583                    java2DHints.put(RenderingHints.KEY_ANTIALIASING,
2584                                    aa ? RenderingHints.VALUE_ANTIALIAS_ON
2585                                                    : RenderingHints.VALUE_ANTIALIAS_OFF);
2586                    java2DHints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
2587                                    aa ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON
2588                                                    : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
2589                    java2DHints.put(RenderingHints.KEY_RENDERING,
2590                                    aa ? RenderingHints.VALUE_RENDER_QUALITY
2591                                                    : RenderingHints.VALUE_RENDER_SPEED);
2592    
2593            }
2594    
2595  }  }

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

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26