Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / branches / org.gvsig.raster.tools_dataaccess_refactoring / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / tool / saveas / SaveAsTocMenuEntry.java @ 2340

History | View | Annotate | Download (11.7 KB)

1
/* gvSIG. Geographic Information System of the Valencian Government
2
*
3
* Copyright (C) 2007-2008 Infrastructures and Transports Department
4
* of the Valencian Government (CIT)
5
* 
6
* This program is free software; you can redistribute it and/or
7
* modify it under the terms of the GNU General Public License
8
* as published by the Free Software Foundation; either version 2
9
* of the License, or (at your option) any later version.
10
* 
11
* This program is distributed in the hope that it will be useful,
12
* but WITHOUT ANY WARRANTY; without even the implied warranty of
13
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
* GNU General Public License for more details.
15
* 
16
* You should have received a copy of the GNU General Public License
17
* along with this program; if not, write to the Free Software
18
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
19
* MA  02110-1301, USA.
20
* 
21
*/
22
package org.gvsig.raster.tools.app.basic.tool.saveas;
23
import java.awt.Component;
24
import java.beans.PropertyChangeEvent;
25
import java.beans.PropertyChangeListener;
26
import java.io.File;
27
import java.util.ArrayList;
28

    
29
import javax.swing.Icon;
30
import javax.swing.JOptionPane;
31
import javax.swing.filechooser.FileFilter;
32

    
33
import org.gvsig.andami.IconThemeHelper;
34
import org.gvsig.andami.PluginServices;
35
import org.gvsig.andami.ui.mdiManager.IWindow;
36
import org.gvsig.app.project.documents.view.gui.AbstractViewPanel;
37
import org.gvsig.app.project.documents.view.toc.AbstractTocContextMenuAction;
38
import org.gvsig.app.project.documents.view.toc.ITocItem;
39
import org.gvsig.fmap.dal.coverage.RasterLocator;
40
import org.gvsig.fmap.dal.coverage.RasterManager;
41
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
42
import org.gvsig.fmap.dal.coverage.datastruct.Params;
43
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
44
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
45
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
46
import org.gvsig.fmap.dal.coverage.util.ProviderServices;
47
import org.gvsig.fmap.geom.primitive.Envelope;
48
import org.gvsig.fmap.mapcontext.layers.FLayer;
49
import org.gvsig.gui.beans.propertiespanel.PropertiesComponent;
50
import org.gvsig.gui.beans.swing.JFileChooser;
51
import org.gvsig.raster.algorithm.process.DataProcess;
52
import org.gvsig.raster.fmap.layers.FLyrRaster;
53
import org.gvsig.raster.fmap.layers.ILayerState;
54
import org.gvsig.raster.fmap.layers.IRasterLayerActions;
55
import org.gvsig.raster.mainplugin.toolbar.IGenericToolBarMenuItem;
56
import org.gvsig.raster.swing.RasterSwingLibrary;
57
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
58
import org.gvsig.raster.tools.app.basic.raster.process.ClippingProcess;
59
import org.gvsig.raster.util.ExtendedFileFilter;
60

    
61

    
62
/**
63
 * <p>
64
 * Entrada del TOC que corresponde con la opci?n "Salvar Como" de raster. Esta se apoya
65
 * en el proceso de recorte de raster para salvar datos.
66
 * </p>
67
 * <p>
68
 * Cuando se abre el dialogo de "Salvar como" se cargan las extensiones soportadas en el
69
 * selector. Cada tipo de datos de la fuente soporta unas extensiones de escritura u otras.
70
 * Por ejemplo, si la capa de entrada  es FLOAT no podremos escribir a JPG2000 porque no
71
 * lo soporta, tendriamos que convertila primero a RGB.
72
 * </p>
73
 * <p>
74
 * Cambiando el tipo de extensi?n en el selector cambian el panel de propiedades asociado.
75
 * El fichero de salidad se salvar? con las propiedades ajustadas.
76
 * </P>
77
 * @version 30/05/2007
78
 * @author Nacho Brodin (nachobrodin@gmail.com)
79
 *
80
 */
81
public class SaveAsTocMenuEntry extends AbstractTocContextMenuAction implements PropertyChangeListener, IGenericToolBarMenuItem {
82
        static private SaveAsTocMenuEntry singleton     = null;
83
        private JFileChooser              chooser       = null;
84
        private PropertiesComponent       panelProperty = null;
85

    
86
        /**
87
         * Nadie puede crear una instancia a esta clase ?nica, hay que usar el
88
         * getSingleton()
89
         */
90
        private SaveAsTocMenuEntry() {}
91

    
92
        /**
93
         * Devuelve un objeto unico a dicha clase
94
         * @return
95
         */
96
        static public SaveAsTocMenuEntry getSingleton() {
97
                if (singleton == null)
98
                        singleton = new SaveAsTocMenuEntry();
99
                return singleton;
100

    
101
        }
102

    
103
        public String getGroup() {
104
                return "RasterExport";
105
        }
106

    
107
        public int getGroupOrder() {
108
                return 50;
109
        }
110

    
111
        public int getOrder() {
112
                return 1;
113
        }
114

    
115
        public String getText() {
116
                return PluginServices.getText(this, "saveas");
117
        }
118

    
119
        public boolean isEnabled(ITocItem item, FLayer[] selectedItems) {
120
                if ((selectedItems == null) || (selectedItems.length != 1))
121
                        return false;
122

    
123
                if (!(selectedItems[0] instanceof ILayerState))
124
                        return false;
125

    
126
                if (!((ILayerState) selectedItems[0]).isOpen())
127
                        return false;
128

    
129
                return true;
130
        }
131

    
132
        public boolean isVisible(ITocItem item, FLayer[] selectedItems) {
133
                if ((selectedItems == null) || (selectedItems.length != 1))
134
                        return false;
135

    
136
                if (!(selectedItems[0] instanceof IRasterLayerActions))
137
                        return false;
138

    
139
                return (((IRasterLayerActions) selectedItems[0]).isActionEnabled(IRasterLayerActions.SAVEAS));
140
        }
141

    
142
        public void execute(ITocItem item, FLayer[] selectedItems) {
143
                FLayer lyr = null;
144
                IWindow w = PluginServices.getMDIManager().getActiveWindow();
145
                RasterManager rManager = RasterLocator.getManager();
146

    
147
                if (selectedItems.length != 1)
148
                        return;
149

    
150
                lyr = selectedItems[0];
151

    
152
                if (!(lyr instanceof FLyrRaster))
153
                        return;
154
                
155
                FLyrRaster fLayer = (FLyrRaster)lyr;
156
                
157
                chooser = new JFileChooser("SAVE_AS_TOC_MENU_ENTRY",JFileChooser.getLastPath("SAVE_AS_TOC_MENU_ENTRY", null));
158
                chooser.addPropertyChangeListener(this);
159
                chooser.setDialogTitle(PluginServices.getText(this, "seleccionar_fichero"));
160

    
161
                // Cargamos las extensiones en la lista
162
                ArrayList<String> extList = new ArrayList<String>();
163
                try {
164
                        ProviderServices serv = rManager.getProviderServices();
165
                        extList = serv.getExtensionsSupported(fLayer.getDataStore().getDataType()[0], fLayer.getDataStore().getBandCount());
166
                } catch (RasterDriverException e2) {
167
                        RasterSwingLibrary.messageBoxError("error_extensiones_soportadas", chooser, e2);
168
                        e2.printStackTrace();
169
                        return;
170
                }
171

    
172
                int selected_id = extList.size() - 1;
173
                FileFilter selected = null;
174
                for (int i = 0; i < extList.size(); i++) {
175
                        FileFilter filter = new ExtendedFileFilter((String) extList.get(i));
176
                        if (extList.get(i).equals("tif")) {
177
                                selected = filter;
178
                                selected_id = i;
179
                        }
180
                        chooser.addChoosableFileFilter(filter);
181
                }
182
                if (selected != null)
183
                        chooser.setFileFilter(selected);
184

    
185
                // Cargamos el panel de propiedades en el selector
186
                panelProperty = loadPanelProperties((String) extList.get(selected_id));
187
                chooser.setAccessory(panelProperty);
188
                chooser.setAcceptAllFileFilterUsed(false);
189

    
190
                if (w instanceof AbstractViewPanel) {
191
                        if (chooser.showSaveDialog(((AbstractViewPanel) w).getComponent(0)) == JFileChooser.APPROVE_OPTION) {
192
                                // Creaci?n de par?metros
193
                                String tit = PluginServices.getMDIManager().getWindowInfo(w).getTitle();
194
                                RasterDataStore datastore = ((FLyrRaster)fLayer).getDataStore();
195
                                int[] drawableBands = new int[fLayer.getDataStore().getBandCount()];
196
                                for (int i = 0; i < fLayer.getDataStore().getBandCount(); i++)
197
                                        drawableBands[i] = i;
198
                                JFileChooser.setLastPath("SAVE_AS_TOC_MENU_ENTRY", chooser.getCurrentDirectory());
199
                                String file =  ((ExtendedFileFilter) chooser.getFileFilter()).getNormalizedFilename(chooser.getSelectedFile());
200
                                
201
                                long bytes = rManager.getRasterUtils().getBytesFromRaster((int)fLayer.getDataStore().getWidth(),
202
                                                (int) fLayer.getDataStore().getHeight(),
203
                                                fLayer.getDataStore().getDataType()[0],
204
                                                fLayer.getDataStore().getBandCount());
205
                                
206
                                long maxJp2 = 13000 * 12500 * 3;
207
                                if (bytes > (20000 * 20000 * 3)) {
208
                                        if(!RasterSwingLibrary.messageBoxYesOrNot("output_file_too_big", null))
209
                                                return;
210
                                }
211
                                
212
                                if(new File(file).exists()) {
213
                                        if(!RasterSwingLibrary.messageBoxYesOrNot("raster_error_file_exists", null))
214
                                                return;
215
                                }
216
                                
217
                                if (file.endsWith(".jp2")) {
218
                                        if (bytes > maxJp2) {
219
                                                if(!RasterSwingLibrary.messageBoxYesOrNot("output_file_too_big_jpeg2000", null))
220
                                                        return;
221
                                        }
222
                                }
223
                                
224
                                if (!RasterToolsUtil.canWrite(chooser.getCurrentDirectory().toString(), this))
225
                                        return;
226
                                Params params = null;
227
                                try {
228
                                        params = rManager.createWriter(file).getParams();
229
                                } catch (NotSupportedExtensionException e1) {
230
                                        RasterSwingLibrary.messageBoxError("no_driver_escritura", this, e1);
231
                                } catch (RasterDriverException e1) {
232
                                        RasterSwingLibrary.messageBoxError("no_driver_escritura", this, e1);
233
                                }
234

    
235
                                // Lanzamiento del proceso de guardado
236
                                DataProcess clippingProcess = new ClippingProcess();
237
                                clippingProcess.setActions(new SaveAsActions());
238
                                clippingProcess.addParam("viewname", tit);
239
                                if(fLayer.isRemote()) {
240
                                        Envelope env = ((AbstractViewPanel)w).getMapControl().getViewPort().getEnvelope();
241
                                        clippingProcess.addParam("realcoordinates", new double[] { env.getMinimum(0), env.getMaximum(1), env.getMaximum(0), env.getMinimum(1)});
242
                                        clippingProcess.addParam("resolution", new int[]{(int) fLayer.getDataStore().getWidth(),
243
                                                                                                                                          (int) fLayer.getDataStore().getHeight()});
244
                                } else {
245
                                        clippingProcess.addParam("pixelcoordinates", new int[] { 0, (int) fLayer.getDataStore().getHeight(), (int) fLayer.getDataStore().getWidth(), 0 });
246
                                        clippingProcess.addParam("resolution", new int[]{(int) fLayer.getDataStore().getWidth(),
247
                                                                                                                                          (int) fLayer.getDataStore().getHeight()});
248
                                }
249
                                int index = file.lastIndexOf(".");
250
                                if(index > 0) {
251
                                        String suffix = file.substring(index, file.length());
252
                                        if(suffix.length() == 4)
253
                                                clippingProcess.addParam("suffix", suffix);
254
                                }
255
                                clippingProcess.addParam("filename", file);
256
                                clippingProcess.addParam("layer", fLayer.getDataStore());
257
                                clippingProcess.addParam("drawablebands", drawableBands);
258
                                clippingProcess.addParam("colorInterpretation", datastore.getColorInterpretation());
259
                                clippingProcess.addParam("onelayerperband", new Boolean(false));
260
                                clippingProcess.addParam("interpolationmethod", new Integer(Buffer.INTERPOLATION_NearestNeighbour));
261
                                clippingProcess.addParam("affinetransform", datastore.getAffineTransform());
262
                                clippingProcess.addParam("viewProjection", ((AbstractViewPanel) w).getMapControl().getProjection());
263

    
264
                                if (params != null)
265
                                        RasterToolsUtil.loadWriterParamsFromPropertiesPanel(panelProperty, params);
266
                                clippingProcess.addParam("driverparams", params);
267
                                clippingProcess.start();
268
                        }
269
                }
270
        }
271

    
272
        /**
273
         * Evento que se produce al cambiar el driver de escritura. Esto
274
         * sustituye el panel properties por el del nuevo driver seleccionado
275
         */
276
        public void propertyChange(PropertyChangeEvent evt) {
277
                if (evt.getNewValue() instanceof ExtendedFileFilter) {
278
                        String ext = ((ExtendedFileFilter) evt.getNewValue()).getExtensions().get(0).toString();
279
                        panelProperty = loadPanelProperties(ext);
280
                        chooser.setAccessory(panelProperty);
281
                        chooser.revalidate();
282
                }
283
        }
284

    
285
        /**
286
         * Obtiene el objeto PropertiesComponent para una extensi?n concreta de fichero
287
         * sobre el que se va a escribir.
288
         * @param file Fichero raster sobre el que se escribir?
289
         * @return PropertiesComponent
290
         */
291
        private PropertiesComponent loadPanelProperties(String file) {
292
                PropertiesComponent panelProperty = new PropertiesComponent();
293
                Params params = null;
294
                try {
295
                        params = RasterLocator.getManager().createWriter(file).getParams();
296
                } catch (NotSupportedExtensionException e1) {
297
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), PluginServices.getText(this, "no_driver_escritura"));
298
                        return null;
299
                } catch (RasterDriverException e1) {
300
                        JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(), PluginServices.getText(this, "no_driver_escritura"));
301
                        return null;
302
                }
303
                RasterToolsUtil.loadPropertiesFromWriterParams(panelProperty, params, null);
304
                return panelProperty;
305
        }
306

    
307
        public Icon getIcon() {
308
                return IconThemeHelper.getImageIcon("layer-saveas");
309
        }
310
        
311
        public boolean isEnableEvents() {
312
                return true;
313
        }
314
}