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 @ 324

History | View | Annotate | Download (50.2 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
        double oldDpi = viewPort.getDPI();
632
        
633
        viewPort.setOffset(new Point2D.Double(layoutRectangle.x, layoutRectangle.y));
634
        viewPort.setImageSize(new Dimension((int) layoutRectangle.width, (int) layoutRectangle.height));
635
        double dpi = PrintAttributes.PRINT_QUALITY_DPI[printAttributes.getPrintQuality()];
636
        viewPort.setDPI(dpi);
637

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

    
661
    }
662

    
663
    /**
664
     * Rellena la unidad de medida en la que est? la vista.
665
     * 
666
     * @param i
667
     *            entero que representa la unidad de medida de la vista.
668
     */
669
    public void setMapUnits(int i) {
670
        mapUnits = i;
671
    }
672

    
673
    /**
674
     * Obtiene la unidad de medida en la que est? la vista.
675
     * 
676
     * @return Unidad de medida.
677
     */
678
    public int getMapUnits() {
679
        return mapUnits;
680
    }
681

    
682
    /**
683
     * Devuelve la escala seg?n el tipo de escala que se haya seleccionado al
684
     * a?adida la vista.
685
     * 
686
     * @return escala.
687
     */
688
    public long getScale() {
689
            return (long) getMapContext().getScaleView();
690
    }
691

    
692
    /**
693
     * Inserta la imagen para repintar el FFrameView.
694
     * 
695
     * @param bi
696
     *            Imagen para repintar.
697
     */
698
    public void setBufferedImage(BufferedImage bi) {
699
        m_image = bi;
700
    }
701

    
702
    /**
703
     * Devuelve la imagen para repintar.
704
     * 
705
     * @return Imagen para repintar.
706
     */
707
    public BufferedImage getBufferedImage() {
708
        return m_image;
709
    }
710

    
711
    /**
712
     * Devuelve la MAtriz de transformaci?n utilizada por la FFrameView.
713
     * 
714
     * @return MAtriz de transformaci?n.
715
     */
716
    public AffineTransform getATMap() {
717
        return mapAT;
718
    }
719

    
720
    /**
721
     * Inserta la matriz de transformaci?n.
722
     * 
723
     * @param transform
724
     *            Matriz de transformaci?n.
725
     */
726
    public void setATMap(AffineTransform transform) {
727
        mapAT = transform;
728
    }
729

    
730
    /**
731
     * Inserta el proyecto.
732
     * 
733
     * @param p
734
     *            Proyecto.
735
     */
736
    public void setProject(Project p) {
737
        project = p;
738
    }
739

    
740
    /**
741
     * @see org.gvsig.app.project.documents.layout.fframes.IFFrame#getNameFFrame()
742
     */
743
    public String getNameFFrame() {
744
        return PluginServices.getText(this, "Vista") + num;
745
    }
746

    
747
    public String getName() {
748
        return PERSISTENCE_DEFINITION_NAME;
749
    }
750

    
751
    /**
752
     * DOCUMENT ME!
753
     * 
754
     * @param arg0
755
     *            DOCUMENT ME!
756
     * 
757
     * @return DOCUMENT ME!
758
     */
759
    public boolean compare(Object arg0) {
760
        if (!(arg0 instanceof FFrameView)) {
761
            return false;
762
        }
763

    
764
        if (!this.getName().equals(((FFrameView) arg0).getName())) {
765
            return false;
766
        }
767

    
768
        if (Math.abs(this.getBoundBox().getWidth()
769
            - (((FFrameView) arg0).getBoundBox().getWidth())) > 0.05) {
770
            return false;
771
        }
772
        if (Math.abs(this.getBoundBox().getHeight()
773
            - (((FFrameView) arg0).getBoundBox().getHeight())) > 0.05) {
774
            return false;
775
        }
776

    
777
        if (!this.toString().equals(((FFrameView) arg0).toString())) {
778
            return false;
779
        }
780

    
781
        if (this.getMapContext() != null
782
            && !this.getMapContext()
783
                .equals(((FFrameView) arg0).getMapContext())) {
784
            return false;
785
        }
786

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

    
820
    public void fullExtent() throws ReadException {
821
        setNewEnvelope(getMapContext().getFullEnvelope());
822
    }
823

    
824
    public void setPointsToZoom(Point2D px1, Point2D px2) {
825
        p1 = px1;
826
        p2 = px2;
827
    }
828

    
829
    public void movePoints(Point2D px1, Point2D px2) {
830
        double difX = -px2.getX() + px1.getX();
831
        double difY = -px2.getY() + px1.getY();
832
        if (p1 != null) {
833
            p1.setLocation(p1.getX() + difX, p1.getY() + difY);
834
            p2.setLocation(p2.getX() + difX, p2.getY() + difY);
835
        }
836
    }
837

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

    
847
    public Object clone() throws CloneNotSupportedException {
848
        FFrameView frame = (FFrameView) super.clone();
849
        frame.createListeners(); // necessary to create the listeners within the right scope
850
        frame.setView(this.getView());
851

    
852
        if (grid != null) {
853
            FFrameGrid newGrid = (FFrameGrid) this.grid.clone();
854
            newGrid.setFFrameDependence(frame);
855
            frame.setGrid(newGrid);
856
        }
857
        cloneActions(frame);
858
        return frame;
859
    }
860

    
861
    public void setGrid(IFFrame grid) {
862
        this.grid = grid;
863
        this.grid.setRotation(this.getRotation());
864
    }
865

    
866
    public IFFrame getGrid() {
867
        return this.grid;
868
    }
869

    
870
    public void setRotation(double rotation) {
871
        super.setRotation(rotation);
872
        if (grid != null) {
873
            grid.setRotation(rotation);
874
        }
875
    }
876

    
877
    public void showGrid(boolean b) {
878
        showGrid = b;
879
    }
880

    
881
    public boolean isShowGrid() {
882
        return showGrid;
883
    }
884

    
885
    public void refreshOriginalExtent() {
886
    }
887

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

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

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

    
974
        }
975
        showGrid = state.getBoolean(SHOWGRID_FIELD);
976
        grid = (IFFrame) state.get(GRID_FIELD);
977
    }
978

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

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

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

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

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

    
1120
        public void frameRemoved() {
1121
                if (mapContext!=null) {
1122
                        clearOwnListeners(mapContext);
1123
                }
1124
                if (this.getView()!=null && this.getView().getMapContext()!=null) {
1125
                        clearViewListeners(this.getView().getMapContext());
1126
                }
1127
                if (b_hasToc && getLayoutContext()!=null) {
1128
                        getLayoutContext().setTocModel(null);
1129
                }
1130
                m_image = null; // FIXME: we could instead move it to a LRU cache to keep the last N images
1131
        }
1132

    
1133
        public void frameAdded() {
1134
                setListeners();
1135
                setTocModel();
1136
                updateScaleCtrl();
1137
        }
1138
        
1139
        public void setHasToc(boolean hasToc) {
1140
                this.b_hasToc = hasToc;
1141
                setTocModel();
1142
        }
1143
        
1144
        protected void setTocModel() {
1145
                if (getLayoutContext()!=null) {
1146
                        if (b_hasToc && getMapContext()!=null) {
1147
                                getLayoutContext().setTocModel(getMapContext());
1148
                        }
1149
                        else {
1150
                                getLayoutContext().setTocModel(null);
1151
                        }
1152
                }
1153
        }
1154
        
1155
        @Override
1156
        protected void doSetSelected(int selectedStatus) {
1157
                boolean oldSelectedStatus = isSelected();
1158
                super.doSetSelected(selectedStatus);
1159
                if (!oldSelectedStatus && isSelected()) { // changed from not selected to selected
1160
                        setTocModel();
1161
                        updateScaleCtrl();
1162
                }
1163
        }
1164
        
1165
        public boolean getLayerSynced() {
1166
                return syncLayers;
1167
        }
1168

    
1169
        public void setLayerSynced(boolean synced) {
1170
        syncLayers = synced;
1171
        resetListeners();
1172
        }
1173

    
1174
        public boolean getExtentSynced() {
1175
                return syncExtents;
1176
        }
1177

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

    
1224
                                double minX = envelope.getMinimum(0) + shiftX;
1225
                                double minY = envelope.getMinimum(1) + shiftY;
1226
                                double maxX = envelope.getMaximum(0) + shiftX;
1227
                                double maxY = envelope.getMaximum(1) + shiftY;
1228

    
1229
                                return GeometryLocator.getGeometryManager().createEnvelope(minX, minY, maxX, maxY, SUBTYPES.GEOM2D);
1230
                        }
1231
                }
1232
                catch (LocatorException e) {}
1233
                catch (CreateEnvelopeException e) {}
1234
                return newEnvelope;
1235
        }
1236

    
1237
        private class ViewDocListener
1238
        implements ViewPortListener, LegendListener, LayerCollectionListener, AtomicEventListener {
1239

    
1240
                public void extentChanged(ExtentEvent e) {
1241
                        if (!b_updating && getExtentSynced()) {
1242
                                if (!b_frameInitialized) {
1243
                                        b_frameInitialized = true;
1244
                                        return;
1245
                                }
1246
                                b_updating = true;
1247
                                if (getMapContext()!=null) {
1248
                                        if (scaleType==SCALE_TYPE.FIXED_EXTENT) {
1249
                                                getView().getMapContext().getViewPort().setEnvelope(fixedExtent);
1250
                                        }
1251
                                        else {
1252
                                                getMapContext().getViewPort().setEnvelope(calculateNewExtent());
1253
                                                if (scaleType==SCALE_TYPE.FIXED_SCALE) {
1254
                                                        getMapContext().setScaleView(Math.round(fixedScale));  
1255
                                                        getView().getMapContext().getViewPort().setEnvelope(getMapContext().getViewPort().getAdjustedEnvelope());
1256
                                                }
1257
                                                updateScaleCtrl();
1258
                                                invalidateLayout();
1259
                                        }
1260
                                }
1261
                                b_updating = false;
1262
                        }                        
1263
                }
1264

    
1265
                public void backColorChanged(ColorEvent e) {
1266
                        if (!b_updating && syncLayers) {
1267
                                if (getMapContext()!=null) {
1268
                                        b_updating = true;
1269
                                        mapContext.getViewPort().setBackColor(e.getNewColor());
1270
                                        invalidateLayout();
1271
                                        b_updating = true;
1272
                                }
1273
                        }
1274
                }
1275

    
1276
                public void projectionChanged(ProjectionEvent e) {
1277
                        if (!b_updating && getExtentSynced()) {
1278
                                if (getMapContext()!=null) {
1279
                                        b_updating = true;
1280
                                        getMapContext().getViewPort().setProjection(e.getNewProjection());
1281
                                        invalidateLayout();
1282
                                        // FIXME: force also a view redraw someway??
1283
                                        b_updating = false;
1284
                                }
1285
                        }
1286
                }
1287

    
1288
                public void conditionalRedraw() {
1289
                        if (!b_updating && syncLayers) {
1290
                                b_updating = true;
1291
                                invalidateLayout();
1292
                                // the view should also receive the event and update automatically
1293
                                b_updating = false;
1294
                        }                        
1295
                }
1296

    
1297
                public void legendChanged(LegendChangedEvent e) {
1298
                        conditionalRedraw();
1299
                        invalidateToc();
1300
                }
1301

    
1302
                public void layerAdded(LayerCollectionEvent e) {
1303
                        conditionalRedraw();
1304
                        // no need to invalidate the toc as it is down by the OwnMapContextListener
1305
                }
1306

    
1307
                public void layerMoved(LayerPositionEvent e) {
1308
                        conditionalRedraw();
1309
                        // no need to invalidate the toc as it is down by the OwnMapContextListener
1310
                }
1311

    
1312
                public void layerRemoved(LayerCollectionEvent e) {
1313
                        conditionalRedraw();
1314
                        // no need to invalidate the toc as it is down by the OwnMapContextListener
1315
                }
1316

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

    
1322
                public void layerMoving(LayerPositionEvent e)
1323
                                throws CancelationException {
1324
                        // nothing needed
1325
                }
1326

    
1327
                public void layerRemoving(LayerCollectionEvent e)
1328
                                throws CancelationException {
1329
                        // nothing needed
1330
                }
1331

    
1332
                public void visibilityChanged(LayerCollectionEvent e)
1333
                                throws CancelationException {
1334
                        // AtomicEvent is catching visibility changes instead of this one,
1335
                        // as this event is not being received. Maybe is only triggered if the
1336
                        // visibility of the whole group changes??
1337
                        conditionalRedraw();
1338
                        invalidateToc();
1339
                }
1340

    
1341
                public void atomicEvent(AtomicEvent e) {
1342
                        boolean layoutRedraw = false;
1343
                        // not all the events require a fframeview redraw
1344
                        for (int i=e.getLayerEvents().length-1; i>=0; i--) {
1345
                                FMapEvent at = e.getEvent(i);
1346
                                if (at instanceof LayerEvent) {
1347
                                        if (at.getEventType()==LayerEvent.DRAW_VALUES_CHANGED) {
1348
                                                layoutRedraw = true;
1349
                                                break;
1350
                                        }
1351
                                }
1352
                        }
1353
                        if (layoutRedraw) {
1354
                                conditionalRedraw();
1355
                        }
1356
                        invalidateToc();
1357
                }
1358
        }
1359

    
1360
        private class OwnMapContextListener
1361
                implements ViewPortListener, LegendListener, LayerCollectionListener {
1362

    
1363
                public void extentChanged(ExtentEvent e) {
1364
                        if (!b_drawing && !b_updating) {
1365
                                b_updating = true;
1366
                                if (scaleType==SCALE_TYPE.FIXED_EXTENT) {
1367
                                        getMapContext().getViewPort().setEnvelope(fixedExtent);
1368
                                }
1369
                                else {
1370
                                        Envelope newEnvelope;
1371
                                        if (scaleType==SCALE_TYPE.FIXED_SCALE) {
1372
                                                getMapContext().setScaleView(Math.round(fixedScale));
1373
                                                newEnvelope = getMapContext().getViewPort().getAdjustedEnvelope();
1374
                                        }
1375
                                        else {
1376
                                                newEnvelope = e.getNewExtent();
1377
                                        }
1378
                                        if (getView()!=null) {
1379
                                                if (getExtentSynced()){
1380
                                                        getView().getMapContext().getViewPort().setEnvelope(newEnvelope);
1381
                                                }
1382
                                        }
1383
                                }
1384
                                updateScaleCtrl();
1385
                                invalidateLayout();
1386
                                b_updating = false;
1387
                        }                        
1388
                }
1389

    
1390
                public void backColorChanged(ColorEvent e) {
1391
                        if (!b_updating) {
1392
                                if (getView()!=null) {
1393
                                        b_updating = true;
1394
                                        if (getLayerSynced()) {
1395
                                                getView().getMapContext().getViewPort().setBackColor(e.getNewColor());
1396
                                        }
1397
                                        invalidateLayout();
1398
                                        b_updating = false;
1399
                                }
1400
                        }
1401
                }
1402

    
1403
                public void projectionChanged(ProjectionEvent e) {
1404
                        if (!b_updating && getExtentSynced()) {
1405
                                if (getView()!=null) {
1406
                                        b_updating = true;
1407
                                        if (getLayerSynced()) {
1408
                                                getView().getMapContext().getViewPort().setProjection(e.getNewProjection());
1409
                                        }
1410
                                        invalidateLayout();
1411
                                        // FIXME: force also a view redraw someway??
1412
                                        b_updating = false;
1413
                                }
1414
                        }
1415
                }
1416

    
1417
                public void conditionalRedraw() {
1418
                        if (!b_updating) {
1419
                                b_updating = true;
1420
                                invalidateLayout();
1421
                                // the view should also receive the event and update automatically
1422
                                b_updating = false;
1423
                        }
1424
                }
1425

    
1426
                public void legendChanged(final LegendChangedEvent e) {
1427
                        conditionalRedraw();
1428
                        invalidateToc();
1429
                }
1430

    
1431
                public void layerAdded(final LayerCollectionEvent e) {
1432
                        // necessary to set an envelope when the first layer is added
1433
                        if (!b_updating && getMapContext().getViewPort().getEnvelope()==null) {
1434
                                try {
1435
                                        b_updating = true;
1436
                                        fullExtent();
1437
                                        
1438
                                } catch (ReadException e1) {
1439
                                } finally {
1440
                                        b_updating = false;
1441
                                }
1442
                        }
1443
                        conditionalRedraw();
1444
                        refreshToc();
1445
                }
1446

    
1447
                public void layerMoved(final LayerPositionEvent e) {
1448
                        conditionalRedraw();
1449
                        refreshToc();
1450
                }
1451

    
1452
                public void layerRemoved(final LayerCollectionEvent e) {
1453
                        conditionalRedraw();
1454
                        refreshToc();
1455
                }
1456

    
1457
                public void layerAdding(LayerCollectionEvent e)
1458
                                throws CancelationException {
1459
                        // nothing neededO
1460

    
1461
                }
1462

    
1463
                public void layerMoving(LayerPositionEvent e)
1464
                                throws CancelationException {
1465
                        // nothing needed
1466

    
1467
                }
1468

    
1469
                public void layerRemoving(LayerCollectionEvent e)
1470
                                throws CancelationException {
1471
                        // nothing needed
1472

    
1473
                }
1474

    
1475
                public void visibilityChanged(LayerCollectionEvent e)
1476
                                throws CancelationException {
1477
                        conditionalRedraw();
1478
                }
1479
        }
1480

    
1481
        public void setExtent(Envelope extent) {
1482
                if (getScaleType()==SCALE_TYPE.NORMAL) {
1483
                        getMapContext().getViewPort().setEnvelope(extent);
1484
                }
1485
        }
1486

    
1487
        public SCALE_TYPE getScaleType() {
1488
                return scaleType ;
1489
        }
1490

    
1491
        public void setScaleType(SCALE_TYPE scaleType) {
1492
                this.scaleType = scaleType;
1493
        }
1494
        
1495
        public void setScaleType(SCALE_TYPE scaleType, double fixedScale) {
1496
                if (scaleType == SCALE_TYPE.FIXED_SCALE) {
1497
                        this.scaleType = scaleType;
1498
                        this.fixedScale = new Double(fixedScale);
1499
                        setScale(fixedScale);
1500
                }
1501
        }
1502
        
1503
        public void setScaleType(SCALE_TYPE scaleType, Envelope fixedExtent) {
1504
                if (scaleType == SCALE_TYPE.FIXED_EXTENT) {
1505
                        this.scaleType = scaleType;
1506
                        this.fixedExtent  = fixedExtent;
1507
                        setNewEnvelope(fixedExtent);
1508
                }
1509
        }
1510

    
1511
        @Deprecated
1512
        public int getTypeScale() {
1513
                return AUTOMATICO;
1514
        }
1515

    
1516
        @Deprecated
1517
        public void setLinked(boolean b) {}
1518

    
1519
        @Deprecated
1520
        public boolean getLinked() {
1521
                return false;
1522
        }
1523

    
1524
        public void windowActivated() {
1525
                if (isSelected()
1526
                                && getLayoutContext().getSelectedFFrames(IFFrameUseFMap.class).length==1) {
1527
                        // update the scale control whenever the panel window gets activated,
1528
                        // as the control instance is shared for all the windows
1529
                        updateScaleCtrl();
1530
                }
1531
                
1532
        }
1533

    
1534
        public void windowClosed() {
1535
        }
1536
}