Statistics
| Revision:

root / trunk / extensions / extAnnotations / src / com / iver / cit / gvsig / fmap / layers / Annotation_Layer.java @ 24515

History | View | Annotate | Download (26.4 KB)

1

    
2
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
3
 *
4
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
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., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
19
 *
20
 * For more information, contact:
21
 *
22
 *  Generalitat Valenciana
23
 *   Conselleria d'Infraestructures i Transport
24
 *   Av. Blasco Ib??ez, 50
25
 *   46010 VALENCIA
26
 *   SPAIN
27
 *
28
 *      +34 963862235
29
 *   gvsig@gva.es
30
 *      www.gvsig.gva.es
31
 *
32
 *    or
33
 *
34
 *   IVER T.I. S.A
35
 *   Salamanca 50
36
 *   46005 Valencia
37
 *   Spain
38
 *
39
 *   +34 963163400
40
 *   dac@iver.es
41
 */
42

    
43
package com.iver.cit.gvsig.fmap.layers;
44

    
45
import java.awt.Color;
46
import java.awt.Font;
47
import java.awt.Graphics2D;
48
import java.awt.Shape;
49
import java.awt.font.FontRenderContext;
50
import java.awt.font.GlyphVector;
51
import java.awt.geom.AffineTransform;
52
import java.awt.geom.Point2D;
53
import java.awt.geom.Rectangle2D;
54
import java.awt.image.BufferedImage;
55
import java.io.File;
56

    
57
import javax.print.attribute.PrintRequestAttributeSet;
58
import javax.print.attribute.standard.PrintQuality;
59

    
60
import org.cresques.cts.ICoordTrans;
61
import org.cresques.cts.IProjection;
62

    
63
import com.hardcode.driverManager.Driver;
64
import com.hardcode.driverManager.DriverLoadException;
65
import com.hardcode.gdbms.driver.exceptions.InitializeDriverException;
66
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
67
import com.hardcode.gdbms.engine.data.driver.DriverException;
68
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
69
import com.hardcode.gdbms.engine.values.NullValue;
70
import com.hardcode.gdbms.engine.values.NumericValue;
71
import com.hardcode.gdbms.engine.values.StringValue;
72
import com.hardcode.gdbms.engine.values.Value;
73
import com.hardcode.gdbms.engine.values.ValueFactory;
74
import com.iver.andami.messages.NotificationManager;
75
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
76
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
77
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
78
import com.iver.cit.gvsig.exceptions.layers.StartEditionLayerException;
79
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
80
import com.iver.cit.gvsig.exceptions.visitors.VisitorException;
81
import com.iver.cit.gvsig.fmap.MapContext;
82
import com.iver.cit.gvsig.fmap.ViewPort;
83
import com.iver.cit.gvsig.fmap.core.FPoint2D;
84
import com.iver.cit.gvsig.fmap.core.GeneralPathX;
85
import com.iver.cit.gvsig.fmap.core.IGeometry;
86
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
87
import com.iver.cit.gvsig.fmap.core.SymbologyFactory;
88
import com.iver.cit.gvsig.fmap.core.symbols.IMarkerSymbol;
89
import com.iver.cit.gvsig.fmap.core.symbols.ISymbol;
90
import com.iver.cit.gvsig.fmap.core.symbols.ITextSymbol;
91
import com.iver.cit.gvsig.fmap.core.symbols.SimpleTextSymbol;
92
import com.iver.cit.gvsig.fmap.core.v02.FConstant;
93
import com.iver.cit.gvsig.fmap.crs.CRSFactory;
94
import com.iver.cit.gvsig.fmap.drivers.BoundedShapes;
95
import com.iver.cit.gvsig.fmap.drivers.VectorialFileDriver;
96
import com.iver.cit.gvsig.fmap.edition.Annotation_EditableAdapter;
97
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
98
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
99
import com.iver.cit.gvsig.fmap.operation.strategies.Annotation_Strategy;
100
import com.iver.cit.gvsig.fmap.operations.strategies.Strategy;
101
import com.iver.cit.gvsig.fmap.operations.strategies.StrategyManager;
102
import com.iver.cit.gvsig.fmap.rendering.Annotation_Legend;
103
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
104
import com.iver.cit.gvsig.fmap.rendering.styling.labeling.AttrInTableLabelingStrategy;
105
import com.iver.cit.gvsig.fmap.spatialindex.QuadtreeJts;
106
import com.iver.utiles.XMLEntity;
107
import com.iver.utiles.swing.threads.Cancellable;
108

    
109

    
110
/**
111
 * Annotation's layer.
112
 *
113
 * @author Vicente Caballero Navarro
114
 */
115
public class Annotation_Layer extends FLyrVect {
116
        private Annotation_Mapping mapping = null;
117
        private int indexEditing = -1;
118
        private Annotation_Legend aLegend;
119
        private Strategy strategy = null;
120
        private IMarkerSymbol symbolPoint = SymbologyFactory.createDefaultMarkerSymbol();
121
        private final static AffineTransform ati=new AffineTransform();
122
        /**
123
         * Crea un nuevo FLyrAnnotation.
124
         */
125
        public Annotation_Layer() {
126
                super();
127
        }
128

    
129
        /**
130
         * DOCUMENT ME!
131
         *
132
         * @param mapping DOCUMENT ME!
133
         * @throws ReadDriverException
134
         * @throws LegendLayerException
135
         * @throws DriverException
136
         * @throws FieldNotFoundException
137
         */
138
        public void setMapping(Annotation_Mapping mapping) throws LegendLayerException, ReadDriverException {
139
                this.mapping = mapping;
140
                aLegend = new Annotation_Legend();
141
                setLegend();
142
        }
143

    
144
        /**
145
         * DOCUMENT ME!
146
         *
147
         * @return DOCUMENT ME!
148
         */
149
        public Annotation_Mapping getAnnotatonMapping() {
150
                return mapping;
151
        }
152

    
153
        /**
154
         * @throws ReadDriverException
155
         * @throws InitializeDriverException
156
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#draw(java.awt.image.BufferedImage,
157
         *      java.awt.Graphics2D, ISymbol)
158
         */
159
        public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
160
                        Cancellable cancel, double scale) throws InitializeDriverException, ReadDriverException {
161
                if (isWithinScale(scale)) {
162
                        // Las que solo tienen etiquetado sin pintar el shape,
163
                        // no pasamos por ellas
164
                        boolean bDrawShapes = true;
165

    
166
                        if (bDrawShapes) {
167
                                if (strategy == null) {
168
                                        strategy = new Annotation_Strategy(this);
169
                                }
170
                                g.setColor(Color.black);
171
                                ReadableVectorial adapter = getSource();
172
                                adapter.start();
173
                                drawAnnotations(image,g,viewPort,cancel,null);
174
                                adapter.stop();
175
                        }
176

    
177
                        if (getVirtualLayers() != null) {
178
                                getVirtualLayers().draw(image, g, viewPort, cancel, scale);
179
                        }
180
                }
181
        }
182
        private void drawAnnotations(BufferedImage image, Graphics2D g, ViewPort viewPort,
183
                        Cancellable cancel,PrintRequestAttributeSet properties) {
184
                BufferedImage bi=new BufferedImage(viewPort.getImageWidth(),viewPort.getImageHeight(),BufferedImage.TYPE_INT_ARGB);
185
                Graphics2D gBi=(Graphics2D)bi.getGraphics();
186
                Point2D offset=viewPort.getOffset();
187
                gBi.translate(-offset.getX(),-offset.getY());
188
                Annotation_Legend l = (Annotation_Legend) getLegend();
189
                ITextSymbol sym = (ITextSymbol) l.getDefaultSymbol();
190

    
191
                try {
192
                        ReadableVectorial source = getSource();
193
                        // limit the labeling to the visible extent
194
                        FBitSet bs = queryByRect(viewPort.getAdjustedExtent());
195

    
196
                        SelectableDataSource recordSet = source.getRecordset();
197
                        recordSet.start();
198
                        FBitSet bitSet = recordSet.getSelection();
199
                        Annotation_Mapping mapping = getAnnotatonMapping();
200
                        int idHeightField = mapping.getColumnHeight();
201
                        int idFontName = mapping.getColumnTypeFont();
202
                        int idFontStyle = mapping.getColumnStyleFont();
203
                        int idRotationField = mapping.getColumnRotate();
204
                        int idFontColor = mapping.getColumnColor();
205
                        int idTextField = mapping.getColumnText();
206

    
207
                        double rotation = 0D;
208
                        float size = sym.getFont().getSize()* (float)FConstant.FONT_HEIGHT_SCALE_FACTOR;
209

    
210
                        String fontName = "Dialog";
211
                        int fontStyle = sym.getFont().getStyle();
212
                        int fontColor = sym.getTextColor().getRGB();
213
                        long t1 = System.currentTimeMillis();
214

    
215
                        for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) {
216
                                if (cancel.isCanceled()) {
217
                                        break;
218
                                }
219

    
220
                                Value[] vv = recordSet.getRow(i);
221

    
222
                                if (idHeightField != -1) {
223
                                        // text size is defined in the table
224
                                        try {
225
                                                size = (float)(((NumericValue) vv[idHeightField]).doubleValue() * FConstant.FONT_HEIGHT_SCALE_FACTOR);
226
                                        } catch (ClassCastException ccEx) {
227
                                                if (!NullValue.class.equals(
228
                                                                vv[idHeightField].getClass())) {
229
                                                }
230
                                                continue;
231
                                        }
232
                                }
233

    
234
                                if (idFontName != -1) {
235
                                        fontName = ((StringValue) vv[idFontName]).toString();
236
                                }
237

    
238
                                if (idFontStyle != -1) {
239
                                        fontStyle = ((NumericValue) vv[idFontStyle]).intValue();
240
                                }
241

    
242
                                if (idRotationField != -1) {
243
                                        // text rotation is defined in the table
244
                                        rotation = ((NumericValue) vv[idRotationField]).doubleValue();
245
                                        ((SimpleTextSymbol)sym).setRotation(Math.toRadians(rotation));
246
                                }
247

    
248
                                if (idFontColor != -1) {
249
                                        // text rotation is defined in the table
250
                                        fontColor = ((NumericValue) vv[idFontColor]).intValue();
251
                                        sym.setTextColor(new Color(fontColor));
252
                                }
253

    
254
                                if (bitSet.get(i)) {
255
                                        sym = (ITextSymbol) sym.getSymbolForSelection();
256
                                }
257

    
258
                                sym.setFont(new Font(fontName, fontStyle, (int) size));
259
                                source.start();
260
                                IGeometry geom = source.getShape(i);
261
                                source.stop();
262
                                ICoordTrans ct = getCoordTrans();
263

    
264
                                boolean bMustClone = false;
265

    
266
                                if (geom == null) {
267
                                        return;
268
                                }
269

    
270
                                if (ct != null) {
271
                                        if (bMustClone) {
272
                                                geom = geom.cloneGeometry();
273
                                        }
274

    
275
                                        geom.reProject(ct);
276
                                }
277
                                geom.transform(viewPort.getAffineTransform());
278
                                Shape shape=geom.getInternalShape();
279
                                FPoint2D fpPixels=null;
280
                                if (!(shape instanceof FPoint2D)) {
281
                                        Rectangle2D rP=shape.getBounds2D();
282
                                        fpPixels=new FPoint2D(rP.getX(),rP.getMaxY());
283
                                }else {
284
                                        fpPixels=(FPoint2D)shape;
285
                                }
286
                                //Si el tama?o de la fuente est? en unidades de mapa.
287
                                int unit=-1;
288
                                
289
//                                if (this.getLabelingStrategy()!=null)
290
                                unit=l.getUnits();
291
                                if (unit!=-1){
292
                                        boolean draw=false;
293
                                        Rectangle2D r=getTextWrappingGeometryInPixels(unit,size,vv[idTextField].toString(),rotation,fontName, fontStyle,i,viewPort,geom).getBounds2D();
294
                                        Rectangle2D rPixels=new Rectangle2D.Double(r.getX(),r.getY()+r.getHeight(),r.getWidth(),r.getHeight());
295

    
296
                                        Point2D p=new Point2D.Double(fpPixels.getX(),fpPixels.getY());
297

    
298
                                        if (!isEditing() && l.isAvoidOverLapping()){
299
                                                p=getPoint(bi,rPixels,l.isDelOverLapping());
300
                                                if (p!=null)
301
                                                        draw=true;
302
                                        }else{
303
                                                if (!isEditing() && l.isDelOverLapping()){
304
                                                        if (isOverlapping(bi,rPixels)){
305
                                                                draw=true;
306
                                                        }
307
                                                }else{
308
                                                        draw=true;
309
                                                }
310
                                        }
311
                                        if (draw){
312
                                                if (l.isPointVisible()) {
313
                                                        symbolPoint.draw(gBi,
314
                                                                        ati,
315
                                                                        fpPixels, cancel);
316
                                                }
317
                                                ((SimpleTextSymbol)l.getDefaultSymbol()).setFontSize(r.getHeight());
318
//                                                g.drawRect((int)rPixels.getX(),(int)rPixels.getY(),(int)rPixels.getWidth(),(int)rPixels.getHeight());
319
//FGraphicUtilities.DrawAnnotation(gBi,
320
//                ati, sym, aux[0], metrics, false);
321
                                                drawAnnotation(gBi,unit,this,l, p, vv[idTextField].toString(),viewPort,properties);
322
                                        }
323
                                }else{
324

    
325
                                        // Si el tama?o de la fuente est? en pixels.
326
                                        boolean draw=false;
327

    
328
                                        Rectangle2D r=getTextWrappingGeometryInPixels(unit,size,vv[idTextField].toString(),rotation,fontName,fontStyle,i,viewPort,geom).getBounds2D();
329
//                                        g.draw(capa.getTextWrappingGeometryInPixels(size,vv[idTextField].toString(),rotation,fontName,fontStyle,i,viewPort,geom));
330
                                        Rectangle2D rPixels= new Rectangle2D.Double(r.getX(),r.getY()+r.getHeight(),r.getWidth(),r.getHeight());
331

    
332
                                        Point2D pSearch = new Point2D.Double(fpPixels.getX(),fpPixels.getY());
333

    
334
                                        if (!isEditing() && l.isAvoidOverLapping()){
335
                                                pSearch =getPoint(bi,rPixels,l.isDelOverLapping());
336
                                                if (pSearch !=null){
337
                                                        draw=true;
338
                                                }
339
                                        }else{
340
                                                if (!isEditing() && l.isDelOverLapping()){
341
                                                        if (isOverlapping(bi,rPixels)){
342
                                                                draw=true;
343
                                                        }
344
                                                }else{
345
                                                        draw=true;
346
                                                }
347
                                        }
348
                                        if (draw){
349
                                                if (l.isPointVisible()) {
350
                                                        symbolPoint.draw(gBi,
351
                                                                        ati,
352
                                                                        fpPixels,
353
                                                                        cancel);
354
                                                }
355
                                                drawAnnotation(gBi,unit,this,l, pSearch , vv[idTextField].toString(),viewPort,properties);
356
                                        }
357
                                }
358
                                //Al dibujar esta imagen sobre el graphics la trasparencia no puede existir.
359
                                
360
                                        if (i%1000==0){
361
                                                if (image!=null)
362
                                                        g.drawImage(bi,0,0,null);
363
                                        }
364
                        }
365
                        gBi.translate(offset.getX(),offset.getY());
366
                        g.drawImage(bi,(int)offset.getX(),(int)offset.getY(),null);
367
                        System.err.println(System.currentTimeMillis()-t1+"millis");
368
                        recordSet.stop();
369
                } catch (Exception e) {
370
                        NotificationManager.addError(e); // TODO esto no puede estar aqu?, pertenece a una capa de abtracci?n superior
371
                }
372
        }
373
        private Point2D getPoint(BufferedImage bi, Rectangle2D rec, boolean b) {
374
                //La altura que se suma aqu? para calcular es posible que sea para corregir un error de SimpleTextSymbol
375
                //que en alg?n momento se solucionar?.
376
                Rectangle2D r=new Rectangle2D.Double(rec.getX(),rec.getY()-rec.getHeight(),rec.getWidth(),rec.getHeight());
377
                if (isOverlapping(bi,r))
378
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
379

    
380
                r.setFrame(rec.getX(),rec.getY(),rec.getWidth(),rec.getHeight());
381
                if (isOverlapping(bi,r))
382
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
383

    
384
                r.setFrame(rec.getX()-rec.getWidth(),rec.getY()-rec.getHeight(),rec.getWidth(),rec.getHeight());
385
                if (isOverlapping(bi,r))
386
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
387

    
388
                r.setFrame(rec.getX()-rec.getWidth(),rec.getY(),rec.getWidth(),rec.getHeight());
389
                if (isOverlapping(bi,r))
390
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
391

    
392
                r.setFrame(rec.getX()-rec.getWidth()/2,rec.getY(),rec.getWidth(),rec.getHeight());
393
                if (isOverlapping(bi,r))
394
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
395

    
396
                r.setFrame(rec.getX()-rec.getWidth()/2,rec.getY()-rec.getHeight(),rec.getWidth(),rec.getHeight());
397
                if (isOverlapping(bi,r))
398
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
399

    
400
                r.setFrame(rec.getX(),rec.getY()+rec.getHeight()/2,rec.getWidth(),rec.getHeight());
401
                if (isOverlapping(bi,r))
402
                        return new Point2D.Double(r.getX(),r.getY()+rec.getHeight());
403

    
404
                if (!b)
405
                        return new Point2D.Double(rec.getX(),rec.getY());
406
                else
407
                        return null;
408
        }
409

    
410
        private boolean isOverlapping(BufferedImage bi, Rectangle2D rPixels) {
411
                for (int i=(int)rPixels.getX();i<rPixels.getMaxX();i++){
412
                        for (int j=(int)rPixels.getY();j<rPixels.getMaxY();j++){
413
                                if (i<0 || j<0 || bi.getWidth()<i+1 || bi.getHeight()<j+1)
414
                                        continue;
415
                                if (bi.getRGB(i,j)!=0){
416
                                        return false;
417
                                }
418
                        }
419
                }
420
                return true;
421
        }
422

    
423
        /**
424
         * @throws ReadDriverException
425
         * @throws InitializeDriverException
426
         * @throws ExpansionFileReadException
427
         * @see com.iver.cit.gvsig.fmap.layers.LayerOperations#getFullExtent()
428
         */
429
        public Rectangle2D getFullExtent() throws InitializeDriverException,
430
        ReadDriverException, ExpansionFileReadException {
431
                Rectangle2D rAux;
432
                getSource().start();
433
                rAux = getSource().getFullExtent();
434
                getSource().stop();
435

    
436
                // Si existe reproyecci?n, reproyectar el extent
437
                ICoordTrans ct = getCoordTrans();
438

    
439
                if (ct != null) {
440
                        Point2D pt1 = new Point2D.Double(rAux.getMinX(), rAux.getMinY());
441
                        Point2D pt2 = new Point2D.Double(rAux.getMaxX(), rAux.getMaxY());
442
                        pt1 = ct.convert(pt1, null);
443
                        pt2 = ct.convert(pt2, null);
444
                        rAux = new Rectangle2D.Double();
445
                        rAux.setFrameFromDiagonal(pt1, pt2);
446
                }
447

    
448
                return rAux;
449
        }
450

    
451
        /**
452
         * @throws ReadDriverException
453
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#print(java.awt.Graphics2D,
454
         *      com.iver.cit.gvsig.fmap.ViewPort,
455
         *      com.iver.utiles.swing.threads.Cancellable)
456
         */
457
        public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
458
                        double scale, PrintRequestAttributeSet properties) throws ReadDriverException{
459
                if (isVisible() && isWithinScale(scale)) {
460
                        drawAnnotations(null,g, viewPort, cancel, properties);
461
                }
462
        }
463

    
464
        /*
465
         * (non-Javadoc)
466
         *
467
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#queryByRect(java.awt.geom.Rectangle2D)
468
         */
469
        public FBitSet queryByRect(Rectangle2D rect) throws ReadDriverException, VisitorException {
470
                Strategy s = StrategyManager.getStrategy(this);
471

    
472
                return s.queryByRect(rect);
473
        }
474

    
475
        /**
476
         * DOCUMENT ME!
477
         *
478
         * @param p DOCUMENT ME!
479
         * @param tolerance DOCUMENT ME!
480
         *
481
         * @return DOCUMENT ME!
482
         * @throws VisitorException
483
         * @throws ReadDriverException
484
         *
485
         * @throws DriverException DOCUMENT ME!
486
         */
487
        public FBitSet queryByPoint(Point2D p, double tolerance) throws ReadDriverException, VisitorException {
488
                Strategy s = StrategyManager.getStrategy(this);
489

    
490
                return s.queryByPoint(p, tolerance);
491
        }
492

    
493
        /**
494
         * DOCUMENT ME!
495
         *
496
         * @param g DOCUMENT ME!
497
         * @param relationship DOCUMENT ME!
498
         *
499
         * @return DOCUMENT ME!
500
         * @throws VisitorException
501
         * @throws ReadDriverException
502
         *
503
         * @throws DriverException DOCUMENT ME!
504
         * @throws VisitException DOCUMENT ME!
505
         */
506
        public FBitSet queryByShape(IGeometry g, int relationship) throws ReadDriverException, VisitorException {
507
                Strategy s = StrategyManager.getStrategy(this);
508

    
509
                return s.queryByShape(g, relationship);
510
        }
511

    
512
        /**
513
         * DOCUMENT ME!
514
         *
515
         * @return DOCUMENT ME!
516
         *
517
         * @throws XMLException
518
         *
519
         * @see com.iver.cit.gvsig.fmap.layers.FLayer#getProperties()
520
         */
521
        public XMLEntity getXMLEntity() throws XMLException {
522
                XMLEntity xml = super.getXMLEntity();
523
                return xml;
524
        }
525

    
526
        /**
527
         * @see com.iver.cit.gvsig.fmap.layers.FLyrDefault#setXMLEntity(com.iver.utiles.XMLEntity)
528
         */
529
        public void setXMLEntity(XMLEntity xml) throws XMLException {
530
                IProjection proj = null;
531

    
532
                if (xml.contains("proj")) {
533
                        proj = CRSFactory.getCRS(xml.getStringProperty("proj"));
534
                }
535

    
536
                if (xml.contains("file")) {
537
                        Driver d;
538

    
539
                        try {
540
                                d = LayerFactory.getDM().getDriver(xml.getStringProperty(
541
                                                "driverName"));
542
                        } catch (DriverLoadException e1) {
543
                                throw new XMLException(e1);
544
                        }
545

    
546
                        FLyrVect lv = (FLyrVect) LayerFactory.createLayer(xml.getName(),
547
                                        (VectorialFileDriver) d,
548
                                        new File(xml.getStringProperty("file")), proj);
549

    
550
                        try {
551
                                this.setSource(lv.getSource());
552
                                this.setRecordset(lv.getRecordset());
553
                                this.setProjection(lv.getProjection());
554
                                this.setLegend((IVectorLegend) lv.getLegend());
555

    
556

    
557
                                Annotation_Mapping.addAnnotationMapping(this);
558
                        } catch (ReadDriverException e) {
559
                                throw new XMLException(e);
560
                        } catch (LegendLayerException e) {
561
                                throw new XMLException(e);
562
                        }
563
                }
564
                super.setXMLEntity(xml);
565
//                if (this.getLabelingStrategy()==null){
566
//                        boolean isInPixel=((Annotation_Legend)this.getLegend()).isFontSizeInPixels();
567
//                        if (isInPixel){
568
//                                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
569
//                                labeling.setUnit(-1);
570
//                                setLabelingStrategy(labeling);
571
//                        }else{
572
//                                AttrInTableLabelingStrategy labeling = new AttrInTableLabelingStrategy();
573
//                                labeling.setUnit(1);
574
//                                setLabelingStrategy(labeling);
575
//                        }
576
//                }
577
        }
578

    
579
        public Value getSymbolKey(int i) throws ReadDriverException {
580
                SelectableDataSource ds = getRecordset();
581
                String t = new String();
582
                Value val = ds.getFieldValue(i, mapping.getColumnText());
583
                t = val.toString();
584

    
585
                if (mapping.getColumnColor() != -1) {
586
                        Value valColor = ds.getFieldValue(i, mapping.getColumnColor());
587
                        t = t.concat(valColor.toString());
588
                }
589

    
590
                if (mapping.getColumnTypeFont() != -1) {
591
                        Value valTypeFont = ds.getFieldValue(i, mapping.getColumnTypeFont());
592
                        t = t.concat(valTypeFont.toString());
593
                }
594

    
595
                if (mapping.getColumnStyleFont() != -1) {
596
                        Value valStyleFont = ds.getFieldValue(i,
597
                                        mapping.getColumnStyleFont());
598
                        t = t.concat(valStyleFont.toString());
599
                }
600

    
601
                Value total = ValueFactory.createValue(t);
602

    
603
                return total;
604
        }
605

    
606
        /*
607
         * (non-Javadoc)
608
         *
609
         * @see com.iver.cit.gvsig.fmap.layers.layerOperations.RandomVectorialData#createIndex()
610
         */
611
        public void createSpatialIndex()  {
612
                // FJP: ESTO HABR? QUE CAMBIARLO. PARA LAS CAPAS SECUENCIALES, TENDREMOS
613
                // QUE ACCEDER CON UN WHILE NEXT. (O mejorar lo de los FeatureVisitor
614
                // para que acepten recorrer sin geometria, solo con rectangulos.
615
                // AZABALA: Como no tengo claro de donde se crean las capas de textos
616
                // el ?ndice espacial creado seguir? siendo el Quadtree en memoria
617
                // de JTS (QuadtreeJts es un adapter a nuestra api de indices)
618
                spatialIndex = new QuadtreeJts();
619

    
620
                ReadableVectorial va = getSource();
621
                ICoordTrans ct = getCoordTrans();
622
                BoundedShapes shapeBounds = (BoundedShapes) va.getDriver();
623

    
624
                try {
625
                        va.start();
626

    
627
                        for (int i = 0; i < va.getShapeCount(); i++) {
628
                                Rectangle2D r = null;
629
                                IGeometry geom = va.getShape(i);
630
                                if (geom != null) {
631
                                        r = geom.getBounds2D();
632
                                } else {
633
                                        r = shapeBounds.getShapeBounds(i);
634
                                }
635

    
636
                                // TODO: MIRAR COMO SE TRAGAR?A ESTO LO DE LAS REPROYECCIONES
637
                                if (ct != null) {
638
                                        r = ct.convert(r);
639
                                }
640

    
641
                                if (r != null) {
642
                                        spatialIndex.insert(r, i);
643
                                }
644
                        } // for
645

    
646
                        va.stop();
647
                } catch (ExpansionFileReadException e) {
648
                        NotificationManager.addError(this.getName(),e);
649
                } catch (ReadDriverException e) {
650
                        NotificationManager.addError(this.getName(),e);
651
                }
652
        }
653

    
654
        /**
655
         * DOCUMENT ME!
656
         * @throws ReadDriverException
657
         *
658
         * @throws DriverException DOCUMENT ME!
659
         */
660
        public void setSelectedEditing() throws ReadDriverException {
661
                FBitSet bitSet = getRecordset().getSelection();
662

    
663
                if (bitSet.cardinality() == 0) {
664
                        return;
665
                }
666

    
667
                indexEditing = bitSet.nextSetBit(0);
668
        }
669

    
670
        public void setInEdition(int i) {
671
                indexEditing = i;
672
        }
673

    
674
        /**
675
         * DOCUMENT ME!
676
         *
677
         * @return DOCUMENT ME!
678
         */
679
        public int getInEdition() {
680
                return indexEditing;
681
        }
682

    
683
        protected void setLegend() throws ReadDriverException, LegendLayerException {
684
                getSource().getRecordset().start();
685
                aLegend.setFieldName(getSource().getRecordset().getFieldName(mapping.getColumnText()));
686
                setLegend(aLegend);
687
                getSource().getRecordset().stop();
688
        }
689

    
690
        /**
691
         * DOCUMENT ME!
692
         *
693
         * @return DOCUMENT ME!
694
         */
695
        public Strategy getStrategy() {
696
                return strategy;
697
        }
698

    
699
        /**
700
         * DOCUMENT ME!
701
         *
702
         * @param b DOCUMENT ME!
703
         * @throws StartEditionLayerException
704
         *
705
         * @throws EditionException DOCUMENT ME!
706
         */
707
        public void setEditing(boolean b) throws StartEditionLayerException {
708
                super.setEditing(b);
709
                try {
710
                        if (b) {
711
                                Annotation_EditableAdapter aea = new Annotation_EditableAdapter(this);
712

    
713
                                aea.setOriginalVectorialAdapter(((VectorialEditableAdapter) super.getSource()).getOriginalAdapter());
714

    
715
                                ((VectorialEditableAdapter) super.getSource()).cancelEdition(EditionEvent.GRAPHIC);
716
                                aea.start();
717

    
718
                                aea.setCoordTrans(getCoordTrans());
719
                                // CHEMA
720
                                aea.startEdition(EditionEvent.GRAPHIC);
721
                                setSource(aea);
722
                                getRecordset().setSelectionSupport(aea.getOriginalAdapter()
723
                                                .getRecordset()
724
                                                .getSelectionSupport());
725
                                aea.addEditionListener(this);
726
                        } else {
727
                        }
728

    
729
                } catch (ReadDriverException e) {
730
                        throw new StartEditionLayerException(this.getName(),e);
731
                } catch (CancelEditingLayerException e) {
732
                        throw new StartEditionLayerException(this.getName(),e);
733
                } catch (StartWriterVisitorException e) {
734
                        throw new StartEditionLayerException(this.getName(),e);
735
                }
736
                deleteSpatialIndex();
737
        }
738

    
739
        /**
740
         * DOCUMENT ME!
741
         *
742
         * @param layer DOCUMENT ME!
743
         *
744
         * @return DOCUMENT ME!
745
         * @throws ReadDriverException
746
         *
747
         * @throws DriverException DOCUMENT ME!
748
         * @throws FieldNotFoundException DOCUMENT ME!
749
         */
750
        public static Annotation_Layer createLayerFromVect(FLyrVect layer) throws ReadDriverException {
751
                Annotation_Layer la = new Annotation_Layer();
752
                FLyrVect lv=(FLyrVect)LayerFactory.createLayer(layer.getName(),layer.getSource().getDriver(),layer.getProjection());
753
                la.setSource(lv.getSource());
754
                la.setRecordset(lv.getRecordset());
755
                la.setProjection(layer.getProjection());
756
                la.getRecordset().setSelection(layer.getRecordset().getSelection());
757

    
758
                return la;
759
        }
760

    
761
        /**
762
         * DOCUMENT ME!
763
         */
764
        public void removingThisLayer() {
765
//                super.removingThisLayer();
766
                spatialIndex = null;
767
                aLegend = null;
768
                strategy = null;
769
                System.gc();
770
        }
771
        public IGeometry getTextWrappingGeometryInPixels(int unit,double height, String description,
772
                        double rotation, String type, int style, int numReg,ViewPort vp, IGeometry geom) {
773

    
774
                Shape shapeP=geom.getInternalShape();
775
                FPoint2D p = null;
776
                if (!(shapeP instanceof FPoint2D)) {
777
                        Rectangle2D rP=shapeP.getBounds2D();
778
                        p=new FPoint2D(rP.getX(),rP.getMaxY());
779
                }else {
780
                        p=(FPoint2D)shapeP;
781
                }
782
//                if (geom.getInternalShape() instanceof FPolygon2D){
783
//        r=new Rectangle2D.Double(r.getX()-r.getWidth()*0.5,r.getY()-r.getHeight()*0.5,r.getWidth(),r.getHeight());
784
//                }
785
//                p=new Point2D.Double(r.getCenterX(),r.getCenterY());
786
                if (unit!=-1) {
787
                        height = vp.fromMapDistance((int) (height)*MapContext.getDistanceTrans2Meter()[unit]);
788
                }
789

    
790
                Font font = new Font(type, style,
791
                                (int) (height));
792
                FontRenderContext frc = new FontRenderContext(ati,
793
                                false, true);
794
                GlyphVector gv = font.createGlyphVector(frc, description);
795
                Shape shape = gv.getOutline((float) p.getX(), (float) (p.getY()));// - height));
796
                Rectangle2D rGeom=shape.getBounds2D();
797
                IGeometry geomResult = ShapeFactory.createPolygon2D(new GeneralPathX(
798
                                rGeom));
799

    
800
                if (rotation != 0) {
801
                        AffineTransform Tx = AffineTransform.getRotateInstance(Math.toRadians(-rotation),p.getX(),p.getY());
802
                        geomResult.transform(Tx);
803
//                        geomResult.transform(AffineTransform.getRotateInstance(Math.toRadians(-rotation),p.getX(),p.getY()));
804
//                        geomResult.rotate(Math.toRadians(rotation), p.getX(),
805
//                        p.getY());
806
                }
807

    
808
                return geomResult;
809
        }
810
        public FLayer cloneLayer() throws Exception {
811
                Annotation_Layer clonedLayer = new Annotation_Layer();
812
                clonedLayer.setSource(getSource());
813
                clonedLayer.setVisible(isVisible());
814
                clonedLayer.setISpatialIndex(getISpatialIndex());
815
                clonedLayer.setName(getName());
816
                clonedLayer.setCoordTrans(getCoordTrans());
817
                clonedLayer.setLegend((IVectorLegend)getLegend());
818
                clonedLayer.mapping=mapping;
819
                clonedLayer.aLegend=aLegend;
820
                return clonedLayer;
821
        }
822
        private static void drawAnnotation(Graphics2D g2,int unit,Annotation_Layer layer,
823
                        Annotation_Legend legend,Point2D pAux, String text,ViewPort viewPort,PrintRequestAttributeSet properties) {
824
                SimpleTextSymbol textSymbol=(SimpleTextSymbol)legend.getDefaultSymbol();
825
                textSymbol.setText(text);
826
//                float x;
827
//                float y;
828
                // Las etiquetas que pongamos a nulo ser? porque no la queremos dibujar.
829
                // ?til para cuando queramos eliminar duplicados.
830
                if (text == null) {
831
                        return;
832
                }
833
                int size=textSymbol.getFont().getSize();
834
                double resolutionPrinting=0;
835
                if (unit!=-1){
836
                        size=viewPort.fromMapDistance(size*MapContext.getDistanceTrans2Meter()[unit]);
837
                }
838
                if (properties!=null){
839
                        PrintQuality resolution=(PrintQuality)properties.get(PrintQuality.class);
840
                        if (resolution.equals(PrintQuality.NORMAL)){
841
                                resolutionPrinting=300/72;
842
                        }else if (resolution.equals(PrintQuality.HIGH)){
843
                                resolutionPrinting=600/72;
844
                        }else if (resolution.equals(PrintQuality.DRAFT)){
845
                                resolutionPrinting=72/72;
846
                        }
847
                        size=(int)(size*resolutionPrinting);
848
                }
849

    
850
                textSymbol.draw(g2,viewPort.getAffineTransform(),new FPoint2D(pAux.getX(),pAux.getY()), null);
851
        }
852
}