Statistics
| Revision:

gvsig-raster / org.gvsig.raster.tools / trunk / org.gvsig.raster.tools / org.gvsig.raster.tools.app.basic / src / main / java / org / gvsig / raster / tools / app / basic / tool / saveas / SaveAsTocMenuEntry.java @ 2179

History | View | Annotate | Download (11.6 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.tools.app.basic.RasterToolsUtil;
57
import org.gvsig.raster.tools.app.basic.raster.process.ClippingProcess;
58
import org.gvsig.raster.util.ExtendedFileFilter;
59

    
60

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

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

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

    
100
        }
101

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

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

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

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

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

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

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

    
128
                return true;
129
        }
130

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

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

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

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

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

    
149
                lyr = selectedItems[0];
150

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

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

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

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

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

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

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

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

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

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