Statistics
| Revision:

svn-gvsig-desktop / tags / PilotoRedes_Build_3 / extensions / extGraph_predes / src / com / iver / cit / gvsig / graph / gui / RouteControlPanel.java @ 11678

History | View | Annotate | Download (31.3 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2005 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41

    
42
/* CVS MESSAGES:
43
 *
44
 * $Id: RouteControlPanel.java 11678 2007-05-16 08:17:44Z  $
45
 * $Log$
46
 * Revision 1.25.2.2  2007-05-15 07:08:21  fjp
47
 * Para calcular matrices de distancias
48
 *
49
 * Revision 1.25  2006/11/14 18:32:32  fjp
50
 * *** empty log message ***
51
 *
52
 * Revision 1.24  2006/11/14 16:12:01  fjp
53
 * *** empty log message ***
54
 *
55
 * Revision 1.23  2006/11/14 09:23:30  fjp
56
 * cargar paradas desde cualquier tema de puntos
57
 *
58
 * Revision 1.22  2006/11/10 13:57:04  fjp
59
 * *** empty log message ***
60
 *
61
 * Revision 1.21  2006/11/09 21:08:32  azabala
62
 * *** empty log message ***
63
 *
64
 * Revision 1.20  2006/11/09 12:51:12  jaume
65
 * *** empty log message ***
66
 *
67
 * Revision 1.19  2006/11/09 11:00:43  jaume
68
 * *** empty log message ***
69
 *
70
 * Revision 1.18  2006/11/09 10:59:53  jaume
71
 * *** empty log message ***
72
 *
73
 * Revision 1.17  2006/11/09 10:27:50  fjp
74
 * *** empty log message ***
75
 *
76
 * Revision 1.16  2006/11/09 10:24:11  fjp
77
 * *** empty log message ***
78
 *
79
 * Revision 1.15  2006/11/09 09:16:35  fjp
80
 * Ya va!!
81
 *
82
 * Revision 1.14  2006/11/08 20:14:52  azabala
83
 * *** empty log message ***
84
 *
85
 * Revision 1.13  2006/11/08 19:32:22  azabala
86
 * saveroute and saveflags modifications
87
 *
88
 * Revision 1.12  2006/11/08 18:16:28  fjp
89
 * *** empty log message ***
90
 *
91
 * Revision 1.11  2006/11/08 16:48:19  fjp
92
 * *** empty log message ***
93
 *
94
 * Revision 1.10  2006/11/08 16:00:39  fjp
95
 * Por terminar el enlace flags-cuadro de di?logo
96
 *
97
 * Revision 1.9  2006/11/08 13:18:46  fjp
98
 * Por terminar el enlace flags-cuadro de di?logo
99
 *
100
 * Revision 1.8  2006/11/07 19:49:38  azabala
101
 * *** empty log message ***
102
 *
103
 * Revision 1.7  2006/11/06 13:13:53  azabala
104
 * *** empty log message ***
105
 *
106
 * Revision 1.6  2006/11/06 10:29:32  jaume
107
 * *** empty log message ***
108
 *
109
 * Revision 1.5  2006/11/03 19:39:29  azabala
110
 * *** empty log message ***
111
 *
112
 * Revision 1.4  2006/10/27 18:26:22  azabala
113
 * added implementation of load stages method
114
 *
115
 * Revision 1.3  2006/10/27 12:41:09  jaume
116
 * GUI
117
 *
118
 * Revision 1.2  2006/10/26 16:31:21  jaume
119
 * GUI
120
 *
121
 * Revision 1.1  2006/10/25 10:50:41  jaume
122
 * movement of classes and gui stuff
123
 *
124
 * Revision 1.4  2006/10/24 08:04:41  jaume
125
 * *** empty log message ***
126
 *
127
 * Revision 1.3  2006/10/23 16:00:20  jaume
128
 * *** empty log message ***
129
 *
130
 * Revision 1.2  2006/10/23 08:05:39  jaume
131
 * GUI
132
 *
133
 * Revision 1.1  2006/10/20 12:02:50  jaume
134
 * GUI
135
 *
136
 *
137
 */
138
package com.iver.cit.gvsig.graph.gui;
139

    
140
import java.awt.BorderLayout;
141
import java.awt.Component;
142
import java.awt.Dimension;
143
import java.awt.FlowLayout;
144
import java.awt.Font;
145
import java.awt.GridLayout;
146
import java.awt.event.ActionEvent;
147
import java.awt.event.ActionListener;
148
import java.awt.geom.Rectangle2D;
149
import java.text.NumberFormat;
150
import java.util.ArrayList;
151
import java.util.List;
152

    
153
import javax.swing.ImageIcon;
154
import javax.swing.JComboBox;
155
import javax.swing.JLabel;
156
import javax.swing.JOptionPane;
157
import javax.swing.JPanel;
158
import javax.swing.JScrollPane;
159
import javax.swing.JTable;
160
import javax.swing.ListSelectionModel;
161
import javax.swing.event.ListSelectionEvent;
162
import javax.swing.event.ListSelectionListener;
163
import javax.swing.event.TableModelEvent;
164
import javax.swing.event.TableModelListener;
165
import javax.swing.table.AbstractTableModel;
166
import javax.swing.table.TableColumnModel;
167
import javax.swing.table.TableModel;
168

    
169
import org.cresques.cts.IProjection;
170
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
171
import org.gvsig.gui.beans.swing.JBlank;
172
import org.gvsig.gui.beans.swing.JButton;
173

    
174
import com.hardcode.gdbms.engine.values.Value;
175
import com.hardcode.gdbms.engine.values.ValueFactory;
176
import com.iver.andami.PluginServices;
177
import com.iver.andami.messages.NotificationManager;
178
import com.iver.andami.ui.mdiManager.IWindow;
179
import com.iver.andami.ui.mdiManager.SingletonWindow;
180
import com.iver.andami.ui.mdiManager.WindowInfo;
181
import com.iver.cit.gvsig.fmap.DriverException;
182
import com.iver.cit.gvsig.fmap.MapContext;
183
import com.iver.cit.gvsig.fmap.MapControl;
184
import com.iver.cit.gvsig.fmap.ViewPort;
185
import com.iver.cit.gvsig.fmap.core.DefaultFeature;
186
import com.iver.cit.gvsig.fmap.core.FPoint2D;
187
import com.iver.cit.gvsig.fmap.core.FShape;
188
import com.iver.cit.gvsig.fmap.core.IGeometry;
189
import com.iver.cit.gvsig.fmap.core.ShapeFactory;
190
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
191
import com.iver.cit.gvsig.fmap.edition.EditionException;
192
import com.iver.cit.gvsig.fmap.layers.FLayer;
193
import com.iver.cit.gvsig.fmap.layers.FLayers;
194
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
195
import com.iver.cit.gvsig.fmap.layers.LayerEvent;
196
import com.iver.cit.gvsig.fmap.layers.LayerFactory;
197
import com.iver.cit.gvsig.fmap.layers.LayerListenerAdapter;
198
import com.iver.cit.gvsig.fmap.layers.ReadableVectorial;
199
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
200
import com.iver.cit.gvsig.fmap.layers.SingleLayerIterator;
201
import com.iver.cit.gvsig.graph.GraphException;
202
import com.iver.cit.gvsig.graph.NetworkUtils;
203
import com.iver.cit.gvsig.graph.core.GvFlag;
204
import com.iver.cit.gvsig.graph.core.IFlagListener;
205
import com.iver.cit.gvsig.graph.core.Network;
206
import com.iver.cit.gvsig.graph.solvers.FlagsMemoryDriver;
207
import com.iver.cit.gvsig.graph.solvers.Route;
208
import com.iver.cit.gvsig.graph.solvers.RouteMemoryDriver;
209
import com.iver.cit.gvsig.graph.tools.FlagListener;
210
import com.iver.cit.gvsig.project.documents.gui.FOpenDialog;
211
import com.iver.cit.gvsig.project.documents.view.gui.IView;
212
import com.iver.cit.gvsig.project.documents.view.gui.View;
213
import com.iver.cit.gvsig.util.GvSession;
214
import com.vividsolutions.jts.geom.Coordinate;
215
import com.vividsolutions.jts.geom.Geometry;
216
import com.vividsolutions.jts.geom.MultiPoint;
217
import com.vividsolutions.jts.geom.Point;
218

    
219
public class RouteControlPanel extends JPanel implements SingletonWindow,
220
                ActionListener, IFlagListener {
221
        WindowInfo wi;
222

    
223
        private JPanel westPanel = null;
224

    
225
        private JScrollPane scrlStages = null;
226

    
227
        private JTable tblStages = null;
228

    
229
        private GridBagLayoutPanel eastPanel = null;
230

    
231
        private MyTableModel tableModel = new MyTableModel(); // @jve:decl-index=0:visual-constraint=""
232

    
233
        private JButton btnLoadStage = null;
234

    
235
        private JButton btnSaveStage = null;
236

    
237
        private Network network;
238

    
239
        private ArrayList routeFlags;
240

    
241
        private JLabel lblCost;
242

    
243
        private JLabel lblFlagAmout;
244

    
245
        private JButton btnPullDownStage;
246

    
247
        private JButton btnPushUpStage;
248

    
249
        private JButton btnRemoveStage;
250

    
251
        private JPanel southPanel;
252

    
253
        private final String[] colName = new String[] {
254
                        PluginServices.getText(this, "enable"),
255
                        PluginServices.getText(this, "stage"),
256
                        PluginServices.getText(this, "cost"), };
257

    
258
        private JButton btnCenterOnFlag;
259

    
260
        private JButton btnSaveRoute;
261

    
262
        private MapControl mapCtrl;
263

    
264
        private class MyTableModel extends AbstractTableModel {
265
                public int getColumnCount() {
266
                        return 3;
267
                }
268

    
269
                public int getRowCount() {
270
                        return _getFlags().size();
271
                }
272

    
273
                public Object getValueAt(int rowIndex, int columnIndex) {
274
                        GvFlag flag = (GvFlag) _getFlags().get(rowIndex);
275
                        switch (columnIndex) {
276
                        case 0:
277
                                return new Boolean(flag.isEnabled());
278
                        case 1:
279
                                return flag.getDescription();
280
                        case 2:
281
                                return new Double(flag.getCost());
282
                        }
283

    
284
                        return null;
285
                }
286

    
287
                public Class getColumnClass(int columnIndex) {
288
                        switch (columnIndex)
289
                        {
290
                        case 0:
291
                                return Boolean.class;
292
                        case 1:
293
                                return String.class;
294
                        case 2:
295
                                return Double.class;
296

    
297
                        }
298
                        return super.getColumnClass(columnIndex);
299
                }
300

    
301
                public String getColumnName(int column) {
302
                        return colName[column];
303
                }
304

    
305
                public boolean isCellEditable(int rowIndex, int columnIndex) {
306
                        if (columnIndex == 2)
307
                                return false;
308
                        return true;
309

    
310
                }
311

    
312
                public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
313
                        GvFlag flag = (GvFlag) _getFlags().get(rowIndex);
314
                        switch (columnIndex)
315
                        {
316
                        case 0:
317
                                Boolean bAux = (Boolean) aValue;
318
                                flag.setEnabled(bAux.booleanValue());
319
                                PluginServices.getMainFrame().enableControls();
320
                                return;
321
                        case 1:
322
                                String strAux = (String) aValue;
323
                                flag.setDescription(strAux);
324
                                return;
325

    
326
//                        case 2: // No es editable
327
//                                Double dblAux = (Double) aValue;
328
//                                flag.setCost(dblAux.doubleValue());
329
//                                return;
330

    
331
                        }
332

    
333
                }
334

    
335
        }
336

    
337
        /**
338
         * This method initializes
339
         *
340
         */
341
        public RouteControlPanel(Network network) {
342
                super();
343
                this.network = network;
344
//                GvFlag[] flags = network.getFlags();
345
//                List vflags = _getFlags();
346
//                for (int i = 0; i < flags.length; i++) {
347
//                        vflags.add(flags[i]);
348
//                }
349
                initialize();
350
        }
351

    
352
        /**
353
         * Method to remove all flags (use
354
         * */
355
        public void refresh(){
356
//                GvFlag[] flags = network.getFlags();
357
//                List vflags = _getFlags();
358
//                List tempFlags = Arrays.asList(flags);
359
//                vflags.addAll(tempFlags);
360
                lblFlagAmout.setText(String.valueOf(_getFlags()
361
                                .size()));
362
                updateTotalCost();
363
                getTblStages().revalidate();
364
                System.out.println("Actualizo tabla");
365

    
366
        }
367
        private void processLayer(FLayer layer) {
368
                if (layer.isActive()) {
369
                        if (layer instanceof FLyrVect) {
370
                                Network net = (Network) layer
371
                                                .getProperty("network");
372
                                if (net != null) {
373
                                        network = net;
374
                                        network.addFlagListener(this);
375
                                        refresh();
376
                                }// if
377
                        }// if
378
                }// if
379

    
380
        }
381

    
382
        public void setMapControl(MapControl mapCtrl, Network net) {
383
                if (mapCtrl != null) {
384
                        this.mapCtrl = mapCtrl;
385
                        LayerListenerAdapter listener = new LayerListenerAdapter() {
386
                                public void activationChanged(LayerEvent e) {
387
                                        processLayer(e.getSource());
388
                                }
389
                        };
390
                        mapCtrl.getMapContext().getLayers().addLayerListener(listener);
391
                        mapCtrl.getMapContext().getLayers().addLayerCollectionListener(
392
                                        listener);
393
                        if (net != null) {
394
                                network = net;
395
                                network.addFlagListener(this);
396
                        }
397
                }
398
        }
399

    
400
        public RouteControlPanel() {
401
                super();
402
                initialize();
403
        }
404

    
405
        public void setCostUnits(String unitsName) {
406
                colName[2] = unitsName;
407
                getTblStages().repaint();
408
        }
409

    
410
        /**
411
         * This method initializes this
412
         *
413
         */
414
        private void initialize() {
415
                BorderLayout borderLayout = new BorderLayout();
416
                borderLayout.setHgap(10);
417
                borderLayout.setVgap(10);
418
                JPanel cont = new JPanel(borderLayout);
419
//                cont.setPreferredSize(new Dimension(490, 320));
420
                this.setPreferredSize(new Dimension(460, 280));
421
                cont.add(getWestPanel(), BorderLayout.CENTER);
422
                cont.add(getEastPanel(), BorderLayout.EAST);
423
                cont.add(getSouthPanel(), BorderLayout.SOUTH);
424
                this.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 10));
425
                this.add(cont);
426
                updateFlags();
427
        }
428

    
429
        private void updateFlags() {
430
                lblFlagAmout.setText(String.valueOf(_getFlags().size()));
431
                updateTotalCost();
432
                getTblStages().repaint();
433
        }
434

    
435
        private JPanel getSouthPanel() {
436
                if (southPanel == null) {
437
                        southPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
438
                        southPanel.add(getBtnRemoveStage());
439
                        southPanel.add(new JBlank(50, 20));
440
                        southPanel.add(getBtnPushUpStage());
441
                        southPanel.add(getBtnPullDownStage());
442
                        southPanel.add(new JLabel(PluginServices.getText(this,
443
                                        "flag_amount")));
444
                        lblFlagAmout = new JLabel();
445
                        lblFlagAmout.setFont(lblFlagAmout.getFont().deriveFont(Font.BOLD));
446
                        southPanel.add(lblFlagAmout);
447
                }
448
                return southPanel;
449
        }
450

    
451
        public Object getWindowModel() {
452
                return this.getClass();
453
        }
454

    
455
        public WindowInfo getWindowInfo() {
456
                if (wi == null) {
457
                        wi = new WindowInfo(WindowInfo.MODELESSDIALOG
458
                                    | WindowInfo.MAXIMIZABLE
459
                                        | WindowInfo.ICONIFIABLE | WindowInfo.PALETTE);
460
                        wi.setWidth((int) this.getPreferredSize().getWidth());
461
                        wi.setHeight((int) this.getPreferredSize().getHeight());
462
                        wi.setTitle(PluginServices.getText(this, "route_control_panel"));
463
                }
464
                return wi;
465
        }
466

    
467
        /**
468
         * This method initializes westPanel
469
         *
470
         * @return javax.swing.JPanel
471
         */
472
        private JPanel getWestPanel() {
473
                if (westPanel == null) {
474
                        westPanel = new JPanel(new BorderLayout(5, 5));
475
                        lblCost = new JLabel();
476
                        lblCost.setFont(lblCost.getFont().deriveFont(Font.BOLD));
477
                        GridBagLayoutPanel aux = new GridBagLayoutPanel();
478
                        aux.addComponent(PluginServices.getText(this, "total_route_cost")
479
                                        + ":", lblCost);
480
                        aux.addComponent(getScrlStages());
481

    
482
                        westPanel.add(aux);
483
                }
484
                return westPanel;
485
        }
486

    
487
        private JButton getBtnPullDownStage() {
488
                if (btnPullDownStage == null) {
489
                        btnPullDownStage = new JButton(new ImageIcon(this.getClass()
490
                                        .getClassLoader().getResource("images/down-arrow.png")));
491
                        // btnPullDownStage.setName("btnPullDownStage");
492
                        btnPullDownStage.addActionListener(this);
493
                }
494
                return btnPullDownStage;
495
        }
496

    
497
        private JButton getBtnPushUpStage() {
498
                if (btnPushUpStage == null) {
499
                        btnPushUpStage = new JButton(new ImageIcon(this.getClass()
500
                                        .getClassLoader().getResource("images/up-arrow.png")));
501
                        // btnPushUpStage.setName("btnPushUpStage");
502
                        btnPushUpStage.addActionListener(this);
503
                }
504
                return btnPushUpStage;
505
        }
506

    
507
        private JButton getBtnRemoveStage() {
508
                if (btnRemoveStage == null) {
509
                        btnRemoveStage = new JButton(new ImageIcon(this.getClass()
510
                                        .getClassLoader().getResource("images/delete.png")));
511
                        // btnRemoveStage.setName("btnRemoveStage");
512
                        btnRemoveStage.addActionListener(this);
513
                }
514
                return btnRemoveStage;
515
        }
516

    
517
        /**
518
         * This method initializes scrlStages
519
         *
520
         * @return javax.swing.JScrollPane
521
         */
522
        private JScrollPane getScrlStages() {
523
                if (scrlStages == null) {
524
                        scrlStages = new JScrollPane();
525
                        scrlStages.setViewportView(getTblStages());
526
                        scrlStages.setPreferredSize(new Dimension(270, 200));
527
                }
528
                return scrlStages;
529
        }
530

    
531
        /**
532
         * @deprecated
533
         * @param flag
534
         */
535
        public void addFlag(GvFlag flag) {
536
                _getFlags().add(flag);
537
                lblFlagAmout.setText(String.valueOf(_getFlags().size()));
538
                updateTotalCost();
539
                getTblStages().repaint();
540
        }
541

    
542
        private void updateTotalCost() {
543
                GvFlag[] flags = getFlags();
544
                double cost = 0;
545
                for (int i = 0; i < flags.length; i++) {
546
                        if (!flags[i].isEnabled())
547
                                continue;
548
                        if (flags[i].getCost() >= Double.MAX_VALUE)
549
                        {
550
                                lblCost.setText(PluginServices.getText(this, "no_se_puede_pasar_por_todas_las_paradas"));
551
                                return;
552
                        }
553
                        if (flags[i].getCost() < 0)
554
                        {
555
                                lblCost.setText(PluginServices.getText(this, "solucion_no_valida"));
556
                                return;
557
                        }
558
                                
559
                        cost += flags[i].getCost();
560
                }
561
                NumberFormat nf = NumberFormat.getInstance();
562
                nf.setMaximumFractionDigits(2);
563
                lblCost.setText(nf.format(cost) + getCostUnitName());
564
        }
565

    
566
        private String getCostUnitName() {
567
                if (colName[2].equals(PluginServices.getText(this, "cost")))
568
                        return "";
569
                return colName[2];
570
        }
571

    
572
        public void removeFlag(GvFlag flag) {
573
                removeFlag(_getFlags().indexOf(flag));
574
        }
575

    
576
        public void removeFlag(int index) {
577
                _getFlags().remove(index);
578
                lblFlagAmout.setText(String.valueOf(_getFlags().size()));
579
                getTblStages().repaint();
580
        }
581

    
582
        /**
583
         * This method initializes tblStages
584
         *
585
         * @return javax.swing.JTable
586
         */
587
        private JTable getTblStages() {
588
                if (tblStages == null) {
589
                        tblStages = new JTable();
590
                        tblStages
591
                                        .setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
592
                        tblStages.setModel(getTableModel());
593
                        TableColumnModel cm = tblStages.getColumnModel();
594

    
595
                        int tablePreferredWidth = (int) tblStages.getPreferredSize()
596
                                        .getWidth();
597
                        int colSize = tblStages.getFontMetrics(tblStages.getFont())
598
                                        .stringWidth(tblStages.getModel().getColumnName(0)) * 2;
599
                        cm.getColumn(0).setPreferredWidth((int) (colSize));
600
                        cm.getColumn(0).setMinWidth((int) (colSize));
601
                        cm.getColumn(0).setMaxWidth((int) (colSize));
602
                        tablePreferredWidth -= colSize;
603
                        cm.getColumn(1)
604
                                        .setPreferredWidth((int) (tablePreferredWidth * 0.7));
605
                        cm.getColumn(2)
606
                                        .setPreferredWidth((int) (tablePreferredWidth * 0.3));
607

    
608
                        // Ask to be notified of selection changes.
609
                        ListSelectionModel rowSM = tblStages.getSelectionModel();
610
                        rowSM.addListSelectionListener(new ListSelectionListener() {
611
                            public void valueChanged(ListSelectionEvent e) {
612
                                //Ignore extra messages.
613
                                if (e.getValueIsAdjusting()) return;
614

    
615
                                ListSelectionModel lsm =
616
                                    (ListSelectionModel)e.getSource();
617
                                getBtnCenterOnFlag().setEnabled(!lsm.isSelectionEmpty());
618
                            }
619
                        });
620
                        
621
                        tblStages.getModel().addTableModelListener(new TableModelListener() {
622

    
623
                                public void tableChanged(TableModelEvent e) {
624
                                        System.out.println("Table model changed");
625
                                        
626
                                }
627
                                
628
                        });
629

    
630
                        
631
                }
632
                return tblStages;
633
        }
634

    
635
        protected int getFlagCount() {
636
                return _getFlags().size();
637
        }
638

    
639
        private List _getFlags() {
640
//                if (routeFlags == null) {
641
//                        routeFlags = new ArrayList();
642
//                }
643
//                return routeFlags;
644

    
645
                return network.getOriginaFlags();
646
        }
647

    
648
        protected boolean isSelected(int row) {
649
                return ((GvFlag) _getFlags().get(row)).isEnabled();
650
        }
651

    
652
        /**
653
         * This method initializes eastPanel
654
         *
655
         * @return javax.swing.JPanel
656
         */
657
        private JPanel getEastPanel() {
658
                if (eastPanel == null) {
659
                        GridLayout layout = new GridLayout();
660
                        layout.setColumns(1);
661
                        layout.setVgap(5);
662
                        JPanel aux = new JPanel();
663
                        aux.add(getBtnLoadStage());
664
                        aux.add(getBtnSaveStage());
665
                        aux.add(getBtnSaveRoute());
666
                        aux.add(getBtnCenterOnFlag());
667
                        layout.setRows(aux.getComponentCount());
668
                        aux.setLayout(layout);
669
                        eastPanel = new GridBagLayoutPanel();
670
                        eastPanel.addComponent(aux);
671
                }
672
                return eastPanel;
673
        }
674

    
675
        private JButton getBtnCenterOnFlag() {
676
                if (btnCenterOnFlag == null) {
677
                        btnCenterOnFlag = new JButton();
678
                        btnCenterOnFlag.setText(PluginServices.getText(this,
679
                                        "center_on_flag"));
680
                        btnCenterOnFlag.setEnabled(false);
681
                        btnCenterOnFlag.addActionListener(this);
682
                }
683
                return btnCenterOnFlag;
684
        }
685

    
686
        private JButton getBtnSaveRoute() {
687
                if (btnSaveRoute == null) {
688
                        btnSaveRoute = new JButton();
689
                        btnSaveRoute.setText(PluginServices.getText(this, "save_route"));
690
                        btnSaveRoute.addActionListener(this);
691
                }
692
                return btnSaveRoute;
693
        }
694

    
695
        /**
696
         * This method initializes defaultTableModel
697
         *
698
         * @return javax.swing.table.DefaultTableModel
699
         */
700
        private TableModel getTableModel() {
701
                return tableModel;
702
        }
703

    
704
        /**
705
         * This method initializes btnLoadStage
706
         *
707
         * @return javax.swing.JButton
708
         */
709
        private JButton getBtnLoadStage() {
710
                if (btnLoadStage == null) {
711
                        btnLoadStage = new JButton();
712
                        btnLoadStage.setText(PluginServices.getText(this, "load_stages"));
713
                        btnLoadStage.addActionListener(this);
714
                }
715
                return btnLoadStage;
716
        }
717

    
718
        /**
719
         * This method initializes btnSaveStages
720
         *
721
         * @return javax.swing.JButton
722
         */
723
        private JButton getBtnSaveStage() {
724
                if (btnSaveStage == null) {
725
                        btnSaveStage = new JButton();
726
                        btnSaveStage.setText(PluginServices.getText(this, "save_stages"));
727
                        btnSaveStage.addActionListener(this);
728
                }
729
                return btnSaveStage;
730
        }
731

    
732
        class FormatSelectionPanel extends JPanel implements IWindow {
733

    
734
                JComboBox formats;
735
                WindowInfo wi = null;
736

    
737
                public FormatSelectionPanel(String introductoryText) {
738
                        super(new BorderLayout());
739
                        String[] formatos = { "SHP", "DXF", "POSTGIS", "GML" };
740
                        formats = new JComboBox(formatos);
741
                        GridBagLayoutPanel contentPanel =
742
                                new GridBagLayoutPanel();
743
                        contentPanel.addComponent(new JLabel(introductoryText));
744
                        contentPanel.addComponent(formats);
745
                        JButton okButton = new JButton(PluginServices.getText(null,
746
                                        "Aceptar"));
747
                        okButton.addActionListener(new ActionListener() {
748
                                public void actionPerformed(ActionEvent arg0) {
749
                                        close();
750
                                }
751
                        });
752
                        contentPanel.addComponent(okButton);
753

    
754
                        add(contentPanel);
755
                }
756

    
757
                void close() {
758
                        PluginServices.getMDIManager().closeWindow(this);
759
                }
760

    
761
                public String getSelectedFormat() {
762
                        return (String) formats.getSelectedItem();
763
                }
764

    
765
                public WindowInfo getWindowInfo() {
766
                        if (wi == null) {
767
                                wi = new WindowInfo(WindowInfo.MODALDIALOG | WindowInfo.PALETTE);
768
                                wi.setTitle(PluginServices
769
                                                .getText(null, "Seleccion_de_formato"));// Internacionalizar
770
                                                                                                                                // esto
771
                                wi.setWidth(300);
772
                                wi.setHeight(55);
773
                        }
774
                        return wi;
775
                }
776

    
777
        }
778

    
779
        public void actionPerformed(ActionEvent e) {
780
                Component c = (Component) e.getSource();
781
                if (c.equals(getBtnLoadStage())) {
782
                        loadStages();
783
                } else if (c.equals(getBtnSaveStage())) {
784
                        saveStage();
785
                } else if (c.equals(getBtnPushUpStage())) {
786
                        int[] selected = tblStages.getSelectedRows();
787
                        if (selected.length == 0 || selected[0] == 0)
788
                                return;
789
                        tblStages.clearSelection();
790
                        for (int i = 0; i < selected.length; i++) {
791
                                Object aux = _getFlags().get(selected[i] - 1);
792
                                _getFlags().set(selected[i] - 1, _getFlags().get(selected[i]));
793
                                _getFlags().set(selected[i], aux);
794
                                selected[i]--;
795
                                tblStages.addRowSelectionInterval(selected[i], selected[i]);
796
                        }
797
                        invalidateSolution();
798
                } else if (c.equals(getBtnPullDownStage())) {
799
                        // pull down
800
                        int[] selected = tblStages.getSelectedRows();
801
                        if (selected.length == 0
802
                                        || selected[selected.length - 1] >= _getFlags().size() - 1)
803
                                return;
804

    
805
                        // move rows
806
                        tblStages.clearSelection();
807
                        for (int i = selected.length - 1; i >= 0; i--) {
808
                                Object aux = _getFlags().get(selected[i] + 1);
809
                                _getFlags().set(selected[i] + 1, _getFlags().get(selected[i]));
810
                                _getFlags().set(selected[i], aux);
811
                                selected[i]++;
812
                                tblStages.addRowSelectionInterval(selected[i], selected[i]);
813
                        }
814
                        invalidateSolution();
815

    
816
                } else if (c.equals(getBtnRemoveStage())) {
817
                        removeStage();                        
818
                } else if (c.equals(getBtnSaveRoute())) {
819
                        saveRoute();
820
                } else if (c.equals(getBtnCenterOnFlag())) {
821
                        // Center on first selected flag.
822
                        int[] selected = tblStages.getSelectedRows();
823
                        if (selected.length == 0)
824
                                return;
825
                        GvFlag flag = (GvFlag) _getFlags().get(selected[0]);
826
                        IWindow window = PluginServices.getMDIManager().getActiveWindow();
827
                        if(! (window instanceof IView))
828
                                return;
829
                        IView view = (IView) window;
830
                        ViewPort vp = view.getMapControl().getViewPort();
831
                        Rectangle2D extent = vp.getAdjustedExtent();
832
                        double xNC = flag.getOriginalPoint().getX();
833
                        double yNC = flag.getOriginalPoint().getY();
834
                        double width = extent.getWidth();
835
                        double height = extent.getHeight();
836
                        
837
                        Rectangle2D.Double r = new Rectangle2D.Double();
838
                        
839
                        r.width = width;
840
                        r.height = height;
841
                        r.x = xNC - width/2;
842
                        r.y = yNC - height/2;
843

    
844
                        vp.setExtent(r);
845

    
846
                        
847
                                
848
                }
849
                repaint();
850
        }
851

    
852
        private void invalidateSolution() {
853
                for (int i=0; i < _getFlags().size(); i++)
854
                {
855
                        GvFlag flag = (GvFlag) _getFlags().get(i);
856
                        flag.setCost(-1.0);
857
                }
858
                updateTotalCost();
859
        }
860

    
861
        private void saveStage(){
862
                if(network == null){
863
                        IWindow window = PluginServices.getMDIManager().getActiveWindow();
864
                        if(! (window instanceof IView))
865
                                return;
866
                        IView view = (View) window;
867
                        MapControl mapControl = view.getMapControl();
868
                        MapContext map = mapControl.getMapContext();
869
                        FLayers layers = map.getLayers();
870
                        SingleLayerIterator it = new SingleLayerIterator(layers);
871
                        while (it.hasNext() && network == null) {
872
                                FLayer aux = it.next();
873
                                if (!aux.isActive())
874
                                        continue;
875
                                network = (Network) aux.getProperty("network");
876
                        }
877
                }
878
                if (network == null)
879
                        return;
880

    
881
                List features = new ArrayList();
882
                GvFlag[] flags = network.getFlags();
883
                for(int i = 0; i < flags.length; i++){
884
                        GvFlag flag = flags[i];
885
                        // Solo se guardan los flags habilitados
886
                        if (!flag.isEnabled())
887
                                continue;
888
                        FPoint2D point = new FPoint2D(flag.getOriginalPoint());
889
                        Value[] values = new Value[6];
890
                        values[GvFlag.ID_FLAG_INDEX] = ValueFactory.createValue(flag.getIdFlag());
891
                        values[GvFlag.ID_ARC_INDEX] = ValueFactory.createValue(flag.getIdArc());
892
                        values[GvFlag.DESCRIPTION_INDEX] = ValueFactory.createValue(flag.getDescription());
893
                        values[GvFlag.DIREC_INDEX] = ValueFactory.createValue(flag.getDirec());
894
                        values[GvFlag.PCT_INDEX] = ValueFactory.createValue(flag.getPct());
895
                        values[GvFlag.COST_INDEX] = ValueFactory.createValue(flag.getCost());
896
                        IGeometry geo = ShapeFactory.createPoint2D(point);
897
                        DefaultFeature feature = new DefaultFeature(geo, values, new Integer(flag.getIdFlag()).toString() );
898
                        features.add(feature);
899
                }
900

    
901
                FlagsMemoryDriver driver = new FlagsMemoryDriver(features);
902
                IProjection projection = FOpenDialog.getLastProjection();
903
                FLyrVect routeLayer = (FLyrVect) LayerFactory.createLayer("Flags",
904
                                driver, projection);
905

    
906
                FormatSelectionPanel selectionPanel =
907
                        new FormatSelectionPanel(PluginServices.
908
                                        getText(null,
909
                                "Seleccione_un_formato_para_guardar_los_flags"));
910
                PluginServices.getMDIManager().addWindow(selectionPanel);
911

    
912
                String format = selectionPanel.getSelectedFormat();
913
                com.iver.cit.gvsig.ExportTo export = new com.iver.cit.gvsig.ExportTo();
914
                IWindow window = PluginServices.getMDIManager().getActiveWindow();
915
                if(! (window instanceof IView))
916
                        return;
917
                IView view = (View) window;
918
                MapControl mapControl = view.getMapControl();
919
                MapContext context = mapControl.getMapContext();
920
                try {
921
                        if (format.equalsIgnoreCase("SHP")) {
922
                                export.saveToShp(context, routeLayer);
923
                        } else if (format.equalsIgnoreCase("DXF")) {
924
                                export.saveToDxf(context, routeLayer);
925
                        } else if (format.equalsIgnoreCase("GML")) {
926
                                export.saveToGml(context, routeLayer);
927
                        } else if (format.equalsIgnoreCase("POSTGIS")) {
928
                                export.saveToPostGIS(context, routeLayer);
929
                        }
930
                } catch (EditionException e1) {
931
                        // TODO Auto-generated catch block
932
                        e1.printStackTrace();
933
                } catch (DriverIOException e1) {
934
                        // TODO Auto-generated catch block
935
                        e1.printStackTrace();
936
                }
937

    
938
        }
939
        private void saveRoute() {
940
                IWindow window = PluginServices.getMDIManager().getActiveWindow();
941
                if(! (window instanceof IView))
942
                        return;
943
                IView view = (View) window;
944
                MapControl mapControl = view.getMapControl();
945
                List routes = (List) GvSession.getInstance().get(mapControl, "Route");
946
                if(routes == null || routes.size() == 0){
947
                        JOptionPane.showMessageDialog(this, PluginServices.getText(this, "Ruta_borrada_o_inexistente"),
948
                                        PluginServices.getText(this, "Ruta_no_encontrada"),
949
                                        JOptionPane.ERROR_MESSAGE);
950
                        return;
951
                }        
952
                Route lastRoute = (Route) routes.get(routes.size() - 1);
953
                RouteMemoryDriver driver = new RouteMemoryDriver(lastRoute.getFeatureList());
954
                IProjection projection = FOpenDialog.getLastProjection();
955
                FLyrVect routeLayer = (FLyrVect) LayerFactory.createLayer("Route",
956
                                driver, projection);
957

    
958
                FormatSelectionPanel selectionPanel = new FormatSelectionPanel(PluginServices.getText(null,
959
                "Seleccione_un_formato_para_guardar_la_ruta"));
960
                PluginServices.getMDIManager().addWindow(selectionPanel);
961

    
962
                String format = selectionPanel.getSelectedFormat();
963
                com.iver.cit.gvsig.ExportTo export = new com.iver.cit.gvsig.ExportTo();
964
                MapContext context = mapControl.getMapContext();
965
                try {
966
                        if (format.equalsIgnoreCase("SHP")) {
967
                                export.saveToShp(context, routeLayer);
968
                        } else if (format.equalsIgnoreCase("DXF")) {
969
                                export.saveToDxf(context, routeLayer);
970
                        } else if (format.equalsIgnoreCase("GML")) {
971
                                export.saveToGml(context, routeLayer);
972
                        } else if (format.equalsIgnoreCase("POSTGIS")) {
973
                                export.saveToPostGIS(context, routeLayer);
974
                        }
975
                } catch (EditionException e1) {
976
                        // TODO Auto-generated catch block
977
                        e1.printStackTrace();
978
                } catch (DriverIOException e1) {
979
                        // TODO Auto-generated catch block
980
                        e1.printStackTrace();
981
                }
982
        }
983

    
984
        /**
985
         * Converts a point layer loaded in the active view's toc in a collection of
986
         * flags of the active network
987
         *
988
         */
989
        private void loadStages() {
990

    
991
                IWindow window = PluginServices.getMDIManager().getActiveWindow();
992
                if(! (window instanceof IView))
993
                        return;
994
                IView view = (IView) window;
995
                MapControl mapControl = view.getMapControl();
996
                MapContext map = mapControl.getMapContext();
997
                FLayers layers = map.getLayers();
998

    
999
                String title = PluginServices.getText(this,
1000
                                "Seleccionar_capa_con_puntos_de_parada");
1001
                String introductoryText = PluginServices.getText(this,
1002
                                "Seleccione_una_capa_de_puntos_para_crear_paradas");
1003

    
1004
                LayerSelectionPanel selectionPanel = new LayerSelectionPanel(layers,
1005
                                title, introductoryText, FLyrVect.class, FShape.POINT);
1006
                PluginServices.getMDIManager().addWindow(selectionPanel);
1007

    
1008
                if (!selectionPanel.wasFinishPressed())
1009
                        return;
1010
                else {
1011
                        FLayer layer = selectionPanel.getLayer();
1012
                        if (layer == null)
1013
                                return;
1014
                        if (!(layer instanceof FLyrVect))
1015
                                return;
1016
                        FLyrVect vectLyr = (FLyrVect) layer;
1017

    
1018
                        try {
1019
                                if (vectLyr.getShapeType() != FShape.POINT)
1020
                                        return;
1021

    
1022
                                // TODO
1023
                                // Hay que refinar bastante, para que el usuario elija
1024
                                // con que red y con qu? capa lineal quiere trabajar
1025
                                // tal y como est?, si hubiese varias se trabajaria
1026
                                // con la primera que devuelva el iterador
1027

    
1028
                                Network net = null;
1029
                                SingleLayerIterator it = new SingleLayerIterator(layers);
1030
                                while (it.hasNext() && net == null) {
1031
                                        FLayer aux = it.next();
1032
                                        if (!aux.isActive())
1033
                                                continue;
1034
                                        net = (Network) aux.getProperty("network");
1035
                                }
1036
                                if (net == null)
1037
                                        return;
1038

    
1039
                                // Por si queremos a?adir paradas a otras ya existentes
1040
//                                _getFlags().clear();
1041
                                
1042
                                GvFlag flag;
1043
                                ReadableVectorial reader = vectLyr.getSource();
1044
                                SelectableDataSource recordset = vectLyr.getRecordset();
1045
                                int numShapes = reader.getShapeCount();
1046

    
1047
                                double realTol = mapCtrl.getViewPort()
1048
                                                .toMapDistance(FlagListener.pixelTolerance);
1049
                                reader.start();
1050
                                for (int i = 0; i < numShapes; i++) {
1051
                                        Geometry geo = reader.getShape(i).toJTSGeometry();
1052
                                        if (!((geo instanceof Point) || (geo instanceof MultiPoint)))
1053
                                                continue;
1054
                                        
1055
                                        
1056

    
1057
                                        Coordinate[] coords = geo.getCoordinates();
1058
                                        for (int j = 0; j < coords.length; j++) {
1059

    
1060
                                                try {
1061
                                                        flag = net.addFlag(coords[j].x, coords[j].y, realTol);
1062

    
1063
                                                // TODO: Create use a IFlagListener to do this
1064
                                                // inside flagsChanged. The best solution is
1065
                                                // to put all the code in RouteControlPanel
1066
                                                        NetworkUtils.addGraphicFlag(mapControl, flag);
1067
                                                } catch (GraphException e) {
1068
                                                        e.printStackTrace();
1069
                                                        NotificationManager.addError("No se puedo situar el registro " + i + 
1070
                                                                        "Por favor, compruebe que est? encima de la red.", e);
1071
                                                }
1072

    
1073
                                        } // for j
1074
                                } // for i
1075
                                reader.stop();
1076
                                mapControl.drawGraphics();
1077
                                PluginServices.getMainFrame().enableControls();
1078

    
1079
                        } catch (DriverException e1) {
1080
                                return;
1081
                        } catch (DriverIOException e2) {
1082
                                return;
1083
                        }
1084
                }
1085
        }
1086

    
1087
        /**
1088
         * Removes the selected flags in the component's table from: -the graphic
1089
         * layer of the active view -the active network -the own table
1090
         *
1091
         */
1092
        private void removeStage() {
1093
                int[] selected = tblStages.getSelectedRows();
1094

    
1095
                for (int i = selected.length - 1; i >= 0; i--) {
1096
                        try {
1097
                                // removeFlag(selected[i]);
1098
                                if (network != null) {
1099
                                        final GvFlag flag = (GvFlag) _getFlags().get(selected[i]);
1100
                                        NetworkUtils.clearFlagFromGraphics(mapCtrl, flag);
1101
                                        network.removeFlag(flag);
1102
                                        mapCtrl.repaint();
1103
                                }
1104
                        } catch (IndexOutOfBoundsException iobEx) {
1105
                        }
1106

    
1107
                }// for
1108
                tblStages.clearSelection();
1109
                invalidateSolution();
1110
                mapCtrl.drawMap(false);
1111
        }
1112

    
1113
        public GvFlag[] getFlags() {
1114
                return (GvFlag[]) _getFlags().toArray(new GvFlag[0]);
1115
        }
1116

    
1117
        public void flagsChanged(int reason) {
1118
                refresh();
1119
                mapCtrl.drawGraphics();
1120

    
1121
        }
1122
} // @jve:decl-index=0:visual-constraint="17,9"