Statistics
| Revision:

svn-gvsig-desktop / branches / v10 / extensions / extAnnotations / src / com / iver / cit / gvsig / project / documents / view / legend / gui / FThemeManagerWindow2.java @ 11588

History | View | Annotate | Download (30.9 KB)

1
/*
2
 * Created on 24-ene-2005
3
 *
4
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
5
 *
6
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
7
 *
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
21
 *
22
 * For more information, contact:
23
 *
24
 *  Generalitat Valenciana
25
 *   Conselleria d'Infraestructures i Transport
26
 *   Av. Blasco Ib??ez, 50
27
 *   46010 VALENCIA
28
 *   SPAIN
29
 *
30
 *      +34 963862235
31
 *   gvsig@gva.es
32
 *      www.gvsig.gva.es
33
 *
34
 *    or
35
 *
36
 *   IVER T.I. S.A
37
 *   Salamanca 50
38
 *   46005 Valencia
39
 *   Spain
40
 *
41
 *   +34 963163400
42
 *   dac@iver.es
43
 */
44
package com.iver.cit.gvsig.project.documents.view.legend.gui;
45

    
46
import java.awt.BorderLayout;
47
import java.awt.Component;
48
import java.awt.event.ActionEvent;
49
import java.awt.event.ActionListener;
50
import java.io.File;
51
import java.io.FileInputStream;
52
import java.io.FileNotFoundException;
53
import java.io.FileOutputStream;
54
import java.io.FileWriter;
55
import java.io.InputStreamReader;
56
import java.io.OutputStreamWriter;
57
import java.io.Reader;
58
import java.io.UnsupportedEncodingException;
59
import java.text.NumberFormat;
60
import java.text.ParseException;
61

    
62
import javax.swing.JButton;
63
import javax.swing.JDialog;
64
import javax.swing.JFileChooser;
65
import javax.swing.JOptionPane;
66
import javax.swing.JPanel;
67
import javax.swing.JTabbedPane;
68

    
69
import org.exolab.castor.xml.MarshalException;
70
import org.exolab.castor.xml.Marshaller;
71
import org.exolab.castor.xml.ValidationException;
72

    
73
import com.hardcode.gdbms.engine.data.DataSource;
74
import com.hardcode.gdbms.engine.instruction.FieldNotFoundException;
75
import com.iver.andami.PluginServices;
76
import com.iver.andami.messages.NotificationManager;
77
import com.iver.andami.ui.mdiManager.IWindow;
78
import com.iver.andami.ui.mdiManager.WindowInfo;
79
import com.iver.cit.gvsig.ProjectExtension;
80
import com.iver.cit.gvsig.fmap.DriverException;
81
import com.iver.cit.gvsig.fmap.MapContext;
82
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
83
import com.iver.cit.gvsig.fmap.layers.Annotation_Layer;
84
import com.iver.cit.gvsig.fmap.layers.FLayer;
85
import com.iver.cit.gvsig.fmap.layers.FLayers;
86
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
87
import com.iver.cit.gvsig.fmap.layers.XMLException;
88
import com.iver.cit.gvsig.fmap.layers.layerOperations.AlphanumericData;
89
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
90
import com.iver.cit.gvsig.fmap.rendering.Annotation_Legend;
91
import com.iver.cit.gvsig.fmap.rendering.ClassifiedLegend;
92
import com.iver.cit.gvsig.fmap.rendering.Legend;
93
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
94
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
95
import com.iver.cit.gvsig.fmap.rendering.VectorialLegend;
96
import com.iver.cit.gvsig.gui.panels.LinkPanel;
97
import com.iver.cit.gvsig.project.documents.view.IProjectView;
98
import com.iver.cit.gvsig.project.documents.view.legend.CreateSpatialIndexMonitorableTask;
99
import com.iver.cit.gvsig.project.documents.view.legend.scale.gui.FPanelScaleManager;
100
import com.iver.utiles.GenericFileFilter;
101
import com.iver.utiles.XMLEntity;
102
import com.iver.utiles.swing.threads.IMonitorableTask;
103
import com.iver.utiles.xml.XMLEncodingUtils;
104
import com.iver.utiles.xmlEntity.generate.XmlTag;
105

    
106
/**
107
 * @author jmorell (jose.morell@gmail.com)
108
 * @version 24-ene-2005
109
 */
110
public final class FThemeManagerWindow2 extends AbstractPanel implements IWindow {
111
        private MapContext mapContext;
112
        private FLayer layer;
113
    private Legend renderer; // Le asignaremos la leyenda del primer tema activo.
114
        private FPanelScaleManager fPanelScaleManager;
115
    private FPanelLegendManager fPanelLegendManager;
116
    private PanelLegendAnnotation panelLegendAnnotation;
117
    private LinkPanel linkPanel;
118
    private JTabbedPane organizador = new JTabbedPane();  //  @jve:decl-index=0:
119
    private ComandosListener m_actionListener = new ComandosListener(this);
120
        //private ProjectView view;
121
        private NumberFormat nf = NumberFormat.getInstance();
122

    
123
    /**
124
     * Creates new form JPanel
125
     */
126
    public FThemeManagerWindow2() {
127
        initialize();
128
                this.setSize(650, 420);
129
    }
130

    
131
    /**
132
     * Sobrecarga del constructor. Este se utiliza cuando se llama a este
133
     * di?logo desde la barra de comandos.
134
     *
135
     */
136
    public FThemeManagerWindow2(FLayer l, MapContext fMap) {
137
            layer = l;
138
            mapContext = fMap;
139
            initialize();
140
            try {
141
                        ClassifiableVectorial aux = (ClassifiableVectorial) layer;
142
                        renderer = (Legend) aux.getLegend().cloneLegend();
143
                        fPanelScaleManager.setMapContext(mapContext);
144
                        fPanelLegendManager.setMapContext(mapContext);
145
                } catch (XMLException e) {
146
                        // TODO Auto-generated catch block
147
                        e.printStackTrace();
148
                } catch (DriverException e1) {
149
                        // TODO Auto-generated catch block
150
                        e1.printStackTrace();
151
                }
152

    
153
        fPanelScaleManager.setLayer(layer, renderer);
154
        if (!(layer instanceof Annotation_Layer)){
155
                fPanelLegendManager.setLayer(layer, renderer);
156
        }
157
        organizador.setSelectedIndex(0);
158

    
159
                this.setSize(650, 420);
160
    }
161

    
162
        /**
163
         * This method initializes this
164
         *
165
         * @return void
166
         */
167
        private  void initialize() {
168

    
169
                fPanelScaleManager = new FPanelScaleManager();
170
                fPanelLegendManager = new FPanelLegendManager();
171
                panelLegendAnnotation=new PanelLegendAnnotation();
172

    
173
                organizador.addTab(PluginServices.getText(this,"General"), fPanelScaleManager);
174
                if (layer instanceof Annotation_Layer){
175
                        organizador.addTab(PluginServices.getText(this,"annotations"),panelLegendAnnotation);
176
                }else{
177
                        organizador.addTab(PluginServices.getText(this,"Simbologia"), fPanelLegendManager);
178
                }
179
        JPanel panelButtons = new JPanel();
180

    
181
        JButton btnAceptar = new JButton(PluginServices.getText(this,"Aceptar"));
182
        btnAceptar.setActionCommand("OK");
183
        btnAceptar.addActionListener(m_actionListener);
184

    
185
        JButton btnApply = new JButton(PluginServices.getText(this,"Aplicar"));
186
        btnApply.setActionCommand("APPLY");
187
        btnApply.addActionListener(m_actionListener);
188

    
189
        JButton btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
190
        btnSaveLegend.setActionCommand("SAVE_LEGEND");
191
        btnSaveLegend.addActionListener(m_actionListener);
192

    
193
        JButton btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
194
        btnLoadLegend.setActionCommand("LOAD_LEGEND");
195
        btnLoadLegend.addActionListener(m_actionListener);
196

    
197
        JButton btnCancelar = new JButton(PluginServices.getText(this,"Cerrar"));
198
        btnCancelar.setActionCommand("CANCEL");
199
        btnCancelar.addActionListener(m_actionListener);
200

    
201
        panelButtons.add(btnApply, null);
202

    
203
                setLayout(new BorderLayout());
204
                panelButtons.setLayout(null);
205
                organizador.setPreferredSize(new java.awt.Dimension(640,390));
206
                btnAceptar.setBounds(9, 5, 89, 23);
207
                btnApply.setBounds(107, 5, 89, 23);
208
                btnSaveLegend.setBounds(205, 5, 159, 23);
209
                btnLoadLegend.setBounds(373, 5, 159, 23);
210
                btnCancelar.setBounds(541, 5, 89, 23);
211
                panelButtons.setPreferredSize(new java.awt.Dimension(493,33));
212
                add(organizador, java.awt.BorderLayout.NORTH);
213
                panelButtons.add(btnAceptar, null);
214
                add(panelButtons, java.awt.BorderLayout.SOUTH);
215
                panelButtons.add(btnSaveLegend, null);
216
                panelButtons.add(btnLoadLegend, null);
217
                panelButtons.add(btnCancelar, null);
218
//                if (!(layer instanceof Annotation_Layer)){
219
//                        btnSaveLegend.setEnabled(false);
220
//                        btnLoadLegend.setEnabled(false);
221
//                }
222
        }
223

    
224

    
225

    
226
    /**
227
     * En esta funci?n se coge el primer tema activo del TOC y se usa su
228
     * renderer para inicializar. Hay que llamarla SIEMPRE que se abra el
229
     * cuadro de di?logo, en el  openLegendManager() de la vista.
230
     *
231
     * @param mapContext TOC que abre este cuadro de di?logo.
232
     * @throws DriverException
233
     */
234
    public void setMapContext(MapContext mapContext) throws DriverException {
235
        this.mapContext = mapContext;
236
        layer = getFirstActiveLayerVect(mapContext.getLayers());
237
                try {
238
                        ClassifiableVectorial aux = (ClassifiableVectorial) layer;
239
                        renderer = (Legend) aux.getLegend().cloneLegend();
240
                } catch (XMLException e) {
241
                        // TODO Auto-generated catch block
242
                        e.printStackTrace();
243
                }
244
                fPanelScaleManager.setMapContext(mapContext);
245
                if (!(layer instanceof Annotation_Layer)){
246
                      fPanelLegendManager.setMapContext(mapContext);
247
            }
248
        actualizar();
249
    }
250

    
251
    /**
252
     * DOCUMENT ME!
253
     */
254
    private void actualizar() {
255
            FLayer lyrSelected = getFirstActiveLayerVect(mapContext.getLayers());
256

    
257
        fPanelScaleManager.setLayer(lyrSelected, renderer);
258
        if ((layer instanceof Annotation_Layer)){
259
                panelLegendAnnotation.setLayer(lyrSelected,renderer);
260
        }else{
261
                fPanelLegendManager.setLayer(lyrSelected, renderer);
262
        }
263
        organizador.setSelectedIndex(0);
264
    }
265

    
266
    private void btnApply_actionPerformed(ActionEvent evt) {
267
       // ClassifiableVectorial aux = (ClassifiableVectorial) layer;
268

    
269

    
270
            switch (fPanelLegendManager.getVisibleCard()) {
271
        case 0: // default symbol
272
            renderer = fPanelLegendManager.getM_defaultLegendPanel().getLegend();
273
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + PluginServices.getText(this,"_(Simbolo_unico)"));
274
            break;
275
        case 1: // Unique Values
276
            renderer = fPanelLegendManager.getM_valuesLegendPanel().getLegend();
277
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Valores_unicos)");
278
            break;
279
        case 2:// break values
280
                   renderer = fPanelLegendManager.getM_breaksLegendPanel().getLegend();
281
            fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Intervalos)");
282
                   break;
283
        case 3://text
284
                fPanelLegendManager.getJComboBox().getModel().setSelectedItem(layer.getName() + "_(Etiquetas_estandar)");
285
        }
286
        // System.out.println("Color punto 1 " + renderer.getDefaultSymbol().getColor().toString());
287
            // fPanelLegendManager.getM_labelsLegendPanel().setFSymbol(renderer.getDefaultSymbol());
288
            // boolean bShapesVisibles = renderer.getDefaultSymbol().isShapeVisible();
289
            fPanelLegendManager.getM_labelsLegendPanel().updateValuesFromControls((VectorialLegend)renderer);
290
            // renderer.getDefaultSymbol().setShapeVisible(bShapesVisibles);
291
        // System.out.println("Color punto 2 " + renderer.getDefaultSymbol().getColor().toString());
292
        try {
293
                        // Intentamos aplicar la leyenda a todas
294
            // las capas activas a las que se les pueda aplicar
295
            FLayer[] activeLyrs =  mapContext.getLayers().getActives();
296
            for (int i=0; i < activeLyrs.length; i++)
297
            {
298
                    FLayer laux=activeLyrs[i];
299
                    if (activeLyrs[i] instanceof FLayers){
300
                            laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
301
                    }
302
                if (laux instanceof ClassifiableVectorial)
303
                {
304
                    ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
305
                    if (renderer instanceof ClassifiedLegend)
306
                    {
307
                        // Es una leyenda que necesita un recordset con un
308
                        // nombre de campo. Comprobamos que ese recordset
309
                        // tiene ese nombre de campo y es del tipo esperado
310
                        ClassifiedLegend cl = (ClassifiedLegend) renderer;
311
                        if (aux2 instanceof AlphanumericData)
312
                        {
313
                            DataSource rs = ((AlphanumericData) aux2).getRecordset();
314
                            if (cl.getValues().length==0) {
315
                                    JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
316
                                    return;
317
                            }
318
                            int idField = rs.getFieldIndexByName(cl.getFieldName());
319
                            if (idField != -1)
320
                            {
321
                                //TODO: Aqu? deber?amos comprobar si el tipo de campo
322
                                // es el tipo de campo esperado.
323
                                    /*if (renderer instanceof VectorialUniqueValueLegend){
324
                                            ((VectorialUniqueValueLegend)renderer).setLabelHeightField(null);
325
                                            ((VectorialUniqueValueLegend)renderer).setLabelRotationField(null);
326
                                    }
327
                                    */
328
                                aux2.setLegend((VectorialLegend) renderer);
329
                            }
330

    
331
                        }
332
                    }
333
                    else if (renderer instanceof SingleSymbolLegend)
334
                        aux2.setLegend((VectorialLegend) renderer);
335
                }
336

    
337
            }
338
                        // aux.setLegend((VectorialLegend) m_Renderer);
339

    
340
                } catch (FieldNotFoundException e) {
341
                        // TODO Auto-generated catch block
342
                        e.printStackTrace();
343
                } catch (DriverException e) {
344
                        // TODO Auto-generated catch block
345
                        e.printStackTrace();
346
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
347
            // TODO Auto-generated catch block
348
            e.printStackTrace();
349
        }
350

    
351
                if (fPanelScaleManager.getJRadioButton1().isSelected()) {
352
                        try
353
                        {
354
                                layer.setMinScale((nf.parse(fPanelScaleManager.getJTextField1().getText())).doubleValue());
355
                        }
356
                        catch (ParseException ex)
357
                        {
358
                            if (fPanelScaleManager.getJTextField1().getText().compareTo("") == 0)
359
                                layer.setMinScale(-1);
360
                            else
361
                                System.err.print(ex.getLocalizedMessage());
362
                        }
363
                        try
364
                        {
365
                            layer.setMaxScale((nf.parse(fPanelScaleManager.getJTextField2().getText())).doubleValue());
366
                        }
367
                        catch (ParseException ex)
368
                        {
369
                            if (fPanelScaleManager.getJTextField2().getText().compareTo("") == 0)
370
                                layer.setMaxScale(-1);
371
                            else
372
                                System.err.print(ex.getLocalizedMessage());
373
                        }
374

    
375
                } else {
376
                layer.setMinScale(-1);
377
                layer.setMaxScale(-1);
378
                }
379
                if (!fPanelScaleManager.getLayerName().equals(layer.getName())){
380
                        layer.setName(fPanelScaleManager.getLayerName());
381
                }
382
        if (layer instanceof FLyrVect)
383
        {
384
            FLyrVect lyrVect = (FLyrVect) layer;
385
            if (fPanelScaleManager.isSpatialIndexSelected())
386
            {
387
//                if (lyrVect.getSpatialIndex() == null)
388
                    if(lyrVect.getISpatialIndex() == null)
389
                {
390
                        //AZABALA
391
                        try {
392
                                                PluginServices.
393
                                                        cancelableBackgroundExecution(getCreateSpatialIndexTask());
394
                                        } catch (DriverIOException e) {
395
                                                // TODO Auto-generated catch block
396
                                                e.printStackTrace();
397
                                        } catch (DriverException e) {
398
                                                // TODO Auto-generated catch block
399
                                                e.printStackTrace();
400
                                        }
401
//                    lyrVect.createSpatialIndex();
402
                }
403
            }
404
            //AZABALA
405
            /*
406
             * If we unselect the spatial index checkbox...Must we delete
407
             * spatial index file, or we only have to put Spatial Index
408
             * reference to null?. I have followed the second choice
409
             */
410
            else{
411
                lyrVect.deleteSpatialIndex();
412
            }
413

    
414

    
415
        }
416
                //layer.getFMap().invalidate();
417
                layer.getMapContext().callLegendChanged();
418
    }
419

    
420

    
421
    /**
422
     * Instanciates a ITask (@see com.iver.utiles.swing.threads.ITask)
423
     * to create a spatial index for the selected layer in background.
424
     * This task also allow to monitor process evolution, and to cancel
425
     * this process.
426
     * @throws DriverException
427
     * @throws DriverIOException
428
     */
429
    public IMonitorableTask getCreateSpatialIndexTask() throws DriverIOException,
430
                                                                                                                            DriverException{
431

    
432
//              FIXME REVISAR ESTO (Quizas lanzar TaskException)
433
                        return new CreateSpatialIndexMonitorableTask((FLyrVect)layer);
434
    }
435

    
436
    /**
437
     * DOCUMENT ME!
438
     *
439
     * @author Fernando Gonz?lez Cort?s
440
     */
441
    private class ComandosListener implements ActionListener {
442
        private FThemeManagerWindow2 fLayerPropertiesWindow;
443

    
444
        /**
445
         * Creates a new ComandosListener object.
446
         *
447
         * @param lg DOCUMENT ME!
448
         */
449
        public ComandosListener(FThemeManagerWindow2 fLayerPropertiesWindow) {
450
                this.fLayerPropertiesWindow = fLayerPropertiesWindow;
451
        }
452

    
453
        /* (non-Javadoc)
454
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
455
         */
456
        public void actionPerformed(ActionEvent e) {
457
            if (e.getActionCommand() == "OK") {
458
                // Implementaci?n para hacer funcionar el hyperlink ...
459
                //com.iver.cit.gvsig.gui.View theView = (com.iver.cit.gvsig.gui.View)PluginServices.getMDIManager().getActiveView();
460
                //ProjectView view = theView.getModel();
461
                    if (PluginServices.getMainFrame() != null)
462
                    {
463
                            IProjectView view = fPanelScaleManager.getView();
464
                            view.setTypeLink(fPanelScaleManager.getLinkType());
465
                            if (fPanelScaleManager.getSelectedLinkField()!=null)
466
                            {
467
                                    view.setSelectedField(fPanelScaleManager.getSelectedLinkField().toString().trim());
468
                                    view.setExtLink(fPanelScaleManager.getExtensionLink());
469
                            }
470
                    }
471
                //
472
                    if (layer instanceof Annotation_Layer){
473
                            fLayerPropertiesWindow.btnApply_actionPerformedAnnotation(e);
474
                }else{
475
                            fLayerPropertiesWindow.btnApply_actionPerformed(e);
476
                    }
477
                    if (PluginServices.getMainFrame() == null)
478
                            ((JDialog) (getParent().getParent().getParent().getParent())).dispose();
479
                    else
480
                            PluginServices.getMDIManager().closeWindow(FThemeManagerWindow2.this);
481
                System.out.println("Ok");
482
            } else if (e.getActionCommand() == "CANCEL") {
483
                    if (PluginServices.getMainFrame() == null)
484
                            ((JDialog) (getParent().getParent().getParent().getParent())).dispose();
485
                    else
486
                            PluginServices.getMDIManager().closeWindow(FThemeManagerWindow2.this);
487
                System.out.println("CANCEL");
488
            } else if (e.getActionCommand() == "APPLY") {
489
                    if (layer instanceof Annotation_Layer){
490
                            fLayerPropertiesWindow.btnApply_actionPerformedAnnotation(e);
491
                }else{
492
                            fLayerPropertiesWindow.btnApply_actionPerformed(e);
493
                    }
494
                System.out.println("APPLY");
495
            } else if (e.getActionCommand() == "LOAD_LEGEND") {
496
                        JFileChooser jfc = new JFileChooser();
497
                            jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
498
                                            PluginServices.getText(this, "tipo_de_leyenda")));
499
                            //jfc.addChoosableFileFilter(new GenericFileFilter("sld","sld"));
500

    
501
                            if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
502
                                    File file=jfc.getSelectedFile();
503
                                    if (!(file.getPath().endsWith(".gvl") || file.getPath().endsWith(".GVL")))
504
                                    {
505
                                            file=new File(file.getPath()+".gvl");
506
                                    }
507
                                    readLegend(file);
508
                                    if (layer instanceof Annotation_Layer){
509
                                            panelLegendAnnotation.setRenderer(renderer);
510
                                            panelLegendAnnotation.actualizar();
511
                                    }else{
512
                                fPanelLegendManager.setRenderer(renderer);
513
                                            fPanelLegendManager.actualizar();
514
                            }
515

    
516
                            }
517
            } else if (e.getActionCommand() == "SAVE_LEGEND") {
518
                    if (layer instanceof Annotation_Layer){
519

    
520
                            }else{
521
                                    fLayerPropertiesWindow.btnApply_actionPerformed(e);
522
                            }
523
                                JFileChooser jfc = new JFileChooser();
524
                                jfc.addChoosableFileFilter(new GenericFileFilter("sld","*.sld"));
525
                                jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
526
                                                PluginServices.getText(this, "tipo_de_leyenda")));
527

    
528

    
529
                                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION)
530
                                {
531
                                        File file=jfc.getSelectedFile();
532
                                        if (jfc.getFileFilter().accept(new File("dummy.sld")))
533
                                        {
534
                                                if (!(file.getPath().toLowerCase().endsWith(".sld"))){
535
                                                        file=new File(file.getPath()+".sld");
536
                                                }
537
                                                export2SLD(file);
538
                                        }
539
                                        else{
540
                                                if (!(file.getPath().toLowerCase().endsWith(".gvl"))){
541
                                                        file=new File(file.getPath()+".gvl");
542
                                                }
543
                                                writeLegend(file);
544
                                        }
545
                                }
546
            } else {}
547
        }
548
    }
549

    
550
    private void export2SLD(File file) {
551
                try {
552
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
553
                        writer.write( renderer.getSLDString(layer.getName()));
554
                        writer.close();
555

    
556
//                        Marshaller m = new Marshaller(writer);
557
//                        m.setEncoding("ISO-8859-1");
558
//                        m.marshal(renderer.getSLDString());
559
                } catch (Exception e) {
560
                        NotificationManager.addError(PluginServices.getText(this, "Error_exportando_SLD"), e);
561
                }
562
        }
563

    
564
    public void btnApply_actionPerformedAnnotation(ActionEvent evt) {
565
            try {
566
                    renderer = panelLegendAnnotation.getLegend();
567
                    panelLegendAnnotation.updateValuesFromControls((VectorialLegend)renderer);
568
                    // Intentamos aplicar la leyenda a todas
569
            // las capas activas a las que se les pueda aplicar
570
            FLayer[] activeLyrs =  mapContext.getLayers().getActives();
571
            for (int i=0; i < activeLyrs.length; i++)
572
            {
573
                    FLayer laux=activeLyrs[i];
574
                    if (activeLyrs[i] instanceof FLayers){
575
                            laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
576
                    }
577
                if (laux instanceof ClassifiableVectorial)
578
                {
579
                    ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
580
                    if (renderer instanceof ClassifiedLegend)
581
                    {
582
                        // Es una leyenda que necesita un recordset con un
583
                        // nombre de campo. Comprobamos que ese recordset
584
                        // tiene ese nombre de campo y es del tipo esperado
585
                        ClassifiedLegend cl = (ClassifiedLegend) renderer;
586
                        if (aux2 instanceof AlphanumericData)
587
                        {
588
                            DataSource rs = ((AlphanumericData) aux2).getRecordset();
589
                            if (cl.getValues().length==0) {
590
                                    JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
591
                                    return;
592
                            }
593
                            int idField = rs.getFieldIndexByName(cl.getFieldName());
594
                            if (idField != -1)
595
                            {
596
                                //TODO: Aqu? deber?amos comprobar si el tipo de campo
597
                                // es el tipo de campo esperado.
598
                                    /*if (renderer instanceof VectorialUniqueValueLegend){
599
                                            ((VectorialUniqueValueLegend)renderer).setLabelHeightField(null);
600
                                            ((VectorialUniqueValueLegend)renderer).setLabelRotationField(null);
601
                                    }
602
                                    */
603
                                aux2.setLegend((VectorialLegend) renderer);
604
                            }
605

    
606
                        }
607
                    }else if (renderer instanceof Annotation_Legend){
608
                            aux2.setLegend((VectorialLegend) renderer);
609
                    }
610
                    else if (renderer instanceof SingleSymbolLegend)
611
                        aux2.setLegend((VectorialLegend) renderer);
612
                }
613

    
614
            }
615
                        // aux.setLegend((VectorialLegend) m_Renderer);
616

    
617
                } catch (FieldNotFoundException e) {
618
                        // TODO Auto-generated catch block
619
                        e.printStackTrace();
620
                } catch (DriverException e) {
621
                        // TODO Auto-generated catch block
622
                        e.printStackTrace();
623
                } catch (com.hardcode.gdbms.engine.data.driver.DriverException e) {
624
            // TODO Auto-generated catch block
625
            e.printStackTrace();
626
        }
627

    
628
                if (fPanelScaleManager.getJRadioButton1().isSelected()) {
629
                        try
630
                        {
631
                                layer.setMinScale((nf.parse(fPanelScaleManager.getJTextField1().getText())).doubleValue());
632
                        }
633
                        catch (ParseException ex)
634
                        {
635
                            if (fPanelScaleManager.getJTextField1().getText().compareTo("") == 0)
636
                                layer.setMinScale(-1);
637
                            else
638
                                System.err.print(ex.getLocalizedMessage());
639
                        }
640
                        try
641
                        {
642
                            layer.setMaxScale((nf.parse(fPanelScaleManager.getJTextField2().getText())).doubleValue());
643
                        }
644
                        catch (ParseException ex)
645
                        {
646
                            if (fPanelScaleManager.getJTextField2().getText().compareTo("") == 0)
647
                                layer.setMaxScale(-1);
648
                            else
649
                                System.err.print(ex.getLocalizedMessage());
650
                        }
651

    
652
                } else {
653
                layer.setMinScale(-1);
654
                layer.setMaxScale(-1);
655
                }
656
                if (!fPanelScaleManager.getLayerName().equals(layer.getName())){
657
                        layer.setName(fPanelScaleManager.getLayerName());
658
                }
659
        if (layer instanceof FLyrVect)
660
        {
661
            FLyrVect lyrVect = (FLyrVect) layer;
662
            if (fPanelScaleManager.isSpatialIndexSelected())
663
            {
664
//                if (lyrVect.getSpatialIndex() == null)
665
                    if(lyrVect.getISpatialIndex() == null)
666
                {
667
                        //AZABALA
668
                        try {
669
                                                PluginServices.
670
                                                        cancelableBackgroundExecution(getCreateSpatialIndexTask());
671
                                        } catch (DriverIOException e) {
672
                                                // TODO Auto-generated catch block
673
                                                e.printStackTrace();
674
                                        } catch (DriverException e) {
675
                                                // TODO Auto-generated catch block
676
                                                e.printStackTrace();
677
                                        }
678
//                    lyrVect.createSpatialIndex();
679
                }
680
            }
681
            //AZABALA
682
            /*
683
             * If we unselect the spatial index checkbox...Must we delete
684
             * spatial index file, or we only have to put Spatial Index
685
             * reference to null?. I have followed the second choice
686
             */
687
            else{
688
                lyrVect.deleteSpatialIndex();
689
            }
690

    
691

    
692
        }
693
                //layer.getFMap().invalidate();
694
                layer.getMapContext().callLegendChanged();
695

    
696
        }
697

    
698
        private void writeLegend(File file) {
699
                try {
700
                        FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
701
            OutputStreamWriter writer = new OutputStreamWriter(fos, ProjectExtension.PROJECTENCODING);
702
                        Marshaller m = new Marshaller(writer);
703
                        m.setEncoding(ProjectExtension.PROJECTENCODING);
704
                        XMLEntity xml = renderer.getXMLEntity();
705
                        xml.putProperty("followHeaderEncoding", true);
706
                        m.marshal(xml.getXmlTag());
707
                } catch (Exception e) {
708
                        NotificationManager.addError(PluginServices.getText(this, "Error_guardando_la_leyenda"), e);
709
                }
710
        }
711

    
712
        public void readLegend(File file) {
713
                File xmlFile = new File(file.getAbsolutePath());
714
                try {
715
                        String encoding = XMLEncodingUtils.getEncoding(new FileInputStream(xmlFile));
716
                        InputStreamReader reader=null;
717
                        if (encoding!=null) {
718
                                try {
719
                                        reader = new InputStreamReader(new FileInputStream(xmlFile), encoding);
720
                                        renderer= readLegend(reader, true);
721
                                } catch (UnsupportedEncodingException e) {
722
                                        reader = new InputStreamReader(new FileInputStream(xmlFile),"ISO-8859-1");
723
                                        try {
724
                                                renderer= readLegend(reader, false);
725
                                        } catch (UnsupportedEncodingException e1) {
726
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
727
                                                return;
728
                                        }
729
                                }
730
                        }
731
                        else {
732
                                reader = new InputStreamReader(new FileInputStream(xmlFile),"UTF-8");
733
                                try {
734
                                        renderer= readLegend(reader, false);
735
                                } catch (UnsupportedEncodingException e1) {
736
                                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, e1.getLocalizedMessage()));
737
                                        return;
738
                                }
739
                        }
740
                } catch (FileNotFoundException e) {
741
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "fichero_incorrecto"));
742
                        return;
743
                } catch (UnsupportedEncodingException e) {
744
                        e.printStackTrace();
745
                }
746
        }
747
        public Legend readLegend(Reader reader, boolean encodingFollowed) throws UnsupportedEncodingException {
748
                Legend legend = null;
749

    
750
                try {
751
                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
752
                        XMLEntity xml=new XMLEntity(tag);
753
                        if (encodingFollowed) {
754
                                if (xml.contains("followHeaderEncoding")) {
755
                                        boolean useEncoding = xml.getBooleanProperty("followHeaderEncoding");
756
                                        if (!useEncoding) {
757
                                                throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
758
                                        }
759
                                }
760
                                else {
761
                                        // Old projects didn't contain followHeaderEncoding and they were
762
                                        // not correctly encoded. We throw an exception now, and we'll try
763
                                        // to reopen the project
764
                                        // using the default system encoding.
765
                                        throw new UnsupportedEncodingException("the encoding specified in the xml header is not safe");
766
                                }
767
                        }
768

    
769
                        legend = LegendFactory.createFromXML(xml);
770
                        return legend;
771
                }  catch (MarshalException e) {
772
//                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
773
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
774
                        //NotificationManager.addError("Al leer el proyecto", e);
775
                } catch (ValidationException e) {
776
//                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
777
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
778
                        //NotificationManager.addError("Al leer el proyecto", e);
779
                } catch (XMLException e) {
780
//                        PluginServices.getLogger().error(PluginServices.getText(this, "formato_incorrecto"),e);
781
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this, "formato_incorrecto"));
782
                        //NotificationManager.addError("Al leer el proyecto", e);
783
                }
784
                return null;
785
        }
786
        /* (non-Javadoc)
787
         * @see com.iver.andami.ui.mdiManager.View#getViewInfo()
788
         */
789
        public WindowInfo getWindowInfo() {
790
                // Solo se llama una vez
791
                WindowInfo viewInfo = new WindowInfo(WindowInfo.MODELESSDIALOG);
792
                viewInfo.setWidth(650);
793
                viewInfo.setHeight(420);
794
                viewInfo.setTitle(PluginServices.getText(this,"propiedades_de_la_capa"));
795
                return viewInfo;
796
        }
797

    
798
        /**
799
         * @see com.iver.mdiApp.ui.MDIManager.View#viewActivated()
800
         */
801
        /*public void viewActivated() {
802
        }
803

804
        public FMap getMapContext() {
805
                return mapContext;
806
        }
807
        public FLayer getLayer() {
808
                return layer;
809
        }
810
        public Legend getRenderer() {
811
                return renderer;
812
        }*/
813

    
814
        /**
815
         * @return Returns the organizador.
816
         */
817
        public JTabbedPane getOrganizador() {
818
                return organizador;
819
        }
820
        /**
821
         * @param organizador The organizador to set.
822
         */
823
        public void setOrganizador(JTabbedPane organizador) {
824
                this.organizador = organizador;
825
        }
826
}