Revision 205

View differences:

org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/buildNumber.properties
1
#Sat Oct 05 19:38:29 CEST 2019
2
buildNumber=29
0 3

  
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/assembly/gvsig-plugin-package.xml
1
<!-- gvSIG. Desktop Geographic Information System. Copyright (C) 2007-2013 gvSIG
2
  Association. This program is free software; you can redistribute it and/or modify
3
  it under the terms of the GNU General Public License as published by the Free Software
4
  Foundation; either version 3 of the License, or (at your option) any later version.
5
  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
6
  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
7
  PURPOSE. See the GNU General Public License for more details. You should have received
8
  a copy of the GNU General Public License along with this program; if not, write to
9
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
10
  USA. For any additional information, do not hesitate to contact us at info AT gvsig.com,
11
  or visit our website www.gvsig.com. -->
12
<assembly>
13
  <id>gvsig-plugin-package</id>
14
  <formats>
15
    <format>zip</format>
16
  </formats>
17
  <baseDirectory>${project.artifactId}</baseDirectory>
18
  <includeBaseDirectory>true</includeBaseDirectory>
19
  <files>
20
    <file>
21
      <source>target/${project.artifactId}-${project.version}.jar</source>
22
      <outputDirectory>lib</outputDirectory>
23
    </file>
24
    <file>
25
      <source>target/package.info</source>
26
    </file>
27
  </files>
28

  
29
  <fileSets>
30
    <fileSet>
31
      <directory>src/main/resources-plugin</directory>
32
      <outputDirectory>.</outputDirectory>
33
    </fileSet>
34
  </fileSets>
35

  
36

  
37
  <dependencySets>
38
    <dependencySet>
39
      <useProjectArtifact>false</useProjectArtifact>
40
      <useTransitiveDependencies>false</useTransitiveDependencies>
41
      <outputDirectory>lib</outputDirectory>
42
      <includes>
43
        <include>org.gvsig:org.gvsig.lrs.lib.api</include>
44
        <include>org.gvsig:org.gvsig.lrs.lib.impl</include>
45
        <include>org.gvsig:org.gvsig.lrs.swing.api</include>
46
        <include>org.gvsig:org.gvsig.lrs.swing.impl</include>
47
      </includes>
48
    </dependencySet>
49
  </dependencySets>
50

  
51
</assembly>
52

  
0 53

  
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/java/org/gvsig/lrs/app/calibrateroute/CalibrateRouteExtension.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.app.calibrateroute;
24

  
25
import java.awt.event.ActionEvent;
26
import java.awt.event.ActionListener;
27

  
28
import javax.swing.JOptionPane;
29

  
30
import org.apache.commons.lang3.StringUtils;
31
import org.gvsig.andami.IconThemeHelper;
32
import org.gvsig.andami.PluginServices;
33
import org.gvsig.andami.PluginsLocator;
34
import org.gvsig.andami.PluginsManager;
35
import org.gvsig.andami.plugins.Extension;
36
import org.gvsig.app.ApplicationLocator;
37
import org.gvsig.app.ApplicationManager;
38
import org.gvsig.app.project.documents.view.ViewDocument;
39
import org.gvsig.app.project.documents.view.gui.IView;
40
import org.gvsig.fmap.dal.exception.DataException;
41
import org.gvsig.fmap.dal.feature.EditableFeature;
42
import org.gvsig.fmap.dal.feature.Feature;
43
import org.gvsig.fmap.dal.feature.FeatureSelection;
44
import org.gvsig.fmap.dal.feature.FeatureStore;
45
import org.gvsig.fmap.dal.store.shp.SHPNewStoreParameters;
46
import org.gvsig.fmap.geom.Geometry;
47
import org.gvsig.fmap.mapcontext.MapContextLocator;
48
import org.gvsig.fmap.mapcontext.MapContextManager;
49
import org.gvsig.fmap.mapcontext.exceptions.LoadLayerException;
50
import org.gvsig.fmap.mapcontext.layers.FLayers;
51
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
52
import org.gvsig.lrs.lib.api.LrsAlgorithm;
53
import org.gvsig.lrs.lib.api.LrsAlgorithmsLocator;
54
import org.gvsig.lrs.lib.api.LrsAlgorithmsManager;
55
import org.gvsig.lrs.lib.api.LrsCalibrateRouteAlgorithmParams;
56
import org.gvsig.lrs.lib.api.MeasuresCalculator;
57
import org.gvsig.lrs.lib.api.exceptions.LrsGettingParametersException;
58
import org.gvsig.lrs.lib.api.exceptions.LrsNeededParameterException;
59
import org.gvsig.lrs.swing.api.JLrsAlgorithmParams;
60
import org.gvsig.lrs.swing.api.JLrsLastUsedValues;
61
import org.gvsig.lrs.swing.api.JLrsProgressDialog;
62
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingLocator;
63
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingManager;
64
import org.gvsig.lrs.swing.impl.JLrsCalibrateRouteParamsController;
65
import org.gvsig.lrs.swing.impl.JLrsUtils;
66
import org.gvsig.tools.ToolsLocator;
67
import org.gvsig.tools.dispose.DisposableIterator;
68
import org.gvsig.tools.dynobject.DynObject;
69
import org.gvsig.tools.i18n.I18nManager;
70
import org.gvsig.tools.swing.api.ToolsSwingLocator;
71
import org.gvsig.tools.swing.api.windowmanager.Dialog;
72
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
73
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
74
import org.gvsig.tools.task.SimpleTaskStatus;
75
import org.slf4j.Logger;
76
import org.slf4j.LoggerFactory;
77

  
78

  
79
/**
80
 * @author fdiaz
81
 *
82
 */
83
public class CalibrateRouteExtension extends Extension {
84

  
85
	private static final Logger logger = LoggerFactory.getLogger(CalibrateRouteExtension.class);
86

  
87
	/* (non-Javadoc)
88
	 * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
89
	 */
90
	public void execute(String actionCommand) {
91
		if (StringUtils.equalsIgnoreCase(actionCommand, "calibrate-routes")) {
92
			IView view = getActiveView();
93
			FLayers layers = view.getMapControl().getMapContext().getLayers();
94

  
95
			final WindowManager winManager = ToolsSwingLocator.getWindowManager();
96

  
97
			final LrsAlgorithmsSwingManager manager = LrsAlgorithmsSwingLocator.getLrsAlgorithmsSwingManager();
98

  
99
			final I18nManager i18nManager = ToolsLocator.getI18nManager();
100

  
101
			JLrsCalibrateRouteParamsController panel;
102
			try {
103
				panel = (JLrsCalibrateRouteParamsController)manager.createJLrsCalibrateRouteAlgorithmParameters(layers, null);
104
			} catch (LrsNeededParameterException e2) {
105
				logger.error("Error creating panel", e2);
106
				JOptionPane.showMessageDialog(
107
						null,
108
						new StringBuilder().append(i18nManager.getTranslation("error_creating_panel"))
109
						.append(":").append(e2.getLocalizedMessage()),
110
						i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
111
				return;
112
			}
113
			panel.setVisibleAceptCancel(true);
114
			panel.addActionListener(new ActionListener() {
115

  
116
				public void actionPerformed(ActionEvent e) {
117
					JLrsAlgorithmParams panel = (JLrsAlgorithmParams) e.getSource();
118
					if (panel.isCanceled()) {
119
						return;
120
					}
121
					LrsCalibrateRouteAlgorithmParams params = null;
122
					try {
123
						params = (LrsCalibrateRouteAlgorithmParams)panel.getParams();
124
					} catch (LrsGettingParametersException e1) {
125
						logger.error("Error getting parameters", e1);
126
						JOptionPane.showMessageDialog(
127
								null,
128
								new StringBuilder().append(i18nManager.getTranslation("error_getting_parameters"))
129
								.append(":").append(e1.getLocalizedMessage()),
130
								i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
131
						return;
132
					} catch (LrsNeededParameterException e1) {
133
						logger.warn("Error getting parameters", e1);
134
						JOptionPane.showMessageDialog(
135
								null,
136
								i18nManager.getTranslation(e1.getMessage()),
137
								i18nManager.getTranslation("warning"), JOptionPane.WARNING_MESSAGE);
138
						return;
139
					}
140
					LrsAlgorithmsManager algorithmsManager = LrsAlgorithmsLocator.getLrsAlgorithmsManager();
141
					final LrsAlgorithm algorithm = algorithmsManager.createLrsAlgorithm(params);
142
					final SHPNewStoreParameters shpParams=(SHPNewStoreParameters)params.getNewFeatureStoreParameters();
143

  
144
					final SimpleTaskStatus taskStatus =
145
							ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus(i18nManager.getTranslation("progress"));
146

  
147
					final JLrsProgressDialog progressDialog = manager.createJLrsProgressDialog(taskStatus);
148

  
149
					winManager.showWindow(progressDialog.asJComponent(), i18nManager.getTranslation("calibrate_routes"),
150
							WindowManager.MODE.WINDOW);
151

  
152
					Thread task = new Thread(new Runnable() {
153

  
154
						public void run() {
155
							try {
156
								algorithm.execute(taskStatus);
157
								int resultLoadLayer =JOptionPane.showConfirmDialog(
158
										null,
159
										i18nManager.getTranslation("load_layer_question"),
160
										i18nManager.getTranslation("load_layer_question_title"), JOptionPane.YES_NO_OPTION);
161
								if (resultLoadLayer==JOptionPane.YES_OPTION){
162
									loadLayer(shpParams);
163
								}
164
							} catch (Exception e) {
165
								logger.error("Error calibrating route", e);
166
								String message = e.getMessage();
167
								if (e.getCause() != null) {
168
									message = e.getCause().getMessage();
169
								}
170
								JOptionPane.showMessageDialog(
171
										progressDialog.asJComponent(),
172
										message,
173
										i18nManager.getTranslation("calibrate_routes"),
174
										JOptionPane.ERROR_MESSAGE
175
										);
176
							}
177
						}
178
					});
179
					task.start();
180

  
181
				}
182
			});
183
			winManager.showWindow(panel.asJComponent(), i18nManager.getTranslation("calibrate_routes"),
184
					WindowManager.MODE.WINDOW);
185
		}
186

  
187
	}
188

  
189
	/* (non-Javadoc)
190
	 * @see org.gvsig.andami.plugins.IExtension#initialize()
191
	 */
192
	public void initialize() {
193
		registerIcons();
194
	}
195

  
196
	/* (non-Javadoc)
197
	 * @see org.gvsig.andami.plugins.IExtension#isEnabled()
198
	 */
199
	public boolean isEnabled() {
200
        IView view = getActiveView();
201
        //FLyrVect activeLayer = getActiveLayer(view);
202
        if (view!=null){
203
            ViewDocument viewDocument = view.getViewDocument();
204
            FLayers layers = viewDocument.getMapContext().getLayers();
205
            return JLrsUtils.validatedMCurveAndPointLayer(layers);
206
        }
207

  
208
        return false;
209

  
210
	}
211

  
212
	/* (non-Javadoc)
213
	 * @see org.gvsig.andami.plugins.IExtension#isVisible()
214
	 */
215
	public boolean isVisible() {
216
		ApplicationManager application = ApplicationLocator.getManager();
217

  
218
		return application.getActiveComponent(ViewDocument.class) != null;
219
	}
220

  
221
	private void registerIcons() {
222
		IconThemeHelper.registerIcon("lrs", "pk_blue", this);
223
	}
224

  
225

  
226
	private IView getActiveView() {
227
		ApplicationManager application = ApplicationLocator.getManager();
228
		IView view = (IView) application.getActiveComponent(ViewDocument.class);
229
		return view;
230
	}
231

  
232
	private void loadLayer(SHPNewStoreParameters shpParams){
233
		if (shpParams!=null ){
234
			String name=shpParams.getFile().getName();
235
			if (name.contains(".shp")){
236
				name=name.substring(0,name.lastIndexOf(".shp"));
237
			}
238
			MapContextManager mapContextManager =MapContextLocator.getMapContextManager();
239

  
240
			FLyrVect newLayer=null;
241
			try {
242
				newLayer = (FLyrVect) mapContextManager.createLayer(name,shpParams);
243
			} catch (LoadLayerException e) {
244
				logger.warn("Couldn't load layer",e);
245
			}
246
			getActiveView().getMapControl().getMapContext().getLayers().addLayer(newLayer);
247
		}
248
	}
249

  
250
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/java/org/gvsig/lrs/app/calibrateroute/MeasureCalculatorRouteExtension.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.app.calibrateroute;
24

  
25
import java.awt.event.ActionEvent;
26
import java.awt.event.ActionListener;
27

  
28
import org.apache.commons.lang3.StringUtils;
29
import org.gvsig.andami.IconThemeHelper;
30
import org.gvsig.andami.PluginServices;
31
import org.gvsig.andami.PluginsLocator;
32
import org.gvsig.andami.PluginsManager;
33
import org.gvsig.andami.plugins.Extension;
34
import org.gvsig.app.ApplicationLocator;
35
import org.gvsig.app.ApplicationManager;
36
import org.gvsig.app.project.documents.view.ViewDocument;
37
import org.gvsig.app.project.documents.view.gui.IView;
38
import org.gvsig.fmap.dal.exception.DataException;
39
import org.gvsig.fmap.dal.feature.EditableFeature;
40
import org.gvsig.fmap.dal.feature.Feature;
41
import org.gvsig.fmap.dal.feature.FeatureSelection;
42
import org.gvsig.fmap.dal.feature.FeatureStore;
43
import org.gvsig.fmap.geom.Geometry;
44
import org.gvsig.fmap.mapcontext.layers.FLayer;
45
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
46
import org.gvsig.lrs.lib.api.LrsAlgorithmsLocator;
47
import org.gvsig.lrs.lib.api.LrsAlgorithmsManager;
48
import org.gvsig.lrs.lib.api.MeasuresCalculator;
49
import org.gvsig.lrs.lib.api.exceptions.LrsNeededParameterException;
50
import org.gvsig.lrs.swing.api.JLrsAlgorithmParams;
51
import org.gvsig.lrs.swing.api.JLrsLastUsedValues;
52
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingLocator;
53
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingManager;
54
import org.gvsig.tools.ToolsLocator;
55
import org.gvsig.tools.dispose.DisposableIterator;
56
import org.gvsig.tools.dynobject.DynObject;
57
import org.gvsig.tools.i18n.I18nManager;
58
import org.gvsig.tools.swing.api.ToolsSwingLocator;
59
import org.gvsig.tools.swing.api.windowmanager.Dialog;
60
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
61
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
62
import org.slf4j.Logger;
63
import org.slf4j.LoggerFactory;
64

  
65

  
66
/**
67
 * @author jbadia
68
 *
69
 */
70
public class MeasureCalculatorRouteExtension extends Extension {
71

  
72
	private static final Logger logger = LoggerFactory.getLogger(MeasureCalculatorRouteExtension.class);
73

  
74
	/* (non-Javadoc)
75
	 * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
76
	 */
77
	public void execute(String actionCommand) {
78

  
79
		if (StringUtils.equalsIgnoreCase(actionCommand, "calculate-m-routes")) {
80
			IView view = getActiveView();
81
			FLyrVect layer = view.getMapControl().getMapContext().getLayers().getFirstActiveVectorLayer();
82

  
83

  
84
			LrsAlgorithmsSwingManager manager = LrsAlgorithmsSwingLocator.getLrsAlgorithmsSwingManager();
85
			I18nManager i18nManager = ToolsLocator.getI18nManager();
86

  
87
			PluginsManager pluginsManager = PluginsLocator.getManager();
88
			PluginServices plugin = pluginsManager.getPlugin(this);
89
			DynObject pluginProperties = plugin.getPluginProperties();
90

  
91

  
92

  
93
			JLrsAlgorithmParams panel;
94
			try {
95
				JLrsLastUsedValues params = manager.getJLrsLastUsedValues(pluginProperties);
96
				panel = manager.createJLrsCalculateMRoutePanel(layer, params);
97
				WindowManager_v2 winManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
98

  
99
				final Dialog dialog = winManager.createDialog(panel.asJComponent(), 
100
						i18nManager.getTranslation("m-coordinate-selector"), "", WindowManager_v2.BUTTONS_OK_CANCEL);      
101
				dialog.addActionListener(new ActionListener() {
102
					public void actionPerformed(ActionEvent e) {
103
						if( dialog.getAction()==WindowManager_v2.BUTTON_OK) {
104
							LrsAlgorithmsManager lrsAlgMng = LrsAlgorithmsLocator.getLrsAlgorithmsManager();
105
							LrsAlgorithmsSwingManager lrsAlgSwingMng = LrsAlgorithmsSwingLocator.getLrsAlgorithmsSwingManager();
106

  
107
							JLrsLastUsedValues prms = lrsAlgSwingMng.getJLrsLastUsedValues();
108
							if(prms != null && !StringUtils.isBlank(prms.getPkInicial()) && !StringUtils.isBlank(prms.getPkFinal())){
109

  
110
								FLyrVect lyrVect = (FLyrVect) getActiveView().getMapControl().getMapContext().getLayers().getFirstActiveVectorLayer();
111
								FeatureStore featStore = lyrVect.getFeatureStore();
112
								try {
113
									featStore.edit(FeatureStore.MODE_FULLEDIT);
114

  
115
									FeatureSelection selection = featStore.getFeatureSelection();
116
									DisposableIterator it = selection.fastIterator();
117
									while(it.hasNext()){
118
										Feature feat = (Feature) it.next();
119
										EditableFeature editfeat = feat.getEditable();
120

  
121
										MeasuresCalculator mcalc = lrsAlgMng.createMeasuresCalculator(editfeat.getDefaultGeometry(), false);
122
										mcalc.setFirstMeasure(editfeat.getDouble(prms.getPkInicial()));
123
										mcalc.setLastMeasure(editfeat.getDouble(prms.getPkFinal()));
124
										mcalc.calculate();
125
										Geometry mgeom = mcalc.getResult();
126

  
127
										editfeat.setDefaultGeometry(mgeom);
128
										editfeat.validate(EditableFeature.FINISH_EDITING);
129
										featStore.update(editfeat);
130
									}
131

  
132
									featStore.finishEditing();
133
								} catch (DataException e1) {
134
									logger.debug("Error creating the M coordinate: ", e1);
135
								}
136
							}else{
137

  
138
							}
139

  
140
						}
141
					}
142
				});
143
				dialog.show(WindowManager.MODE.WINDOW);
144
			} catch (LrsNeededParameterException e1) {
145
				// TODO Auto-generated catch block
146
				e1.printStackTrace();
147
			}
148

  
149
		}
150
	}
151

  
152
	/* (non-Javadoc)
153
	 * @see org.gvsig.andami.plugins.IExtension#initialize()
154
	 */
155
	public void initialize() {
156
		registerIcons();
157
	}
158

  
159
	/* (non-Javadoc)
160
	 * @see org.gvsig.andami.plugins.IExtension#isEnabled()
161
	 */
162
	public boolean isEnabled() {
163
        IView view = getActiveView();
164
        if (view!=null){
165
            ViewDocument viewDocument = view.getViewDocument();
166
            FLayer[] layers = viewDocument.getMapContext().getLayers().getActives();
167
            return layers.length > 0;
168
        }
169

  
170
        return false;
171

  
172
	}
173

  
174
	/* (non-Javadoc)
175
	 * @see org.gvsig.andami.plugins.IExtension#isVisible()
176
	 */
177
	public boolean isVisible() {
178
		ApplicationManager application = ApplicationLocator.getManager();
179
		return application.getActiveComponent(ViewDocument.class) != null;
180
	}
181

  
182
	private void registerIcons() {
183
		IconThemeHelper.registerIcon("lrs", "pk_blue", this);
184
	}
185

  
186

  
187
	private IView getActiveView() {
188
		ApplicationManager application = ApplicationLocator.getManager();
189
		IView view = (IView) application.getActiveComponent(ViewDocument.class);
190
		return view;
191
	}
192

  
193

  
194
}
0 195

  
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/java/org/gvsig/lrs/app/showmeasures/WiperMeasuresExtension.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.app.showmeasures;
24

  
25
import org.apache.commons.lang3.StringUtils;
26
import org.slf4j.Logger;
27
import org.slf4j.LoggerFactory;
28

  
29
import org.gvsig.andami.IconThemeHelper;
30
import org.gvsig.andami.plugins.Extension;
31
import org.gvsig.app.ApplicationLocator;
32
import org.gvsig.app.ApplicationManager;
33
import org.gvsig.app.project.documents.view.ViewDocument;
34
import org.gvsig.app.project.documents.view.gui.IView;
35
import org.gvsig.fmap.mapcontext.MapContext;
36
import org.gvsig.fmap.mapcontext.layers.FLayer;
37
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
38
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
39
import org.gvsig.lrs.swing.impl.JLrsShowMeasuresParamsController;
40

  
41
/**
42
 * @author dmartinez
43
 *
44
 */
45
public class WiperMeasuresExtension extends Extension {
46

  
47
    private static final Logger logger = LoggerFactory.getLogger(WiperMeasuresExtension.class);
48

  
49
    private JLrsShowMeasuresParamsController panel;
50

  
51

  
52
    /*
53
     * (non-Javadoc)
54
     *
55
     * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
56
     */
57
    public void execute(String actionCommand) {
58
        if (StringUtils.equalsIgnoreCase(actionCommand, "wiper-measures")) {
59
            IView view = getActiveView();
60
            final MapContext mapContext = view.getMapControl().getMapContext();
61
            final GraphicLayer graphics = mapContext.getGraphicsLayer();
62

  
63
            graphics.removeGraphics(ShowMeasuresExtension.SHOW_MEASURES_GRAPHICS_ID);
64
            mapContext.invalidate();
65

  
66
        }
67
    }
68

  
69
    /*
70
     * (non-Javadoc)
71
     *
72
     * @see org.gvsig.andami.plugins.IExtension#initialize()
73
     */
74
    public void initialize() {
75
        registerIcons();
76
    }
77

  
78
    /*
79
     * (non-Javadoc)
80
     *
81
     * @see org.gvsig.andami.plugins.IExtension#isEnabled()
82
     */
83
    public boolean isEnabled() {
84
        IView view = getActiveView();
85
        FLyrVect activeLayer = getActiveLayer(view);
86
        if (panel == null && activeLayer != null) {
87
            return true;
88
        }
89
        return false;
90
    }
91

  
92
    /*
93
     * (non-Javadoc)
94
     *
95
     * @see org.gvsig.andami.plugins.IExtension#isVisible()
96
     */
97
    public boolean isVisible() {
98
        ApplicationManager application = ApplicationLocator.getManager();
99

  
100
        return application.getActiveComponent(ViewDocument.class) != null;
101
    }
102

  
103
    private void registerIcons() {
104
        IconThemeHelper.registerIcon("lrs", "wiper", this);
105
    }
106

  
107
    private IView getActiveView() {
108
        ApplicationManager application = ApplicationLocator.getManager();
109
        IView view = (IView) application.getActiveComponent(ViewDocument.class);
110
        return view;
111
    }
112

  
113
    private FLyrVect getActiveLayer(IView vista) {
114
        if (vista != null) {
115
            ViewDocument viewDocument = vista.getViewDocument();
116
            FLayer[] actives = viewDocument.getMapContext().getLayers().getActives();
117

  
118
            if ((actives.length == 1) && (actives[0] instanceof FLyrVect)) {
119
                return (FLyrVect) actives[0];
120
            }
121
        }
122
        return null;
123
    }
124
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/java/org/gvsig/lrs/app/showmeasures/ShowMeasuresExtension.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.app.showmeasures;
24

  
25
import java.awt.Color;
26
import java.awt.event.ActionEvent;
27
import java.awt.event.ActionListener;
28
import java.awt.event.ComponentEvent;
29
import java.awt.event.ComponentListener;
30
import java.text.DecimalFormat;
31
import java.util.ArrayList;
32
import java.util.Iterator;
33
import java.util.List;
34

  
35
import javax.swing.JOptionPane;
36

  
37
import org.apache.commons.lang3.StringUtils;
38
import org.cresques.cts.ICoordTrans;
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41

  
42
import org.gvsig.andami.IconThemeHelper;
43
import org.gvsig.andami.plugins.Extension;
44
import org.gvsig.app.ApplicationLocator;
45
import org.gvsig.app.ApplicationManager;
46
import org.gvsig.app.project.documents.view.ViewDocument;
47
import org.gvsig.app.project.documents.view.gui.IView;
48
import org.gvsig.fmap.dal.DataSet;
49
import org.gvsig.fmap.dal.exception.DataException;
50
import org.gvsig.fmap.dal.feature.Feature;
51
import org.gvsig.fmap.dal.feature.FeatureSelection;
52
import org.gvsig.fmap.dal.feature.FeatureStore;
53
import org.gvsig.fmap.geom.Geometry;
54
import org.gvsig.fmap.geom.GeometryLocator;
55
import org.gvsig.fmap.geom.GeometryManager;
56
import org.gvsig.fmap.geom.aggregate.MultiLine;
57
import org.gvsig.fmap.geom.exception.CreateGeometryException;
58
import org.gvsig.fmap.geom.primitive.Line;
59
import org.gvsig.fmap.geom.primitive.Point;
60
import org.gvsig.fmap.mapcontext.MapContext;
61
import org.gvsig.fmap.mapcontext.MapContextLocator;
62
import org.gvsig.fmap.mapcontext.layers.FLayer;
63
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
64
import org.gvsig.fmap.mapcontext.layers.vectorial.GraphicLayer;
65
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
66
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
67
import org.gvsig.gui.beans.ProgressDialog;
68
import org.gvsig.lrs.lib.api.LrsAlgorithm;
69
import org.gvsig.lrs.lib.api.LrsAlgorithmsLocator;
70
import org.gvsig.lrs.lib.api.LrsAlgorithmsManager;
71
import org.gvsig.lrs.lib.api.LrsShowMeasuresAlgorithmParams;
72
import org.gvsig.lrs.lib.api.exceptions.LrsGettingParametersException;
73
import org.gvsig.lrs.lib.api.exceptions.LrsNeededParameterException;
74
import org.gvsig.lrs.swing.api.JLrsAlgorithmParams;
75
import org.gvsig.lrs.swing.api.JLrsProgressDialog;
76
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingLocator;
77
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingManager;
78
import org.gvsig.lrs.swing.impl.JLrsShowMeasuresParamsController;
79
import org.gvsig.lrs.swing.impl.JLrsUtils;
80
import org.gvsig.symbology.SymbologyLocator;
81
import org.gvsig.symbology.SymbologyManager;
82
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.text.ISimpleTextSymbol;
83
import org.gvsig.tools.ToolsLocator;
84
import org.gvsig.tools.dispose.DisposableIterator;
85
import org.gvsig.tools.i18n.I18nManager;
86
import org.gvsig.tools.locator.LocatorException;
87
import org.gvsig.tools.swing.api.ToolsSwingLocator;
88
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
89
import org.gvsig.tools.task.SimpleTaskStatus;
90

  
91
/**
92
 * @author dmartinez
93
 *
94
 */
95
public class ShowMeasuresExtension extends Extension implements ComponentListener {
96

  
97
    private static final Logger logger = LoggerFactory.getLogger(ShowMeasuresExtension.class);
98

  
99
    public static final String SHOW_MEASURES_GRAPHICS_ID = "ShowMeasures";
100

  
101
    private JLrsShowMeasuresParamsController panel;
102

  
103

  
104
    /*
105
     * (non-Javadoc)
106
     *
107
     * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
108
     */
109
    public void execute(String actionCommand) {
110
        if (StringUtils.equalsIgnoreCase(actionCommand, "show-measures")) {
111
            IView view = getActiveView();
112
            final MapContext mapContext = view.getMapControl().getMapContext();
113
            final GraphicLayer graphics = mapContext.getGraphicsLayer();
114

  
115
            final FLyrVect activeLayer = getActiveLayer(view);
116

  
117
            final WindowManager winManager = ToolsSwingLocator.getWindowManager();
118

  
119
            final LrsAlgorithmsSwingManager manager = LrsAlgorithmsSwingLocator.getLrsAlgorithmsSwingManager();
120

  
121
            final I18nManager i18nManager = ToolsLocator.getI18nManager();
122

  
123
            try {
124
                panel =
125
                    (JLrsShowMeasuresParamsController) manager.createJLrsShowMeasuresAlgorithmParameters(activeLayer,
126
                        null);
127
                panel.addComponentListener(this);
128
            } catch (LrsNeededParameterException e2) {
129
                logger.error("Error creating panel", e2);
130
                JOptionPane.showMessageDialog(
131
                    null,
132
                    new StringBuilder().append(i18nManager.getTranslation("error_creating_panel")).append(":")
133
                        .append(e2.getLocalizedMessage()), i18nManager.getTranslation("error"),
134
                    JOptionPane.ERROR_MESSAGE);
135
                return;
136
            }
137
            panel.setVisibleAceptCancel(true);
138
            panel.addActionListener(new ActionListener() {
139

  
140
                public void actionPerformed(ActionEvent e) {
141
                    JLrsAlgorithmParams panel = (JLrsAlgorithmParams) e.getSource();
142
                    if (panel.isCanceled()) {
143
                        return;
144
                    }
145
                    LrsShowMeasuresAlgorithmParams params = null;
146
                    try {
147
                        params = (LrsShowMeasuresAlgorithmParams) panel.getParams();
148
                    } catch (LrsGettingParametersException e1) {
149
                        logger.error("Error getting parameters", e1);
150
                        JOptionPane.showMessageDialog(
151
                            null,
152
                            new StringBuilder().append(i18nManager.getTranslation("error_getting_parameters"))
153
                                .append(":").append(e1.getLocalizedMessage()), i18nManager.getTranslation("error"),
154
                            JOptionPane.ERROR_MESSAGE);
155
                        return;
156
                    } catch (LrsNeededParameterException e1) {
157
                        logger.warn("Error getting parameters", e1);
158
                        JOptionPane.showMessageDialog(null, i18nManager.getTranslation(e1.getMessage()),
159
                            i18nManager.getTranslation("warning"), JOptionPane.WARNING_MESSAGE);
160
                        return;
161
                    }
162
                    final SimpleTaskStatus taskStatus =
163
                        ToolsLocator.getTaskStatusManager().createDefaultSimpleTaskStatus(
164
                            i18nManager.getTranslation("progress"));
165

  
166
                    final JLrsProgressDialog progressDialog = manager.createJLrsProgressDialog(taskStatus);
167

  
168
                    winManager.showWindow(progressDialog.asJComponent(), i18nManager.getTranslation("show_measures"),
169
                        WindowManager.MODE.WINDOW);
170

  
171
                    final double distance = params.getDistance();
172

  
173
                    Thread task = new Thread(new Runnable() {
174

  
175
                        public void run() {
176
                            try {
177
                                showMeasures(graphics, activeLayer, distance, taskStatus);
178
                                mapContext.invalidate();
179
                                if(!taskStatus.isRunning() && progressDialog.asJComponent().isVisible()){
180
                                    progressDialog.asJComponent().setVisible(false);
181
                                }
182
                            } catch (Exception e) {
183
                                logger.error("Error showing measures", e);
184
                                String message = e.getMessage();
185
                                if (e.getCause() != null) {
186
                                    message = e.getCause().getMessage();
187
                                }
188
                                JOptionPane.showMessageDialog(progressDialog.asJComponent(), message,
189
                                    i18nManager.getTranslation("show_measures"), JOptionPane.ERROR_MESSAGE);
190
                            }
191
                        }
192
                    });
193
                    task.start();
194

  
195
                }
196
            });
197
            winManager.showWindow(panel.asJComponent(), i18nManager.getTranslation("show_measures"),
198
                WindowManager.MODE.WINDOW);
199
        }
200
    }
201

  
202
    /*
203
     * (non-Javadoc)
204
     *
205
     * @see org.gvsig.andami.plugins.IExtension#initialize()
206
     */
207
    public void initialize() {
208
        registerIcons();
209
    }
210

  
211
    /*
212
     * (non-Javadoc)
213
     *
214
     * @see org.gvsig.andami.plugins.IExtension#isEnabled()
215
     */
216
    public boolean isEnabled() {
217
        IView view = getActiveView();
218
        FLyrVect activeLayer = getActiveLayer(view);
219
        if (panel == null && activeLayer != null) {
220
            return JLrsUtils.hasMLayersWithSelectedFeatures(activeLayer);
221
        }
222
        return false;
223
    }
224

  
225
    /*
226
     * (non-Javadoc)
227
     *
228
     * @see org.gvsig.andami.plugins.IExtension#isVisible()
229
     */
230
    public boolean isVisible() {
231
        ApplicationManager application = ApplicationLocator.getManager();
232

  
233
        return application.getActiveComponent(ViewDocument.class) != null;
234
    }
235

  
236
    private void registerIcons() {
237
        IconThemeHelper.registerIcon("lrs", "pk_green", this);
238
    }
239

  
240
    /*
241
     * Shows measurements along the selected features in a layer with a fixed spacing
242
     *
243
     */
244
    private void showMeasures(GraphicLayer graphics, FLyrVect layer, double distance, SimpleTaskStatus taskStatus)
245
        throws DataException, CreateGeometryException, LocatorException {
246
        FeatureStore featureStore = layer.getFeatureStore();
247
        FeatureSelection selection = featureStore.getFeatureSelection();
248
        if (selection != null && !selection.isEmpty()) {
249
            long range = getRange(selection);
250
            taskStatus.setRangeOfValues(0, range);
251
            long curValue = 0;
252
            taskStatus.setCurValue(curValue);
253
            DisposableIterator it = selection.fastIterator();
254
            ICoordTrans ct = layer.getCoordTrans();
255
            while (it.hasNext()) {
256
                Feature feature = (Feature) it.next();
257
                Geometry geometry = feature.getDefaultGeometry();
258
                if (geometry instanceof Line) {
259
                    curValue = showLineMeasures(graphics, curValue, (Line) geometry, distance, ct);
260
                    taskStatus.setCurValue(curValue);
261
                } else if (geometry instanceof MultiLine) {
262
                    MultiLine multiLine = (MultiLine) geometry;
263
                    int primitives = multiLine.getPrimitivesNumber();
264
                    for (int i = 0; i < primitives; i++) {
265
                        curValue = showLineMeasures(graphics, curValue, (Line) multiLine.getPrimitiveAt(i), distance, ct);
266
                        taskStatus.setCurValue(curValue);
267
                    }
268
                }
269
            }
270
            it.dispose();
271
        }
272
        taskStatus.terminate();
273
    }
274

  
275
    /**
276
     * Shows measurements along a line with a fixed spacing
277
     *
278
     * @param curValue
279
     * @param ct2
280
     * @param taskStatus
281
     * @param geometry
282
     * @return
283
     * @throws LocatorException
284
     * @throws CreateGeometryException
285
     */
286
    private long showLineMeasures(GraphicLayer graphics, long curValue, Line line, Double distance, ICoordTrans ct) throws CreateGeometryException, LocatorException {
287
        long value = curValue;
288
        for (int i = 0; i < line.getNumVertices() - 1; i++) {
289
            value++;
290
            Point vertex = (Point) line.getVertex(i);
291
            double m0 = vertex.getCoordinateAt(vertex.getDimension() - 1);
292

  
293
            double div = m0 / distance;
294
            if (isMultiple(m0, distance)) {
295
                showMeasure(graphics, vertex, m0, ct);
296
            }
297
            Point nextVertex = line.getVertex(i + 1);
298
            double m1 = nextVertex.getCoordinateAt(vertex.getDimension() - 1);
299
            List<Double> multiples = calculateMultiplesBetweenTwoValues(distance, m0, m1);
300
            for (Iterator iterator = multiples.iterator(); iterator.hasNext();) {
301
                Double m = (Double) iterator.next();
302
                Point point = getPointWithMBetweenTwoVertex(m, vertex, nextVertex);
303
                showMeasure(graphics, point, m, ct);
304
            }
305
        }
306
        value++;
307
        return value;
308
    }
309

  
310
    /**
311
     * Show the m in the point p on the graphicLayer
312
     *
313
     * @param m
314
     * @param ct
315
     */
316
    private void showMeasure(GraphicLayer graphics, Point p, double m, ICoordTrans ct) {
317

  
318
        GeometryManager geomManager = GeometryLocator.getGeometryManager();
319
        SymbolManager symbolManager = MapContextLocator.getSymbolManager();
320

  
321
        ISymbol markerSymbol = symbolManager.createSymbol(Geometry.TYPES.POINT, Color.RED);
322
        ISimpleTextSymbol textSymbol = getTextSymbol();
323

  
324
        DecimalFormat formato = new DecimalFormat("0.000");
325
        textSymbol.setText(formato.format(m).replace(",", " + "));
326
        int idMarkerSymbol = graphics.addSymbol(markerSymbol);
327
        int idTextSymbol = graphics.addSymbol(textSymbol);
328
        Point clonedPoint = (Point) p.cloneGeometry();
329
        clonedPoint.reProject(ct);
330
        graphics.addGraphic(SHOW_MEASURES_GRAPHICS_ID, clonedPoint, idTextSymbol);
331
        graphics.addGraphic(SHOW_MEASURES_GRAPHICS_ID, clonedPoint, idMarkerSymbol);
332
    }
333

  
334
    /*
335
     * Creates a text symbol to be used in showMeasure
336
     */
337
    private ISimpleTextSymbol getTextSymbol(){
338
        SymbologyManager symbologyManager = SymbologyLocator.getSymbologyManager();
339
        ISimpleTextSymbol textSymbol = symbologyManager.createSimpleTextSymbol();
340
        textSymbol.setFontSize(10);
341
        return textSymbol;
342
    }
343

  
344
    /**
345
     * Dados dos puntos con coordenada M, calcula el punto correspondiente a la m dada.
346
     *
347
     * @param m
348
     * @param vertex
349
     * @param nextVertex
350
     * @return
351
     * @throws LocatorException
352
     * @throws CreateGeometryException
353
     */
354
    private Point getPointWithMBetweenTwoVertex(Double m, Point vertex, Point nextVertex) throws CreateGeometryException, LocatorException {
355
        Point point = (Point)GeometryLocator.getGeometryManager().create(Geometry.TYPES.POINT, Geometry.SUBTYPES.GEOM2D);
356
        point.setX(
357
            getCoordinateBetweenTwoValues(
358
                m,
359
                vertex.getCoordinateAt(vertex.getDimension()-1),
360
                nextVertex.getCoordinateAt(vertex.getDimension()-1),
361
                vertex.getX(),
362
                nextVertex.getX()));
363
        point.setY(
364
            getCoordinateBetweenTwoValues(
365
                m,
366
                vertex.getCoordinateAt(vertex.getDimension()-1),
367
                nextVertex.getCoordinateAt(vertex.getDimension()-1),
368
                vertex.getY(),
369
                nextVertex.getY()));
370

  
371
        return point;
372
    }
373

  
374
    /**
375
     * Dados los valores en una dimensi?n de dos puntos y sus "m" correspondientes,
376
     * calcula el valor en esa dimensi?n correspondiente a la "m" dada.
377
     *
378
     * @param m
379
     * @param m1
380
     * @param m2
381
     * @param v1
382
     * @param v2
383
     * @return
384
     */
385
    private double getCoordinateBetweenTwoValues(double m, double m1, double m2, double v1, double v2) {
386
        if (v1==v2){
387
            return Double.POSITIVE_INFINITY;
388
        }
389
         return ((v2-v1)*(m-m1)/(m2-m1))+v1;
390
    }
391

  
392
    /**
393
     * Calcula los m?ltiplos de "distance" que existen entre los valores "value0" y "value1"
394
     *
395
     * @param distance
396
     * @param value0
397
     * @param value1
398
     * @return
399
     */
400
    private List<Double> calculateMultiplesBetweenTwoValues(Double distance, double value0, double value1) {
401
        List<Double> result = new ArrayList<Double>();
402

  
403
        double v0;
404
        double v1;
405
        if(value0<=value1){
406
            v0 = value0;
407
            v1 = value1;
408
        } else {
409
            v0 = value1;
410
            v1 = value0;
411
        }
412

  
413
        int factor1 = (int) Math.ceil(v0/distance);
414
        int factor2 = (int) Math.floor(v1/distance);
415
            for (int factor = factor1; factor <= factor2; factor++) {
416
                double m = factor * distance;
417
                if(m>=v0 && m<=v1){
418
                    result.add(m);
419
                }
420
            }
421
        return result;
422
    }
423

  
424

  
425
    /**
426
     * Calcula si el valor del par?metro n es m?ltiplo del valor del par?metro d
427
     * @param n
428
     * @param d
429
     */
430
    private boolean isMultiple(double n, double d) {
431
        double div = n / d;
432
        return ((div - (int) div) < 0.000001);
433
    }
434

  
435
    /**
436
     * @param selection
437
     * @throws DataException
438
     */
439
    private long getRange(FeatureSelection selection) throws DataException {
440
        long range = 0;
441
        DisposableIterator it = selection.fastIterator();
442
        while (it.hasNext()) {
443
            Feature feature = (Feature) it.next();
444
            Geometry geometry = feature.getDefaultGeometry();
445
            if (geometry instanceof Line) {
446
                range += ((Line) geometry).getNumVertices();
447
            } else if (geometry instanceof MultiLine) {
448
                MultiLine multiLine = (MultiLine) geometry;
449
                int primitives = multiLine.getPrimitivesNumber();
450
                for (int i = 0; i < primitives; i++) {
451
                    range += ((Line) multiLine.getPrimitiveAt(i)).getNumVertices();
452
                }
453
            }
454
        }
455
        it.dispose();
456
        return range;
457
    }
458

  
459
    private IView getActiveView() {
460
        ApplicationManager application = ApplicationLocator.getManager();
461
        IView view = (IView) application.getActiveComponent(ViewDocument.class);
462
        return view;
463
    }
464

  
465
    private FLyrVect getActiveLayer(IView vista) {
466
        if (vista != null) {
467
            ViewDocument viewDocument = vista.getViewDocument();
468
            FLayer[] actives = viewDocument.getMapContext().getLayers().getActives();
469

  
470
            if ((actives.length == 1) && (actives[0] instanceof FLyrVect)) {
471
                return (FLyrVect) actives[0];
472
            }
473
        }
474
        return null;
475
    }
476

  
477
    /*
478
     * (non-Javadoc)
479
     *
480
     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.
481
     * ComponentEvent)
482
     */
483
    public void componentResized(ComponentEvent e) {
484
        // TODO Auto-generated method stub
485

  
486
    }
487

  
488
    /*
489
     * (non-Javadoc)
490
     *
491
     * @see
492
     * java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent
493
     * )
494
     */
495
    public void componentMoved(ComponentEvent e) {
496
        // TODO Auto-generated method stub
497

  
498
    }
499

  
500
    /*
501
     * (non-Javadoc)
502
     *
503
     * @see
504
     * java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent
505
     * )
506
     */
507
    public void componentShown(ComponentEvent e) {
508
        // TODO Auto-generated method stub
509

  
510
    }
511

  
512
    /*
513
     * (non-Javadoc)
514
     *
515
     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.
516
     * ComponentEvent)
517
     */
518
    public void componentHidden(ComponentEvent e) {
519
        panel = null;
520
    }
521
}
org.gvsig.lrs/tags/org.gvsig.lrs-1.0.27/org.gvsig.lrs.app/org.gvsig.lrs.app.mainplugin/src/main/java/org/gvsig/lrs/app/editroutecalibration/EditRouteCalibrationExtension.java
1
/* gvSIG. Desktop Geographic Information System.
2
 *
3
 * Copyright ? 2007-2015 gvSIG Association
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., 51 Franklin Street, Fifth Floor, Boston,
18
 * MA  02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us
21
 * at info AT gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.lrs.app.editroutecalibration;
24

  
25
import java.awt.Component;
26
import java.awt.event.ActionEvent;
27
import java.awt.event.ActionListener;
28
import java.awt.event.ComponentEvent;
29
import java.awt.event.ComponentListener;
30
import java.text.MessageFormat;
31
import java.util.List;
32

  
33
import javax.swing.JOptionPane;
34

  
35
import org.apache.commons.lang3.StringUtils;
36
import org.slf4j.Logger;
37
import org.slf4j.LoggerFactory;
38

  
39
import org.gvsig.andami.IconThemeHelper;
40
import org.gvsig.andami.plugins.Extension;
41
import org.gvsig.app.ApplicationLocator;
42
import org.gvsig.app.ApplicationManager;
43
import org.gvsig.app.project.documents.view.ViewDocument;
44
import org.gvsig.app.project.documents.view.gui.IView;
45
import org.gvsig.fmap.dal.exception.DataException;
46
import org.gvsig.fmap.dal.feature.EditableFeature;
47
import org.gvsig.fmap.dal.feature.Feature;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
49
import org.gvsig.fmap.dal.feature.FeatureSet;
50
import org.gvsig.fmap.dal.feature.FeatureStore;
51
import org.gvsig.fmap.geom.Geometry;
52
import org.gvsig.fmap.mapcontext.MapContext;
53
import org.gvsig.fmap.mapcontext.layers.FLayer;
54
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
55
import org.gvsig.lrs.lib.api.LrsEditRouteCalibrationAlgorithmParams;
56
import org.gvsig.lrs.lib.api.LrsEditRouteCalibrationSelectIdRouteAlgorithmParams;
57
import org.gvsig.lrs.lib.api.exceptions.LrsGettingParametersException;
58
import org.gvsig.lrs.lib.api.exceptions.LrsNeededParameterException;
59
import org.gvsig.lrs.swing.api.JLrsAlgorithmParams;
60
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingLocator;
61
import org.gvsig.lrs.swing.api.LrsAlgorithmsSwingManager;
62
import org.gvsig.lrs.swing.impl.JLrsEditRouteCalibrationController;
63
import org.gvsig.lrs.swing.impl.JLrsEditRouteCalibrationSelectIdRouteController;
64
import org.gvsig.lrs.swing.impl.JLrsUtils;
65
import org.gvsig.tools.ToolsLocator;
66
import org.gvsig.tools.dispose.DisposableIterator;
67
import org.gvsig.tools.i18n.I18nManager;
68
import org.gvsig.tools.swing.api.ToolsSwingLocator;
69
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
70

  
71

  
72
/**
73
 * @author dmartinez
74
 *
75
 */
76
public class EditRouteCalibrationExtension extends Extension implements ComponentListener {
77

  
78
    private static final Logger logger = LoggerFactory.getLogger(EditRouteCalibrationExtension.class);
79

  
80
    private JLrsEditRouteCalibrationSelectIdRouteController panelSelectId;
81

  
82
    private JLrsEditRouteCalibrationController panelController;
83

  
84

  
85

  
86
    /* (non-Javadoc)
87
     * @see org.gvsig.andami.plugins.IExtension#execute(java.lang.String)
88
     */
89
    public void execute(String actionCommand) {
90
        if (StringUtils.equalsIgnoreCase(actionCommand, "edit-route-calibration")) {
91
            IView view = getActiveView();
92
            final FLyrVect activeLayer;
93
            if (view!=null){
94
                activeLayer = getActiveLayer(view);
95
            }else{
96
                activeLayer = null;
97
            }
98

  
99
            final MapContext mapContext = view.getMapControl().getMapContext();
100

  
101
            final WindowManager winManager = ToolsSwingLocator.getWindowManager();
102

  
103
            final LrsAlgorithmsSwingManager manager = LrsAlgorithmsSwingLocator.getLrsAlgorithmsSwingManager();
104

  
105
            final I18nManager i18nManager = ToolsLocator.getI18nManager();
106

  
107
            try {
108
                panelSelectId = (JLrsEditRouteCalibrationSelectIdRouteController)manager.createJLrsEditRouteCalibrationSelectIdRouteAlgorithmParameters(activeLayer, null);
109
                panelSelectId.addComponentListener(this);
110
            } catch (LrsNeededParameterException e2) {
111
                logger.error("Error creating panel", e2);
112
                JOptionPane.showMessageDialog(
113
                    null,
114
                    new StringBuilder().append(i18nManager.getTranslation("error_creating_panel"))
115
                        .append(":").append(e2.getLocalizedMessage()),
116
                    i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
117
                return;
118
            }
119
            panelSelectId.setVisibleAceptCancel(true);
120
            panelSelectId.addActionListener(new ActionListener() {
121

  
122
                public void actionPerformed(ActionEvent e) {
123
                    JLrsAlgorithmParams panel = (JLrsAlgorithmParams) e.getSource();
124
                    if (panel.isCanceled()) {
125
                        return;
126
                    }
127
                    LrsEditRouteCalibrationSelectIdRouteAlgorithmParams params = null;
128
                    try {
129
                        params = (LrsEditRouteCalibrationSelectIdRouteAlgorithmParams)panel.getParams();
130
                    } catch (LrsGettingParametersException e1) {
131
                        logger.error("Error getting parameters", e1);
132
                        JOptionPane.showMessageDialog(
133
                            null,
134
                            new StringBuilder().append(i18nManager.getTranslation("error_getting_parameters"))
135
                                .append(":").append(e1.getLocalizedMessage()),
136
                            i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
137
                        return;
138
                    } catch (LrsNeededParameterException e1) {
139
                        logger.warn("Error getting parameters", e1);
140
                        JOptionPane.showMessageDialog(
141
                            null,
142
                            i18nManager.getTranslation(e1.getMessage()),
143
                            i18nManager.getTranslation("warning"), JOptionPane.WARNING_MESSAGE);
144
                        return;
145
                    }
146

  
147
                    try {
148
                        panelController = (JLrsEditRouteCalibrationController)manager.createJLrsEditRouteCalibrationAlgorithmParameters(activeLayer, mapContext, params.getIdRouteField(), null);
149
                        panelController.addComponentListener(EditRouteCalibrationExtension.this);
150
                    } catch (Exception e2) {
151
                        logger.error("Error creating panel", e2);
152
                        JOptionPane.showMessageDialog(
153
                            null,
154
                            new StringBuilder().append(i18nManager.getTranslation("error_creating_panel"))
155
                                .append(":").append(e2.getLocalizedMessage()),
156
                            i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
157
                        return;
158
                    }
159
                    panelController.setVisibleAceptCancel(true);
160
                    panelController.addActionListener(new ActionListener() {
161
                        public void actionPerformed(ActionEvent e) {
162
                            JLrsEditRouteCalibrationController panel = (JLrsEditRouteCalibrationController) e.getSource();
163
                            if (panel.isCanceled()) {
164
                                return;
165
                            }
166

  
167
                            if (panel.hasWarnings()){
168
                                boolean acceptedWarnings=showWarnings(panel.getWarnings());
169
                                if (acceptedWarnings){
170
                                    panel.close();
171
                                }else{
172
                                    return;
173
                                }
174
                            }
175

  
176
                            final LrsEditRouteCalibrationAlgorithmParams params;
177
                            try {
178
                                params = (LrsEditRouteCalibrationAlgorithmParams)panel.getParams();
179
                            } catch (LrsGettingParametersException e1) {
180
                                logger.error("Error getting parameters", e1);
181
                                JOptionPane.showMessageDialog(
182
                                    null,
183
                                    new StringBuilder().append(i18nManager.getTranslation("error_getting_parameters"))
184
                                        .append(":").append(e1.getLocalizedMessage()),
185
                                    i18nManager.getTranslation("error"), JOptionPane.ERROR_MESSAGE);
186
                                return;
187
                            } catch (LrsNeededParameterException e1) {
188
                                logger.warn("Error getting parameters", e1);
189
                                JOptionPane.showMessageDialog(
190
                                    null,
191
                                    i18nManager.getTranslation(e1.getMessage()),
192
                                    i18nManager.getTranslation("warning"), JOptionPane.WARNING_MESSAGE);
193
                                return;
194
                            }
195

  
196
                            if (params!=null){
197
                                saveLayer(activeLayer,params);
198
                            }
199

  
200
                            panel.close();
201
                        }
202

  
203
                    });
204
                    winManager.showWindow(panelController.asJComponent(), i18nManager.getTranslation("edit_route_calibration"),
205
                        WindowManager.MODE.WINDOW);
206
                }
207
            });
208
            winManager.showWindow(panelSelectId.asJComponent(), i18nManager.getTranslation("edit_route_calibration"),
209
                WindowManager.MODE.WINDOW);
210
        }
211
    }
212

  
213
    /* (non-Javadoc)
214
     * @see org.gvsig.andami.plugins.IExtension#initialize()
215
     */
216
    public void initialize() {
217
        registerIcons();
218
    }
219

  
220
    /* (non-Javadoc)
221
     * @see org.gvsig.andami.plugins.IExtension#isEnabled()
222
     */
223
    public boolean isEnabled() {
224
        IView view = getActiveView();
225
        if (view!=null){
226
            FLyrVect activeLayer = getActiveLayer(view);
227
            if (panelSelectId == null && panelController == null && activeLayer!=null && activeLayer.isEditing()){
228
                return JLrsUtils.isMlayerWithNonGeomField(activeLayer);
229
            }
230
        }
231
        return false;
232
    }
233

  
234
    /* (non-Javadoc)
235
     * @see org.gvsig.andami.plugins.IExtension#isVisible()
236
     */
237
    public boolean isVisible() {
238
        ApplicationManager application = ApplicationLocator.getManager();
239

  
240
        return application.getActiveComponent(ViewDocument.class) != null;
241
    }
242

  
243
    private void registerIcons() {
244
        IconThemeHelper.registerIcon("lrs", "pk_cian", this);
245
    }
246

  
247

  
248
    private IView getActiveView() {
249
        ApplicationManager application = ApplicationLocator.getManager();
250
        IView view = (IView) application.getActiveComponent(ViewDocument.class);
251
        return view;
252
    }
253

  
254
    private FLyrVect getActiveLayer(IView vista) {
255
        if (vista != null) {
256
            ViewDocument viewDocument = vista.getViewDocument();
257
            FLayer[] actives =
258
                viewDocument.getMapContext().getLayers().getActives();
259

  
260
            if ((actives.length == 1) && (actives[0] instanceof FLyrVect)) {
261
                return (FLyrVect) actives[0];
262
            }
263
        }
264
        return null;
265
    }
266

  
267
    private boolean showWarnings(List<String> warnings){
268
        final int MAXWARNINGSSHOWED=15;
269

  
270
        final I18nManager i18nManager = ToolsLocator.getI18nManager();
271
        logger.debug("Warnings found accepting edit route panel");
272
        StringBuilder messageBuilder= new StringBuilder().append(i18nManager.getTranslation("warnings_in_edit_route"));
273
        String newLine=System.getProperty("line.separator");
274
        messageBuilder.append(newLine);
275
        for (int i=0;(i<=MAXWARNINGSSHOWED&&i<warnings.size());i++){
276
            if(i<MAXWARNINGSSHOWED){
277
                String warning=warnings.get(i);
278
                messageBuilder.append(newLine);
279
                messageBuilder.append(warning);
280
            }
281
            if (i==MAXWARNINGSSHOWED&&warnings.size()>MAXWARNINGSSHOWED){
282
                messageBuilder.append(newLine);
283
                int warningsNotShowed=warnings.size()-MAXWARNINGSSHOWED;
284
                messageBuilder.append(MessageFormat.format(
285
                    i18nManager.getTranslation("more_warnings_found"), warningsNotShowed));
286
            }
287
        }
288
        messageBuilder.append(newLine);
289
        messageBuilder.append(newLine).append(i18nManager.getTranslation("accept_warnings_question"));
290
        int result =JOptionPane.showConfirmDialog(
291
            null,
292
            messageBuilder,
293
            i18nManager.getTranslation("warnings_dialog"), JOptionPane.YES_NO_OPTION);
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff