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 / raster / process / ClippingProcess.java @ 2308

History | View | Annotate | Download (25.9 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.raster.process;
23

    
24
import java.awt.Rectangle;
25
import java.awt.geom.AffineTransform;
26
import java.awt.geom.Point2D;
27
import java.io.File;
28
import java.io.IOException;
29
import java.util.ArrayList;
30
import java.util.List;
31

    
32
import org.cresques.cts.IProjection;
33
import org.gvsig.app.project.ProjectManager;
34
import org.gvsig.app.project.documents.Document;
35
import org.gvsig.app.project.documents.view.BaseViewDocument;
36
import org.gvsig.fmap.dal.DALLocator;
37
import org.gvsig.fmap.dal.DataManager;
38
import org.gvsig.fmap.dal.DataServerExplorer;
39
import org.gvsig.fmap.dal.DataServerExplorerParameters;
40
import org.gvsig.fmap.dal.coverage.RasterLibrary;
41
import org.gvsig.fmap.dal.coverage.RasterLocator;
42
import org.gvsig.fmap.dal.coverage.RasterManager;
43
import org.gvsig.fmap.dal.coverage.dataset.Buffer;
44
import org.gvsig.fmap.dal.coverage.datastruct.Extent;
45
import org.gvsig.fmap.dal.coverage.datastruct.NoData;
46
import org.gvsig.fmap.dal.coverage.datastruct.Params;
47
import org.gvsig.fmap.dal.coverage.exception.NotSupportedExtensionException;
48
import org.gvsig.fmap.dal.coverage.exception.ProcessInterruptedException;
49
import org.gvsig.fmap.dal.coverage.exception.QueryException;
50
import org.gvsig.fmap.dal.coverage.exception.ROIException;
51
import org.gvsig.fmap.dal.coverage.exception.RasterDriverException;
52
import org.gvsig.fmap.dal.coverage.exception.RmfSerializerException;
53
import org.gvsig.fmap.dal.coverage.process.BaseIncrementableTask;
54
import org.gvsig.fmap.dal.coverage.store.DataServerWriter;
55
import org.gvsig.fmap.dal.coverage.store.RasterDataStore;
56
import org.gvsig.fmap.dal.coverage.store.RasterQuery;
57
import org.gvsig.fmap.dal.coverage.store.parameter.NewRasterStoreParameters;
58
import org.gvsig.fmap.dal.coverage.store.parameter.RemoteStoreParameters;
59
import org.gvsig.fmap.dal.coverage.store.props.ColorInterpretation;
60
import org.gvsig.fmap.dal.coverage.store.props.ColorTable;
61
import org.gvsig.fmap.dal.coverage.util.RasterUtils;
62
import org.gvsig.fmap.dal.exception.CloseException;
63
import org.gvsig.fmap.dal.exception.DataException;
64
import org.gvsig.fmap.dal.exception.InitializeException;
65
import org.gvsig.fmap.dal.exception.ProviderNotRegisteredException;
66
import org.gvsig.fmap.dal.exception.ValidateDataParametersException;
67
import org.gvsig.fmap.mapcontext.layers.FLayer;
68
import org.gvsig.fmap.mapcontext.layers.FLayers;
69
import org.gvsig.i18n.Messages;
70
import org.gvsig.raster.algorithm.process.DataProcess;
71
import org.gvsig.raster.fmap.layers.DefaultFLyrRaster;
72
import org.gvsig.raster.mainplugin.RasterMainPluginUtils;
73
import org.gvsig.raster.roi.ROI;
74
import org.gvsig.raster.swing.RasterSwingLibrary;
75
import org.gvsig.raster.tools.app.basic.RasterToolsUtil;
76
import org.gvsig.raster.util.RasterNotLoadException;
77
/**
78
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
79
 * para aplicar un recorte a una capa y guardarlo en disco. Muestra una barra
80
 * de incremento informativa.
81
 *
82
 * @author BorSanZa - Borja S?nchez Zamorano
83
 */
84
public class ClippingProcess extends DataProcess {
85
        public static final String            PROCESS_LABEL       = "ClippingProcess";
86
        public static String                  FILENAME            = "filename";
87
        public static String                  SUFFIX              = "suffix";
88
        public static String                  VIEWNAME            = "viewname";
89
        public static String                  PX_COORDS           = "pixelcoordinates";
90
        public static String                  WORLD_COORDS        = "realcoordinates";
91
        public static String                  RASTER_STORE        = "layer";
92
        public static String                  DRAWABLE_BANDS      = "drawablebands";
93
        public static String                  ONE_LYE_PER_BAND    = "onelayerperband";
94
        public static String                  INTERP_METHOD       = "interpolationmethod";
95
        public static String                  AT                  = "affinetransform";
96
        public static String                  COLOR_INTERPR       = "colorInterpretation";
97
        public static String                  SELECTED_ROIS       = "selectedrois";
98
        public static String                  RESOLUTION          = "resolution";
99
        public static String                  DRIVER_PARAMS       = "driverparams";
100
        public static String                  VIEW_PROJ           = "viewProjection";
101
        
102
        private String                        fileName            = "";
103
        private String                        suffix              = ".tif";
104
        private RasterDataStore               dataStore           = null;
105
        private boolean                       oneLayerPerBand     = false;
106
        private int[]                         drawableBands       = { 0, 1, 2 };
107
        private double[]                      pValues             = null;
108
        private int                           interpolationMethod = Buffer.INTERPOLATION_Undefined;
109
        private String                        viewName            = "";
110
        private Params                        params              = null;
111
        private ColorInterpretation           colorInterp         = null;
112
        private ArrayList<ROI>                selectedRois        = null;
113
        private AffineTransform               affineTransform     = null;
114
        private double[]                      wcValues            = null;
115
        private RasterManager                 rManager            = RasterLocator.getManager();
116
        private BaseIncrementableTask         processIncrement    = null; 
117
        
118
        /**
119
         * Variables de la resoluci?n de salida
120
         */
121
        private int                           resolutionWidth     = 0;
122
        private int                           resolutionHeight    = 0;
123
        
124
        private Buffer                        buffer              = null;
125
        private IProjection                   viewProjection      = null;
126
        
127
        public static void registerParameters() {
128
                registerInputParameter(FILENAME, String.class, PROCESS_LABEL);
129
                registerInputParameter(SUFFIX, String.class, PROCESS_LABEL);
130
                registerInputParameter(VIEWNAME, String.class, PROCESS_LABEL);
131
                registerInputParameter(PX_COORDS, Double.class, PROCESS_LABEL);
132
                registerInputParameter(WORLD_COORDS, Double.class, PROCESS_LABEL);
133
                registerInputParameter(RASTER_STORE, RasterDataStore.class, PROCESS_LABEL);
134
                registerInputParameter(DRAWABLE_BANDS, Integer[].class, PROCESS_LABEL);
135
                registerInputParameter(ONE_LYE_PER_BAND, Boolean.class, PROCESS_LABEL);
136
                registerInputParameter(INTERP_METHOD, Integer.class, PROCESS_LABEL);
137
                registerInputParameter(AT, AffineTransform.class, PROCESS_LABEL);
138
                registerInputParameter(COLOR_INTERPR, ColorInterpretation.class, PROCESS_LABEL);
139
                registerInputParameter(SELECTED_ROIS, ArrayList.class, PROCESS_LABEL);
140
                registerInputParameter(RESOLUTION, Integer[].class, PROCESS_LABEL);
141
                registerInputParameter(DRIVER_PARAMS, Params.class, PROCESS_LABEL);
142
                registerInputParameter(VIEW_PROJ, IProjection.class, PROCESS_LABEL);
143
                
144
                //TODO: Falta definir salidas y asignarlas en el Map
145
                registerOutputParameter(FILENAME, String.class, PROCESS_LABEL);
146
        }
147
        
148
        /**
149
         * Par?metros obligatorios al proceso:
150
         * <UL>
151
         * <LI>filename: Nombre del fichero de salida</LI>
152
         * <LI>datawriter: Escritor de datos</LI>
153
         * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
154
         * <LI>pixelcoordinates: Coordenadas pixel del recorte (ulx, uly, lrx, lry)</LI>
155
         * <LI>layer: Capa de entrada para el recorte</LI>
156
         * <LI>drawablebands: Bandas de entrada</LI>
157
         * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
158
         * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
159
         * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
160
         * <LI>resolution: Ancho y alto de la capa de salida</LI>
161
         * </UL> 
162
         */
163
        @SuppressWarnings("unchecked")
164
        public void init() {
165
                fileName = getStringParam("filename");
166
                suffix = getStringParam("suffix");
167
                viewName = getStringParam("viewname");
168
                pValues = getDoubleArrayParam("pixelcoordinates");
169
                wcValues = getDoubleArrayParam("realcoordinates");
170
                dataStore = getParam("layer") != null ? (RasterDataStore)getParam("layer") : null;
171
                drawableBands = getIntArrayParam("drawablebands");
172
                oneLayerPerBand = getBooleanParam("onelayerperband");
173
                interpolationMethod = getIntParam("interpolationmethod");
174
                affineTransform = (AffineTransform)getParam("affinetransform");
175
                colorInterp = (ColorInterpretation)getParam("colorInterpretation");
176
                selectedRois = (ArrayList<ROI>)getParam("selectedrois");
177
                if(getIntArrayParam("resolution") != null) {
178
                        resolutionWidth = getIntArrayParam("resolution")[0];
179
                        resolutionHeight = getIntArrayParam("resolution")[1];
180
                }
181
                params = (Params) getParam("driverparams");
182
                viewProjection = getParam("viewProjection") != null ? (IProjection)getParam("viewProjection") : null;
183
        }
184

    
185
        /**
186
         * Salva la tabla de color al fichero rmf.
187
         * @param fName
188
         * @throws IOException
189
         */
190
        private void saveToRmf(String fileName) {
191
                int limitNumberOfRequests = 20;
192
                while (dataStore == null && limitNumberOfRequests > 0) {
193
                        try {
194
                        } catch (IndexOutOfBoundsException e) {
195
                                //En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
196
                                //se supone que es porque hay un refresco en el mismo momento de la petici?n por lo que como es m?s lento de
197
                                //gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
198
                                //haberlo cargado ya.
199
                                try {
200
                                        Thread.sleep(200);
201
                                } catch (InterruptedException e1) {
202
                                }
203
                        }
204
                        limitNumberOfRequests--;
205
                }
206
                
207
                if (dataStore == null) {
208
                        //RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
209
                        return;
210
                }
211

    
212
                // Guardamos en el RMF el valor NoData
213
                if(dataStore.getNoDataValue() != null) {
214
                        NoData nodata = (NoData)dataStore.getNoDataValue();
215
                        nodata.setFileName(fileName);
216
                        nodata.save();
217
                }
218

    
219
                // Guardamos en el RMF la tabla de color
220
                ColorTable colorTable = dataStore.getColorTable();
221
                try {
222
                        rManager.getProviderServices().saveObjectToRmfFile(fileName, ColorTable.class, colorTable);
223
                } catch (RmfSerializerException e) {
224
                        RasterSwingLibrary.messageBoxError("error_salvando_rmf", this, e);
225
                }
226
        }
227

    
228
        /**
229
         * Tarea de recorte
230
         */
231
        @SuppressWarnings("deprecation")
232
        public void process() throws ProcessInterruptedException {
233
                RasterDataStore dstoreCopy = null;
234
                RasterUtils util = RasterLocator.getManager().getRasterUtils();
235
                
236
                try {
237
                        long t2;
238
                        long t1 = new java.util.Date().getTime();
239

    
240
                        try {
241
                                Thread.sleep(1000);
242
                        } catch (InterruptedException e1) {
243
                                e1.printStackTrace();
244
                        }
245
                        
246
                        insertLineLog(Messages.getText("leyendo_raster"));
247
                        
248
                        dstoreCopy = dataStore.newNotTiledDataStore();
249
                        RasterQuery query = rManager.createQuery();
250
                        query.setDrawableBands(drawableBands);
251

    
252
                        if(dstoreCopy.getParameters() instanceof RemoteStoreParameters &&
253
                                !((RemoteStoreParameters)dstoreCopy.getParameters()).isSizeFixed()) {
254
                                insertLineLog(Messages.getText("downloading_image"));
255
                                ((RemoteStoreParameters)dstoreCopy.getParameters()).setWidth(resolutionWidth);
256
                                ((RemoteStoreParameters)dstoreCopy.getParameters()).setHeight(resolutionHeight);
257
                                Extent bbox = RasterLocator.getManager().getDataStructFactory().createExtent(wcValues[0], wcValues[1], wcValues[2], wcValues[3]);
258
                                query.setAreaOfInterest(bbox, resolutionWidth, resolutionHeight);
259
                                try {
260
                                        buffer = dstoreCopy.query(query);
261
                                } catch (QueryException e) {
262
                                        RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
263
                                }
264
                        } else {
265
                                if(interpolationMethod != Buffer.INTERPOLATION_Undefined) {
266
                                        try {
267
                                                if(pValues != null) {
268
                                                        if (util.isBufferTooBig(new double[] { pValues[0], pValues[3], pValues[2], pValues[1] }, drawableBands.length))
269
                                                                query.setReadOnly(true);
270
                                                        Rectangle r = new Rectangle((int)pValues[0], (int)pValues[1], (int)Math.abs(pValues[2] - pValues[0]) + 1, (int)Math.abs(pValues[3] - pValues[1]) + 1);
271
                                                        query.setAreaOfInterest(r);
272
                                                } else if(wcValues != null) {
273
                                                        query.setReadOnly(true);
274
                                                        Extent e = RasterLocator.getManager().getDataStructFactory().createExtent(
275
                                                                        wcValues[0], wcValues[1], wcValues[2], wcValues[3]);
276
                                                        query.setAreaOfInterest(e);
277
                                                        //query.setAreaOfInterest(wcValues[0], wcValues[1], Math.abs(wcValues[0] - wcValues[2]), Math.abs(wcValues[1] - wcValues[3]));
278
                                                }
279
                                                buffer = dstoreCopy.query(query);
280
                                        } catch (QueryException e) {
281
                                                RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
282
                                        }
283

    
284
                                        insertLineLog(Messages.getText("interpolando"));
285
                                        
286
                                        Buffer bufTmp = buffer;
287
                                        processIncrement = bufTmp.getIncrementableTask(Buffer.INCREMENTABLE_INTERPOLATION);
288
                                        buffer = bufTmp.getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
289
                                        if(bufTmp != buffer)
290
                                                bufTmp.dispose();
291
                                } else {
292
                                        try {
293
                                                if (util.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length))
294
                                                        query.setReadOnly(true);
295
                                                if(pValues != null) {
296
                                                        Rectangle r = new Rectangle(
297
                                                                        (int)pValues[0], 
298
                                                                        (int)pValues[3], 
299
                                                                        (int)Math.abs(pValues[2] - pValues[0]) + 1, 
300
                                                                        (int)Math.abs(pValues[1] - pValues[3]) + 1);
301
                                                        query.setAreaOfInterest(r, resolutionWidth, resolutionHeight);
302
                                                }
303
                                                else if(wcValues != null) {
304
                                                        Extent bbox = RasterLocator.getManager().getDataStructFactory().createExtent(wcValues[0], wcValues[1], wcValues[2], wcValues[3]);
305
                                                        query.setAreaOfInterest(bbox, resolutionWidth, resolutionHeight);
306
                                                }
307
                                                buffer = dstoreCopy.query(query);
308
                                        } catch (QueryException e) {
309
                                                RasterSwingLibrary.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
310
                                        }
311
                                }
312
                        }
313
                        
314
                        //TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
315

    
316
                        if ((selectedRois != null) && (!query.isReadOnly())){
317
                                if (selectedRois.size() > 0){
318
                                        int despX = 0;
319
                                        int despY = 0;
320
                                        if (pValues != null){
321
                                                despX = (int)pValues[0];
322
                                                despY = (int)pValues[1];
323
                                        } else if (wcValues != null){
324
                                                despX = (int)dstoreCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getX();
325
                                                despY = (int)dstoreCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getY();
326
                                        }
327
                                        drawOnlyROIs(buffer, selectedRois, despX, despY);
328
                                }
329
                        }
330
                        
331
                        
332
                        insertLineLog(Messages.getText("salvando_imagen"));
333
                        
334
                        DataManager manager = DALLocator.getDataManager();
335
                        String provider = "Gdal Store";
336
                        DataServerExplorerParameters eparams = manager.createServerExplorerParameters("FilesystemExplorer");
337
                        
338
                        String finalFileName = "";
339
                        NewRasterStoreParameters sparams = null;
340
                        processIncrement = RasterLocator.getManager().createDataServerWriter();
341
                        if (oneLayerPerBand) {
342
                                long[] milis = new long[drawableBands.length];
343
                                String[] fileNames = new String[drawableBands.length];
344
                                for (int i = 0; i < drawableBands.length; i++) {
345
                                        fileNames[i] = fileName + "_B" + drawableBands[i] + suffix;
346
                                        
347
                                        int index = fileNames[i].lastIndexOf(File.separator);
348
                                        if(index < 0)
349
                                                index = fileNames[i].length();
350
                                        String path = fileNames[i].substring(0, index);
351
                                        String file = fileNames[i].substring(index + 1, fileNames[i].length());
352
                                        
353
                                        eparams.setDynValue("initialpath", path);
354
                                        DataServerExplorer serverExplorer = manager.openServerExplorer(eparams.getExplorerName(), eparams);
355

    
356
                                        sparams = (NewRasterStoreParameters)serverExplorer.getAddParameters(provider);
357
                                        sparams.setDataServer((DataServerWriter)processIncrement);
358
                                        sparams.setDestination(path, file);
359
                                        sparams.setBuffer(buffer);
360
                                        sparams.setColorInterpretation(new String[]{ColorInterpretation.GRAY_BAND});
361
                                        sparams.setWktProjection(dstoreCopy.getWktProjection());
362
                                        sparams.setBand(i);
363
                                        sparams.setAffineTransform(affineTransform);
364
                                        sparams.setDriverParams(params);
365
                                        
366
                                        serverExplorer.add(provider, sparams, true);
367
                                        
368
                                        saveToRmf(fileNames[i]);
369
                                        t2 = new java.util.Date().getTime();
370
                                        milis[i] = (t2 - t1);
371
                                        t1 = new java.util.Date().getTime();
372
                                }
373
                                if (incrementableTask != null) {
374
                                        incrementableTask.processFinalize();
375
                                        incrementableTask = null;
376
                                }
377
                                if(viewName != null) {
378
                                        if (RasterSwingLibrary.messageBoxYesOrNot("cargar_toc", this)) {
379
                                                try {
380
                                                        for (int i = 0; i < drawableBands.length; i++) {
381
                                                                FLayer lyr = RasterMainPluginUtils.loadLayer(viewName, fileNames[i], null);
382
                                                                if(lyr != null && lyr instanceof DefaultFLyrRaster) {
383
                                                                        if(dataStore.getProjection() != null)
384
                                                                                ((DefaultFLyrRaster)lyr).setRois(dataStore.getRois(dataStore.getProjection()));
385
                                                                        else
386
                                                                                ((DefaultFLyrRaster)lyr).setRois(dataStore.getRois(viewProjection));
387
                                                                }
388
                                                        }
389
                                                } catch (RasterNotLoadException e) {
390
                                                        RasterSwingLibrary.messageBoxError("error_load_layer", this, e);
391
                                                }
392
                                        }
393
                                }
394
                                for (int i = 0; i < drawableBands.length; i++) {
395
                                        if (externalActions != null)
396
                                                externalActions.end(new Object[] { fileName + "_B" + drawableBands[i] + suffix, new Long(milis[i]) });
397
                                }
398
                        } else {
399
                                if (isUsingFile(fileName)) {
400
                                        incrementableTask.hideWindow();
401
                                        RasterSwingLibrary.messageBoxError("error_opened_file", this);
402
                                        return;
403
                                }
404
                                File f = new File(fileName);
405
                                if (f.exists()) {
406
                                        f.delete();
407
                                }
408
                                f = null;
409
                                
410
                                if(suffix != null)
411
                                        finalFileName = fileName.endsWith(suffix) ? fileName : fileName + suffix;
412
                                else
413
                                        finalFileName = fileName;
414
                                
415
                                int index = finalFileName.lastIndexOf(File.separator);
416
                                if(index < 0)
417
                                        index = finalFileName.length();
418
                                String path = finalFileName.substring(0, index);
419
                                String file = finalFileName.substring(index + 1, finalFileName.length());
420
                                
421
                                eparams.setDynValue("initialpath", path);
422
                                DataServerExplorer serverExplorer = manager.openServerExplorer(eparams.getExplorerName(), eparams);
423

    
424
                                try {
425
                                        provider = rManager.createWriter(finalFileName).getProviderName();
426
                                } catch (NotSupportedExtensionException e1) {
427
                                        RasterSwingLibrary.messageBoxError("no_driver_escritura", this, e1);
428
                                } catch (RasterDriverException e1) {
429
                                        RasterSwingLibrary.messageBoxError("no_driver_escritura", this, e1);
430
                                }
431
                                
432
                                sparams = (NewRasterStoreParameters)serverExplorer.getAddParameters(provider);
433
                                sparams.setDataServer((DataServerWriter)processIncrement);
434
                                sparams.setDestination(path, file);
435
                                sparams.setBuffer(buffer);
436
                                if(colorInterp != null)
437
                                        sparams.setColorInterpretation(colorInterp.getValues());
438
                                sparams.setWktProjection(dstoreCopy.getWktProjection());
439
                                sparams.setAffineTransform(affineTransform);
440
                                sparams.setDriverParams(params);
441
                                sparams.setBand(-1);
442
                                
443
                                serverExplorer.add(provider, sparams, true);
444
                                
445
                                saveToRmf(finalFileName);
446
                                
447
                                
448
                                t2 = new java.util.Date().getTime();
449
                                if (incrementableTask != null) {
450
                                        incrementableTask.processFinalize();
451
                                        incrementableTask = null;
452
                                }
453
                                //Damos tiempo a parar el Thread del incrementable para que no se cuelgue la ventana
454
                                //El tiempo es como m?nimo el de un bucle del run de la tarea incrementable
455
                                try {
456
                                        Thread.sleep(600);
457
                                } catch (InterruptedException e) {
458
                                        throw new ProcessInterruptedException(e);
459
                                }
460
                                cutFinalize(finalFileName, (t2 - t1));
461
                        }
462

    
463
                } catch (RasterDriverException e) {
464
                        RasterSwingLibrary.messageBoxError("error_writer", this, e);
465
                } catch (ValidateDataParametersException e) {
466
                        RasterSwingLibrary.messageBoxError("error_georasterwriter", this);
467
                } catch (ProviderNotRegisteredException e) {
468
                        RasterSwingLibrary.messageBoxError("error_georasterwriter", this, e);
469
                } catch (InitializeException e) {
470
                        RasterSwingLibrary.messageBoxError("error_georasterwriter", this, e);
471
                } catch (DataException e) {
472
                        RasterSwingLibrary.messageBoxError("error_georasterwriter", this, e);
473
                } catch (Exception e) {
474
                        e.printStackTrace();
475
                } finally {
476
                        if (dstoreCopy != null)
477
                                try {
478
                                        dstoreCopy.close();
479
                                } catch (CloseException e) {
480
                                        RasterToolsUtil.debug("error_writer", this, e);
481
                                }
482
                        buffer = null;
483
                }
484
        }
485
        
486
        
487
        /**
488
         * Acciones para poner a NoData los pixels que est?n fuera de las
489
         * regiones de inter?s seleccionadas.
490
         * @param buffer
491
         */
492
        private void drawOnlyROIs(Buffer buffer, List<ROI> rois, int despX, int despY){
493
                for (int i = 0 ; i < buffer.getWidth() ; i++){
494
                        for (int j = 0 ; j < buffer.getHeight() ; j++){
495
                                boolean  inside = false;
496
                                for (int k = 0 ; k < rois.size() ; k++){
497
                                        ROI roi = rois.get(k);
498
                                        //TODO: Hacer la comprobacion por coordenadas del mundo en lugar de coordenadas pixel.
499
                                        if (roi.isInsideOfPolygon(i + despX, j + despY)){
500
                                                inside = true;
501
                                        }
502
                                }
503
                                if (!inside){
504
                                        for (int l = 0 ; l < buffer.getBandCount() ; l++){
505
                                                if (buffer.getDataType() == Buffer.TYPE_BYTE){
506
                                                        buffer.setElem(j, i, l, 
507
                                                                        buffer.getNoDataValue().isDefined() ? buffer.getNoDataValue().getValue().byteValue() : RasterLibrary.defaultByteNoDataValue);
508
                                                } else if (buffer.getDataType() == Buffer.TYPE_SHORT){
509
                                                        buffer.setElem(j, i, l, 
510
                                                                        buffer.getNoDataValue().isDefined() ? buffer.getNoDataValue().getValue().shortValue() : RasterLibrary.defaultShortNoDataValue);
511
                                                } else if (buffer.getDataType() == Buffer.TYPE_INT){
512
                                                        buffer.setElem(j, i, l, 
513
                                                                        buffer.getNoDataValue().isDefined() ? buffer.getNoDataValue().getValue().intValue() : RasterLibrary.defaultIntegerNoDataValue);
514
                                                } else if (buffer.getDataType() == Buffer.TYPE_FLOAT){
515
                                                        buffer.setElem(j, i, l, 
516
                                                                        buffer.getNoDataValue().isDefined() ? buffer.getNoDataValue().getValue().floatValue() : RasterLibrary.defaultFloatNoDataValue);
517
                                                } else if (buffer.getDataType() == Buffer.TYPE_DOUBLE){
518
                                                        buffer.setElem(j, i, l, 
519
                                                                        buffer.getNoDataValue().isDefined() ? buffer.getNoDataValue().getValue().doubleValue() : RasterLibrary.defaultDoubleNoDataValue);
520
                                                }
521
                                        }
522
                                }
523
                        }
524
                }
525
        }
526
        
527
        
528
        /**
529
         * Returns true if there is a layer in the current project using the file named with
530
         * fileName.
531
         * @param fileName
532
         * @return
533
         */
534
        private boolean isUsingFile(String fileName) {
535
                List<Document> docs = ProjectManager.getInstance().getCurrentProject().getDocuments();
536
                
537
                for (int i = 0 ;i < docs.size() ;i++) {
538
                        if (docs.get(i) instanceof BaseViewDocument) {
539
                                FLayers lyrs = ((BaseViewDocument)docs.get(i)).getMapContext().getLayers();
540
                                for (int j = 0 ;j < lyrs.getLayersCount() ;j++) {
541
                                        if (lyrs.getLayer(j) instanceof DefaultFLyrRaster) {
542
                                                DefaultFLyrRaster lyr = (DefaultFLyrRaster)lyrs.getLayer(j);                                                
543
                                                if (lyr.getDataStore() != null ){                                                        
544
                                                        if (fileName.equals(lyr.getDataStore().getName())) {
545
                                                                return true;
546
                                                        }
547
                                                }                
548
                                        }
549
                                }
550
                        }
551
                }
552
                return false;
553
        }
554
        
555
        
556
        /**
557
         * Acciones que se realizan al finalizar de crear los recortes de imagen.
558
         * Este m?todo es llamado por el thread TailRasterProcess al finalizar.
559
         */
560
        private void cutFinalize(String fileName, long milis) {
561
                if (!new File(fileName).exists())
562
                        return;
563

    
564
                if(viewName != null) {
565
                        if (RasterSwingLibrary.messageBoxYesOrNot("cargar_toc", null)) {
566

    
567
                                try {
568
                                        FLayer lyr = RasterMainPluginUtils.loadLayer(viewName, fileName, null);
569
                                        if(lyr != null && lyr instanceof DefaultFLyrRaster) {
570
                                                if(dataStore.getProjection() != null)
571
                                                        ((DefaultFLyrRaster)lyr).setRois(dataStore.getRois(dataStore.getProjection()));
572
                                                else
573
                                                        ((DefaultFLyrRaster)lyr).setRois(dataStore.getRois(viewProjection));
574
                                        }
575
                                } catch (RasterNotLoadException e) {
576
                                        RasterSwingLibrary.messageBoxError("error_load_layer", this, e);
577
                                } catch (ROIException e) {
578
                                        RasterSwingLibrary.messageBoxError("error_load_layer", this, e);
579
                                }
580
                        }
581
                }
582

    
583
                if (externalActions != null)
584
                        externalActions.end(new Object[]{fileName, new Long(milis)});
585
        }
586

    
587
        /*
588
         * (non-Javadoc)
589
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
590
         */
591
        public int getPercent() {
592
                return (processIncrement != null) ? processIncrement.getPercent() : 0;
593
        }
594

    
595
        /*
596
         * (non-Javadoc)
597
         * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
598
         */
599
        public String getTitle() {
600
                return Messages.getText("incremento_recorte");
601
        }
602
        
603
        /*
604
         * (non-Javadoc)
605
         * @see java.lang.Object#finalize()
606
         */
607
        protected void finalize() throws Throwable {
608
                fileName            = null;
609
                suffix              = null;
610
                dataStore            = null;
611
                drawableBands       = null;
612
                pValues             = null;
613
                viewName            = null;
614
                params              = null;
615
                colorInterp         = null;
616
                affineTransform     = null;
617
                wcValues            = null;
618
                buffer              = null;
619
                processIncrement    = null;
620
                if(selectedRois != null) {
621
                        selectedRois.clear();
622
                        selectedRois = null;
623
                }
624
                super.finalize();
625
        }
626
}