Statistics
| Revision:

root / branches / v2_0_0_prep / applications / appgvSIG / src / org / gvsig / app / project / documents / view / legend / gui / LegendManager.java @ 31631

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 org.gvsig.app.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.util.ArrayList;
53
import java.util.Enumeration;
54
import java.util.Hashtable;
55
import java.util.prefs.Preferences;
56

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

    
71
import org.gvsig.andami.PluginServices;
72
import org.gvsig.andami.messages.NotificationManager;
73
import org.gvsig.fmap.mapcontext.exceptions.LegendLayerException;
74
import org.gvsig.fmap.mapcontext.layers.FLayer;
75
import org.gvsig.fmap.mapcontext.layers.FLayers;
76
import org.gvsig.fmap.mapcontext.layers.operations.Classifiable;
77
import org.gvsig.fmap.mapcontext.layers.operations.ClassifiableVectorial;
78
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
79
import org.gvsig.fmap.mapcontext.rendering.legend.IClassifiedVectorLegend;
80
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
81
import org.gvsig.fmap.mapcontext.rendering.legend.ISingleSymbolLegend;
82
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
83
import org.gvsig.gui.beans.swing.JButton;
84

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

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

    
120
        public static String defaultLegendFolderPath;
121
        {
122

    
123
                Preferences prefs = Preferences.userRoot().node( "gvsig.foldering" );
124
                defaultLegendFolderPath = prefs.get("LegendsFolder", "");
125
        }
126
        private ActionListener loadSaveLegendAction = new ActionListener() {
127
                public void actionPerformed(java.awt.event.ActionEvent e) {
128
//                        JComponent c = (JComponent) e.getSource();
129
//                        if (c.equals(getBtnSaveLegend())) {
130
//
131
//                                JLegendFileChooser jfc = new JLegendFileChooser(getLegendDrivers(),true);
132
//                                jfc.setAcceptAllFileFilterUsed(false);
133
//
134
//
135
//                                File basedir = null;
136
//                                jfc.setCurrentDirectory(basedir);
137
//                                if (jfc.showSaveDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
138
//
139
//                                        File file = jfc.getSelectedFile();
140
//                                        String version = jfc.getDriverVersion();
141
//                                        IFMapLegendDriver driver = jfc.getSuitableDriver();
142
//
143
//                                        if(!(driver instanceof FMapGVLDriver)){
144
//                                                Object[] options = {PluginServices.getText(this, "yes"),
145
//                                                                PluginServices.getText(this, "no")};
146
//
147
//                                                int answer = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
148
//                                                                PluginServices.getText(this, "not_GVL_save_question")+"\n"+
149
//                                                                PluginServices.getText(this, "desea_continuar"),
150
//                                                                PluginServices.getText(this, "confirmation_dialog"),
151
//                                                                JOptionPane.YES_NO_OPTION,
152
//                                                                JOptionPane.QUESTION_MESSAGE,
153
//                                                                null,
154
//                                                                options, options[1]);
155
//                                                if (answer!=JOptionPane.OK_OPTION) {
156
//                                                        // 'Cancel' pressed or window closed: don't save anythig, exit save dialog
157
//                                                        return;
158
//                                                }
159
//                                        }
160
//
161
//                                        if (file.exists()) {
162
//                                                Object[] options = {PluginServices.getText(this, "yes"),
163
//                                                                PluginServices.getText(this, "no"),
164
//                                                                PluginServices.getText(this, "Cancel")};
165
//
166
//                                                int answer = JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
167
//                                                                PluginServices.getText(this, "fichero_ya_existe_seguro_desea_guardarlo"),
168
//                                                                PluginServices.getText(this, "confirmation_dialog"),
169
//                                                                JOptionPane.YES_NO_CANCEL_OPTION,
170
//                                                                JOptionPane.QUESTION_MESSAGE,
171
//                                                                null,
172
//                                                                options, options[1]);
173
//                                                if (answer!=JOptionPane.OK_OPTION) {
174
//                                                        // 'Cancel' pressed or window closed: don't save anythig, exit save dialog
175
//                                                        return;
176
//                                                }
177
//                                        }
178
//
179
//
180
//                                        try {
181
//                                                driver.write(layer.getMapContext().getLayers(),layer, activePanel.getLegend(), file, version);
182
//
183
//                                        } catch (LegendDriverException e1) {
184
//                                                int type = e1.getType();
185
//                                                String message=PluginServices.getText(this, "could_not_save_legend")+":\n";
186
//
187
//                                                if ((type & LegendDriverException.SAVE_LEGEND_ERROR) != 0){
188
//                                                        type = type & ~LegendDriverException.SAVE_LEGEND_ERROR;
189
//                                                        message += PluginServices.getText(this, "error_writing_file")+".\n";
190
//                                                }
191
//                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_CREATION) != 0){
192
//                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_CREATION;
193
//                                                        message += "-"+ PluginServices.getText(this, "legend_format_not_yet_supported")+"\n";
194
//                                                }
195
//                                                if (type != 0) {
196
//                                                        message = "-"+PluginServices.getText(this, "unknown_error")+"\n";
197
//                                                }
198
//                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), message);
199
//                                        }
200
//                                }
201
//                        } else if (c.equals(getBtnLoadLegend())) {
202
//
203
//                                JLegendFileChooser jfc = new JLegendFileChooser(getLegendDrivers());
204
//                                jfc.setAcceptAllFileFilterUsed(false);
205
//
206
//                                if (jfc.showOpenDialog((Component) PluginServices.getMainFrame()) == JFileChooser.APPROVE_OPTION) {
207
//                                        File file=jfc.getSelectedFile();
208
//                                        IFMapLegendDriver driver = jfc.getSuitableDriver();
209
//                                        String path = file.getAbsolutePath();
210
//                                        defaultLegendFolderPath = path.substring(0, path.lastIndexOf(File.separator));
211
//
212
//                                        try {
213
//                                                table = driver.read(layer.getMapContext().getLayers(),layer, file);
214
//
215
//                                                if(table.containsKey(layer))
216
//                                                        applyLegend((ILegend) table.get(layer));
217
//
218
//
219
//                                        } catch (LegendDriverException e1) {
220
//                                                int type = e1.getType();
221
//                                                String message = PluginServices.getText(this, "the_legend_will_not_be_applied")+":\n";
222
//                                                boolean hasReason = false;
223
//
224
//                                                if ((type & LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND) != 0){
225
//                                                        type = type & ~LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND;
226
//                                                        message +="-"+ PluginServices.getText(this, "classification_field_does_not_exists")+"\n";
227
//                                                        hasReason = true;
228
//                                                }
229
//                                                if ((type & LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED) != 0){
230
//                                                        type = type & ~LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED;
231
//                                                        message += "-"+ PluginServices.getText(this, "legend_type_not_yet_supported")+"\n";
232
//                                                        hasReason = true;
233
//                                                }
234
//                                                if ((type & LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED) != 0){
235
//                                                        type = type & ~LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED;
236
//                                                        message += "-"+ PluginServices.getText(this, "unsupported_symbol_type")+"\n";
237
//                                                        hasReason = true;
238
//                                                }
239
//                                                if ((type & LegendDriverException.LAYER_SHAPETYPE_MISMATCH) != 0){
240
//                                                        type = type & ~LegendDriverException.LAYER_SHAPETYPE_MISMATCH;
241
//                                                        message += "-"+ PluginServices.getText(this, "layer_geometry_and_legend_types_are_incompatible")+"\n";
242
//                                                        hasReason = true;
243
//                                                }
244
//                                                if ((type & LegendDriverException.PARSE_LEGEND_FILE_ERROR) != 0){
245
//                                                        type = type & ~LegendDriverException.PARSE_LEGEND_FILE_ERROR;
246
//                                                        message += "-"+ PluginServices.getText(this, "failed_reading_file")+"\n";
247
//                                                        hasReason = true;
248
//                                                }
249
//                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION) != 0){
250
//                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION;
251
//                                                        message += "-"+ PluginServices.getText(this, "unsupported_legend_file_version")+"\n";
252
//                                                        hasReason = true;
253
//                                                }
254
//                                                if ((type & LegendDriverException.UNSUPPORTED_LEGEND_READING) != 0){
255
//                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
256
//                                                        message +="-"+ PluginServices.getText(this, "unsupported_legend_file_format")+"\n";
257
//                                                        hasReason = true;
258
//                                                }
259
//                                                if ((type & LegendDriverException.LAYER_NAME_NOT_FOUND) != 0){
260
//                                                        type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
261
//                                                        message +="-"+ PluginServices.getText(this, "could_not_find_layer")+"\n";
262
//                                                        hasReason = true;
263
//                                                }
264
//                                                if (!hasReason) {
265
//                                                        message = "-"+ PluginServices.getText(this, "unknown_error")+"\n";
266
//                                                }
267
//                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), message);
268
//                                        }
269
//                                }
270
//                        }
271
                }
272

    
273

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

    
292

    
293
        public LegendManager() {
294
                initialize();
295
        }
296

    
297
        private void initialize() {
298
                setLayout(new BorderLayout());
299
                add(getTopPanel(), BorderLayout.NORTH);
300
                add(getSplitPane(), BorderLayout.CENTER);
301
                setSize(500, 360);
302
                treeModel = new DefaultTreeModel(root);
303
        }
304

    
305
        private JSplitPane getSplitPane() {
306
                if (jSplitPane == null) {
307
                        jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
308
                        JPanel aux = new JPanel(new BorderLayout(0, 5));
309
                        aux.add(getLegendTreeScrollPane(), BorderLayout.CENTER);
310
                        aux.add(getPreviewPanel(), BorderLayout.SOUTH);
311
                        jSplitPane.setLeftComponent(aux);
312
                        jSplitPane.setRightComponent(getCentralPanel());
313
                        jSplitPane.setDividerLocation(150);
314
                }
315
                return jSplitPane;
316
        }
317

    
318
        private JPanel getCentralPanel() {
319
                if (jCentralPanel == null) {
320
                        jCentralPanel = new JPanel(new BorderLayout(0,10));
321
                        jCentralPanel.add(getTitleScroll(), BorderLayout.NORTH);
322
                        jCentralPanel.add(getJPanelContainer(), BorderLayout.CENTER);
323
                }
324
                return jCentralPanel;
325
        }
326

    
327
        private JScrollPane getJPanelContainer() {
328
                if (jPanelContainer == null) {
329
                        jPanelContainer = new JScrollPane();
330
                }
331
                return jPanelContainer;
332
        }
333

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

    
350
        private JButton getBtnSaveLegend() {
351
                if (btnSaveLegend == null) {
352
                        btnSaveLegend = new JButton(PluginServices.getText(this,"Guardar_leyenda")+"...");
353
                        btnSaveLegend.addActionListener(loadSaveLegendAction);
354
                }
355
                return btnSaveLegend;
356
        }
357

    
358
        private JButton getBtnLoadLegend() {
359
                if (btnLoadLegend == null) {
360
                        btnLoadLegend = new JButton(PluginServices.getText(this,"Recuperar_leyenda")+"...");
361
                        btnLoadLegend.addActionListener(loadSaveLegendAction);
362
                }
363
                return btnLoadLegend;
364
        }
365

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

    
403
        private JLabel getIconLabel() {
404
                if (iconLabel == null) {
405
                        iconLabel = new JLabel();
406
                        iconLabel.setVerticalAlignment(JLabel.CENTER);
407
                        iconLabel.setHorizontalAlignment(JLabel.CENTER);
408
                }
409

    
410
                return iconLabel;
411
        }
412

    
413
        /**
414
         * This method initializes jScrollPane
415
         *
416
         * @return javax.swing.JScrollPane
417
         */
418
        private JScrollPane getLegendTreeScrollPane() {
419
                if (legendTreeScrollPane == null) {
420
                        legendTreeScrollPane = new JScrollPane();
421
                        legendTreeScrollPane.setViewportView(getJTreeLegends());
422
                }
423
                return legendTreeScrollPane;
424
        }
425

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

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

    
458
                                                if (dirtyTree) {
459
                                                        // rebuild page tree
460
                                                        dirtyTree = false;
461

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

    
481
                                        }
482
                                        getJTreeLegends().setModel(treeModel);
483

    
484
                                } catch (InstantiationException e) {
485
                                        NotificationManager.addError("Trying to instantiate an interface" +
486
                                                        " or abstract class + "+pageClass.getName(), e);
487
                                } catch (IllegalAccessException e) {
488
                                        NotificationManager.addError("IllegalAccessException: does " +
489
                                                        pageClass.getName()        + " class have an anonymous" +
490
                                                        " constructor?", e);
491
                                }
492

    
493
                        }
494
                        getJTreeLegends().repaint();
495
                        empty = false;
496
                }
497
        }
498

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

    
510
                Enumeration e = root.breadthFirstEnumeration();
511
                while (e.hasMoreElements()) {
512
                        DefaultMutableTreeNode nodeAux = (DefaultMutableTreeNode) e.nextElement();
513
                        if (nodeAux != null) {
514
                                ILegendPanel legend = (ILegendPanel) nodeAux.getUserObject();
515
                                if (legend == null) continue; // Root node
516
                                if (legend.getTitle().equals(title)) {
517
                                        return nodeAux;
518
                                }
519
                        }
520
                }
521
                return null;
522
        }
523

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

    
566
        private JScrollPane getTitleScroll() {
567
                if (jTitleScrollPane == null) {
568
                        jTitleScrollPane = new JScrollPane();
569
                        jTitleScrollPane.setBounds(2, 2, 498, 42);
570
                        jTitleScrollPane.setViewportView(getTitleArea());
571
                }
572
                return jTitleScrollPane;
573
        }
574

    
575
        private JTree getJTreeLegends() {
576
                if (jTreeLegends == null) {
577
                        jTreeLegends = new JTree();
578
                        jTreeLegends.setRootVisible(false);
579
                        MyTreeCellRenderer treeCellRenderer = new MyTreeCellRenderer();
580
                        treeCellRenderer.setOpenIcon(null);
581
                        treeCellRenderer.setClosedIcon(null);
582
                        treeCellRenderer.setLeafIcon(null);
583

    
584
                        jTreeLegends.setCellRenderer(treeCellRenderer);
585
                        jTreeLegends.setShowsRootHandles(true);
586
                        jTreeLegends.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
587
                                public void valueChanged(javax.swing.event.TreeSelectionEvent e) {
588
                                        if (isTreeListenerDisabled) return;
589
                                        DefaultMutableTreeNode node = (DefaultMutableTreeNode)
590
                                        jTreeLegends.getLastSelectedPathComponent();
591

    
592
                                        if (node == null) return;
593
                                        setActivePage((ILegendPanel) node.getUserObject());
594
                                }
595
                        });
596
                        jTreeLegends.putClientProperty("JTree.linestyle", "Angled");
597
                        jTreeLegends.getSelectionModel().
598
                        setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
599
                }
600
                return jTreeLegends;
601
        }
602

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

    
620
                        activePanel.setData(layer, legend);
621
                        getTitleArea().setText(activePanel.getDescription());
622
                        jPanelContainer.setViewportView(activePanel.getPanel());
623
                }
624
        }
625

    
626

    
627
        private void setIcon(ImageIcon icon) {
628
                getIconLabel().setIcon(icon);
629
        }
630

    
631

    
632
        private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
633
                private static final long serialVersionUID = -6013698992263578041L;
634

    
635
                public MyTreeCellRenderer() {}
636

    
637
                public Component getTreeCellRendererComponent(
638
                                JTree tree,
639
                                Object value,
640
                                boolean sel,
641
                                boolean expanded,
642
                                boolean leaf,
643
                                int row,
644
                                boolean hasFocus) {
645

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

    
663
        }
664

    
665
        private void expandAndSelect(Object node) {
666
                isTreeListenerDisabled = true;
667
                // will expand the tree and select the node
668
                int i = 0;
669
                boolean exit = false;
670

    
671
                TreePath tp = null;
672
                // find the page in the tree
673
                while (i<jTreeLegends.getRowCount() && !exit) {
674
                        //see if this row is the node that we are looking for
675

    
676
                        tp = jTreeLegends.getPathForRow(i);
677
                        Object[] obj = tp.getPath();
678
                        for (int j = 0; j < obj.length && !exit ; j++) {
679
                                Object o = ((DefaultMutableTreeNode) obj[j]).getUserObject();
680

    
681
                                if (o!=null        && o.getClass().equals(node.getClass())        && o.equals(node)) {
682
                                        // found it! collapse the tree
683
                                        while (i>=0) {
684
                                                jTreeLegends.collapseRow(i);
685
                                                i--;
686
                                        }
687
                                        exit = true;
688
                                }
689
                        }
690
                        jTreeLegends.expandRow(i);
691
                        i++;
692
                }
693

    
694
                // expand the tree and set the selection
695
                if (tp != null) {
696
                        jTreeLegends.expandPath(tp);
697
                        jTreeLegends.setSelectionPath(tp);
698
                }
699
                isTreeListenerDisabled = false;
700
        }
701

    
702
        public String getName() {
703
                return PluginServices.getText(this,"Simbologia");
704
        }
705

    
706
        public void acceptAction() {
707
                // automatically handled by the ThemeManagerWindow
708
        }
709

    
710
        public void cancelAction() {
711
                // does nothing
712
        }
713

    
714
        public void applyAction() {
715
                legend = activePanel.getLegend();
716

    
717

    
718
                if (table != null && table.size() > 1)
719
                        applyRestOfLegends(table,layer.getMapContext().getLayers());
720

    
721
                /* try to apply the legend to all the active layers that
722
                 can accept it */
723
                FLayer[] activeLyrs = layer.getMapContext().getLayers().getActives();
724
                for (int i=0; i < activeLyrs.length; i++) {
725
                        FLayer laux=activeLyrs[i];
726

    
727
                        if (activeLyrs[i] instanceof FLayers){
728
                                laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
729
                        }
730

    
731
                        if (laux instanceof ClassifiableVectorial) {
732
                                ClassifiableVectorial aux2 = (ClassifiableVectorial) laux;
733
                                try {
734
                                        if (legend instanceof IClassifiedVectorLegend) {
735
                                                // Es una leyenda que necesita un recordset con un
736
                                                // nombre de campo. Comprobamos que ese recordset
737
                                                // tiene ese nombre de campo y es del tipo esperado
738
                                                IClassifiedVectorLegend cl = (IClassifiedVectorLegend) legend;
739

    
740
                                                if (aux2 instanceof FLyrVect) {
741

    
742
                                                        if (cl.getValues().length==0) {
743
                                                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
744
                                                                return;
745
                                                        }
746

    
747
                                                        aux2.setLegend((IVectorLegend) legend);
748
                                                }
749
                                        }
750
                                        else if (legend instanceof ISingleSymbolLegend)
751
                                                aux2.setLegend((IVectorLegend) legend);
752
                                } catch (LegendLayerException e) {
753
                                        NotificationManager.addError(PluginServices.getText(this, "legend_exception"), e);
754
                                }
755
                        }
756
                }
757
        }
758

    
759
        private void applyRestOfLegends(Hashtable<FLayer, ILegend> table2,FLayers layers) {
760

    
761
                for(int i = 0; i < layers.getLayersCount(); i++) {
762
                        FLayer my_layer= layers.getLayer(i);
763

    
764
                        if(!(my_layer instanceof FLayers)){
765
                                if(my_layer instanceof ClassifiableVectorial){
766
                                        try {
767
                                                if(table.containsKey(my_layer)){
768
                                                        ClassifiableVectorial lyr = (ClassifiableVectorial)my_layer;
769
                                                        lyr.setLegend((IVectorLegend) table.get(my_layer));
770
                                                }
771

    
772
                                        } catch (LegendLayerException e) {
773
                                                // TODO Auto-generated catch block
774
                                                e.printStackTrace();
775
                                        }
776
                                }
777
                        }
778
                        else
779
                                applyRestOfLegends(table,(FLayers) my_layer);
780
                }
781
        }
782

    
783
        @Override
784
        public void setModel(FLayer layer) {
785
                this.layer = layer;
786
                applyLegend(((Classifiable) layer).getLegend());
787
        }
788

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

    
812
//        public static void addLegendDriver(Class<? extends IFMapLegendDriver> legendDriverClass) {
813
//                if (!legendDriverPool.contains(legendDriverClass)) {
814
//                        legendDriverPool.add(legendDriverClass);
815
//                }
816
//        }
817
}