Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / view / legend / gui / LegendManager.java @ 16225

History | View | Annotate | Download (24.7 KB)

1
/*
2
 * Created on 08-feb-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.Color;
48
import java.awt.Component;
49
import java.awt.Dimension;
50
import java.awt.FlowLayout;
51
import java.awt.event.ActionListener;
52
import java.io.File;
53
import java.io.FileNotFoundException;
54
import java.io.FileReader;
55
import java.io.FileWriter;
56
import java.util.ArrayList;
57
import java.util.Enumeration;
58
import java.util.Hashtable;
59

    
60
import javax.swing.JCheckBox;
61
import javax.swing.JComboBox;
62
import javax.swing.JComponent;
63
import javax.swing.JFileChooser;
64
import javax.swing.JLabel;
65
import javax.swing.JOptionPane;
66
import javax.swing.JPanel;
67
import javax.swing.JScrollPane;
68
import javax.swing.JSplitPane;
69
import javax.swing.JTextArea;
70
import javax.swing.JTree;
71
import javax.swing.tree.DefaultMutableTreeNode;
72
import javax.swing.tree.DefaultTreeCellRenderer;
73
import javax.swing.tree.DefaultTreeModel;
74
import javax.swing.tree.TreePath;
75
import javax.swing.tree.TreeSelectionModel;
76

    
77
import org.exolab.castor.xml.MarshalException;
78
import org.exolab.castor.xml.Marshaller;
79
import org.exolab.castor.xml.ValidationException;
80
import org.gvsig.gui.beans.swing.JButton;
81

    
82
import com.iver.andami.PluginServices;
83
import com.iver.andami.messages.NotificationManager;
84
import com.iver.cit.gvsig.exceptions.layers.LegendLayerException;
85
import com.iver.cit.gvsig.fmap.layers.FLayer;
86
import com.iver.cit.gvsig.fmap.layers.FLayers;
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.Classifiable;
90
import com.iver.cit.gvsig.fmap.layers.layerOperations.ClassifiableVectorial;
91
import com.iver.cit.gvsig.fmap.rendering.IClassifiedVectorLegend;
92
import com.iver.cit.gvsig.fmap.rendering.ILegend;
93
import com.iver.cit.gvsig.fmap.rendering.IVectorLegend;
94
import com.iver.cit.gvsig.fmap.rendering.LegendFactory;
95
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
96
import com.iver.cit.gvsig.gui.styling.SymbolPreviewer;
97
import com.iver.utiles.GenericFileFilter;
98
import com.iver.utiles.XMLEntity;
99
import com.iver.utiles.xmlEntity.generate.XmlTag;
100
/**
101
 *
102
 * @author jaume dominguez faus - jaume.dominguez@iver.es
103
 */
104
public class LegendManager extends AbstractThemeManagerPage {
105
        private static ArrayList legendPool = new ArrayList();
106
    private FLayer layer;
107
    private ILegend legend; // Le asignaremos la leyenda del primer tema activo.
108
    private Hashtable pages = new Hashtable();
109
    private JPanel topPanel = null;
110
    private JLabel jLabel = null;
111
    private JComboBox jComboBox = null;
112
    private JCheckBox jCheckBox = null;
113
    private JTextArea titleArea = null;
114
    private SymbolPreviewer preview = null;
115
    private JScrollPane jTitleScrollPane = null;
116
    private JTree jTreeLegends;
117
    private ILegendPanel activePanel;
118
    private JScrollPane legendTreeScrollPane;
119
    private boolean dirtyTree;
120
    private DefaultMutableTreeNode root = new DefaultMutableTreeNode();
121
    private DefaultTreeModel treeModel;
122
    private JScrollPane jPanelContainer;
123
        private JPanel jCentralPanel;
124
        private JSplitPane jSplitPane;
125
        private boolean isTreeListenerDisabled;
126
        private JButton btnSaveLegend;
127
        private JButton btnLoadLegend;
128
        private ActionListener loadSaveLegendAction = new ActionListener() {
129
                public void actionPerformed(java.awt.event.ActionEvent e) {
130
                        JComponent c = (JComponent) e.getSource();
131
                        if (c.equals(getBtnSaveLegend())) {
132
                                JFileChooser jfc = new JFileChooser();
133
                                jfc.addChoosableFileFilter(new GenericFileFilter("sld","*.sld"));
134
                                jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
135
                                                PluginServices.getText(this, "tipo_de_leyenda")));
136
                                File basedir = null;
137
                                Object[] options = {PluginServices.getText(this, "yes"),
138
                            PluginServices.getText(this, "no"),
139
                            PluginServices.getText(this, "Cancel")};
140

    
141
                                while (true) {
142
                                        jfc.setCurrentDirectory(basedir);
143
                                        if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION)
144
                                        {
145
                                                File file=jfc.getSelectedFile();
146
                                                if (file.exists()) {
147
                                                        int answer = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
148
                                                                        PluginServices.getText(this, "error_file_exists"),
149
                                                                        PluginServices.getText(this, "confirmation_dialog"),
150
                                                                        JOptionPane.YES_NO_CANCEL_OPTION,
151
                                                                        JOptionPane.QUESTION_MESSAGE,
152
                                                                        null,
153
                                                                        options, options[1]);
154
                                                        if (answer==2 || answer==JOptionPane.CLOSED_OPTION) {
155
                                                                // 'Cancel' pressed or window closed: don't save anythig, exit save dialog
156
                                                                break;
157
                                                        }
158
                                                        else if (answer==1) {
159
                                                                // 'No' pressed, show jfc dialog again
160
                                                                basedir = file.getParentFile();
161
                                                                continue;
162
                                                        }
163
                                                        // "Yes" pressed, overwrite the file...
164
                                                }
165
                                                if (jfc.getFileFilter().accept(new File("dummy.sld")))
166
                                                {
167
                                                        if (!(file.getPath().toLowerCase().endsWith(".sld"))){
168
                                                                file=new File(file.getPath()+".sld");
169
                                                        }
170
                                                        export2SLD(file);
171
                                                }
172
                                                else{
173
                                                        if (!(file.getPath().toLowerCase().endsWith(".gvl"))){
174
                                                                file=new File(file.getPath()+".gvl");
175
                                                        }
176
                                                        writeLegend(file);
177
                                                }
178
                                                break;
179
                                        }
180
                                }
181
                        } else if (c.equals(getBtnLoadLegend())) {
182
                                JFileChooser jfc = new JFileChooser();
183
                            jfc.addChoosableFileFilter(new GenericFileFilter("gvl",
184
                                            PluginServices.getText(this, "tipo_de_leyenda")));
185
                            //jfc.addChoosableFileFilter(new GenericFileFilter("sld","sld"));
186

    
187
                            if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
188
                                    File file=jfc.getSelectedFile();
189
                                    if (!(file.getPath().endsWith(".gvl") || file.getPath().endsWith(".GVL")))        {
190
                                            file=new File(file.getPath()+".gvl");
191
                                    }
192
                                    loadLegend(file);
193
                            }
194
                        }
195
                };
196
        };
197
        
198
    private void writeLegend(File file) {
199
                try {
200
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
201
                        Marshaller m = new Marshaller(writer);
202
                        m.setEncoding("ISO-8859-1");
203
                        m.marshal(legend.getXMLEntity().getXmlTag());
204
                } catch (Exception e) {
205
                        NotificationManager.addError(PluginServices.getText(this, "Error_guardando_la_leyenda"), e);
206
                }
207
        }
208

    
209
        private void export2SLD(File file) {
210
                try {
211
                        FileWriter writer = new FileWriter(file.getAbsolutePath());
212
                        writer.write( legend.getSLDString(layer.getName()));
213
                        writer.close();
214

    
215
                } catch (Exception e) {
216
                        NotificationManager.addError(PluginServices.getText(this, "Error_exportando_SLD"), e);
217
                }
218
        }
219
        
220

    
221
         /**
222
    * Reads a legend file and loads into the this LegendManager
223
    * @param file
224
    */
225
   private void loadLegend(File file) {
226
           File xmlFile = new File(file.getAbsolutePath());
227
           FileReader reader;
228
           try {
229
                   reader = new FileReader(xmlFile);
230

    
231
                   XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
232

    
233
                   legend = LegendFactory.createFromXML(new XMLEntity(tag));
234
           } catch (FileNotFoundException e) {
235
                   // should be unreachable code
236
                   NotificationManager.addError(PluginServices.getText(this, "file_not_found"), e);
237
           } catch (MarshalException e) {
238
                   NotificationManager.addError(PluginServices.getText(this, "file_corrupt"), e);
239
           } catch (ValidationException e) {
240
                   // should be unreachable code
241
                   NotificationManager.addError("ValidationException", e);
242
           } catch (XMLException e) {
243
                   NotificationManager.addError(PluginServices.getText(this, "unsupported_legend"), e);
244
           }
245
   }
246
    public LegendManager() {
247
        initialize();
248
    }
249

    
250
    private void initialize() {
251
        setLayout(new BorderLayout());
252
        add(getTopPanel(), BorderLayout.NORTH);
253
        add(getSplitPane(), BorderLayout.CENTER);
254
        setSize(500, 360);
255
        treeModel = new DefaultTreeModel(root);
256
    }
257

    
258
    private JSplitPane getSplitPane() {
259
            if (jSplitPane == null) {
260
                    jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
261
                    JPanel aux = new JPanel(new BorderLayout(0, 5));
262
            aux.add(getLegendTreeScrollPane(), BorderLayout.CENTER);
263
            aux.add(getPreviewPanel(), BorderLayout.SOUTH);
264
                    jSplitPane.setLeftComponent(aux);
265
                    jSplitPane.setRightComponent(getCentralPanel());
266
                       jSplitPane.setDividerLocation(150);
267
            }
268
            return jSplitPane;
269
    }
270

    
271
    private JPanel getCentralPanel() {
272
        if (jCentralPanel == null) {
273
                jCentralPanel = new JPanel(new BorderLayout(0,10));
274
                jCentralPanel.add(getTitleScroll(), BorderLayout.NORTH);
275
                jCentralPanel.add(getJPanelContainer(), BorderLayout.CENTER);
276
        }
277
        return jCentralPanel;
278
    }
279

    
280
    private JScrollPane getJPanelContainer() {
281
        if (jPanelContainer == null) {
282
            jPanelContainer = new JScrollPane();
283
        }
284
        return jPanelContainer;
285
    }
286

    
287
    /**
288
     * This method initializes jPanel
289
     *
290
     * @return javax.swing.JPanel
291
     */
292
    private JPanel getTopPanel() {
293
        if (topPanel == null) {
294
            topPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
295
            topPanel.setPreferredSize(new Dimension(638, 31));
296
            topPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
297
            topPanel.add(getBtnSaveLegend(), null);
298
            topPanel.add(getBtnLoadLegend(), null);
299
        }
300
        return topPanel;
301
    }
302
    
303
    private JButton getBtnSaveLegend() {
304
        if (btnSaveLegend == null) {
305
            btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
306
            btnSaveLegend.addActionListener(loadSaveLegendAction);
307
        }
308
        return btnSaveLegend;
309
    }
310
  
311
    private JButton getBtnLoadLegend() {
312
        if (btnLoadLegend == null) {
313
            btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
314
            btnLoadLegend.addActionListener(loadSaveLegendAction);
315
        }
316
        return btnLoadLegend;
317
    }
318

    
319
    /**
320
     * This method initializes jTextArea
321
     *
322
     * @return javax.swing.JTextArea
323
     */
324
    private JTextArea getTitleArea() {
325
        if (titleArea == null) {
326
            titleArea = new JTextArea();
327
            titleArea.setBackground(java.awt.SystemColor.control);
328
            titleArea.setLineWrap(true);
329
            titleArea.setRows(0);
330
            titleArea.setWrapStyleWord(false);
331
            titleArea.setEditable(false);
332
            titleArea.setPreferredSize(new java.awt.Dimension(495,40));
333
        }
334
        return titleArea;
335
    }
336
    /**
337
     * This method initializes jPanel1
338
     *
339
     * @return javax.swing.JPanel
340
     */
341
    private SymbolPreviewer getPreviewPanel() {
342
        if (preview == null) {
343
            preview = new SymbolPreviewer();
344
            preview.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
345
            preview.setBackground(java.awt.SystemColor.text);
346
            preview.setPreferredSize(new Dimension(
347
                            getSplitPane().getDividerLocation(),
348
                            130));
349
            preview.setBackground(Color.white);
350
        }
351
        return preview;
352
    }
353

    
354
    /**
355
     * This method initializes jScrollPane
356
     *
357
     * @return javax.swing.JScrollPane
358
     */
359
    private JScrollPane getLegendTreeScrollPane() {
360
        if (legendTreeScrollPane == null) {
361
            legendTreeScrollPane = new JScrollPane();
362
            legendTreeScrollPane.setViewportView(getJTreeLegends());
363
        }
364
        return legendTreeScrollPane;
365
    }
366

    
367
    /**
368
     * <p>Adds a new fully-featured legend panel to the LegendManager.<br></p>
369
     *
370
     * <p><b>CAUTION:</b> Trying to add a child page whose parent hasn't been added yet
371
     * causes the application to fall in an infinite loop. This is a known
372
     * bug, sorry. Just avoid this case or try to fix it (lol).<br></p>
373
     *
374
     * <p><b>Notice</b> that there is no type check so if you add a non-ILegendPanel class,
375
     * you'll have a runtime error later.</p>
376
     * @param page, Class of type ILegendPanel
377
     */
378
    public static void addLegendPage(Class iLegendPanelClass) {
379
            if (!legendPool.contains(iLegendPanelClass)) {
380
                    legendPool.add(iLegendPanelClass);
381
            }
382
    }
383

    
384
    /**
385
     * Causes the component to be autofilled with the legend pages that
386
     * were added through the static method addLegendPage(ILegendPanel page)
387
     */
388
    private void fillDialog() {
389
            for (int i = 0; i < legendPool.size(); i++) {
390
                    Class pageClass = (Class) legendPool.get(i);
391
                    ILegendPanel page;
392
                    try {
393
                            page = (ILegendPanel) pageClass.newInstance();
394
                            if (page.isSuitableFor(layer)) {
395
                                    // this legend can be applied to this layer
396
                                    pages.put(page.getClass(), page);
397

    
398
                                    if (dirtyTree) {
399
                                            // rebuild page tree
400
                                            dirtyTree = false;
401

    
402
                                            ArrayList legList = new ArrayList(pages.values());
403
                                            ArrayList alreadyAdded = new ArrayList();
404
                                            DefaultTreeModel model = new DefaultTreeModel(root);
405
                                            while (legList.size()>0) {
406
                                                    ILegendPanel legend = (ILegendPanel) legList.get(0);
407
                                                    Class parent = legend.getParentClass();
408
                                                    while (parent != null &&
409
                                                                    !alreadyAdded.contains(pages.get(parent))) {
410
                                                            legend = (ILegendPanel) pages.get(parent);
411
                                                    }
412
                                                    doInsertNode(model, legend);
413
                                                    legList.remove(legend);
414
                                                    alreadyAdded.add(legend);
415
                                            }
416
                                            treeModel = model;
417
                                            jTreeLegends.setModel(model);
418
                                    }
419
                                    doInsertNode(treeModel, page);
420

    
421
                            }
422
                            getJTreeLegends().setModel(treeModel);
423

    
424
                    } catch (InstantiationException e) {
425
                            NotificationManager.addError("Trying to instantiate an interface" +
426
                                            " or abstract class + "+pageClass.getName(), e);
427
                    } catch (IllegalAccessException e) {
428
                            NotificationManager.addError("IllegalAccessException: does " +
429
                                            pageClass.getName()        + " class have an anonymous" +
430
                                            " constructor?", e);
431
                    }
432

    
433
            }
434
            getJTreeLegends().repaint();
435

    
436
    }
437

    
438
    private DefaultMutableTreeNode findNode(Class searchID) {
439
            String title;
440
            try {
441
                    title = ((ILegendPanel) Class.forName(searchID.getName()).newInstance()).getTitle();
442
            } catch (Exception e) {
443
                    // this should be impossible, but anyway this case will be treat as the node does not
444
                    // exist.
445
                    return null;
446
            }
447

    
448
        Enumeration e = root.breadthFirstEnumeration();
449
        while (e.hasMoreElements()) {
450
            DefaultMutableTreeNode nodeAux = (DefaultMutableTreeNode) e.nextElement();
451
            if (nodeAux != null) {
452
                ILegendPanel legend = (ILegendPanel) nodeAux.getUserObject();
453
                if (legend == null) continue; // Root node
454
                if (legend.getTitle().equals(title)) {
455
                    return nodeAux;
456
                }
457
            }
458
        }
459
        return null;
460
    }
461

    
462
    private void doInsertNode(DefaultTreeModel treeModel, ILegendPanel page) {
463
        dirtyTree = ((page.getParentClass() != null) && (findNode(page.getParentClass())==null));
464
        if (findNode(page.getClass()) != null) // It is already added
465
            return;
466
        if (page.getParentClass() != null) {
467
            if (pages.containsKey(page.getParentClass())) {
468
                ILegendPanel parent = (ILegendPanel) pages.get(page.getParentClass());
469
                DefaultMutableTreeNode nodeParent = findNode(parent.getClass());
470
                if (nodeParent == null) {
471
                        // the parent is empty
472
                    // Recursively add it
473
                    doInsertNode(treeModel, parent);
474
                } else {
475
                    DefaultMutableTreeNode nodeValue = new DefaultMutableTreeNode(page);
476
                    int children = nodeParent.getChildCount();
477
                    int pos=0;
478
                    for (int i = 0; i < children; i++) {
479
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeModel.getChild(nodeParent, i);
480
                        if (node.getUserObject() instanceof ILegendPanel) {
481
                            String pageTitle = ((ILegendPanel) node.getUserObject()).getTitle();
482
                            if (pageTitle.compareTo(page.getTitle()) < 0) ++pos;
483
                        }
484
                    }
485
                    treeModel.insertNodeInto(nodeValue, nodeParent, pos);
486
                }
487
            }
488
        } else {
489
                // First level node
490
            DefaultMutableTreeNode nodeValue = new DefaultMutableTreeNode(page);
491
            int children = root.getChildCount();
492
            int pos=0;
493
            for (int i = 0; i < children; i++) {
494
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeModel.getChild(root, i);
495
                if (node.getUserObject() instanceof ILegendPanel) {
496
                    String pageTitle = ((ILegendPanel) node.getUserObject()).getTitle();
497
                    if (pageTitle.compareTo(page.getTitle()) < 0) ++pos;
498
                }
499
            }
500
            treeModel.insertNodeInto(nodeValue, root, pos);
501
        }
502
    }
503

    
504
    private JScrollPane getTitleScroll() {
505
        if (jTitleScrollPane == null) {
506
            jTitleScrollPane = new JScrollPane();
507
            jTitleScrollPane.setBounds(2, 2, 498, 42);
508
            jTitleScrollPane.setViewportView(getTitleArea());
509
        }
510
        return jTitleScrollPane;
511
    }
512

    
513
    private JTree getJTreeLegends() {
514
        if (jTreeLegends == null) {
515
            jTreeLegends = new JTree();
516
            jTreeLegends.setRootVisible(false);
517
            MyTreeCellRenderer treeCellRenderer = new MyTreeCellRenderer();
518
            treeCellRenderer.setOpenIcon(null);
519
            treeCellRenderer.setClosedIcon(null);
520
            treeCellRenderer.setLeafIcon(null);
521

    
522
            jTreeLegends.setCellRenderer(treeCellRenderer);
523
            jTreeLegends.setShowsRootHandles(true);
524
            jTreeLegends.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
525
                    public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
526
                            if (isTreeListenerDisabled) return;
527
                            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
528
                            jTreeLegends.getLastSelectedPathComponent();
529

    
530
                            if (node == null) return;
531
                            setActivePage((ILegendPanel) node.getUserObject());
532
                    }
533
            });
534
            jTreeLegends.putClientProperty("JTree.linestyle", "Angled");
535
            jTreeLegends.getSelectionModel().
536
                    setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
537
        }
538
        return jTreeLegends;
539
    }
540

    
541
    private void setActivePage(ILegendPanel page) {
542
        if (page.getPanel() == null) {
543
                // this is what happens when the user clicked in a parent node
544
                // which only acts as a folder, and does not manage any legend
545
                // then it expands and selects the first child
546
            DefaultMutableTreeNode node = findNode(page.getClass());
547
            if (treeModel.getChildCount(node)>0) {
548
                DefaultMutableTreeNode dmn = (DefaultMutableTreeNode) treeModel.getChild(node, 0);
549
                page = (ILegendPanel) dmn.getUserObject();
550
                setActivePage(page);
551
                expandAndSelect(page);
552
            }
553
        } else {
554
                // show the page
555
            activePanel = page;
556
            getPreviewPanel().setSymbol(activePanel.getIconSymbol());
557
            
558
            activePanel.setData(layer, legend);
559
            getTitleArea().setText(activePanel.getDescription());
560
            jPanelContainer.setViewportView(activePanel.getPanel());
561
        }
562
    }
563

    
564

    
565
    private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
566
              private static final long serialVersionUID = -6013698992263578041L;
567

    
568
                public MyTreeCellRenderer() {}
569

    
570
        public Component getTreeCellRendererComponent(
571
                            JTree tree,
572
                            Object value,
573
                            boolean sel,
574
                            boolean expanded,
575
                            boolean leaf,
576
                            int row,
577
                            boolean hasFocus) {
578

    
579
            super.getTreeCellRendererComponent(
580
                            tree, value, sel,
581
                            expanded, leaf, row,
582
                            hasFocus);
583
            if (value instanceof DefaultMutableTreeNode)
584
            {
585
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
586
                if (node.getUserObject() instanceof ILegendPanel)
587
                {
588
                    ILegendPanel legend = (ILegendPanel) node.getUserObject();
589
                    this.setText(
590
                            legend.getPanel() == null ? "<html><b>"+legend.getTitle()+"</b></html>":legend.getTitle());
591
                }
592
            }
593
            return this;
594
        }
595

    
596
    }
597

    
598
        private void expandAndSelect(Object node) {
599
                isTreeListenerDisabled = true;
600
            // will expand the tree and select the node
601
            int i = 0;
602
            boolean exit = false;
603

    
604
            TreePath tp = null;
605
            // find the page in the tree
606
            while (i<jTreeLegends.getRowCount() && !exit) {
607
                    //see if this row is the node that we are looking for
608

    
609
                    tp = jTreeLegends.getPathForRow(i);
610
                    Object[] obj = tp.getPath();
611
                    for (int j = 0; j < obj.length && !exit ; j++) {
612
                                Object o = ((DefaultMutableTreeNode) obj[j]).getUserObject();
613

    
614
                                if (o!=null        && o.getClass().equals(node.getClass())        && o.equals(node)) {
615
                                // found it! collapse the tree
616
                                while (i>=0) {
617
                                        jTreeLegends.collapseRow(i);
618
                                        i--;
619
                                }
620
                                exit = true;
621
                        }
622
                        }
623
                    jTreeLegends.expandRow(i);
624
                    i++;
625
            }
626

    
627
            // expand the tree and set the selection
628
            if (tp != null) {
629
                    jTreeLegends.expandPath(tp);
630
                    jTreeLegends.setSelectionPath(tp);
631
            }
632
            isTreeListenerDisabled = false;
633
        }
634

    
635
        public String getName() {
636
                return PluginServices.getText(this,"Simbologia");
637
        }
638

    
639
        public void acceptAction() {
640
                // automatically handled by the ThemeManagerWindow
641
        }
642

    
643
        public void cancelAction() {
644
                // does nothing
645
        }
646

    
647
        public void applyAction() {
648
                legend = activePanel.getLegend();
649

    
650
                /* try to apply the legend to all the active layers that
651
                 can accept it */
652
                FLayer[] activeLyrs = layer.getMapContext().getLayers().getActives();
653
                for (int i=0; i < activeLyrs.length; i++) {
654
                        FLayer laux=activeLyrs[i];
655

    
656
                        if (activeLyrs[i] instanceof FLayers){
657
                                laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
658
                        }
659

    
660
                        if (laux instanceof ClassifiableVectorial) {
661
                                ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
662
                                try {
663
                                        if (legend instanceof IClassifiedVectorLegend) {
664
                                                // Es una leyenda que necesita un recordset con un
665
                                                // nombre de campo. Comprobamos que ese recordset
666
                                                // tiene ese nombre de campo y es del tipo esperado
667
                                                IClassifiedVectorLegend cl = (IClassifiedVectorLegend) legend;
668

    
669
                                                if (aux2 instanceof AlphanumericData) {
670

    
671
                                                        if (cl.getValues().length==0) {
672
                                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
673
                                                                return;
674
                                                        }
675

    
676
                                                                aux2.setLegend((IVectorLegend) legend);
677
                                                }
678
                                        }
679
                                        else if (legend instanceof SingleSymbolLegend)
680
                                                aux2.setLegend((IVectorLegend) legend);
681
                                } catch (LegendLayerException e) {
682
                                        NotificationManager.addError(PluginServices.getText(this, "legend_exception"), e);
683
                                }
684
                        }
685
                }
686
        }
687

    
688
        public void setModel(FLayer layer) {
689
                this.layer = layer;
690
                this.legend = ((Classifiable) layer).getLegend();
691
                fillDialog();
692
        Enumeration en = pages.keys();
693
        while (en.hasMoreElements()) {
694
                ILegendPanel page = (ILegendPanel) pages.get(en.nextElement());
695
                if (legend.getClass().equals(page.getLegendClass())) {
696
                        setActivePage(page);
697
                        expandAndSelect(page);
698
                }
699
        }
700
        }
701
}