Revision 35299

View differences:

tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/ConfigurationListener.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;
20

  
21
import java.util.EventListener;
22

  
23
public interface ConfigurationListener extends EventListener {
24
	/**
25
	 * Evento que se dispara cuando cambia un valor de configuracion.
26
	 * @param e
27
	 */
28
	public void actionConfigurationChanged(ConfigurationEvent e);
29
}
tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/util/Queue.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.util;
20

  
21
/*
22
 * Created on 10-mar-2006
23
 *
24
 * gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
25
 *
26
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
27
 *
28
 * This program is free software; you can redistribute it and/or
29
 * modify it under the terms of the GNU General Public License
30
 * as published by the Free Software Foundation; either version 2
31
 * of the License, or (at your option) any later version.
32
 *
33
 * This program is distributed in the hope that it will be useful,
34
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
35
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36
 * GNU General Public License for more details.
37
 *
38
 * You should have received a copy of the GNU General Public License
39
 * along with this program; if not, write to the Free Software
40
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
41
 *
42
 * For more information, contact:
43
 */
44

  
45
import java.util.Vector;
46

  
47
/**
48
 * A simple FIFO queue class which causes the calling thread to wait if the
49
 * queue is empty and notifies threads that are waiting when it is not
50
 * empty.
51
 * 
52
 * @author Anil V (akv@eng.sun.com)
53
 */
54
public class Queue {
55
	private Vector vector = new Vector();
56

  
57
	/**
58
	 * Put the object into the queue.
59
	 * 
60
	 * @param object
61
	 *            the object to be appended to the queue.
62
	 */
63
	public synchronized void put(Object object) {
64
		vector.addElement(object);
65
		notify();
66
	}
67

  
68
	/**
69
	 * Pull the first object out of the queue. Wait if the queue is empty.
70
	 */
71
	public synchronized Object pull() {
72
		while (isEmpty())
73
			try {
74
				wait();
75
			} catch (InterruptedException ex) {
76
			}
77
			return get();
78
	}
79

  
80
	/**
81
	 * Get the first object out of the queue. Return null if the queue is
82
	 * empty.
83
	 */
84
	public synchronized Object get() {
85
		Object object = peek();
86
		if (object != null)
87
			vector.removeElementAt(0);
88
		return object;
89
	}
90

  
91
	/**
92
	 * Peek to see if something is available.
93
	 */
94
	public Object peek() {
95
		if (isEmpty())
96
			return null;
97
		return vector.elementAt(0);
98
	}
99

  
100
	/**
101
	 * Is the queue empty?
102
	 */
103
	public boolean isEmpty() {
104
		return vector.isEmpty();
105
	}
106

  
107
	/**
108
	 * How many elements are there in this queue?
109
	 */
110
	public int size() {
111
		return vector.size();
112
	}
113
}
tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/util/ExtendedFileFilter.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;
20

  
21
import java.io.File;
22
import java.util.ArrayList;
23

  
24
import javax.swing.filechooser.FileFilter;
25

  
26
import org.gvsig.andami.PluginServices;
27

  
28
/**
29
 * ExtendedFileFilter es una clase para usarla junto a los JFileChooser.
30
 * Ofrece una funcionalidad simple para poder agregar extensiones de manera
31
 * comoda y rapida. Las descripciones ya las pone con un formato, asi que esto
32
 * es opcional poner una descripci?n especifica.
33
 * 
34
 * Un ejemplo t?pico de como se usaria:
35
 * <pre>
36
 * // Usamos el JFileChooser de libUIComponents
37
 * JFileChooser chooser = new JFileChooser(this.getClass().toString(), (File) null);
38
 * // Desactivamos el modo de ver todos los ficheros
39
 * chooser.setAcceptAllFileFilterUsed(false);
40
 * // Activamos la multiseleccion
41
 * chooser.setMultiSelectionEnabled(true);
42
 * // Nos guardamos cada tipo de fichero en uno que contenga todos
43
 * ExtendedFileFilter allFilters = new ExtendedFileFilter();
44
 * for (int i = 0; i < formats.length; i++) {
45
 *   ExtendedFileFilter fileFilter = new ExtendedFileFilter();
46
 *   fileFilter.addExtension(formats[i]);
47
 *   // Agregamos el filefilter al JFileChooser
48
 *   chooser.addChoosableFileFilter(fileFilter);
49
 *   // Agregamos el mismo filtro a un ExtendedFileFilter global 
50
 *   allFilters.addExtension(formats[i]);
51
 * }
52
 * // Poner una descripcion (OPCIONAL) para todos los ficheros.
53
 * allFilters.setDescription(PluginServices.getText(this, "todos_soportados"));
54
 * // Lo a?adimos
55
 * chooser.addChoosableFileFilter(allFilters);
56
 * // Y lo dejamos seleccionado por defecto
57
 * chooser.setFileFilter(allFilters);
58
 * </pre>
59
 * 
60
 * @version 21/11/2007
61
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
62
 */
63
public class ExtendedFileFilter extends FileFilter {
64
	String description = null;
65

  
66
	ArrayList extensions = new ArrayList();
67

  
68
	/**
69
	 * Constructor de un ExtendedFileFilter
70
	 */
71
	public ExtendedFileFilter() {
72
	}
73

  
74
	/**
75
	 * Construye un ExtendedFileFilter con una extensi?n ya agregada
76
	 * @param extension
77
	 */
78
	public ExtendedFileFilter(String extension) {
79
		addExtension(extension);
80
	}
81

  
82
	/**
83
	 * A?ade una extensi?n a la lista de extensiones soportadas
84
	 * @param extension
85
	 */
86
	public void addExtension(String extension) {
87
		if (extension == null)
88
			return;
89

  
90
		extensions.add(extension);
91
	}
92

  
93
	/*
94
	 * (non-Javadoc)
95
	 * @see javax.swing.filechooser.FileFilter#accept(java.io.File)
96
	 */
97
	public boolean accept(File f) {
98
		if (f.isDirectory())
99
			return true;
100

  
101
		String s = f.getName();
102
		int i = s.lastIndexOf('.');
103

  
104
		if (i > 0 && i < s.length() - 1) {
105
			String extension = s.substring(i + 1).toLowerCase();
106
			for (int j = 0; j < extensions.size(); j++) {
107
				if (extensions.get(j).toString().toLowerCase().equals(extension))
108
					return true;
109
			}
110
		}
111

  
112
		return false;
113
	}
114

  
115
	/**
116
	 * Normaliza el nombre de un fichero, a?adiendo la extension si fuera
117
	 * necesario
118
	 * @param file
119
	 * @return
120
	 */
121
	public String getNormalizedFilename(File file) {
122
		String s = file.getName();
123
		int i = s.lastIndexOf('.');
124

  
125
		if (i > 0 && i < s.length() - 1) {
126
			String extension = s.substring(i + 1).toLowerCase();
127
			for (int j = 0; j < extensions.size(); j++) {
128
				if (extensions.get(j).toString().toLowerCase().equals(extension))
129
					return file.toString();
130
			}
131
		}
132

  
133
		return file.toString() + "." + extensions.get(0).toString().toLowerCase();
134
	}
135

  
136
	/*
137
	 * (non-Javadoc)
138
	 * @see javax.swing.filechooser.FileFilter#getDescription()
139
	 */
140
	public String getDescription() {
141
		String format1 = "";
142
		String format2 = "";
143
		for (int j = 0; j < extensions.size(); j++) {
144
			if (format1.length() != 0) {
145
				format1 = format1 + ", ";
146
				format2 = format2 + "; ";
147
			}
148
			// Files JPG, GIF, ... (*.jpg; *.gif ...)
149
			if (j >= 4) {
150
				format1 = "...";
151
				format2 = "...";
152
				break;
153
			}
154
			format1 = format1 + extensions.get(j).toString().toUpperCase();
155
			format2 = format2 + "*." + extensions.get(j).toString().toLowerCase();
156
		}
157
		if (description == null)
158
			return PluginServices.getText(this, "files") + " " + format1 + " (" + format2 + ")";
159

  
160
		return description + " (" + format2 + ")";
161
	}
162

  
163
	/**
164
	 * Especifica la descripcion del item
165
	 * @param description the description to set
166
	 */
167
	public void setDescription(String description) {
168
		this.description = description;
169
	}
170

  
171
	/**
172
	 * Borra una extension de la lista de extensiones
173
	 * @param extension
174
	 */
175
	public void removeExtension(String extension){
176
		extensions.remove(extension);
177
 }
178

  
179
	/**
180
	 * Borra todas las extensiones existentes
181
	 */
182
	public void clearExtensions(){
183
		extensions.clear();
184
	}
185

  
186
	/**
187
	 * Devuelve una lista con las extensiones disponibles
188
	 * @return
189
	 */
190
	public ArrayList getExtensions(){
191
		return extensions;
192
	}
193
}
tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/util/GenericBasePanel.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.util;
20

  
21
/**
22
 * Clase no abstracta para instanciar un BasePanel generico
23
 * 18/08/2008
24
 * @author Nacho Brodin nachobrodin@gmail.com
25
 */
26
public class GenericBasePanel extends BasePanel {
27
	private static final long serialVersionUID = 1L;
28

  
29
	/*
30
	 * (non-Javadoc)
31
	 * @see org.gvsig.raster.util.BasePanel#init()
32
	 */
33
	protected void init() {
34
	}
35

  
36
	/*
37
	 * (non-Javadoc)
38
	 * @see org.gvsig.raster.util.BasePanel#translate()
39
	 */
40
	protected void translate() {
41
	}	
42
}
tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/util/BasePanel.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;
20

  
21
import java.awt.Component;
22
import java.awt.event.ActionListener;
23
import java.awt.event.KeyListener;
24
import java.awt.event.MouseListener;
25
import java.util.ArrayList;
26

  
27
import javax.swing.AbstractButton;
28
import javax.swing.JPanel;
29

  
30
/**
31
 * Clase base para los paneles gr?ficos. 
32
 * 
33
 * 17/07/2008
34
 * @author Nacho Brodin nachobrodin@gmail.com
35
 */
36
public abstract class BasePanel extends JPanel {
37
	private static final long    serialVersionUID         = -8877600252349334979L;
38
	private boolean	             enableValueChangedEvent  = true;
39
	
40
	public static final int      KEYLISTENER              = 0;
41
	public static final int      ACTIONLISTENER           = 1;
42
	public static final int      MOUSELISTENER            = 2;
43
	
44
	/**
45
	 * Obtiene una instancia de una clase generica que hereda de BasePanel
46
	 * @return BasePanel
47
	 */
48
	public static BasePanel getInstance() {
49
		return new GenericBasePanel();
50
	}
51
	
52
	/**
53
	 * Obtiene la traducci?n de la cadena de texto
54
	 * @param parent Ventana padre
55
	 * @param text Cadena a traducir
56
	 * @return Cadena de texto traducida
57
	 */
58
	public String getText(Object parent, String text) {
59
		return RasterToolsUtil.getText(parent, text);
60
	}
61
	
62
	/**
63
	 * Obtiene la traducci?n de la cadena de texto
64
	 * @param text Cadena a traducir
65
	 * @return Cadena de texto traducida
66
	 */
67
	public String getText(String text) {
68
		return RasterToolsUtil.getText(this, text);
69
	}
70
	
71
	/**
72
	 * Asigna el valor para la activaci?n y desactivaci?n del evento de cambio de valor en
73
	 * las cajas de texto.
74
	 * @param enableValueChangedEvent
75
	 */
76
	public void setEnableValueChangedEvent(boolean enableValueChangedEvent) {
77
		this.enableValueChangedEvent = enableValueChangedEvent;
78
	}
79
	
80
	/**
81
	 * Obtiene el valor para la activaci?n y desactivaci?n del evento de cambio de valor en
82
	 * las cajas de texto.
83
	 * @param enableValueChangedEvent
84
	 */
85
	public boolean isEnableValueChangedEvent() {
86
		return this.enableValueChangedEvent;
87
	}
88
	
89
	/**
90
	 * Obtiene la lista de componentes del panel. Si dentro tiene alg?n BasePanel
91
	 * consulta la lista de componentes de este y la devuelve.
92
	 * @return
93
	 */
94
	public ArrayList getComponentList() {
95
		ArrayList listComp = new ArrayList();
96
		for (int i = 0; i < this.getComponentCount(); i++) {
97
			if(getComponent(i) instanceof BasePanel) {
98
				ArrayList list = ((BasePanel)getComponent(i)).getComponentList();
99
				for (int j = 0; j < list.size(); j++) 
100
					listComp.add(list.get(j));
101
			} else
102
				listComp.add(getComponent(i));
103
		}
104
		return listComp;
105
	}
106
	
107
	/**
108
	 * Registra un listener en todos los componentes contenidos en este panel.
109
	 * @param type Tipo de listener definido por las variables est?ticas en esta clase
110
	 * @param listener Objeto listener del tipo correcto
111
	 */
112
	public void registerListener(int type, Object listener) {
113
		ArrayList listComp = getComponentList();
114
		if(type == KEYLISTENER) {
115
			if(listener instanceof KeyListener) {
116
				for (int i = 0; i < listComp.size(); i++)
117
					if(listComp.get(i) instanceof Component)
118
						((Component)listComp.get(i)).addKeyListener((KeyListener)listener);
119
			}
120
		}
121
		if(type == ACTIONLISTENER) {
122
			if(listener instanceof ActionListener) {
123
				for (int i = 0; i < listComp.size(); i++)
124
					if(listComp.get(i) instanceof AbstractButton)
125
						((AbstractButton)listComp.get(i)).addActionListener((ActionListener)listener);
126
			}
127
		}
128
		if(type == MOUSELISTENER) {
129
			if(listener instanceof MouseListener) {
130
				for (int i = 0; i < listComp.size(); i++)
131
					if(listComp.get(i) instanceof Component)
132
						((Component)listComp.get(i)).addMouseListener((MouseListener)listener);
133
			}
134
		}
135
	}
136
	
137
	/**
138
	 * Traducci?n centralizada de los componentes de una panel
139
	 */
140
	protected abstract void translate();
141
	
142
	/**
143
	 * Acciones de inicializaci?n
144
	 */
145
	protected abstract void init();
146
}
tags/v2_0_0_Build_2026/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.awt.geom.Point2D;
23
import java.io.File;
24
import java.io.IOException;
25
import java.util.ArrayList;
26
import java.util.List;
27

  
28
import org.gvsig.andami.PluginServices;
29
import org.gvsig.app.extension.ProjectExtension;
30
import org.gvsig.app.project.ProjectManager;
31
import org.gvsig.app.project.documents.Document;
32
import org.gvsig.app.project.documents.view.BaseViewDocument;
33
import org.gvsig.fmap.mapcontext.layers.FLayer;
34
import org.gvsig.fmap.mapcontext.layers.FLayers;
35
import org.gvsig.fmap.raster.grid.roi.VectorialROI;
36
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
37
import org.gvsig.fmap.raster.layers.IRasterLayerActions;
38
import org.gvsig.raster.Configuration;
39
import org.gvsig.raster.RasterProcess;
40
import org.gvsig.raster.buffer.BufferFactory;
41
import org.gvsig.raster.buffer.BufferInterpolation;
42
import org.gvsig.raster.buffer.RasterBuffer;
43
import org.gvsig.raster.buffer.WriterBufferServer;
44
import org.gvsig.raster.dataset.GeoRasterWriter;
45
import org.gvsig.raster.dataset.IBuffer;
46
import org.gvsig.raster.dataset.IRasterDataSource;
47
import org.gvsig.raster.dataset.InvalidSetViewException;
48
import org.gvsig.raster.dataset.NotSupportedExtensionException;
49
import org.gvsig.raster.dataset.Params;
50
import org.gvsig.raster.dataset.RasterDataset;
51
import org.gvsig.raster.dataset.RasterDriverException;
52
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
53
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
54
import org.gvsig.raster.datastruct.ColorTable;
55
import org.gvsig.raster.datastruct.NoData;
56
import org.gvsig.raster.grid.GridPalette;
57
import org.gvsig.raster.grid.filter.RasterFilterList;
58
import org.gvsig.raster.grid.filter.bands.ColorTableFilter;
59
import org.gvsig.raster.util.RasterNotLoadException;
60
import org.gvsig.raster.util.RasterToolsUtil;
61
/**
62
 * <code>ClippingProcess</code> es un proceso que usa un <code>Thread</code>
63
 * para aplicar un recorte a una capa y guardarlo en disco. Muestra una barra
64
 * de incremento informativa.
65
 *
66
 * @version 24/04/2007
67
 * @author BorSanZa - Borja S?nchez Zamorano (borja.sanchez@iver.es)
68
 */
69
public class ClippingProcess extends RasterProcess {
70
	private String                        fileName            = "";
71
	private WriterBufferServer            writerBufferServer  = null;
72
	private FLyrRasterSE                  rasterSE            = null;
73
	private AffineTransform               affineTransform     = new AffineTransform();
74
	private boolean                       oneLayerPerBand     = false;
75
	private int[]                         drawableBands       = { 0, 1, 2 };
76
	private int[]                         pValues             = null;
77
	private GeoRasterWriter               grw                 = null;
78
	private int                           interpolationMethod = BufferInterpolation.INTERPOLATION_Undefined;
79
	private String                        viewName            = "";
80
	private Params                        params              = null;
81
	private DatasetColorInterpretation    colorInterp         = null;
82
	private ArrayList                     selectedRois        = null;
83

  
84
	private double[]                      wcValues             = null;
85
	
86
	/**
87
	 * Variables de la resoluci?n de salida
88
	 */
89
	private int                           resolutionWidth     = 0;
90
	private int                           resolutionHeight    = 0;
91
	
92
	private IBuffer                       buffer              = null;
93

  
94
	/**
95
	 * Par?metros obligatorios al proceso:
96
	 * <UL>
97
	 * <LI>filename: Nombre del fichero de salida</LI>
98
	 * <LI>datawriter: Escritor de datos</LI>
99
	 * <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso</LI>
100
	 * <LI>pixelcoordinates: Coordenadas pixel del recorte (ulx, uly, lrx, lry)</LI>
101
	 * <LI>layer: Capa de entrada para el recorte</LI>
102
	 * <LI>drawablebands: Bandas de entrada</LI>
103
	 * <LI>onelayerperband: booleano que informa de si escribimos una banda por fichero de salida o todas en un fichero</LI>
104
	 * <LI>interpolationmethod: M?todo de interpolaci?n.</LI>
105
	 * <LI>affinetransform: Transformaci?n que informa al dataset de salida de su referencia geografica</LI>
106
	 * <LI>resolution: Ancho y alto de la capa de salida</LI>
107
	 * </UL> 
108
	 */
109
	public void init() {
110
		fileName = getStringParam("filename");
111
		writerBufferServer = (WriterBufferServer) getParam("datawriter");
112
		viewName = getStringParam("viewname");
113
		pValues = getIntArrayParam("pixelcoordinates");
114
		wcValues = getDoubleArrayParam("realcoordinates");
115
		rasterSE = getLayerParam("layer");
116
		drawableBands = getIntArrayParam("drawablebands");
117
		oneLayerPerBand = getBooleanParam("onelayerperband");
118
		interpolationMethod = getIntParam("interpolationmethod");
119
		affineTransform = (AffineTransform)getParam("affinetransform");
120
		colorInterp = (DatasetColorInterpretation)getParam("colorInterpretation");
121
		selectedRois = (ArrayList)getParam("selectedrois");
122
		if(getIntArrayParam("resolution") != null) {
123
			resolutionWidth = getIntArrayParam("resolution")[0];
124
			resolutionHeight = getIntArrayParam("resolution")[1];
125
		}
126
		params = (Params) getParam("driverparams");
127
	}
128

  
129
	/**
130
	 * Salva la tabla de color al fichero rmf.
131
	 * @param fName
132
	 * @throws IOException
133
	 */
134
	private void saveToRmf(String fileName) {
135
		RasterDataset rds = null;
136
		int limitNumberOfRequests = 20;
137
		while (rds == null && limitNumberOfRequests > 0) {
138
			try {
139
				rds = rasterSE.getDataSource().getDataset(0)[0];
140
			} catch (IndexOutOfBoundsException e) {
141
				//En ocasiones, sobre todo con servicios remotos al pedir un datasource da una excepci?n de este tipo
142
				//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
143
				//gestionar pilla a la capa sin datasources asociados ya que est? reasignandolo. Si volvemos a pedirlo debe
144
				//haberlo cargado ya.
145
				try {
146
					Thread.sleep(200);
147
				} catch (InterruptedException e1) {
148
				}
149
			}
150
			limitNumberOfRequests--;
151
		}
152
		
153
		if (rds == null) {
154
			//RasterToolsUtil.messageBoxError("error_load_layer", this, new Exception("Error writing RMF. limitNumberOfRequests=" + limitNumberOfRequests));
155
			return;
156
		}
157

  
158
		RasterFilterList rasterFilterList = rasterSE.getRenderFilterList();
159

  
160
		// Guardamos en el RMF el valor NoData
161
		if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
162
			try {
163
				RasterDataset.saveObjectToRmfFile(fileName, NoData.class, new NoData(rasterSE.getNoDataValue(), rasterSE.getNoDataType(), rasterSE.getDataType()[0]));
164
			} catch (RmfSerializerException e) {
165
				RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
166
			}
167
		}
168

  
169
		// Guardamos en el RMF la tabla de color
170
		ColorTableFilter colorTableFilter = (ColorTableFilter) rasterFilterList.getByName(ColorTableFilter.names[0]);
171
		if (colorTableFilter != null) {
172
			GridPalette gridPalette = new GridPalette((ColorTable) colorTableFilter.getColorTable().clone());
173
			try {
174
				RasterDataset.saveObjectToRmfFile(fileName, ColorTable.class, (ColorTable) gridPalette);
175
			} catch (RmfSerializerException e) {
176
				RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
177
			}
178
		}
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
				try {
198
					if(pValues != null) {
199
						if (RasterBuffer.isBufferTooBig(new double[] { pValues[0], pValues[3], pValues[2], pValues[1] }, drawableBands.length))
200
							bufferFactory.setReadOnly(true);
201
						bufferFactory.setAreaOfInterest(pValues[0], pValues[3], pValues[2] - pValues[0], pValues[1] - pValues[3]);
202
					} else if(wcValues != null) {
203
						if(!rasterSE.isActionEnabled(IRasterLayerActions.REMOTE_ACTIONS))
204
							bufferFactory.setReadOnly(true);
205
						bufferFactory.setAreaOfInterest(wcValues[0], wcValues[1], Math.abs(wcValues[0] - wcValues[2]), Math.abs(wcValues[1] - wcValues[3]));
206
					}
207
				} catch (InvalidSetViewException e) {
208
					RasterToolsUtil.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
209
				}
210
				buffer = bufferFactory.getRasterBuf();
211

  
212
				insertLineLog(RasterToolsUtil.getText(this, "interpolando"));
213

  
214
				buffer = ((RasterBuffer) buffer).getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
215
			} else {
216
				try {
217
					if (RasterBuffer.isBufferTooBig(new double[] { 0, 0, resolutionWidth, resolutionHeight }, drawableBands.length))
218
						bufferFactory.setReadOnly(true);
219
					if(pValues != null) 
220
						bufferFactory.setAreaOfInterest(pValues[0], pValues[3], Math.abs(pValues[2] - pValues[0]) + 1, Math.abs(pValues[1] - pValues[3]) + 1, resolutionWidth, resolutionHeight);
221
					else if(wcValues != null) 
222
						bufferFactory.setAreaOfInterest(wcValues[0], wcValues[1], wcValues[2], wcValues[3], resolutionWidth, resolutionHeight);
223
					buffer = bufferFactory.getRasterBuf();
224
				} catch (InvalidSetViewException e) {
225
					RasterToolsUtil.messageBoxError("No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
226
				}
227
			}
228
			//TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
229
			
230

  
231
			if ((selectedRois != null) && (!bufferFactory.isReadOnly())){
232
				if (selectedRois.size()>0){
233
					int despX = 0;
234
					int despY = 0;
235
					if (pValues != null){
236
						despX = pValues[0];
237
						despY = pValues[1];
238
					} else if (wcValues != null){
239
						despX = (int)dsetCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getX();
240
						despY = (int)dsetCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getY();
241
					}
242
					drawOnlyROIs(buffer, selectedRois, despX, despY);
243
				}
244
			}
245
			
246
			
247
			insertLineLog(RasterToolsUtil.getText(this, "salvando_imagen"));
248

  
249
			String finalFileName = "";
250
			if (oneLayerPerBand) {
251
				long[] milis = new long[drawableBands.length];
252
				String[] fileNames = new String[drawableBands.length];
253
				for (int i = 0; i < drawableBands.length; i++) {
254
					fileNames[i] = fileName + "_B" + drawableBands[i] + ".tif";
255
					writerBufferServer.setBuffer(buffer, i);
256
					Params p = null;
257
					if (params == null)
258
						p = GeoRasterWriter.getWriter(fileNames[i]).getParams();
259
					else
260
						p = params;
261
					grw = GeoRasterWriter.getWriter(writerBufferServer, fileNames[i], 1,
262
							affineTransform, buffer.getWidth(), buffer.getHeight(),
263
							buffer.getDataType(), p, null);
264
					grw.setColorBandsInterpretation(new String[]{DatasetColorInterpretation.GRAY_BAND});
265
					grw.setWkt(dsetCopy.getWktProjection());
266
					grw.dataWrite();
267
					grw.writeClose();
268
					saveToRmf(fileNames[i]);
269
					t2 = new java.util.Date().getTime();
270
					milis[i] = (t2 - t1);
271
					t1 = new java.util.Date().getTime();
272
				}
273
				if (incrementableTask != null) {
274
					incrementableTask.processFinalize();
275
					incrementableTask = null;
276
				}
277
				if(viewName != null) {
278
					if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
279
						try {
280
							for (int i = 0; i < drawableBands.length; i++) {
281
								FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileNames[i], null);
282
								if(lyr != null && lyr instanceof FLyrRasterSE)
283
									((FLyrRasterSE)lyr).setRois(rasterSE.getRois());
284
							}
285
						} catch (RasterNotLoadException e) {
286
							RasterToolsUtil.messageBoxError("error_load_layer", this, e);
287
						}
288
					}
289
				}
290
				for (int i = 0; i < drawableBands.length; i++) {
291
					if (externalActions != null)
292
						externalActions.end(new Object[] { fileName + "_B" + drawableBands[i] + ".tif", new Long(milis[i]) });
293
				}
294
			} else {
295
				if (isUsingFile(fileName)){
296
					incrementableTask.hideWindow();
297
					RasterToolsUtil.messageBoxError("error_opened_file", this);
298
					return;
299
				}
300
				File f = new File(fileName);
301
				if (f.exists()){
302
					f.delete();
303
				}
304
				f = null;
305
				writerBufferServer.setBuffer(buffer, -1);
306
				if (params == null) {
307
					finalFileName = fileName + ".tif";
308
					params = GeoRasterWriter.getWriter(finalFileName).getParams();
309
				} else
310
					finalFileName = fileName;
311
				grw = GeoRasterWriter.getWriter(writerBufferServer, finalFileName,
312
						buffer.getBandCount(), affineTransform, buffer.getWidth(),
313
						buffer.getHeight(), buffer.getDataType(), params, null);
314
				if(colorInterp != null)
315
					grw.setColorBandsInterpretation(colorInterp.getValues());
316
				grw.setWkt(dsetCopy.getWktProjection());
317
				grw.dataWrite();
318
				grw.writeClose();
319
				saveToRmf(finalFileName);
320
				t2 = new java.util.Date().getTime();
321
				if (incrementableTask != null) {
322
					incrementableTask.processFinalize();
323
					incrementableTask = null;
324
				}
325
				//Damos tiempo a parar el Thread del incrementable para que no se cuelgue la ventana
326
				//El tiempo es como m?nimo el de un bucle del run de la tarea incrementable
327
				Thread.sleep(600);
328
				cutFinalize(finalFileName, (t2 - t1));
329
			}
330

  
331
		} catch (NotSupportedExtensionException e) {
332
			RasterToolsUtil.messageBoxError("error_not_suported_extension", this, e);
333
		} catch (RasterDriverException e) {
334
			RasterToolsUtil.messageBoxError("error_writer", this, e);
335
		} catch (IOException e) {
336
			RasterToolsUtil.messageBoxError("error_georasterwriter", this, e);
337
		} finally {
338
			if (dsetCopy != null)
339
				dsetCopy.close();
340
			buffer = null;
341
		}
342
	}
343
	
344
	
345
	/**
346
	 * Acciones para poner a NoData los pixels que est?n fuera de las
347
	 * regiones de inter?s seleccionadas.
348
	 * @param buffer
349
	 */
350
	private void drawOnlyROIs(IBuffer buffer, ArrayList rois, int despX, int despY){
351
		for (int i = 0 ; i<buffer.getWidth() ; i++){
352
			for (int j = 0 ; j<buffer.getHeight() ; j++){
353
				boolean  inside = false;
354
				for (int k = 0 ; k<rois.size() ; k++){
355
					VectorialROI roi = (VectorialROI)rois.get(k);
356
					//TODO: Hacer la comprobacion por coordenadas del mundo en lugar de coordenadas pixel.
357
					if (roi.isInGrid(i + despX, j + despY)){
358
						inside = true;
359
					}
360
				}
361
				if (!inside){
362
					for (int l = 0 ; l<buffer.getBandCount() ; l++){
363
						if (buffer.getDataType() == RasterBuffer.TYPE_BYTE){
364
							buffer.setElem(j, i, l, buffer.getByteNoDataValue());
365
						} else if (buffer.getDataType() == RasterBuffer.TYPE_DOUBLE){
366
							buffer.setElem(j, i, l, buffer.getFloatNoDataValue());
367
						} else if (buffer.getDataType() == RasterBuffer.TYPE_FLOAT){
368
							buffer.setElem(j, i, l, buffer.getFloatNoDataValue());
369
						} else if (buffer.getDataType() == RasterBuffer.TYPE_INT){
370
							buffer.setElem(j, i, l, buffer.getIntNoDataValue());
371
						} else if (buffer.getDataType() == RasterBuffer.TYPE_SHORT){
372
							buffer.setElem(j, i, l, buffer.getShortNoDataValue());
373
						}
374
					}
375
				}
376
			}
377
		}
378
	}
379
	
380
	
381
	/**
382
	 * Returns true if there is a layer in the current project using the file named with
383
	 * fileName.
384
	 * @param fileName
385
	 * @return
386
	 */
387
	private boolean isUsingFile(String fileName){
388
//		ProjectExtension ext = (ProjectExtension)PluginServices.getExtension(ProjectExtension.class);
389
		List<Document> docs = ProjectManager.getInstance().getCurrentProject().getDocuments();
390
		
391
		for (int i = 0 ; i<docs.size() ; i++){
392
			if (docs.get(i) instanceof BaseViewDocument){
393
				FLayers lyrs = ((BaseViewDocument)docs.get(i)).getMapContext().getLayers();
394
				for (int j = 0 ; j<lyrs.getLayersCount() ; j++){
395
					if (lyrs.getLayer(j) instanceof FLyrRasterSE){
396
						FLyrRasterSE lyr = (FLyrRasterSE)lyrs.getLayer(j);						
397
						if (lyr.getDataSource() != null ){							
398
							if (lyr.getDataSource().getDataset(0)[0] != null ){
399
								if (lyr.getDataSource().getDataset(0)[0].getFName().equals(fileName)){
400
									return true;
401
								}
402
							}
403
						}		
404
					}
405
				}
406
			}
407
		}
408
		return false;
409
	}
410
	
411
	
412
	/**
413
	 * Acciones que se realizan al finalizar de crear los recortes de imagen.
414
	 * Este m?todo es llamado por el thread TailRasterProcess al finalizar.
415
	 */
416
	private void cutFinalize(String fileName, long milis) {
417
		if (!new File(fileName).exists())
418
			return;
419

  
420
		if(viewName != null) {
421
			if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
422

  
423
				try {
424
					FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileName, null);
425
					if(lyr != null && lyr instanceof FLyrRasterSE)
426
						((FLyrRasterSE)lyr).setRois(rasterSE.getRois());
427
				} catch (RasterNotLoadException e) {
428
					RasterToolsUtil.messageBoxError("error_load_layer", this, e);
429
				}
430
			}
431
		}
432

  
433
		if (externalActions != null)
434
			externalActions.end(new Object[]{fileName, new Long(milis)});
435
	}
436

  
437
	/*
438
	 * (non-Javadoc)
439
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
440
	 */
441
	public int getPercent() {
442
		if (buffer != null) {
443
			BufferInterpolation interpolation = ((RasterBuffer) buffer).getLastInterpolation();
444
			
445
			if (interpolation != null)
446
				if ((interpolation.getPercent() > 0) && (interpolation.getPercent() < 99))
447
					return interpolation.getPercent();
448
		}
449
		
450
		return (writerBufferServer != null) ? writerBufferServer.getPercent() : 0;
451
	}
452

  
453
	/*
454
	 * (non-Javadoc)
455
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
456
	 */
457
	public String getTitle() {
458
		return RasterToolsUtil.getText(this, "incremento_recorte");
459
	}
460
}
tags/v2_0_0_Build_2026/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.IOException;
22
import java.util.ArrayList;
23

  
24
import javax.swing.SwingUtilities;
25

  
26
import org.gvsig.andami.PluginServices;
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.beans.previewbase.ParamStruct;
31
import org.gvsig.raster.buffer.BufferFactory;
32
import org.gvsig.raster.buffer.WriterBufferServer;
33
import org.gvsig.raster.buffer.cache.RasterReadOnlyBuffer;
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.NotSupportedExtensionException;
38
import org.gvsig.raster.dataset.RasterDataset;
39
import org.gvsig.raster.dataset.RasterDriverException;
40
import org.gvsig.raster.dataset.properties.DatasetColorInterpretation;
41
import org.gvsig.raster.dataset.serializer.RmfSerializerException;
42
import org.gvsig.raster.datastruct.NoData;
43
import org.gvsig.raster.datastruct.Transparency;
44
import org.gvsig.raster.grid.Grid;
45
import org.gvsig.raster.grid.filter.FilterTypeException;
46
import org.gvsig.raster.grid.filter.IRasterFilterListManager;
47
import org.gvsig.raster.grid.filter.RasterFilterList;
48
import org.gvsig.raster.grid.filter.RasterFilterListManager;
49
import org.gvsig.raster.hierarchy.IRasterRendering;
50
import org.gvsig.raster.util.RasterToolsUtil;
51

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

  
64
	private RasterFilterList  rasterFilterList = null;
65
	private GeoRasterWriter   geoRasterWriter  = null;
66
	private IRasterRendering  rendering        = null;
67
	private FLyrRasterSE      lyr              = null;
68

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

  
81
	/**
82
	 * Devuelve una interpretacion de color. Es usado cuando no conseguimos un
83
	 * rendering y no podemos saber que interpretacion l?gica ten?a antes.
84
	 * @param geoRasterWriter
85
	 */
86
	private DatasetColorInterpretation getColorIntepretation(IBuffer buffer, Grid grid) {
87
		DatasetColorInterpretation colorInterpretation = null;
88

  
89
		do {
90
			// Si tiene una tabla de color asignamos las tres bandas
91
			if (grid.getFilterList().isActive("colortable")) {
92
				colorInterpretation = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.RED_BAND, DatasetColorInterpretation.GREEN_BAND, DatasetColorInterpretation.BLUE_BAND });
93
				break;
94
			}
95

  
96
			// Si el numero de bandas coincide asignamos la misma interpretacion que tenia antes
97
			if ((rendering != null) && (buffer.getBandCount() == rasterDataSource.getBandCount())) {
98
				colorInterpretation = rasterDataSource.getColorInterpretation();
99
				break;
100
			}
101

  
102
			String[] colorInterp = new String[rasterDataSource.getColorInterpretation().getValues().length];
103

  
104
			for (int i = 0; i < rasterDataSource.getColorInterpretation().getValues().length; i++) {
105
				if (rasterDataSource.getColorInterpretation().getValues()[i].equals(DatasetColorInterpretation.UNDEF_BAND)) {
106
					colorInterp[i] = DatasetColorInterpretation.GRAY_BAND;
107
					continue;
108
				}
109
				colorInterp[i] = rasterDataSource.getColorInterpretation().getValues()[i];
110
			}
111
			colorInterpretation = new DatasetColorInterpretation(colorInterp);
112
		} while (false);
113

  
114
		return colorInterpretation;
115
	}
116
	
117
	/*
118
	 * (non-Javadoc)
119
	 * @see org.gvsig.rastertools.RasterProcess#process()
120
	 */
121
	public void process() throws InterruptedException {
122
		WriterBufferServer writerBufferServer = null;
123
		if(lyr != null)
124
			lyr.setReadingData(Thread.currentThread().toString());
125

  
126
		IRasterDataSource dsetCopy = null;
127
		BufferFactory bufferFactory = null;
128
		IBuffer buffer = null;
129
		
130
		try {
131
			insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));
132
			
133
			//Creaci?n del BufferFactory
134
			dsetCopy = rasterDataSource.newDataset();
135
			bufferFactory = new BufferFactory(dsetCopy);
136
			//if (!RasterBuffer.loadInMemory(dsetCopy))
137
				bufferFactory.setReadOnly(true);
138

  
139
			//Asignaci?n de bandas
140
			int[] renderBands = rendering.getRenderBands();
141
			if (rendering != null) {
142
				// Si es gris, se reduce a una sola banda
143
				if ((renderBands.length == 3) && (renderBands[0] == renderBands[1]) && (renderBands[1] == renderBands[2])) 
144
					renderBands = new int[] { renderBands[0] };
145
				bufferFactory.setDrawableBands(renderBands);
146
			} else
147
				bufferFactory.setAllDrawableBands();
148

  
149
			bufferFactory.setAreaOfInterest();
150
			
151
			IBuffer buff = bufferFactory.getRasterBuf();
152
			if(buff instanceof RasterReadOnlyBuffer) 
153
				((RasterReadOnlyBuffer) buff).addDrawableBands(renderBands);
154
			
155
			Grid grid = new Grid(bufferFactory, true);
156

  
157
			//Obtenemos la lista de filtros
158
			rasterFilterList = grid.getFilterList();
159
			
160
			//Aplicamos los filtros usados en el panel
161
			addSelectedFilters(rasterFilterList, listFilterUsed);
162
			
163
			insertLineLog(RasterToolsUtil.getText(this, "aplicando_filtros"));
164

  
165
			grid.setNoDataValue(rasterDataSource.getNoDataValue());
166
			grid.applyFilters();
167
			
168
			insertLineLog(RasterToolsUtil.getText(this, "guardando_capa"));
169

  
170
			buffer = grid.getRasterBuf();
171

  
172
			writerBufferServer = new WriterBufferServer();
173
			writerBufferServer.setBuffer(buffer, -1);
174
			// TODO: FUNCIONALIDAD: Poner los getWriter con la proyecci?n del fichero fuente
175

  
176
			//Calculo de la interpretaci?n de color
177
			DatasetColorInterpretation colorInterpretation = null;
178
			if((rendering != null && rendering.existColorTable()) || buffer.getBandCount() > 1)
179
				colorInterpretation = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.RED_BAND, DatasetColorInterpretation.GREEN_BAND, DatasetColorInterpretation.BLUE_BAND });
180
			else if(rendering != null && buffer.getBandCount() == 2) {
181
				renderBands = rendering.getRenderBands();
182
				String[] ci = new String[renderBands.length];
183
				for (int i = 0; i < renderBands.length; i++) {
184
					switch (renderBands[i]) {
185
					case 0:ci[i] = DatasetColorInterpretation.RED_BAND; break;
186
					case 1:ci[i] = DatasetColorInterpretation.GREEN_BAND; break;
187
					case 2:ci[i] = DatasetColorInterpretation.BLUE_BAND; break;
188
					default: ci[i] = DatasetColorInterpretation.UNDEF_BAND; 
189
					}
190
				}
191
				colorInterpretation = new DatasetColorInterpretation(ci);
192
			} else
193
				colorInterpretation = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.GRAY_BAND });
194
			
195
			//Si la imagen original ten?a una banda de transparencia se asignar? esta. Si los filtros generados
196
			//crean una banda se mezclar? con la original. 
197
			int nbands = buffer.getBandCount();
198
			if( rasterDataSource.getTransparencyFilesStatus() != null &&
199
					rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber() >= 0) {
200
				bufferFactory.setDrawableBands(new int[]{rasterDataSource.getTransparencyFilesStatus().getAlphaBandNumber()});
201
				bufferFactory.setAreaOfInterest();
202
				IBuffer alpha = bufferFactory.getRasterBuf();
203
				if(grid.getFilterList().getAlphaBand() != null)
204
					alpha = Transparency.merge(alpha, grid.getFilterList().getAlphaBand());
205
				writerBufferServer.setAlphaBuffer(alpha);
206
				//Asignamos la interpretaci?n de color de la banda alpha				
207
				DatasetColorInterpretation alphaI = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.ALPHA_BAND });
208
				colorInterpretation.addColorInterpretation(alphaI);
209
				nbands ++;
210
			} else if(grid.getFilterList().getAlphaBand() != null) {
211
				writerBufferServer.setAlphaBuffer(grid.getFilterList().getAlphaBand());
212
				//Asignamos la interpretaci?n de color de la banda alpha
213
				DatasetColorInterpretation alphaI = new DatasetColorInterpretation(new String[] { DatasetColorInterpretation.ALPHA_BAND });
214
				colorInterpretation.addColorInterpretation(alphaI);
215
				nbands ++;
216
			}
217
			
218
			geoRasterWriter = GeoRasterWriter.getWriter(writerBufferServer, filename, nbands, rasterDataSource.getAffineTransform(0), buffer.getWidth(), buffer.getHeight(), buffer.getDataType(), GeoRasterWriter.getWriter(filename).getParams(), null);
219
			
220
			if (rendering == null)
221
				colorInterpretation = getColorIntepretation(buffer, grid);
222

  
223
			geoRasterWriter.setColorBandsInterpretation(colorInterpretation.getValues());
224

  
225
			geoRasterWriter.dataWrite();
226
			geoRasterWriter.writeClose();
227
			geoRasterWriter = null;
228
			
229
			// Guardamos en el RMF del fichero el valor NoData
230
			if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
231
				try {
232
					RasterDataset.saveObjectToRmfFile(filename, NoData.class, new NoData(rasterDataSource.getNoDataValue(), rasterDataSource.isNoDataEnabled()?2:0, rasterDataSource.getDataType()[0]));
233
				} catch (RmfSerializerException e) {
234
					RasterToolsUtil.messageBoxError(PluginServices.getText(this,"error_salvando_rmf"), this, e);
235
				}
236
			}
237
			
238
			SwingUtilities.invokeLater(new Runnable() {
239
				public void run() {
240
					if (externalActions != null)
241
						externalActions.end(filename);
242
				}
243
			});
244
		} catch (NotSupportedExtensionException e) {
245
			RasterToolsUtil.messageBoxError("error_writer_notsupportedextension", this, e);
246
		} catch (RasterDriverException e) {
247
			RasterToolsUtil.messageBoxError("error_writer", this, e);
248
		} catch (IOException e) {
249
			RasterToolsUtil.messageBoxError("error_writer", this, e);
250
		} catch (FilterTypeException e) {
251
			RasterToolsUtil.messageBoxError("error_adding_filters", this, e);
252
		} finally {
253
			rasterDataSource = null;
254
			if(bufferFactory != null)
255
				bufferFactory.free();
256
			if(buffer != null)
257
				buffer.free();
258
			if(lyr != null)
259
				lyr.setReadingData(null);
260
		}
261
	}
262

  
263
	/**
264
	 * Sustituye la lista de filtros de filterList por la que le pasamos en forma
265
	 * de ArrayList
266
	 * @param filterList
267
	 * @param listFilterUsed
268
	 * @throws FilterTypeException 
269
	 */
270
	public static void addSelectedFilters(RasterFilterList filterList, ArrayList listFilterUsed) throws FilterTypeException {
271
		filterList.clear();
272
		RasterFilterListManager stackManager = new RasterFilterListManager(filterList);
273

  
274
		for (int i = 0; i < listFilterUsed.size(); i++) {
275
			ParamStruct aux = (ParamStruct) listFilterUsed.get(i);
276
			IRasterFilterListManager filterManager = stackManager.getManagerByFilterClass(aux.getFilterClass());
277
			filterManager.addFilter(aux.getFilterClass(), aux.getFilterParam());
278
		}
279

  
280
		filterList.resetPercent();
281
	}
282

  
283
	/*
284
	 * (non-Javadoc)
285
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getPercent()
286
	 */
287
	public int getPercent() {
288
		if (rasterFilterList == null)
289
			return 0;
290

  
291
		if (rasterFilterList.getPercent() < 100)
292
			return rasterFilterList.getPercent();
293

  
294
		if (geoRasterWriter == null)
295
			return 0;
296

  
297
		return geoRasterWriter.getPercent();
298
	}
299

  
300
	/*
301
	 * (non-Javadoc)
302
	 * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
303
	 */
304
	public String getTitle() {
305
		return PluginServices.getText(this, "aplicando_filtros");
306
	}
307
}
0 308

  
tags/v2_0_0_Build_2026/extensions/extRasterTools-SE/src/org/gvsig/raster/util/RasterToolsUtil.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.util;
20

  
21
import java.awt.Component;
22
import java.awt.Dimension;
23
import java.awt.Point;
24
import java.io.File;
25
import java.util.ArrayList;
26

  
27
import javax.swing.ImageIcon;
28
import javax.swing.JOptionPane;
29

  
30
import org.gvsig.andami.PluginServices;
31
import org.gvsig.andami.ui.mdiManager.IWindow;
32
import org.gvsig.app.project.Project;
33
import org.gvsig.app.project.ProjectManager;
34
import org.gvsig.app.project.documents.view.gui.DefaultViewPanel;
35
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
36
import org.gvsig.fmap.mapcontext.layers.FLayer;
37
import org.gvsig.fmap.mapcontext.layers.FLayers;
38
import org.gvsig.fmap.raster.layers.FLyrRasterSE;
39
import org.gvsig.gui.beans.propertiespanel.PropertiesComponent;
40
import org.gvsig.gui.beans.propertiespanel.PropertyStruct;
41
import org.gvsig.raster.dataset.Params;
42
import org.gvsig.raster.dataset.Params.Param;
43
import org.slf4j.LoggerFactory;
44

  
45
/**
46
 * Herramientas de uso general y que son dependientes de gvSIG, FMap o de
47
 * libUIComponents. En caso de no serlo existe una clase independiente de
48
 * cualquier proyecto dentro de libRaster para este tipo de funciones.
49
 *
50
 * @version 31/05/2007
51
 * @author Nacho Brodin (nachobrodin@gmail.com)
52
 */
53
public class RasterToolsUtil {
54

  
55
	/**
56
	 * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
57
	 * dentro de la agrupaci?n.
58
	 * @param srcLyrs FLayers de la vista
59
	 * @param destLyrs Lista de capas 
60
	 * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
61
	 * en la lista es de abajo a arriba las que aparecen en el TOC.
62
	 */
63
	public static ArrayList getRasterLayerList(FLayers srcLyrs, ArrayList destLyrs) {
64
		if(destLyrs == null)
65
			destLyrs = new ArrayList();
66
		for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
67
			if(srcLyrs.getLayer(i) instanceof FLyrRasterSE)
68
				destLyrs.add(srcLyrs.getLayer(i));
69
			if(srcLyrs.getLayer(i) instanceof FLayers)
70
				destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
71
		}
72
		return destLyrs;
73
	}
74
	
75
	/**
76
	 * Obtiene la lista de capas del TOC y devuelve las raster. Si hay capas agrupadas lo tiene en cuenta y mira
77
	 * dentro de la agrupaci?n.
78
	 * @param srcLyrs FLayers de la vista
79
	 * @param destLyrs Lista de capas 
80
	 * @return ArrayList con la lista de capas raster agrupadas o no. El orden en que aparecen
81
	 * en la lista es de abajo a arriba las que aparecen en el TOC.
82
	 */
83
	public static ArrayList getLayerList(FLayers srcLyrs, ArrayList destLyrs) {
84
		if(destLyrs == null)
85
			destLyrs = new ArrayList();
86
		for (int i = 0; i < srcLyrs.getLayersCount(); i++) {
87
			if(srcLyrs.getLayer(i) instanceof FLayers)
88
				destLyrs = getLayerList((FLayers)srcLyrs.getLayer(i), destLyrs);
89
			else 
90
				destLyrs.add(srcLyrs.getLayer(i));
91
		}
92
		return destLyrs;
93
	}
94
	
95
	/**
96
	 * Obtiene el nombre de la vista donde est? cargada la capa que se pasa por par?metro
97
	 * @param layer Capa cargada en una vista
98
	 * @return Nombre de la vista donde est? cargada la capa.
99
	 */
100
	public static String getView(FLayer layer) {
101
//		Project p = ((ProjectExtension) PluginServices.getExtension(ProjectExtension.class)).getProject();
102
		Project p = ProjectManager.getInstance().getCurrentProject();
103
		return p.getViewName(layer);	
104
	}
105
	
106
	/**
107
	 * Devuelve la traducci?n de un texto. En caso de no existir la traducci?n al idioma seleccionado
108
	 * devolver? la cadena de entrada.
109
	 * @param parent Ventana padre que contiene el objeto con la traducci?n
110
	 * @param text Texto a traducir
111
	 * @return Texto traducido o cadena de entrada en caso de no encontrar una traducci?n
112
	 */
113
	public static String getText(Object parent, String text) {
114
		return PluginServices.getText(parent, text);
115
	}
116
	
117
	/**
118
	 * Obtiene un icono definido por la etiqueta que se especifica en el 
119
	 * par?metro
120
	 * @param ico Etiqueta del icono
121
	 * @return Icono
122
	 */
123
	public static ImageIcon getIcon(String ico) {
124
		return PluginServices.getIconTheme().get(ico);	
125
	}
126
	
127
	/**
128
	 * A?ade una ventana al gestor de ventanas
129
	 * @param window
130
	 */
131
	public static void addWindow(IWindow window) {
132
		PluginServices.getMDIManager().addWindow(window);
133
	}
134
	
135
	/**
136
	 * Elimina una ventana al gestor de ventanas
137
	 * @param window
138
	 */
139
	public static void closeWindow(IWindow window) {
140
		PluginServices.getMDIManager().closeWindow(window);
141
	}
142
	
143
	/**
144
	 * Selecciona los controles del panel de propiedades a partir de los par?mtros
145
	 * obtenidos del driver. Este m?todo realiza una transformaci?n entre Params
146
	 * obtenido del driver de escritura y los par?metros del panel de propiedades.
147
	 * @param panel Panel de propiedades
148
	 * @param params Par?metros del driver
149
	 * @param notTakeIntoAccount Nombre de par?metros que no hay que tener en cuenta. Si es null se tienen en cuenta todos.
150
	 */
151
	public static void loadPropertiesFromWriterParams(PropertiesComponent pComp, Params params, String[] notTakeIntoAccount) {
152
		for (int i = 0; i < params.getNumParams(); i++) {
153
			Param p = params.getParam(i);
154
			String name = getText(null, p.id);
155
			String key = p.id;
156

  
157
			//Miramos si el par?metro coincide con  alguno en la lista de parametros que no hay que
158
			//tener en cuenta. Si es as? no lo a?adimos
159
			if(notTakeIntoAccount != null && notTakeIntoAccount.length > 0) {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff