Statistics
| Revision:

svn-document-layout / trunk / org.gvsig.app.document.layout2.app / org.gvsig.app.document.layout2.app.mainplugin / src / main / java / org / gvsig / app / project / documents / layout / fframes / FFrameView.java @ 308

History | View | Annotate | Download (49.8 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
 *
3
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
4
 * of the Valencian Government (CIT)
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 2
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 */
22
package org.gvsig.app.project.documents.layout.fframes;
23

    
24
import java.awt.BasicStroke;
25
import java.awt.Color;
26
import java.awt.Dimension;
27
import java.awt.Font;
28
import java.awt.Graphics2D;
29
import java.awt.Point;
30
import java.awt.Rectangle;
31
import java.awt.geom.AffineTransform;
32
import java.awt.geom.Area;
33
import java.awt.geom.NoninvertibleTransformException;
34
import java.awt.geom.Point2D;
35
import java.awt.geom.Rectangle2D;
36
import java.awt.image.BufferedImage;
37

    
38
import org.cresques.cts.IProjection;
39
import org.gvsig.andami.PluginServices;
40
import org.gvsig.andami.messages.NotificationManager;
41
import org.gvsig.andami.ui.mdiFrame.NewStatusBar;
42
import org.gvsig.app.project.Project;
43
import org.gvsig.app.project.ProjectManager;
44
import org.gvsig.app.project.documents.Document;
45
import org.gvsig.app.project.documents.layout.DefaultLayoutNotification;
46
import org.gvsig.app.project.documents.layout.FLayoutFunctions;
47
import org.gvsig.app.project.documents.layout.FLayoutUtilities;
48
import org.gvsig.app.project.documents.layout.LayoutNotification;
49
import org.gvsig.app.project.documents.layout.TocModelChangedNotification;
50
import org.gvsig.app.project.documents.view.ViewDocument;
51
import org.gvsig.compat.print.PrintAttributes;
52
import org.gvsig.fmap.dal.exception.ReadException;
53
import org.gvsig.fmap.geom.Geometry;
54
import org.gvsig.fmap.geom.Geometry.SUBTYPES;
55
import org.gvsig.fmap.geom.GeometryLocator;
56
import org.gvsig.fmap.geom.GeometryManager;
57
import org.gvsig.fmap.geom.exception.CreateEnvelopeException;
58
import org.gvsig.fmap.geom.primitive.Envelope;
59
import org.gvsig.fmap.mapcontext.MapContext;
60
import org.gvsig.fmap.mapcontext.MapContextException;
61
import org.gvsig.fmap.mapcontext.ViewPort;
62
import org.gvsig.fmap.mapcontext.events.AtomicEvent;
63
import org.gvsig.fmap.mapcontext.events.ColorEvent;
64
import org.gvsig.fmap.mapcontext.events.ExtentEvent;
65
import org.gvsig.fmap.mapcontext.events.FMapEvent;
66
import org.gvsig.fmap.mapcontext.events.ProjectionEvent;
67
import org.gvsig.fmap.mapcontext.events.listeners.AtomicEventListener;
68
import org.gvsig.fmap.mapcontext.events.listeners.ViewPortListener;
69
import org.gvsig.fmap.mapcontext.layers.CancelationException;
70
import org.gvsig.fmap.mapcontext.layers.LayerCollectionEvent;
71
import org.gvsig.fmap.mapcontext.layers.LayerCollectionListener;
72
import org.gvsig.fmap.mapcontext.layers.LayerEvent;
73
import org.gvsig.fmap.mapcontext.layers.LayerPositionEvent;
74
import org.gvsig.fmap.mapcontext.rendering.legend.events.LegendChangedEvent;
75
import org.gvsig.fmap.mapcontext.rendering.legend.events.listeners.LegendListener;
76
import org.gvsig.gui.beans.Messages;
77
import org.gvsig.tools.ToolsLocator;
78
import org.gvsig.tools.dynobject.DynStruct;
79
import org.gvsig.tools.locator.LocatorException;
80
import org.gvsig.tools.persistence.PersistenceManager;
81
import org.gvsig.tools.persistence.PersistentState;
82
import org.gvsig.tools.persistence.exception.PersistenceException;
83
import org.slf4j.Logger;
84
import org.slf4j.LoggerFactory;
85

    
86
/**
87
 * FFrame used for embedding a View in the Layout. The View is not actually
88
 * inserted on the Layout, but it is used together with the MapContext
89
 * in order do draw an image which is then painted on the FFrame. Therefore,
90
 * no MapControl is used in current implementation, but a similar behavior
91
 * is simulated by the FFrameView. The original MapContext is cloned when
92
 * assigned to the FFrameView, which is then used for drawing.
93
 * 
94
 * The FFrameView and the associated View can be synchronized, depending
95
 * on the values of {@link #getTypeScale()} and {@link #getLinked()}.
96
 * 
97
 * The main synchronization logic is kept on two internal classes: 
98
 * {@link OwnMapContextListener} and {@link ViewDocListener}. The first one
99
 * listens for events on the FFrameView and synchronizes the View accordingly.
100
 * The second one listens for events on the View and synchronizes the FFrameView
101
 * accordingly. There synchronization process is flagged using
102
 * {@link #b_updating} and {@link #b_updating}, in order
103
 * to avoid incurring on infinite synchronization loops. 
104
 * 
105
 * @author Vicente Caballero Navarro
106
 * @author Cesar Martinez Izquierdo
107
 */
108
public class FFrameView extends FFrame implements IFFrameUseProject,
109
                IFFrameUseFMap, LayoutPanelListener{
110

    
111
    public static final String PERSISTENCE_DEFINITION_NAME = "FFrameView";
112

    
113
    private static final String QUALITY_FIELD = "quality";
114
    private static final String MAPUNITS_FIELD = "mapUnits";
115
    private static final String SCALE_FIELD = "scale";
116
    private static final String VIEW_FIELD = "view";
117
    private static final String ENVELOPE_FIELD = "envelope";
118
    private static final String SHOWGRID_FIELD = "showGrid";
119
    private static final String GRID_FIELD = "gridview";
120
    private static final String HAS_TOC_FIELD = "hasToc";
121
    private static final String LAYER_SYNC_FIELD = "layerSync";
122
    private static final String EXTENT_SYNC_FIELD = "extentSync";
123
    private static final String SCALE_TYPE_FIELD = "scaleType";
124
    // following fields are unused - they are kept for backward-compatibility 
125
    private static final String EXTENSION_FIELD = "extension";
126
    private static final String BLINKED_FIELD = "bLinked";
127
    private static final String MODE_FIELD = "mode";
128
    private static final String TYPESCALE_FIELD = "typeScale";
129
    private static final String MAPCONTEXT_FIELD = "mapContext";
130
    private static final String VIEWING_FIELD = "viewing";
131

    
132
    private static final Logger logger = LoggerFactory
133
        .getLogger(FFrameView.class);
134
    public static final int PRESENTATION = 0;
135
    public static final int DRAFT = 1;
136

    
137
    protected boolean syncLayers = true;
138
    protected boolean syncExtents = true;
139
    protected int quality = PRESENTATION;
140
    protected ViewDocument viewDocument = null;
141
    protected MapContext mapContext = null;
142
    protected int mapUnits = 1; // Meters.
143

    
144
    protected BufferedImage m_image = null;
145
    protected AffineTransform mapAT = null;
146
    protected Project project = null;
147
    protected double scaleAnt;
148
    protected Point origin;
149
    protected Point2D p1;
150
    protected Point2D p2;
151
    protected IFFrame grid;
152
    protected boolean showGrid = false;
153

    
154
        private boolean b_updating = false;
155
        protected boolean b_validCache = false;
156
        protected boolean b_drawing = false;
157
        protected ViewDocListener viewDocListener;
158
        protected OwnMapContextListener ownMapContextListener;
159
        private boolean b_hasToc = true;
160
    protected static final GeometryManager geomManager = GeometryLocator.getGeometryManager();
161

    
162
        /**
163
         * When we load a FFrameview from project, it will receive a wrong
164
         * extentChanged event the first time the View is painted, so we must
165
         * ignore this first event. 
166
         */
167
        private boolean b_frameInitialized = true;
168

    
169
        protected AffineTransform originalGraphicsAT = null;
170
        protected Rectangle originalClip = null;
171

    
172
        private SCALE_TYPE scaleType = SCALE_TYPE.NORMAL;
173
        private Double fixedScale = null;
174
        private Envelope fixedExtent = null;
175

    
176

    
177
    /**
178
     * Creates a new FFrameView object.
179
     */
180
    public FFrameView() {
181
        num++;
182
        createListeners();
183
    }
184
    
185
    protected void createListeners() {
186
            viewDocListener = new ViewDocListener();
187
            ownMapContextListener = new OwnMapContextListener();
188
    }
189

    
190
    /**
191
     * Returns a description of the FFrame
192
     * 
193
     * @return Description.
194
     */
195
    public String toString() {
196
        if (getView() == null) {
197
            return "FFrameView " + num + ": " + "Vacio";
198
        }
199

    
200
        return "FFrameView " + num + ": " + getView().getName();
201
    }
202

    
203
    /**
204
     * Sets the scale of the MapContext contained in this FFrameView
205
     * 
206
     * @param d Scale to be set
207
     */
208
    public void setScale(double d) {
209
            if (getMapContext()!=null) {
210
                    getMapContext().setScaleView((long) d);
211
            }
212
    }
213

    
214
    /**
215
     * Sets a new Envelope on the MapContext contained in
216
     * this FFrameView
217
     * 
218
     * @param r Envelope to be set
219
     */
220
    public void setNewEnvelope(Envelope r) {
221
            getMapContext().getViewPort().setEnvelope(r);
222
            updateScaleCtrl();
223
    }
224
    
225
    /**
226
     * Calculates the resolution (measured on dots per inch, DPI) to be
227
     * considered to draw the FFrameView on screen. It is calculated by
228
     * dividing the width (in pixels) of the FFrame divided by the width
229
     * in inches of the paper.
230
     */
231
    protected double getDrawPaperDPI() {
232
            AffineTransform at = null;
233
            if (getLayoutContext()!=null) {
234
                    at = getLayoutContext().getAT();
235
            }
236
            return (2.54*getBoundingBox(at).width)/getBoundBox().width;        
237
    }
238

    
239
    /**
240
     * Returns the MapContext contained in this FFrameView, which is
241
     * usually a clone of the associated View. This MapContext
242
     * may be synchronized with the View one, depending on the
243
     * scale type that has been set (see {{@link #getTypeScale()}.
244
     * 
245
     * @return The mapContext object
246
     */
247
    public MapContext getMapContext() {
248
        return mapContext;
249
    }
250

    
251
    /**
252
     * Sets the quality of the visualization of the FFrame on screen.
253
     * Valid values include {@link #DRAFT} and {@link #PRESENTATION}.
254
     * Draft will disable the frame normal drawing, which will be
255
     * replaced by an empty rectangle only showing the name of the
256
     * frame.  
257
     * 
258
     * @param q Integer representing the quality.
259
     */
260
    public void setQuality(int q) {
261
        quality = q;
262
    }
263

    
264
    /**
265
     * Gets the quality of the visualization of the FFrame on screen.
266
     * Valid values include {@link #DRAFT} and {@link #PRESENTATION}.
267
     * Draft will disable the frame normal drawing, which will be
268
     * replaced by an empty rectangle only showing the name of the
269
     * frame.  
270
     * 
271
     * @param q The selected quality
272
     */
273
    public int getQuality() {
274
        return quality;
275
    }
276

    
277
    /**
278
     * Sets the MapContext associated with this FFrameView, which will
279
     * be used to clone the layers and synchronize the FFrameView with
280
     * the associated View 
281
     * 
282
     * @param viewMapContext
283
     */
284
    public void setViewMapContext(MapContext viewMapContext) {
285
            Envelope oldEnvelope = null;
286
            if (mapContext!=null) {
287
                    clearOwnListeners(mapContext);
288
                    if (mapContext.getViewPort()!=null) {
289
                            oldEnvelope = mapContext.getViewPort().getEnvelope();
290
                    }
291
            }
292
            try {
293
                    if (syncLayers){
294
                            mapContext =
295
                                            viewMapContext.createNewFMap(
296
                                                            (ViewPort) viewMapContext.getViewPort().clone());
297
                    }
298
                    else {
299
                            mapContext = viewMapContext.cloneFMap();
300
                            mapContext.setViewPort((ViewPort) viewMapContext
301
                                            .getViewPort().clone());
302
                    }
303
                    ViewPort newViewPort = getMapContext().getViewPort();
304
                    if (!syncExtents && oldEnvelope!=null) {
305
                            // if extent is not synced with the view, restore the previous
306
                            // envelope if existing
307
                            newViewPort.setEnvelope(oldEnvelope);
308
                    }
309
                    AffineTransform at;
310
                    if (getLayoutContext()!=null) {
311
                            at = getLayoutContext().getAT();
312
                    }
313
                    else {
314
                            at = null;
315
                    }
316
                    newViewPort.setImageSize(new Dimension((int) getBoundingBox(at).width,
317
                                    (int) getBoundingBox(at).height));
318
                    newViewPort.setDPI(getDrawPaperDPI());
319
                    setListeners();
320
                    updateScaleCtrl();
321
                    setTocModel();
322
            } catch (CloneNotSupportedException e1) {
323
                    NotificationManager.addError("Excepci?n :", e1);
324
            }
325

    
326
    }
327

    
328
    /**
329
     * Sets the View associated with this FFrameView, which will
330
     * be used to clone the MapContext and the layers. It will
331
     * also used to synchronize the FFrameView with
332
     * the associated View, depending on the selected scle type 
333
     * 
334
     * @param viewMapContext
335
     */
336
    public void setView(ViewDocument dvd) {
337
            ViewDocument oldDoc = viewDocument;
338
            if (oldDoc!=null) {
339
                    if (oldDoc.getMapContext()!=null) {
340
                            clearViewListeners(oldDoc.getMapContext());
341
                    }
342
            }
343
        viewDocument = dvd;
344
        if (dvd!=null) {
345
            setViewMapContext(dvd.getMapContext());
346
        }
347
    }
348

    
349
    /**
350
     * Gets the associated View
351
     * 
352
     * @return The associated view
353
     * @see {@link #setView(ViewDocument)}
354
     */
355
    public ViewDocument getView() {
356
        return viewDocument;
357
    }
358

    
359
    /**
360
     * Draws the FFrameView on the provided Graphics, according to the
361
     * provided affine transform and the visible rectangle.
362
     * 
363
     * @param g Graphics2D
364
     * @param at Affine transform to translate sheet coordinates (in cm)
365
     *                                 to screen coordinates (in pixels)
366
     * @param visibleLayoutDocRect visible rectangle
367
     * @param imgBase Image used to speed up the drawing process
368
     */
369
    public void draw(Graphics2D g, AffineTransform at, Rectangle2D visibleLayoutDocRect, BufferedImage imgBase) {
370
        Rectangle2D.Double fframeViewRect = getBoundingBox(at);
371
        Rectangle2D.Double visibleArea = (Rectangle2D.Double) getVisibleRect(visibleLayoutDocRect, fframeViewRect);
372
        if (visibleArea==null) {
373
                return;
374
        }
375
        preDraw(g, fframeViewRect, visibleArea);
376
        if (getMapContext() == null) {
377
                drawEmpty(g);
378
        } else {
379
                if (FLayoutUtilities.hasEditingLayers(getView())) {
380

    
381
                        /*
382
                         * We are not drawing if any layer is in editing mode
383
                         */
384
                        drawMessage(g, Messages.getText(
385
                                        "_Cannot_draw_view_if_layers_in_editing_mode"));
386

    
387
                } else {
388
                        if (getQuality() == PRESENTATION) {
389
                                try {
390
                                        drawPresentation(g, at, fframeViewRect, visibleArea, imgBase);
391
                                } catch (Exception exc) {
392
                                        drawMessage(g, FLayoutFunctions.getLastMessage(exc));
393
                                }
394

    
395
                        } else {
396
                                drawDraft(g);
397
                        }               
398
                }
399
        }
400
        postDraw(g, fframeViewRect, at); 
401
        if (showGrid && grid != null) {           
402
            grid.draw(g, at, visibleLayoutDocRect, imgBase);
403
        }    
404
    }
405
    
406
    private void drawMessage(Graphics2D g, String msg) {
407
        
408
        Rectangle2D r = getBoundingBox(null);
409
        g.setColor(Color.lightGray);
410
        g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(),
411
            (int) r.getHeight());
412
        g.setColor(Color.darkGray);
413
        g.setStroke(new BasicStroke(2));
414
        g.drawRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(),
415
            (int) r.getHeight());
416
        g.setColor(Color.black);
417

    
418
        int scale = (int) (r.getWidth() / 24);
419
        Font f = new Font("SansSerif", Font.PLAIN, scale);
420
        g.setFont(f);
421
        if (msg==null) {
422
                msg = Messages.getText("error");
423
        }
424
        g.drawString(msg, (int) (r.getCenterX() - ((msg.length() * scale) / 4)),
425
                        (int) (r.getCenterY()));
426
    }
427

    
428
    /**
429
     * Gets the visible envelope, in map coordinates
430
     * 
431
     * @param fframeViewRect Rectangle defining the bounding box of the
432
     * FFrameView, in screen coordinates
433
     * @param visiblefframeViewRect Rectangle defining the bounding box
434
     * of the visible area of the fframeView, in screen coordinates
435
     * @return
436
     */
437
    protected Envelope getVisibleEnvelope(Rectangle2D.Double fframeViewRect,
438
            Rectangle2D.Double visiblefframeViewRect) {
439
            Envelope oldEnv = getMapContext().getViewPort().getAdjustedEnvelope();
440
            double widthFactor = ((int)visiblefframeViewRect.width) / fframeViewRect.width;
441
            double heightFactor = ((int)visiblefframeViewRect.height) / fframeViewRect.height;
442
            
443
            double newWidth = oldEnv.getLength(0)*widthFactor;
444
            double newHeight = oldEnv.getLength(1)*heightFactor;
445
        
446
        double translateX = visiblefframeViewRect.x - fframeViewRect.x;
447
        double translateY = visiblefframeViewRect.y - fframeViewRect.y;
448
        double translateFactorX = translateX / fframeViewRect.width;
449
        double translateFactorY = translateY / fframeViewRect.height;
450
        
451
        double newX = oldEnv.getMinimum(0) + translateFactorX*oldEnv.getLength(0);
452
        double newMaxY =  oldEnv.getMaximum(1) - translateFactorY*oldEnv.getLength(1);
453
        double newMaxX = newX + newWidth;
454
        double newY = newMaxY - newHeight;
455

    
456
        Envelope newEnv = null;
457
                try {
458
                        newEnv = geomManager.createEnvelope(newX, newY, newMaxX, newMaxY, SUBTYPES.GEOM2D);
459
                } catch (CreateEnvelopeException e) {
460
                        logger.error("Error calculating visible extent", e);
461
                }
462
        return newEnv;
463
                    
464
    }
465
    
466
    protected void drawPresentation(
467
        Graphics2D g,
468
        AffineTransform affineTransform,
469
        Rectangle2D.Double fframeViewRect,
470
        Rectangle2D.Double visibleRect,
471
        BufferedImage imgBase) throws Exception {
472
            
473
            b_drawing = true;
474
            int drawWidth = (int)visibleRect.width;
475
            int drawHeight = (int)visibleRect.height;
476

    
477
            Envelope oldEnvelope = null;
478
        if (!visibleRect.equals(fframeViewRect)) {
479
                // if visible area is smaller than the fframe, we will only draw this area,
480
                // so we need to tell the ViewPort the image size and extent for drawing,
481
                // and restore the real extent after drawing
482
            oldEnvelope = getMapContext().getViewPort().getEnvelope();
483
            if (oldEnvelope==null) {
484
                    return;
485
            }
486

    
487
                Envelope newEnvelope = getVisibleEnvelope(fframeViewRect, visibleRect);
488
                // image size must be set before the envelope, as it has influence on the adjustedExtent
489
                getMapContext().getViewPort().setImageSize(new Dimension(drawWidth, drawHeight));
490
                getMapContext().getViewPort().setEnvelope(newEnvelope);
491
        }
492
        else {
493
                getMapContext().getViewPort().setImageSize(new Dimension(drawWidth, drawHeight));
494
                getMapContext().getViewPort().refreshExtent();
495
        }
496
        
497
        // map origin should be calculated using the full fframeview, as the visible position will be relative
498
        Point mapOrigin = new Point((int)fframeViewRect.getMinX(), (int)fframeViewRect.getMaxY());
499

    
500
        // paint the MapContext on m_image, if not already cached
501
        createImage(affineTransform, drawWidth, drawHeight, mapOrigin);
502

    
503
        //Draw the created image
504
        drawImage(g, m_image, visibleRect);
505
        
506
        if (oldEnvelope!=null) {
507
                // restore real envelope and image size
508
                getMapContext().getViewPort().setImageSize(new Dimension((int)fframeViewRect.width, (int) fframeViewRect.height));
509
                getMapContext().getViewPort().setEnvelope(oldEnvelope);
510
        }
511
        
512
        scaleAnt = affineTransform.getScaleX();
513
        origin = mapOrigin;
514
        b_drawing = false;
515
    }
516
    
517
    protected void createImage(AffineTransform affineTransform,
518
                    int width, int height, Point mapOrigin) throws ReadException, MapContextException {
519
            ViewPort viewPort = this.getMapContext().getViewPort();
520

    
521
        //If the image has to be created...
522
            if (origin == null ||
523
                            !origin.equals(mapOrigin) ||
524
                            affineTransform.getScaleX() != scaleAnt ||
525
                            m_image == null ||
526
                            !b_validCache) { 
527

    
528
                    viewPort.setDPI(getDrawPaperDPI());
529
                viewPort.setImageSize(new Dimension(width, height)); 
530
            
531
            m_image =
532
                    new BufferedImage(
533
                                    width,
534
                                    height,
535
                                    BufferedImage.TYPE_INT_ARGB);
536

    
537
            Graphics2D gimg = (Graphics2D) m_image.createGraphics();
538
            getMapContext().draw(m_image, gimg, getScale());
539
            gimg.dispose();
540
            b_validCache = true;
541
        } 
542

    
543
    }
544
    
545
    protected void drawImage(Graphics2D g, BufferedImage image,
546
                    Rectangle2D.Double visibleRectangle) {
547

    
548
            Color theBackColor = getMapContext().getViewPort().getBackColor();
549
        if (theBackColor != null) {
550
            g.setColor(theBackColor);
551
            g.fillRect((int) visibleRectangle.x, (int) visibleRectangle.y,
552
                            (int)visibleRectangle.width,
553
                            (int)visibleRectangle.height);
554
        }
555
        g.drawImage(m_image, 
556
                        (int) visibleRectangle.x,
557
                        (int) visibleRectangle.y,
558
                        null);            
559
    }
560

    
561
    protected void preDraw(Graphics2D g, Rectangle2D.Double fframeViewRect, Rectangle2D.Double visibleRect){
562
            originalGraphicsAT = (AffineTransform) g.getTransform().clone();
563
            
564
        if (g.getClipBounds() != null) {
565
            originalClip = (Rectangle) g.getClipBounds().clone();
566
        }
567
        AffineTransform rotationAT = getRotationAT();
568
        if (rotationAT!=null) {
569
                g.transform(rotationAT);
570
        }
571
        g.setClip((int) visibleRect.getMinX(), (int) visibleRect.getMinY(),
572
            (int) visibleRect.getWidth(), (int) visibleRect.getHeight());
573
    }
574
    
575
    protected void postDraw(Graphics2D g, Rectangle2D.Double fframeViewRect, AffineTransform at){
576
            g.setTransform(originalGraphicsAT);
577
        if (getMapContext() != null) {
578
            setATMap(getMapContext().getViewPort().getAffineTransform());
579
        }
580
        if (originalClip != null) {
581
            g.setClip(originalClip.x, originalClip.y, originalClip.width, originalClip.height);
582
        }            
583
    }
584
    
585

    
586
    /**
587
     * @deprecated Use {@link #postDraw(Graphics2D, java.awt.geom.Rectangle2D.Double, AffineTransform)} instead.
588
     */
589
    @Deprecated
590
    protected void postDraw(Graphics2D g, Rectangle2D.Double rectangleLayout, Rectangle2D rectangleView, BufferedImage imgBase, Rectangle originalClip, AffineTransform at) {
591
            postDraw(g, rectangleLayout, at);
592
            
593
    }
594
    
595
    /**
596
     * @deprecated Use {@link #preDraw(Graphics2D, java.awt.geom.Rectangle2D.Double, java.awt.geom.Rectangle2D.Double) instead
597
     */
598
    @Deprecated
599
    protected Rectangle preDraw(Graphics2D g, Rectangle2D.Double rectangleLayout){
600
            Rectangle originalClip = null;
601
        if (g.getClipBounds() != null) {
602
            originalClip = (Rectangle) g.getClipBounds().clone();
603
        }
604
            preDraw(g, rectangleLayout, rectangleLayout);
605
            return originalClip;
606
    }
607

    
608
    public void print(Graphics2D g, AffineTransform at, Geometry geom,
609
        PrintAttributes printAttributes) {
610
        Rectangle2D.Double rectangleLayout = getBoundingBox(at);  
611
        
612
        preDraw(g, rectangleLayout, rectangleLayout);
613
        print(g, at, printAttributes);
614
        postDraw(g, rectangleLayout, at);
615
        if (showGrid && grid != null) {
616
            grid.print(g, at, geom, printAttributes);
617
        }    
618
    }
619

    
620
    protected void print(Graphics2D g, AffineTransform at, PrintAttributes printAttributes) {
621
        Rectangle2D.Double layoutRectangle = getBoundingBox(at);
622
        
623
        // FIXME: should we clone the mapcontext and viewport before printing ??
624
        // otherwise we will probably have unexpected results if the user modifies
625
        // the layout while printing (answer: not an issue at the moment as printing is
626
        // a blocking operation)
627
        ViewPort viewPort = this.getMapContext().getViewPort();
628
        
629
        Point2D old_offset = viewPort.getOffset();
630
        Dimension old_imgsize = viewPort.getImageSize();
631
        
632
        viewPort.setOffset(new Point2D.Double(layoutRectangle.x, layoutRectangle.y));
633
        viewPort.setImageSize(new Dimension((int) layoutRectangle.width, (int) layoutRectangle.height));
634

    
635
        //Draw the backgroung color of the map
636
        Color theBackColor = viewPort.getBackColor();
637
        if (theBackColor != null) {
638
            g.setColor(theBackColor);
639
            g.fillRect((int) layoutRectangle.x, (int) layoutRectangle.y, viewPort
640
                    .getImageWidth(), viewPort
641
                    .getImageHeight());
642
        }        
643
        
644
        //Print the map
645
        try {
646
            this.getMapContext().print(g, getScale(), printAttributes);
647
        } catch (ReadException e) {
648
            NotificationManager.addError(e.getMessage(), e);
649
        } catch (MapContextException e) {
650
            NotificationManager.addError(e.getMessage(), e);
651
        }      
652
        
653
        // Restore offset, imgsize
654
        viewPort.setOffset(old_offset);
655
        viewPort.setImageSize(old_imgsize);
656
    }
657

    
658
    /**
659
     * Rellena la unidad de medida en la que est? la vista.
660
     * 
661
     * @param i
662
     *            entero que representa la unidad de medida de la vista.
663
     */
664
    public void setMapUnits(int i) {
665
        mapUnits = i;
666
    }
667

    
668
    /**
669
     * Obtiene la unidad de medida en la que est? la vista.
670
     * 
671
     * @return Unidad de medida.
672
     */
673
    public int getMapUnits() {
674
        return mapUnits;
675
    }
676

    
677
    /**
678
     * Devuelve la escala seg?n el tipo de escala que se haya seleccionado al
679
     * a?adida la vista.
680
     * 
681
     * @return escala.
682
     */
683
    public long getScale() {
684
            return (long) getMapContext().getScaleView();
685
    }
686

    
687
    /**
688
     * Inserta la imagen para repintar el FFrameView.
689
     * 
690
     * @param bi
691
     *            Imagen para repintar.
692
     */
693
    public void setBufferedImage(BufferedImage bi) {
694
        m_image = bi;
695
    }
696

    
697
    /**
698
     * Devuelve la imagen para repintar.
699
     * 
700
     * @return Imagen para repintar.
701
     */
702
    public BufferedImage getBufferedImage() {
703
        return m_image;
704
    }
705

    
706
    /**
707
     * Devuelve la MAtriz de transformaci?n utilizada por la FFrameView.
708
     * 
709
     * @return MAtriz de transformaci?n.
710
     */
711
    public AffineTransform getATMap() {
712
        return mapAT;
713
    }
714

    
715
    /**
716
     * Inserta la matriz de transformaci?n.
717
     * 
718
     * @param transform
719
     *            Matriz de transformaci?n.
720
     */
721
    public void setATMap(AffineTransform transform) {
722
        mapAT = transform;
723
    }
724

    
725
    /**
726
     * Inserta el proyecto.
727
     * 
728
     * @param p
729
     *            Proyecto.
730
     */
731
    public void setProject(Project p) {
732
        project = p;
733
    }
734

    
735
    /**
736
     * @see org.gvsig.app.project.documents.layout.fframes.IFFrame#getNameFFrame()
737
     */
738
    public String getNameFFrame() {
739
        return PluginServices.getText(this, "Vista") + num;
740
    }
741

    
742
    public String getName() {
743
        return PERSISTENCE_DEFINITION_NAME;
744
    }
745

    
746
    /**
747
     * DOCUMENT ME!
748
     * 
749
     * @param arg0
750
     *            DOCUMENT ME!
751
     * 
752
     * @return DOCUMENT ME!
753
     */
754
    public boolean compare(Object arg0) {
755
        if (!(arg0 instanceof FFrameView)) {
756
            return false;
757
        }
758

    
759
        if (!this.getName().equals(((FFrameView) arg0).getName())) {
760
            return false;
761
        }
762

    
763
        if (Math.abs(this.getBoundBox().getWidth()
764
            - (((FFrameView) arg0).getBoundBox().getWidth())) > 0.05) {
765
            return false;
766
        }
767
        if (Math.abs(this.getBoundBox().getHeight()
768
            - (((FFrameView) arg0).getBoundBox().getHeight())) > 0.05) {
769
            return false;
770
        }
771

    
772
        if (!this.toString().equals(((FFrameView) arg0).toString())) {
773
            return false;
774
        }
775

    
776
        if (this.getMapContext() != null
777
            && !this.getMapContext()
778
                .equals(((FFrameView) arg0).getMapContext())) {
779
            return false;
780
        }
781

    
782
        if (this.getRotation() != ((FFrameView) arg0).getRotation()) {
783
            return false;
784
        }
785
        return true;
786
    }
787
    
788
    public void updateScaleCtrl() {
789
            NewStatusBar statusbar = PluginServices.getMainFrame().getStatusBar();
790
            MapContext mapContext = this.getMapContext();
791
            if (mapContext==null) {
792
                    return;
793
            }
794
            statusbar.setMessage("units",
795
                            PluginServices.getText(this, mapContext.getDistanceName()));
796
            String scale; 
797
            if (fixedScale!=null && getScaleType()==SCALE_TYPE.FIXED_SCALE) {
798
                    // prefer fixedScale as getScaleView() may offer slight differences
799
                    // because the influence of the adjusted envelope
800
                    scale = String.valueOf(fixedScale.longValue());
801
            }
802
            else {
803
                    scale = String.valueOf(getMapContext().getScaleView());
804
            }
805
            statusbar.setControlValue("layout-view-change-scale",
806
                            scale);
807
            IProjection proj = mapContext.getViewPort().getProjection();
808
            if (proj != null) {
809
                    statusbar.setMessage("projection", proj.getAbrev());
810
            } else {
811
                    statusbar.setMessage("projection", "");
812
            }
813
    }
814

    
815
    public void fullExtent() throws ReadException {
816
        setNewEnvelope(getMapContext().getFullEnvelope());
817
    }
818

    
819
    public void setPointsToZoom(Point2D px1, Point2D px2) {
820
        p1 = px1;
821
        p2 = px2;
822
    }
823

    
824
    public void movePoints(Point2D px1, Point2D px2) {
825
        double difX = -px2.getX() + px1.getX();
826
        double difY = -px2.getY() + px1.getY();
827
        if (p1 != null) {
828
            p1.setLocation(p1.getX() + difX, p1.getY() + difY);
829
            p2.setLocation(p2.getX() + difX, p2.getY() + difY);
830
        }
831
    }
832

    
833
    /**
834
     * This method deals with places where this fframeview and the cloned
835
     * fframeview (frame) are registered as listeners. The goal should be
836
     * leaving the cloned instance (frame) as listener in the same way
837
     * that 'this' instance is doing.
838
     */
839
    protected void cloneActions(FFrameView frame) {
840
    }
841

    
842
    public Object clone() throws CloneNotSupportedException {
843
            Document d = ProjectManager.getInstance().getCurrentProject().getDocuments().get(0);
844
        FFrameView frame = (FFrameView) super.clone();
845
        frame.createListeners(); // necessary to create the listeners within the right scope
846
        frame.setView(this.getView());
847

    
848
        if (grid != null) {
849
            FFrameGrid newGrid = (FFrameGrid) this.grid.clone();
850
            newGrid.setFFrameDependence(frame);
851
            frame.setGrid(newGrid);
852
        }
853
        cloneActions(frame);
854
        return frame;
855
    }
856

    
857
    public void setGrid(IFFrame grid) {
858
        this.grid = grid;
859
        this.grid.setRotation(this.getRotation());
860
    }
861

    
862
    public IFFrame getGrid() {
863
        return this.grid;
864
    }
865

    
866
    public void setRotation(double rotation) {
867
        super.setRotation(rotation);
868
        if (grid != null) {
869
            grid.setRotation(rotation);
870
        }
871
    }
872

    
873
    public void showGrid(boolean b) {
874
        showGrid = b;
875
    }
876

    
877
    public boolean isShowGrid() {
878
        return showGrid;
879
    }
880

    
881
    public void refreshOriginalExtent() {
882
    }
883

    
884
    public static void registerPersistent() {
885
        PersistenceManager manager = ToolsLocator.getPersistenceManager();
886
        if (manager.getDefinition(PERSISTENCE_DEFINITION_NAME) == null) {          
887
            DynStruct definition =
888
                manager.addDefinition(FFrameView.class,
889
                    PERSISTENCE_DEFINITION_NAME,
890
                    "FFrameView persistence definition", null, null);
891
            definition.extend(manager
892
                .getDefinition(FFrame.PERSISTENCE_DEFINITION_NAME));
893
            definition.addDynFieldInt(QUALITY_FIELD).setMandatory(true);
894
            definition.addDynFieldInt(MAPUNITS_FIELD).setMandatory(true);
895
            definition.addDynFieldDouble(SCALE_FIELD).setMandatory(false);
896
            definition.addDynFieldObject(VIEW_FIELD)
897
                .setClassOfValue(ViewDocument.class).setMandatory(false);
898
            definition.addDynFieldObject(ENVELOPE_FIELD)
899
                .setClassOfValue(Envelope.class).setMandatory(false);
900
            definition.addDynFieldBoolean(SHOWGRID_FIELD).setMandatory(true);
901
            definition.addDynFieldObject(GRID_FIELD)
902
                .setClassOfValue(IFFrame.class).setMandatory(false);
903
            definition.addDynFieldBoolean(HAS_TOC_FIELD).setMandatory(false);
904
            definition.addDynFieldBoolean(EXTENT_SYNC_FIELD).setMandatory(false);
905
            definition.addDynFieldBoolean(LAYER_SYNC_FIELD).setMandatory(false);
906
            definition.addDynFieldInt(SCALE_TYPE_FIELD).setMandatory(false);
907
            // unused fields, kept for backward compatibility
908
            definition.addDynFieldInt(MODE_FIELD).setMandatory(false);
909
            definition.addDynFieldInt(TYPESCALE_FIELD).setMandatory(false);
910
            definition.addDynFieldBoolean(BLINKED_FIELD).setMandatory(false);
911
            definition.addDynFieldObject(MAPCONTEXT_FIELD)
912
            .setClassOfValue(MapContext.class).setMandatory(false);
913
            definition.addDynFieldInt(VIEWING_FIELD).setMandatory(false);
914
            definition.addDynFieldInt(EXTENSION_FIELD).setMandatory(false);
915
        }
916
    }
917

    
918
    @Override
919
    public void loadFromState(PersistentState state)
920
        throws PersistenceException {
921
        super.loadFromState(state);
922
        b_frameInitialized = false;
923
        if (state.hasValue(EXTENT_SYNC_FIELD)) {
924
                syncExtents = state.getBoolean(EXTENT_SYNC_FIELD);
925
        }
926
        else {
927
                syncExtents = true;
928
        }
929
        if (state.hasValue(LAYER_SYNC_FIELD)) {
930
                syncLayers = state.getBoolean(LAYER_SYNC_FIELD);
931
        }
932
        else {
933
                syncLayers = true;
934
        }
935
        double layoutScale = state.getDouble(SCALE_FIELD);
936
            Envelope envelope = (Envelope) state.get(ENVELOPE_FIELD); 
937

    
938
        if (state.hasValue(SCALE_TYPE_FIELD)) {
939
                int value = state.getInt(SCALE_TYPE_FIELD);
940
                if (value==SCALE_TYPE.FIXED_EXTENT.ordinal()) {
941
                        scaleType = SCALE_TYPE.FIXED_EXTENT;
942
                        fixedExtent = envelope;
943
                }
944
                else if (value==SCALE_TYPE.FIXED_SCALE.ordinal()) {
945
                        scaleType = SCALE_TYPE.FIXED_SCALE;
946
                        fixedScale = new Double(layoutScale);
947
                }
948
                // else use the default value
949
        }
950
        quality = state.getInt(QUALITY_FIELD);
951
        mapUnits = state.getInt(MAPUNITS_FIELD);;
952
        viewDocument = (ViewDocument) state.get(VIEW_FIELD);
953
        if (state.hasValue(HAS_TOC_FIELD)) {
954
                this.b_hasToc = state.getBoolean(HAS_TOC_FIELD);
955
        }        
956
        if (viewDocument!=null) {
957
                this.setView(viewDocument);
958
                // it is crucial to don't persist the MapContext and get a cloned one from the View instead,
959
                // as the cloned instance is different from the one created using persistence. In particular,
960
                // the cloned one will share the EventBuffer with the original one, while persistence would
961
                // create 2 separate EventBuffers, which will then have a very stange behaviour
962
        }
963
        if (getMapContext()!=null) {
964
                getMapContext().setScaleView((long)layoutScale);
965
                getMapContext().getViewPort().setEnvelope(envelope);
966
                if (this.getLayoutContext()!=null) {
967
                        this.getLayoutContext().setTocModel(getMapContext());
968
                }
969

    
970
        }
971
        showGrid = state.getBoolean(SHOWGRID_FIELD);
972
        grid = (IFFrame) state.get(GRID_FIELD);
973
    }
974

    
975
    @Override
976
    public void saveToState(PersistentState state) throws PersistenceException {
977
        super.saveToState(state);
978
        state.set(EXTENT_SYNC_FIELD, syncExtents);
979
        state.set(LAYER_SYNC_FIELD, syncLayers);
980
        state.set(QUALITY_FIELD, quality);
981
        state.set(MAPUNITS_FIELD, mapUnits);
982
        state.set(VIEW_FIELD, viewDocument);
983
        state.set(HAS_TOC_FIELD, b_hasToc);
984
        state.set(SCALE_TYPE_FIELD, scaleType.ordinal());
985

    
986
        if (getMapContext() != null
987
            && getMapContext().getViewPort().getEnvelope() != null) {
988
                if (scaleType==SCALE_TYPE.FIXED_SCALE && fixedScale!=null) {
989
                        state.set(SCALE_FIELD, (double)fixedScale);
990
                }
991
                else {
992
                        state.set(SCALE_FIELD, (double)getMapContext().getScaleView());        
993
                }
994
                if (scaleType == SCALE_TYPE.FIXED_EXTENT && fixedExtent!=null) {
995
                        state.set(ENVELOPE_FIELD, fixedExtent);
996
                }
997
                else {
998
                        state.set(ENVELOPE_FIELD, getMapContext().getViewPort()
999
                        .getAdjustedEnvelope());        
1000
                }
1001
        }
1002

    
1003
        state.set(SHOWGRID_FIELD, showGrid);
1004
        state.set(GRID_FIELD, grid);
1005
    }
1006
    
1007
    @Override
1008
    public void setBoundBox(Rectangle2D r) {
1009
            super.setBoundBox(r);
1010
            if (getMapContext()!=null) {
1011
                    AffineTransform at = this.getLayoutContext().getAT();
1012
                    long scale = getMapContext().getScaleView();
1013
                    getMapContext().getViewPort().setImageSize(
1014
                                    new Dimension((int)getBoundingBox(at).getWidth(), (int)getBoundingBox(at).getHeight()));
1015
                    getMapContext().getViewPort().setDPI(getDrawPaperDPI());
1016
                    if (getScaleType()==SCALE_TYPE.FIXED_SCALE) {
1017
                            getMapContext().setScaleView((long) scale);
1018
                    }
1019
                    updateScaleCtrl();
1020
                    refresh();
1021
            }
1022
    }   
1023

    
1024
    /**
1025
     * Gets the rotation of the frame
1026
     * 
1027
     * @return Rotation in degrees
1028
     */
1029
    public double getMapRotation() {
1030
        return 0;
1031
    }
1032
    
1033
        protected void invalidateLayout() {
1034
                b_validCache = false;
1035
                if (getLayoutContext()!=null) {
1036
                        getLayoutContext().notifAllObservers();
1037
                }
1038
        observers.notifyObservers(this, 
1039
                new DefaultLayoutNotification(LayoutNotification.LAYOUT_REFRESH));
1040
        }
1041
        
1042
        protected void invalidateToc() {
1043
                if (getLayoutContext()!=null) {
1044
                        getLayoutContext().notifyTocUpdated(TocModelChangedNotification.Type.MODEL_CHANGED);
1045
                }
1046
        }
1047

    
1048
        public void refresh() {
1049
        // FIXME: what should we do here? do we really need to invalidate cache??
1050
            b_validCache = false;
1051
        }
1052
    
1053
    protected void resetListeners() {
1054
                if (this.getMapContext()!=null) {
1055
                        clearOwnListeners(this.getMapContext());
1056
                }
1057
                if (this.getView()!=null && this.getView().getMapContext()!=null) {
1058
                        clearViewListeners(this.getView().getMapContext());
1059
                }
1060
            setListeners();
1061
    }
1062
    
1063
    protected void setListeners() {
1064
            if (getView()!=null) {
1065
                    if (syncLayers) {
1066
                            getView().getMapContext().addLayerListener(viewDocListener);
1067
                            getView().getMapContext().getLayers().addLayerCollectionListener(viewDocListener);
1068
                            getView().getMapContext().addAtomicEventListener(viewDocListener);
1069
                    }
1070
                    if (getExtentSynced()) {
1071
                            getView().getMapContext().getViewPort().addViewPortListener(viewDocListener);
1072
                    }
1073
            }
1074
            if (getMapContext()!=null) {
1075
                    getMapContext().addLayerListener(ownMapContextListener);
1076
                    getMapContext().getLayers().addLayerCollectionListener(ownMapContextListener);
1077
                    getMapContext().getViewPort().addViewPortListener(ownMapContextListener);
1078
            }
1079
    }
1080
    protected void clearOwnListeners(MapContext mapContext) {
1081
            mapContext.removeLayerListener(ownMapContextListener);
1082
            mapContext.getViewPort().removeViewPortListener(ownMapContextListener);
1083
            mapContext.getLayers().removeLayerCollectionListener(ownMapContextListener);
1084
    }
1085
    protected void clearViewListeners(MapContext mapContext) {
1086
            mapContext.removeLayerListener(viewDocListener);
1087
            mapContext.getViewPort().removeViewPortListener(viewDocListener);
1088
            mapContext.getLayers().removeLayerCollectionListener(viewDocListener);
1089
            mapContext.removeAtomicEventListener(viewDocListener);
1090
    }
1091
    
1092
    /*
1093
     * (non-Javadoc)
1094
     * @see org.gvsig.tools.dispose.Disposable#dispose()
1095
     */
1096
        public void dispose() {
1097
                try {
1098
                        if (this.getMapContext()!=null) {
1099
                                clearOwnListeners(this.getMapContext());
1100
                        }
1101
                        if (this.getView()!=null && this.getView().getMapContext()!=null) {
1102
                                clearViewListeners(this.getView().getMapContext());
1103
                        }
1104
                }
1105
                catch (Exception ex) {}
1106
                this.viewDocument = null;
1107
                this.mapContext = null;
1108
        }
1109

    
1110
        public void frameRemoved() {
1111
                if (mapContext!=null) {
1112
                        clearOwnListeners(mapContext);
1113
                }
1114
                if (this.getView()!=null && this.getView().getMapContext()!=null) {
1115
                        clearViewListeners(this.getView().getMapContext());
1116
                }
1117
                if (b_hasToc && getLayoutContext()!=null) {
1118
                        getLayoutContext().setTocModel(null);
1119
                }
1120
                m_image = null; // FIXME: we could instead move it to a LRU cache to keep the last N images
1121
        }
1122

    
1123
        public void frameAdded() {
1124
                setListeners();
1125
                setTocModel();
1126
                updateScaleCtrl();
1127
        }
1128
        
1129
        public void setHasToc(boolean hasToc) {
1130
                this.b_hasToc = hasToc;
1131
                setTocModel();
1132
        }
1133
        
1134
        protected void setTocModel() {
1135
                if (getLayoutContext()!=null) {
1136
                        if (b_hasToc && getMapContext()!=null) {
1137
                                getLayoutContext().setTocModel(getMapContext());
1138
                        }
1139
                        else {
1140
                                getLayoutContext().setTocModel(null);
1141
                        }
1142
                }
1143
        }
1144
        
1145
        @Override
1146
        protected void doSetSelected(int selectedStatus) {
1147
                boolean oldSelectedStatus = isSelected();
1148
                super.doSetSelected(selectedStatus);
1149
                if (!oldSelectedStatus && isSelected()) { // changed from not selected to selected
1150
                        setTocModel();
1151
                        updateScaleCtrl();
1152
                }
1153
        }
1154
        
1155
        public boolean getLayerSynced() {
1156
                return syncLayers;
1157
        }
1158

    
1159
        public void setLayerSynced(boolean synced) {
1160
        syncLayers = synced;
1161
        resetListeners();
1162
        }
1163

    
1164
        public boolean getExtentSynced() {
1165
                return syncExtents;
1166
        }
1167

    
1168
        public void setExtentSynced(boolean synced) {
1169
                syncExtents = synced;
1170
        resetListeners();
1171
        }
1172
        
1173
        /**
1174
         * Returns true if the newEnvelope represents a pan operation on oldEnvelope,
1175
         * (both extents have the same height and width)
1176
         */
1177
        public static boolean isPan(Envelope oldEnvelope, Envelope newEnvelope) {
1178
                if (oldEnvelope!=null && newEnvelope!=null) {
1179
                        double toleranceX = 0.00000001*Math.min(oldEnvelope.getLength(0), newEnvelope.getLength(0));
1180
                        double toleranceY = 0.00000001*Math.min(oldEnvelope.getLength(1), newEnvelope.getLength(1));
1181
                        
1182
                        // we consider it to be a pan if both lengths are equal 
1183
                        // (we use tolerance to avoid direct comparison of double values)
1184
                        if ( ((oldEnvelope.getLength(0)-newEnvelope.getLength(0))<toleranceX)
1185
                                        && ((oldEnvelope.getLength(1)-newEnvelope.getLength(1))<toleranceY) ) {
1186
                                return true;
1187
                        }
1188
                }
1189
                return false;
1190
        }
1191
        
1192
        /**
1193
         * Calculates the new extent for the FFrame. It is necessary to avoid
1194
         * scale changes when a pan is triggered from the view, as the different
1195
         * size factors from View/FFrameView introduces scale changes even for
1196
         * pans
1197
         * 
1198
         * @param newEnvelope
1199
         * @return
1200
         */
1201
        protected Envelope calculateNewExtent() {
1202
                Envelope newEnvelope = getView().getMapContext().getViewPort().getEnvelope();
1203
                Envelope oldViewEnvelope = null;
1204
                try {
1205
                        if (getView().getMapContext().getViewPort().getEnvelopes().hasPrevious()) {
1206
                                Rectangle2D r = getView().getMapContext().getViewPort().getEnvelopes().get();
1207
                                oldViewEnvelope = GeometryLocator.getGeometryManager().createEnvelope(r.getMinX(), r.getMinY(), r.getMaxX(), r.getMaxY(), SUBTYPES.GEOM2D);
1208
                        }
1209
                        if (isPan(oldViewEnvelope, newEnvelope)) {
1210
                                Envelope envelope = getMapContext().getViewPort().getAdjustedEnvelope();
1211
                                double shiftX = newEnvelope.getMinimum(0) - oldViewEnvelope.getMinimum(0);
1212
                                double shiftY = newEnvelope.getMinimum(1) - oldViewEnvelope.getMinimum(1);
1213

    
1214
                                double minX = envelope.getMinimum(0) + shiftX;
1215
                                double minY = envelope.getMinimum(1) + shiftY;
1216
                                double maxX = envelope.getMaximum(0) + shiftX;
1217
                                double maxY = envelope.getMaximum(1) + shiftY;
1218

    
1219
                                return GeometryLocator.getGeometryManager().createEnvelope(minX, minY, maxX, maxY, SUBTYPES.GEOM2D);
1220
                        }
1221
                }
1222
                catch (LocatorException e) {}
1223
                catch (CreateEnvelopeException e) {}
1224
                return newEnvelope;
1225
        }
1226

    
1227
        private class ViewDocListener
1228
        implements ViewPortListener, LegendListener, LayerCollectionListener, AtomicEventListener {
1229

    
1230
                public void extentChanged(ExtentEvent e) {
1231
                        if (!b_updating && getExtentSynced()) {
1232
                                if (!b_frameInitialized) {
1233
                                        b_frameInitialized = true;
1234
                                        return;
1235
                                }
1236
                                b_updating = true;
1237
                                if (getMapContext()!=null) {
1238
                                        if (scaleType==SCALE_TYPE.FIXED_EXTENT) {
1239
                                                getView().getMapContext().getViewPort().setEnvelope(fixedExtent);
1240
                                        }
1241
                                        else {
1242
                                                getMapContext().getViewPort().setEnvelope(calculateNewExtent());
1243
                                                if (scaleType==SCALE_TYPE.FIXED_SCALE) {
1244
                                                        getMapContext().setScaleView(Math.round(fixedScale));  
1245
                                                        getView().getMapContext().getViewPort().setEnvelope(getMapContext().getViewPort().getAdjustedEnvelope());
1246
                                                }
1247
                                                updateScaleCtrl();
1248
                                                invalidateLayout();
1249
                                        }
1250
                                }
1251
                                b_updating = false;
1252
                        }                        
1253
                }
1254

    
1255
                public void backColorChanged(ColorEvent e) {
1256
                        if (!b_updating && syncLayers) {
1257
                                if (getMapContext()!=null) {
1258
                                        b_updating = true;
1259
                                        mapContext.getViewPort().setBackColor(e.getNewColor());
1260
                                        invalidateLayout();
1261
                                        b_updating = true;
1262
                                }
1263
                        }
1264
                }
1265

    
1266
                public void projectionChanged(ProjectionEvent e) {
1267
                        if (!b_updating && getExtentSynced()) {
1268
                                if (getMapContext()!=null) {
1269
                                        b_updating = true;
1270
                                        getMapContext().getViewPort().setProjection(e.getNewProjection());
1271
                                        invalidateLayout();
1272
                                        // FIXME: force also a view redraw someway??
1273
                                        b_updating = false;
1274
                                }
1275
                        }
1276
                }
1277

    
1278
                public void conditionalRedraw() {
1279
                        if (!b_updating && syncLayers) {
1280
                                b_updating = true;
1281
                                invalidateLayout();
1282
                                // the view should also receive the event and update automatically
1283
                                b_updating = false;
1284
                        }                        
1285
                }
1286

    
1287
                public void legendChanged(LegendChangedEvent e) {
1288
                        conditionalRedraw();
1289
                        invalidateToc();
1290
                }
1291

    
1292
                public void layerAdded(LayerCollectionEvent e) {
1293
                        conditionalRedraw();
1294
                        invalidateToc();
1295
                }
1296

    
1297
                public void layerMoved(LayerPositionEvent e) {
1298
                        conditionalRedraw();
1299
                        invalidateToc();
1300
                }
1301

    
1302
                public void layerRemoved(LayerCollectionEvent e) {
1303
                        conditionalRedraw();
1304
                        invalidateToc();
1305
                }
1306

    
1307
                public void layerAdding(LayerCollectionEvent e)
1308
                                throws CancelationException {
1309
                        // nothing needed
1310
                }
1311

    
1312
                public void layerMoving(LayerPositionEvent e)
1313
                                throws CancelationException {
1314
                        // nothing needed
1315
                }
1316

    
1317
                public void layerRemoving(LayerCollectionEvent e)
1318
                                throws CancelationException {
1319
                        // nothing needed
1320
                }
1321

    
1322
                public void visibilityChanged(LayerCollectionEvent e)
1323
                                throws CancelationException {
1324
                        // AtomicEvent is catching visibility changes instead of this one,
1325
                        // as this event is not being received. Maybe is only triggered if the
1326
                        // visibility of the whole group changes??
1327
                        conditionalRedraw();
1328
                        invalidateToc();
1329
                }
1330

    
1331
                public void atomicEvent(AtomicEvent e) {
1332
                        boolean needRedraw = false;
1333
                        // not all the events require a fframeview redraw
1334
                        for (int i=e.getLayerEvents().length-1; i>=0; i--) {
1335
                                FMapEvent at = e.getEvent(i);
1336
                                if (at instanceof LayerEvent) {
1337
                                        if (at.getEventType()==LayerEvent.DRAW_VALUES_CHANGED) {
1338
                                                needRedraw = true;
1339
                                                break;
1340
                                        }
1341
                                }
1342
                        }
1343
                        if (needRedraw) {
1344
                                conditionalRedraw();
1345
                        }
1346
                        invalidateToc();
1347
                }
1348
        }
1349

    
1350
        private class OwnMapContextListener
1351
                implements ViewPortListener, LegendListener, LayerCollectionListener {
1352

    
1353
                public void extentChanged(ExtentEvent e) {
1354
                        if (!b_drawing && !b_updating) {
1355
                                b_updating = true;
1356
                                if (scaleType==SCALE_TYPE.FIXED_EXTENT) {
1357
                                        getMapContext().getViewPort().setEnvelope(fixedExtent);
1358
                                }
1359
                                else {
1360
                                        Envelope newEnvelope;
1361
                                        if (scaleType==SCALE_TYPE.FIXED_SCALE) {
1362
                                                getMapContext().setScaleView(Math.round(fixedScale));
1363
                                                newEnvelope = getMapContext().getViewPort().getAdjustedEnvelope();
1364
                                        }
1365
                                        else {
1366
                                                newEnvelope = e.getNewExtent();
1367
                                        }
1368
                                        if (getView()!=null) {
1369
                                                if (getExtentSynced()){
1370
                                                        getView().getMapContext().getViewPort().setEnvelope(newEnvelope);
1371
                                                }
1372
                                        }
1373
                                }
1374
                                updateScaleCtrl();
1375
                                invalidateLayout();
1376
                                b_updating = false;
1377
                        }                        
1378
                }
1379

    
1380
                public void backColorChanged(ColorEvent e) {
1381
                        if (!b_updating) {
1382
                                if (getView()!=null) {
1383
                                        b_updating = true;
1384
                                        if (getLayerSynced()) {
1385
                                                getView().getMapContext().getViewPort().setBackColor(e.getNewColor());
1386
                                        }
1387
                                        invalidateLayout();
1388
                                        b_updating = false;
1389
                                }
1390
                        }
1391
                }
1392

    
1393
                public void projectionChanged(ProjectionEvent e) {
1394
                        if (!b_updating && getExtentSynced()) {
1395
                                if (getView()!=null) {
1396
                                        b_updating = true;
1397
                                        if (getLayerSynced()) {
1398
                                                getView().getMapContext().getViewPort().setProjection(e.getNewProjection());
1399
                                        }
1400
                                        invalidateLayout();
1401
                                        // FIXME: force also a view redraw someway??
1402
                                        b_updating = false;
1403
                                }
1404
                        }
1405
                }
1406

    
1407
                public void conditionalRedraw() {
1408
                        if (!b_updating) {
1409
                                b_updating = true;
1410
                                invalidateLayout();
1411
                                // the view should also receive the event and update automatically
1412
                                b_updating = false;
1413
                        }
1414
                }
1415

    
1416
                public void legendChanged(final LegendChangedEvent e) {
1417
                        conditionalRedraw();
1418
                        invalidateToc();
1419
                }
1420

    
1421
                public void layerAdded(final LayerCollectionEvent e) {
1422
                        // necessary to set an envelope when the first layer is added
1423
                        if (!b_updating && getMapContext().getViewPort().getEnvelope()==null) {
1424
                                try {
1425
                                        b_updating = true;
1426
                                        fullExtent();
1427
                                        
1428
                                } catch (ReadException e1) {
1429
                                } finally {
1430
                                        b_updating = false;
1431
                                }
1432
                        }
1433
                        conditionalRedraw();
1434
                        invalidateToc();
1435
                }
1436

    
1437
                public void layerMoved(final LayerPositionEvent e) {
1438
                        conditionalRedraw();
1439
                        invalidateToc();
1440
                }
1441

    
1442
                public void layerRemoved(final LayerCollectionEvent e) {
1443
                        conditionalRedraw();
1444
                        invalidateToc();
1445
                }
1446

    
1447
                public void layerAdding(LayerCollectionEvent e)
1448
                                throws CancelationException {
1449
                        // nothing neededO
1450

    
1451
                }
1452

    
1453
                public void layerMoving(LayerPositionEvent e)
1454
                                throws CancelationException {
1455
                        // nothing needed
1456

    
1457
                }
1458

    
1459
                public void layerRemoving(LayerCollectionEvent e)
1460
                                throws CancelationException {
1461
                        // nothing needed
1462

    
1463
                }
1464

    
1465
                public void visibilityChanged(LayerCollectionEvent e)
1466
                                throws CancelationException {
1467
                        conditionalRedraw();
1468
                }
1469
        }
1470

    
1471
        public void setExtent(Envelope extent) {
1472
                if (getScaleType()==SCALE_TYPE.NORMAL) {
1473
                        getMapContext().getViewPort().setEnvelope(extent);
1474
                }
1475
        }
1476

    
1477
        public SCALE_TYPE getScaleType() {
1478
                return scaleType ;
1479
        }
1480

    
1481
        public void setScaleType(SCALE_TYPE scaleType) {
1482
                this.scaleType = scaleType;
1483
        }
1484
        
1485
        public void setScaleType(SCALE_TYPE scaleType, double fixedScale) {
1486
                if (scaleType == SCALE_TYPE.FIXED_SCALE) {
1487
                        this.scaleType = scaleType;
1488
                        this.fixedScale = new Double(fixedScale);
1489
                        setScale(fixedScale);
1490
                }
1491
        }
1492
        
1493
        public void setScaleType(SCALE_TYPE scaleType, Envelope fixedExtent) {
1494
                if (scaleType == SCALE_TYPE.FIXED_EXTENT) {
1495
                        this.scaleType = scaleType;
1496
                        this.fixedExtent  = fixedExtent;
1497
                        setNewEnvelope(fixedExtent);
1498
                }
1499
        }
1500

    
1501
        @Deprecated
1502
        public int getTypeScale() {
1503
                return AUTOMATICO;
1504
        }
1505

    
1506
        @Deprecated
1507
        public void setLinked(boolean b) {}
1508

    
1509
        @Deprecated
1510
        public boolean getLinked() {
1511
                return false;
1512
        }
1513

    
1514
        public void windowActivated() {
1515
                if (isSelected()
1516
                                && getLayoutContext().getSelectedFFrames(IFFrameUseFMap.class).length==1) {
1517
                        // update the scale control whenever the panel window gets activated,
1518
                        // as the control instance is shared for all the windows
1519
                        updateScaleCtrl();
1520
                }
1521
                
1522
        }
1523

    
1524
        public void windowClosed() {
1525
        }
1526
}