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 @ 42264

History | View | Annotate | Download (29.9 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.*;
44
import java.awt.event.ActionEvent;
45
import java.awt.event.ActionListener;
46
import java.util.logging.Level;
47

    
48
import javax.swing.AbstractCellEditor;
49
import javax.swing.BorderFactory;
50
import javax.swing.ButtonGroup;
51
import javax.swing.JButton;
52
import javax.swing.JCheckBox;
53
import javax.swing.JComponent;
54
import javax.swing.JLabel;
55
import javax.swing.JOptionPane;
56
import javax.swing.JPanel;
57
import javax.swing.JRadioButton;
58
import javax.swing.JScrollPane;
59
import javax.swing.JTable;
60
import javax.swing.JTextField;
61
import javax.swing.border.EmptyBorder;
62
import javax.swing.table.DefaultTableModel;
63
import javax.swing.table.TableCellEditor;
64
import javax.swing.table.TableColumnModel;
65

    
66
import org.gvsig.andami.ui.mdiManager.IWindow;
67
import org.gvsig.andami.ui.mdiManager.WindowInfo;
68
import org.gvsig.app.ApplicationLocator;
69
import org.gvsig.app.gui.labeling.LabelClassEditor;
70
import org.gvsig.app.gui.styling.SingleStyleSelectorFilter;
71
import org.gvsig.app.gui.styling.StylePreviewer;
72
import org.gvsig.app.gui.styling.StyleSelector;
73
import org.gvsig.fmap.dal.exception.DataException;
74
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
75
import org.gvsig.fmap.dal.feature.FeatureStore;
76
import org.gvsig.fmap.dal.feature.FeatureType;
77
import org.gvsig.fmap.mapcontext.rendering.legend.styling.ILabelClass;
78
import org.gvsig.fmap.mapcontext.rendering.symbols.ITextSymbol;
79
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.ILabelStyle;
80
import org.gvsig.fmap.mapcontext.rendering.symbols.styles.IStyle;
81
import org.gvsig.gui.beans.AcceptCancelPanel;
82
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
83
import org.gvsig.gui.beans.swing.JBlank;
84
import org.gvsig.i18n.Messages;
85
import org.gvsig.labeling.lang.LabelClassUtils;
86
import org.gvsig.tools.ToolsLocator;
87
import org.gvsig.tools.i18n.I18nManager;
88

    
89
import org.jfree.chart.block.EmptyBlock;
90
import org.slf4j.Logger;
91
import org.slf4j.LoggerFactory;
92

    
93

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

    
135
        /**
136
         * <p>
137
         * Creates a new instance of the dialog that configures all the properties
138
         * of a LabelClass.
139
         * </p>
140
         * @param strategy
141
         * @param asWindow
142
         */
143
        public LabelClassProperties(FeatureStore fsto) {
144

    
145
                featureStore = fsto;
146
                initialize();
147
        }
148

    
149
        private void initialize() {
150
            
151
            I18nManager i18nManager = ToolsLocator.getI18nManager();
152
            
153
                this.setPreferredSize(new Dimension(850, 580));
154
                this.setLayout(new BorderLayout());
155
                this.setBorder(new EmptyBorder(5, 5, 5, 5));
156

    
157

    
158
                JPanel northPanel = new JPanel();
159
                northPanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,5));
160
                
161
                JLabel lbl_name = new JLabel();
162
                lbl_name.setText(i18nManager.getTranslation("name").concat(":"));
163
                northPanel.add(lbl_name);
164

    
165
                txtName = new JTextField(40);
166
                northPanel.add(txtName);
167
                
168
                add(northPanel, BorderLayout.NORTH);
169

    
170
                
171
                JPanel centerPanel = new JPanel(new BorderLayout());
172
                
173
                textStyle = new LabelTextStylePanel();
174
                textStyle.addActionListener(this);
175
                centerPanel.add(textStyle, BorderLayout.NORTH);
176

    
177
                JPanel labelExpressionsPanel = new JPanel(new BorderLayout());
178
                labelExpressionsPanel.setBorder(new EmptyBorder(5, 7, 5, 5));
179
                labelExpressionsPanel.add(new JScrollPane(getTableFields()),
180
                                BorderLayout.CENTER);
181

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

    
197

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

    
204

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

    
226
                JPanel auxPanel = new JPanel(new BorderLayout());
227
                
228
                JPanel aux2 = new JPanel();
229
                auxPanel.setBorder(BorderFactory.createTitledBorder(
230
                                Messages.getText("background_style")));
231

    
232
                aux2.add(getStylePreviewer());
233

    
234
                gbl = new GridLayout(2, 1, 0, 5);
235
                JPanel aux3 = new JPanel(gbl);
236
                aux3.add(getBtnSelectStyle());
237
                aux3.add(getBtnDontUseStyle());
238
                aux3.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
239
                auxpp = new JPanel();
240
                auxpp.add(aux3);
241

    
242
                auxPanel.add(aux2,BorderLayout.WEST);
243
                auxPanel.add(auxpp,BorderLayout.EAST);
244

    
245
                JPanel aux4 = new JPanel(new GridLayout(1,2));
246
                aux4.add(auxPanel);
247
                aux2 = new JPanel(new BorderLayout());
248
                aux2.setBorder(BorderFactory.createTitledBorder(Messages.getText("preview")));
249
                aux2.add(new JBlank(5, 5), BorderLayout.NORTH);
250
                aux2.add(labelPreview = new LabelClassPreview(), BorderLayout.CENTER);
251
        aux2.add(new JBlank(5, 5), BorderLayout.WEST);
252
        aux2.add(new JBlank(5, 5), BorderLayout.EAST);
253
        aux2.add(new JBlank(5, 5), BorderLayout.SOUTH);
254
                aux4.add(aux2);
255

    
256
                GridBagLayoutPanel aux5 = new GridBagLayoutPanel();
257
                aux5.addComponent("", aux);
258
                aux5.addComponent("", aux4);
259
                centerPanel.add(aux5, BorderLayout.SOUTH);
260
                add(centerPanel, BorderLayout.CENTER);
261
                this.acceptCancelPanel = new AcceptCancelPanel(this, this);
262
                add(this.acceptCancelPanel, BorderLayout.SOUTH);
263

    
264
                chkLabelFeatures.addActionListener(this);
265
                txtName.addActionListener(this);
266

    
267
        }
268
        
269
        public void setAcceptCancelVisible(boolean visible) {
270
            this.acceptCancelPanel.setVisible(visible);
271
        }
272

    
273
        private JComponent getStylePreviewer() {
274

    
275
                if (styPreviewer == null) {
276
                        styPreviewer = new StylePreviewer();
277
                        styPreviewer.setPreferredSize(new java.awt.Dimension(90,90));
278
                        styPreviewer.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
279
                        ((StylePreviewer) styPreviewer).setShowOutline(true);
280
                }
281
                return styPreviewer;
282

    
283
        }
284

    
285
        private JButton getBtnSelectStyle() {
286
                if (btnSelStyle == null) {
287
                        btnSelStyle = new JButton(Messages.getText("select"));
288
                        btnSelStyle.setActionCommand(SELECT_STYLE);
289
                        btnSelStyle.addActionListener(this);
290
                }
291

    
292
                return btnSelStyle;
293
        }
294

    
295

    
296
        private JButton getBtnRemoveField() {
297
                if (btnRemoveField == null) {
298
                        btnRemoveField = new JButton(Messages.getText("remove"));
299
                        btnRemoveField.setActionCommand(DELETE_FIELD);
300
                        btnRemoveField.addActionListener(this);
301
                }
302

    
303
                return btnRemoveField;
304
        }
305

    
306
        private JButton getBtnAddField() {
307
                if (btnAddField == null) {
308
                        btnAddField = new JButton(Messages.getText("add"));
309
                        btnAddField.setActionCommand(ADD_FIELD);
310
                        btnAddField.addActionListener(this);
311
                }
312

    
313
                return btnAddField;
314
        }
315

    
316
        private JButton getBtnVerify() {
317
                if(btnVerify == null) {
318
                        btnVerify = new JButton(Messages.getText("verify"));
319
                        btnVerify.setActionCommand(VERIFY);
320
                        btnVerify.addActionListener(this);
321
                }
322
                return btnVerify;
323
        }
324

    
325
        private JButton getBtnDontUseStyle() {
326
                if (btnDontUseStyle == null) {
327
                        btnDontUseStyle = new JButton(Messages.getText("no_style"));
328
                        btnDontUseStyle.setActionCommand(CLEAR_STYLE);
329
                        btnDontUseStyle.addActionListener(this);
330
                }
331

    
332
                return btnDontUseStyle;
333
        }
334

    
335
        private JTable getTableFields() {
336
                if (tblExpressions == null) {
337
                        tblExpressions = new JTable();
338
                        tblExpressions.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
339
                }
340

    
341
                return tblExpressions;
342
        }
343

    
344

    
345
        private void setComponentEnabled(Component c, boolean b) {
346
                if (c instanceof JComponent) {
347
                        JComponent c1 = (JComponent) c;
348
                        for (int i = 0; i < c1.getComponentCount(); i++) {
349
                                setComponentEnabled(c1.getComponent(i), b);
350
                        }
351
                }
352
                c.setEnabled(b);
353
        }
354

    
355

    
356

    
357
        public void setLabelClass(ILabelClass labelClass) {
358
                if (labelClass == null)
359
                        return;
360

    
361
                lc = labelClass;
362
                
363
                try {
364
                    clonedClass = (ILabelClass) lc.clone();
365
                } catch (CloneNotSupportedException ex) {
366
                    clonedClass = lc;
367
                }
368

    
369
                labelPreview.setLabelClass(clonedClass);
370
                boolean clo_use_sql = LabelClassUtils.isUseSqlQuery(clonedClass); 
371
                if (!clo_use_sql) {
372
                        rdBtnAllFeatures.setSelected(true);
373
                        txtSQL.setText("");
374
                } else {
375
                        rdBtnFilteredFeatures.setSelected(true);
376
                        txtSQL.setText(clonedClass.getSQLQuery());
377
                }
378

    
379
                chkLabelFeatures.setSelected(clonedClass.isVisible());
380
                rdBtnFilteredFeatures.setSelected(clo_use_sql);
381
                rdBtnAllFeatures.setSelected(!clo_use_sql);
382
                ((StylePreviewer) styPreviewer).setStyle(clonedClass.getLabelStyle());
383
                txtName.setText(clonedClass.getName());
384
                
385
                // String expr = lc.getStringLabelExpression();
386

    
387
                /*
388
                String EOExpr = LabelExpressionParser.tokenFor(LabelExpressionParser.EOEXPR);
389
                if (expr == null)
390
                        expr = EOExpr;
391
                expr = expr.trim();
392
                if (!expr.endsWith(EOExpr)) {
393
                        throw new Error("Invalid expression. Missing EOExpr token ("+EOExpr+").\n"+expr);
394
                }
395
                expr = expr.substring(0, expr.length()-1);
396
                */
397

    
398
                // expr = expr.trim();
399

    
400
                ITextSymbol lcTextSymbol = lc.getTextSymbol();
401
                ITextSymbol clonedSymbol = null;
402
                
403
                try {
404
                        clonedSymbol = (ITextSymbol) lcTextSymbol.clone();
405
                } catch (CloneNotSupportedException e) {
406
                        logger.error("While clonin.", e);
407
                }
408

    
409
                textStyle.setModel(
410
                                clonedSymbol, //lc.getTextSymbol(),
411
                                lc.getUnit(),
412
                                lc.getReferenceSystem());
413

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

    
435
                actionPerformed(new ActionEvent(this, 0, null));
436
        }
437

    
438
        public JComponent asJComponent() {
439
            return this;
440
        }
441

    
442
        public void showDialog() {
443
            ApplicationLocator.getManager().getUIManager().addWindow(this);
444
        }
445

    
446
        private class DefaultEditor extends AbstractCellEditor implements
447
                        TableCellEditor, ActionListener {
448

    
449
                JPanel editor;
450
                LabelExpressionEditorPanel dialog;
451
                private JTextField text;
452
                private JButton button;
453
                protected static final String EDIT = "edit";
454

    
455
                public DefaultEditor(FeatureAttributeDescriptor[] atts) {
456
                        editor = new JPanel();
457
                        editor.setLayout(new GridBagLayout());
458
                        GridBagConstraints cons = new GridBagConstraints();
459
//                        cons.anchor = GridBagConstraints.FIRST_LINE_START;
460
                        cons.fill = cons.BOTH;
461
                        cons.weightx=1.0;
462
                        cons.weighty =1.0;
463
                        text = new JTextField();
464
                        editor.add(text, cons);
465

    
466
                        GridBagConstraints cons1 = new GridBagConstraints();
467
//                        cons.anchor = GridBagConstraints.FIRST_LINE_END;
468
                        cons1.fill = cons1.VERTICAL;
469
                        cons1.weighty =1.0;
470
//                        cons.gridheight = GridBagConstraints.REMAINDER;
471
                        button = new JButton("...");
472
                        button.setActionCommand(DefaultEditor.EDIT);
473
                        button.addActionListener(this);
474
                        editor.add(button,cons1);
475

    
476
                        editor.updateUI();
477

    
478
                        // Set up the dialog that the button brings up.
479
                        dialog = new LabelExpressionEditorPanel(atts);
480
                }
481

    
482
                public void actionPerformed(ActionEvent e) {
483
                        if (EDIT.equals(e.getActionCommand())) {
484

    
485
                                dialog.setValue(text.getText());
486
                                ApplicationLocator.getManager().getUIManager().addWindow(dialog);
487
                                //fireEditingStopped(); // Make the renderer reappear.
488
                                text.setText(dialog.getValue());
489
                        }
490
                }
491

    
492
                // Implement the one CellEditor method that AbstractCellEditor doesn't.
493
                public Object getCellEditorValue() {
494
                        return text.getText();
495
                }
496

    
497
                // Implement the one method defined by TableCellEditor.
498
                public Component getTableCellEditorComponent(JTable table,
499
                                Object value, boolean isSelected, int row, int column) {
500
                        text.setText((String) value);
501
                        return editor;
502
                }
503
        }
504

    
505

    
506

    
507

    
508
        public WindowInfo getWindowInfo() {
509
                WindowInfo wi = new WindowInfo(WindowInfo.MODALDIALOG
510
                                | WindowInfo.RESIZABLE);
511
                wi.setTitle(Messages.getText("label_class_properties"));
512
                wi.setWidth(getPreferredSize().width + 8);
513
                wi.setHeight(getPreferredSize().height);
514
                return wi;
515
        }
516

    
517
        public Object getWindowProfile() {
518
                return WindowInfo.DIALOG_PROFILE;
519
        }
520

    
521

    
522
        /*
523
         * Return a hashtable with example values.
524
         * Only for verification purposes.
525
        private Hashtable<String, Value> getValuesTable(String[] fNames, int[] fTypes) {
526
                
527
                Hashtable<String, Value> parser_symbol_table = new Hashtable<String, Value>();
528

529
                Random rand = new Random();
530
                byte b = 0;
531
            short s = (short)rand.nextInt(Short.MAX_VALUE);
532
            int i = rand.nextInt();
533
                long l = rand.nextLong();
534
                boolean bool = rand.nextBoolean();
535
                float f = rand.nextFloat();
536
                double d = rand.nextDouble();
537

538
                for (int j = 0; j < fNames.length; j++) {
539
                        Value value=null;
540

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

    
601

    
602
        /*
603
        private boolean verifyExpresion(String expresion, Hashtable<String, Value> symbols){
604
                LabelExpressionParser parser;
605
                try {
606
                        parser = new LabelExpressionParser(new StringReader(expresion),symbols);
607
                        parser.LabelExpression();
608
                        Expression expr = ((Expression)parser.getStack().pop());
609
                        expr.evaluate();
610
                } catch (ExpressionException e2) {
611
                        return false;
612
                } catch (Exception e3) {
613
                        return false;
614
                }
615
                return true;
616
        }
617
        */
618

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

    
656
        public boolean isAccepted(){
657
                return accepted;
658
        }
659
        
660
        public void doCancel() {
661
            accepted = false;
662
            setLabelClass(lc);        
663
        }
664

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

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

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

    
756
                        if (sty != null) {
757
                                // gather the style and apply to the class
758
                                clonedClass.setLabelStyle(sty);
759
                                clonedClass.setUnit(stySel.getUnit());
760
                                clonedClass.setReferenceSystem(stySel.getReferenceSystem());
761
                                setLabelClass(clonedClass);
762
                        }
763

    
764
//                        styPreviewer.setStyle(sty);
765
                        ((StylePreviewer) styPreviewer).setStyle(sty);
766

    
767
                }else if (e.getSource().equals(rdBtnAllFeatures) || e.getSource().equals(rdBtnFilteredFeatures)){
768
                        clonedClass.setUseSqlQuery(rdBtnFilteredFeatures.isSelected());
769
                }
770

    
771
                repaint();
772
        }
773

    
774
        private boolean validVisibleSQL(String sqlstr, FeatureStore fsto) {
775
            
776
            return LabelClassUtils.validExpression(sqlstr, fsto, true);
777
    }
778

    
779
    private void applySettings() {
780
            
781
                clonedClass.setVisible(chkLabelFeatures.isSelected());
782
                clonedClass.setName(txtName.getText());
783
                
784
                if (rdBtnFilteredFeatures.isSelected()) {
785
                    clonedClass.setSQLQuery(txtSQL.getText());
786
                } else {
787
                    clonedClass.setSQLQuery("");
788
                }
789
                
790
                JTable tableFields=getTableFields();
791
                TableCellEditor cellEditor=tableFields.getCellEditor();
792
                if(cellEditor != null){
793
                        int row = tableFields.getEditingRow();
794
                        int column = tableFields.getEditingColumn();
795
                        cellEditor.stopCellEditing();
796
                        Object value = cellEditor.getCellEditorValue();
797

    
798
                        if (value != null) {
799
                                ((FieldTableExpressions) tableFields.
800
                                                getModel()).setValueAt(value, row, column);
801
                        }
802
                }
803
                clonedClass.setLabelExpressions(
804
                                ((FieldTableExpressions) tableFields.
805
                                                getModel()).getExpression());
806
                clonedClass.setTextSymbol(textStyle.getTextSymbol());
807
        }
808

    
809
        private void addField() {
810
                addField("");
811
        }
812

    
813
        private void addField(String fieldExpr) {
814
                FieldTableExpressions m = ((FieldTableExpressions) getTableFields().getModel());
815
                m.addRow(new Object[] { m.getRowCount()+1, fieldExpr });
816
        }
817

    
818
        private void delField(int fieldIndex) {
819
                try {
820
                        ((FieldTableExpressions) getTableFields().getModel()).removeRow(fieldIndex);
821
                } catch (ArrayIndexOutOfBoundsException ex) {}
822
        }
823

    
824

    
825
        public ILabelClass getLabelClass() {
826
                return lc;
827
        }
828

    
829

    
830

    
831
        private static final Object[] TABLE_HEADERS = new String[] {
832
                
833
                Messages.getText("field_number"),
834
                Messages.getText("label_expression")
835
        };
836
        
837
        /*
838
        private static String fieldSeparator =
839
        LabelExpressionParser.tokenImage[LabelExpressionParser.EOFIELD].replaceAll("\"", "");
840
        */
841
        
842
        private class FieldTableExpressions extends DefaultTableModel {
843
                private static final long serialVersionUID = 2002427714889477770L;
844
                public FieldTableExpressions(String[] expressions) {
845
                        super();
846

    
847
                        if(expressions != null && expressions.length > 0){
848
                                Integer[] aux = new Integer[expressions.length];
849
                                for (int i = 0; i < aux.length; i++) {
850
                                        aux[i] = i+1;
851
                                }
852

    
853
                                Object[][] values = new Object[aux.length][2];
854
                                for (int i = 0; i < values.length; i++) {
855
                                        values[i][0] = aux[i];
856
                                        values[i][1] = expressions[i];
857
                                }
858
                                setDataVector(values, TABLE_HEADERS);
859
                        }
860
                        else{
861
                                Object[][] values = new Object[1][2];
862
                                values[0][0] = 1;
863
                                values[0][1] = "";
864
                                setDataVector(values,TABLE_HEADERS);
865
                        }
866

    
867
                }
868

    
869

    
870
                @Override
871
                public boolean isCellEditable(int row, int column) {
872
                        return column == 1;
873
                }
874

    
875
                public String[] getExpression() {
876

    
877
                        String[] expressions = new String[getRowCount()];
878

    
879
                        for (int i = 0; i < getRowCount(); i++) {
880
                                expressions[i] = ""+(String) getValueAt(i,1);
881
                        }
882
                        return expressions;
883
                }
884

    
885
        }
886

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

    
965
}