Statistics
| Revision:

root / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / table / gui / Table.java @ 16775

History | View | Annotate | Download (38.2 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 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
package com.iver.cit.gvsig.project.documents.table.gui;
42

    
43
import java.awt.Color;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.event.FocusEvent;
47
import java.awt.event.FocusListener;
48
import java.awt.event.KeyAdapter;
49
import java.awt.event.KeyEvent;
50
import java.awt.event.KeyListener;
51
import java.awt.event.MouseAdapter;
52
import java.awt.event.MouseEvent;
53
import java.beans.PropertyChangeEvent;
54
import java.beans.PropertyChangeListener;
55
import java.io.IOException;
56
import java.sql.Types;
57
import java.util.BitSet;
58
import java.util.EventObject;
59

    
60
import javax.swing.DefaultCellEditor;
61
import javax.swing.DefaultListSelectionModel;
62
import javax.swing.JFrame;
63
import javax.swing.JLabel;
64
import javax.swing.JOptionPane;
65
import javax.swing.JPanel;
66
import javax.swing.JTextField;
67
import javax.swing.event.ChangeEvent;
68
import javax.swing.event.ListSelectionEvent;
69
import javax.swing.event.ListSelectionListener;
70
import javax.swing.table.AbstractTableModel;
71
import javax.swing.table.TableColumn;
72

    
73
import org.apache.log4j.Logger;
74

    
75
import com.hardcode.gdbms.driver.exceptions.ReadDriverException;
76
import com.hardcode.gdbms.driver.exceptions.WriteDriverException;
77
import com.hardcode.gdbms.engine.values.Value;
78
import com.hardcode.gdbms.engine.values.ValueFactory;
79
import com.iver.andami.PluginServices;
80
import com.iver.andami.messages.NotificationManager;
81
import com.iver.andami.ui.mdiFrame.MainFrame;
82
import com.iver.andami.ui.mdiManager.IWindowListener;
83
import com.iver.andami.ui.mdiManager.IWindowTransform;
84
import com.iver.andami.ui.mdiManager.SingletonWindow;
85
import com.iver.andami.ui.mdiManager.WindowInfo;
86
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileReadException;
87
import com.iver.cit.gvsig.exceptions.expansionfile.ExpansionFileWriteException;
88
import com.iver.cit.gvsig.exceptions.layers.CancelEditingLayerException;
89
import com.iver.cit.gvsig.exceptions.table.CancelEditingTableException;
90
import com.iver.cit.gvsig.exceptions.table.StartEditingTableException;
91
import com.iver.cit.gvsig.exceptions.table.StopEditingTableException;
92
import com.iver.cit.gvsig.exceptions.validate.ValidateRowException;
93
import com.iver.cit.gvsig.exceptions.visitors.StartWriterVisitorException;
94
import com.iver.cit.gvsig.fmap.MapContext;
95
import com.iver.cit.gvsig.fmap.core.DefaultRow;
96
import com.iver.cit.gvsig.fmap.core.IRow;
97
import com.iver.cit.gvsig.fmap.drivers.DriverIOException;
98
import com.iver.cit.gvsig.fmap.drivers.FieldDescription;
99
import com.iver.cit.gvsig.fmap.drivers.ITableDefinition;
100
import com.iver.cit.gvsig.fmap.edition.AfterFieldEditEvent;
101
import com.iver.cit.gvsig.fmap.edition.AfterRowEditEvent;
102
import com.iver.cit.gvsig.fmap.edition.BeforeFieldEditEvent;
103
import com.iver.cit.gvsig.fmap.edition.BeforeRowEditEvent;
104
import com.iver.cit.gvsig.fmap.edition.EditableAdapter;
105
import com.iver.cit.gvsig.fmap.edition.EditionEvent;
106
import com.iver.cit.gvsig.fmap.edition.IEditableSource;
107
import com.iver.cit.gvsig.fmap.edition.IEditionListener;
108
import com.iver.cit.gvsig.fmap.edition.IRowEdited;
109
import com.iver.cit.gvsig.fmap.edition.ISpatialWriter;
110
import com.iver.cit.gvsig.fmap.edition.IWriteable;
111
import com.iver.cit.gvsig.fmap.edition.IWriter;
112
import com.iver.cit.gvsig.fmap.edition.VectorialEditableAdapter;
113
import com.iver.cit.gvsig.fmap.edition.commands.CommandListener;
114
import com.iver.cit.gvsig.fmap.layers.FLayer;
115
import com.iver.cit.gvsig.fmap.layers.FLyrVect;
116
import com.iver.cit.gvsig.fmap.layers.SelectableDataSource;
117
import com.iver.cit.gvsig.fmap.layers.SelectionEvent;
118
import com.iver.cit.gvsig.fmap.layers.SelectionListener;
119
import com.iver.cit.gvsig.project.documents.table.EditionTable;
120
import com.iver.cit.gvsig.project.documents.table.ProjectTable;
121
import com.iver.cit.gvsig.project.documents.table.gui.tablemodel.ColumnModel;
122
import com.iver.cit.gvsig.project.documents.table.gui.tablemodel.DataSourceDataModel;
123
import com.iver.utiles.swing.jtable.FieldSelectionEvent;
124
import com.iver.utiles.swing.jtable.FieldSelectionListener;
125
import com.iver.utiles.swing.jtable.SelectionHeaderSupport;
126

    
127
/**
128
 * DOCUMENT ME!
129
 *
130
 * @author Fernando Gonz?lez Cort?s
131
 */
132
public class Table extends JPanel implements SingletonWindow, EditionTable,
133
    IWindowListener,CommandListener, IWindowTransform, IEditionListener {
134
    private static Logger logger = Logger.getLogger(Table.class.getName());
135
    private javax.swing.JScrollPane jScrollPane = null;
136
    protected javax.swing.JTable table = null;
137
    protected ProjectTable model = null;
138
    protected JLabel jLabelStatus = null;
139
    protected MapContext fmap;
140
    protected boolean updating = false;
141
    private TableSelectionListener selectionListener = new TableSelectionListener();
142
    private long numReg = 0;
143
    protected SelectionHeaderSupport headerSelectionSupport = new SelectionHeaderSupport();
144
//    private long[] orderIndexes = null;
145
    private long[] orderIndexesInverted = null;
146
    private IRow[] rowsCopied = null;
147
    private WindowInfo m_viewInfo = null;
148
        private boolean isPalette=false;
149
//        private String[] antAliases;
150
//        private int[] antMapping;
151
//        private FBitSet oldSelection;
152
        /**
153
     * This is the default constructor
154
     */
155
    public Table() {
156
        super();
157
        initialize();
158
    }
159

    
160
    /**
161
     * DOCUMENT ME!
162
     *
163
     * @return DOCUMENT ME!
164
     */
165
    public ProjectTable getModel() {
166
        return model;
167
    }
168

    
169
    /**
170
     * DOCUMENT ME!
171
     *
172
     * @return DOCUMENT ME!
173
     */
174
    public BitSet getSelectedFieldIndices() {
175
            BitSet bs=headerSelectionSupport.getSelectedColumns();
176
            return bs;
177
    }
178

    
179
    /**
180
     * DOCUMENT ME!
181
     *
182
     * @return DOCUMENT ME!
183
     */
184
    public int[] getSelectedRowIndices() {
185
        return getTable().getSelectedRows();
186
    }
187

    
188
    /**
189
     * DOCUMENT ME!
190
     */
191
    protected void refreshControls() {
192
        try {
193
            MainFrame mF = PluginServices.getMainFrame();
194

    
195
            if (mF != null) {
196
                PluginServices.getMDIManager().getWindowInfo(Table.this).setTitle(PluginServices.getText(
197
                        this, "Tabla") + ": " + model.getName());
198
            }
199

    
200
            if (model.getAssociatedTable() != null) {
201
                this.fmap = ((FLayer) model.getAssociatedTable()).getMapContext();
202
            } else {
203
                this.fmap = null;
204
            }
205

    
206
            SelectableDataSource dataSource = model.getModelo().getRecordset();
207
            dataSource.mapExternalFields();
208
            logger.debug("dataSource.start()");
209
            dataSource.start();
210

    
211
            ColumnModel cm=new ColumnModel(model);
212
            getTable().setColumnModel(cm);
213

    
214
            AbstractTableModel dataModel = new DataSourceDataModel(model);
215

    
216
            getModel().createAlias();
217

    
218
            getTable().setModel(dataModel);
219

    
220
            TableColumn column = null;
221
                        for (int i = 0; i < model.getMapping().length; i++) {
222
                            column = table.getColumnModel().getColumn(i);
223
                            int w=model.getColumn(i).getWidth();
224
                            column.setPreferredWidth(w); //sport column is bigger
225
//                            System.err.println("Table.Dentro de refreshControls. column=" + column.toString());
226

    
227
                        }
228

    
229
            for (int i=0;i<dataModel.getColumnCount();i++) {
230
                    if (getModel().getModelo().getRecordset().getFieldType(i)==Types.STRUCT) {
231
                            TableColumn tc=getTable().getColumnModel().getColumn(i);
232
                        ValueComplexRenderer vcr=new ValueComplexRenderer();
233
                            tc.setCellRenderer(vcr);
234
                            ValueComplexEditor vce=new ValueComplexEditor();
235
                            tc.setCellEditor(vce);
236
                    }
237
            }
238
                        headerSelectionSupport.setTableHeader(getTable().getTableHeader());
239
            headerSelectionSupport.addFieldSelectionListener(new FieldSelectionListener() {
240
                    public void fieldSelected(FieldSelectionEvent e) {
241
                        if (PluginServices.getMainFrame() != null) {
242
                            PluginServices.getMainFrame().enableControls();
243
                        }
244
                    }
245
                });
246

    
247
            model.getModelo().getRecordset().addSelectionListener(selectionListener);
248

    
249
            updateSelection();
250
        } catch (ReadDriverException e) {
251
                  NotificationManager.addError("No se pudo leer la informaci?n", e);
252
                }
253
    }
254

    
255
    /**
256
     * DOCUMENT ME!
257
     *
258
     * @param table DOCUMENT ME!
259
     */
260
    public void setModel(ProjectTable table) {
261
        model = table;
262

    
263
        //Gesti?n del nombre de la ventana
264
        model.addPropertyChangeListener(new PropertyChangeListener() {
265
                public void propertyChange(PropertyChangeEvent evt) {
266
                    if (evt.getPropertyName().equals("name")) {
267
                        PluginServices.getMDIManager().getWindowInfo(Table.this)
268
                                      .setTitle(PluginServices.getText(this,
269
                                "Tabla") + ": " + (String) evt.getNewValue());
270
                    } else if (evt.getPropertyName().equals("model")) {
271
                        refreshControls();
272
                    }
273
                }
274
            });
275

    
276
        IEditableSource ies=getModel().getModelo();
277
        ies.addEditionListener(this);
278

    
279
        refreshControls();
280

    
281

    
282
    }
283
    /**
284
     *
285
     */
286
    public void updateSelection() {
287
        updating = true;
288
        try {
289
            DefaultListSelectionModel sm = (DefaultListSelectionModel) getTable()
290
                                                                           .getSelectionModel();
291
            sm.clearSelection();
292

    
293
            BitSet bs = (model.getModelo().getRecordset()).getSelection();
294
            sm.setValueIsAdjusting(true);
295

    
296
            if (model.getOrderIndexes() != null) {
297
                    if (orderIndexesInverted==null) {
298
                        orderInverter(model.getOrderIndexes());
299
                }
300
                for (int i = 0; i < model.getOrderIndexes().length; i++) {
301
                    if (bs.get(i)) {
302
                        sm.addSelectionInterval((int) orderIndexesInverted[i],
303
                            (int) orderIndexesInverted[i]);
304
                        if (isEditing())
305
                                table.setEditingRow((int)orderIndexesInverted[i]);
306
                    }
307
                }
308
            } else {
309
                    for (int i = bs.nextSetBit(0); i >= 0;
310
                             i = bs.nextSetBit(i + 1)) {
311
                         sm.addSelectionInterval(i, i);
312
                         if (isEditing())
313
                                  table.setEditingRow(i);
314
                    }
315
            }
316

    
317
            sm.setValueIsAdjusting(false);
318
            numReg = model.getModelo().getRowCount();
319

    
320
            jLabelStatus.setText(" " +
321
                (model.getModelo().getRecordset()).getSelection()
322
                 .cardinality() + " / " + numReg + " " +
323
                PluginServices.getText(this, "registros_seleccionados_total") +
324
                ".");
325
            if (PluginServices.getMainFrame() != null)
326
                    PluginServices.getMainFrame().enableControls();
327
        } catch (ReadDriverException e) {
328
                        // TODO Auto-generated catch block
329
                        e.printStackTrace();
330
                }
331
        updating = false;
332
    }
333

    
334
    /**
335
     * This method initializes this
336
     */
337
    protected void initialize() {
338
        jLabelStatus = new JLabel();
339
        setLayout(new java.awt.BorderLayout());
340
        jLabelStatus.setText("");
341
        jLabelStatus.setName("");
342
        jLabelStatus.setPreferredSize(new java.awt.Dimension(100, 18));
343
        add(getJScrollPane(), java.awt.BorderLayout.CENTER);
344
        this.add(jLabelStatus, java.awt.BorderLayout.SOUTH);
345
        this.setPreferredSize(new Dimension(300,200));
346
    }
347

    
348
    /**
349
     * This method initializes table
350
     *
351
     * @return javax.swing.JTable
352
     */
353
    public javax.swing.JTable getTable() {
354
        if (table == null) {
355
            table = new javax.swing.JTable();
356
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
357
            table.setSelectionModel(new DefaultListSelectionModel());
358
//            table.getTableHeader().addMouseListener(new MouseHandler());
359
            table.addKeyListener(new TableKeyListener());
360
            table.addMouseListener(new MouseRow());
361
            table.setSelectionForeground(Color.blue);
362
                    table.setSelectionBackground(Color.yellow);
363
                    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
364
                    public void valueChanged(ListSelectionEvent e) {
365

    
366
                            if (updating) {
367
                                 return;
368
                        }
369

    
370
                        SelectableDataSource dataModel = null;
371

    
372
                        try {
373
                            dataModel = Table.this.model.getModelo()
374
                                                        .getRecordset();
375
                        } catch (ReadDriverException e1) {
376
                                                        e1.printStackTrace();
377
                                                }
378

    
379
                        DefaultListSelectionModel model = (DefaultListSelectionModel) table.getSelectionModel();
380
                        BitSet selection = dataModel.getSelection();
381
                        int firstIndex=e.getFirstIndex();
382
                        if (firstIndex >= 0) {
383
                                                                for (int i = firstIndex; i <= e.getLastIndex(); i++) {
384
                                                                        if (Table.this.model.getOrderIndexes() != null) {
385
                                                                                selection.set((int) Table.this.model
386
                                                                                                .getOrderIndexes()[i], model
387
                                                                                                .isSelectedIndex(i));
388
                                                                        } else {
389
                                                                                selection.set(i, model
390
                                                                                                .isSelectedIndex(i));
391
                                                                        }
392
                                                                }
393
                                                        }
394
                        if (e.getValueIsAdjusting() == false) {
395
                            if (fmap != null) {
396
                                fmap.endAtomicEvent();
397
                            }
398

    
399
                            dataModel.fireSelectionEvents();
400
                        } else {
401
                            if (fmap != null) {
402
                                fmap.beginAtomicEvent();
403
                            }
404
                        }
405

    
406
                        jLabelStatus.setText(" " + selection.cardinality() +
407
                            " / " + numReg + " " +
408
                            PluginServices.getText(this,
409
                                "registros_seleccionados_total") + ".");
410

    
411
                    }
412
                });
413

    
414
                       JTextField tf=new JTextField();
415
                       tf.addFocusListener(new FocusListener() {
416
                          public void focusGained(FocusEvent e) {
417
                                // TODO Auto-generated method stub
418

    
419
                        }
420
                          public void focusLost(FocusEvent e) {
421
                                  table.editingStopped(new ChangeEvent(table));
422
                        }
423
                   });
424
                    table.setDefaultEditor(Object.class, new DefaultEditor(tf));
425
//            table.setDefaultEditor(String.class, new DefaultEditor(tf));
426
//            table.setDefaultEditor(Object.class, new DefaultEditor(tf));
427
//            table.setDefaultEditor(BooleanValue.class,new BooleanTableCellEditor(table));
428
//            table.setDefaultEditor(StringValue.class,new DefaultCellEditor(tf));
429
//            table.setDefaultEditor(Number.class,new IntegerTableCellEditor());
430

    
431
        }
432

    
433
        return table;
434
    }
435
    protected class DefaultEditor extends DefaultCellEditor{
436
                public Component getTableCellEditorComponent(javax.swing.JTable table,
437
                                Object value, boolean isSelected, int row, int column) {
438
                        JTextField tf=(JTextField)super.getTableCellEditorComponent(table, value, isSelected,
439
                                        row, column);
440
                        if (isSelected){
441
                                tf.setBackground(new Color(230,220,220));
442
                                tf.selectAll();
443

    
444
                        }
445
                        return tf;
446
                }
447

    
448
                public DefaultEditor(JTextField tf) {
449
                        super(tf);
450
                    tf.addMouseListener(new MouseRow());
451
                    getComponent().addKeyListener(new KeyAdapter() {
452
                                int keyPressed = 0;
453

    
454
                                public void keyPressed(KeyEvent ke) {
455
                                        if (ke.getKeyCode() != KeyEvent.VK_TAB)
456
                                                keyPressed++;
457
                                        JTextField tf = (JTextField) getComponent();
458

    
459

    
460
                                        if (ke.getKeyCode() == KeyEvent.VK_RIGHT
461
                                                        || ke.getKeyCode() == KeyEvent.VK_ENTER) {
462
                                                int caretPosition = tf.getCaretPosition();
463
                                                if (caretPosition >= tf.getText().length()) {
464
                                                        int x = table.getSelectedColumn();
465
                                                        int y = table.getSelectedRow();
466
                                                        if (x + 1 >= table.getColumnCount()) {
467
                                                                x = 0;
468
                                                                y++;
469
                                                        } else {
470
                                                                x++;
471
                                                        }
472
                                                        getComponent().setEnabled(false);
473
                                                }
474

    
475
                                        } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
476
                                                int caretPosition = tf.getCaretPosition();
477
                                                if (caretPosition <= 0) {
478
                                                        int x = table.getSelectedColumn();
479
                                                        int y = table.getSelectedRow();
480
                                                        if (x == 0) {
481
                                                                x = table.getColumnCount() - 1;
482
                                                                if (y - 1 < 0)
483
                                                                        y = table.getRowCount() - 1;
484
                                                                else
485
                                                                        y--;
486
                                                        } else {
487
                                                                x--;
488
                                                        }
489
                                                        getComponent().setEnabled(false);
490
                                                }
491

    
492
                                        }
493
                                }
494

    
495
                                public void keyReleased(KeyEvent ke) {
496
                                        keyPressed--;
497
                                        if (keyPressed < 0)
498
                                                keyPressed = 0;
499
                                        getComponent().setEnabled(true);
500
                                }
501
                        });
502

    
503
                }
504

    
505
                public Object getCellEditorValue() {
506
                        String s = ((JTextField) (DefaultEditor.this.getComponent()))
507
                                        .getText();
508
                        getComponent().setEnabled(true);
509
                        return s;
510
                }
511

    
512
                public boolean isCellEditable(EventObject event) {
513
                        // IF NUMBER OF CLICKS IS LESS THAN THE CLICKCOUNTTOSTART RETURN
514
                        // FALSE
515
                        // FOR CELL EDITING.
516
                        if (event instanceof MouseEvent) {
517
                                return ((MouseEvent) event).getClickCount() >= getClickCountToStart();
518
                        }
519

    
520
                        return true;
521
                }
522
        }
523

    
524

    
525

    
526
    /**
527
         * This method initializes jScrollPane
528
         *
529
         * @return javax.swing.JScrollPane
530
         */
531
    protected javax.swing.JScrollPane getJScrollPane() {
532
        if (jScrollPane == null) {
533
            jScrollPane = new javax.swing.JScrollPane();
534
            jScrollPane.setViewportView(getTable());
535
        }
536

    
537
        return jScrollPane;
538
    }
539

    
540
    /**
541
         * @see com.iver.mdiApp.ui.MDIManager.SingletonWindow#getWindowModel()
542
         */
543
    public Object getWindowModel() {
544
        return model;
545
    }
546

    
547
    /**
548
         * This method is used to get <strong>an initial</strong> ViewInfo object
549
         * for this Table. It is not intended to retrieve the ViewInfo object in a
550
         * later time. <strong>Use PluginServices.getMDIManager().getViewInfo(view)
551
         * to retrieve the ViewInfo object at any time after the creation of the
552
         * object.
553
         *
554
         * @see com.iver.mdiApp.ui.MDIManager.IWindow#getWindowInfo()
555
         */
556
    public WindowInfo getWindowInfo() {
557
            if (m_viewInfo==null) {
558
                    m_viewInfo = new WindowInfo(WindowInfo.ICONIFIABLE |
559
                        WindowInfo.MAXIMIZABLE | WindowInfo.RESIZABLE);
560
                    m_viewInfo.setTitle(PluginServices.getText(this, "Tabla")+ " : " +model.getName());
561
                    m_viewInfo.setWidth(300);
562
                    m_viewInfo.setHeight(200);
563
            }
564
        return m_viewInfo;
565
    }
566

    
567
    /**
568
     * DOCUMENT ME!
569
     *
570
     * @param indexes
571
     *
572
     * @throws IOException
573
     */
574
    public void setOrder(long[] indexes){
575
        model.setOrderIndexes(indexes);
576
        orderInverter(indexes);
577

    
578
        updating = true;
579
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
580
        updating = false;
581

    
582
        updateSelection();
583
    }
584

    
585
    private void orderInverter(long[] indexes) {
586
            orderIndexesInverted = new long[indexes.length];
587

    
588
        for (int i = 0; i < indexes.length; i++) {
589
            orderIndexesInverted[(int) indexes[i]] = i;
590
        }
591
        }
592

    
593
        /**
594
     * Quita los campos seleccionados
595
     */
596
    public void clearSelectedFields() {
597
        headerSelectionSupport.clearSelectedColumns();
598
    }
599

    
600
    /**
601
     * DOCUMENT ME!
602
     *
603
     * @param index DOCUMENT ME!
604
     *
605
     * @return DOCUMENT ME!
606
     */
607
    public Value[] getValueRow(int index) {
608
        DataSourceDataModel dsdm = (DataSourceDataModel) getTable().getModel();
609
        Value[] values = new Value[dsdm.getColumnCount()];
610

    
611
        for (int i = 0; i < dsdm.getColumnCount(); i++) {
612
            values[i] = (Value) dsdm.getValueAt(index, i);
613
        }
614

    
615
        return values;
616
    }
617

    
618
    /* private void refresh() throws DriverException{
619
       //dw.commitTrans();
620
       //model.getModelo().stop();
621
       //dw.beginTrans();
622
           //DataSourceDataModel dsdm=(DataSourceDataModel)getTable().getModel();
623
           //dsdm.fireTableDataChanged();
624
       }*/
625
    /*  public void addEmptyRow() throws DriverException{
626
       ValueCollection valuePK=new ValueCollection();
627
           valuePK.setValues(new Value[]{ValueFactory.createValue(dw.getRowCount())});
628
           dw.insertEmptyRow(valuePK);
629
           refresh();
630
       }
631
     */
632
    /*        public void copySelectedRows() throws DriverException{
633
       int[] sel=getSelectedRowIndices();
634
       for(int i=0;i<sel.length;i++){
635
               rowsCopied.add(getValueRow(sel[i]));
636
       }
637
       }
638
     */
639
    /*        public void addSelectionToEnd() throws DriverException {
640
       for (int i=0;i<rowsCopied.size();i++){
641
               dw.insertFilledRow((Value[])rowsCopied.get(i));
642
       }
643
       refresh();
644
       }
645
     */
646
    /*public void delSelectionRow() throws DriverException{
647
       int[] sel=getSelectedRowIndices();
648
       for(int i=sel.length-1;i>=0;i--){
649
               dw.deleteRow(sel[i]);
650
       }
651
       refresh();
652
       }
653
     */
654
    /*public boolean isCopy(){
655
       return !rowsCopied.isEmpty();
656
       }
657
     */
658
    /*
659
       public void addSelectionToRow() throws DriverException {
660
                   int[] sel=getSelectedRowIndices();
661
                           dw.insertFilledRow((Value[])rowsCopied.get(i),sel[0]);
662
                   refresh();
663
           }
664
     */
665
    public void startEditing() throws StartEditingTableException {
666
                try {
667
                        getModel().getModelo().startEdition(EditionEvent.ALPHANUMERIC);
668
                } catch (StartWriterVisitorException e) {
669
                        throw new StartEditingTableException(getName(), e);
670
                }
671
        }
672
    private void initEditField(int[] x, int[] y) {
673
                if (getTable().getRowCount() > 0) {
674
                        if (isEditing()) {
675

    
676
                                if (x.length == 1 && y.length == 1)
677
                                        table.editCellAt(y[0], x[0]);
678
                                JTextField tf = (JTextField) table.getEditorComponent();
679
                                if (tf != null) {
680
                                        tf.selectAll();
681
                                        tf.requestFocus();
682
                                }
683
                        }
684
                }
685
        }
686
    /**
687
         * DOCUMENT ME!
688
         */
689
    public void stopEditing() {
690
        try {
691
                this.stopEditingCell();
692

    
693
            FLyrVect lyr = (FLyrVect) getModel().getAssociatedTable();
694

    
695
            if ((lyr != null) &&
696
                    lyr.getSource() instanceof VectorialEditableAdapter) {
697
                    VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr.getSource();
698
                    ISpatialWriter spatialWriter = (ISpatialWriter) vea.getOriginalDriver();
699
                    vea.stopEdition(spatialWriter,EditionEvent.ALPHANUMERIC);
700
                    lyr.setSource(vea.getOriginalAdapter());
701
                    lyr.setEditing(false);
702
                    refreshControls();
703

    
704
            } else {
705

    
706
                 IEditableSource ies=getModel().getModelo();
707
                 if (ies instanceof IWriteable)
708
                 {
709
                         IWriteable w = (IWriteable) ies;
710
                         IWriter writer = w.getWriter();
711
                         if (writer == null){
712
                                 throw new StopEditingTableException(getName(),null);
713
                         }else{
714
                                             ITableDefinition tableDef = ies.getTableDefinition();
715
                                            writer.initialize(tableDef);
716
                                            ies.stopEdition(writer,EditionEvent.ALPHANUMERIC);
717
                                ies.getSelection().clear();
718
                                refreshControls();
719
                         }
720
                 }
721

    
722
                 /*
723
                GdbmsWriter gdbmswriter = new GdbmsWriter();
724
                gdbmswriter.setDataWare(getModel().getModelo()
725
                                                              .getRecordset()
726
                                                              .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER));
727
                gdbmswriter.preProcess();
728

729
                for (int i = 0; i < getModel().getModelo().getRowCount();
730
                        i++) {
731
                    gdbmswriter.process(getModel().getModelo().getRow(i));
732
                }
733

734
                gdbmswriter.postProcess();
735
                */
736

    
737
            }
738

    
739
        } catch (Exception e) {
740
            NotificationManager.addError("No se pudo guardar la edici?n", e);
741
        }
742
    }
743

    
744
    /**
745
     * DOCUMENT ME!
746
     *
747
     * @param index DOCUMENT ME!
748
     */
749
    public void hideColumns(int[] index) {
750
        // TODO Auto-generated method stub
751
    }
752

    
753
    /**
754
     * DOCUMENT ME!
755
     *
756
     * @param index DOCUMENT ME!
757
     */
758
    public void setUneditableColumns(int[] index) {
759
        // TODO Auto-generated method stub
760
    }
761

    
762
    /**
763
     * DOCUMENT ME!
764
     *
765
     * @param numColumns DOCUMENT ME!
766
     * @param values DOCUMENT ME!
767
     */
768
    public void setDefaultValues(int[] numColumns, Value[] values) {
769
        // TODO Auto-generated method stub
770
    }
771

    
772
    /**
773
     * DOCUMENT ME!
774
     *
775
     * @return DOCUMENT ME!
776
     */
777
    public Value getDefaultValue() {
778
        // TODO Auto-generated method stub
779
        return null;
780
    }
781

    
782
    /**
783
     * DOCUMENT ME!
784
     *
785
     * @throws IOException DOCUMENT ME!
786
     */
787
    public void cancelEditing() throws CancelEditingTableException {
788
            this.cancelEditingCell();
789
        try {
790
                        getModel().getModelo().cancelEdition(EditionEvent.ALPHANUMERIC);
791
                } catch (CancelEditingLayerException e) {
792
                        throw new CancelEditingTableException(getName(),e);
793
                }
794
//        if (antAliases != null)
795
//        {
796
//                getModel().setAliases(antAliases);
797
//                getModel().setMapping(antMapping);
798
//                getModel().recalculateColumnsFromAliases();
799
//        }
800
//        else
801
//        {
802
//                System.err.println("Algo ha ido mal con antAliases");
803
//        }
804
//        getModel().getModelo().getRecordset().setSelection(oldSelection);
805
        refreshControls();
806
    }
807

    
808
    /**
809
     * DOCUMENT ME!
810
     *
811
     * @return DOCUMENT ME!
812
     */
813
    public boolean isEditing() {
814
        return getModel().getModelo().isEditing();
815
    }
816

    
817
    /**
818
     * DOCUMENT ME!
819
     */
820
    public void refresh() {
821
            int row=table.getSelectedRow();
822
            int column=table.getSelectedColumn();
823
            if (row!=-1 && column!=-1 && table.getEditorComponent()!=null){
824
                    Value[] values=getValueRow(row);
825
                    JTextField jtf=(JTextField)table.getEditorComponent();
826
                    jtf.setText(values[column].toString());
827
            }
828
        updating = true;
829
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
830

    
831
        updating = false;
832
        updateSelection();
833
        PluginServices.getMainFrame().enableControls();
834

    
835
    }
836

    
837
    /**
838
     * Add the rows that are passed like parameter and if parameter is null a
839
     * row is added empties.
840
     *
841
     * @param rows Rows to add or null.
842
     * @throws ExpansionFileWriteException
843
     * @throws ReadDriverException
844
     * @throws ValidateRowException
845
     *
846
     * @throws DriverIOException
847
     * @throws IOException
848
     */
849
    public void addRow(IRow[] rows) throws ValidateRowException, ReadDriverException, ExpansionFileWriteException {
850
            IEditableSource ies=getModel().getModelo();
851
            if (rows == null) {
852

    
853
                    if (getModel().getAssociatedTable()!=null){
854
                            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),"No se puede a?adir una fila a una tabla asociada a una capa.");
855
                            return;
856
                    }
857
                IRow row;
858
                int numAttr=getModel().getModelo()
859
                        .getRecordset()
860
                        .getFieldCount();
861
                    Value[] values=new Value[numAttr];
862
                    for (int i=0;i<numAttr;i++){
863
                            values[i]=ValueFactory.createNullValue();
864
                    }
865
                row = new DefaultRow(values);
866
//TODO Lo cambio pq da problemas
867
//                ies.addRow(row,"Fila en blanco",EditionEvent.ALPHANUMERIC);
868
                ies.doAddRow(row, EditionEvent.ALPHANUMERIC);
869

    
870
            } else {
871
                    ies.startComplexRow();
872
                for (int i = 0; i < rows.length; i++) {
873
                   ies.addRow(((IRowEdited) rows[i]).getLinkedRow(),"Pegar filas",EditionEvent.ALPHANUMERIC);
874
                }
875
                String description=PluginServices.getText(this,"add_rows");
876
                ies.endComplexRow(description);
877
            }
878
        refresh();
879

    
880
    }
881

    
882
    /**
883
     * Copy in the arraylist the rows that be selected just then.
884
     * @throws ExpansionFileReadException
885
     * @throws ReadDriverException
886
     *
887
     * @throws DriverIOException
888
     * @throws IOException
889
     */
890
    public void copyRow() throws ReadDriverException, ExpansionFileReadException {
891
        int[] index = getSelectedRowIndices();
892
        rowsCopied = new IRow[index.length];
893

    
894
        for (int i = 0; i < index.length; i++) {
895
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
896
        }
897
    }
898

    
899
    /**
900
     * Cut the rows that be selected just then.
901
     * @throws ExpansionFileReadException
902
     * @throws ReadDriverException
903
     *
904
     * @throws DriverIOException
905
     * @throws IOException
906
     */
907
    public void cutRow() throws ReadDriverException, ExpansionFileReadException {
908
        int[] index = getSelectedRowIndices();
909
        rowsCopied = new IRow[index.length];
910

    
911
        for (int i = 0; i < index.length; i++) {
912
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
913
        }
914

    
915
        removeRow();
916
    }
917

    
918
    /**
919
     * Remove in the rows that be selected just then.
920
     * @throws ExpansionFileReadException
921
     * @throws ReadDriverException
922
     *
923
     * @throws DriverIOException
924
     * @throws IOException
925
     */
926
    public void removeRow() throws ReadDriverException, ExpansionFileReadException{
927
            int[] index = getSelectedRowIndices();
928
        getModel().getModelo().startComplexRow();
929
        for (int i = index.length-1; i >=0; i--) {
930
            getModel().getModelo().removeRow(index[i],"Eliminar fila", EditionEvent.ALPHANUMERIC);
931
        }
932
//        int[] sel={0};
933
//        getTable().setEditingRow(-1);
934
//        getTable().getCellEditor().
935
//        initEditField(sel,sel);
936
        if (getTable().getCellEditor() != null)
937
                getTable().getCellEditor().cancelCellEditing();
938
        String description=PluginServices.getText(this,"remove_rows");
939
        getModel().getModelo().endComplexRow(description);
940
        getTable().clearSelection();
941

    
942
        refresh();
943
        //repaintAssociatedView();
944
    }
945

    
946
//    private void repaintAssociatedView(){
947
//             View[] views = (View[]) PluginServices.getMDIManager().getAllViews();
948
//
949
//                 for (int i=0 ; i<views.length ; i++){
950
//                         if (views[i] instanceof com.iver.cit.gvsig.gui.View){
951
//                                 com.iver.cit.gvsig.gui.View view=(com.iver.cit.gvsig.gui.View)views[i];
952
//                                 FLayers layers =view.getMapControl().getMapContext().getLayers();
953
//                                 for (int j=0;j<layers.getLayersCount();j++){
954
//                                         if (layers.getLayer(j).equals(this.getModel().getAssociatedTable())){
955
//                                                 view.getMapControl().getMapContext().invalidate();
956
//                                         }
957
//                                 }
958
//                         }
959
//                 }
960
//    }
961
    /**
962
     * DOCUMENT ME!
963
     */
964
    public void addColumn(FieldDescription newField) {
965
            EditableAdapter edAdapter = (EditableAdapter) getModel().getModelo();
966
                    try {
967
                                edAdapter.addField(newField);
968
                        } catch (ReadDriverException e) {
969
                                e.printStackTrace();
970
                                NotificationManager.addError(e);
971
                        }
972
                        if (getTable().getCellEditor() != null)
973
                                getTable().getCellEditor().cancelCellEditing();
974
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
975
                // refresh();
976
                refreshControls();
977
        }
978

    
979
    /**
980
     * DOCUMENT ME!
981
     */
982
    public void removeColumn() {
983
            EditableAdapter edAdapter = (EditableAdapter) getModel().getModelo();
984
            try {
985
                    BitSet selectedFields = getSelectedFieldIndices();
986
                    SelectableDataSource sds = edAdapter.getRecordset();
987
                    edAdapter.startComplexRow();
988
                    FieldDescription[] auxFlds = sds.getFieldsDescription();
989
                    for(int i=selectedFields.nextSetBit(0); i>=0; i=selectedFields.nextSetBit(i+1)) {
990
                            FieldDescription fld = auxFlds[i];
991
                            edAdapter.removeField(fld.getFieldAlias());
992
                    }
993
                    if (getTable().getCellEditor() != null)
994
                                getTable().getCellEditor().cancelCellEditing();
995

    
996
                edAdapter.endComplexRow(PluginServices.getText(this, "remove_fields"));
997
                clearSelectedFields();
998
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
999
                // refresh();
1000
                refreshControls();
1001
            } catch (ReadDriverException e) {
1002
                    e.printStackTrace();
1003
                        NotificationManager.addError(e);
1004
                } catch (WriteDriverException e) {
1005
                        e.printStackTrace();
1006
                        NotificationManager.addError(e);
1007
                }
1008

    
1009
    }
1010

    
1011
    /**
1012
     * Return if we have rows copied or not.
1013
     *
1014
     * @return True if we have rows copied.
1015
     */
1016
    public boolean isCopied() {
1017
        return (rowsCopied != null);
1018
    }
1019

    
1020
    /**
1021
     * Paste the arraylist rows.
1022
     * @throws ExpansionFileWriteException
1023
     * @throws ReadDriverException
1024
     * @throws ValidateRowException
1025
     *
1026
     * @throws DriverIOException
1027
     * @throws IOException
1028
     */
1029
    public void pasteRow() throws ValidateRowException, ReadDriverException, ExpansionFileWriteException {
1030
        addRow(rowsCopied);
1031
        //repaintAssociatedView();
1032
    }
1033

    
1034
    /**
1035
     * DOCUMENT ME!
1036
     */
1037
    public void windowActivated() {
1038
        //if (isEditing() && getModel().getModelo() instanceof VectorialEditableAdapter)
1039
        updateSelection();
1040
    }
1041

    
1042
    /**
1043
     * DOCUMENT ME!
1044
     */
1045
    public void windowClosed() {
1046
        // TODO Auto-generated method stub
1047
    }
1048

    
1049
    /**
1050
     * DOCUMENT ME!
1051
     *
1052
     * @author Vicente Caballero Navarro
1053
     */
1054
    public class TableSelectionListener implements SelectionListener {
1055
        /**
1056
         * @see com.iver.cit.gvsig.fmap.layers.LegendListener#selectionChanged(com.iver.cit.gvsig.fmap.layers.LayerEvent)
1057
         */
1058
        public void selectionChanged(SelectionEvent e) {
1059
            updateSelection();
1060
            Table.this.repaint();
1061
            //((ValueComplexRenderer)Table.this.getTable().getColumnModel().getColumn(getSelectedFieldIndices().nextSetBit(0)).getCellRenderer()).getValue();
1062
        }
1063
    }
1064

    
1065
    /**
1066
     * DOCUMENT ME!
1067
     *
1068
     * @author Vicente Caballero Navarro
1069
     */
1070
//    private class MouseHandler extends MouseAdapter {
1071
//        /**
1072
//         * DOCUMENT ME!
1073
//         *
1074
//         * @param e DOCUMENT ME!
1075
//         */
1076
//        public void mouseClicked(MouseEvent e) {
1077
//
1078
//            /* JTableHeader h = (JTableHeader) e.getSource();
1079
//               TableColumnModel columnModel = h.getColumnModel();
1080
//               int viewColumn = columnModel.getColumnIndexAtX(e.getX());
1081
//               int column = columnModel.getColumn(viewColumn).getModelIndex();
1082
//               if (column != -1) {
1083
//               }*/
1084
//        }
1085
//    }
1086
    /**
1087
     * DOCUMENT ME!
1088
     *
1089
     * @author Vicente Caballero Navarro
1090
     */
1091
    private class TableKeyListener implements KeyListener {
1092

    
1093
                public void keyPressed(KeyEvent arg0) {
1094
                        //JTextField tf=(JTextField)table.getEditorComponent();
1095
                        //table.setCellSelectionEnabled(true);
1096
                        //FocusManager fm = FocusManager.getCurrentManager();
1097
                        //fm.focusPreviousComponent(table);
1098
                }
1099

    
1100
                public void keyReleased(KeyEvent ke) {
1101
                        int[] row=table.getSelectedRows();
1102
                    int[] column=table.getSelectedColumns();
1103
                    initEditField(column,row);
1104
                }
1105

    
1106
                public void keyTyped(KeyEvent arg0) {
1107
                        // TODO Auto-generated method stub
1108

    
1109
                }
1110

    
1111
    }
1112

    
1113
    /**
1114
     * DOCUMENT ME!
1115
     *
1116
     * @author Vicente Caballero Navarro
1117
     */
1118
    private class MouseRow extends MouseAdapter {
1119
               public void mouseReleased(MouseEvent arg0) {
1120
                        super.mouseReleased(arg0);
1121
                        int[] row=table.getSelectedRows();
1122
                    int[] column=table.getSelectedColumns();
1123
                    initEditField(column,row);
1124
                }
1125

    
1126
                /**
1127
         * DOCUMENT ME!
1128
         *
1129
         * @param e DOCUMENT ME!
1130
         */
1131
    /*    public void mouseClicked(MouseEvent e) {
1132
            super.mouseClicked(e);
1133

1134

1135
                PluginServices.getMainFrame().enableControls();
1136

1137
            if (e.getButton() == MouseEvent.BUTTON3) {
1138
                new PopupMenu(e.getPoint());
1139
            }
1140
        }
1141
*/
1142
    }
1143

    
1144
        public void commandRepaint() {
1145
                refresh();
1146
        }
1147

    
1148
        public void commandRefresh() {
1149
                commandRepaint();
1150
        }
1151

    
1152
        public void toPalette() {
1153
                isPalette=true;
1154
                m_viewInfo.toPalette(true);
1155
                m_viewInfo.setClosed(false);
1156
                PluginServices.getMDIManager().changeWindowInfo(this,getWindowInfo());
1157
        }
1158

    
1159
        public void restore() {
1160
                isPalette=false;
1161
                m_viewInfo.toPalette(false);
1162
                m_viewInfo.setClosed(false);
1163
                PluginServices.getMDIManager().changeWindowInfo(this,getWindowInfo());
1164
        }
1165

    
1166
        public boolean isPalette() {
1167
                return isPalette;
1168
        }
1169

    
1170
        public static void main(String[] args) {
1171
                JTextField tf=new JTextField("hola");
1172
                tf.selectAll();
1173
                JFrame frame=new JFrame();
1174
                frame.getContentPane().add(tf);
1175
                frame.setVisible(true);
1176
        }
1177

    
1178
        public void stopEditingCell() {
1179
            if (table.isEditing()) {
1180

    
1181
                    // TODO: finalizar la edicion de la columna
1182
                    this.table.getCellEditor().stopCellEditing();
1183
                    this.refresh();
1184

    
1185
            }
1186

    
1187
        }
1188

    
1189
        public void cancelEditingCell() {
1190
            if (table.isEditing()) {
1191
                    // TODO: finalizar la edicion de la columna
1192
                    this.table.getCellEditor().cancelCellEditing();
1193
                    this.refresh();
1194
            }
1195

    
1196
        }
1197

    
1198
        public void processEvent(EditionEvent e) {
1199
                if (e.getChangeType() == EditionEvent.STOP_EDITION)
1200
                {
1201
                        refreshControls();
1202
                }
1203

    
1204
        }
1205

    
1206
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1207
                // TODO Auto-generated method stub
1208

    
1209
        }
1210

    
1211
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1212
                // TODO Auto-generated method stub
1213

    
1214
        }
1215

    
1216
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1217
                // TODO Auto-generated method stub
1218

    
1219
        }
1220

    
1221
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1222
//                        getModel().createAlias();
1223
                        clearSelectedFields();
1224
//                        refresh();
1225
                        refreshControls();
1226
                // ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
1227

    
1228
        }
1229
}