Statistics
| Revision:

svn-gvsig-desktop / trunk / applications / appgvSIG / src / com / iver / cit / gvsig / project / documents / table / gui / Table.java @ 28940

History | View | Annotate | Download (38.4 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
                    String title = PluginServices.getText(this, "Tabla") + ": " + model.getName();
197
                    if (model.getJoinedTables()!=null) {
198
                            String[] joinedTables = model.getJoinedTables();
199
                            for (int i=0; i<joinedTables.length; i++) {
200
                                    title = title + " X " + joinedTables[i];
201
                            }
202
                    }
203
                    PluginServices.getMDIManager().getWindowInfo(Table.this).setTitle(title);
204
            }
205

    
206
            if (model.getAssociatedTable() != null) {
207
                this.fmap = ((FLayer) model.getAssociatedTable()).getMapContext();
208
            } else {
209
                this.fmap = null;
210
            }
211

    
212
            SelectableDataSource dataSource = model.getModelo().getRecordset();
213
            dataSource.mapExternalFields();
214
            logger.debug("dataSource.start()");
215
            dataSource.start();
216

    
217
            ColumnModel cm=new ColumnModel(model);
218
            getTable().setColumnModel(cm);
219

    
220
            AbstractTableModel dataModel = new DataSourceDataModel(model);
221

    
222
            getTable().setModel(dataModel);
223

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

    
231
                        }
232

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

    
251
            model.getModelo().getRecordset().addSelectionListener(selectionListener);
252

    
253
            updateSelection();
254
        } catch (ReadDriverException e) {
255
                  NotificationManager.addError("No se pudo leer la informaci?n", e);
256
                }
257
    }
258

    
259
    /**
260
     * DOCUMENT ME!
261
     *
262
     * @param table DOCUMENT ME!
263
     */
264
    public void setModel(ProjectTable table) {
265
        model = table;
266

    
267
        //Gesti?n del nombre de la ventana
268
        model.addPropertyChangeListener(new PropertyChangeListener() {
269
                public void propertyChange(PropertyChangeEvent evt) {
270
                    if (evt.getPropertyName().equals("name")) {
271
                            String title = PluginServices.getText(this, "Tabla") + ": " + model.getName();
272
                            if (model.getJoinedTables()!=null) {
273
                                    String[] joinedTables = model.getJoinedTables();
274
                                    for (int i=0; i<joinedTables.length; i++) {
275
                                            title = title + " X " + joinedTables[i];
276
                                    }
277
                            }
278
                            PluginServices.getMDIManager().getWindowInfo(Table.this).setTitle(title);
279

    
280
                    } else if (evt.getPropertyName().equals("model")) {
281
                        refreshControls();
282
                    }
283
                }
284
            });
285

    
286
        IEditableSource ies=getModel().getModelo();
287
        ies.addEditionListener(this);
288

    
289
        refreshControls();
290

    
291

    
292
    }
293
    /**
294
     *
295
     */
296
    public void updateSelection() {
297
        updating = true;
298
        try {
299
            DefaultListSelectionModel sm = (DefaultListSelectionModel) getTable()
300
                                                                           .getSelectionModel();
301
            sm.clearSelection();
302

    
303
            BitSet bs = (model.getModelo().getRecordset()).getSelection();
304
            sm.setValueIsAdjusting(true);
305

    
306
            if (model.getOrderIndexes() != null) {
307
//                    if (orderIndexesInverted==null) {
308
                        orderInverter(model.getOrderIndexes());
309
//                }
310
                for (int i = 0; i < model.getOrderIndexes().length; i++) {
311
                    if (bs.get(i)) {
312
                        sm.addSelectionInterval((int) orderIndexesInverted[i],
313
                            (int) orderIndexesInverted[i]);
314
                        if (isEditing())
315
                                table.setEditingRow((int)orderIndexesInverted[i]);
316
                    }
317
                }
318
            } else {
319
                    for (int i = bs.nextSetBit(0); i >= 0;
320
                             i = bs.nextSetBit(i + 1)) {
321
                         sm.addSelectionInterval(i, i);
322
                         if (isEditing())
323
                                  table.setEditingRow(i);
324
                    }
325
            }
326

    
327
            sm.setValueIsAdjusting(false);
328
            numReg = model.getModelo().getRowCount();
329

    
330
            jLabelStatus.setText(" " +
331
                (model.getModelo().getRecordset()).getSelection()
332
                 .cardinality() + " / " + numReg + " " +
333
                PluginServices.getText(this, "registros_seleccionados_total") +
334
                ".");
335
            if (PluginServices.getMainFrame() != null)
336
                    PluginServices.getMainFrame().enableControls();
337
        } catch (ReadDriverException e) {
338
                        // TODO Auto-generated catch block
339
                        e.printStackTrace();
340
                }
341
        updating = false;
342
    }
343

    
344
    /**
345
     * This method initializes this
346
     */
347
    protected void initialize() {
348
        jLabelStatus = new JLabel();
349
        setLayout(new java.awt.BorderLayout());
350
        jLabelStatus.setText("");
351
        jLabelStatus.setName("");
352
        jLabelStatus.setPreferredSize(new java.awt.Dimension(100, 18));
353
        add(getJScrollPane(), java.awt.BorderLayout.CENTER);
354
        this.add(jLabelStatus, java.awt.BorderLayout.SOUTH);
355
        this.setPreferredSize(new Dimension(300,200));
356
    }
357

    
358
    /**
359
     * This method initializes table
360
     *
361
     * @return javax.swing.JTable
362
     */
363
    public javax.swing.JTable getTable() {
364
        if (table == null) {
365
            table = new javax.swing.JTable();
366
            table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
367
            table.setSelectionModel(new DefaultListSelectionModel());
368
//            table.getTableHeader().addMouseListener(new MouseHandler());
369
            table.addKeyListener(new TableKeyListener());
370
            table.addMouseListener(new MouseRow());
371
            table.setSelectionForeground(Color.blue);
372
                    table.setSelectionBackground(Color.yellow);
373
                    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
374
                    public void valueChanged(ListSelectionEvent e) {
375

    
376
                            if (updating) {
377
                                 return;
378
                        }
379

    
380
                        SelectableDataSource dataModel = null;
381

    
382
                        try {
383
                            dataModel = Table.this.model.getModelo()
384
                                                        .getRecordset();
385
                        } catch (ReadDriverException e1) {
386
                                                        e1.printStackTrace();
387
                                                }
388

    
389
                        DefaultListSelectionModel model = (DefaultListSelectionModel) table.getSelectionModel();
390
                        BitSet selection = dataModel.getSelection();
391
                        int firstIndex=e.getFirstIndex();
392
                        if (firstIndex >= 0) {
393
                                                                for (int i = firstIndex; i <= e.getLastIndex(); i++) {
394
                                                                        if (Table.this.model.getOrderIndexes() != null) {
395
                                                                                selection.set((int) Table.this.model
396
                                                                                                .getOrderIndexes()[i], model
397
                                                                                                .isSelectedIndex(i));
398
                                                                        } else {
399
                                                                                selection.set(i, model
400
                                                                                                .isSelectedIndex(i));
401
                                                                        }
402
                                                                }
403
                                                        }
404
                        if (e.getValueIsAdjusting() == false) {
405
                            if (fmap != null) {
406
                                fmap.endAtomicEvent();
407
                            }
408

    
409
                            dataModel.fireSelectionEvents();
410
                        } else {
411
                            if (fmap != null) {
412
                                fmap.beginAtomicEvent();
413
                            }
414
                        }
415

    
416
                        jLabelStatus.setText(" " + selection.cardinality() +
417
                            " / " + numReg + " " +
418
                            PluginServices.getText(this,
419
                                "registros_seleccionados_total") + ".");
420

    
421
                    }
422
                });
423

    
424
                       JTextField tf=new JTextField();
425
                       tf.addFocusListener(new FocusListener() {
426
                          public void focusGained(FocusEvent e) {
427
                                // TODO Auto-generated method stub
428

    
429
                        }
430
                          public void focusLost(FocusEvent e) {
431
                                  table.editingStopped(new ChangeEvent(table));
432
                        }
433
                   });
434
                    table.setDefaultEditor(Object.class, new DefaultEditor(tf));
435
//            table.setDefaultEditor(String.class, new DefaultEditor(tf));
436
//            table.setDefaultEditor(Object.class, new DefaultEditor(tf));
437
//            table.setDefaultEditor(BooleanValue.class,new BooleanTableCellEditor(table));
438
//            table.setDefaultEditor(StringValue.class,new DefaultCellEditor(tf));
439
//            table.setDefaultEditor(Number.class,new IntegerTableCellEditor());
440

    
441
        }
442

    
443
        return table;
444
    }
445
    protected class DefaultEditor extends DefaultCellEditor{
446
                public Component getTableCellEditorComponent(javax.swing.JTable table,
447
                                Object value, boolean isSelected, int row, int column) {
448
                        JTextField tf=(JTextField)super.getTableCellEditorComponent(table, value, isSelected,
449
                                        row, column);
450
                        if (isSelected){
451
                                tf.setBackground(new Color(230,220,220));
452
                                tf.selectAll();
453

    
454
                        }
455
                        return tf;
456
                }
457

    
458
                public DefaultEditor(JTextField tf) {
459
                        super(tf);
460
                    tf.addMouseListener(new MouseRow());
461
                    getComponent().addKeyListener(new KeyAdapter() {
462
                                int keyPressed = 0;
463

    
464
                                public void keyPressed(KeyEvent ke) {
465
                                        if (ke.getKeyCode() != KeyEvent.VK_TAB)
466
                                                keyPressed++;
467
                                        JTextField tf = (JTextField) getComponent();
468

    
469

    
470
                                        if (ke.getKeyCode() == KeyEvent.VK_RIGHT
471
                                                        || ke.getKeyCode() == KeyEvent.VK_ENTER) {
472
                                                int caretPosition = tf.getCaretPosition();
473
                                                if (caretPosition >= tf.getText().length()) {
474
                                                        int x = table.getSelectedColumn();
475
                                                        int y = table.getSelectedRow();
476
                                                        if (x + 1 >= table.getColumnCount()) {
477
                                                                x = 0;
478
                                                                y++;
479
                                                        } else {
480
                                                                x++;
481
                                                        }
482
                                                        getComponent().setEnabled(false);
483
                                                }
484

    
485
                                        } else if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
486
                                                int caretPosition = tf.getCaretPosition();
487
                                                if (caretPosition <= 0) {
488
                                                        int x = table.getSelectedColumn();
489
                                                        int y = table.getSelectedRow();
490
                                                        if (x == 0) {
491
                                                                x = table.getColumnCount() - 1;
492
                                                                if (y - 1 < 0)
493
                                                                        y = table.getRowCount() - 1;
494
                                                                else
495
                                                                        y--;
496
                                                        } else {
497
                                                                x--;
498
                                                        }
499
                                                        getComponent().setEnabled(false);
500
                                                }
501

    
502
                                        }
503
                                }
504

    
505
                                public void keyReleased(KeyEvent ke) {
506
                                        keyPressed--;
507
                                        if (keyPressed < 0)
508
                                                keyPressed = 0;
509
                                        getComponent().setEnabled(true);
510
                                }
511
                        });
512

    
513
                }
514

    
515
                public Object getCellEditorValue() {
516
                        String s = ((JTextField) (DefaultEditor.this.getComponent()))
517
                                        .getText();
518
                        getComponent().setEnabled(true);
519
                        return s;
520
                }
521

    
522
                public boolean isCellEditable(EventObject event) {
523
                        // IF NUMBER OF CLICKS IS LESS THAN THE CLICKCOUNTTOSTART RETURN
524
                        // FALSE
525
                        // FOR CELL EDITING.
526
                        if (event instanceof MouseEvent) {
527
                                return ((MouseEvent) event).getClickCount() >= getClickCountToStart();
528
                        }
529

    
530
                        return true;
531
                }
532
        }
533

    
534

    
535

    
536
    /**
537
         * This method initializes jScrollPane
538
         *
539
         * @return javax.swing.JScrollPane
540
         */
541
    protected javax.swing.JScrollPane getJScrollPane() {
542
        if (jScrollPane == null) {
543
            jScrollPane = new javax.swing.JScrollPane();
544
            jScrollPane.setViewportView(getTable());
545
        }
546

    
547
        return jScrollPane;
548
    }
549

    
550
    /**
551
         * @see com.iver.mdiApp.ui.MDIManager.SingletonWindow#getWindowModel()
552
         */
553
    public Object getWindowModel() {
554
        return model;
555
    }
556

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

    
577
    /**
578
     * DOCUMENT ME!
579
     *
580
     * @param indexes
581
     *
582
     * @throws IOException
583
     */
584
    public void setOrder(long[] indexes){
585
        model.setOrderIndexes(indexes);
586
        orderInverter(indexes);
587

    
588
        updating = true;
589
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
590
        updating = false;
591

    
592
        updateSelection();
593
    }
594

    
595
    private void orderInverter(long[] indexes) {
596
            orderIndexesInverted = new long[indexes.length];
597

    
598
        for (int i = 0; i < indexes.length; i++) {
599
            orderIndexesInverted[(int) indexes[i]] = i;
600
        }
601
        }
602

    
603
        /**
604
     * Quita los campos seleccionados
605
     */
606
    public void clearSelectedFields() {
607
        headerSelectionSupport.clearSelectedColumns();
608
    }
609

    
610
    /**
611
     * DOCUMENT ME!
612
     *
613
     * @param index DOCUMENT ME!
614
     *
615
     * @return DOCUMENT ME!
616
     */
617
    public Value[] getValueRow(int index) {
618
        DataSourceDataModel dsdm = (DataSourceDataModel) getTable().getModel();
619
        Value[] values = new Value[dsdm.getColumnCount()];
620

    
621
        for (int i = 0; i < dsdm.getColumnCount(); i++) {
622
            values[i] = (Value) dsdm.getValueAt(index, i);
623
        }
624

    
625
        return values;
626
    }
627

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

    
686
                                if (x.length == 1 && y.length == 1)
687
                                        table.editCellAt(y[0], x[0]);
688
                                JTextField tf = (JTextField) table.getEditorComponent();
689
                                if (tf != null) {
690
                                        tf.selectAll();
691
                                        tf.requestFocus();
692
                                }
693
                        }
694
                }
695
        }
696
    /**
697
         * DOCUMENT ME!
698
         */
699
    public void stopEditing() {
700
        try {
701
                this.stopEditingCell();
702

    
703
            FLyrVect lyr = (FLyrVect) getModel().getAssociatedTable();
704

    
705
            if ((lyr != null) &&
706
                    lyr.getSource() instanceof VectorialEditableAdapter) {
707
                    VectorialEditableAdapter vea = (VectorialEditableAdapter) lyr.getSource();
708
                    ISpatialWriter spatialWriter = (ISpatialWriter) vea.getOriginalDriver();
709
                    vea.stopEdition(spatialWriter,EditionEvent.ALPHANUMERIC);
710
                    lyr.setSource(vea.getOriginalAdapter());
711
                    lyr.setEditing(false);
712
                    refreshControls();
713

    
714
            } else {
715

    
716
                 IEditableSource ies=getModel().getModelo();
717
                 if (ies instanceof IWriteable)
718
                 {
719
                         IWriteable w = (IWriteable) ies;
720
                         IWriter writer = w.getWriter();
721
                         if (writer == null){
722
                                 throw new StopEditingTableException(getName(),null);
723
                         }else{
724
                                             ITableDefinition tableDef = ies.getTableDefinition();
725
                                            writer.initialize(tableDef);
726
                                            ies.stopEdition(writer,EditionEvent.ALPHANUMERIC);
727
                                ies.getSelection().clear();
728
                                refreshControls();
729
                         }
730
                 }
731

    
732
                 /*
733
                GdbmsWriter gdbmswriter = new GdbmsWriter();
734
                gdbmswriter.setDataWare(getModel().getModelo()
735
                                                              .getRecordset()
736
                                                              .getDataWare(DataSourceFactory.DATA_WARE_COHERENT_ROW_ORDER));
737
                gdbmswriter.preProcess();
738

739
                for (int i = 0; i < getModel().getModelo().getRowCount();
740
                        i++) {
741
                    gdbmswriter.process(getModel().getModelo().getRow(i));
742
                }
743

744
                gdbmswriter.postProcess();
745
                */
746

    
747
            }
748

    
749
        } catch (Exception e) {
750
            NotificationManager.addError("No se pudo guardar la edici?n", e);
751
        }
752
    }
753

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

    
763
    /**
764
     * DOCUMENT ME!
765
     *
766
     * @param index DOCUMENT ME!
767
     */
768
    public void setUneditableColumns(int[] index) {
769
        // TODO Auto-generated method stub
770
    }
771

    
772
    /**
773
     * DOCUMENT ME!
774
     *
775
     * @param numColumns DOCUMENT ME!
776
     * @param values DOCUMENT ME!
777
     */
778
    public void setDefaultValues(int[] numColumns, Value[] values) {
779
        // TODO Auto-generated method stub
780
    }
781

    
782
    /**
783
     * DOCUMENT ME!
784
     *
785
     * @return DOCUMENT ME!
786
     */
787
    public Value getDefaultValue() {
788
        // TODO Auto-generated method stub
789
        return null;
790
    }
791

    
792
    /**
793
     * DOCUMENT ME!
794
     *
795
     * @throws IOException DOCUMENT ME!
796
     */
797
    public void cancelEditing() throws CancelEditingTableException {
798
            this.cancelEditingCell();
799
        try {
800
                        getModel().getModelo().cancelEdition(EditionEvent.ALPHANUMERIC);
801
                } catch (CancelEditingLayerException e) {
802
                        throw new CancelEditingTableException(getName(),e);
803
                }
804
//        if (antAliases != null)
805
//        {
806
//                getModel().setAliases(antAliases);
807
//                getModel().setMapping(antMapping);
808
//                getModel().recalculateColumnsFromAliases();
809
//        }
810
//        else
811
//        {
812
//                System.err.println("Algo ha ido mal con antAliases");
813
//        }
814
//        getModel().getModelo().getRecordset().setSelection(oldSelection);
815
        refreshControls();
816
    }
817

    
818
    /**
819
     * DOCUMENT ME!
820
     *
821
     * @return DOCUMENT ME!
822
     */
823
    public boolean isEditing() {
824
        return getModel().getModelo().isEditing();
825
    }
826

    
827
    /**
828
     * DOCUMENT ME!
829
     */
830
    public void refresh() {
831
            int row=table.getSelectedRow();
832
            int column=table.getSelectedColumn();
833
            if (row!=-1 && column!=-1 && table.getEditorComponent()!=null){
834
                    Value[] values=getValueRow(row);
835
                    JTextField jtf=(JTextField)table.getEditorComponent();
836
                    jtf.setText(values[column].toString());
837
            }
838
        updating = true;
839
        ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
840

    
841
        updating = false;
842
        updateSelection();
843
        PluginServices.getMainFrame().enableControls();
844

    
845
    }
846

    
847
    /**
848
     * Add the rows that are passed like parameter and if parameter is null a
849
     * row is added empties.
850
     *
851
     * @param rows Rows to add or null.
852
     * @throws ExpansionFileWriteException
853
     * @throws ReadDriverException
854
     * @throws ValidateRowException
855
     *
856
     * @throws DriverIOException
857
     * @throws IOException
858
     */
859
    public void addRow(IRow[] rows) throws ValidateRowException, ReadDriverException, ExpansionFileWriteException {
860
            IEditableSource ies=getModel().getModelo();
861
            if (rows == null) {
862

    
863
                    if (getModel().getAssociatedTable()!=null){
864
                            JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),"No se puede a?adir una fila a una tabla asociada a una capa.");
865
                            return;
866
                    }
867
                IRow row;
868
                int numAttr=getModel().getModelo()
869
                        .getRecordset()
870
                        .getFieldCount();
871
                    Value[] values=new Value[numAttr];
872
                    for (int i=0;i<numAttr;i++){
873
                            values[i]=ValueFactory.createNullValue();
874
                    }
875
                row = new DefaultRow(values);
876
//TODO Lo cambio pq da problemas
877
//                ies.addRow(row,"Fila en blanco",EditionEvent.ALPHANUMERIC);
878
                ies.doAddRow(row, EditionEvent.ALPHANUMERIC);
879

    
880
            } else {
881
                    ies.startComplexRow();
882
                for (int i = 0; i < rows.length; i++) {
883
                   ies.addRow(((IRowEdited) rows[i]).getLinkedRow(),"Pegar filas",EditionEvent.ALPHANUMERIC);
884
                }
885
                String description=PluginServices.getText(this,"add_rows");
886
                ies.endComplexRow(description);
887
            }
888
        refresh();
889

    
890
    }
891

    
892
    /**
893
     * Copy in the arraylist the rows that be selected just then.
894
     * @throws ExpansionFileReadException
895
     * @throws ReadDriverException
896
     *
897
     * @throws DriverIOException
898
     * @throws IOException
899
     */
900
    public void copyRow() throws ReadDriverException, ExpansionFileReadException {
901
        int[] index = getSelectedRowIndices();
902
        rowsCopied = new IRow[index.length];
903

    
904
        for (int i = 0; i < index.length; i++) {
905
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
906
        }
907
    }
908

    
909
    /**
910
     * Cut the rows that be selected just then.
911
     * @throws ExpansionFileReadException
912
     * @throws ReadDriverException
913
     *
914
     * @throws DriverIOException
915
     * @throws IOException
916
     */
917
    public void cutRow() throws ReadDriverException, ExpansionFileReadException {
918
        int[] index = getSelectedRowIndices();
919
        rowsCopied = new IRow[index.length];
920

    
921
        for (int i = 0; i < index.length; i++) {
922
            rowsCopied[i] = getModel().getModelo().getRow(index[i]);
923
        }
924

    
925
        removeRow();
926
    }
927

    
928
    /**
929
     * Remove in the rows that be selected just then.
930
     * @throws ExpansionFileReadException
931
     * @throws ReadDriverException
932
     *
933
     * @throws DriverIOException
934
     * @throws IOException
935
     */
936
    public void removeRow() throws ReadDriverException, ExpansionFileReadException{
937
            int[] index = getSelectedRowIndices();
938
        getModel().getModelo().startComplexRow();
939
        long[] orderIndexes=getModel().getOrderIndexes();
940
        for (int i = index.length-1; i >=0; i--) {
941
                if (orderIndexes!=null)
942
                        getModel().getModelo().removeRow((int)orderIndexes[index[i]],"Eliminar fila", EditionEvent.ALPHANUMERIC);
943
                else
944
                        getModel().getModelo().removeRow((int)index[i],"Eliminar fila", EditionEvent.ALPHANUMERIC);
945
        }
946
        if (getTable().getCellEditor() != null)
947
                getTable().getCellEditor().cancelCellEditing();
948
        String description=PluginServices.getText(this,"remove_rows");
949
        getModel().getModelo().endComplexRow(description);
950
        getTable().clearSelection();
951

    
952
        refresh();
953
    }
954

    
955
    /**
956
     * DOCUMENT ME!
957
     */
958
    public void addColumn(FieldDescription newField) {
959
            EditableAdapter edAdapter = (EditableAdapter) getModel().getModelo();
960
                    try {
961
                                edAdapter.addField(newField);
962
                        } catch (ReadDriverException e) {
963
                                e.printStackTrace();
964
                                NotificationManager.addError(e);
965
                        }
966
                        if (getTable().getCellEditor() != null)
967
                                getTable().getCellEditor().cancelCellEditing();
968
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
969
                // refresh();
970
                refreshControls();
971
        }
972

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

    
990
                edAdapter.endComplexRow(PluginServices.getText(this, "remove_fields"));
991
                clearSelectedFields();
992
                getModel().setModel(edAdapter); // Para que se recalculen los campos. TODO: Limpiear todo esto
993
                // refresh();
994
                refreshControls();
995
            } catch (ReadDriverException e) {
996
                    e.printStackTrace();
997
                        NotificationManager.addError(e);
998
                } catch (WriteDriverException e) {
999
                        e.printStackTrace();
1000
                        NotificationManager.addError(e);
1001
                }
1002

    
1003
    }
1004

    
1005
    /**
1006
     * Return if we have rows copied or not.
1007
     *
1008
     * @return True if we have rows copied.
1009
     */
1010
    public boolean isCopied() {
1011
        return (rowsCopied != null);
1012
    }
1013

    
1014
    /**
1015
     * Paste the arraylist rows.
1016
     * @throws ExpansionFileWriteException
1017
     * @throws ReadDriverException
1018
     * @throws ValidateRowException
1019
     *
1020
     * @throws DriverIOException
1021
     * @throws IOException
1022
     */
1023
    public void pasteRow() throws ValidateRowException, ReadDriverException, ExpansionFileWriteException {
1024
        addRow(rowsCopied);
1025
        //repaintAssociatedView();
1026
    }
1027

    
1028
    /**
1029
     * DOCUMENT ME!
1030
     */
1031
    public void windowActivated() {
1032
        //if (isEditing() && getModel().getModelo() instanceof VectorialEditableAdapter)
1033
        updateSelection();
1034
    }
1035

    
1036
    /**
1037
     * DOCUMENT ME!
1038
     */
1039
    public void windowClosed() {
1040
        // TODO Auto-generated method stub
1041
    }
1042

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

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

    
1087
                public void keyPressed(KeyEvent arg0) {
1088
                        //JTextField tf=(JTextField)table.getEditorComponent();
1089
                        //table.setCellSelectionEnabled(true);
1090
                        //FocusManager fm = FocusManager.getCurrentManager();
1091
                        //fm.focusPreviousComponent(table);
1092
                }
1093

    
1094
                public void keyReleased(KeyEvent ke) {
1095
                        int[] row=table.getSelectedRows();
1096
                    int[] column=table.getSelectedColumns();
1097
                    initEditField(column,row);
1098
                }
1099

    
1100
                public void keyTyped(KeyEvent arg0) {
1101
                        // TODO Auto-generated method stub
1102

    
1103
                }
1104

    
1105
    }
1106

    
1107
    /**
1108
     * DOCUMENT ME!
1109
     *
1110
     * @author Vicente Caballero Navarro
1111
     */
1112
    private class MouseRow extends MouseAdapter {
1113
               public void mouseReleased(MouseEvent arg0) {
1114
                        super.mouseReleased(arg0);
1115
                        int[] row=table.getSelectedRows();
1116
                    int[] column=table.getSelectedColumns();
1117
                    initEditField(column,row);
1118
                }
1119

    
1120
                /**
1121
         * DOCUMENT ME!
1122
         *
1123
         * @param e DOCUMENT ME!
1124
         */
1125
    /*    public void mouseClicked(MouseEvent e) {
1126
            super.mouseClicked(e);
1127

1128

1129
                PluginServices.getMainFrame().enableControls();
1130

1131
            if (e.getButton() == MouseEvent.BUTTON3) {
1132
                new PopupMenu(e.getPoint());
1133
            }
1134
        }
1135
*/
1136
    }
1137

    
1138
        public void commandRepaint() {
1139
                refresh();
1140
        }
1141

    
1142
        public void commandRefresh() {
1143
                commandRepaint();
1144
        }
1145

    
1146
        public void toPalette() {
1147
                isPalette=true;
1148
                m_viewInfo.toPalette(true);
1149
                m_viewInfo.setClosed(false);
1150
                PluginServices.getMDIManager().changeWindowInfo(this,getWindowInfo());
1151
        }
1152

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

    
1160
        public boolean isPalette() {
1161
                return isPalette;
1162
        }
1163

    
1164
        public static void main(String[] args) {
1165
                JTextField tf=new JTextField("hola");
1166
                tf.selectAll();
1167
                JFrame frame=new JFrame();
1168
                frame.getContentPane().add(tf);
1169
                frame.setVisible(true);
1170
        }
1171

    
1172
        public void stopEditingCell() {
1173
            if (table.isEditing()) {
1174

    
1175
                    // TODO: finalizar la edicion de la columna
1176
                    this.table.getCellEditor().stopCellEditing();
1177
                    this.refresh();
1178

    
1179
            }
1180

    
1181
        }
1182

    
1183
        public void cancelEditingCell() {
1184
            if (table.isEditing()) {
1185
                    // TODO: finalizar la edicion de la columna
1186
                    this.table.getCellEditor().cancelCellEditing();
1187
                    this.refresh();
1188
            }
1189

    
1190
        }
1191

    
1192
        public void processEvent(EditionEvent e) {
1193
                if (e.getChangeType() == EditionEvent.STOP_EDITION)
1194
                {
1195
                        refreshControls();
1196
                }
1197

    
1198
        }
1199

    
1200
        public void beforeRowEditEvent(IRow feat, BeforeRowEditEvent e) {
1201
                // TODO Auto-generated method stub
1202

    
1203
        }
1204

    
1205
        public void afterRowEditEvent(IRow feat, AfterRowEditEvent e) {
1206
                // TODO Auto-generated method stub
1207

    
1208
        }
1209

    
1210
        public void beforeFieldEditEvent(BeforeFieldEditEvent e) {
1211
                // TODO Auto-generated method stub
1212

    
1213
        }
1214

    
1215
        public void afterFieldEditEvent(AfterFieldEditEvent e) {
1216
                        try {
1217
                                getModel().createAlias();
1218
                        } catch (ReadDriverException e1) {
1219
                                NotificationManager.showMessageError(
1220
                                                PluginServices.getText(this, "Error creating table aliases"), e1);
1221
                        }
1222
                        clearSelectedFields();
1223
//                        refresh();
1224
                        refreshControls();
1225
                // ((DataSourceDataModel) getTable().getModel()).fireTableDataChanged();
1226

    
1227
        }
1228

    
1229
        public Object getWindowProfile() {
1230
                return WindowInfo.EDITOR_PROFILE;
1231
        }
1232
}