Statistics
| Revision:

root / trunk / extensions / extSelectionTools / src / org / gvsig / selectionTools / tools / buffer / process / BufferSelectionProcess.java @ 27833

History | View | Annotate | Download (33.8 KB)

1
package org.gvsig.selectionTools.tools.buffer.process;
2

    
3
/* gvSIG. Geographic Information System of the Valencian Government
4
 *
5
 * Copyright (C) 2007-2008 Infrastructures and Transports Department
6
 * of the Valencian Government (CIT)
7
 * 
8
 * This program is free software; you can redistribute it and/or
9
 * modify it under the terms of the GNU General Public License
10
 * as published by the Free Software Foundation; either version 2
11
 * of the License, or (at your option) any later version.
12
 * 
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *  
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program; if not, write to the Free Software
20
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 
21
 * MA  02110-1301, USA.
22
 * 
23
 */
24

    
25
import java.awt.Color;
26
import java.awt.event.MouseAdapter;
27
import java.awt.event.MouseEvent;
28
import java.io.File;
29
import java.util.ArrayList;
30
import java.util.HashMap;
31

    
32
import javax.swing.JButton;
33

    
34
import org.cresques.cts.ICoordTrans;
35
import org.cresques.cts.IProjection;
36
import org.gvsig.gui.beans.buttonspanel.ButtonsPanel;
37
import org.gvsig.gui.beans.incrementabletask.IncrementableProcess;
38
import org.gvsig.gui.beans.incrementabletask.IncrementableTask;
39

    
40
import com.iver.andami.PluginServices;
41
import com.iver.andami.messages.NotificationManager;
42
import com.iver.cit.gvsig.fmap.MapContext;
43
import com.iver.cit.gvsig.fmap.MapControl;
44
import com.iver.cit.gvsig.fmap.ViewPort;
45
import com.iver.cit.gvsig.fmap.core.FShape;
46
import com.iver.cit.gvsig.fmap.core.IGeometry;
47
import com.iver.cit.gvsig.fmap.core.symbols.IFillSymbol;
48
import com.iver.cit.gvsig.fmap.core.symbols.SimpleFillSymbol;
49
import com.iver.cit.gvsig.fmap.core.v02.FSymbol;
50
import com.iver.cit.gvsig.fmap.drivers.SHPLayerDefinition;
51
import com.iver.cit.gvsig.fmap.edition.IWriter;
52
import com.iver.cit.gvsig.fmap.edition.ShpSchemaManager;
53
import com.iver.cit.gvsig.fmap.edition.writers.shp.MultiShpWriter;
54
import com.iver.cit.gvsig.fmap.edition.writers.shp.ShpWriter;
55
import com.iver.cit.gvsig.fmap.layers.FBitSet;
56
import com.iver.cit.gvsig.fmap.layers.FLayer;
57
import com.iver.cit.gvsig.fmap.layers.FLayers;
58
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
59
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
60
import com.iver.cit.gvsig.fmap.operations.strategies.DefaultStrategy;
61
import com.iver.cit.gvsig.fmap.rendering.SingleSymbolLegend;
62
import com.iver.cit.gvsig.geoprocess.core.fmap.GeoprocessException;
63
import com.iver.cit.gvsig.geoprocess.core.fmap.XTypes;
64
import com.iver.cit.gvsig.geoprocess.impl.buffer.fmap.BufferGeoprocess;
65
import com.iver.cit.gvsig.geoprocess.impl.buffer.fmap.BufferVisitor;
66
import com.iver.cit.gvsig.project.documents.view.gui.View;
67
import com.iver.utiles.swing.threads.IMonitorableTask;
68

    
69

    
70
/**
71
 * 
72
 *
73
 * @author Pablo Piqueras Bartolom? (pablo.piqueras@iver.es)
74
 */
75
public class BufferSelectionProcess extends IncrementableProcess {
76
//        private boolean                                 layerWasBeingEdited            = false;
77

    
78
        private MapControl                         mapControl                                   = null;
79
        private byte                                 pol_side                                   = -1;
80
        private byte                                 line_side                                    = -1;
81
        private byte                                 point_side                                   = -1;
82
        private byte                                 multi_point_side                    = -1;
83
        private short                                 selectedDistanceUnit          = -1;
84
        private FLyrVect[]                          layers                                          = null;
85
        private final double                 f_width;
86
//        private boolean                                 showBufferLayers                    = false;
87
        private boolean                                 showInfluenceAreasLayers = false;
88
        private boolean                                 multiLayerSelection            = false;
89
        private IMonitorableTask         task1                                           = null;
90

    
91

    
92
//        /**
93
//         * Creates a new <p>BufferSelectionProcess</p>.
94
//         * 
95
//         * @param title of the progress dialog
96
//         * @param label the label that explains the process
97
//         * @param mapControl reference to the current active view's <code>MapControl</code>.
98
//         * @param pol_side side of the buffer in a polyline layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE},
99
//         *    {@link BufferConfigurationPanel#INSIDE BufferConfigurationPanel#INSIDE}, or {@link BufferConfigurationPanel#OUTSIDE_AND_INSIDE BufferConfigurationPanel#OUTSIDE_AND_INSIDE}
100
//         * @param line_side side of the buffer in a line layer: {@link BufferConfigurationPanel#OUTSIDE_AND_INSIDE BufferConfigurationPanel#OUTSIDE_AND_INSIDE}
101
//         * @param point_side side of the buffer in a point layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE}
102
//         * @param multi_point_side side of the buffer in a multi point layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE}
103
//         * @param width buffer's width   
104
//         * @param selectedDistanceUnit distance unit selected
105
//         * @param activeLayers current active view's active layers
106
//         * @param showBufferLayers determines if will show the layers with the buffers as new temporal layers
107
//         * @param showInfluenceAreasLayers determines if will show the layers with the influence areas as new temporal layers
108
//         * @param multiLayerSelection determines if the selection in each active layer affects the other
109
//         */
110
        /**
111
         * Creates a new <p>BufferSelectionProcess</p>.
112
         * 
113
         * @param title of the progress dialog
114
         * @param label the label that explains the process
115
         * @param mapControl reference to the current active view's <code>MapControl</code>.
116
         * @param pol_side side of the buffer in a polyline layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE},
117
         *    {@link BufferConfigurationPanel#INSIDE BufferConfigurationPanel#INSIDE}, or {@link BufferConfigurationPanel#OUTSIDE_AND_INSIDE BufferConfigurationPanel#OUTSIDE_AND_INSIDE}
118
         * @param line_side side of the buffer in a line layer: {@link BufferConfigurationPanel#OUTSIDE_AND_INSIDE BufferConfigurationPanel#OUTSIDE_AND_INSIDE}
119
         * @param point_side side of the buffer in a point layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE}
120
         * @param multi_point_side side of the buffer in a multi point layer: {@link BufferConfigurationPanel#OUTSIDE BufferConfigurationPanel#OUTSIDE}
121
         * @param width buffer's width   
122
         * @param selectedDistanceUnit distance unit selected
123
         * @param activeLayers current active view's active layers
124
         * @param showBufferLayers determines if will show the layers with the buffers as new temporal layers
125
         * @param multiLayerSelection determines if the selection in each active layer affects the other
126
         */
127
//        public BufferSelectionProcess(String title, String label, MapControl mapControl, byte pol_side, byte line_side, byte point_side, byte multi_point_side, double width, short selectedDistanceUnit, FLyrVect[] activeLayers, boolean showBufferLayers, boolean showInfluenceAreasLayers, boolean multiLayerSelection) {
128
        public BufferSelectionProcess(String title, String label, MapControl mapControl, byte pol_side, byte line_side, byte point_side, byte multi_point_side, double width, short selectedDistanceUnit, FLyrVect[] activeLayers, boolean showInfluenceAreasLayers, boolean multiLayerSelection) {
129
                super(title);
130

    
131
                this.label = label;
132
                this.mapControl = mapControl;
133
                this.pol_side = pol_side;
134
                this.line_side = line_side;
135
                this.point_side = point_side;
136
                this.multi_point_side = multi_point_side;
137
                this.f_width = width;
138
                this.selectedDistanceUnit = selectedDistanceUnit;
139
                this.layers = activeLayers;
140
//                this.showBufferLayers = showBufferLayers;
141
                this.showInfluenceAreasLayers = showInfluenceAreasLayers;
142
                this.multiLayerSelection = multiLayerSelection;
143
                this.isPausable = true;
144
        }
145

    
146
        /**
147
         * Sets the object that will display the evolution of this loading process as a progress dialog.
148
         * 
149
         * @param iTask the object that will display the evolution of this loading process
150
         */
151
        public void setIncrementableTask(IncrementableTask iTask) {
152
                this.iTask = iTask;
153
                iTask.setAskCancel(true);
154
                iTask.getButtonsPanel().addAccept();
155
                iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_ACCEPT, false);
156

    
157
                JButton jButton = iTask.getButtonsPanel().getButton(ButtonsPanel.BUTTON_ACCEPT);
158
                jButton.addMouseListener(new MouseAdapter() {
159
                        /*
160
                         * (non-Javadoc)
161
                         * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
162
                         */
163
                        public void mouseClicked(MouseEvent e) {
164
                                processFinalize();
165
                        }
166
                });
167
        }
168
//        
169
//        /*
170
//         * (non-Javadoc)
171
//         * @see java.lang.Runnable#run()
172
//         */
173
//        public synchronized void run() {
174
//                String text = null;
175
//
176
//                try {
177
//                        process();
178
//                        while (! ended) {
179
//                                t0 += 500;
180
//                Thread.currentThread().sleep(150);
181
//                        }
182
//                } catch (InterruptedException ie) {
183
//                        iTask.getProgressPanel().setLabel(PluginServices.getText(null, "Process_canceled"));
184
//
185
//                        if (cancel == false) {
186
//                                text = PluginServices.getText(null, "Failed_the_process");
187
//                        }
188
//                        else {
189
//                                log.addLine(PluginServices.getText(null, "Process_cancelled"));
190
//                                JOptionPane.showMessageDialog(iTask.getButtonsPanel(), PluginServices.getText(null, "Process_cancelled"), PluginServices.getText(this, "Information"), JOptionPane.INFORMATION_MESSAGE);
191
//                        }
192
//                }
193
//                finally {
194
//                        iTask.setAskCancel(false);
195
//                        iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_ACCEPT, true);
196
//                        iTask.getButtonsPanel().setEnabled(ButtonsPanel.BUTTON_CANCEL, false);
197
////                        iTask.stop();
198
////                        ended = true;
199
//
200
//                        if (text != null) {
201
//                                log.addLine(PluginServices.getText(null, "Percent") + ": " + getPercent());
202
//                                log.addLine(text);
203
//                                JOptionPane.showMessageDialog(iTask.getButtonsPanel(), text, PluginServices.getText(this, "Error"), JOptionPane.ERROR_MESSAGE);
204
//                        }
205
//                        
206
//                        if (percentage == 100)
207
//                                iTask.getProgressPanel().setLabel(PluginServices.getText(null, "Process_finished"));
208
////                                iTask.getProgressPanel().setPercent(100); // Forces setting the progress bar at 100 %
209
//
210
//                        // Ends this process
211
//                        ended = true;
212
//                        
213
//                        // Ends the progress panel
214
//                        iTask.stop();
215
//                }
216
//        }
217

    
218
        /**
219
         * Importation process.
220
         * 
221
         * @throws InterruptedException if fails the process
222
         */
223
        public void process() throws InterruptedException {
224
                percentage = 5;
225
                try {
226
        
227
                        /* 2- Gets the distance relation */
228
                        double relationDistanceUnitsToMeters = MapContext.CHANGEM[selectedDistanceUnit];
229
                        percentage = 6;
230

    
231
                        /* 3- Stores the new selections */
232
                        FLyrVect layer = null; //, auxLayer = null;
233
                        FBitSet bitsets[] = new FBitSet[layers.length];
234
                        FBitSet copy_bitsets[] = new FBitSet[layers.length];
235
                        FBitSet multiLayerbitsets[] = new FBitSet[layers.length];
236

    
237
                        int size;
238

    
239
                        for (int i = 0; i < layers.length; i++) {
240
                                layer = layers[i];
241
                                
242
                                size = layer.getSource().getRecordset().getSelection().size();
243

    
244
                                bitsets[i] = new FBitSet();
245
                                bitsets[i].clear();
246
                                bitsets[i].or(layer.getSource().getRecordset().getSelection());
247

    
248
                                copy_bitsets[i] = new FBitSet();
249
                                copy_bitsets[i].clear(0, size);
250
                                copy_bitsets[i].or(layer.getSource().getRecordset().getSelection());
251

    
252
                                multiLayerbitsets[i] = new FBitSet();
253
                                multiLayerbitsets[i].clear(0, size);
254
                        }
255
                        percentage = 9;
256
                        
257
                        /* 4- Gets the buffer and intersects to select new geometries */                                        
258
                        ReadableVectorial rv = null;
259
                        IGeometry aux_geometry = null;
260
                        double width = 1; // default value (not used)
261
                        BufferGeoprocess bufferGeoprocess;
262
//                        DifferenceGeoprocess differenceGeoprocess;
263
                        HashMap params = null;
264
                        File outputFile = null; //, outputFile2 = null;
265
                        FLayers tocLayers = mapControl.getMapContext().getLayers();
266
                        FLyrVect layerWithInfluenceAreas = null; //, layerWithBuffers = null;
267
                        IProjection tempProjection = null;
268
                        double inc;
269
                        byte side;
270
                        long number = 0;
271
                        ArrayList layersAdded = new ArrayList(); // Used to cancel the process
272
                        
273
                        final short LAYER_NOT_REPROJECTED = 0;
274
                        final short LAYER_REPROJECTED_TO_PLAIN_COORDINATES = 1;
275
                        final short LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES = 2;
276

    
277
                        short typeReprojection = LAYER_NOT_REPROJECTED;
278
                        percentage = 11;
279

    
280
                        params = new HashMap();
281
                        params.put("layer_selection", new Boolean(true)); // Only selected geometries
282
                        params.put("dissolve_buffers", new Boolean(true)); // Default value 
283
                        params.put("strategy_flag", new Byte(BufferGeoprocess.CONSTANT_DISTANCE_STRATEGY));
284
                        params.put("numRings", new Integer(1));
285
                        //params.put("buffer_distance", new Double(width));
286
                        params.put("cap", new Byte(BufferVisitor.CAP_ROUND));
287
                        
288
                        // Sets projection
289
                        IProjection proj =  ((View)PluginServices.
290
                                        getMDIManager().
291
                                        getActiveWindow()).
292
                                        getMapControl().
293
                                        getViewPort().
294
                                        getProjection();
295
                        params.put("projection", proj);
296
                        
297
                        // Sets distance units
298
                        int distanceUnits = ((View)PluginServices.
299
                                        getMDIManager().
300
                                        getActiveWindow()).getMapControl().getViewPort().getDistanceUnits();
301
                        params.put("distanceunits", new Integer(distanceUnits));
302
                        
303
                        // Sets map units
304
                        boolean isProjected = proj.isProjected();
305
                        int mapUnits = -1;
306
                        if(isProjected){
307
                                mapUnits = ((View)PluginServices.
308
                                        getMDIManager().
309
                                        getActiveWindow()).getMapControl().getViewPort().getMapUnits();
310
                        }else{
311
                                mapUnits = 1;
312
                        }
313
                        params.put("mapunits", new Integer(mapUnits));
314
                        
315
                        percentage = 14;
316

    
317
                        inc = (100 - percentage) / layers.length;
318
                        
319
                        /* 4.1- For each vector layer with geometries selected */
320
                        for (int i = 0; i < layers.length; i++) {
321
                                try {
322
                                        if (cancelProcess.isCanceled()) {
323
                                                throw new InterruptedException();
324
                                        }
325

    
326
                                        layer = layers[i];
327
                                        
328
                                        log.addLine(PluginServices.getText(null, "Starting_selection_of_layer") + " \"" + layer.getName() + "\"");
329

    
330
                                        switch(layer.getShapeType()) {
331
                                                case FShape.POINT:
332
                                                        side = point_side;
333
                                                        break;
334
                                                case FShape.LINE:
335
                                                        side = line_side;
336
                                                        break;
337
                                                case FShape.POLYGON:
338
                                                        side = pol_side;
339
                                                        break;
340
                                                case FShape.MULTIPOINT:
341
                                                        side = multi_point_side;
342
                                                        break;
343
                                                case FShape.MULTI: case FShape.Z: case FShape.NULL: case FShape.TEXT: case FShape.CIRCLE: case FShape.ARC:        case FShape.ELLIPSE:
344
                                                        // UNSUPPORTED
345
                                                        log.addLine(PluginServices.getText(null, "Layer_with_unsupported_geometries_type"));
346
                                                        percentage += inc;
347
                                                        continue;
348
                                                default : // UNDEFINED
349
                                                        // UNSUPPORTED
350
                                                        log.addLine(PluginServices.getText(null, "Layer_with_unsupported_geometries_type"));
351
                                                        percentage += inc;
352
                                                        continue;
353
                                        }
354
                                        
355
                                        
356
                                        /* 4.2- Calculates the width */
357
                                        if (cancelProcess.isCanceled()) {
358
                                                throw new InterruptedException();
359
                                        }
360
                                        
361
                                        //width = f_width * relationDistanceUnitsToMeters;
362
                                        if (layer.getProjection().getAbrev().equals(mapControl.getViewPort().getProjection().getAbrev())) {
363
//                                        if (layer.getProjection() == mapControl.getViewPort().getProjection()) {
364
                                                /* 4.2.1- If the layer isn't projected -> Geographic coordinates (the default units are grades) */
365
                                                if (! layer.getProjection().isProjected()) {
366
                                                        log.addLine(PluginServices.getText(null, "Wont_select_geometries_on_the_layer_because_has_incompatible_projection") + ": " + layer.getName());
367
                                                        continue;
368
                                                        // UNSUPORTED
369
//                                                                        width = (f_width * relationDistanceUnitsToMeters);
370
//                                                                        width = mapControl.getViewPort().fromMapDistance(width);
371
//                                                                        width = Geo.getDecimalDegrees(width);
372
//                                                                        
373
//                                                                        width = (f_width * relationDistanceUnitsToMeters) * MapContext.CHANGEM[8]; // (units selected to meters) * conversion to ?
374
                                                }
375
                                                else {
376
                                                        width = f_width * relationDistanceUnitsToMeters;
377
                                                }
378

    
379
                                                typeReprojection = LAYER_NOT_REPROJECTED;
380
                                        }
381
                                        else {
382
                                                /* 4.2.1.1- If the layer isn't projected -> Geographic coordinates (the default units are grades) */
383
                                                /* 4.2.1.2- If the layer has been re-projected */
384
                                                if (! mapControl.getProjection().isProjected()) {
385
                                                        // UNSUPORTED
386
                                                        if (! layer.getProjection().isProjected()) {
387
                                                                log.addLine(PluginServices.getText(null, "Wont_select_geometries_on_the_layer_because_has_incompatible_projection") + ": " + layer.getName());
388
                                                                continue;
389
                                                        }
390
//                                                                        
391
//                                                                        width = (f_width * relationDistanceUnitsToMeters) * MapContext.CHANGEM[8]; // (units selected to meters) * conversion to ?
392
//                                                                        width = f_width * relationDistanceUnitsToMeters;
393
                                                        
394
//                                                                        width = (f_width * relationDistanceUnitsToMeters);
395
//                                                                        width = mapControl.getViewPort().fromMapDistance(width);
396
//                                                                        width = Geo.getDecimalDegrees(width);
397

    
398
                                                        typeReprojection = LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES;
399
                                                }
400
                                                else {
401
                                                        width = f_width * relationDistanceUnitsToMeters;
402
                                                        typeReprojection = LAYER_REPROJECTED_TO_PLAIN_COORDINATES;
403
                                                }
404
                                                
405
                                                /* 4.3- Fixes a bug with the geoprocesses when the layer is reprojected */
406
                                                if (cancelProcess.isCanceled()) {
407
                                                        throw new InterruptedException();
408
                                                }
409

    
410
                                                tempProjection = layer.getProjection();
411
                                                layer.setProjection(mapControl.getProjection());
412
                                        }
413

    
414
                                        /* 4.4- Sets the buffer width */
415
                                        params.put("buffer_distance", new Double(width));
416
                                        log.addLine(PluginServices.getText(null, "Buffer_information") + ":");
417

    
418
                                        /* 4.5- Shows width information */
419
                                        if (cancelProcess.isCanceled()) {
420
                                                if (tempProjection != null)
421
                                                        layer.setProjection(tempProjection);
422

    
423
                                                throw new InterruptedException();
424
                                        }
425

    
426
                                        if (mapControl.getProjection().isProjected()) {
427
                                                log.addLine("    " + PluginServices.getText(null, "Buffer_width") + ": " + width + " m.");
428
                                        }
429
                                        else {
430
                                                log.addLine("    " + PluginServices.getText(null, "Buffer_width") + ": " + width + " m");
431
                                                log.addLine("    " + PluginServices.getText(null, "Buffer_width") + ": " + width / MapContext.CHANGEM[8] + " ?");
432
                                        }
433

    
434
                                        log.addLine("    " + PluginServices.getText(null, "Buffer_cap") + ": " + PluginServices.getText(null, "Round"));
435

    
436
                                        params.put("typePolBuffer", new Byte(side));
437
                                        
438
                                        switch (side) {
439
                                                case BufferVisitor.BUFFER_OUTSIDE_POLY:
440
                                                        log.addLine("    " + PluginServices.getText(null, "Side") + ": " + PluginServices.getText(null, "Outside"));
441
                                                        break;
442
                                                case BufferVisitor.BUFFER_INSIDE_POLY:
443
                                                        log.addLine("    " + PluginServices.getText(null, "Side") + ": " + PluginServices.getText(null, "Inside"));
444
                                                        break;
445
                                                case BufferVisitor.BUFFER_INSIDE_OUTSIDE_POLY:
446
                                                        log.addLine("    " + PluginServices.getText(null, "Side") + ": " + PluginServices.getText(null, "Outside_and_inside"));
447
                                                        break;
448
                                        }
449
                                        
450
                                        /* 4.3- Creates the influence area using the BufferGeoprocess */
451
                                        if (cancelProcess.isCanceled()) {
452
                                                if (tempProjection != null)
453
                                                        layer.setProjection(tempProjection);
454

    
455
                                                throw new InterruptedException();
456
                                        }
457

    
458
                                        bufferGeoprocess = new BufferGeoprocess(layer);
459

    
460
                                        try {
461
                                                /* 4.3.1- Temporal file */
462
                                                number = 0;
463
                                                do {
464
                                                        int index = layer.getName().lastIndexOf(".");
465
                                                        
466
                                                        if (index == -1) {
467
                                                                outputFile = new File(System.getProperty("java.io.tmpdir") + "/influence_areas_" + layer.getName() + "_" + number + ".shp");                                                                
468
                                                        }
469
                                                        else {
470
                                                                outputFile = new File(System.getProperty("java.io.tmpdir") + "/influence_areas_" + layer.getName().substring(0, index) + "_" + number + ".shp");
471
                                                        }
472

    
473
                                                        number ++;
474
                                                }
475
                                                while (outputFile.exists());
476
                                                        
477
                                                
478
                                                log.addLine(PluginServices.getText(null, "Creating_temp_file") + ": \"" + outputFile.getAbsolutePath() + "\"");
479
                                        }
480
                                        catch(Exception e0) {
481
                                                /* Notifies the exception in the log */
482
                                                if (! cancelProcess.isCanceled()) {
483
                                                        NotificationManager.showMessageError(PluginServices.getText(this, "failed_creating_the_temporal_layer"), e0);
484
                                                        log.addLine(PluginServices.getText(null, "Failed_creating_the_temporal_layer") + ": " + outputFile.getName());;
485
                                                }
486

    
487
                                                throw new InterruptedException();
488
                                        }
489

    
490
                                        if (cancelProcess.isCanceled()) {
491
                                                if (tempProjection != null)
492
                                                        layer.setProjection(tempProjection);
493

    
494
                                                throw new InterruptedException();
495
                                        }
496
                                        
497
                                        try {
498
                                                /* 4.3.2- Sets the parameters of the new influence area geoProcess */
499
                                                bufferGeoprocess.setParameters(params);
500
                                        } catch (GeoprocessException e1) {
501
                                                /* Notifies the exception in the log */
502
                                                if (! cancelProcess.isCanceled()) {
503
                                                        NotificationManager.showMessageError(PluginServices.getText(this, "Error_fallo_geoproceso"), e1);
504
                                                        log.addLine(PluginServices.getText(null, "Error_fallo_geoproceso"));
505
                                                }
506

    
507
                                                throw new InterruptedException();
508
                                        }
509

    
510
                                        /* 4.3.3- Creates the temporal shape layer with the influence areas */
511
                                        if (cancelProcess.isCanceled()) {
512
                                                if (tempProjection != null)
513
                                                        layer.setProjection(tempProjection);
514

    
515
                                                throw new InterruptedException();
516
                                        }
517

    
518
                                        SHPLayerDefinition definition = (SHPLayerDefinition) bufferGeoprocess.createLayerDefinition();
519
                                        definition.setFile(outputFile);
520
                                        ShpSchemaManager schemaManager = new ShpSchemaManager(outputFile.getAbsolutePath());
521
                                        IWriter writer = null;
522

    
523
                                        try {
524
                                                writer = getShpWriter(definition);
525
                                        } catch (Exception e2) {
526
                                                /* Notifies the exception in the log */
527
                                                if (! cancelProcess.isCanceled()) {
528
                                                        NotificationManager.showMessageError("Error_preparar_escritura_resultados", e2);
529
                                                        log.addLine(PluginServices.getText(null, "Error_preparar_escritura_resultados"));
530
                                                }
531

    
532
                                                throw new InterruptedException();
533
                                        }
534

    
535
                                        /* 4.3.4- Sets the properties to create the result layer */
536
                                        if (cancelProcess.isCanceled()) {
537
                                                if (tempProjection != null)
538
                                                        layer.setProjection(tempProjection);
539

    
540
                                                throw new InterruptedException();
541
                                        }
542

    
543
                                        bufferGeoprocess.setResultLayerProperties(writer, schemaManager);
544

    
545
                                        try {
546
                                                /* 4.3.5- Task of the geoProcess, creates an influence area with the parameters */
547
                                                bufferGeoprocess.checkPreconditions();
548
                                                log.addLine(PluginServices.getText(null, "Creating_layer_with_influence_areas"));
549
                                                task1 = bufferGeoprocess.createTask();
550
                                                task1.run();
551
                                                layerWithInfluenceAreas = (FLyrVect) bufferGeoprocess.getResult();
552

    
553
                                                /* 4.3.6- Sets transparency */
554
                                                Color c = ((SimpleFillSymbol)((SingleSymbolLegend)layerWithInfluenceAreas.getLegend()).getDefaultSymbol()).getFillColor();
555
                                                ((SimpleFillSymbol)((SingleSymbolLegend)layerWithInfluenceAreas.getLegend()).getDefaultSymbol()).setFillColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 180));
556

    
557
                                                log.addLine(PluginServices.getText(null, "Layer_with_influence_areas_created"));
558

    
559
                                                switch (typeReprojection) {
560
                                                        case LAYER_NOT_REPROJECTED:
561
                                                                break;
562
                                                        case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
563
                                                                layer.setProjection(tempProjection);
564

    
565
                                                                // Reprojects the layer
566
//                                                                layerWithInfluenceAreas.reProject(mapControl);
567
                                                                ViewPort vPort = mapControl.getViewPort();
568
                                                                ICoordTrans ct = layer.getProjection().getCT(vPort.getProjection());
569
                                                                layer.setCoordTrans(ct);
570

    
571
                                                                log.addLine(PluginServices.getText(null, "Layer_with_influence_areas_reprojected"));
572
                                                                break;
573
                                                }
574

    
575
                                                /* 4.3.7- (Opcional) Adds the temporal layers with the influence areas */
576
                                                if (showInfluenceAreasLayers) {
577
                                                        tocLayers.addLayer(layerWithInfluenceAreas);
578
                                                        layersAdded.add(layerWithInfluenceAreas); // Used to cancel the process
579
                                                        log.addLine(PluginServices.getText(null, "Added_layer_with_influence_areas_to_TOC"));
580
                                                }
581
                                        }
582
                                        catch(Exception e3) {
583
                                                /* Notifies the exception in the log */
584
                                                if (! cancelProcess.isCanceled()) {
585
                                                        NotificationManager.showMessageError(PluginServices.getText(null, "Error_fallo_geoproceso"), e3);
586
                                                        log.addLine(PluginServices.getText(null, "Error_fallo_geoproceso"));
587
                                                }
588
//                                                else {
589
//                                                        // Cancellation process: removes the layers added
590
//                                                        for (int k = 0; k < layersAdded.size(); k++) {
591
//                                                                tocLayers.removeLayer((FLayer) layersAdded.get(k));
592
//                                                        }
593
//                                                }
594

    
595
                                                throw new InterruptedException();
596
                                        }
597
//
598
//                                        /* 4.4- Creates the buffers using the DifferenceGeoprocess */
599
//                                        differenceGeoprocess = new DifferenceGeoprocess(layerWithInfluenceAreas);
600
//                                        differenceGeoprocess.setSecondOperand(layer);
601
//
602
//                                        try {
603
//                                                /* 4.4.1- Temporal file */
604
//                                                number = 0;
605
//                                                do {
606
//                                                        outputFile2 = new File(System.getProperty("java.io.tmpdir") + "/buffers_" + layer.getName() + "_" + number);
607
//                                                        number ++;
608
//                                                }
609
//                                                while (outputFile2.exists());
610
//                                                        
611
//                                                
612
//                                                log.addLine(PluginServices.getText(null, "Creating_temp_file") + ": \"" + outputFile2.getAbsolutePath() + "\"");
613
//                                        }
614
//                                        catch(Exception e0) {
615
//                                                /* Notifies the exception in the log */
616
//                                                NotificationManager.showMessageError(PluginServices.getText(this, "failed_creating_the_temporal_layer"), e0);
617
//                                                log.addLine(PluginServices.getText(null, "Failed_creating_the_temporal_layer") + ": " + outputFile2.getName());;
618
//                                                throw new InterruptedException();
619
//                                        }
620
//
621
//                                        try {
622
//                                                /* 4.4.2- Sets the parameters of the new influence area geoProcess */
623
//                                                differenceGeoprocess.setParameters(params);
624
//                                        } catch (GeoprocessException e1) {
625
//                                                /* Notifies the exception in the log */
626
//                                                NotificationManager.showMessageError(PluginServices.getText(this, "Error_fallo_geoproceso"), e1);
627
//                                                log.addLine(PluginServices.getText(null, "Error_fallo_geoproceso"));
628
//                                                throw new InterruptedException();
629
//                                        }
630
//
631
//                                        /* 4.4.3- Creates the temporal shape layer with the influence areas */
632
//                                        definition = (SHPLayerDefinition) differenceGeoprocess.createLayerDefinition();
633
//                                        definition.setFile(outputFile2);
634
//                                        schemaManager = new ShpSchemaManager(outputFile2.getAbsolutePath());
635
//                                        writer = null;
636
//
637
//                                        try {
638
//                                                writer = getShpWriter(definition);
639
//                                        } catch (Exception e2) {
640
//                                                /* Notifies the exception in the log */
641
//                                                NotificationManager.showMessageError("Error_preparar_escritura_resultados", e2);
642
//                                                log.addLine(PluginServices.getText(null, "Error_preparar_escritura_resultados"));
643
//                                                throw new InterruptedException();
644
//                                        }
645
//
646
//                                        /* 4.4.4- Sets the properties to create the result layer */
647
//                                        differenceGeoprocess.setResultLayerProperties(writer, schemaManager);
648
//
649
//                                        params.put("firstlayerselection", new Boolean(false));
650
//                                        params.put("secondlayerselection", new Boolean(true));
651
//
652
//                                        try {
653
//                                                differenceGeoprocess.setParameters(params);
654
//                                                
655
//                                                /* 4.4.5- Task of the geoProcess, creates a buffer with the parameters */
656
//                                                differenceGeoprocess.checkPreconditions();
657
//                                                log.addLine(PluginServices.getText(null, "Creating_layer_with_buffers"));
658
//                                                task1 = differenceGeoprocess.createTask();
659
//                                                task1.run();
660
//                                                layerWithBuffers = (FLyrVect) differenceGeoprocess.getResult();
661
//
662
//                                                /* 4.4.6- Sets transparency */
663
//                                                Color c = ((FSymbol)((SingleSymbolLegend)layerWithBuffers.getLegend()).getDefaultSymbol()).getColor();
664
//                                                ((FSymbol)((SingleSymbolLegend)layerWithBuffers.getLegend()).getDefaultSymbol()).setColor(new Color(c.getRed(), c.getGreen(), c.getBlue(), 180));
665
//
666
//                                                log.addLine(PluginServices.getText(null, "Layer_with_buffers_created"));
667
//
668
//                                                /* 4.4.7- Fixes a bug with the geoprocesses when the layer is reprojected */
669
//                                                switch (typeReprojection) {
670
//                                                        case LAYER_NOT_REPROJECTED:
671
//                                                                break;
672
//                                                        case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
673
//                                                                layer.setProjection(tempProjection);
674
//
675
//                                                                if (showInfluenceAreasLayers)
676
//                                                                        layerWithInfluenceAreas.reProject(mapControl);
677
//
678
//                                                                layerWithBuffers.reProject(mapControl);
679
//                                                                
680
//                                                                log.addLine(PluginServices.getText(null, "Layer_with_buffers_reprojected"));
681
//                                                                break;
682
//                                                }
683
//
684
//                                                /* 4.4.8- (Opcional) Adds the temporal layers with the influence areas */
685
//                                                if (showBufferLayers) {
686
//                                                        tocLayers.addLayer(layerWithBuffers);
687
//                                                        log.addLine(PluginServices.getText(null, "Added_buffer_areas_to_TOC"));
688
//                                                }
689
//                                        }
690
//                                        catch(Exception e3) {
691
//                                                /* Notifies the exception in the log */
692
//                                                NotificationManager.showMessageError("Error_fallo_geoproceso", e3);
693
//                                                throw new InterruptedException();
694
//                                        }
695
        
696
                                        
697
                                        
698
                                        /* 4.5- Gets the geometries that are contained in the layer */
699
                                        if (cancelProcess.isCanceled()) {
700
                                                throw new InterruptedException();
701
                                        }
702

    
703
                                        //rv = layerWithBuffers.getSource();
704
                                        rv = layerWithInfluenceAreas.getSource();
705

    
706
                                        /* 4.6- For each buffer */
707
                                        log.addLine(PluginServices.getText(null, "Starting_selection_process"));
708

    
709
                                        for (int k = 0; k < rv.getShapeCount(); k++) {
710
                                                if (cancelProcess.isCanceled()) {
711
                                                        throw new InterruptedException();
712
                                                }
713

    
714
                                                rv.start();
715
                                                aux_geometry = (IGeometry) rv.getShape(k);
716
                                                rv.stop();
717

    
718
                                                switch (typeReprojection) {
719
                                                        case LAYER_NOT_REPROJECTED:
720
                                                                break;
721
                                                        case LAYER_REPROJECTED_TO_GEOGRAPHIC_COORDINATES: case LAYER_REPROJECTED_TO_PLAIN_COORDINATES:
722
                                                                aux_geometry.reProject(layer.getCoordTrans());
723
                                                                break;
724
                                                }
725

    
726
                                                /* 4.6.1- Adds new geometries that intersect the new buffer */
727
                                                bitsets[i].or(layer.queryByShape(aux_geometry, DefaultStrategy.INTERSECTS));
728

    
729
                                                /* 4.6.1.1- (Opcional) Multi-layer selection */
730
                                                if (multiLayerSelection) {
731
                                                        for (int j = 0; j < layers.length; j++) {
732
                                                                // Only in different layers
733
                                                                if (i != j) {
734
                                                                        if (! layers[j].getProjection().isProjected()) {
735
                                                                                log.addLine(PluginServices.getText(null, "Wont_select_geometries_on_the_layer_because_has_incompatible_projection") + ": " + layer.getName());
736
                                                                                continue;
737
                                                                        }
738
                                                                        
739
                                                                        multiLayerbitsets[j].or(layers[j].queryByShape(aux_geometry, DefaultStrategy.INTERSECTS));
740

    
741
                                                                        log.addLine(PluginServices.getText(null, "Multi_layer_selection_applied_for_influence_area"));
742
                                                                }
743
                                                        }
744
                                                }
745
                                        }                                                
746
                                                        
747
                                        log.addLine(PluginServices.getText(null, "Selection_process_finished_succesfully"));
748
                                        log.addLine(""); // Empty line
749

    
750
                                } catch (Exception de) {
751
                                        /* 5- Notifies the exception in the log */
752
                                        if (! cancelProcess.isCanceled()) {
753
                                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_selecting_geometries_in_layer") + " " + layer.getName(), de);
754
                                                log.addLine(PluginServices.getText(null, "Failed_selecting_geometries_in_layer"));
755
                                        }
756

    
757
                                        /* C- Cancellation process */
758
                                        int k;
759

    
760
                                        /* C.1- Removes the layers added */
761
                                        for (k = 0; k < layersAdded.size(); k++) {
762
                                                log.addLine(PluginServices.getText(null, "Removed_layer_with_influence_areas_to_TOC"));
763
                                                tocLayers.removeLayer((FLayer) layersAdded.get(k));
764
                                        }
765

    
766
                                        /* C.2- Restores the selection of the layers */
767
                                        for (k = 0; k < layers.length; k++) {
768
                                                layer = layers[k];
769
                                                
770
                                                layer.getSource().getRecordset().setSelection(copy_bitsets[k]);
771
                                        }
772

    
773
                                        // Forces to reload the layers
774
                                        mapControl.drawMap(false);
775

    
776
                                        log.addLine(PluginServices.getText(null, "Selection_restored"));
777

    
778
                                        throw new InterruptedException();
779
                                }
780
                                
781
                                percentage += inc;
782
                        }
783

    
784
                        /* 6- Sets the new selections */
785
                        for (int i = 0; i < layers.length; i++) {
786
                                layer = layers[i];
787

    
788
                                /* 6.1- All geometries selected, included because of multi-layer selections */
789
                                bitsets[i].or(multiLayerbitsets[i]);
790
                                
791
                                /* 6.2- Adds the new geometries selected to the layer's */
792
                                try {
793
                                        layer.getSource().getRecordset().setSelection(bitsets[i]);
794
                                }
795
                                catch (RuntimeException rE) {
796
                                        // Skips the runtime exception launched when this thread tries to update the main frame
797
                                        if (rE.getMessage().compareTo("No Event Dispatch Thread") == 0) {
798
                                                log.addLine(PluginServices.getText(this, "Runtime_exception_refreshing_the_main_frame_by_a_Swing_thread"));
799
                                        }
800
                                }
801
                                //layer.getSource().getRecordset().getSelection().or(bitsets[i]);
802
                        }
803

    
804
                        percentage = 100;
805
                }
806
                catch (Exception ex) {
807
                        if (! cancelProcess.isCanceled()) {
808
                                NotificationManager.showMessageError(PluginServices.getText(null, "Failed_selecting_geometries"), ex);
809
                                log.addLine(PluginServices.getText(null, "Failed_selecting_geometries"));
810
                        }
811

    
812
                        throw new InterruptedException();
813
                }
814
        }
815

    
816
        /**
817
         * Returns a ShpWriter from a SHPLayerDefinition.
818
         * TODO Independize Writer and LayerDefinition of implementation
819
         * (by now we are only saving in SHP format)
820
         * 
821
         * @param definition
822
         * @return
823
         * @throws Exception
824
         */
825
        public IWriter getShpWriter(SHPLayerDefinition definition) throws Exception {
826
                int shapeType = definition.getShapeType();
827
        
828
                if (shapeType != XTypes.MULTI) {
829
                        ShpWriter writer = new ShpWriter();
830
                        writer.setFile(definition.getFile());
831
                        writer.initialize(definition);
832
                        return writer;
833
                } else {
834
                        MultiShpWriter writer = new MultiShpWriter();
835
                        writer.setFile(definition.getFile());
836
                        writer.initialize(definition);
837
                        return writer;
838
                }
839
        }
840

    
841
//        /*
842
//         * (non-Javadoc)
843
//         * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionCanceled(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
844
//         */
845
//        public void actionCanceled(IncrementableEvent e) {
846
//                if (percentage < 100) {
847
//                        ended = true;
848
//
849
//                        cancelProcess.setCanceled(true);
850
////                        if ((task1 != null) && (!task1.isCanceled()) && (!task1.isFinished())) {
851
////                                try {
852
////                                        task1.cancel();
853
////                                }
854
////                                catch (Exception ex) {
855
////                                        NotificationManager.showMessageError(PluginServices.getText(null, "Failed_canceling_the_current_task_of_creation_a_buffer_layer"), ex);
856
////                                        log.addLine(PluginServices.getText(null, "Failed_canceling_the_current_task_of_creation_a_buffer_layer"));
857
////                                }
858
////                        }
859
////
860
////                        blinker.interrupt();
861
//                }
862
//                else {
863
//                        JOptionPane.showMessageDialog(null, Messages.getText("Process_finished_wont_be_cancelled"), Messages.getText("Warning"), JOptionPane.WARNING_MESSAGE);
864
//                }
865
//        }
866
//        
867
//        /*
868
//         * (non-Javadoc)
869
//         * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionResumed(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
870
//         */
871
//        public void actionResumed(IncrementableEvent e) {
872
//        }
873
//        
874
//        /*
875
//         * (non-Javadoc)
876
//         * @see org.gvsig.gui.beans.incrementabletask.IncrementableListener#actionSuspended(org.gvsig.gui.beans.incrementabletask.IncrementableEvent)
877
//         */
878
//        public void actionSuspended(IncrementableEvent e) {
879
//        }
880
}