Statistics
| Revision:

gvsig-lrs / org.gvsig.lrs / trunk / org.gvsig.lrs / org.gvsig.lrs.app / org.gvsig.lrs.app.mainplugin / src / main / java / org / gvsig / lrs / app / showmeasures / ShowMeasuresExtension.java @ 69

History | View | Annotate | Download (19.4 KB)

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
}