Statistics
| Revision:

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

History | View | Annotate | Download (27.4 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.util.ArrayList;
54
import java.util.Enumeration;
55
import java.util.Hashtable;
56
import java.util.prefs.Preferences;
57

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

    
74
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
75
import org.gvsig.fmap.mapcontext.layers.FLayer;
76
import org.gvsig.fmap.mapcontext.layers.FLayers;
77
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
78
import org.gvsig.fmap.mapcontext.layers.operations.ClassifiableVectorial;
79
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
80
import org.gvsig.fmap.mapcontext.rendering.legend.IClassifiedVectorLegend;
81
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
82
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
83
import org.gvsig.fmap.mapcontext.rendering.legend.SingleSymbolLegend;
84
import org.gvsig.fmap.mapcontext.rendering.legend.driver.IFMapLegendDriver;
85
import org.gvsig.fmap.mapcontext.rendering.legend.driver.LegendDriverException;
86
import org.gvsig.fmap.mapcontext.rendering.legend.driver.gvl.FMapGVLDriver;
87
import org.gvsig.gui.beans.swing.JButton;
88

    
89
import com.iver.andami.PluginServices;
90
import com.iver.andami.messages.NotificationManager;
91
/**
92
 * Implements the panel which allows the user to control all the information about the
93
 * legends of a layer in order to improve the information that it offers to the user.
94
 * There are options to create, save or load an existing legend.
95
 *
96
 * @author jaume dominguez faus - jaume.dominguez@iver.es
97
 */
98
public class LegendManager extends AbstractThemeManagerPage {
99
        private static final long serialVersionUID = 7989057553773181019L;
100
        private static ArrayList<Class<? extends ILegendPanel>> legendPool = new ArrayList<Class<? extends ILegendPanel>>();
101
        private static ArrayList<Class<? extends IFMapLegendDriver>> legendDriverPool = new ArrayList<Class<? extends IFMapLegendDriver>>();
102

    
103
        private FLayer layer;
104
        private ILegend legend; // Le asignaremos la leyenda del primer tema activo.
105
        private Hashtable<Class<? extends ILegendPanel>, ILegendPanel> pages = new Hashtable<Class<? extends ILegendPanel>, ILegendPanel>();
106
        private JPanel topPanel = null;
107
        private JTextArea titleArea = null;
108
        private JPanel preview = null;
109
        private JScrollPane jTitleScrollPane = null;
110
        private JTree jTreeLegends;
111
        private ILegendPanel activePanel;
112
        private JScrollPane legendTreeScrollPane;
113
        private boolean dirtyTree;
114
        private DefaultMutableTreeNode root = new DefaultMutableTreeNode();
115
        private DefaultTreeModel treeModel;
116
        private JScrollPane jPanelContainer;
117
        private JPanel jCentralPanel;
118
        private JSplitPane jSplitPane;
119
        private boolean isTreeListenerDisabled;
120
        private JButton btnSaveLegend;
121
        private JButton btnLoadLegend;
122
        private Hashtable<FLayer, ILegend> table = null;
123
        private boolean empty = true;
124
        private JLabel iconLabel;
125

    
126
        public static String defaultLegendFolderPath;
127
        {
128

    
129
                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
130
                defaultLegendFolderPath = prefs.get("LegendsFolder", "");
131
        }
132
        private ActionListener loadSaveLegendAction = new ActionListener() {
133
                public void actionPerformed(java.awt.event.ActionEvent e) {
134
                        JComponent c = (JComponent) e.getSource();
135
                        if (c.equals(getBtnSaveLegend())) {
136

    
137
                                JLegendFileChooser jfc = new JLegendFileChooser(getLegendDrivers(),true);
138
                                jfc.setAcceptAllFileFilterUsed(false);
139

    
140

    
141
                                File basedir = null;
142
                                jfc.setCurrentDirectory(basedir);
143
                                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
144

    
145
                                        File file = jfc.getSelectedFile();
146
                                        String version = jfc.getDriverVersion();
147
                                        IFMapLegendDriver driver = jfc.getSuitableDriver();
148

    
149
                                        if(!(driver instanceof FMapGVLDriver)){
150
                                                Object[] options = {PluginServices.getText(this, "yes"),
151
                                                                PluginServices.getText(this, "no")};
152

    
153
                                                int answer = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
154
                                                                PluginServices.getText(this, "not_GVL_save_question")+"\n"+
155
                                                                PluginServices.getText(this, "desea_continuar"),
156
                                                                PluginServices.getText(this, "confirmation_dialog"),
157
                                                                JOptionPane.YES_NO_OPTION,
158
                                                                JOptionPane.QUESTION_MESSAGE,
159
                                                                null,
160
                                                                options, options[1]);
161
                                                if (answer!=JOptionPane.OK_OPTION) {
162
                                                        // 'Cancel' pressed or window closed: don't save anythig, exit save dialog
163
                                                        return;
164
                                                }
165
                                        }
166

    
167
                                        if (file.exists()) {
168
                                                Object[] options = {PluginServices.getText(this, "yes"),
169
                                                                PluginServices.getText(this, "no"),
170
                                                                PluginServices.getText(this, "Cancel")};
171

    
172
                                                int answer = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
173
                                                                PluginServices.getText(this, "fichero_ya_existe_seguro_desea_guardarlo"),
174
                                                                PluginServices.getText(this, "confirmation_dialog"),
175
                                                                JOptionPane.YES_NO_CANCEL_OPTION,
176
                                                                JOptionPane.QUESTION_MESSAGE,
177
                                                                null,
178
                                                                options, options[1]);
179
                                                if (answer!=JOptionPane.OK_OPTION) {
180
                                                        // 'Cancel' pressed or window closed: don't save anythig, exit save dialog
181
                                                        return;
182
                                                }
183
                                        }
184

    
185

    
186
                                        try {
187
                                                driver.write(layer.getMapContext().getLayers(),layer, activePanel.getLegend(), file, version);
188

    
189
                                        } catch (LegendDriverException e1) {
190
                                                int type = e1.getType();
191
                                                String message=PluginServices.getText(this, "could_not_save_legend")+":\n";
192

    
193
                                                if ((type & LegendDriverException.SAVE_LEGEND_ERROR) != 0){
194
                                                        type = type & ~LegendDriverException.SAVE_LEGEND_ERROR;
195
                                                        message += PluginServices.getText(this, "error_writing_file")+".\n";
196
                                                }
197
                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_CREATION) != 0){
198
                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_CREATION;
199
                                                        message += "-"+ PluginServices.getText(this, "legend_format_not_yet_supported")+"\n";
200
                                                }
201
                                                if (type != 0) {
202
                                                        message = "-"+PluginServices.getText(this, "unknown_error")+"\n";
203
                                                }
204
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), message);
205
                                        }
206
                                }
207
                        } else if (c.equals(getBtnLoadLegend())) {
208

    
209
                                JLegendFileChooser jfc = new JLegendFileChooser(getLegendDrivers());
210
                                jfc.setAcceptAllFileFilterUsed(false);
211

    
212
                                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
213
                                        File file=jfc.getSelectedFile();
214
                                        IFMapLegendDriver driver = jfc.getSuitableDriver();
215
                                        String path = file.getAbsolutePath();
216
                                        defaultLegendFolderPath = path.substring(0, path.lastIndexOf(File.separator));
217

    
218
                                        try {
219
                                                table = driver.read(layer.getMapContext().getLayers(),layer, file);
220

    
221
                                                if(table.containsKey(layer))
222
                                                        applyLegend((ILegend) table.get(layer));
223

    
224

    
225
                                        } catch (LegendDriverException e1) {
226
                                                int type = e1.getType();
227
                                                String message = PluginServices.getText(this, "the_legend_will_not_be_applied")+":\n";
228
                                                boolean hasReason = false;
229

    
230
                                                if ((type & LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND) != 0){
231
                                                        type = type & ~LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND;
232
                                                        message +="-"+ PluginServices.getText(this, "classification_field_does_not_exists")+"\n";
233
                                                        hasReason = true;
234
                                                }
235
                                                if ((type & LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED) != 0){
236
                                                        type = type & ~LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED;
237
                                                        message += "-"+ PluginServices.getText(this, "legend_type_not_yet_supported")+"\n";
238
                                                        hasReason = true;
239
                                                }
240
                                                if ((type & LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED) != 0){
241
                                                        type = type & ~LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED;
242
                                                        message += "-"+ PluginServices.getText(this, "unsupported_symbol_type")+"\n";
243
                                                        hasReason = true;
244
                                                }
245
                                                if ((type & LegendDriverException.LAYER_SHAPETYPE_MISMATCH) != 0){
246
                                                        type = type & ~LegendDriverException.LAYER_SHAPETYPE_MISMATCH;
247
                                                        message += "-"+ PluginServices.getText(this, "layer_geometry_and_legend_types_are_incompatible")+"\n";
248
                                                        hasReason = true;
249
                                                }
250
                                                if ((type & LegendDriverException.PARSE_LEGEND_FILE_ERROR) != 0){
251
                                                        type = type & ~LegendDriverException.PARSE_LEGEND_FILE_ERROR;
252
                                                        message += "-"+ PluginServices.getText(this, "failed_reading_file")+"\n";
253
                                                        hasReason = true;
254
                                                }
255
                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION) != 0){
256
                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION;
257
                                                        message += "-"+ PluginServices.getText(this, "unsupported_legend_file_version")+"\n";
258
                                                        hasReason = true;
259
                                                }
260
                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_READING) != 0){
261
                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
262
                                                        message +="-"+ PluginServices.getText(this, "unsupported_legend_file_format")+"\n";
263
                                                        hasReason = true;
264
                                                }
265
                                                if ((type & LegendDriverException.LAYER_NAME_NOT_FOUND) != 0){
266
                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
267
                                                        message +="-"+ PluginServices.getText(this, "could_not_find_layer")+"\n";
268
                                                        hasReason = true;
269
                                                }
270
                                                if (!hasReason) {
271
                                                        message = "-"+ PluginServices.getText(this, "unknown_error")+"\n";
272
                                                }
273
                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), message);
274
                                        }
275
                                }
276
                        }
277
                }
278

    
279

    
280
                private IFMapLegendDriver[] getLegendDrivers() {
281
                        Class<?>[] legendDriverClasses = legendDriverPool.toArray(new Class[0]);
282
                        ArrayList<IFMapLegendDriver> drivers = new ArrayList<IFMapLegendDriver>();
283
                        for (int i = 0; i < legendDriverClasses.length; i++) {
284
                                String message = PluginServices.getText(this, "adding_legend_file_format_support")+": ";
285
                                try {
286
                                        Class<?> c = legendDriverClasses[i];
287
                                        drivers.add((IFMapLegendDriver) c.newInstance());
288
                                } catch (Exception e) {
289
                                        NotificationManager.addError(message+PluginServices.getText(this, "failed"), e);
290
                                }
291
                                NotificationManager.addInfo(message+PluginServices.getText(this, "OK"));
292

    
293
                        }
294
                        return (IFMapLegendDriver[]) drivers.toArray(new IFMapLegendDriver[0]);
295
                };
296
        };
297

    
298

    
299
        public LegendManager() {
300
                initialize();
301
        }
302

    
303
        private void initialize() {
304
                setLayout(new BorderLayout());
305
                add(getTopPanel(), BorderLayout.NORTH);
306
                add(getSplitPane(), BorderLayout.CENTER);
307
                setSize(500, 360);
308
                treeModel = new DefaultTreeModel(root);
309
        }
310

    
311
        private JSplitPane getSplitPane() {
312
                if (jSplitPane == null) {
313
                        jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
314
                        JPanel aux = new JPanel(new BorderLayout(0, 5));
315
                        aux.add(getLegendTreeScrollPane(), BorderLayout.CENTER);
316
                        aux.add(getPreviewPanel(), BorderLayout.SOUTH);
317
                        jSplitPane.setLeftComponent(aux);
318
                        jSplitPane.setRightComponent(getCentralPanel());
319
                        jSplitPane.setDividerLocation(150);
320
                }
321
                return jSplitPane;
322
        }
323

    
324
        private JPanel getCentralPanel() {
325
                if (jCentralPanel == null) {
326
                        jCentralPanel = new JPanel(new BorderLayout(0,10));
327
                        jCentralPanel.add(getTitleScroll(), BorderLayout.NORTH);
328
                        jCentralPanel.add(getJPanelContainer(), BorderLayout.CENTER);
329
                }
330
                return jCentralPanel;
331
        }
332

    
333
        private JScrollPane getJPanelContainer() {
334
                if (jPanelContainer == null) {
335
                        jPanelContainer = new JScrollPane();
336
                }
337
                return jPanelContainer;
338
        }
339

    
340
        /**
341
         * This method initializes jPanel
342
         *
343
         * @return javax.swing.JPanel
344
         */
345
        private JPanel getTopPanel() {
346
                if (topPanel == null) {
347
                        topPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
348
                        topPanel.setPreferredSize(new Dimension(638, 31));
349
                        topPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
350
                        topPanel.add(getBtnSaveLegend(), null);
351
                        topPanel.add(getBtnLoadLegend(), null);
352
                }
353
                return topPanel;
354
        }
355

    
356
        private JButton getBtnSaveLegend() {
357
                if (btnSaveLegend == null) {
358
                        btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
359
                        btnSaveLegend.addActionListener(loadSaveLegendAction);
360
                }
361
                return btnSaveLegend;
362
        }
363

    
364
        private JButton getBtnLoadLegend() {
365
                if (btnLoadLegend == null) {
366
                        btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
367
                        btnLoadLegend.addActionListener(loadSaveLegendAction);
368
                }
369
                return btnLoadLegend;
370
        }
371

    
372
        /**
373
         * This method initializes jTextArea
374
         *
375
         * @return javax.swing.JTextArea
376
         */
377
        private JTextArea getTitleArea() {
378
                if (titleArea == null) {
379
                        titleArea = new JTextArea();
380
                        titleArea.setBackground(java.awt.SystemColor.control);
381
                        titleArea.setLineWrap(true);
382
                        titleArea.setRows(0);
383
                        titleArea.setWrapStyleWord(false);
384
                        titleArea.setEditable(false);
385
                        titleArea.setPreferredSize(new java.awt.Dimension(495,40));
386
                }
387
                return titleArea;
388
        }
389
        /**
390
         * This method initializes jPanel1
391
         *
392
         * @return javax.swing.JPanel
393
         */
394
        private JPanel getPreviewPanel() {
395
                if (preview == null) {
396
                        preview = new JPanel();
397
                        preview.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
398
                        preview.setBackground(java.awt.SystemColor.text);
399
                        preview.setLayout(new BorderLayout(5,5));
400
                        preview.add(getIconLabel());
401
                        preview.setPreferredSize(new Dimension(
402
                                        getSplitPane().getDividerLocation(),
403
                                        130));
404
                        preview.setBackground(Color.white);
405
                }
406
                return preview;
407
        }
408

    
409
        private JLabel getIconLabel() {
410
                if (iconLabel == null) {
411
                        iconLabel = new JLabel();
412
                        iconLabel.setVerticalAlignment(JLabel.CENTER);
413
                        iconLabel.setHorizontalAlignment(JLabel.CENTER);
414
                }
415

    
416
                return iconLabel;
417
        }
418

    
419
        /**
420
         * This method initializes jScrollPane
421
         *
422
         * @return javax.swing.JScrollPane
423
         */
424
        private JScrollPane getLegendTreeScrollPane() {
425
                if (legendTreeScrollPane == null) {
426
                        legendTreeScrollPane = new JScrollPane();
427
                        legendTreeScrollPane.setViewportView(getJTreeLegends());
428
                }
429
                return legendTreeScrollPane;
430
        }
431

    
432
        /**
433
         * <p>Adds a new fully-featured legend panel to the LegendManager.<br></p>
434
         *
435
         * <p><b>CAUTION:</b> Trying to add a child page whose parent hasn't been added yet
436
         * causes the application to fall in an infinite loop. This is a known
437
         * bug, sorry. Just avoid this case or try to fix it (lol).<br></p>
438
         *
439
         * <p><b>Notice</b> that there is no type check so if you add a non-ILegendPanel class,
440
         * you'll have a runtime error later.</p>
441
         * @param page, Class of type ILegendPanel
442
         */
443
        public static void addLegendPage(Class<? extends ILegendPanel> iLegendPanelClass) {
444
                if (!legendPool.contains(iLegendPanelClass)) {
445
                        legendPool.add(iLegendPanelClass);
446
                }
447
        }
448

    
449
        /**
450
         * Causes the component to be autofilled with the legend pages that
451
         * were added through the static method addLegendPage(ILegendPanel page)
452
         */
453
        private void fillDialog() {
454
                if (empty) {
455
                        for (int i = 0; i < legendPool.size(); i++) {
456
                                Class<?> pageClass = (Class<?>) legendPool.get(i);
457
                                ILegendPanel page;
458
                                try {
459
                                        page = (ILegendPanel) pageClass.newInstance();
460
                                        if (page.isSuitableFor(layer)) {
461
                                                // this legend can be applied to this layer
462
                                                pages.put(page.getClass(), page);
463

    
464
                                                if (dirtyTree) {
465
                                                        // rebuild page tree
466
                                                        dirtyTree = false;
467

    
468
                                                        ArrayList<ILegendPanel> legList = new ArrayList<ILegendPanel>(pages.values());
469
                                                        ArrayList<ILegendPanel> alreadyAdded = new ArrayList<ILegendPanel>();
470
                                                        DefaultTreeModel model = new DefaultTreeModel(root);
471
                                                        while (legList.size()>0) {
472
                                                                ILegendPanel legend = (ILegendPanel) legList.get(0);
473
                                                                Class<? extends ILegendPanel> parent = legend.getParentClass();
474
                                                                while (parent != null &&
475
                                                                                !alreadyAdded.contains(pages.get(parent))) {
476
                                                                        legend = (ILegendPanel) pages.get(parent);
477
                                                                }
478
                                                                doInsertNode(model, legend);
479
                                                                legList.remove(legend);
480
                                                                alreadyAdded.add(legend);
481
                                                        }
482
                                                        treeModel = model;
483
                                                        jTreeLegends.setModel(model);
484
                                                }
485
                                                doInsertNode(treeModel, page);
486

    
487
                                        }
488
                                        getJTreeLegends().setModel(treeModel);
489

    
490
                                } catch (InstantiationException e) {
491
                                        NotificationManager.addError("Trying to instantiate an interface" +
492
                                                        " or abstract class + "+pageClass.getName(), e);
493
                                } catch (IllegalAccessException e) {
494
                                        NotificationManager.addError("IllegalAccessException: does " +
495
                                                        pageClass.getName()        + " class have an anonymous" +
496
                                                        " constructor?", e);
497
                                }
498

    
499
                        }
500
                        getJTreeLegends().repaint();
501
                        empty = false;
502
                }
503
        }
504

    
505
        @SuppressWarnings("unchecked")
506
        private DefaultMutableTreeNode findNode(Class searchID) {
507
                String title;
508
                try {
509
                        title = ((ILegendPanel) Class.forName(searchID.getName()).newInstance()).getTitle();
510
                } catch (Exception e) {
511
                        // this should be impossible, but anyway this case will be treat as the node does not
512
                        // exist.
513
                        return null;
514
                }
515

    
516
                Enumeration e = root.breadthFirstEnumeration();
517
                while (e.hasMoreElements()) {
518
                        DefaultMutableTreeNode nodeAux = (DefaultMutableTreeNode) e.nextElement();
519
                        if (nodeAux != null) {
520
                                ILegendPanel legend = (ILegendPanel) nodeAux.getUserObject();
521
                                if (legend == null) continue; // Root node
522
                                if (legend.getTitle().equals(title)) {
523
                                        return nodeAux;
524
                                }
525
                        }
526
                }
527
                return null;
528
        }
529

    
530
        private void doInsertNode(DefaultTreeModel treeModel, ILegendPanel page) {
531
                dirtyTree = ((page.getParentClass() != null) && (findNode(page.getParentClass())==null));
532
                if (findNode(page.getClass()) != null) // It is already added
533
                        return;
534
                if (page.getParentClass() != null) {
535
                        if (pages.containsKey(page.getParentClass())) {
536
                                ILegendPanel parent = (ILegendPanel) pages.get(page.getParentClass());
537
                                DefaultMutableTreeNode nodeParent = findNode(parent.getClass());
538
                                if (nodeParent == null) {
539
                                        // the parent is empty
540
                                        // Recursively add it
541
                                        doInsertNode(treeModel, parent);
542
                                } else {
543
                                        DefaultMutableTreeNode nodeValue = new DefaultMutableTreeNode(page);
544
                                        int children = nodeParent.getChildCount();
545
                                        int pos=0;
546
                                        for (int i = 0; i < children; i++) {
547
                                                DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeModel.getChild(nodeParent, i);
548
                                                if (node.getUserObject() instanceof ILegendPanel) {
549
                                                        String pageTitle = ((ILegendPanel) node.getUserObject()).getTitle();
550
                                                        if (pageTitle.compareTo(page.getTitle()) < 0) ++pos;
551
                                                }
552
                                        }
553
                                        treeModel.insertNodeInto(nodeValue, nodeParent, pos);
554
                                }
555
                        }
556
                } else {
557
                        // First level node
558
                        DefaultMutableTreeNode nodeValue = new DefaultMutableTreeNode(page);
559
                        int children = root.getChildCount();
560
                        int pos=0;
561
                        for (int i = 0; i < children; i++) {
562
                                DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeModel.getChild(root, i);
563
                                if (node.getUserObject() instanceof ILegendPanel) {
564
                                        String pageTitle = ((ILegendPanel) node.getUserObject()).getTitle();
565
                                        if (pageTitle.compareTo(page.getTitle()) < 0) ++pos;
566
                                }
567
                        }
568
                        treeModel.insertNodeInto(nodeValue, root, pos);
569
                }
570
        }
571

    
572
        private JScrollPane getTitleScroll() {
573
                if (jTitleScrollPane == null) {
574
                        jTitleScrollPane = new JScrollPane();
575
                        jTitleScrollPane.setBounds(2, 2, 498, 42);
576
                        jTitleScrollPane.setViewportView(getTitleArea());
577
                }
578
                return jTitleScrollPane;
579
        }
580

    
581
        private JTree getJTreeLegends() {
582
                if (jTreeLegends == null) {
583
                        jTreeLegends = new JTree();
584
                        jTreeLegends.setRootVisible(false);
585
                        MyTreeCellRenderer treeCellRenderer = new MyTreeCellRenderer();
586
                        treeCellRenderer.setOpenIcon(null);
587
                        treeCellRenderer.setClosedIcon(null);
588
                        treeCellRenderer.setLeafIcon(null);
589

    
590
                        jTreeLegends.setCellRenderer(treeCellRenderer);
591
                        jTreeLegends.setShowsRootHandles(true);
592
                        jTreeLegends.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
593
                                public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
594
                                        if (isTreeListenerDisabled) return;
595
                                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
596
                                        jTreeLegends.getLastSelectedPathComponent();
597

    
598
                                        if (node == null) return;
599
                                        setActivePage((ILegendPanel) node.getUserObject());
600
                                }
601
                        });
602
                        jTreeLegends.putClientProperty("JTree.linestyle", "Angled");
603
                        jTreeLegends.getSelectionModel().
604
                        setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
605
                }
606
                return jTreeLegends;
607
        }
608

    
609
        private void setActivePage(ILegendPanel page) {
610
                if (page.getPanel() == null) {
611
                        // this is what happens when the user clicked in a parent node
612
                        // which only acts as a folder, and does not manage any legend
613
                        // then it expands and selects the first child
614
                        DefaultMutableTreeNode node = findNode(page.getClass());
615
                        if (treeModel.getChildCount(node)>0) {
616
                                DefaultMutableTreeNode dmn = (DefaultMutableTreeNode) treeModel.getChild(node, 0);
617
                                page = (ILegendPanel) dmn.getUserObject();
618
                                setActivePage(page);
619
                                expandAndSelect(page);
620
                        }
621
                } else {
622
                        // show the page
623
                        activePanel = page;
624
                        setIcon(activePanel.getIcon());
625

    
626
                        activePanel.setData(layer, legend);
627
                        getTitleArea().setText(activePanel.getDescription());
628
                        jPanelContainer.setViewportView(activePanel.getPanel());
629
                }
630
        }
631

    
632

    
633
        private void setIcon(ImageIcon icon) {
634
                getIconLabel().setIcon(icon);
635
        }
636

    
637

    
638
        private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
639
                private static final long serialVersionUID = -6013698992263578041L;
640

    
641
                public MyTreeCellRenderer() {}
642

    
643
                public Component getTreeCellRendererComponent(
644
                                JTree tree,
645
                                Object value,
646
                                boolean sel,
647
                                boolean expanded,
648
                                boolean leaf,
649
                                int row,
650
                                boolean hasFocus) {
651

    
652
                        super.getTreeCellRendererComponent(
653
                                        tree, value, sel,
654
                                        expanded, leaf, row,
655
                                        hasFocus);
656
                        if (value instanceof DefaultMutableTreeNode)
657
                        {
658
                                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
659
                                if (node.getUserObject() instanceof ILegendPanel)
660
                                {
661
                                        ILegendPanel legend = (ILegendPanel) node.getUserObject();
662
                                        this.setText(
663
                                                        legend.getPanel() == null ? "<html><b>"+legend.getTitle()+"</b></html>":legend.getTitle());
664
                                }
665
                        }
666
                        return this;
667
                }
668

    
669
        }
670

    
671
        private void expandAndSelect(Object node) {
672
                isTreeListenerDisabled = true;
673
                // will expand the tree and select the node
674
                int i = 0;
675
                boolean exit = false;
676

    
677
                TreePath tp = null;
678
                // find the page in the tree
679
                while (i<jTreeLegends.getRowCount() && !exit) {
680
                        //see if this row is the node that we are looking for
681

    
682
                        tp = jTreeLegends.getPathForRow(i);
683
                        Object[] obj = tp.getPath();
684
                        for (int j = 0; j < obj.length && !exit ; j++) {
685
                                Object o = ((DefaultMutableTreeNode) obj[j]).getUserObject();
686

    
687
                                if (o!=null        && o.getClass().equals(node.getClass())        && o.equals(node)) {
688
                                        // found it! collapse the tree
689
                                        while (i>=0) {
690
                                                jTreeLegends.collapseRow(i);
691
                                                i--;
692
                                        }
693
                                        exit = true;
694
                                }
695
                        }
696
                        jTreeLegends.expandRow(i);
697
                        i++;
698
                }
699

    
700
                // expand the tree and set the selection
701
                if (tp != null) {
702
                        jTreeLegends.expandPath(tp);
703
                        jTreeLegends.setSelectionPath(tp);
704
                }
705
                isTreeListenerDisabled = false;
706
        }
707

    
708
        public String getName() {
709
                return PluginServices.getText(this,"Simbologia");
710
        }
711

    
712
        public void acceptAction() {
713
                // automatically handled by the ThemeManagerWindow
714
        }
715

    
716
        public void cancelAction() {
717
                // does nothing
718
        }
719

    
720
        public void applyAction() {
721
                legend = activePanel.getLegend();
722

    
723

    
724
                if (table != null && table.size() > 1)
725
                        applyRestOfLegends(table,layer.getMapContext().getLayers());
726

    
727
                /* try to apply the legend to all the active layers that
728
                 can accept it */
729
                FLayer[] activeLyrs = layer.getMapContext().getLayers().getActives();
730
                for (int i=0; i < activeLyrs.length; i++) {
731
                        FLayer laux=activeLyrs[i];
732

    
733
                        if (activeLyrs[i] instanceof FLayers){
734
                                laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
735
                        }
736

    
737
                        if (laux instanceof ClassifiableVectorial) {
738
                                ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
739
                                try {
740
                                        if (legend instanceof IClassifiedVectorLegend) {
741
                                                // Es una leyenda que necesita un recordset con un
742
                                                // nombre de campo. Comprobamos que ese recordset
743
                                                // tiene ese nombre de campo y es del tipo esperado
744
                                                IClassifiedVectorLegend cl = (IClassifiedVectorLegend) legend;
745

    
746
                                                if (aux2 instanceof FLyrVect) {
747

    
748
                                                        if (cl.getValues().length==0) {
749
                                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
750
                                                                return;
751
                                                        }
752

    
753
                                                        aux2.setLegend((IVectorLegend) legend);
754
                                                }
755
                                        }
756
                                        else if (legend instanceof SingleSymbolLegend)
757
                                                aux2.setLegend((IVectorLegend) legend);
758
                                } catch (LegendLayerException e) {
759
                                        NotificationManager.addError(PluginServices.getText(this, "legend_exception"), e);
760
                                }
761
                        }
762
                }
763
        }
764

    
765
        private void applyRestOfLegends(Hashtable<FLayer, ILegend> table2,FLayers layers) {
766

    
767
                for(int i = 0; i < layers.getLayersCount(); i++) {
768
                        FLayer my_layer= layers.getLayer(i);
769

    
770
                        if(!(my_layer instanceof FLayers)){
771
                                if(my_layer instanceof ClassifiableVectorial){
772
                                        try {
773
                                                if(table.containsKey(my_layer)){
774
                                                        ClassifiableVectorial lyr = (ClassifiableVectorial)my_layer;
775
                                                        lyr.setLegend((IVectorLegend) table.get(my_layer));
776
                                                }
777

    
778
                                        } catch (LegendLayerException e) {
779
                                                // TODO Auto-generated catch block
780
                                                e.printStackTrace();
781
                                        }
782
                                }
783
                        }
784
                        else
785
                                applyRestOfLegends(table,(FLayers) my_layer);
786
                }
787
        }
788

    
789
        @Override
790
        public void setModel(FLayer layer) {
791
                this.layer = layer;
792
                applyLegend(((Classifiable) layer).getLegend());
793
        }
794

    
795
        /**
796
         * Applies the legend to the layer.
797
         *
798
         * @param aLegend , legend that the user wants to apply
799
         */
800
        private void applyLegend(ILegend aLegend) {
801
                this.legend = aLegend;
802
                fillDialog();
803
                Enumeration<Class<? extends ILegendPanel>> en = pages.keys();
804
                while (en.hasMoreElements()) {
805
                        ILegendPanel page = (ILegendPanel) pages.get(en.nextElement());
806
                        if (legend.getClass().equals(page.getLegendClass())) {
807
                                setActivePage(page);
808
                                expandAndSelect(page);
809
                                return;
810
                        }
811
                }
812
                NotificationManager.addWarning(
813
                                PluginServices.getText(this,
814
                                                "caution_no_registered_panel_associated_to_" +
815
                                                "loaded_legend_the_legend_wont_be_applied"));
816
        }
817

    
818
        public static void addLegendDriver(Class<? extends IFMapLegendDriver> legendDriverClass) {
819
                if (!legendDriverPool.contains(legendDriverClass)) {
820
                        legendDriverPool.add(legendDriverClass);
821
                }
822
        }
823
}