Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.plugin / org.gvsig.labeling.app / org.gvsig.labeling.app.mainplugin / src / main / java / org / gvsig / labeling / gui / layerproperties / LabelClassProperties.java @ 41676

History | View | Annotate | Download (29.7 KB)

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

    
43
import java.awt.BorderLayout;
44
import java.awt.Component;
45
import java.awt.Dimension;
46
import java.awt.FlowLayout;
47
import java.awt.GridBagConstraints;
48
import java.awt.GridBagLayout;
49
import java.awt.GridLayout;
50
import java.awt.event.ActionEvent;
51
import java.awt.event.ActionListener;
52
import java.util.logging.Level;
53

    
54
import javax.swing.AbstractCellEditor;
55
import javax.swing.BorderFactory;
56
import javax.swing.ButtonGroup;
57
import javax.swing.JButton;
58
import javax.swing.JCheckBox;
59
import javax.swing.JComponent;
60
import javax.swing.JLabel;
61
import javax.swing.JOptionPane;
62
import javax.swing.JPanel;
63
import javax.swing.JRadioButton;
64
import javax.swing.JScrollPane;
65
import javax.swing.JTable;
66
import javax.swing.JTextField;
67
import javax.swing.table.DefaultTableModel;
68
import javax.swing.table.TableCellEditor;
69
import javax.swing.table.TableColumnModel;
70

    
71
import org.gvsig.andami.ui.mdiManager.IWindow;
72
import org.gvsig.andami.ui.mdiManager.WindowInfo;
73
import org.gvsig.app.ApplicationLocator;
74
import org.gvsig.app.gui.labeling.LabelClassEditor;
75
import org.gvsig.app.gui.styling.SingleStyleSelectorFilter;
76
import org.gvsig.app.gui.styling.StylePreviewer;
77
import org.gvsig.app.gui.styling.StyleSelector;
78
import org.gvsig.fmap.dal.exception.DataException;
79
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
80
import org.gvsig.fmap.dal.feature.FeatureStore;
81
import org.gvsig.fmap.dal.feature.FeatureType;
82
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelClass;
83
import org.gvsig.fmap.mapcontext.rendering.symbols.ITextSymbol;
84
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.ILabelStyle;
85
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
86
import org.gvsig.gui.beans.AcceptCancelPanel;
87
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
88
import org.gvsig.gui.beans.swing.JBlank;
89
import org.gvsig.i18n.Messages;
90
import org.gvsig.labeling.lang.LabelClassUtils;
91
import org.slf4j.Logger;
92
import org.slf4j.LoggerFactory;
93

    
94

    
95
/**
96
 *
97
 * LabelClassProperties.java
98
 *
99
 *
100
 * @author jaume dominguez faus - jaume.dominguez@iver.es May 27, 2008
101
 *
102
 */
103
public class LabelClassProperties extends JPanel implements LabelClassEditor, IWindow,
104
ActionListener {
105
        
106
        private static final Logger logger =
107
                        LoggerFactory.getLogger(LabelClassProperties.class);
108
        
109
        private static final String TEST_SQL = "TEST_SQL";
110
        private static final String DELETE_FIELD = "DELETE_FIELD";
111
        private static final long serialVersionUID = 6528513396536811057L;
112
        private static final String ADD_FIELD = "ADD_FIELD";
113
        private static final String SELECT_STYLE = "SELECT_STYLE";
114
        private static final String CLEAR_STYLE = "CLEAR_STYLE";
115
        private static final String VERIFY = "VERIFY";
116
        private JTextField txtName;
117
        private ILabelClass lc, clonedClass;
118
        private JTable tblExpressions;
119
        private JButton btnRemoveField;
120
        private JButton btnAddField;
121
        private JButton btnVerify;
122
        private JComponent styPreviewer;
123
        private JButton btnSelStyle;
124
        private JRadioButton rdBtnFilteredFeatures;
125
        private JRadioButton rdBtnAllFeatures;
126
        private JTextField txtSQL;
127
        private JCheckBox chkLabelFeatures;
128
        private LabelTextStylePanel textStyle;
129
        private JPanel sqlPnl;
130
        private LabelClassPreview labelPreview;
131
        
132
        /*
133
        private String[] fieldNames;
134
        private int[] fieldTypes;
135
        */
136
        private FeatureStore featureStore = null;
137
        private JButton btnDontUseStyle;
138
        private boolean accepted = true;
139
        private AcceptCancelPanel acceptCancelPanel;
140

    
141

    
142

    
143
        /**
144
         * <p>
145
         * Creates a new instance of the dialog that configures all the properties
146
         * of a LabelClass.
147
         * </p>
148
         * @param strategy
149
         * @param asWindow
150
         */
151
        public LabelClassProperties(FeatureStore fsto) {
152

    
153
                featureStore = fsto;
154
                initialize();
155
        }
156

    
157
        private void initialize() {
158
                setPreferredSize(new Dimension(810, 580));
159
                setLayout(new BorderLayout(1, 1));
160

    
161
                txtName = new JTextField(40);
162
                JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 15, 2));
163
                northPanel.add(new JLabel(Messages.getText("name") + ":"));
164
                northPanel.add(txtName);
165
                add(northPanel, BorderLayout.NORTH);
166

    
167
                JPanel centerPanel = new JPanel(new BorderLayout(10, 10));
168
                textStyle = new LabelTextStylePanel();
169
                textStyle.addActionListener(this);
170
                centerPanel.add(textStyle, BorderLayout.NORTH);
171

    
172
                JPanel labelExpressionsPanel = new JPanel(new BorderLayout(1, 1));
173

    
174
                labelExpressionsPanel.add(new JBlank(10, 30), BorderLayout.WEST);
175
                labelExpressionsPanel.add(new JScrollPane(getTableFields()),
176
                                BorderLayout.CENTER);
177

    
178
                JPanel a = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 0));
179
                a.add(new JLabel("<html><b>"+Messages.getText("text_fields")+"</b></html>"));
180
                centerPanel.add(labelExpressionsPanel, BorderLayout.CENTER);
181
                
182
                
183
                GridLayout gbl = new GridLayout(3, 1, 0, 6);
184
                JPanel auxp = new JPanel(gbl);
185
                auxp.add(getBtnVerify());
186
                auxp.add(getBtnAddField());
187
                auxp.add(getBtnRemoveField());
188
                auxp.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
189
                JPanel auxpp = new JPanel();
190
                auxpp.add(auxp);
191
                
192
                centerPanel.add(auxpp, BorderLayout.EAST);
193

    
194

    
195
                GridBagLayoutPanel aux = new GridBagLayoutPanel();
196
//                aux.setBorder(BorderFactory.createTitledBorder(PluginServices.getText(
197
//                this, "features")));
198
                rdBtnAllFeatures = new JRadioButton(Messages.getText("all_features"));
199
                rdBtnFilteredFeatures = new JRadioButton(Messages.getText("filtered_features")
200
                                +" (SQL GDBMS)");
201

    
202
                rdBtnAllFeatures.addActionListener(this);
203
                rdBtnFilteredFeatures.addActionListener(this);
204

    
205
                ButtonGroup g = new ButtonGroup();
206
                g.add(rdBtnAllFeatures);
207
                g.add(rdBtnFilteredFeatures);
208
                aux.addComponent(chkLabelFeatures = new JCheckBox(
209
                                Messages.getText("label_features_in_this_class")));
210
                aux.addComponent("", rdBtnAllFeatures);
211
                aux.addComponent("", rdBtnFilteredFeatures);
212
                sqlPnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
213
                sqlPnl.add(new JLabel("   SQL: SELECT * FROM "));
214
                sqlPnl.add(new JLabel("<" + Messages.getText("layer_name")
215
                                + ">"));
216
                sqlPnl.add(new JLabel(" WHERE  "));
217
                sqlPnl.add(txtSQL = new JTextField(40));
218
                sqlPnl.add(new JLabel(";"));
219
                aux.addComponent("", sqlPnl);
220

    
221

    
222
                JPanel auxPanel = new JPanel(new BorderLayout(1,1));
223

    
224
                JPanel aux2 = new JPanel();
225
                auxPanel.setBorder(BorderFactory.createTitledBorder(
226
                                Messages.getText("background_style")));
227

    
228
                aux2.add(getStylePreviewer());
229

    
230
                gbl = new GridLayout(2, 1, 0, 6);
231
                JPanel aux3 = new JPanel(gbl);
232
                aux3.add(getBtnSelectStyle());
233
                aux3.add(getBtnDontUseStyle());
234
                aux3.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));
235
                auxpp = new JPanel();
236
                auxpp.add(aux3);
237

    
238
                auxPanel.add(aux2,BorderLayout.CENTER);
239
                auxPanel.add(auxpp,BorderLayout.EAST);
240

    
241
                JPanel aux4 = new JPanel(new GridLayout(1,2));
242
                aux4.add(auxPanel);
243
                aux2 = new JPanel(new BorderLayout());
244
                aux2.setBorder(BorderFactory.createTitledBorder(Messages.getText("preview")));
245
                aux2.add(labelPreview = new LabelClassPreview(), BorderLayout.CENTER);
246
                aux4.add(aux2);
247

    
248
                GridBagLayoutPanel aux5 = new GridBagLayoutPanel();
249
                aux5.addComponent("", aux);
250
                aux5.addComponent(new JBlank(3, 5));
251
                aux5.addComponent("", aux4);
252
                centerPanel.add(aux5, BorderLayout.SOUTH);
253
                add(centerPanel, BorderLayout.CENTER);
254
                this.acceptCancelPanel = new AcceptCancelPanel(this, this);
255
                add(this.acceptCancelPanel, BorderLayout.SOUTH);
256

    
257
                chkLabelFeatures.addActionListener(this);
258
                txtName.addActionListener(this);
259

    
260
        }
261
        
262
        public void setAcceptCancelVisible(boolean visible) {
263
            this.acceptCancelPanel.setVisible(visible);
264
        }
265

    
266
        private JComponent getStylePreviewer() {
267

    
268
                if (styPreviewer == null) {
269
                        styPreviewer = new StylePreviewer();
270
                        styPreviewer.setPreferredSize(new java.awt.Dimension(90,90));
271
                        styPreviewer.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
272
                        ((StylePreviewer) styPreviewer).setShowOutline(true);
273
                }
274
                return styPreviewer;
275

    
276
        }
277

    
278
        private JButton getBtnSelectStyle() {
279
                if (btnSelStyle == null) {
280
                        btnSelStyle = new JButton(Messages.getText("select"));
281
                        btnSelStyle.setActionCommand(SELECT_STYLE);
282
                        btnSelStyle.addActionListener(this);
283
                }
284

    
285
                return btnSelStyle;
286
        }
287

    
288

    
289
        private JButton getBtnRemoveField() {
290
                if (btnRemoveField == null) {
291
                        btnRemoveField = new JButton(Messages.getText("remove"));
292
                        btnRemoveField.setActionCommand(DELETE_FIELD);
293
                        btnRemoveField.addActionListener(this);
294
                }
295

    
296
                return btnRemoveField;
297
        }
298

    
299
        private JButton getBtnAddField() {
300
                if (btnAddField == null) {
301
                        btnAddField = new JButton(Messages.getText("add"));
302
                        btnAddField.setActionCommand(ADD_FIELD);
303
                        btnAddField.addActionListener(this);
304
                }
305

    
306
                return btnAddField;
307
        }
308

    
309
        private JButton getBtnVerify() {
310
                if(btnVerify == null) {
311
                        btnVerify = new JButton(Messages.getText("verify"));
312
                        btnVerify.setActionCommand(VERIFY);
313
                        btnVerify.addActionListener(this);
314
                }
315
                return btnVerify;
316
        }
317

    
318
        private JButton getBtnDontUseStyle() {
319
                if (btnDontUseStyle == null) {
320
                        btnDontUseStyle = new JButton(Messages.getText("no_style"));
321
                        btnDontUseStyle.setActionCommand(CLEAR_STYLE);
322
                        btnDontUseStyle.addActionListener(this);
323
                }
324

    
325
                return btnDontUseStyle;
326
        }
327

    
328
        private JTable getTableFields() {
329
                if (tblExpressions == null) {
330
                        tblExpressions = new JTable();
331
                        tblExpressions.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
332
                }
333

    
334
                return tblExpressions;
335
        }
336

    
337

    
338
        private void setComponentEnabled(Component c, boolean b) {
339
                if (c instanceof JComponent) {
340
                        JComponent c1 = (JComponent) c;
341
                        for (int i = 0; i < c1.getComponentCount(); i++) {
342
                                setComponentEnabled(c1.getComponent(i), b);
343
                        }
344
                }
345
                c.setEnabled(b);
346
        }
347

    
348

    
349

    
350
        public void setLabelClass(ILabelClass labelClass) {
351
                if (labelClass == null)
352
                        return;
353

    
354
                lc = labelClass;
355
                
356
                try {
357
                    clonedClass = (ILabelClass) lc.clone();
358
                } catch (CloneNotSupportedException ex) {
359
                    clonedClass = lc;
360
                }
361

    
362
                labelPreview.setLabelClass(clonedClass);
363
                boolean clo_use_sql = LabelClassUtils.isUseSqlQuery(clonedClass); 
364
                if (!clo_use_sql) {
365
                        rdBtnAllFeatures.setSelected(true);
366
                        txtSQL.setText("");
367
                } else {
368
                        rdBtnFilteredFeatures.setSelected(true);
369
                        txtSQL.setText(clonedClass.getSQLQuery());
370
                }
371

    
372
                chkLabelFeatures.setSelected(clonedClass.isVisible());
373
                rdBtnFilteredFeatures.setSelected(clo_use_sql);
374
                rdBtnAllFeatures.setSelected(!clo_use_sql);
375
                ((StylePreviewer) styPreviewer).setStyle(clonedClass.getLabelStyle());
376
                txtName.setText(clonedClass.getName());
377
                
378
                // String expr = lc.getStringLabelExpression();
379

    
380
                /*
381
                String EOExpr = LabelExpressionParser.tokenFor(LabelExpressionParser.EOEXPR);
382
                if (expr == null)
383
                        expr = EOExpr;
384
                expr = expr.trim();
385
                if (!expr.endsWith(EOExpr)) {
386
                        throw new Error("Invalid expression. Missing EOExpr token ("+EOExpr+").\n"+expr);
387
                }
388
                expr = expr.substring(0, expr.length()-1);
389
                */
390

    
391
                // expr = expr.trim();
392

    
393
                ITextSymbol lcTextSymbol = lc.getTextSymbol();
394
                ITextSymbol clonedSymbol = null;
395
                
396
                try {
397
                        clonedSymbol = (ITextSymbol) lcTextSymbol.clone();
398
                } catch (CloneNotSupportedException e) {
399
                        logger.error("While clonin.", e);
400
                }
401

    
402
                textStyle.setModel(
403
                                clonedSymbol, //lc.getTextSymbol(),
404
                                lc.getUnit(),
405
                                lc.getReferenceSystem());
406

    
407
                getTableFields().setRowHeight(22);
408
                getTableFields().setModel(new FieldTableExpressions(lc.getLabelExpressions()));
409
                TableColumnModel colMod = getTableFields().getColumnModel();
410
                colMod.getColumn(0).setPreferredWidth(100);
411
                colMod.getColumn(0).setWidth(100);
412
                colMod.getColumn(1).setResizable(true);
413
                colMod.getColumn(1).setPreferredWidth(513);
414
                
415
                FeatureAttributeDescriptor[] atts = null;
416
                
417
                try {
418
                        atts = featureStore.getDefaultFeatureType().getAttributeDescriptors();
419
                } catch (DataException e) {
420
                        logger.error("While getting attributes.", e);
421
                }
422
                
423
                getTableFields().setDefaultEditor(
424
                                Object.class,
425
                                new DefaultEditor(atts));
426
                repaint();
427

    
428
                actionPerformed(new ActionEvent(this, 0, null));
429
        }
430

    
431
        public JComponent asJComponent() {
432
            return this;
433
        }
434

    
435
        public void showDialog() {
436
            ApplicationLocator.getManager().getUIManager().addWindow(this);
437
        }
438

    
439
        private class DefaultEditor extends AbstractCellEditor implements
440
                        TableCellEditor, ActionListener {
441

    
442
                JPanel editor;
443
                LabelExpressionEditorPanel dialog;
444
                private JTextField text;
445
                private JButton button;
446
                protected static final String EDIT = "edit";
447

    
448
                public DefaultEditor(FeatureAttributeDescriptor[] atts) {
449
                        editor = new JPanel();
450
                        editor.setLayout(new GridBagLayout());
451
                        GridBagConstraints cons = new GridBagConstraints();
452
//                        cons.anchor = GridBagConstraints.FIRST_LINE_START;
453
                        cons.fill = cons.BOTH;
454
                        cons.weightx=1.0;
455
                        cons.weighty =1.0;
456
                        text = new JTextField();
457
                        editor.add(text, cons);
458

    
459
                        GridBagConstraints cons1 = new GridBagConstraints();
460
//                        cons.anchor = GridBagConstraints.FIRST_LINE_END;
461
                        cons1.fill = cons1.VERTICAL;
462
                        cons1.weighty =1.0;
463
//                        cons.gridheight = GridBagConstraints.REMAINDER;
464
                        button = new JButton("...");
465
                        button.setActionCommand(DefaultEditor.EDIT);
466
                        button.addActionListener(this);
467
                        editor.add(button,cons1);
468

    
469
                        editor.updateUI();
470

    
471
                        // Set up the dialog that the button brings up.
472
                        dialog = new LabelExpressionEditorPanel(atts);
473
                }
474

    
475
                public void actionPerformed(ActionEvent e) {
476
                        if (EDIT.equals(e.getActionCommand())) {
477

    
478
                                dialog.setValue(text.getText());
479
                                ApplicationLocator.getManager().getUIManager().addWindow(dialog);
480
                                //fireEditingStopped(); // Make the renderer reappear.
481
                                text.setText(dialog.getValue());
482
                        }
483
                }
484

    
485
                // Implement the one CellEditor method that AbstractCellEditor doesn't.
486
                public Object getCellEditorValue() {
487
                        return text.getText();
488
                }
489

    
490
                // Implement the one method defined by TableCellEditor.
491
                public Component getTableCellEditorComponent(JTable table,
492
                                Object value, boolean isSelected, int row, int column) {
493
                        text.setText((String) value);
494
                        return editor;
495
                }
496
        }
497

    
498

    
499

    
500

    
501
        public WindowInfo getWindowInfo() {
502
                WindowInfo wi = new WindowInfo(WindowInfo.MODALDIALOG
503
                                | WindowInfo.RESIZABLE);
504
                wi.setTitle(Messages.getText("label_class_properties"));
505
                wi.setWidth(getPreferredSize().width + 8);
506
                wi.setHeight(getPreferredSize().height);
507
                return wi;
508
        }
509

    
510
        public Object getWindowProfile() {
511
                return WindowInfo.DIALOG_PROFILE;
512
        }
513

    
514

    
515
        /*
516
         * Return a hashtable with example values.
517
         * Only for verification purposes.
518
        private Hashtable<String, Value> getValuesTable(String[] fNames, int[] fTypes) {
519
                
520
                Hashtable<String, Value> parser_symbol_table = new Hashtable<String, Value>();
521

522
                Random rand = new Random();
523
                byte b = 0;
524
            short s = (short)rand.nextInt(Short.MAX_VALUE);
525
            int i = rand.nextInt();
526
                long l = rand.nextLong();
527
                boolean bool = rand.nextBoolean();
528
                float f = rand.nextFloat();
529
                double d = rand.nextDouble();
530

531
                for (int j = 0; j < fNames.length; j++) {
532
                        Value value=null;
533

534
                        int type = fTypes[j];
535
            switch (type) {
536
            case Types.BIGINT:
537
                value = ValueFactory.createValue(l);
538
                break;
539
            case Types.BIT:
540
            case Types.BOOLEAN:
541
                value = ValueFactory.createValue(bool);
542
                break;
543
            case Types.CHAR:
544
            case Types.VARCHAR:
545
            case Types.LONGVARCHAR:
546
                value = ValueFactory.createValue("");
547
                break;
548
            case Types.DATE:
549
                Date auxDate = new Date();
550
                    if (auxDate != null){
551
                    value = ValueFactory.createValue(auxDate);
552
                    }
553
                break;
554
            case Types.DECIMAL:
555
            case Types.NUMERIC:
556
            case Types.FLOAT:
557
            case Types.DOUBLE:
558
                value = ValueFactory.createValue(d);
559
                break;
560
            case Types.INTEGER:
561
                value = ValueFactory.createValue(i);
562
                break;
563
            case Types.REAL:
564
                value = ValueFactory.createValue(f);
565
                break;
566
            case Types.SMALLINT:
567
                value = ValueFactory.createValue(s);
568
                break;
569
            case Types.TINYINT:
570
                value = ValueFactory.createValue(b);
571
                break;
572
            case Types.BINARY:
573
            case Types.VARBINARY:
574
            case Types.LONGVARBINARY:
575
                byte[] auxByteArray = {b}; //new byte[1];
576
                value = ValueFactory.createValue(auxByteArray);
577
                break;
578
            case Types.TIMESTAMP:
579
                           value = ValueFactory.createValue(new Timestamp(l));
580
                break;
581
            case Types.TIME:
582
                    value = ValueFactory.createValue(new Time(l));
583
                break;
584
            default:
585
                    value = ValueFactory.createValue("");
586
                    break;
587
        }
588
                        parser_symbol_table.put(fNames[j], value);
589
                }
590
                return parser_symbol_table;
591
        }
592
                 */
593

    
594

    
595
        /*
596
        private boolean verifyExpresion(String expresion, Hashtable<String, Value> symbols){
597
                LabelExpressionParser parser;
598
                try {
599
                        parser = new LabelExpressionParser(new StringReader(expresion),symbols);
600
                        parser.LabelExpression();
601
                        Expression expr = ((Expression)parser.getStack().pop());
602
                        expr.evaluate();
603
                } catch (ExpressionException e2) {
604
                        return false;
605
                } catch (Exception e3) {
606
                        return false;
607
                }
608
                return true;
609
        }
610
        */
611

    
612
        private boolean verifyExpressions(){
613
                
614
                String[] expressions = ((FieldTableExpressions) getTableFields().getModel()).getExpression();
615
                if(expressions.length == 1 && expressions[0].equals("")){
616
                        return true;
617
                }
618
                boolean result = true;
619
                String message = "";
620
                for (int i = 0; i < expressions.length; i++) {
621
                        String expresion = expressions[i];
622
                        
623
                        if( !LabelClassUtils.validExpression(expresion, featureStore, false) ){
624
                                result = false;
625
                                if(message.compareTo("")!=0){
626
                                        message = message +        " , " + (i+1);
627
                                } else {
628
                                        message = " " + Messages.getText("at_fields")+" "+(i+1);
629
                                }
630
                        }
631
                }
632
                message = message +".";
633
                if(!result){
634
                        JOptionPane.showMessageDialog(
635
                                        ApplicationLocator.getManager().getRootComponent(),
636
                                        Messages.getText("malformed_or_empty_expression") + message,
637
                                        Messages.getText("verify"),
638
                                        JOptionPane.ERROR_MESSAGE);
639
                } else {
640
                        JOptionPane.showMessageDialog(
641
                                        ApplicationLocator.getManager().getRootComponent(),
642
                                        Messages.getText("_Expressions_are_correct"),
643
                                        Messages.getText("verify"),
644
                                        JOptionPane.INFORMATION_MESSAGE);
645
                }
646
                return result;
647
        }
648

    
649
        public boolean isAccepted(){
650
                return accepted;
651
        }
652
        
653
        public void doCancel() {
654
            accepted = false;
655
            setLabelClass(lc);        
656
        }
657

    
658
        public void doAccept() {
659
            if (rdBtnFilteredFeatures.isSelected()) {
660
                String sqlstr = txtSQL.getText();
661
                if (!validVisibleSQL(sqlstr, featureStore)) {
662
                    JOptionPane.showMessageDialog(
663
                            ApplicationLocator.getManager().getRootComponent(),
664
                            Messages.getText("error_validating_filter_query")
665
                            + ":\n\n'" + sqlstr + "'",
666
                            Messages.getText("filtered_features"),
667
                            JOptionPane.ERROR_MESSAGE);
668
                    return;
669
                }
670
            }
671
            clonedClass.setUnit(textStyle.getUnit());
672
            clonedClass.setReferenceSystem(textStyle.getReferenceSystem());
673
            clonedClass.setTextSymbol(textStyle.getTextSymbol());
674
            lc = clonedClass;
675
            accepted = true;
676
        }
677

    
678
        public void actionPerformed(ActionEvent e) {
679
                setComponentEnabled(sqlPnl, rdBtnFilteredFeatures.isSelected());
680
                
681
                applySettings();
682
                
683
                if ("OK".equals(e.getActionCommand())) {
684
                        doAccept();
685
                        try {
686
                                ApplicationLocator.getManager().getUIManager().closeWindow(this);
687
                        } catch (Exception ex) {
688
                                // this only happens when running this as stand-alone app
689
                                // from main method;
690
                                logger.warn("While closing window.", ex);
691
                        }
692
                } else if ("CANCEL".equals(e.getActionCommand())) {
693
                        doCancel();
694
                        try {
695
                                ApplicationLocator.getManager().getUIManager().closeWindow(this);
696
                        } catch (Exception ex) {
697
                                // this only happens when running this as stand-alone app
698
                                // from main method;
699
                                logger.warn("While closing window.", ex);
700
                        }
701
                } else if (CLEAR_STYLE.equals(e.getActionCommand())) {
702
                        clonedClass.setLabelStyle(null);
703
//                        styPreviewer.setStyle(null);
704
                        ((StylePreviewer) styPreviewer).setStyle(null);
705
                } else if (TEST_SQL.equals(e.getActionCommand())) {
706
                        logger.info("TEST_SQL = " + TEST_SQL);
707
                } else if (DELETE_FIELD.equals(e.getActionCommand())) {
708
                        int[] rowInd = getTableFields().getSelectedRows();
709
                        for (int i = rowInd.length-1; i >= 0 ; i--) {
710
                                delField(rowInd[i]);
711
                        }
712
                        clonedClass.setLabelExpressions(((FieldTableExpressions) getTableFields().getModel()).getExpression());
713
                        setLabelClass(clonedClass);
714
                } else if (VERIFY.equals(e.getActionCommand())) {
715
                        verifyExpressions();
716
                } else if (ADD_FIELD.equals(e.getActionCommand())) {
717
                        addField();
718
                } else if (SELECT_STYLE.equals(e.getActionCommand())) {
719

    
720
                        IStyle myStyle = ((StylePreviewer)styPreviewer).getStyle();
721
                        
722
                        FeatureType fty = null;
723
                        
724
                        try {
725
                                fty = featureStore.getDefaultFeatureType();
726
                        } catch (DataException e1) {
727
                                logger.error("While getting feat type.", e1);
728
                        }
729
                        
730
                        int geotype = fty.getDefaultGeometryAttribute().getGeomType().getType();
731
                        
732
                        SingleStyleSelectorFilter filter =
733
                                        new SingleStyleSelectorFilter(ILabelStyle.class);
734
                        StyleSelector stySel = null;
735
                        
736
                        try {
737
                                stySel = new StyleSelector(myStyle, geotype, filter);
738
                        } catch (IllegalArgumentException iae) {
739
                                JOptionPane.showMessageDialog(this,
740
                                                Messages.getText("_Option_not_available_for_this_geometry_type"),
741
                                                getWindowInfo().getTitle(),
742
                                                JOptionPane.WARNING_MESSAGE);
743
                                return;
744
                        }
745
                        
746
                        ApplicationLocator.getManager().getUIManager().addWindow(stySel);
747
                        ILabelStyle sty = (ILabelStyle) stySel.getSelectedObject();
748

    
749
                        if (sty != null) {
750
                                // gather the style and apply to the class
751
                                clonedClass.setLabelStyle(sty);
752
                                clonedClass.setUnit(stySel.getUnit());
753
                                clonedClass.setReferenceSystem(stySel.getReferenceSystem());
754
                                setLabelClass(clonedClass);
755
                        }
756

    
757
//                        styPreviewer.setStyle(sty);
758
                        ((StylePreviewer) styPreviewer).setStyle(sty);
759

    
760
                }else if (e.getSource().equals(rdBtnAllFeatures) || e.getSource().equals(rdBtnFilteredFeatures)){
761
                        clonedClass.setUseSqlQuery(rdBtnFilteredFeatures.isSelected());
762
                }
763

    
764
                repaint();
765
        }
766

    
767
        private boolean validVisibleSQL(String sqlstr, FeatureStore fsto) {
768
            
769
            return LabelClassUtils.validExpression(sqlstr, fsto, true);
770
    }
771

    
772
    private void applySettings() {
773
            
774
                clonedClass.setVisible(chkLabelFeatures.isSelected());
775
                clonedClass.setName(txtName.getText());
776
                
777
                if (rdBtnFilteredFeatures.isSelected()) {
778
                    clonedClass.setSQLQuery(txtSQL.getText());
779
                } else {
780
                    clonedClass.setSQLQuery("");
781
                }
782
                
783
                JTable tableFields=getTableFields();
784
                TableCellEditor cellEditor=tableFields.getCellEditor();
785
                if(cellEditor != null){
786
                        int row = tableFields.getEditingRow();
787
                        int column = tableFields.getEditingColumn();
788
                        cellEditor.stopCellEditing();
789
                        Object value = cellEditor.getCellEditorValue();
790

    
791
                        if (value != null) {
792
                                ((FieldTableExpressions) tableFields.
793
                                                getModel()).setValueAt(value, row, column);
794
                        }
795
                }
796
                clonedClass.setLabelExpressions(
797
                                ((FieldTableExpressions) tableFields.
798
                                                getModel()).getExpression());
799
                clonedClass.setTextSymbol(textStyle.getTextSymbol());
800
        }
801

    
802
        private void addField() {
803
                addField("");
804
        }
805

    
806
        private void addField(String fieldExpr) {
807
                FieldTableExpressions m = ((FieldTableExpressions) getTableFields().getModel());
808
                m.addRow(new Object[] { m.getRowCount()+1, fieldExpr });
809
        }
810

    
811
        private void delField(int fieldIndex) {
812
                try {
813
                        ((FieldTableExpressions) getTableFields().getModel()).removeRow(fieldIndex);
814
                } catch (ArrayIndexOutOfBoundsException ex) {}
815
        }
816

    
817

    
818
        public ILabelClass getLabelClass() {
819
                return lc;
820
        }
821

    
822

    
823

    
824
        private static final Object[] TABLE_HEADERS = new String[] {
825
                
826
                Messages.getText("field_number"),
827
                Messages.getText("label_expression")
828
        };
829
        
830
        /*
831
        private static String fieldSeparator =
832
        LabelExpressionParser.tokenImage[LabelExpressionParser.EOFIELD].replaceAll("\"", "");
833
        */
834
        
835
        private class FieldTableExpressions extends DefaultTableModel {
836
                private static final long serialVersionUID = 2002427714889477770L;
837
                public FieldTableExpressions(String[] expressions) {
838
                        super();
839

    
840
                        if(expressions != null && expressions.length > 0){
841
                                Integer[] aux = new Integer[expressions.length];
842
                                for (int i = 0; i < aux.length; i++) {
843
                                        aux[i] = i+1;
844
                                }
845

    
846
                                Object[][] values = new Object[aux.length][2];
847
                                for (int i = 0; i < values.length; i++) {
848
                                        values[i][0] = aux[i];
849
                                        values[i][1] = expressions[i];
850
                                }
851
                                setDataVector(values, TABLE_HEADERS);
852
                        }
853
                        else{
854
                                Object[][] values = new Object[1][2];
855
                                values[0][0] = 1;
856
                                values[0][1] = "";
857
                                setDataVector(values,TABLE_HEADERS);
858
                        }
859

    
860
                }
861

    
862

    
863
                @Override
864
                public boolean isCellEditable(int row, int column) {
865
                        return column == 1;
866
                }
867

    
868
                public String[] getExpression() {
869

    
870
                        String[] expressions = new String[getRowCount()];
871

    
872
                        for (int i = 0; i < getRowCount(); i++) {
873
                                expressions[i] = ""+(String) getValueAt(i,1);
874
                        }
875
                        return expressions;
876
                }
877

    
878
        }
879

    
880
//        public static void main(String[] args) {
881
//                JFrame f = new JFrame("Test LabelClassProperties panel");
882
//
883
//                String xmlString =
884
//                        "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" +
885
//                        "<xml-tag xmlns=\"http://www.gvsig.gva.es\">\n" +
886
//                        "    <property key=\"className\" value=\"com.iver.cit.gvsig.fmap.rendering.styling.labeling.LabelClass\"/>\n" +
887
//                        "    <property key=\"isVisible\" value=\"false\"/>\n" +
888
//                        "    <property key=\"name\" value=\"Default\"/>\n" +
889
//                        "    <property key=\"labelExpression\" value=\"[TIPO] : lao39805502232 : Substring([MOTO], 2,2);\"/>\n" +
890
//                        "    <property key=\"unit\" value=\"-1\"/>\n" +
891
//                        "    <property key=\"referenceSystem\" value=\"0\"/>\n" +
892
//                        "    <property key=\"sqlQuery\" value=\"TIPO = 'C'\"/>\n" +
893
//                        "    <property key=\"priority\" value=\"0\"/>\n" +
894
//                        "    <xml-tag>\n" +
895
//                        "        <property key=\"className\" value=\"org.gvsig.symbology.fmap.styles.SimpleLabelStyle\"/>\n" +
896
//                        "        <property key=\"desc\" value=\"Placa Carrer VLC.style\"/>\n" +
897
//                        "        <property key=\"markerPointX\" value=\"0.0\"/>\n" +
898
//                        "        <property key=\"markerPointY\" value=\"0.0\"/>\n" +
899
//                        "        <property key=\"minXArray\" value=\"0.35 ,0.25\"/>\n" +
900
//                        "        <property key=\"minYArray\" value=\"0.15 ,0.5\"/>\n" +
901
//                        "        <property key=\"widthArray\" value=\"0.5 ,0.6\"/>\n" +
902
//                        "        <property key=\"heightArray\" value=\"0.27 ,0.37\"/>\n" +
903
//                        "        <property key=\"id\" value=\"labelStyle\"/>\n" +
904
//                        "        <xml-tag>\n" +
905
//                        "            <property key=\"className\" value=\"org.gvsig.symbology.fmap.styles.RemoteFileStyle\"/>\n" +
906
//                        "            <property key=\"source\" value=\"http://www.boomlapop.com/boomlapop.jpg\"/>\n" +
907
//                        "            <property key=\"desc\"/>\n" +
908
//                        "            <property key=\"id\" value=\"LabelStyle\"/>\n" +
909
//                        "        </xml-tag>\n" +
910
//                        "    </xml-tag>\n" +
911
//                        "    <xml-tag>\n" +
912
//                        "        <property key=\"className\" value=\"com.iver.cit.gvsig.fmap.core.symbols.SimpleTextSymbol\"/>\n" +
913
//                        "        <property key=\"desc\"/>\n" +
914
//                        "        <property key=\"isShapeVisible\" value=\"true\"/>\n" +
915
//                        "        <property key=\"font\" value=\"Arial\"/>\n" +
916
//                        "        <property key=\"fontStyle\" value=\"1\"/>\n" +
917
//                        "        <property key=\"size\" value=\"12\"/>\n" +
918
//                        "        <property key=\"text\" value=\"GeneralLabeling.sample_text\"/>\n" +
919
//                        "        <property key=\"textColor\" value=\"255,255,0,255\"/>\n" +
920
//                        "        <property key=\"unit\" value=\"-1\"/>\n" +
921
//                        "        <property key=\"referenceSystem\" value=\"0\"/>\n" +
922
//                        "        <property key=\"id\" value=\"TextSymbol\"/>\n" +
923
//                        "    </xml-tag>\n" +
924
//                        "</xml-tag>\n" +
925
//                        "";
926
//
927
//                LabelClass lc = null;
928
//                try {
929
//                        XMLEntity xml = new XMLEntity((XmlTag) XmlTag.unmarshal(
930
//                                        XMLEncodingUtils.getReader(new ByteArrayInputStream(xmlString.getBytes()))));
931
//                        lc = new LabelClass();
932
//                        lc.setXMLEntity(xml);
933
//                } catch (Exception e) {
934
//                        e.printStackTrace();
935
//                }
936
//                String[] names = new String[] { "Field1", "Field2", "Field3"        };
937
//                int[] types = new int[] { Types.VARCHAR, Types.INTEGER, Types.DOUBLE };
938
//                final LabelClassProperties lcp = new LabelClassProperties(
939
//                                names, types ) {
940
//                        private static final long serialVersionUID = -1843509415649666459L;
941
//
942
//                        @Override
943
//                        public void actionPerformed(ActionEvent e) {
944
//                                super.actionPerformed(e);
945
//                                if ("OK".equals(e.getActionCommand())) {
946
//                                        Sys tem.out.println(getLabelClass().getXMLEntity());
947
//                                }
948
//                        }
949
//                };
950
//                lcp.setLabelClass(lc);
951
//                f.setContentPane(lcp);
952
//                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
953
//                f.pack();
954
//                f.setVisible(true);
955
//
956
//        }
957

    
958
}