Statistics
| Revision:

root / trunk / extensions / extRasterTools-SE / src / org / gvsig / rastertools / colortable / ui / library / ColorTableLibraryPanel.java @ 22364

History | View | Annotate | Download (17.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 */
19
package org.gvsig.rastertools.colortable.ui.library;
20

    
21
import java.awt.BorderLayout;
22
import java.awt.Dimension;
23
import java.awt.FlowLayout;
24
import java.awt.event.ActionEvent;
25
import java.awt.event.ActionListener;
26
import java.io.File;
27
import java.io.IOException;
28
import java.util.ArrayList;
29
import java.util.EventObject;
30
import java.util.Iterator;
31

    
32
import javax.swing.ImageIcon;
33
import javax.swing.JButton;
34
import javax.swing.JFileChooser;
35
import javax.swing.JOptionPane;
36
import javax.swing.JPanel;
37
import javax.swing.JScrollPane;
38

    
39
import org.gvsig.gui.beans.listview.ListViewComponent;
40
import org.gvsig.gui.beans.listview.ListViewItem;
41
import org.gvsig.gui.beans.listview.ListViewListener;
42
import org.gvsig.raster.datastruct.ColorTable;
43
import org.gvsig.raster.datastruct.io.RasterLegendIO;
44
import org.gvsig.raster.datastruct.io.exceptions.RasterLegendIONotFound;
45
import org.gvsig.raster.datastruct.persistence.ColorTableLibraryPersistence;
46
import org.gvsig.raster.util.ExtendedFileFilter;
47
import org.gvsig.raster.util.BasePanel;
48
import org.gvsig.raster.util.RasterToolsUtil;
49
import org.gvsig.raster.util.RasterUtilities;
50

    
51
import com.iver.andami.PluginServices;
52
/**
53
 * Panel que aparece en la parte inferior derecha que contiene la lista
54
 * de librerias disponibles para las tablas de color, con sus botones correspondientes
55
 * para importar, exportar, borrar y a?adir librerias.
56
 * 
57
 * 19/02/2008
58
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
59
 */
60
public class ColorTableLibraryPanel extends BasePanel implements ActionListener, ListViewListener {
61
        private static final long serialVersionUID       = 1L;
62
        private JPanel            panelButtons           = null;
63
        private JButton           buttonAdd              = null;
64
        private JButton           buttonDel              = null;
65
        private JButton           buttonImport           = null;
66
        private JButton           buttonExport           = null;
67
        private ListViewComponent listViewComponent      = null;
68

    
69
        private boolean           hasChanged             = false;
70

    
71
        private ArrayList         actionCommandListeners = new ArrayList();
72

    
73
        private String palettesPath = System.getProperty("user.home") +
74
        File.separator +
75
        "gvSIG" + // PluginServices.getArguments()[0] +
76
        File.separator + "colortable";
77
                
78
        /**
79
         *Inicializa componentes gr?ficos y traduce
80
         */
81
        public ColorTableLibraryPanel() {
82
                init();
83
                translate();
84
        }
85
        
86
        /*
87
         * (non-Javadoc)
88
         * @see org.gvsig.raster.util.BasePanel#init()
89
         */
90
        protected void init() {
91
                setLayout(new BorderLayout());
92
                
93
                JPanel panel = new JPanel();
94
                panel.setLayout(new BorderLayout());
95
                panel.setBorder(javax.swing.BorderFactory.createEmptyBorder(8, 8, 8, 8));
96
                
97
                JScrollPane jScrollPane = new JScrollPane();
98
                jScrollPane.setViewportView(getListViewComponent());
99
                jScrollPane.setAutoscrolls(true);
100
                
101
                panel.add(jScrollPane, BorderLayout.CENTER);
102
                add(panel, BorderLayout.CENTER);
103
                add(getPanelButtons(), BorderLayout.SOUTH);
104
                setPreferredSize(new Dimension(0, 192));
105

    
106
                loadDiskLibrary();
107
        }
108

    
109
        /*
110
         * (non-Javadoc)
111
         * @see org.gvsig.raster.util.BasePanel#translate()
112
         */
113
        protected void translate() {
114
        }
115
        
116
        private void loadDiskLibrary() {
117
                ArrayList fileList = ColorTableLibraryPersistence.getPaletteFileList(palettesPath);
118
                for (int i = 0; i < fileList.size(); i++) {
119
                        ArrayList paletteItems = new ArrayList();
120
                        String paletteName = ColorTableLibraryPersistence.loadPalette(palettesPath, (String) fileList.get(i), paletteItems);
121

    
122
                        if (paletteItems.size() <= 0)
123
                                continue;
124

    
125
                        ColorTable colorTable = new ColorTable();
126
                        colorTable.setName(paletteName);
127
                        colorTable.createPaletteFromColorItems(paletteItems, true);
128
                        colorTable.setInterpolated(true);
129

    
130
                        ListViewItem item = new ListViewItem(new ColorTableIconPainter(colorTable), paletteName);
131
                        item.setTag(fileList.get(i));
132
                        getListViewComponent().addItem(item);
133
                }
134
                getListViewComponent().setSelectedIndex(0);
135
                callColorTableChanged();                
136
        }
137
        
138
        /**
139
         * Devuelve el jButtonAdd
140
         * @return
141
         */
142
        private JButton getButtonAdd() {
143
                if (buttonAdd == null) {
144
                        ImageIcon icon = null;
145
                        try {
146
                                icon = PluginServices.getIconTheme().get("addlayer-icon");
147
                        } catch (NullPointerException n) {
148
                                // No ha encontrado el icono, no lo muestra.
149
                        }
150

    
151
                        buttonAdd = new JButton(icon);
152
                        buttonAdd.setPreferredSize(new Dimension(22, 19));
153
                        buttonAdd.addActionListener(this);
154
                        buttonAdd.setToolTipText(getText(this, "nueva_libreria_title"));
155
                }
156
                return buttonAdd;
157
        }
158

    
159
        /**
160
         * Devuelve el jButtonDel
161
         * @return
162
         */
163
        private JButton getButtonDel() {
164
                if (buttonDel == null) {
165
                        ImageIcon icon = null;
166
                        try {
167
                                icon = PluginServices.getIconTheme().get("delall-icon");
168
                        } catch (NullPointerException n) {
169
                                // No ha encontrado el icono, no lo muestra.
170
                        }
171
                        buttonDel = new JButton(icon);
172
                        buttonDel.setPreferredSize(new Dimension(22, 19));
173
                        buttonDel.addActionListener(this);
174
                        buttonDel.setToolTipText(getText(this, "borrar_libreria"));
175
                }
176
                return buttonDel;
177
        }
178

    
179
        /**
180
         * Devuelve el jButtonDel
181
         * @return
182
         */
183
        private JButton getButtonImport() {
184
                if (buttonImport == null) {
185
                        ImageIcon icon = null;
186
                        try {
187
                                icon = PluginServices.getIconTheme().get("import-icon");
188
                        } catch (NullPointerException n) {
189
                                // No ha encontrado el icono, no lo muestra.
190
                        }
191
                        buttonImport = new JButton(icon);
192
                        buttonImport.setPreferredSize(new Dimension(22, 19));
193
                        buttonImport.addActionListener(this);
194
                        buttonImport.setToolTipText(getText(this, "import_libreria"));
195
                }
196
                return buttonImport;
197
        }
198

    
199
        /**
200
         * Devuelve el jButtonDel
201
         * @return
202
         */
203
        private JButton getButtonExport() {
204
                if (buttonExport == null) {
205
                        ImageIcon icon = null;
206
                        try {
207
                                icon = PluginServices.getIconTheme().get("export-icon");
208
                        } catch (NullPointerException n) {
209
                                // No ha encontrado el icono, no lo muestra.
210
                        }
211
                        buttonExport = new JButton(icon);
212
                        buttonExport.setPreferredSize(new Dimension(22, 19));
213
                        buttonExport.addActionListener(this);
214
                        buttonExport.setToolTipText(getText(this, "export_libreria"));
215
                }
216
                return buttonExport;
217
        }
218
        
219
        /**
220
         * Devuelve el panel de botones de la libreria de a?adir y borrar
221
         * @return
222
         */
223
        private JPanel getPanelButtons() {
224
                if (panelButtons == null) {
225
                        panelButtons = new JPanel();
226
                        panelButtons.setPreferredSize(new Dimension(0, 21));
227

    
228
                        FlowLayout flowLayout5 = new FlowLayout();
229
                        flowLayout5.setHgap(5);
230
                        flowLayout5.setVgap(0);
231
                        flowLayout5.setAlignment(java.awt.FlowLayout.CENTER);
232
                        panelButtons.setLayout(flowLayout5);
233

    
234
                        panelButtons.add(getButtonAdd(), null);
235
                        panelButtons.add(getButtonExport(), null);
236
                        panelButtons.add(getButtonImport(), null);
237
                        panelButtons.add(getButtonDel(), null);
238
                }
239
                return panelButtons;
240
        }
241

    
242
        private ListViewComponent getListViewComponent() {
243
                if (listViewComponent == null) {
244
                        listViewComponent = new ListViewComponent();
245
                        listViewComponent.addListSelectionListener(this);
246
                        listViewComponent.setEditable(true);
247
                }
248
                return listViewComponent;
249
        }
250

    
251
        private void callColorTableChanged() {
252
                Iterator acIterator = actionCommandListeners.iterator();
253
                while (acIterator.hasNext()) {
254
                        ColorTableLibraryListener listener = (ColorTableLibraryListener) acIterator.next();
255
                        listener.actionColorTableChanged(new ColorTableLibraryEvent(this));
256
                }
257
        }
258
        
259
        /**
260
         * Accion que se ejecuta cuando se disparan los siguientes eventos:
261
         *  - Checkbox de interpolacion.
262
         *  - Checkbox de habilitacion de colortables.
263
         *  - Boton de a?adir un colortable nuevo.
264
         *  - Boton de borrar un colortable seleccionado.
265
         */
266
        public void actionPerformed(ActionEvent e) {
267
                if (e.getSource() == getButtonAdd()) {
268
                        AddLibrary addLibrary = new AddLibrary();
269
                        if (addLibrary.showConfirm(this) == JOptionPane.OK_OPTION) {
270
                                ColorTable colorTable = addLibrary.getColorTable();
271
                                if (colorTable != null) {
272
                                        ListViewItem item = new ListViewItem(new ColorTableIconPainter(colorTable), colorTable.getName());
273
                                        item.setTag(item.getName() + ".xml");
274
                                        getListViewComponent().addItem(item);
275
                                        getListViewComponent().setSelectedIndex(getListViewComponent().getItems().size() - 1);
276
                                        ((ColorTableIconPainter) item.getIcon()).getColorTable().setName(item.getName());
277
                                        colorTable.setName(((ColorTableIconPainter) item.getIcon()).getColorTable().getName());
278
                                        ColorTableLibraryPersistence.save_to_1_1(palettesPath, colorTable);
279
                                        callColorTableChanged();
280
                                }
281
                        }
282
                }
283
                
284
                if (e.getSource() == getButtonExport()) {
285
                        JFileChooser chooser = new JFileChooser();
286
                        chooser.setAcceptAllFileFilterUsed(false);
287

    
288
                        String[] formats = RasterLegendIO.getFormats();
289
                        ExtendedFileFilter fileFilter = null;
290
                        ExtendedFileFilter firstFileFilter = null;
291
                        for (int i = 0; i < formats.length; i++) {
292
                                fileFilter = new ExtendedFileFilter();
293
                                fileFilter.addExtension(formats[i]);
294

    
295
                                try {
296
                                        String desc = RasterLegendIO.getRasterLegendIO(RasterUtilities.getExtensionFromFileName(formats[i])).getDescription();
297
                                        if (desc != null)
298
                                                fileFilter.setDescription(desc);
299
                                } catch (RasterLegendIONotFound e1) {
300
                                        // Si no puedo pillar la descripcion no pasa nada
301
                                }
302
                                if (firstFileFilter == null)
303
                                        firstFileFilter = fileFilter;
304

    
305
                                chooser.addChoosableFileFilter(fileFilter);
306
                        }
307
                        if (firstFileFilter != null)
308
                                chooser.setFileFilter(firstFileFilter);
309

    
310
                        int returnVal = chooser.showSaveDialog(this);
311
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
312
                                try {
313
                                        ExtendedFileFilter filter = (ExtendedFileFilter) chooser.getFileFilter();
314
                                        String file = filter.getNormalizedFilename(chooser.getSelectedFile());
315

    
316
                                        RasterLegendIO.getRasterLegendIO(RasterUtilities.getExtensionFromFileName(file)).write(getColorTableSelected(), new File(file));
317
                                } catch (IOException e1) {
318
                                        e1.printStackTrace();
319
                                } catch (RasterLegendIONotFound e1) {
320
                                        e1.printStackTrace();
321
                                }
322
                        }
323
                }
324

    
325
                if (e.getSource() == getButtonImport()) {
326
                        JFileChooser chooser = new JFileChooser();
327
                        chooser.setAcceptAllFileFilterUsed(false);
328
                        chooser.setMultiSelectionEnabled(true);
329

    
330
                        String[] formats = RasterLegendIO.getFormats();
331
                        ExtendedFileFilter allFilters = new ExtendedFileFilter();
332
                        ExtendedFileFilter fileFilter = null;
333
                        for (int i = 0; i < formats.length; i++) {
334
                                fileFilter = new ExtendedFileFilter();
335
                                fileFilter.addExtension(formats[i]);
336
                                allFilters.addExtension(formats[i]);
337

    
338
                                try {
339
                                        String desc = RasterLegendIO.getRasterLegendIO(RasterUtilities.getExtensionFromFileName(formats[i])).getDescription();
340
                                        if (desc != null)
341
                                                fileFilter.setDescription(desc);
342
                                } catch (RasterLegendIONotFound e1) {
343
                                        // Si no puedo pillar la descripcion no pasa nada
344
                                }
345

    
346
                                chooser.addChoosableFileFilter(fileFilter);
347
                        }
348
                        allFilters.setDescription(getText(this, "todos_soportados"));
349
                        chooser.addChoosableFileFilter(allFilters);
350
                        chooser.setFileFilter(allFilters);
351

    
352
                        int returnVal = chooser.showOpenDialog(this);
353

    
354
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
355
                                try {
356
                                        for (int file = 0; file<chooser.getSelectedFiles().length; file++) {
357
                                                fileFilter = null;
358
                                                for (int i = 0; i < formats.length; i++) {
359
                                                        fileFilter = new ExtendedFileFilter();
360
                                                        fileFilter.addExtension(formats[i]);
361
                                                        if (fileFilter.accept(chooser.getSelectedFiles()[file])) {
362
                                                                ColorTable colorTable = RasterLegendIO.getRasterLegendIO(formats[i]).read(chooser.getSelectedFiles()[file]);
363

    
364
                                                                colorTable.setInterpolated(true);
365

    
366
                                                                ListViewItem item = new ListViewItem(new ColorTableIconPainter(colorTable), colorTable.getName());
367
                                                                item.setTag(item.getName() + ".xml");
368
                                                                getListViewComponent().addItem(item);
369
                                                                getListViewComponent().setSelectedIndex(getListViewComponent().getItems().size() - 1);
370
                                                                ((ColorTableIconPainter) item.getIcon()).getColorTable().setName(item.getName());
371
                                                                colorTable.setName(((ColorTableIconPainter) item.getIcon()).getColorTable().getName());
372
                                                                ColorTableLibraryPersistence.save_to_1_1(palettesPath, colorTable);
373
                                                                callColorTableChanged();
374
                                                                break;
375
                                                        }
376
                                                }
377
                                        }
378
                                } catch (IOException e1) {
379
                                        e1.printStackTrace();
380
                                } catch (RasterLegendIONotFound e1) {
381
                                        e1.printStackTrace();
382
                                }
383
                        }
384
                }
385

    
386
                if (e.getSource() == getButtonDel()) {
387
                        if (getListViewComponent().getSelectedIndices().length > 0) {
388
                                if (RasterToolsUtil.messageBoxYesOrNot("desea_borrar_librerias", this)) {
389
                                        File oldFile = new File(palettesPath + File.separator + getListViewComponent().getSelectedValue().getTag());
390
                                        oldFile.delete();
391
                                        int pos = getListViewComponent().getSelectedIndices()[0];
392
                                        getListViewComponent().removeSelecteds();
393
                                        
394
                                        if (getListViewComponent().getItems().size() == 0) {
395
                                                loadDiskLibrary();
396
                                        } else {
397
                                                getListViewComponent().setSelectedIndex(pos - 1);
398
                                                callColorTableChanged();
399
                                        }
400
                                }
401
                        }
402
                        return;
403
                }
404
        }
405

    
406
        /*
407
         * (non-Javadoc)
408
         * @see org.gvsig.gui.beans.listview.ListViewListener#actionItemNameChanged(java.util.EventObject, java.lang.String, org.gvsig.gui.beans.listview.ListViewItem)
409
         */
410
        public void actionItemNameChanged(EventObject e, String oldName, ListViewItem item) {
411
                File oldFile = new File(palettesPath + File.separator + oldName + ".xml");
412
                oldFile.delete();
413

    
414
                getColorTableSelected().setName(item.getName());
415
                item.setTag(item.getName() + ".xml");
416

    
417
                ColorTableLibraryPersistence.save_to_1_1(palettesPath, getColorTableSelected());
418
                
419
                callColorTableChanged();
420
        }
421

    
422
        /**
423
         * Comprueba si el usuario ha cambiado los valores de la tabla de colores,
424
         * si es as?, le pregunta al usuario si quiere guardar los datos, y seg?n la
425
         * selecci?n, restaura los datos antiguos o los machaca.
426
         */
427
        private void testLibraryChanged() {
428
                if (hasChanged) {
429
                        if (RasterToolsUtil.messageBoxYesOrNot("desea_guardar_cambios", this)) {
430
                                ColorTableLibraryPersistence.save_to_1_1(palettesPath, getColorTableSelected());
431
                                getListViewComponent().repaint();
432
                        }
433
                        hasChanged = false;
434
                }
435
        }
436
        
437
        /**
438
         * Selecciona la tabla de color por defecto.
439
         */
440
        public void selectDefault() {
441
                int selected = 0;
442
                for (int i = 0; i < getListViewComponent().getItems().size(); i++) {
443
                        if (((ListViewItem) getListViewComponent().getItems().get(i)).getName().equals("Default")) {
444
                                selected = i;
445
                                break;
446
                        }
447
                }
448
                getListViewComponent().setSelectedIndex(selected);
449
                callColorTableChanged();
450
        }
451
        
452
        /**
453
         * Inserta una tabla de color en la posicion especificada y selecciona.
454
         */
455
        public void addColorTable(int pos, ColorTable colorTable) {
456
                ListViewItem item = new ListViewItem(new ColorTableIconPainter(colorTable), getText(this, "tabla_actual"));
457
                getListViewComponent().addItem(pos, item);
458
                getListViewComponent().setSelectedIndex(pos);
459
                callColorTableChanged();
460
        }
461
        
462
        /**
463
         * Accion que se ejecuta cuando cambia la seleccion de un item del
464
         * ListViewComponent
465
         */
466
        public void actionValueChanged(EventObject e) {
467
                testLibraryChanged();
468
                callColorTableChanged();
469
        }
470
        
471
        /**
472
         * Define si se visualizara el componente con interpolacion o no.
473
         * @param enabled
474
         */
475
        public void setInterpolated(boolean enabled) {
476
                for (int i = 0; i < getListViewComponent().getItems().size(); i++)
477
                        ((ColorTableIconPainter) ((ListViewItem) getListViewComponent().getItems().get(i)).getIcon()).setInterpolated(enabled);
478
                getListViewComponent().repaint();
479
        }
480
        
481
        /**
482
         * A?adir un listener a la lista de eventos
483
         * @param listener
484
         */
485
        public void addColorTableLibraryListener(ColorTableLibraryListener listener) {
486
                if (!actionCommandListeners.contains(listener))
487
                        actionCommandListeners.add(listener);
488
        }
489

    
490
        /**
491
         * Borrar un listener de la lista de eventos
492
         * @param listener
493
         */
494
        public void removeColorTableLibraryListener(ColorTableLibraryListener listener) {
495
                actionCommandListeners.remove(listener);
496
        }
497

    
498
        /**
499
         * Devuelve la tabla de color que hay seleccionada en ese momento
500
         * @return
501
         */
502
        public ColorTable getColorTableSelected() {
503
                return ((ColorTableIconPainter) getListViewComponent().getSelectedValue().getIcon()).getColorTable();
504
        }
505
        
506
        /**
507
         * Reescribe la tabla de color en la posicion seleccionada
508
         * @param colorTable
509
         */
510
        public void setColorTableSelected(ColorTable colorTable) {
511
                hasChanged = true;
512
                ((ColorTableIconPainter) getListViewComponent().getSelectedValue().getIcon()).getColorTable().createPaletteFromColorItems(colorTable.getColorItems(), false);
513
                getListViewComponent().repaint();
514
        }
515

    
516
}