Revision 37340

View differences:

branches/v2_0_0_prep/libraries/libFMap_mapcontext/src/org/gvsig/fmap/mapcontext/rendering/symbols/SymbolManager.java
42 42
 */
43 43
public interface SymbolManager {
44 44

  
45
    public static final String LEGEND_FILE_EXTENSION = ".gvsleg";
46
    
45 47
	/**
46 48
	 * Loads the symbols persisted into a folder. It loads the symbols through
47 49
	 * the use of the current {@link PersistenceManager}, loading all files
branches/v2_0_0_prep/libraries/libFMap_mapcontext/src/org/gvsig/fmap/mapcontext/impl/DefaultMapContextManager.java
32 32
import java.io.FileFilter;
33 33
import java.io.FileInputStream;
34 34
import java.lang.reflect.Method;
35
import java.security.acl.LastOwnerException;
35 36
import java.util.Collections;
36 37
import java.util.HashMap;
37 38
import java.util.Map;
......
484 485
			if (method != null){
485 486
				Object[] params = new Object[2];
486 487
				params[0] = dataStore;
487
				params[1] = "gvl";
488
				params[1] = SymbolManager.LEGEND_FILE_EXTENSION.substring(1);
488 489
				File file = (File)method.invoke(dataServerExplorer, params);
489 490
				if ((file != null) && (file.exists())){
490 491
					PersistenceManager persistenceManager = ToolsLocator.getPersistenceManager();
491
					PersistentState persistentState = persistenceManager.loadState(new FileInputStream(file));
492
					legend = (ILegend)persistenceManager.create(persistentState);
492
					FileInputStream is = new FileInputStream(file);
493
					legend = (ILegend) persistenceManager.getObject(is);
494
					is.close();
493 495
				}
494 496
			}	
495 497

  
branches/v2_0_0_prep/applications/appgvSIG/src/org/gvsig/app/project/documents/view/legend/gui/LegendManager.java
49 49
import java.awt.Dimension;
50 50
import java.awt.FlowLayout;
51 51
import java.awt.event.ActionListener;
52
import java.io.File;
53
import java.io.FileInputStream;
54
import java.io.FileNotFoundException;
55
import java.io.FileOutputStream;
56
import java.io.InputStream;
57
import java.io.OutputStream;
52 58
import java.util.ArrayList;
53 59
import java.util.Enumeration;
54 60
import java.util.Hashtable;
55 61
import java.util.prefs.Preferences;
56 62

  
57 63
import javax.swing.ImageIcon;
64
import javax.swing.JButton;
65
import javax.swing.JComponent;
66
import javax.swing.JFileChooser;
58 67
import javax.swing.JLabel;
59 68
import javax.swing.JOptionPane;
60 69
import javax.swing.JPanel;
......
62 71
import javax.swing.JSplitPane;
63 72
import javax.swing.JTextArea;
64 73
import javax.swing.JTree;
74
import javax.swing.filechooser.FileFilter;
65 75
import javax.swing.tree.DefaultMutableTreeNode;
66 76
import javax.swing.tree.DefaultTreeCellRenderer;
67 77
import javax.swing.tree.DefaultTreeModel;
......
78 88
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
79 89
import org.gvsig.fmap.mapcontext.rendering.legend.IClassifiedVectorLegend;
80 90
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
81
import org.gvsig.fmap.mapcontext.rendering.legend.ISingleSymbolLegend;
82 91
import org.gvsig.fmap.mapcontext.rendering.legend.IVectorLegend;
83
import org.gvsig.gui.beans.swing.JButton;
92
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
93
import org.gvsig.tools.ToolsLocator;
94
import org.gvsig.tools.persistence.PersistenceManager;
84 95

  
85 96
/**
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.
97
 * Implements the panel which allows the user to control all the information
98
 * about the
99
 * legends of a layer in order to improve the information that it offers to the
100
 * user.
88 101
 * There are options to create, save or load an existing legend.
89
 *
102
 * 
90 103
 * @author jaume dominguez faus - jaume.dominguez@iver.es
91 104
 */
92 105
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 106

  
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;
107
    private static final long serialVersionUID = 7989057553773181019L;
108
    private static ArrayList<Class<? extends ILegendPanel>> legendPool =
109
        new ArrayList<Class<? extends ILegendPanel>>();
110
    // private static ArrayList<Class<? extends IFMapLegendDriver>>
111
    // legendDriverPool = new ArrayList<Class<? extends IFMapLegendDriver>>();
119 112

  
120
	public static String defaultLegendFolderPath;
121
	{
113
    private FLayer layer;
114
    private ILegend legend; // Le asignaremos la leyenda del primer tema activo.
115
    private Hashtable<Class<? extends ILegendPanel>, ILegendPanel> pages =
116
        new Hashtable<Class<? extends ILegendPanel>, ILegendPanel>();
117
    private JPanel topPanel = null;
118
    private JTextArea titleArea = null;
119
    private JPanel preview = null;
120
    private JScrollPane jTitleScrollPane = null;
121
    private JTree jTreeLegends;
122
    private ILegendPanel activePanel;
123
    private JScrollPane legendTreeScrollPane;
124
    private boolean dirtyTree;
125
    private DefaultMutableTreeNode root = new DefaultMutableTreeNode();
126
    private DefaultTreeModel treeModel;
127
    private JScrollPane jPanelContainer;
128
    private JPanel jCentralPanel;
129
    private JSplitPane jSplitPane;
130
    private boolean isTreeListenerDisabled;
131
    private JButton btnSaveLegend;
132
    private JButton btnLoadLegend;
133
    private Hashtable<FLayer, ILegend> table = null;
134
    private boolean empty = true;
135
    private JLabel iconLabel;
122 136

  
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
		}
137
    public static String defaultLegendFolderPath;
138
    {
272 139

  
140
        Preferences prefs = Preferences.userRoot().node("gvsig.foldering");
141
        defaultLegendFolderPath = prefs.get("LegendsFolder", "");
142
    }
143
    private ActionListener loadSaveLegendAction = new ActionListener() {
273 144

  
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
	};
145
        public void actionPerformed(java.awt.event.ActionEvent e) {
146
            JComponent c = (JComponent) e.getSource();
147
            if (c.equals(getBtnSaveLegend())) {
148
                saveLegend();
291 149

  
150
            } else
151
                if (c.equals(getBtnLoadLegend())) {
152
                    loadLegend();
153
                }
154
        }
292 155

  
293
	public LegendManager() {
294
		initialize();
295
	}
156
        private void saveLegend() {
157
            ILegend legend = activePanel.getLegend();
296 158

  
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
	}
159
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
160
            JFileChooser fileChooser = new JFileChooser();
161
            fileChooser.setAcceptAllFileFilterUsed(false);
304 162

  
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
	}
163
            fileChooser.setFileFilter(new FileFilter() {
317 164

  
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
	}
165
                @Override
166
                public String getDescription() {
167
                    return "Legend files (*"
168
                        + SymbolManager.LEGEND_FILE_EXTENSION + ")";
169
                }
326 170

  
327
	private JScrollPane getJPanelContainer() {
328
		if (jPanelContainer == null) {
329
			jPanelContainer = new JScrollPane();
330
		}
331
		return jPanelContainer;
332
	}
171
                @Override
172
                public boolean accept(File f) {
173
                    if (f.isDirectory()) {
174
                        return true;
175
                    } else
176
                        if (f.isFile() && getExtension(f) != null) {
177
                            return getExtension(f).equals(
178
                                SymbolManager.LEGEND_FILE_EXTENSION);
179
                        } else {
180
                            return false;
181
                        }
182
                }
183
            });
333 184

  
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
	}
185
            if (fileChooser.showSaveDialog((Component) PluginServices
186
                .getMainFrame()) == JFileChooser.APPROVE_OPTION) {
187
                OutputStream os;
188
                File selectedFile = fileChooser.getSelectedFile();
349 189

  
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
	}
190
                if (getExtension(selectedFile) == null
191
                    || !getExtension(selectedFile).equals(
192
                        SymbolManager.LEGEND_FILE_EXTENSION)) {
193
                    File selectedFileWithExtension =
194
                        new File(selectedFile.getAbsolutePath()
195
                            + SymbolManager.LEGEND_FILE_EXTENSION);
196
                    selectedFile = selectedFileWithExtension;
197
                }
357 198

  
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
	}
199
                try {
200
                    os = new FileOutputStream(selectedFile);
201
                } catch (FileNotFoundException e) {
202
                    JOptionPane.showMessageDialog(null,
203
                        "_cant_open_the_input_file_legend");
204
                    return;
205
                }
365 206

  
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
	}
207
                manager.putObject(os, legend);
208
            }
209
        }
402 210

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

  
410
		return iconLabel;
411
	}
213
            JFileChooser fileChooser = new JFileChooser();
214
            fileChooser.setAcceptAllFileFilterUsed(false);
412 215

  
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
	}
216
            // fileChooser filter
217
            fileChooser.setFileFilter(new FileFilter() {
425 218

  
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
	}
219
                @Override
220
                public String getDescription() {
221
                    // get this extension from manager or somewhere!
442 222

  
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);
223
                    return "Legend files (*"
224
                        + SymbolManager.LEGEND_FILE_EXTENSION + ")";
225
                }
457 226

  
458
						if (dirtyTree) {
459
							// rebuild page tree
460
							dirtyTree = false;
227
                @Override
228
                public boolean accept(File f) {
229
                    if (f.isDirectory()) {
230
                        return true;
231
                    } else
232
                        if (f.isFile() && getExtension(f) != null) {
461 233

  
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);
234
                            return getExtension(f).equals(
235
                                SymbolManager.LEGEND_FILE_EXTENSION);
236
                        } else {
237
                            return false;
238
                        }
239
                }
240
            });
480 241

  
481
					}
482
					getJTreeLegends().setModel(treeModel);
242
            // open a file
243
            if (fileChooser.showOpenDialog((Component) PluginServices
244
                .getMainFrame()) == JFileChooser.APPROVE_OPTION) {
245
                File file = fileChooser.getSelectedFile();
246
                PersistenceManager manager =
247
                    ToolsLocator.getPersistenceManager();
248
                InputStream is;
483 249

  
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
				}
250
                try {
251
                    is = new FileInputStream(file);
252
                } catch (FileNotFoundException e) {
253
                    JOptionPane.showMessageDialog(null,
254
                        "_cant_open_the_input_file_legend");
255
                    return;
256
                }
257
                ILegend legend = (ILegend) manager.getObject(is);
258
                applyLegend(legend);
259
            }
260
        }
261
    };
492 262

  
493
			}
494
			getJTreeLegends().repaint();
495
			empty = false;
496
		}
497
	}
263
    //
264
    // JLegendFileChooser jfc = new
265
    // JLegendFileChooser(getLegendDrivers(),true);
266
    // jfc.setAcceptAllFileFilterUsed(false);
267
    //
268
    //
269
    // File basedir = null;
270
    // jfc.setCurrentDirectory(basedir);
271
    // if (jfc.showSaveDialog((Component) PluginServices.getMainFrame())
272
    // == JFileChooser.APPROVE_OPTION) {
273
    //
274
    // File file = jfc.getSelectedFile();
275
    // String version = jfc.getDriverVersion();
276
    // IFMapLegendDriver driver = jfc.getSuitableDriver();
277
    //
278
    // if(!(driver instanceof FMapGVLDriver)){
279
    // Object[] options = {PluginServices.getText(this, "yes"),
280
    // PluginServices.getText(this, "no")};
281
    //
282
    // int answer =
283
    // JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
284
    // PluginServices.getText(this, "not_GVSLEG_save_question")+"\n"+ //GVL
285
    // changed to GVSLEG, be aware
286
    // PluginServices.getText(this, "desea_continuar"),
287
    // PluginServices.getText(this, "confirmation_dialog"),
288
    // JOptionPane.YES_NO_OPTION,
289
    // JOptionPane.QUESTION_MESSAGE,
290
    // null,
291
    // options, options[1]);
292
    // if (answer!=JOptionPane.OK_OPTION) {
293
    // // 'Cancel' pressed or window closed: don't save anythig, exit
294
    // save dialog
295
    // return;
296
    // }
297
    // }
298
    //
299
    // if (file.exists()) {
300
    // Object[] options = {PluginServices.getText(this, "yes"),
301
    // PluginServices.getText(this, "no"),
302
    // PluginServices.getText(this, "Cancel")};
303
    //
304
    // int answer =
305
    // JOptionPane.showOptionDialog((Component)PluginServices.getMainFrame(),
306
    // PluginServices.getText(this,
307
    // "fichero_ya_existe_seguro_desea_guardarlo"),
308
    // PluginServices.getText(this, "confirmation_dialog"),
309
    // JOptionPane.YES_NO_CANCEL_OPTION,
310
    // JOptionPane.QUESTION_MESSAGE,
311
    // null,
312
    // options, options[1]);
313
    // if (answer!=JOptionPane.OK_OPTION) {
314
    // // 'Cancel' pressed or window closed: don't save anythig, exit
315
    // save dialog
316
    // return;
317
    // }
318
    // }
319
    //
320
    //
321
    // try {
322
    // driver.write(layer.getMapContext().getLayers(),layer,
323
    // activePanel.getLegend(), file, version);
324
    //
325
    // } catch (LegendDriverException e1) {
326
    // int type = e1.getType();
327
    // String message=PluginServices.getText(this,
328
    // "could_not_save_legend")+":\n";
329
    //
330
    // if ((type & LegendDriverException.SAVE_LEGEND_ERROR) != 0){
331
    // type = type & ~LegendDriverException.SAVE_LEGEND_ERROR;
332
    // message += PluginServices.getText(this,
333
    // "error_writing_file")+".\n";
334
    // }
335
    // if ((type & LegendDriverException.UNSUPPORTED_LEGEND_CREATION) !=
336
    // 0){
337
    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_CREATION;
338
    // message += "-"+ PluginServices.getText(this,
339
    // "legend_format_not_yet_supported")+"\n";
340
    // }
341
    // if (type != 0) {
342
    // message = "-"+PluginServices.getText(this, "unknown_error")+"\n";
343
    // }
344
    // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
345
    // message);
346
    // }
347
    // }
348
    // } else if (c.equals(getBtnLoadLegend())) {
349
    //
350
    // JLegendFileChooser jfc = new
351
    // JLegendFileChooser(getLegendDrivers());
352
    // jfc.setAcceptAllFileFilterUsed(false);
353
    //
354
    // if (jfc.showOpenDialog((Component) PluginServices.getMainFrame())
355
    // == JFileChooser.APPROVE_OPTION) {
356
    // File file=jfc.getSelectedFile();
357
    // IFMapLegendDriver driver = jfc.getSuitableDriver();
358
    // String path = file.getAbsolutePath();
359
    // defaultLegendFolderPath = path.substring(0,
360
    // path.lastIndexOf(File.separator));
361
    //
362
    // try {
363
    // table = driver.read(layer.getMapContext().getLayers(),layer,
364
    // file);
365
    //
366
    // if(table.containsKey(layer))
367
    // applyLegend((ILegend) table.get(layer));
368
    //
369
    //
370
    // } catch (LegendDriverException e1) {
371
    // int type = e1.getType();
372
    // String message = PluginServices.getText(this,
373
    // "the_legend_will_not_be_applied")+":\n";
374
    // boolean hasReason = false;
375
    //
376
    // if ((type &
377
    // LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND) != 0){
378
    // type = type &
379
    // ~LegendDriverException.CLASSIFICATION_FIELDS_NOT_FOUND;
380
    // message +="-"+ PluginServices.getText(this,
381
    // "classification_field_does_not_exists")+"\n";
382
    // hasReason = true;
383
    // }
384
    // if ((type & LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED)
385
    // != 0){
386
    // type = type &
387
    // ~LegendDriverException.LEGEND_TYPE_NOT_YET_SUPPORTED;
388
    // message += "-"+ PluginServices.getText(this,
389
    // "legend_type_not_yet_supported")+"\n";
390
    // hasReason = true;
391
    // }
392
    // if ((type & LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED)
393
    // != 0){
394
    // type = type &
395
    // ~LegendDriverException.SYMBOL_TYPE_NOT_YET_SUPPORTED;
396
    // message += "-"+ PluginServices.getText(this,
397
    // "unsupported_symbol_type")+"\n";
398
    // hasReason = true;
399
    // }
400
    // if ((type & LegendDriverException.LAYER_SHAPETYPE_MISMATCH) !=
401
    // 0){
402
    // type = type & ~LegendDriverException.LAYER_SHAPETYPE_MISMATCH;
403
    // message += "-"+ PluginServices.getText(this,
404
    // "layer_geometry_and_legend_types_are_incompatible")+"\n";
405
    // hasReason = true;
406
    // }
407
    // if ((type & LegendDriverException.PARSE_LEGEND_FILE_ERROR) != 0){
408
    // type = type & ~LegendDriverException.PARSE_LEGEND_FILE_ERROR;
409
    // message += "-"+ PluginServices.getText(this,
410
    // "failed_reading_file")+"\n";
411
    // hasReason = true;
412
    // }
413
    // if ((type &
414
    // LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION) != 0){
415
    // type = type &
416
    // ~LegendDriverException.UNSUPPORTED_LEGEND_FILE_VERSION;
417
    // message += "-"+ PluginServices.getText(this,
418
    // "unsupported_legend_file_version")+"\n";
419
    // hasReason = true;
420
    // }
421
    // if ((type & LegendDriverException.UNSUPPORTED_LEGEND_READING) !=
422
    // 0){
423
    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
424
    // message +="-"+ PluginServices.getText(this,
425
    // "unsupported_legend_file_format")+"\n";
426
    // hasReason = true;
427
    // }
428
    // if ((type & LegendDriverException.LAYER_NAME_NOT_FOUND) != 0){
429
    // type = type & ~LegendDriverException.UNSUPPORTED_LEGEND_READING;
430
    // message +="-"+ PluginServices.getText(this,
431
    // "could_not_find_layer")+"\n";
432
    // hasReason = true;
433
    // }
434
    // if (!hasReason) {
435
    // message = "-"+ PluginServices.getText(this,
436
    // "unknown_error")+"\n";
437
    // }
438
    // JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
439
    // message);
440
    // }
441
    // }
442
    // }
498 443

  
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
		}
444
    // private IFMapLegendDriver[] getLegendDrivers() {
445
    // Class<?>[] legendDriverClasses = legendDriverPool.toArray(new Class[0]);
446
    // ArrayList<IFMapLegendDriver> drivers = new
447
    // ArrayList<IFMapLegendDriver>();
448
    // for (int i = 0; i < legendDriverClasses.length; i++) {
449
    // String message = PluginServices.getText(this,
450
    // "adding_legend_file_format_support")+": ";
451
    // try {
452
    // Class<?> c = legendDriverClasses[i];
453
    // drivers.add((IFMapLegendDriver) c.newInstance());
454
    // } catch (Exception e) {
455
    // NotificationManager.addError(message+PluginServices.getText(this,
456
    // "failed"), e);
457
    // }
458
    // NotificationManager.addInfo(message+PluginServices.getText(this, "OK"));
459
    //
460
    // }
461
    // return (IFMapLegendDriver[]) drivers.toArray(new IFMapLegendDriver[0]);
462
    // };
509 463

  
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
	}
464
    private String getExtension(File f) {
465
        String ext = null;
466
        String s = f.getName();
467
        int i = s.lastIndexOf('.');
523 468

  
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
	}
469
        if (i > 0 && i < s.length() - 1) {
470
            // ext = s.substring(i + 1).toLowerCase();
471
            ext = s.substring(i).toLowerCase();
472
        }
473
        return ext;
474
    }
565 475

  
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
	}
476
    public LegendManager() {
477
        initialize();
478
    }
574 479

  
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);
480
    private void initialize() {
481
        setLayout(new BorderLayout());
482
        add(getTopPanel(), BorderLayout.NORTH);
483
        add(getSplitPane(), BorderLayout.CENTER);
484
        setSize(500, 360);
485
        treeModel = new DefaultTreeModel(root);
486
    }
583 487

  
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();
488
    private JSplitPane getSplitPane() {
489
        if (jSplitPane == null) {
490
            jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
491
            JPanel aux = new JPanel(new BorderLayout(0, 5));
492
            aux.add(getLegendTreeScrollPane(), BorderLayout.CENTER);
493
            aux.add(getPreviewPanel(), BorderLayout.SOUTH);
494
            jSplitPane.setLeftComponent(aux);
495
            jSplitPane.setRightComponent(getCentralPanel());
496
            jSplitPane.setDividerLocation(150);
497
        }
498
        return jSplitPane;
499
    }
591 500

  
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
	}
501
    private JPanel getCentralPanel() {
502
        if (jCentralPanel == null) {
503
            jCentralPanel = new JPanel(new BorderLayout(0, 10));
504
            jCentralPanel.add(getTitleScroll(), BorderLayout.NORTH);
505
            jCentralPanel.add(getJPanelContainer(), BorderLayout.CENTER);
506
        }
507
        return jCentralPanel;
508
    }
602 509

  
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());
510
    private JScrollPane getJPanelContainer() {
511
        if (jPanelContainer == null) {
512
            jPanelContainer = new JScrollPane();
513
        }
514
        return jPanelContainer;
515
    }
619 516

  
620
			activePanel.setData(layer, legend);
621
			getTitleArea().setText(activePanel.getDescription());
622
			jPanelContainer.setViewportView(activePanel.getPanel());
623
		}
624
	}
517
    /**
518
     * This method initializes jPanel
519
     * 
520
     * @return javax.swing.JPanel
521
     */
522
    private JPanel getTopPanel() {
523
        if (topPanel == null) {
524
            topPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
525
            topPanel.setPreferredSize(new Dimension(638, 31));
526
            topPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(
527
                null, "",
528
                javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
529
                javax.swing.border.TitledBorder.DEFAULT_POSITION, null, null));
530
            topPanel.add(getBtnSaveLegend(), null);
531
            topPanel.add(getBtnLoadLegend(), null);
532
        }
533
        return topPanel;
534
    }
625 535

  
536
    private JButton getBtnSaveLegend() {
537
        if (btnSaveLegend == null) {
538
            btnSaveLegend =
539
                new JButton(PluginServices.getText(this, "Guardar_leyenda")
540
                    + "...");
541
            btnSaveLegend.addActionListener(loadSaveLegendAction);
542
        }
543
        return btnSaveLegend;
544
    }
626 545

  
627
	private void setIcon(ImageIcon icon) {
628
		getIconLabel().setIcon(icon);
629
	}
546
    private JButton getBtnLoadLegend() {
547
        if (btnLoadLegend == null) {
548
            btnLoadLegend =
549
                new JButton(PluginServices.getText(this, "Recuperar_leyenda")
550
                    + "...");
551
            btnLoadLegend.addActionListener(loadSaveLegendAction);
552
        }
553
        return btnLoadLegend;
554
    }
630 555

  
556
    /**
557
     * This method initializes jTextArea
558
     * 
559
     * @return javax.swing.JTextArea
560
     */
561
    private JTextArea getTitleArea() {
562
        if (titleArea == null) {
563
            titleArea = new JTextArea();
564
            titleArea.setBackground(java.awt.SystemColor.control);
565
            titleArea.setLineWrap(true);
566
            titleArea.setRows(0);
567
            titleArea.setWrapStyleWord(false);
568
            titleArea.setEditable(false);
569
            titleArea.setPreferredSize(new java.awt.Dimension(495, 40));
570
        }
571
        return titleArea;
572
    }
631 573

  
632
	private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
633
		private static final long serialVersionUID = -6013698992263578041L;
574
    /**
575
     * This method initializes jPanel1
576
     * 
577
     * @return javax.swing.JPanel
578
     */
579
    private JPanel getPreviewPanel() {
580
        if (preview == null) {
581
            preview = new JPanel();
582
            preview.setBorder(javax.swing.BorderFactory
583
                .createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
584
            preview.setBackground(java.awt.SystemColor.text);
585
            preview.setLayout(new BorderLayout(5, 5));
586
            preview.add(getIconLabel());
587
            preview.setPreferredSize(new Dimension(getSplitPane()
588
                .getDividerLocation(), 130));
589
            preview.setBackground(Color.white);
590
        }
591
        return preview;
592
    }
634 593

  
635
		public MyTreeCellRenderer() {}
594
    private JLabel getIconLabel() {
595
        if (iconLabel == null) {
596
            iconLabel = new JLabel();
597
            iconLabel.setVerticalAlignment(JLabel.CENTER);
598
            iconLabel.setHorizontalAlignment(JLabel.CENTER);
599
        }
636 600

  
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) {
601
        return iconLabel;
602
    }
645 603

  
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
		}
604
    /**
605
     * This method initializes jScrollPane
606
     * 
607
     * @return javax.swing.JScrollPane
608
     */
609
    private JScrollPane getLegendTreeScrollPane() {
610
        if (legendTreeScrollPane == null) {
611
            legendTreeScrollPane = new JScrollPane();
612
            legendTreeScrollPane.setViewportView(getJTreeLegends());
613
        }
614
        return legendTreeScrollPane;
615
    }
662 616

  
663
	}
617
    /**
618
     * <p>
619
     * Adds a new fully-featured legend panel to the LegendManager.<br>
620
     * </p>
621
     * 
622
     * <p>
623
     * <b>CAUTION:</b> Trying to add a child page whose parent hasn't been added
624
     * yet causes the application to fall in an infinite loop. This is a known
625
     * bug, sorry. Just avoid this case or try to fix it (lol).<br>
626
     * </p>
627
     * 
628
     * <p>
629
     * <b>Notice</b> that there is no type check so if you add a
630
     * non-ILegendPanel class, you'll have a runtime error later.
631
     * </p>
632
     * 
633
     * @param page
634
     *            , Class of type ILegendPanel
635
     */
636
    public static void addLegendPage(
637
        Class<? extends ILegendPanel> iLegendPanelClass) {
638
        if (!legendPool.contains(iLegendPanelClass)) {
639
            legendPool.add(iLegendPanelClass);
640
        }
641
    }
664 642

  
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;
643
    /**
644
     * Causes the component to be autofilled with the legend pages that
645
     * were added through the static method addLegendPage(ILegendPanel page)
646
     */
647
    private void fillDialog() {
648
        if (empty) {
649
            for (int i = 0; i < legendPool.size(); i++) {
650
                Class<?> pageClass = (Class<?>) legendPool.get(i);
651
                ILegendPanel page;
652
                try {
653
                    page = (ILegendPanel) pageClass.newInstance();
654
                    if (page.isSuitableFor(layer)) {
655
                        // this legend can be applied to this layer
656
                        pages.put(page.getClass(), page);
670 657

  
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
658
                        if (dirtyTree) {
659
                            // rebuild page tree
660
                            dirtyTree = false;
675 661

  
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();
662
                            ArrayList<ILegendPanel> legList =
663
                                new ArrayList<ILegendPanel>(pages.values());
664
                            ArrayList<ILegendPanel> alreadyAdded =
665
                                new ArrayList<ILegendPanel>();
666
                            DefaultTreeModel model = new DefaultTreeModel(root);
667
                            while (legList.size() > 0) {
668
                                ILegendPanel legend =
669
                                    (ILegendPanel) legList.get(0);
670
                                Class<? extends ILegendPanel> parent =
671
                                    legend.getParentClass();
672
                                while (parent != null
673
                                    && !alreadyAdded
674
                                        .contains(pages.get(parent))) {
675
                                    legend = (ILegendPanel) pages.get(parent);
676
                                }
677
                                doInsertNode(model, legend);
678
                                legList.remove(legend);
679
                                alreadyAdded.add(legend);
680
                            }
681
                            treeModel = model;
682
                            jTreeLegends.setModel(model);
683
                        }
684
                        doInsertNode(treeModel, page);
680 685

  
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
		}
686
                    }
687
                    getJTreeLegends().setModel(treeModel);
693 688

  
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
	}
689
                } catch (InstantiationException e) {
690
                    NotificationManager.addError(
691
                        "Trying to instantiate an interface"
692
                            + " or abstract class + " + pageClass.getName(), e);
693
                } catch (IllegalAccessException e) {
694
                    NotificationManager.addError(
695
                        "IllegalAccessException: does " + pageClass.getName()
696
                            + " class have an anonymous" + " constructor?", e);
697
                }
701 698

  
702
	public String getName() {
703
		return PluginServices.getText(this,"Simbologia");
704
	}
699
            }
700
            getJTreeLegends().repaint();
701
            empty = false;
702
        }
703
    }
705 704

  
706
	public void acceptAction() {
707
		// automatically handled by the ThemeManagerWindow
708
	}
705
    @SuppressWarnings("unchecked")
706
    private DefaultMutableTreeNode findNode(Class searchID) {
707
        String title;
708
        try {
709
            title =
710
                ((ILegendPanel) Class.forName(searchID.getName()).newInstance())
711
                    .getTitle();
712
        } catch (Exception e) {
713
            // this should be impossible, but anyway this case will be treat as
714
            // the node does not
715
            // exist.
716
            return null;
717
        }
709 718

  
710
	public void cancelAction() {
711
		// does nothing
712
	}
719
        Enumeration e = root.breadthFirstEnumeration();
720
        while (e.hasMoreElements()) {
721
            DefaultMutableTreeNode nodeAux =
722
                (DefaultMutableTreeNode) e.nextElement();
723
            if (nodeAux != null) {
724
                ILegendPanel legend = (ILegendPanel) nodeAux.getUserObject();
725
                if (legend == null)
726
                    continue; // Root node
727
                if (legend.getTitle().equals(title)) {
728
                    return nodeAux;
729
                }
730
            }
731
        }
732
        return null;
733
    }
713 734

  
714
	public void applyAction() {
715
		legend = activePanel.getLegend();
735
    private void doInsertNode(DefaultTreeModel treeModel, ILegendPanel page) {
736
        dirtyTree =
737
            ((page.getParentClass() != null) && (findNode(page.getParentClass()) == null));
738
        if (findNode(page.getClass()) != null) // It is already added
739
            return;
740
        if (page.getParentClass() != null) {
741
            if (pages.containsKey(page.getParentClass())) {
742
                ILegendPanel parent =
743
                    (ILegendPanel) pages.get(page.getParentClass());
744
                DefaultMutableTreeNode nodeParent = findNode(parent.getClass());
745
                if (nodeParent == null) {
746
                    // the parent is empty
747
                    // Recursively add it
748
                    doInsertNode(treeModel, parent);
749
                } else {
750
                    DefaultMutableTreeNode nodeValue =
751
                        new DefaultMutableTreeNode(page);
752
                    int children = nodeParent.getChildCount();
753
                    int pos = 0;
754
                    for (int i = 0; i < children; i++) {
755
                        DefaultMutableTreeNode node =
756
                            (DefaultMutableTreeNode) treeModel.getChild(
757
                                nodeParent, i);
758
                        if (node.getUserObject() instanceof ILegendPanel) {
759
                            String pageTitle =
760
                                ((ILegendPanel) node.getUserObject())
761
                                    .getTitle();
762
                            if (pageTitle.compareTo(page.getTitle()) < 0)
763
                                ++pos;
764
                        }
765
                    }
766
                    treeModel.insertNodeInto(nodeValue, nodeParent, pos);
767
                }
768
            }
769
        } else {
770
            // First level node
771
            DefaultMutableTreeNode nodeValue = new DefaultMutableTreeNode(page);
772
            int children = root.getChildCount();
773
            int pos = 0;
774
            for (int i = 0; i < children; i++) {
775
                DefaultMutableTreeNode node =
776
                    (DefaultMutableTreeNode) treeModel.getChild(root, i);
777
                if (node.getUserObject() instanceof ILegendPanel) {
778
                    String pageTitle =
779
                        ((ILegendPanel) node.getUserObject()).getTitle();
780
                    if (pageTitle.compareTo(page.getTitle()) < 0)
781
                        ++pos;
782
                }
783
            }
784
            treeModel.insertNodeInto(nodeValue, root, pos);
785
        }
786
    }
716 787

  
788
    private JScrollPane getTitleScroll() {
789
        if (jTitleScrollPane == null) {
790
            jTitleScrollPane = new JScrollPane();
791
            jTitleScrollPane.setBounds(2, 2, 498, 42);
792
            jTitleScrollPane.setViewportView(getTitleArea());
793
        }
794
        return jTitleScrollPane;
795
    }
717 796

  
718
		if (table != null && table.size() > 1)
719
			applyRestOfLegends(table,layer.getMapContext().getLayers());
797
    private JTree getJTreeLegends() {
798
        if (jTreeLegends == null) {
799
            jTreeLegends = new JTree();
800
            jTreeLegends.setRootVisible(false);
801
            MyTreeCellRenderer treeCellRenderer = new MyTreeCellRenderer();
802
            treeCellRenderer.setOpenIcon(null);
803
            treeCellRenderer.setClosedIcon(null);
804
            treeCellRenderer.setLeafIcon(null);
720 805

  
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];
806
            jTreeLegends.setCellRenderer(treeCellRenderer);
807
            jTreeLegends.setShowsRootHandles(true);
808
            jTreeLegends
809
                .addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
726 810

  
727
			if (activeLyrs[i] instanceof FLayers){
728
				laux=getFirstActiveLayerVect((FLayers)activeLyrs[i]);
729
			}
811
                    public void valueChanged(
812
                        javax.swing.event.TreeSelectionEvent e) {
813
                        if (isTreeListenerDisabled)
814
                            return;
815
                        DefaultMutableTreeNode node =
816
                            (DefaultMutableTreeNode) jTreeLegends
817
                                .getLastSelectedPathComponent();
730 818

  
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;
819
                        if (node == null)
820
                            return;
821
                        setActivePage((ILegendPanel) node.getUserObject());
822
                    }
823
                });
824
            jTreeLegends.putClientProperty("JTree.linestyle", "Angled");
825
            jTreeLegends.getSelectionModel().setSelectionMode(
826
                TreeSelectionModel.SINGLE_TREE_SELECTION);
827
        }
828
        return jTreeLegends;
829
    }
739 830

  
740
						if (aux2 instanceof FLyrVect) {
831
    private void setActivePage(ILegendPanel page) {
832
        if (page.getPanel() == null) {
833
            // this is what happens when the user clicked in a parent node
834
            // which only acts as a folder, and does not manage any legend
835
            // then it expands and selects the first child
836
            DefaultMutableTreeNode node = findNode(page.getClass());
837
            if (treeModel.getChildCount(node) > 0) {
838
                DefaultMutableTreeNode dmn =
839
                    (DefaultMutableTreeNode) treeModel.getChild(node, 0);
840
                page = (ILegendPanel) dmn.getUserObject();
841
                setActivePage(page);
842
                expandAndSelect(page);
843
            }
844
        } else {
845
            // show the page
846
            activePanel = page;
847
            setIcon(activePanel.getIcon());
741 848

  
742
							if (cl.getValues().length==0) {
743
								JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),PluginServices.getText(this,"no_es_posible_aplicar_leyenda_vacia"));
744
								return;
745
							}
849
            activePanel.setData(layer, legend);
850
            getTitleArea().setText(activePanel.getDescription());
851
            jPanelContainer.setViewportView(activePanel.getPanel());
852
        }
853
    }
746 854

  
747
							aux2.setLegend((IVectorLegend) legend);
748
						}
749
					}
750
					else if (legend instanceof IVectorLegend) {
751
						aux2.setLegend((IVectorLegend) legend);
752
					}	
753
				} catch (LegendLayerException e) {
754
					NotificationManager.addError(PluginServices.getText(this, "legend_exception"), e);
755
				}
756
			}
757
		}
758
	}
855
    private void setIcon(ImageIcon icon) {
856
        getIconLabel().setIcon(icon);
857
    }
759 858

  
760
	private void applyRestOfLegends(Hashtable<FLayer, ILegend> table2,FLayers layers) {
859
    private class MyTreeCellRenderer extends DefaultTreeCellRenderer {
761 860

  
762
		for(int i = 0; i < layers.getLayersCount(); i++) {
763
			FLayer my_layer= layers.getLayer(i);
861
        private static final long serialVersionUID = -6013698992263578041L;
764 862

  
765
			if(!(my_layer instanceof FLayers)){
766
				if(my_layer instanceof ClassifiableVectorial){
767
					try {
768
						if(table.containsKey(my_layer)){
769
							ClassifiableVectorial lyr = (ClassifiableVectorial)my_layer;
770
							lyr.setLegend((IVectorLegend) table.get(my_layer));
771
						}
863
        public MyTreeCellRenderer() {
864
        }
772 865

  
773
					} catch (LegendLayerException e) {
774
						// TODO Auto-generated catch block
775
						e.printStackTrace();
776
					}
777
				}
778
			}
779
			else
780
				applyRestOfLegends(table,(FLayers) my_layer);
781
		}
782
	}
866
        public Component getTreeCellRendererComponent(JTree tree, Object value,
867
            boolean sel, boolean expanded, boolean leaf, int row,
868
            boolean hasFocus) {
783 869

  
784
	@Override
785
	public void setModel(FLayer layer) {
786
		this.layer = layer;
787
		applyLegend(((Classifiable) layer).getLegend());
788
	}
870
            super.getTreeCellRendererComponent(tree, value, sel, expanded,
871
                leaf, row, hasFocus);
872
            if (value instanceof DefaultMutableTreeNode) {
873
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
874
                if (node.getUserObject() instanceof ILegendPanel) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff