Revision 19568

View differences:

trunk/extensions/extRasterTools-SE/src/org/gvsig/raster/beans/previewbase/PreviewFiltering.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 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.raster.beans.previewbase;
20

  
21
import java.util.ArrayList;
22

  
23
import org.gvsig.raster.dataset.Params;
24
import org.gvsig.raster.grid.filter.FilterTypeException;
25
import org.gvsig.raster.grid.filter.IRasterFilterListManager;
26
import org.gvsig.raster.grid.filter.RasterFilter;
27
import org.gvsig.raster.grid.filter.RasterFilterList;
28
import org.gvsig.raster.grid.filter.RasterFilterListManager;
29
import org.gvsig.raster.hierarchy.IRasterRendering;
30
import org.gvsig.raster.util.RasterToolsUtil;
31

  
32
import com.iver.andami.PluginServices;
33

  
34
/**
35
 * Procesado de la imagen para la previsualizaci?n. Para poder usar esta clase despu?s de instanciarla
36
 * habr? que asignarle un valor a showFiltersSelected aunque por defecto est? a true por lo que se
37
 * visualizaran los cambios sin problemas, asigna una lista de filtros inicial (que ya tenga el raster
38
 * aplicado) con setFilterStatus y asignar los filtros que queramos aplicar con addNewParam (una llamada
39
 * por cada filtro).
40
 * 
41
 * 19/02/2008
42
 * @author Nacho Brodin nachobrodin@gmail.com
43
 */
44
public class PreviewFiltering implements IPreviewRenderProcess {
45

  
46
	private boolean          showFiltersSelected     = true;
47
	private ArrayList        paramsList              = new ArrayList();
48
	private ArrayList        filtersInit             = new ArrayList();
49
	
50
	/**
51
	 * Flag de selecci?n de activaci?n y desactivaci?n
52
	 * @param show
53
	 */
54
	public void showFiltersSelected(boolean show) {
55
		this.showFiltersSelected = show;
56
	}
57
	
58
	/**
59
	 * Obtiene la lista de par?metros
60
	 * @return the paramsList
61
	 */
62
	public ArrayList getParamsList() {
63
		return paramsList;
64
	}
65
	
66
	/**
67
	 * Asigna la lista de par?metros
68
	 * @param params
69
	 */
70
	public void setParamsList(ArrayList params) {
71
		this.paramsList = params;
72
	}
73
	
74
	/**
75
	 * Asigna el arrayList de filtros inicial. Esto hace que aplique los filtros que ya
76
	 * existen en el raster. Estos pueden ser obtenidos del render de la capa de la forma
77
	 * lyr.getRender().getFilterList().getStatusCloned().  
78
	 * @param params Lista de filtros aplicados.
79
	 */
80
	public void setFilterStatus(ArrayList filtersInit) {
81
		this.filtersInit = filtersInit;
82
	}
83
	
84
	/**
85
	 * Devuelve el arrayList de filtros inicial
86
	 * @return
87
	 */
88
	public ArrayList getFilterStatus() {
89
		return filtersInit;
90
	}
91
	
92
	/**
93
	 * A?adir un nuevo Params a la lista de Params que podemos manejar. Un Params
94
	 * equivale a un filtro cargado. El hecho de trabajar con Params y no con
95
	 * filtros, simplifica totalmente el panel. Sin tener que depender de los
96
	 * filtros nada m?s que para el momento de dibujado o guardado.
97
	 * @param name
98
	 * @param params
99
	 * @param classFilter
100
	 */
101
	public void addNewParam(String name, Params params, Class classFilter) {
102
		ParamStruct param = new ParamStruct();
103
		param.setFilterName(name);
104
		param.setFilterParam(params);
105
		param.setFilterClass(classFilter);
106
		paramsList.add(param);
107
	}
108

  
109
	/**
110
	 * Procesa la imagen con la lista de filtros si el flag showFilterSelected est? a true.
111
	 * Esta funci?n llama a addFilter por cada filtro a?adido pero es applyFilters la encargada
112
	 * de construir la lista. 
113
	 */
114
	public void process(IRasterRendering rendering) throws FilterTypeException {
115
		rendering.getRenderFilterList().clear();
116

  
117
		if (showFiltersSelected) {
118
			RasterFilterList filterList = rendering.getRenderFilterList();
119
			RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
120

  
121
			ArrayList listFilterUsed = applyFilters(rendering);
122
			ArrayList exc = new ArrayList();
123
			for (int i = 0; i < listFilterUsed.size(); i++) {
124
				IRasterFilterListManager filterManager = stackManager.getManagerByFilterClass(((ParamStruct) listFilterUsed.get(i)).getFilterClass());
125
				try {
126
					filterManager.addFilter(((ParamStruct) listFilterUsed.get(i)).getFilterClass(), ((ParamStruct) listFilterUsed.get(i)).getFilterParam());
127
				} catch (FilterTypeException e) {
128
					exc.add(e);
129
				}
130
			}
131
			if(exc.size() != 0) {
132
				RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_adding_filters"), this, exc);
133
				exc.clear();
134
			}
135
		}
136
	}
137
	
138
	/**
139
	 * Aqui se seleccionan que filtros se van a aplicar y se devuelven en forma
140
	 * de ArrayList tanto para el dibujado como cuando aceptan o aplican el panel.
141
	 * @param rendering
142
	 * @return
143
	 */
144
	public ArrayList applyFilters(IRasterRendering rendering) {
145
		ArrayList listFilterUsed = new ArrayList();
146

  
147
		RasterFilterList filterList = new RasterFilterList();
148
		filterList.setEnv(rendering.getRenderFilterList().getEnv());
149
		RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
150

  
151
		if(filtersInit == null)
152
			return listFilterUsed;
153
		
154
		// Conservamos filtros ya existentes
155
		for (int i = 0; i < filtersInit.size(); i++) {
156
			
157
			RasterFilter obj = null;
158
			for (int j = 0; j < stackManager.getRasterFilterList().size(); j++) {
159
				Class classFilter = (Class) stackManager.getRasterFilterList().get(j);
160
				try {
161
					obj = (RasterFilter) classFilter.newInstance();
162
					if (obj.getName().equals(((RasterFilter) filtersInit.get(i)).getName()))
163
						break;
164
				} catch (InstantiationException e) {
165
					RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
166
				} catch (IllegalAccessException e) {
167
					RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
168
				}
169
			}
170

  
171
			// Si no encontramos el filtro apropiado, nos olvidamos de el
172
			if (obj == null)
173
				continue;
174

  
175
			// Si no es visible tenemos que conservar el filtro
176
			try {
177
				Params params = (Params) ((RasterFilter) filtersInit.get(i)).getUIParams(((RasterFilter) filtersInit.get(i)).getName()).clone();
178
				// A?ado el parametro RenderBands a los parametros del filtro
179
				String rgb = rendering.getRenderBands()[0] + " " + rendering.getRenderBands()[1] + " " + rendering.getRenderBands()[2];
180
				params.setParam("RenderBands", rgb, 0, null);
181
			
182
				ParamStruct newParam = new ParamStruct();
183
				newParam.setFilterClass(obj.getClass());
184
				newParam.setFilterName(((RasterFilter) filtersInit.get(i)).getName());
185
				newParam.setFilterParam(params);
186
				listFilterUsed.add(newParam);
187
			} catch (CloneNotSupportedException e) {
188
			}
189
		}
190
		
191
		// Metemos los filtros seleccionados en listFilterUsed
192
		for (int i = 0; i < paramsList.size(); i++) {
193
			// En caso de existir el filtro, lo reemplazamos
194
			boolean finded = false;
195
			for (int j = 0; j < listFilterUsed.size(); j++) {
196
				if (((ParamStruct) listFilterUsed.get(j)).filterName.equals(((ParamStruct) paramsList.get(i)).getFilterName())) {
197
					listFilterUsed.set(j, paramsList.get(i));
198
					finded = true;
199
					break;
200
				}
201
			}
202
			if (!finded)
203
				listFilterUsed.add(paramsList.get(i));
204
		}
205
		
206
		return listFilterUsed;
207
	}
208

  
209
}
trunk/extensions/extRasterTools-SE/src/org/gvsig/raster/util/process/ClippingProcess.java
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.raster.util.process;
20

  
21
import java.awt.geom.AffineTransform;
22
import java.io.File;
23
import java.io.FileNotFoundException;
24
import java.io.IOException;
25

  
26
import org.apache.log4j.Logger;
27
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
28
import org.gvsig.raster.Configuration;
29
import org.gvsig.raster.RasterProcess;
30
import org.gvsig.raster.buffer.BufferFactory;
31
import org.gvsig.raster.buffer.BufferInterpolation;
32
import org.gvsig.raster.buffer.RasterBuffer;
33
import org.gvsig.raster.buffer.WriterBufferServer;
34
import org.gvsig.raster.dataset.GeoRasterWriter;
35
import org.gvsig.raster.dataset.IBuffer;
36
import org.gvsig.raster.dataset.IRasterDataSource;
37
import org.gvsig.raster.dataset.InvalidSetViewException;
38
import org.gvsig.raster.dataset.NotSupportedExtensionException;
39
import org.gvsig.raster.dataset.Params;
40
import org.gvsig.raster.dataset.RasterDataset;
41
import org.gvsig.raster.dataset.io.RasterDriverException;
42
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
43
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
44
import org.gvsig.raster.datastruct.ColorTable;
45
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer;
46
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
47
import org.gvsig.raster.grid.GridPalette;
48
import org.gvsig.raster.grid.filter.RasterFilterList;
49
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
50
import org.gvsig.raster.util.RasterNotLoadException;
51
import org.gvsig.raster.util.RasterToolsUtil;
52
import org.gvsig.raster.util.RasterUtilities;
53
/**
54
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
55
 * para aplicar un recorte a una capa y guardarlo en disco. Muestra una barra
56
 * de incremento informativa.
57
 *
58
 * @version 24/04/2007
59
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
60
 */
61
public class ClippingProcess extends RasterProcess {
62
	private String                        fileName            = "";
63
	private WriterBufferServer            writerBufferServer  = null;
64
	private FLyrRasterSE                  rasterSE            = null;
65
	private AffineTransform               affineTransform     = new AffineTransform();
66
	private boolean                       oneLayerPerBand     = false;
67
	private int[]                         drawableBands       = { 0, 1, 2 };
68
	private int[]                         dValues             = null;
69
	private GeoRasterWriter               grw                 = null;
70
	private int                           interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined;
71
	private String                        viewName            = "";
72
	private Params                        params              = null;
73
	private DatasetColorInterpretation    colorInterp         = null;
74

  
75
	/**
76
	 * Variables de la resoluci?n de salida
77
	 */
78
	private int                           resolutionWidth     = 0;
79
	private int                           resolutionHeight    = 0;
80
	
81
	private IBuffer                       buffer              = null;
82

  
83
	/**
84
	 * Par?metros obligatorios al proceso:
85
	 * <UL>
86
	 * <LI>filename: Nombre del fichero de salida</LI>
87
	 * <LI>datawriter: Escritor de datos</LI>
88
	 * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
89
	 * <LI>pixelcoordinates: Coordenadas pixel del recorte</LI>
90
	 * <LI>layer: Capa de entrada para el recorte</LI>
91
	 * <LI>drawablebands: Bandas de entrada</LI>
92
	 * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
93
	 * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
94
	 * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
95
	 * <LI>resolution: Ancho y alto de la capa de salida</LI>
96
	 * </UL> 
97
	 */
98
	public void init() {
99
		fileName = getStringParam("filename");
100
		writerBufferServer = (WriterBufferServer) getParam("datawriter");
101
		viewName = getStringParam("viewname");
102
		dValues = getIntArrayParam("pixelcoordinates");
103
		rasterSE = getLayerParam("layer");
104
		drawableBands = getIntArrayParam("drawablebands");
105
		oneLayerPerBand = getBooleanParam("onelayerperband");
106
		interpolationMethod = getIntParam("interpolationmethod");
107
		affineTransform = (AffineTransform)getParam("affinetransform");
108
		colorInterp = (DatasetColorInterpretation)getParam("colorInterpretation");
109
		if(getIntArrayParam("resolution") != null) {
110
			resolutionWidth = getIntArrayParam("resolution")[0];
111
			resolutionHeight = getIntArrayParam("resolution")[1];
112
		}
113
		params = (Params) getParam("driverparams");
114
	}
115

  
116
	/**
117
	 * Salva la tabla de color al fichero rmf.
118
	 * @param fName
119
	 * @throws IOException
120
	 */
121
	private void saveToRmf(String fileName) {
122
		fileName = RasterUtilities.getNameWithoutExtension(fileName) + ".rmf";
123

  
124
		RasterDataset rds = null;
125
		int limitNumberOfRequests = 20;
126
		while (rds == null && limitNumberOfRequests > 0) {
127
			try {
128
				rds = rasterSE.getDataSource().getDataset(0)[0];
129
			} catch (IndexOutOfBoundsException e) {
130
				//En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
131
				//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
132
				//gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
133
				//haberlo cargado ya.
134
				try {
135
					Thread.sleep(200);
136
				} catch (InterruptedException e1) {
137
				}
138
			}
139
			limitNumberOfRequests--;
140
		}
141
		
142
		if (rds == null) {
143
			//RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
144
			return;
145
		}
146
		
147
		RmfBlocksManager manager = rds.getRmfBlocksManager();
148

  
149
		RasterFilterList rasterFilterList = rasterSE.getRenderFilterList();
150

  
151
		manager.setPath(fileName);
152

  
153
		if (!manager.checkRmf())
154
			return;
155

  
156
		// A?adimos el serializador de NoData
157
		if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
158
			NoDataRmfSerializer ser = new NoDataRmfSerializer(Double.valueOf(rasterSE.getNoDataValue(0)));
159
			manager.addClient(ser);
160
		}
161
		
162
		// A?adimos el serializador para tablas de color
163
		ColorTableFilter colorTableFilter = (ColorTableFilter) rasterFilterList.getByName(ColorTableFilter.names[0]);
164
		if (colorTableFilter != null) {
165
			GridPalette gridPalette = new GridPalette((ColorTable) colorTableFilter.getColorTable().clone());
166
			ColorTableRmfSerializer ser = new ColorTableRmfSerializer(gridPalette);
167
			manager.addClient(ser);
168
		}
169

  
170
		try {
171
			manager.write(true);
172
		} catch (FileNotFoundException e) {
173
			RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
174
		} catch (IOException e) {
175
			RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
176
		}
177

  
178
		manager.deleteAllClients();
179
	}
180

  
181
	/**
182
	 * Tarea de recorte
183
	 */
184
	public void process() throws InterruptedException {
185
		IRasterDataSource dsetCopy = null;
186
		try {
187
			long t2;
188
			long t1 = new java.util.Date().getTime();
189

  
190
			insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
191

  
192
			dsetCopy = rasterSE.getDataSource().newDataset();
193
			BufferFactory bufferFactory = new BufferFactory(dsetCopy);
194
			bufferFactory.setDrawableBands(drawableBands);
195
	
196
			if(	interpolationMethod != BufferInterpolation.INTERPOLATION_Undefined &&
197
					interpolationMethod != BufferInterpolation.INTERPOLATION_NearestNeighbour) {
198
				try {
199
					if (RasterBuffer.isBufferTooBig(new double[] { dValues[0], dValues[3], dValues[2], dValues[1] }, drawableBands.length))
200
						bufferFactory.setReadOnly(true);
201

  
202
					bufferFactory.setAreaOfInterest(dValues[0], dValues[3], dValues[2] - dValues[0], dValues[1] - dValues[3]);
203
				} catch (InvalidSetViewException e) {
204
					Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e);
205
				}
206
				buffer = bufferFactory.getRasterBuf();
207

  
208
				insertLineLog(RasterToolsUtil.getText(this, "interpolando"));
209

  
210
				buffer = ((RasterBuffer) buffer).getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
211
			} else {
212
				try {
213
					if (RasterBuffer.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length))
214
						bufferFactory.setReadOnly(true);
215
					bufferFactory.setAreaOfInterest(dValues[0], dValues[3], Math.abs(dValues[2] - dValues[0]), Math.abs(dValues[1] - dValues[3]), resolutionWidth, resolutionHeight);
216
					buffer = bufferFactory.getRasterBuf();
217
				} catch (InvalidSetViewException e) {
218
					Logger.getLogger(this.getClass().getName()).debug("No se ha podido asignar la vista al inicial el proceso de recorte.", e);
219
				}
220
			}
221
			//TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
222
			
223
			insertLineLog(RasterToolsUtil.getText(this, "salvando_imagen"));
224

  
225
			String finalFileName = "";
226
			if (oneLayerPerBand) {
227
				long[] milis = new long[drawableBands.length];
228
				String[] fileNames = new String[drawableBands.length];
229
				for (int i = 0; i < drawableBands.length; i++) {
230
					fileNames[i] = fileName + "_B" + drawableBands[i] + ".tif";
231
					writerBufferServer.setBuffer(buffer, i);
232
					Params p = null;
233
					if (params == null)
234
						p = GeoRasterWriter.getWriter(fileNames[i]).getParams();
235
					else
236
						p = params;
237
					grw = GeoRasterWriter.getWriter(writerBufferServer, fileNames[i], 1,
238
							affineTransform, buffer.getWidth(), buffer.getHeight(),
239
							buffer.getDataType(), p, null);
240
					grw.setColorBandsInterpretation(new String[]{DatasetColorInterpretation.GRAY_BAND});
241
					grw.setWkt(dsetCopy.getWktProjection());
242
					grw.dataWrite();
243
					grw.writeClose();
244
					saveToRmf(fileNames[i]);
245
					t2 = new java.util.Date().getTime();
246
					milis[i] = (t2 - t1);
247
					t1 = new java.util.Date().getTime();
248
				}
249
				if (incrementableTask != null) {
250
					incrementableTask.processFinalize();
251
					incrementableTask = null;
252
				}
253
				if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
254
					try {
255
						for (int i = 0; i < drawableBands.length; i++) {
256
							RasterToolsUtil.loadLayer(viewName, fileNames[i], null);
257
						}
258
					} catch (RasterNotLoadException e) {
259
						RasterToolsUtil.messageBoxError("error_load_layer", this, e);
260
					}
261
				}
262
				for (int i = 0; i < drawableBands.length; i++) {
263
					if (externalActions != null)
264
						externalActions.end(new Object[] { fileName, new Long(milis[i]) });
265
				}
266
			} else {
267
				writerBufferServer.setBuffer(buffer, -1);
268
				if (params == null) {
269
					finalFileName = fileName + ".tif";
270
					params = GeoRasterWriter.getWriter(finalFileName).getParams();
271
				} else
272
					finalFileName = fileName;
273
				grw = GeoRasterWriter.getWriter(writerBufferServer, finalFileName,
274
						buffer.getBandCount(), affineTransform, buffer.getWidth(),
275
						buffer.getHeight(), buffer.getDataType(), params, null);
276
				if(colorInterp != null)
277
					grw.setColorBandsInterpretation(colorInterp.getValues());
278
				grw.setWkt(dsetCopy.getWktProjection());
279
				grw.dataWrite();
280
				grw.writeClose();
281
				saveToRmf(finalFileName);
282
				t2 = new java.util.Date().getTime();
283
				if (incrementableTask != null) {
284
					incrementableTask.processFinalize();
285
					incrementableTask = null;
286
				}
287
				//Damos tiempo a parar el Thread del incrementable para que no se cuelgue la ventana
288
				//El tiempo es como m?nimo el de un bucle de del run de la tarea incrementable
289
				Thread.sleep(600);
290
				cutFinalize(finalFileName, (t2 - t1));
291
			}
292

  
293
		} catch (NotSupportedExtensionException e) {
294
			Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer. Extensi?n no soportada", e);
295
		} catch (RasterDriverException e) {
296
			Logger.getLogger(this.getClass().getName()).debug("No se ha podido obtener el writer.", e);
297
		} catch (IOException e) {
298
			Logger.getLogger(this.getClass().getName()).debug("Error en la escritura en GeoRasterWriter.", e);
299
		} finally {
300
			if (dsetCopy != null)
301
				dsetCopy.close();
302
			buffer = null;
303
		}
304
	}
305
	
306
	/**
307
	 * Acciones que se realizan al finalizar de crear los recortes de imagen.
308
	 * Este m?todo es llamado por el thread TailRasterProcess al finalizar.
309
	 */
310
	private void cutFinalize(String fileName, long milis) {
311
		if (!new File(fileName).exists())
312
			return;
313

  
314
		if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
315
			try {
316
				RasterToolsUtil.loadLayer(viewName, fileName, null);
317
			} catch (RasterNotLoadException e) {
318
				RasterToolsUtil.messageBoxError("error_load_layer", this, e);
319
			}
320
		}
321

  
322
		if (externalActions != null)
323
			externalActions.end(new Object[]{fileName, new Long(milis)});
324
	}
325

  
326
	/*
327
	 * (non-Javadoc)
328
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
329
	 */
330
	public int getPercent() {
331
		return (writerBufferServer != null) ? writerBufferServer.getPercent() : 0;
332
	}
333

  
334
	/*
335
	 * (non-Javadoc)
336
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
337
	 */
338
	public String getTitle() {
339
		return RasterToolsUtil.getText(this, "incremento_recorte");
340
	}
341
}
trunk/extensions/extRasterTools-SE/src/org/gvsig/raster/util/process/FilterProcess.java
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.raster.util.process;
20

  
21
import java.io.FileNotFoundException;
22
import java.io.IOException;
23
import java.util.ArrayList;
24

  
25
import org.gvsig.raster.Configuration;
26
import org.gvsig.raster.RasterProcess;
27
import org.gvsig.raster.beans.previewbase.ParamStruct;
28
import org.gvsig.raster.buffer.BufferFactory;
29
import org.gvsig.raster.buffer.RasterBuffer;
30
import org.gvsig.raster.buffer.WriterBufferServer;
31
import org.gvsig.raster.dataset.GeoRasterWriter;
32
import org.gvsig.raster.dataset.IBuffer;
33
import org.gvsig.raster.dataset.IRasterDataSource;
34
import org.gvsig.raster.dataset.NotSupportedExtensionException;
35
import org.gvsig.raster.dataset.io.RasterDriverException;
36
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
37
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
38
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
39
import org.gvsig.raster.grid.Grid;
40
import org.gvsig.raster.grid.GridTransparency;
41
import org.gvsig.raster.grid.filter.FilterTypeException;
42
import org.gvsig.raster.grid.filter.IRasterFilterListManager;
43
import org.gvsig.raster.grid.filter.RasterFilterList;
44
import org.gvsig.raster.grid.filter.RasterFilterListManager;
45
import org.gvsig.raster.hierarchy.IRasterRendering;
46
import org.gvsig.raster.util.RasterToolsUtil;
47
import org.gvsig.raster.util.RasterUtilities;
48

  
49
import com.iver.andami.PluginServices;
50
/**
51
 * Clase donde se hara todo el proceso de aplicar una lista de filtros a una
52
 * capa. Muestra una ventana de dialogo de incremento informativa.
53
 *
54
 * @version 24/05/2007
55
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
56
 */
57
public class FilterProcess extends RasterProcess {
58
	private String            filename         = "";
59
	private IRasterDataSource rasterDataSource = null;
60
	private ArrayList         listFilterUsed   = null;
61

  
62
	private RasterFilterList  rasterFilterList = null;
63
	private GeoRasterWriter   geoRasterWriter  = null;
64
	private IRasterRendering  rendering        = null;
65

  
66
	/*
67
	 * (non-Javadoc)
68
	 * @see org.gvsig.rastertools.RasterProcess#init()
69
	 */
70
	public void init() {
71
		rendering = (IRasterRendering) getParam("rendering");
72
		filename = getStringParam("filename");
73
		rasterDataSource = (IRasterDataSource) getParam("rasterdatasource");
74
		listFilterUsed = (ArrayList) getParam("listfilterused");
75
	}
76

  
77
	/**
78
	 * 
79
	 * @param geoRasterWriter
80
	 */
81
	private DatasetColorInterpretation getColorIntepretation(GeoRasterWriter geoRasterWriter, IBuffer buffer, Grid grid) {
82
		
83
		DatasetColorInterpretation colorInterpretation = null;
84
		
85
		do {
86
			// Si tiene una tabla de color asignamos las tres bandas
87
			if (grid.getFilterList().isActive("colortable")) {
88
				colorInterpretation = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.RED_BAND, DatasetColorInterpretation.GREEN_BAND, DatasetColorInterpretation.BLUE_BAND });
89
				break;
90
			}
91

  
92
			// Si el numero de bandas coincide asignamos la misma interpretacion que tenia antes
93
			if (buffer.getBandCount() == rasterDataSource.getBandCount()) {
94
				colorInterpretation = rendering.getRender().getColorInterpretation();
95
				break;
96
			}
97

  
98
			String[] colorInterp = new String[rasterDataSource.getColorInterpretation(0).getValues().length];
99
			
100
			for (int i = 0; i<rasterDataSource.getColorInterpretation(0).getValues().length; i++) {
101
				if (rasterDataSource.getColorInterpretation(0).getValues()[i].equals(DatasetColorInterpretation.UNDEF_BAND)) {
102
					colorInterp[i] = DatasetColorInterpretation.GRAY_BAND;
103
					continue;
104
				}
105
				colorInterp[i] = rasterDataSource.getColorInterpretation(0).getValues()[i];
106
			}
107
			colorInterpretation = new DatasetColorInterpretation(colorInterp);
108
		} while (false);
109

  
110
		return colorInterpretation;
111
	}
112

  
113
	/*
114
	 * (non-Javadoc)
115
	 * @see org.gvsig.rastertools.RasterProcess#process()
116
	 */
117
	public void process() throws InterruptedException {
118
		WriterBufferServer writerBufferServer = null;
119

  
120
		IRasterDataSource dsetCopy = null;
121
		try {
122
			insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
123
			dsetCopy = rasterDataSource.newDataset();
124
			BufferFactory bufferFactory = new BufferFactory(dsetCopy);
125
			if (!RasterBuffer.loadInMemory(dsetCopy))
126
				bufferFactory.setReadOnly(true);
127
			bufferFactory.setAllDrawableBands();
128

  
129
			IBuffer buffer = null;
130

  
131
			writerBufferServer = new WriterBufferServer();
132

  
133
			bufferFactory.setAreaOfInterest();
134

  
135
			Grid grid = new Grid(bufferFactory, true);
136

  
137
			//Obtenemos la lista de filtros
138
			rasterFilterList = grid.getFilterList();
139
			
140
			//Aplicamos los filtros usados en el panel
141
			addSelectedFilters(rasterFilterList, listFilterUsed);
142
			
143
			insertLineLog(RasterToolsUtil.getText(this, "aplicando_filtros"));
144

  
145
			grid.setNoDataValue(rasterDataSource.getNoDataValue(0));
146

  
147
			//Asignamos el n?mero de banda alpha. Si no tiene asignar? -1 y no se usar?
148
			grid.getFilterList().addEnvParam("alphaBandNumber", new Integer(rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber()));
149
			
150
			grid.applyFilters();
151
			
152
			GridTransparency transparency = (GridTransparency) grid.getFilterList().getEnv().get("Transparency");
153

  
154
			insertLineLog(RasterToolsUtil.getText(this, "guardando_capa"));
155

  
156
			buffer = grid.getRasterBuf();
157

  
158
			writerBufferServer.setBuffer(buffer, -1);
159
			// TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
160
			
161
			//En el caso de que la imagen no tuviera una banda alpha creamos una y la asignamos en el WriteBufferServer
162
			if (rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber() < 0 && transparency.getAlphaBand() != null) {
163
				writerBufferServer.setAlphaBuffer(transparency.getAlphaBand());
164
				geoRasterWriter = GeoRasterWriter.getWriter(writerBufferServer, filename, buffer.getBandCount() + 1, rasterDataSource.getAffineTransform(), buffer.getWidth(), buffer.getHeight(), buffer.getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
165
			} else //Si ya tiene una banda de transparencia se seguir? usando la que ten?a
166
				geoRasterWriter = GeoRasterWriter.getWriter(writerBufferServer, filename, buffer.getBandCount(), rasterDataSource.getAffineTransform(), buffer.getWidth(), buffer.getHeight(), buffer.getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
167
			
168
			//Asignamos la interpretaci?n de color al escritor
169
			DatasetColorInterpretation colorInterpretation = getColorIntepretation(geoRasterWriter, buffer, grid);
170
			if (transparency.isTransparencyActive()) {
171
				DatasetColorInterpretation alphaI;
172
				alphaI = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.ALPHA_BAND });
173
				colorInterpretation.addColorInterpretation(alphaI);
174
			}
175

  
176
			geoRasterWriter.setColorBandsInterpretation(colorInterpretation.getValues());
177

  
178
			geoRasterWriter.dataWrite();
179
			geoRasterWriter.writeClose();
180
			
181
			// Guardamos en el RMF del fichero el valor NoData
182
			if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
183
				String filenameRMF = RasterUtilities.getNameWithoutExtension(filename) + ".rmf";
184
				RmfBlocksManager manager = dsetCopy.getDataset(0)[0].getRmfBlocksManager();
185
				NoDataRmfSerializer ser;
186
				ser = new NoDataRmfSerializer(Double.valueOf(rasterDataSource.getNoDataValue(0)));
187
	
188
				manager.setPath(filenameRMF);
189
	
190
				if (!manager.checkRmf())
191
					return;
192
	
193
				manager.addClient(ser);
194
				try {
195
					manager.write(true);
196
				} catch (FileNotFoundException e) {
197
					RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
198
				} catch (IOException e) {
199
					RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
200
				}
201
				manager.removeClient(ser.getClass());
202
			}
203
			
204
			externalActions.end(filename);
205

  
206
		} catch (NotSupportedExtensionException e) {
207
			RasterToolsUtil.messageBoxError("error_writer_notsupportedextension", this, e);
208
		} catch (RasterDriverException e) {
209
			RasterToolsUtil.messageBoxError("error_writer", this, e);
210
		} catch (IOException e) {
211
			RasterToolsUtil.messageBoxError("error_writer", this, e);
212
		} catch (FilterTypeException e) {
213
			RasterToolsUtil.messageBoxError("error_adding_filters", this, e);
214
		}
215
	}
216

  
217
	/**
218
	 * Sustituye la lista de filtros de filterList por la que le pasamos en forma
219
	 * de ArrayList
220
	 * @param filterList
221
	 * @param listFilterUsed
222
	 * @throws FilterTypeException 
223
	 */
224
	public static void addSelectedFilters(RasterFilterList filterList, ArrayList listFilterUsed) throws FilterTypeException {
225
		filterList.clear();
226
		RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
227

  
228
		for (int i = 0; i < listFilterUsed.size(); i++) {
229
			ParamStruct aux = (ParamStruct) listFilterUsed.get(i);
230
			IRasterFilterListManager filterManager = stackManager.getManagerByFilterClass(aux.getFilterClass());
231
			filterManager.addFilter(aux.getFilterClass(), aux.getFilterParam());
232
		}
233

  
234
		filterList.resetPercent();
235
	}
236

  
237
	/*
238
	 * (non-Javadoc)
239
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
240
	 */
241
	public int getPercent() {
242
		if (rasterFilterList == null)
243
			return 0;
244

  
245
		if (rasterFilterList.getPercent() < 100)
246
			return rasterFilterList.getPercent();
247

  
248
		if (geoRasterWriter == null)
249
			return 0;
250

  
251
		return geoRasterWriter.getPercent();
252
	}
253

  
254
	/*
255
	 * (non-Javadoc)
256
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
257
	 */
258
	public String getTitle() {
259
		return PluginServices.getText(this, "aplicando_filtros");
260
	}
261
}
0 262

  
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/saveas/SaveAsTocMenuEntry.java
46 46
import org.gvsig.raster.hierarchy.IRasterOperations;
47 47
import org.gvsig.raster.util.ExtendedFileFilter;
48 48
import org.gvsig.raster.util.RasterToolsUtil;
49
import org.gvsig.rastertools.clipping.ClippingProcess;
49
import org.gvsig.raster.util.process.ClippingProcess;
50 50

  
51 51
import com.iver.andami.PluginServices;
52 52
import com.iver.andami.ui.mdiManager.IWindow;
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/filter/FilterProcess.java
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.filter;
20

  
21
import java.io.FileNotFoundException;
22
import java.io.IOException;
23
import java.util.ArrayList;
24

  
25
import org.gvsig.raster.Configuration;
26
import org.gvsig.raster.RasterProcess;
27
import org.gvsig.raster.beans.previewbase.ParamStruct;
28
import org.gvsig.raster.buffer.BufferFactory;
29
import org.gvsig.raster.buffer.RasterBuffer;
30
import org.gvsig.raster.buffer.WriterBufferServer;
31
import org.gvsig.raster.dataset.GeoRasterWriter;
32
import org.gvsig.raster.dataset.IBuffer;
33
import org.gvsig.raster.dataset.IRasterDataSource;
34
import org.gvsig.raster.dataset.NotSupportedExtensionException;
35
import org.gvsig.raster.dataset.io.RasterDriverException;
36
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
37
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
38
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
39
import org.gvsig.raster.grid.Grid;
40
import org.gvsig.raster.grid.GridTransparency;
41
import org.gvsig.raster.grid.filter.FilterTypeException;
42
import org.gvsig.raster.grid.filter.IRasterFilterListManager;
43
import org.gvsig.raster.grid.filter.RasterFilterList;
44
import org.gvsig.raster.grid.filter.RasterFilterListManager;
45
import org.gvsig.raster.hierarchy.IRasterRendering;
46
import org.gvsig.raster.util.RasterToolsUtil;
47
import org.gvsig.raster.util.RasterUtilities;
48

  
49
import com.iver.andami.PluginServices;
50
/**
51
 * Clase donde se hara todo el proceso de aplicar un filtro a una capa. Muestra
52
 * una ventana de dialogo de incremento informativa.
53
 *
54
 * @version 24/05/2007
55
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
56
 */
57
public class FilterProcess extends RasterProcess {
58
	private String            filename         = "";
59
	private IRasterDataSource rasterDataSource = null;
60
	private ArrayList         listFilterUsed   = null;
61

  
62
	private RasterFilterList  rasterFilterList = null;
63
	private GeoRasterWriter   geoRasterWriter  = null;
64
	private IRasterRendering  rendering        = null;
65

  
66
	/*
67
	 * (non-Javadoc)
68
	 * @see org.gvsig.rastertools.RasterProcess#init()
69
	 */
70
	public void init() {
71
		rendering = (IRasterRendering) getParam("rendering");
72
		filename = getStringParam("filename");
73
		rasterDataSource = (IRasterDataSource) getParam("rasterdatasource");
74
		listFilterUsed = (ArrayList) getParam("listfilterused");
75
	}
76

  
77
	/**
78
	 * 
79
	 * @param geoRasterWriter
80
	 */
81
	private DatasetColorInterpretation getColorIntepretation(GeoRasterWriter geoRasterWriter, IBuffer buffer, Grid grid) {
82
		
83
		DatasetColorInterpretation colorInterpretation = null;
84
		
85
		do {
86
			// Si tiene una tabla de color asignamos las tres bandas
87
			if (grid.getFilterList().isActive("colortable")) {
88
				colorInterpretation = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.RED_BAND, DatasetColorInterpretation.GREEN_BAND, DatasetColorInterpretation.BLUE_BAND });
89
				break;
90
			}
91

  
92
			// Si el numero de bandas coincide asignamos la misma interpretacion que tenia antes
93
			if (buffer.getBandCount() == rasterDataSource.getBandCount()) {
94
				colorInterpretation = rendering.getRender().getColorInterpretation();
95
				break;
96
			}
97

  
98
			String[] colorInterp = new String[rasterDataSource.getColorInterpretation(0).getValues().length];
99
			
100
			for (int i = 0; i<rasterDataSource.getColorInterpretation(0).getValues().length; i++) {
101
				if (rasterDataSource.getColorInterpretation(0).getValues()[i].equals(DatasetColorInterpretation.UNDEF_BAND)) {
102
					colorInterp[i] = DatasetColorInterpretation.GRAY_BAND;
103
					continue;
104
				}
105
				colorInterp[i] = rasterDataSource.getColorInterpretation(0).getValues()[i];
106
			}
107
			colorInterpretation = new DatasetColorInterpretation(colorInterp);
108
		} while (false);
109

  
110
		return colorInterpretation;
111
	}
112

  
113
	/*
114
	 * (non-Javadoc)
115
	 * @see org.gvsig.rastertools.RasterProcess#process()
116
	 */
117
	public void process() throws InterruptedException {
118
		WriterBufferServer writerBufferServer = null;
119

  
120
		IRasterDataSource dsetCopy = null;
121
		try {
122
			insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
123
			dsetCopy = rasterDataSource.newDataset();
124
			BufferFactory bufferFactory = new BufferFactory(dsetCopy);
125
			if (!RasterBuffer.loadInMemory(dsetCopy))
126
				bufferFactory.setReadOnly(true);
127
			bufferFactory.setAllDrawableBands();
128

  
129
			IBuffer buffer = null;
130

  
131
			writerBufferServer = new WriterBufferServer();
132

  
133
			bufferFactory.setAreaOfInterest();
134

  
135
			Grid grid = new Grid(bufferFactory, true);
136

  
137
			//Obtenemos la lista de filtros
138
			rasterFilterList = grid.getFilterList();
139
			
140
			//Aplicamos los filtros usados en el panel
141
			addSelectedFilters(rasterFilterList, listFilterUsed);
142
			
143
			insertLineLog(RasterToolsUtil.getText(this, "aplicando_filtros"));
144

  
145
			grid.setNoDataValue(rasterDataSource.getNoDataValue(0));
146

  
147
			//Asignamos el n?mero de banda alpha. Si no tiene asignar? -1 y no se usar?
148
			grid.getFilterList().addEnvParam("alphaBandNumber", new Integer(rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber()));
149
			
150
			grid.applyFilters();
151
			
152
			GridTransparency transparency = (GridTransparency) grid.getFilterList().getEnv().get("Transparency");
153

  
154
			insertLineLog(RasterToolsUtil.getText(this, "guardando_capa"));
155

  
156
			buffer = grid.getRasterBuf();
157

  
158
			writerBufferServer.setBuffer(buffer, -1);
159
			// TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
160
			
161
			//En el caso de que la imagen no tuviera una banda alpha creamos una y la asignamos en el WriteBufferServer
162
			if (rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber() < 0 && transparency.getAlphaBand() != null) {
163
				writerBufferServer.setAlphaBuffer(transparency.getAlphaBand());
164
				geoRasterWriter = GeoRasterWriter.getWriter(writerBufferServer, filename, buffer.getBandCount() + 1, rasterDataSource.getAffineTransform(), buffer.getWidth(), buffer.getHeight(), buffer.getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
165
			} else //Si ya tiene una banda de transparencia se seguir? usando la que ten?a
166
				geoRasterWriter = GeoRasterWriter.getWriter(writerBufferServer, filename, buffer.getBandCount(), rasterDataSource.getAffineTransform(), buffer.getWidth(), buffer.getHeight(), buffer.getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
167
			
168
			//Asignamos la interpretaci?n de color al escritor
169
			DatasetColorInterpretation colorInterpretation = getColorIntepretation(geoRasterWriter, buffer, grid);
170
			if (transparency.isTransparencyActive()) {
171
				DatasetColorInterpretation alphaI;
172
				alphaI = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.ALPHA_BAND });
173
				colorInterpretation.addColorInterpretation(alphaI);
174
			}
175

  
176
			geoRasterWriter.setColorBandsInterpretation(colorInterpretation.getValues());
177

  
178
			geoRasterWriter.dataWrite();
179
			geoRasterWriter.writeClose();
180
			
181
			// Guardamos en el RMF del fichero el valor NoData
182
			if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
183
				String filenameRMF = RasterUtilities.getNameWithoutExtension(filename) + ".rmf";
184
				RmfBlocksManager manager = dsetCopy.getDataset(0)[0].getRmfBlocksManager();
185
				NoDataRmfSerializer ser;
186
				ser = new NoDataRmfSerializer(Double.valueOf(rasterDataSource.getNoDataValue(0)));
187
	
188
				manager.setPath(filenameRMF);
189
	
190
				if (!manager.checkRmf())
191
					return;
192
	
193
				manager.addClient(ser);
194
				try {
195
					manager.write(true);
196
				} catch (FileNotFoundException e) {
197
					RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
198
				} catch (IOException e) {
199
					RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
200
				}
201
				manager.removeClient(ser.getClass());
202
			}
203
			
204
			externalActions.end(filename);
205

  
206
		} catch (NotSupportedExtensionException e) {
207
			RasterToolsUtil.messageBoxError("error_writer_notsupportedextension", this, e);
208
		} catch (RasterDriverException e) {
209
			RasterToolsUtil.messageBoxError("error_writer", this, e);
210
		} catch (IOException e) {
211
			RasterToolsUtil.messageBoxError("error_writer", this, e);
212
		} catch (FilterTypeException e) {
213
			RasterToolsUtil.messageBoxError("error_adding_filters", this, e);
214
		}
215
	}
216

  
217
	/**
218
	 * Sustituye la lista de filtros de filterList por la que le pasamos en forma
219
	 * de ArrayList
220
	 * @param filterList
221
	 * @param listFilterUsed
222
	 * @throws FilterTypeException 
223
	 */
224
	public static void addSelectedFilters(RasterFilterList filterList, ArrayList listFilterUsed) throws FilterTypeException {
225
		filterList.clear();
226
		RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
227

  
228
		for (int i = 0; i < listFilterUsed.size(); i++) {
229
			ParamStruct aux = (ParamStruct) listFilterUsed.get(i);
230
			IRasterFilterListManager filterManager = stackManager.getManagerByFilterClass(aux.getFilterClass());
231
			filterManager.addFilter(aux.getFilterClass(), aux.getFilterParam());
232
		}
233

  
234
		filterList.resetPercent();
235
	}
236

  
237
	/*
238
	 * (non-Javadoc)
239
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
240
	 */
241
	public int getPercent() {
242
		if (rasterFilterList == null)
243
			return 0;
244

  
245
		if (rasterFilterList.getPercent() < 100)
246
			return rasterFilterList.getPercent();
247

  
248
		if (geoRasterWriter == null)
249
			return 0;
250

  
251
		return geoRasterWriter.getPercent();
252
	}
253

  
254
	/*
255
	 * (non-Javadoc)
256
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
257
	 */
258
	public String getTitle() {
259
		return PluginServices.getText(this, "aplicando_filtros");
260
	}
261
}
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/filter/FilterListener.java
50 50
import org.gvsig.raster.hierarchy.IRasterRendering;
51 51
import org.gvsig.raster.util.RasterNotLoadException;
52 52
import org.gvsig.raster.util.RasterToolsUtil;
53
import org.gvsig.raster.util.process.FilterProcess;
53 54
import org.gvsig.rastertools.filter.ui.FilterPanel;
54 55

  
55 56
import com.iver.andami.PluginServices;
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/enhanced/ui/EnhancedListener.java
33 33
import org.gvsig.raster.beans.canvas.layers.GraphicHistogram;
34 34
import org.gvsig.raster.beans.canvas.layers.functions.DensitySlicingLine;
35 35
import org.gvsig.raster.beans.previewbase.PreviewBasePanel;
36
import org.gvsig.raster.beans.previewbase.PreviewFiltering;
37 36
import org.gvsig.raster.dataset.IRasterDataSource;
38 37
import org.gvsig.raster.dataset.Params;
39 38
import org.gvsig.raster.grid.filter.FilterTypeException;
......
41 40
import org.gvsig.raster.hierarchy.IRasterRendering;
42 41
import org.gvsig.raster.util.RasterNotLoadException;
43 42
import org.gvsig.raster.util.RasterToolsUtil;
43
import org.gvsig.raster.util.process.FilterProcess;
44 44
import org.gvsig.rastertools.enhanced.graphics.HistogramGraphicBase;
45
import org.gvsig.rastertools.filter.FilterProcess;
46 45

  
47 46
import com.iver.andami.PluginServices;
48 47
/**
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/enhanced/ui/EnhancedDialog.java
28 28

  
29 29
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
30 30
import org.gvsig.raster.beans.previewbase.PreviewBasePanel;
31
import org.gvsig.raster.beans.previewbase.PreviewFiltering;
32 31
import org.gvsig.rastertools.filter.ui.NewOrSaveLayerPanel;
33 32

  
34 33
import com.iver.andami.PluginServices;
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/enhanced/ui/PreviewFiltering.java
1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2007 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.enhanced.ui;
20

  
21
import java.util.ArrayList;
22

  
23
import org.gvsig.raster.beans.previewbase.IPreviewRenderProcess;
24
import org.gvsig.raster.beans.previewbase.ParamStruct;
25
import org.gvsig.raster.dataset.Params;
26
import org.gvsig.raster.grid.filter.FilterTypeException;
27
import org.gvsig.raster.grid.filter.IRasterFilterListManager;
28
import org.gvsig.raster.grid.filter.RasterFilter;
29
import org.gvsig.raster.grid.filter.RasterFilterList;
30
import org.gvsig.raster.grid.filter.RasterFilterListManager;
31
import org.gvsig.raster.hierarchy.IRasterRendering;
32
import org.gvsig.raster.util.RasterToolsUtil;
33

  
34
import com.iver.andami.PluginServices;
35
/**
36
 * Procesado de la imagen para la previsualizaci?n. Para poder usar esta clase despu?s de instanciarla
37
 * habr? que asignarle un valor a showFiltersSelected aunque por defecto est? a true por lo que se
38
 * visualizaran los cambios sin problemas, asigna una lista de filtros inicial (que ya tenga el raster
39
 * aplicado) con setFilterStatus y asignar los filtros que queramos aplicar con addNewParam (una llamada
40
 * por cada filtro).
41
 * 
42
 * 19/02/2008
43
 * @author Nacho Brodin nachobrodin@gmail.com
44
 */
45
public class PreviewFiltering implements IPreviewRenderProcess {
46

  
47
	private boolean          showFiltersSelected     = true;
48
	private ArrayList        paramsList              = new ArrayList();
49
	private ArrayList        filtersInit             = new ArrayList();
50
	
51
	/**
52
	 * Flag de selecci?n de activaci?n y desactivaci?n
53
	 * @param show
54
	 */
55
	public void showFiltersSelected(boolean show) {
56
		this.showFiltersSelected = show;
57
	}
58
	
59
	/**
60
	 * Obtiene la lista de par?metros
61
	 * @return the paramsList
62
	 */
63
	public ArrayList getParamsList() {
64
		return paramsList;
65
	}
66
	
67
	/**
68
	 * Asigna la lista de par?metros
69
	 * @param params
70
	 */
71
	public void setParamsList(ArrayList params) {
72
		this.paramsList = params;
73
	}
74
	
75
	/**
76
	 * Asigna el arrayList de filtros inicial. Esto hace que aplique los filtros que ya
77
	 * existen en el raster. Estos pueden ser obtenidos del render de la capa de la forma
78
	 * lyr.getRender().getFilterList().getStatusCloned().  
79
	 * @param params Lista de filtros aplicados.
80
	 */
81
	public void setFilterStatus(ArrayList filtersInit) {
82
		this.filtersInit = filtersInit;
83
	}
84
	
85
	/**
86
	 * Devuelve el arrayList de filtros inicial
87
	 * @return
88
	 */
89
	public ArrayList getFilterStatus() {
90
		return filtersInit;
91
	}
92
	
93
	/**
94
	 * A?adir un nuevo Params a la lista de Params que podemos manejar. Un Params
95
	 * equivale a un filtro cargado. El hecho de trabajar con Params y no con
96
	 * filtros, simplifica totalmente el panel. Sin tener que depender de los
97
	 * filtros nada m?s que para el momento de dibujado o guardado.
98
	 * @param name
99
	 * @param params
100
	 * @param classFilter
101
	 */
102
	public void addNewParam(String name, Params params, Class classFilter) {
103
		ParamStruct param = new ParamStruct();
104
		param.setFilterName(name);
105
		param.setFilterParam(params);
106
		param.setFilterClass(classFilter);
107
		paramsList.add(param);
108
	}
109

  
110
	/**
111
	 * Procesa la imagen con la lista de filtros si el flag showFilterSelected est? a true.
112
	 * Esta funci?n llama a addFilter por cada filtro a?adido pero es applyFilters la encargada
113
	 * de construir la lista. 
114
	 */
115
	public void process(IRasterRendering rendering) throws FilterTypeException {
116
		rendering.getRenderFilterList().clear();
117

  
118
		if (showFiltersSelected) {
119
			RasterFilterList filterList = rendering.getRenderFilterList();
120
			RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
121

  
122
			ArrayList listFilterUsed = applyFilters(rendering);
123
			ArrayList exc = new ArrayList();
124
			for (int i = 0; i < listFilterUsed.size(); i++) {
125
				IRasterFilterListManager filterManager = stackManager.getManagerByFilterClass(((ParamStruct) listFilterUsed.get(i)).getFilterClass());
126
				try {
127
					filterManager.addFilter(((ParamStruct) listFilterUsed.get(i)).getFilterClass(), ((ParamStruct) listFilterUsed.get(i)).getFilterParam());
128
				} catch (FilterTypeException e) {
129
					exc.add(e);
130
				}
131
			}
132
			if(exc.size() != 0) {
133
				RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_adding_filters"), this, exc);
134
				exc.clear();
135
			}
136
		}
137
	}
138
	
139
	/**
140
	 * Aqui se seleccionan que filtros se van a aplicar y se devuelven en forma
141
	 * de ArrayList tanto para el dibujado como cuando aceptan o aplican el panel.
142
	 * @param rendering
143
	 * @return
144
	 */
145
	public ArrayList applyFilters(IRasterRendering rendering) {
146
		ArrayList listFilterUsed = new ArrayList();
147

  
148
		RasterFilterList filterList = new RasterFilterList();
149
		filterList.setEnv(rendering.getRenderFilterList().getEnv());
150
		RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
151

  
152
		if(filtersInit == null)
153
			return listFilterUsed;
154
		
155
		// Conservamos filtros ya existentes
156
		for (int i = 0; i < filtersInit.size(); i++) {
157
			
158
			RasterFilter obj = null;
159
			for (int j = 0; j < stackManager.getRasterFilterList().size(); j++) {
160
				Class classFilter = (Class) stackManager.getRasterFilterList().get(j);
161
				try {
162
					obj = (RasterFilter) classFilter.newInstance();
163
					if (obj.getName().equals(((RasterFilter) filtersInit.get(i)).getName()))
164
						break;
165
				} catch (InstantiationException e) {
166
					RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
167
				} catch (IllegalAccessException e) {
168
					RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
169
				}
170
			}
171

  
172
			// Si no encontramos el filtro apropiado, nos olvidamos de el
173
			if (obj == null)
174
				continue;
175

  
176
			// Si no es visible tenemos que conservar el filtro
177
			try {
178
				Params params = (Params) ((RasterFilter) filtersInit.get(i)).getUIParams(((RasterFilter) filtersInit.get(i)).getName()).clone();
179
				// A?ado el parametro RenderBands a los parametros del filtro
180
				String rgb = rendering.getRenderBands()[0] + " " + rendering.getRenderBands()[1] + " " + rendering.getRenderBands()[2];
181
				params.setParam("RenderBands", rgb, 0, null);
182
			
183
				ParamStruct newParam = new ParamStruct();
184
				newParam.setFilterClass(obj.getClass());
185
				newParam.setFilterName(((RasterFilter) filtersInit.get(i)).getName());
186
				newParam.setFilterParam(params);
187
				listFilterUsed.add(newParam);
188
			} catch (CloneNotSupportedException e) {
189
			}
190
		}
191
		
192
		// Metemos los filtros seleccionados en listFilterUsed
193
		for (int i = 0; i < paramsList.size(); i++) {
194
			// En caso de existir el filtro, lo reemplazamos
195
			boolean finded = false;
196
			for (int j = 0; j < listFilterUsed.size(); j++) {
197
				if (((ParamStruct) listFilterUsed.get(j)).getFilterName().equals(((ParamStruct) paramsList.get(i)).getFilterName())) {
198
					listFilterUsed.set(j, paramsList.get(i));
199
					finded = true;
200
					break;
201
				}
202
			}
203
			if (!finded)
204
				listFilterUsed.add(paramsList.get(i));
205
		}
206
		
207
		return listFilterUsed;
208
	}
209
}
trunk/extensions/extRasterTools-SE/src/org/gvsig/rastertools/clipping/ClippingProcess.java
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.clipping;
20

  
21
import java.awt.geom.AffineTransform;
22
import java.io.File;
23
import java.io.FileNotFoundException;
24
import java.io.IOException;
25

  
26
import org.apache.log4j.Logger;
27
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
28
import org.gvsig.raster.Configuration;
29
import org.gvsig.raster.RasterProcess;
30
import org.gvsig.raster.buffer.BufferFactory;
31
import org.gvsig.raster.buffer.BufferInterpolation;
32
import org.gvsig.raster.buffer.RasterBuffer;
33
import org.gvsig.raster.buffer.WriterBufferServer;
34
import org.gvsig.raster.dataset.GeoRasterWriter;
35
import org.gvsig.raster.dataset.IBuffer;
36
import org.gvsig.raster.dataset.IRasterDataSource;
37
import org.gvsig.raster.dataset.InvalidSetViewException;
38
import org.gvsig.raster.dataset.NotSupportedExtensionException;
39
import org.gvsig.raster.dataset.Params;
40
import org.gvsig.raster.dataset.RasterDataset;
41
import org.gvsig.raster.dataset.io.RasterDriverException;
42
import org.gvsig.raster.dataset.io.rmf.RmfBlocksManager;
43
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
44
import org.gvsig.raster.datastruct.ColorTable;
45
import org.gvsig.raster.datastruct.serializer.ColorTableRmfSerializer;
46
import org.gvsig.raster.datastruct.serializer.NoDataRmfSerializer;
47
import org.gvsig.raster.grid.GridPalette;
48
import org.gvsig.raster.grid.filter.RasterFilterList;
49
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
50
import org.gvsig.raster.util.RasterNotLoadException;
51
import org.gvsig.raster.util.RasterToolsUtil;
52
import org.gvsig.raster.util.RasterUtilities;
53
/**
54
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
55
 * para calcular el recorte de una capa.
56
 *
57
 * @version 24/04/2007
58
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
59
 */
60
public class ClippingProcess extends RasterProcess {
61
	private String                        fileName            = "";
62
	private WriterBufferServer            writerBufferServer  = null;
63
	private FLyrRasterSE                  rasterSE            = null;
64
	private AffineTransform               affineTransform     = new AffineTransform();
65
	private boolean                       oneLayerPerBand     = false;
66
	private int[]                         drawableBands       = { 0, 1, 2 };
67
	private int[]                         dValues             = null;
68
	private GeoRasterWriter               grw                 = null;
69
	private int                           interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined;
70
	private String                        viewName            = "";
71
	private Params                        params              = null;
72
	private DatasetColorInterpretation    colorInterp         = null;
73

  
74
	/**
75
	 * Variables de la resoluci?n de salida
76
	 */
77
	private int                           resolutionWidth     = 0;
78
	private int                           resolutionHeight    = 0;
79
	
80
	private IBuffer                       buffer              = null;
81

  
82
	/**
83
	 * Par?metros obligatorios al proceso:
84
	 * <UL>
85
	 * <LI>filename: Nombre del fichero de salida</LI>
86
	 * <LI>datawriter: Escritor de datos</LI>
87
	 * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
88
	 * <LI>pixelcoordinates: Coordenadas pixel del recorte</LI>
89
	 * <LI>layer: Capa de entrada para el recorte</LI>
90
	 * <LI>drawablebands: Bandas de entrada</LI>
91
	 * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
92
	 * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
93
	 * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
94
	 * <LI>resolution: Ancho y alto de la capa de salida</LI>
95
	 * </UL> 
96
	 */
97
	public void init() {
98
		fileName = getStringParam("filename");
99
		writerBufferServer = (WriterBufferServer) getParam("datawriter");
100
		viewName = getStringParam("viewname");
101
		dValues = getIntArrayParam("pixelcoordinates");
102
		rasterSE = getLayerParam("layer");
103
		drawableBands = getIntArrayParam("drawablebands");
104
		oneLayerPerBand = getBooleanParam("onelayerperband");
105
		interpolationMethod = getIntParam("interpolationmethod");
106
		affineTransform = (AffineTransform)getParam("affinetransform");
107
		colorInterp = (DatasetColorInterpretation)getParam("colorInterpretation");
108
		if(getIntArrayParam("resolution") != null) {
109
			resolutionWidth = getIntArrayParam("resolution")[0];
110
			resolutionHeight = getIntArrayParam("resolution")[1];
111
		}
112
		params = (Params) getParam("driverparams");
113
	}
114

  
115
	/**
116
	 * Salva la tabla de color al fichero rmf.
117
	 * @param fName
118
	 * @throws IOException
119
	 */
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff