Revision 10134

View differences:

org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/pom.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4

  
5
    <modelVersion>4.0.0</modelVersion>
6
    <artifactId>org.gvsig.legend.vectorfilterexpression.app.mainplugin</artifactId>
7
    <name>${project.artifactId}</name>
8
    <version>1.0.240</version>
9

  
10
    <parent>
11
        <groupId>org.gvsig</groupId>
12
        <artifactId>org.gvsig.desktop</artifactId>
13
        <version>2.0.443</version>
14
    </parent>
15

  
16
    <url>https://devel.gvsig.org/redmine/projects/gvsig-base-legends</url>
17

  
18
    <scm>
19
        <connection>scm:svn:https://devel.gvsig.org/svn/gvsig-base-legends/org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240</connection>
20
        <developerConnection>scm:svn:https://devel.gvsig.org/svn/gvsig-base-legends/org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240</developerConnection>
21
        <url>scm:svn:https://devel.gvsig.org/svn/gvsig-base-legends/org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240</url>
22
    </scm>
23
    <repositories>
24
        <repository>
25
            <id>gvsig-public-http-repository</id>
26
            <name>gvSIG maven public HTTP repository</name>
27
            <url>http://devel.gvsig.org/m2repo/j2se</url>
28
            <releases>
29
                <enabled>true</enabled>
30
                <updatePolicy>daily</updatePolicy>
31
                <checksumPolicy>warn</checksumPolicy>
32
            </releases>
33
            <snapshots>
34
                <enabled>true</enabled>
35
                <updatePolicy>daily</updatePolicy>
36
                <checksumPolicy>warn</checksumPolicy>
37
            </snapshots>
38
        </repository>
39
    </repositories>
40

  
41
    <description>Vector legend: Filter by expression. For each feature, the symbol is only visible if the expression is evaluated to true.</description>
42
    <build>
43

  
44
        <plugins>
45

  
46
            <plugin>
47
                <artifactId>maven-release-plugin</artifactId>
48
                <configuration>
49
                    <tagBase>https://devel.gvsig.org/svn/gvsig-base-legends/org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags</tagBase>
50
                </configuration>
51
            </plugin>
52

  
53
        </plugins>
54
    </build>
55
    <dependencies>
56
        <dependency>
57
            <groupId>org.gvsig</groupId>
58
            <artifactId>org.gvsig.app.mainplugin</artifactId>
59
        </dependency>
60
        <dependency>
61
            <groupId>org.gvsig</groupId>
62
            <artifactId>org.gvsig.andami</artifactId>
63
        </dependency>
64
        <dependency>
65
            <groupId>org.gvsig</groupId>
66
            <artifactId>org.gvsig.symbology.lib.api</artifactId>
67
        </dependency>
68
        <dependency>
69
            <groupId>org.gvsig</groupId>
70
            <artifactId>org.gvsig.symbology.lib.impl</artifactId>
71
        </dependency>
72
        <dependency>
73
            <groupId>org.gvsig</groupId>
74
            <artifactId>org.gvsig.symbology.swing.api</artifactId>
75
        </dependency>
76
        <dependency>
77
            <groupId>org.gvsig</groupId>
78
            <artifactId>org.gvsig.fmap.mapcontext.api</artifactId>
79
        </dependency>
80
        <dependency>
81
            <groupId>org.gvsig</groupId>
82
            <artifactId>org.gvsig.utils</artifactId>
83
        </dependency>
84
        <dependency>
85
            <groupId>org.gvsig</groupId>
86
            <artifactId>org.gvsig.fmap.dal.api</artifactId>
87
        </dependency>
88

  
89
        <dependency>
90
            <groupId>org.gvsig</groupId>
91
            <artifactId>org.gvsig.i18n</artifactId>
92
        </dependency>
93

  
94
        <dependency>
95
            <groupId>org.gvsig</groupId>
96
            <artifactId>org.gvsig.fmap.geometry.api</artifactId>
97
        </dependency>
98

  
99
        <dependency>
100
            <groupId>org.gvsig</groupId>
101
            <artifactId>org.gvsig.tools.lib</artifactId>
102
        </dependency>
103
        <dependency>
104
            <groupId>org.gvsig</groupId>
105
            <artifactId>org.gvsig.ui</artifactId>
106
        </dependency>
107
        <dependency>
108
            <groupId>org.gvsig</groupId>
109
            <artifactId>org.gvsig.projection.api</artifactId>
110
        </dependency>
111
        <dependency>
112
            <groupId>org.gvsig</groupId>
113
            <artifactId>org.gvsig.metadata.lib.basic.api</artifactId>
114
        </dependency>
115

  
116
        <dependency>
117
            <groupId>org.gvsig</groupId>
118
            <artifactId>org.gvsig.compat.api</artifactId>
119
        </dependency>
120

  
121
        <dependency>
122
            <groupId>org.gvsig</groupId>
123
            <artifactId>org.gvsig.tools.evaluator.sqljep</artifactId>
124
        </dependency>
125

  
126
        <dependency>
127
            <groupId>org.gvsig</groupId>
128
            <artifactId>org.gvsig.tools.lib</artifactId>
129
            <scope>compile</scope>
130
        </dependency>
131

  
132
        <dependency>
133
            <groupId>org.gvsig</groupId>
134
            <artifactId>org.gvsig.tools.swing.api</artifactId>
135
        </dependency>
136

  
137
        <!--
138
        <dependency>
139
                <groupId>bsf</groupId>
140
                <artifactId>bsf</artifactId>
141
    <scope>compile</scope>
142
        </dependency>
143
        -->
144

  
145
    </dependencies>
146

  
147
    <properties>
148
        <gvsig.package.info.name>Vector legend: Filter by expression</gvsig.package.info.name>
149
        <gvsig.package.info.categories>View,Vector,Symbology</gvsig.package.info.categories>
150
        <gvsig.package.info.official>true</gvsig.package.info.official>
151
        <gvsig.package.info.dependencies>required: org.gvsig.app.mainplugin -ge 2.1.0-A</gvsig.package.info.dependencies>
152
        <gvsig.package.info.state>testing</gvsig.package.info.state>
153
        <gvsig.package.info.poolURL>https://devel.gvsig.org/download/projects/gvsig-base-legends/pool</gvsig.package.info.poolURL>
154
    </properties>
155

  
156

  
157
</project>
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/buildNumber.properties
1
#Fri Mar 08 00:43:46 CET 2024
2
buildNumber=245
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/resources/META-INF/services/org.gvsig.tools.library.Library
1
org.gvsig.symbology.library.VectorFilterExpressionLibrary
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/assembly/gvsig-plugin-package.xml
1
<!--
2

  
3
    gvSIG. Desktop Geographic Information System.
4

  
5
    Copyright (C) 2007-2013 gvSIG Association.
6

  
7
    This program is free software; you can redistribute it and/or
8
    modify it under the terms of the GNU General Public License
9
    as published by the Free Software Foundation; either version 3
10
    of the License, or (at your option) any later version.
11

  
12
    This program is distributed in the hope that it will be useful,
13
    but WITHOUT ANY WARRANTY; without even the implied warranty of
14
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
    GNU General Public License for more details.
16

  
17
    You should have received a copy of the GNU General Public License
18
    along with this program; if not, write to the Free Software
19
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
20
    MA  02110-1301, USA.
21

  
22
    For any additional information, do not hesitate to contact us
23
    at info AT gvsig.com, or visit our website www.gvsig.com.
24

  
25
-->
26
<assembly>
27
  <id>gvsig-plugin-package</id>
28
  <formats>
29
    <format>zip</format>
30
  </formats>
31
  <baseDirectory>${project.artifactId}</baseDirectory>
32
  <includeBaseDirectory>true</includeBaseDirectory>
33
  <files>
34
    <file>
35
      <source>target/${project.artifactId}-${project.version}.jar</source>
36
      <outputDirectory>lib</outputDirectory>
37
    </file>
38
    <file>
39
      <source>target/package.info</source>
40
    </file>
41
  </files>
42

  
43
  <fileSets>
44
    <fileSet>
45
      <directory>src/main/resources-plugin</directory>
46
      <outputDirectory>.</outputDirectory>
47
    </fileSet>
48
  </fileSets>
49

  
50
<!-- No dependencies
51
  <dependencySets>
52
    <dependencySet>
53
      <useProjectArtifact>false</useProjectArtifact>
54
      <useTransitiveDependencies>false</useTransitiveDependencies>
55
      <outputDirectory>lib</outputDirectory>
56
      <includes>
57
		<include>...</include>
58
      </includes>
59
    </dependencySet>
60
  </dependencySets>
61
-->
62

  
63
</assembly>
64

  
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/java/org/gvsig/symbology/fmap/rendering/VectorFilterExpressionLegend.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.symbology.fmap.rendering;
25

  
26
import java.awt.Graphics2D;
27
import java.awt.image.BufferedImage;
28
import java.util.ArrayList;
29
import javax.swing.JOptionPane;
30
import org.cresques.cts.ICoordTrans;
31
import org.gvsig.app.ApplicationLocator;
32
import org.gvsig.fmap.dal.DALLocator;
33
import org.gvsig.fmap.dal.DataManager;
34
import org.gvsig.fmap.dal.exception.InitializeException;
35

  
36
import org.slf4j.Logger;
37
import org.slf4j.LoggerFactory;
38

  
39
import org.gvsig.fmap.dal.feature.Feature;
40
import org.gvsig.fmap.dal.feature.FeatureSelection;
41
import org.gvsig.fmap.dal.feature.FeatureSet;
42
import org.gvsig.fmap.geom.Geometry;
43
import org.gvsig.fmap.geom.GeometryLocator;
44
import org.gvsig.fmap.geom.GeometryManager;
45
import org.gvsig.fmap.mapcontext.MapContextLocator;
46
import org.gvsig.fmap.mapcontext.MapContextManager;
47
import org.gvsig.fmap.mapcontext.ViewPort;
48
import org.gvsig.fmap.mapcontext.rendering.legend.events.SymbolLegendEvent;
49
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
50
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolManager;
51
import org.gvsig.i18n.Messages;
52
import org.gvsig.symbology.fmap.mapcontext.rendering.legend.driver.impl.PersistenceBasedLegendWriter;
53
import org.gvsig.symbology.fmap.mapcontext.rendering.legend.impl.AbstractClassifiedVectorLegend;
54
import org.gvsig.symbology.fmap.mapcontext.rendering.legend.impl.DefaultFeatureDrawnNotification;
55
import org.gvsig.tools.ToolsLocator;
56
import org.gvsig.tools.dynobject.DynStruct;
57
import org.gvsig.tools.evaluator.Evaluator;
58
import org.gvsig.tools.evaluator.EvaluatorData;
59
import org.gvsig.tools.exception.BaseException;
60
import org.gvsig.tools.i18n.I18nManager;
61
import org.gvsig.tools.persistence.PersistenceManager;
62
import org.gvsig.tools.persistence.PersistentState;
63
import org.gvsig.tools.persistence.exception.PersistenceException;
64
import org.gvsig.tools.task.Cancellable;
65
import org.gvsig.tools.util.Callable;
66
import org.gvsig.tools.util.Caller;
67
import org.gvsig.tools.util.impl.DefaultCaller;
68

  
69
/**
70
 *
71
 * Implements a vector legend which represents the elements of a layer depending
72
 * on the value of an expression. That is, if the expression is evaluated to
73
 * true, then the symbol associated to the expression is painted. In other case
74
 * it is not showed.
75
 *
76
 * If the expression result is a string, it is considered false if it is the
77
 * empty string "", true otherwise.
78
 *
79
 * If the expression result is numeric, it is considered false if it is zero,
80
 * and true otherwise.
81
 *
82
 * In other cases, it is considered false if the result is null and true
83
 * otherwise.
84
 *
85
 * @author gvSIG Team
86
 */
87
public class VectorFilterExpressionLegend
88
        extends AbstractClassifiedVectorLegend {
89

  
90
    private static final Logger logger = LoggerFactory.getLogger(
91
            VectorFilterExpressionLegend.class);
92

  
93
    public static final String FILTER_EXPRESSION_LEGEND_PERSISTENCE_DEFINITION_NAME
94
            = "FILTER_EXPRESSION_LEGEND_PERSISTENCE_DEFINITION_NAME";
95

  
96
    public static final String FILTER_EXPRESSION_LEGEND_NAME = "FILTER_EXPRESSION_LEGEND_NAME";
97

  
98
    public static final String I18N_DEFAULT = Messages.getText("default_value");
99
    public static final String NON_I18N_DEFAULT = Messages.getText("Default");
100

  
101
    private int shapeType;
102
    private ISymbol defaultSymbol;
103

  
104
    private boolean useDefaultSymbol = false;
105

  
106
    private long error_msg_count = 0;
107

  
108
    private ArrayList<Item> newSymbols = new ArrayList<Item>() {
109
        private static final long serialVersionUID = 1L;
110

  
111
        public int indexOf(String expr) {
112
            return super.indexOf(new Item(expr, null));
113
        }
114
    };
115

  
116
    private class Item implements Cloneable {
117

  
118
        private ISymbol sym;
119
        private Evaluator evaluator;
120

  
121
        public Item(String expression, ISymbol sym) {
122
            this.sym = sym;
123
            DataManager dataManager = DALLocator.getDataManager();
124
            try {
125
                evaluator = dataManager.createFilter(expression);
126
            } catch (InitializeException ex) {
127
                evaluator = null;
128
            }
129
        }
130

  
131
        public boolean equals(Object obj) {
132
            if (obj == null) {
133
                return false;
134
            }
135
            if (!obj.getClass().equals(Item.class)) {
136
                return false;
137
            }
138
            return this.evaluator.getSQL().equals(
139
                    ((Item) obj).evaluator.getSQL()
140
            );
141
        }
142

  
143
        public String getStringExpression() {
144
            return evaluator.getSQL();
145
        }
146

  
147
        public Evaluator getEvaluator() {
148
            return evaluator;
149
        }
150

  
151
        public Object clone() {
152

  
153
            ISymbol clonesym = null;
154
            try {
155
                clonesym = (ISymbol) this.sym.clone();
156
            } catch (CloneNotSupportedException e) {
157
                logger.info("Error: unable to clone symbol.", e);
158
                clonesym = this.sym;
159
            }
160
            return new Item(getStringExpression(), clonesym);
161
        }
162
    }
163

  
164
    public VectorFilterExpressionLegend() {
165
        this.setClassifyingFieldNames(new String[0]);
166
        this.setClassifyingFieldTypes(new int[0]);
167
    }
168

  
169
    public ISymbol getSymbolByFeature(Feature featu) {
170

  
171
        EvaluatorData evda = featu.getEvaluatorData();
172

  
173
        ISymbol returnSymbol = null;
174
        Object result = null;
175
        String expr = null;
176

  
177
        try {
178

  
179
            for (int i = 0; i < newSymbols.size(); i++) {
180

  
181
                Evaluator eval = newSymbols.get(i).getEvaluator();
182
                expr = eval.getSQL();
183

  
184
                if (expr.equalsIgnoreCase(VectorFilterExpressionLegend.I18N_DEFAULT)) {
185
                    /*
186
                     * Skip default item
187
                     */
188
                    continue;
189
                }
190

  
191
                result = eval.evaluate(evda);
192
                if (isConsideredTrue(result)) {
193
                    returnSymbol = newSymbols.get(i).sym;
194
                    if (returnSymbol != null) {
195
                        return returnSymbol;
196
                    }
197
                }
198
            }
199
        } catch (Exception e) {
200

  
201
            if (error_msg_count % 1000 == 0) {
202
                I18nManager i18n = ToolsLocator.getI18nManager();
203
                String s;
204
                try{
205
                    s = featu.toJson().toString().replace("\n", " ");
206
                } catch (Throwable t) {
207
                    s=featu.toString();
208
                }
209
                logger.info("Error (msg every 1000 occurrences) while getting symbol in VectorFilterExpressionLegend Expression = ["+expr+"], Feature = ["+s+"]", e);
210
                error_msg_count = 0;
211
                ApplicationLocator.getManager().message(
212
                        i18n.getTranslation("_Error_in_expressions_legend")+
213
                                ". "+
214
                        i18n.getTranslation("_see_error_log_for_more_information")
215
                        , JOptionPane.WARNING_MESSAGE);
216
            }
217
            error_msg_count++;
218
            
219
            return getDefaultSymbol();
220
        }
221

  
222
        if (useDefaultSymbol) {
223
            return getDefaultSymbol();
224
        }
225

  
226
        return null;
227
    }
228

  
229
    /**
230
     * Tells whether the input object is considered true. Basically, it is false
231
     * if it has an empty value (FALSE, null, 0, "")
232
     *
233
     * @param result
234
     * @return
235
     */
236
    private boolean isConsideredTrue(Object res) {
237

  
238
        if (res == null) {
239
            return false;
240
        }
241

  
242
        if (res instanceof Boolean) {
243
            return ((Boolean) res).booleanValue();
244
        }
245

  
246
        if (res instanceof Number) {
247
            return ((Number) res).doubleValue() != 0d;
248
        }
249

  
250
        if (res instanceof String) {
251
            return ((String) res).length() > 0;
252
        }
253

  
254
        // Because it is not null
255
        return true;
256
    }
257

  
258
    public void addSymbol(Object key, ISymbol symbol) {
259
        newSymbols.add(new Item((String) key.toString(),
260
                symbol));
261
    }
262

  
263
    public void clear() {
264
        newSymbols.clear();
265
    }
266

  
267
    public void resetItems() {
268
        newSymbols = new ArrayList<Item>() {
269
            private static final long serialVersionUID = 1L;
270

  
271
            public int indexOf(String expr) {
272
                return super.indexOf(new Item(expr, null));
273
            }
274
        };
275
    }
276

  
277
    public void delSymbol(Object key) {
278
        ISymbol mySymbol = null;
279
        for (int i = 0; i < newSymbols.size(); i++) {
280
            if (newSymbols.get(i).evaluator.getSQL().equals(key)) {
281
                newSymbols.remove(i);
282
            }
283
        }
284
        fireClassifiedSymbolChangeEvent(new SymbolLegendEvent(mySymbol, null));
285
    }
286

  
287
    public void replace(ISymbol oldSymbol, ISymbol newSymbol) {
288

  
289
        for (int i = 0; i < newSymbols.size(); i++) {
290
            if (newSymbols.get(i).sym.equals(oldSymbol)) {
291
                newSymbols.get(i).sym = newSymbol;
292
            }
293
        }
294

  
295
        fireClassifiedSymbolChangeEvent(new SymbolLegendEvent(oldSymbol, newSymbol));
296
    }
297

  
298
    public String[] getDescriptions() {
299
        String[] descriptions = new String[newSymbols.size()];
300
        ISymbol[] auxSym = getSymbols();
301

  
302
        for (int i = 0; i < descriptions.length; i++) {
303
            descriptions[i] = auxSym[i].getDescription();
304
        }
305

  
306
        return descriptions;
307
    }
308

  
309
    public ISymbol[] getSymbols() {
310

  
311
        if (newSymbols != null) {
312
            ISymbol[] mySymbols = new ISymbol[newSymbols.size()];
313
            for (int i = 0; i < newSymbols.size(); i++) {
314
                mySymbols[i] = newSymbols.get(i).sym;
315
            }
316
            return mySymbols;
317
        }
318
        return null;
319
    }
320

  
321
    public ISymbol getDefaultSymbol() {
322
        if (defaultSymbol == null) {
323

  
324
            defaultSymbol = MapContextLocator.getSymbolManager().createSymbol(shapeType);
325
            fireDefaultSymbolChangedEvent(new SymbolLegendEvent(null, defaultSymbol));
326
        }
327
        return defaultSymbol;
328
    }
329

  
330
    public String getClassName() {
331
        return getClass().getName();
332
    }
333

  
334
    public int getShapeType() {
335
        return shapeType;
336
    }
337

  
338
    public boolean isUseDefaultSymbol() {
339
        return useDefaultSymbol;
340
    }
341

  
342
    public void setDefaultSymbol(ISymbol s) throws IllegalArgumentException {
343
        if (s == null) {
344
            throw new NullPointerException("Default symbol cannot be null");
345
        }
346
        ISymbol old = defaultSymbol;
347
        defaultSymbol = s;
348
        fireDefaultSymbolChangedEvent(new SymbolLegendEvent(old, defaultSymbol));
349
    }
350

  
351
    public void setShapeType(int shapeType) {
352
        if (this.shapeType != shapeType) {
353

  
354
            ISymbol sym = MapContextLocator.getSymbolManager().createSymbol(shapeType);
355
            setDefaultSymbol(sym);
356
            this.shapeType = shapeType;
357
        }
358
    }
359

  
360
    public void useDefaultSymbol(boolean b) {
361
        useDefaultSymbol = b;
362
    }
363

  
364
    public Object[] getValues() {
365
        if (newSymbols != null) {
366
            Object[] myObjects = new Object[newSymbols.size()];
367
            for (int i = 0; i < newSymbols.size(); i++) {
368
                myObjects[i] = newSymbols.get(i).getStringExpression();
369
            }
370
            return myObjects;
371
        }
372
        return null;
373
    }
374

  
375
    public static boolean isPolygonal(int ty) {
376
        GeometryManager geomManager = GeometryLocator.getGeometryManager();
377
        return geomManager.isSubtype(Geometry.TYPES.MULTISURFACE, ty)
378
                || geomManager.isSubtype(Geometry.TYPES.SURFACE, ty);
379
    }
380

  
381
    public static boolean isLinear(int ty) {
382
        GeometryManager geomManager = GeometryLocator.getGeometryManager();
383
        return geomManager.isSubtype(Geometry.TYPES.MULTICURVE, ty)
384
                || geomManager.isSubtype(Geometry.TYPES.CURVE, ty);
385
    }
386

  
387
    public static boolean isPoint(int ty) {
388
        GeometryManager geomManager = GeometryLocator.getGeometryManager();
389
        return geomManager.isSubtype(Geometry.TYPES.MULTIPOINT, ty)
390
                || geomManager.isSubtype(Geometry.TYPES.POINT, ty);
391
    }
392

  
393
    public void removeDefaultSymbol() {
394

  
395
    }
396

  
397
    // =============================
398
    public static class RegisterPersistence implements Callable {
399

  
400
        public Object call() throws Exception {
401

  
402
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
403
            if (manager.getDefinition(
404
                    FILTER_EXPRESSION_LEGEND_PERSISTENCE_DEFINITION_NAME) == null) {
405
                DynStruct definition = manager
406
                        .addDefinition(VectorFilterExpressionLegend.class,
407
                                FILTER_EXPRESSION_LEGEND_PERSISTENCE_DEFINITION_NAME,
408
                                FILTER_EXPRESSION_LEGEND_PERSISTENCE_DEFINITION_NAME
409
                                + " Persistence definition", null, null);
410

  
411
                definition.extend(manager.getDefinition(
412
                        AbstractClassifiedVectorLegend.CLASSIFIED_VECTOR_LEGEND_PERSISTENCE_DEFINITION_NAME));
413

  
414
                definition.addDynFieldBoolean("useDefaultSymbol")
415
                        .setMandatory(true);
416
                definition.addDynFieldObject("defaultSymbol")
417
                        .setClassOfValue(ISymbol.class).setMandatory(true);
418
                definition.addDynFieldInt("shapeType")
419
                        .setMandatory(true);
420

  
421
                definition.addDynFieldArray("itemSymbolArray")
422
                        .setClassOfItems(ISymbol.class);
423
                definition.addDynFieldArray("itemStringArray")
424
                        .setClassOfItems(String.class);
425

  
426
            }
427
            return Boolean.TRUE;
428
        }
429

  
430
    }
431

  
432
    public static class RegisterLegend implements Callable {
433

  
434
        public Object call() throws Exception {
435
            MapContextManager manager
436
                    = MapContextLocator.getMapContextManager();
437

  
438
            manager.registerLegend(
439
                    FILTER_EXPRESSION_LEGEND_NAME,
440
                    VectorFilterExpressionLegend.class);
441

  
442
            return Boolean.TRUE;
443
        }
444

  
445
    }
446

  
447
    public void saveToState(PersistentState state) throws PersistenceException {
448

  
449
        super.saveToState(state);
450
        state.set("useDefaultSymbol", this.isUseDefaultSymbol());
451
        state.set("defaultSymbol", this.getDefaultSymbol());
452
        state.set("shapeType", this.getShapeType());
453

  
454
        ISymbol[] syms = this.getSymbols();
455
        if (syms == null) {
456
            syms = new ISymbol[0];
457
        }
458
        Object[] vals = this.getValues();
459
        String[] vals_str = null;
460
        if (vals == null) {
461
            vals_str = new String[0];
462
        } else {
463
            vals_str = new String[vals.length];
464
            for (int i = 0; i < vals.length; i++) {
465
                String aux = ((vals[i] == null) ? null : vals[i].toString());
466
                // Prevents saving localized version of 'Default'
467
                aux = translateDefault(aux, false);
468
                vals_str[i] = aux;
469
            }
470
        }
471

  
472
        state.set("itemSymbolArray", syms);
473
        state.set("itemStringArray", vals_str);
474

  
475
    }
476

  
477
    public void loadFromState(PersistentState state)
478
            throws PersistenceException {
479

  
480
        super.loadFromState(state);
481

  
482
        this.setShapeType(state.getInt("shapeType"));
483
        Boolean b = state.getBoolean("useDefaultSymbol");
484
        this.useDefaultSymbol(b);
485
        ISymbol defsym = (ISymbol) state.get("defaultSymbol");
486
        this.setDefaultSymbol(defsym);
487

  
488
        String[] strs = state.getStringArray("itemStringArray");
489
        ISymbol[] syms = (ISymbol[]) state.getArray("itemSymbolArray",
490
                ISymbol.class);
491

  
492
        if (strs.length != syms.length) {
493
            logger.info("VectorFilterExpressionLegend - load state - Different size in arrays: " + strs.length + ", " + syms.length);
494
        }
495
        int nmin = Math.min(strs.length, syms.length);
496
        for (int i = 0; i < nmin; i++) {
497
            String aux = strs[i];
498
            aux = translateDefault(aux, true);
499
            this.addSymbol(aux, syms[i]);
500
        }
501
    }
502

  
503
    /**
504
     * Utility method to (un)translate the word 'Default'
505
     *
506
     * @param aux
507
     * @param forward If TRUE, then translate (Default -> Por defecto) If FALSE
508
     * then untranslate (Por defecto -> Default)
509
     * @return
510
     */
511
    private String translateDefault(String aux, boolean forward) {
512

  
513
        if (aux == null) {
514
            return null;
515
        }
516
        if (forward && aux.compareTo(NON_I18N_DEFAULT) == 0) {
517
            return I18N_DEFAULT;
518
        }
519
        if (!forward && aux.compareTo(I18N_DEFAULT) == 0) {
520
            return NON_I18N_DEFAULT;
521
        }
522
        return aux;
523
    }
524

  
525
    public Object clone() throws CloneNotSupportedException {
526

  
527
        VectorFilterExpressionLegend resp
528
                = (VectorFilterExpressionLegend) super.clone();
529

  
530
        Object[] vals = this.getValues();
531
        ISymbol[] syms = this.getSymbols();
532
        if (vals != null && syms != null) {
533

  
534
            resp.resetItems();
535

  
536
            int n = Math.min(vals.length, syms.length);
537
            for (int i = 0; i < n; i++) {
538
                resp.addSymbol(
539
                        vals[i],
540
                        (ISymbol) syms[i].clone());
541
            }
542
        }
543
        ISymbol sym = this.getDefaultSymbol();
544
        sym = (ISymbol) sym.clone();
545
        resp.setDefaultSymbol(sym);
546
        return resp;
547
    }
548

  
549
    public static void selfRegister() {
550
        Caller caller = new DefaultCaller();
551

  
552
        caller.add(new VectorFilterExpressionLegend.RegisterLegend());
553
        caller.add(new VectorFilterExpressionLegend.RegisterPersistence());
554

  
555
        if (!caller.call()) {
556
            throw new RuntimeException(
557
                    "Can't register VectorFilterExpressionLegend",
558
                    caller.getException()
559
            );
560
        }
561
        MapContextManager mcoman = MapContextLocator.getMapContextManager();
562
        mcoman.registerLegendWriter(
563
                VectorFilterExpressionLegend.class,
564
                SymbolManager.LEGEND_FILE_EXTENSION.substring(1),
565
                PersistenceBasedLegendWriter.class);
566

  
567
    }
568

  
569
    @Override
570
    protected void drawFeatures(BufferedImage image, Graphics2D g, ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans, double dpi, DefaultFeatureDrawnNotification drawnNotification, FeatureSet featureSet, FeatureSelection selection) throws BaseException {
571
        error_msg_count = 0;
572
        super.drawFeatures(image, g, viewPort, cancel, coordTrans, dpi, drawnNotification, featureSet, selection); //To change body of generated methods, choose Tools | Templates.
573
    }
574
    
575
    
576

  
577
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/java/org/gvsig/symbology/gui/layerproperties/ExpressionFieldCellEditor.java
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 progra/**
11
 * gvSIG. Desktop Geographic Information System.
12
 *
13
 * Copyright (C) 2007-2020 gvSIG Association.
14
 *
15
 * This program is free software; you can redistribute it and/or
16
 * modify it under the terms of the GNU General Public License
17
 * as published by the Free Software Foundation; either version 3
18
 * of the License, or (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
28
 * MA  02110-1301, USA.
29
 *
30
 * For any additional information, do not hesitate to contact us
31
 * at info AT gvsig.com, or visit our website www.gvsig.com.
32
 */
33
package org.gvsig.symbology.gui.layerproperties;
34

  
35
import java.awt.Component;
36
import javax.swing.AbstractCellEditor;
37

  
38
import javax.swing.JTable;
39
import javax.swing.table.TableCellEditor;
40
import org.gvsig.expressionevaluator.Expression;
41
import org.gvsig.expressionevaluator.ExpressionUtils;
42
import org.gvsig.expressionevaluator.swing.ExpressionEvaluatorSwingLocator;
43
import org.gvsig.expressionevaluator.swing.ExpressionEvaluatorSwingManager;
44
import org.gvsig.expressionevaluator.swing.JExpressionPicker;
45
import org.gvsig.fmap.dal.feature.FeatureStore;
46
import org.gvsig.fmap.dal.swing.DALSwingLocator;
47
import org.gvsig.fmap.dal.swing.DataSwingManager;
48

  
49
/**
50
 * Cell Editor for expressions. It controls the edition events in an expression
51
 * column of the table
52
 *
53
 * @author gvSIG Team
54
 */
55
public class ExpressionFieldCellEditor 
56
        extends AbstractCellEditor
57
        implements TableCellEditor 
58
  {
59

  
60
  private final JExpressionPicker picker;
61

  
62
	public ExpressionFieldCellEditor(FeatureStore store) {
63
    ExpressionEvaluatorSwingManager manager = ExpressionEvaluatorSwingLocator.getManager();
64
    this.picker = manager.createJExpressionPicker();
65
    if( store != null ) {
66
      DataSwingManager dataSwingManager = DALSwingLocator.getManager();    
67
      dataSwingManager.configureExpressionBuilder(picker.getConfig(), store);  
68
    }
69
	}
70

  
71
  @Override
72
  public Object getCellEditorValue() {
73
    Expression value = this.picker.getExpression();
74
    if( value == null ) {
75
      return null;
76
    }
77
    return value.getPhrase();
78
  }
79

  
80
  @Override
81
  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
82
    if( value instanceof String ) {
83
      this.picker.setExpression(ExpressionUtils.createExpression((String) value));
84
    } else {
85
      this.picker.setExpression(null);
86
    }
87
    return this.picker.asJComponent();
88
  }
89

  
90

  
91
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/java/org/gvsig/symbology/gui/layerproperties/VectorFilterExpressionPanel2.java
1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2020 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.symbology.gui.layerproperties;
25

  
26
import java.awt.event.ActionEvent;
27
import java.io.File;
28
import java.io.IOException;
29
import java.net.URL;
30
import java.util.ArrayList;
31
import java.util.Arrays;
32
import java.util.List;
33

  
34
import javax.swing.ImageIcon;
35
import javax.swing.JOptionPane;
36
import javax.swing.JPanel;
37
import org.apache.commons.lang3.StringUtils;
38

  
39
import org.slf4j.Logger;
40
import org.slf4j.LoggerFactory;
41

  
42
import org.gvsig.andami.IconThemeHelper;
43
import org.gvsig.app.ApplicationLocator;
44
import org.gvsig.app.project.documents.view.legend.gui.Categories;
45
import org.gvsig.app.project.documents.view.legend.gui.ILegendPanel;
46
import org.gvsig.app.project.documents.view.legend.gui.SymbolTable;
47
import org.gvsig.fmap.dal.exception.ReadException;
48
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
49
import org.gvsig.fmap.dal.feature.FeatureStore;
50
import org.gvsig.fmap.dal.feature.FeatureType;
51
import org.gvsig.fmap.mapcontext.layers.FLayer;
52
import org.gvsig.fmap.mapcontext.layers.operations.ClassifiableVectorial;
53
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
54
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
55
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
56
import org.gvsig.i18n.Messages;
57
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.fill.impl.PictureFillSymbol;
58
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.style.IMarkerFillPropertiesStyle;
59
import org.gvsig.symbology.fmap.rendering.VectorFilterExpressionLegend;
60
import org.gvsig.symbology.swing.SymbologySwingLocator;
61
import org.gvsig.tools.ToolsLocator;
62
import org.gvsig.tools.i18n.I18nManager;
63
import org.gvsig.tools.swing.api.ToolsSwingLocator;
64
import org.gvsig.tools.swing.api.ToolsSwingManager;
65
import org.gvsig.tools.swing.api.pickercontroller.PickerController;
66
import org.gvsig.tools.swing.api.windowmanager.Dialog;
67
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
68
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
69

  
70
/**
71
 * Implements the JPanel that shows the properties of a
72
 * VectorialFilterExpressionLegend in order to allows the user to modify its
73
 * characteristics
74
 *
75
 * @author gvSIG Team
76
 *
77
 */
78
@SuppressWarnings("UseSpecificCatch")
79
public class VectorFilterExpressionPanel2
80
        extends VectorFilterExpressionPanelView
81
        implements ILegendPanel {
82

  
83
  private static final Logger LOGGER = LoggerFactory.getLogger(VectorFilterExpressionPanel2.class);
84

  
85
  private VectorFilterExpressionLegend theLegend;
86
  private VectorFilterExpressionLegend auxLegend;
87
  private ClassifiableVectorial layer;
88
  private PictureFillSymbol previewSymbol;
89
  private SymbolTable symbolTable;
90
  private int shapeType;
91
  private PickerController<ISymbol> defaultSymbolPrev;
92

  
93
  /**
94
   * This is the default constructor
95
   */
96
  public VectorFilterExpressionPanel2() {
97
    super();
98
    initComponents();
99
  }
100

  
101
  /**
102
   * This method initializes this
103
   */
104
  private void initComponents() {
105
    ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
106
    
107
    toolsSwingManager.translate(this.btnAdd);
108
    toolsSwingManager.translate(this.btnRemove);
109
    toolsSwingManager.translate(this.btnRemoveAll);
110
    toolsSwingManager.translate(this.btnDown);
111
    toolsSwingManager.translate(this.btnUp);
112
    toolsSwingManager.translate(this.chkDefaultValues);
113
    
114
    this.defaultSymbolPrev = SymbologySwingLocator.getSwingManager().createSymbolPickerController(
115
            this.btnDefaultValuesPreview, 
116
            null, 
117
            shapeType, 
118
            null
119
    );
120

  
121
    this.btnUp.setIcon(IconThemeHelper.getImageIcon("symbol-layer-move-up"));
122
    this.btnDown.setIcon(IconThemeHelper.getImageIcon("symbol-layer-move-down"));
123

  
124
    this.btnUp.setText("");
125
    this.btnDown.setText("");
126
    
127
    this.btnUp.addActionListener((ActionEvent e) -> {
128
      doUp();
129
    });
130
    this.btnDown.addActionListener((ActionEvent e) -> {
131
      doDown();
132
    });
133
    this.btnAdd.addActionListener((ActionEvent e) -> {
134
      doAdd();
135
    });
136
    this.btnRemove.addActionListener((ActionEvent e) -> {
137
      doRemove();
138
    });
139
    this.btnRemoveAll.addActionListener((ActionEvent e) -> {
140
      doRemoveAll();
141
    });
142
  }
143

  
144
  @Override
145
  public String getDescription() {
146
    return Messages.getText(
147
            "shows_the_elements_of_the_layer_depending_on_the_value_of_a_filter_expression") + ".";
148
  }
149

  
150
  public ISymbol getIconSymbol() {
151
    if (previewSymbol == null) {
152
      try {
153
        previewSymbol = new PictureFillSymbol();
154
        URL resource = this.getClass().getClassLoader().getResource("images/legend/legend-overview-vectorial-unique-value.png");
155
        if( resource == null ) {
156
          return null;
157
        }
158
        previewSymbol.setImage(resource);
159
        previewSymbol.getMarkerFillProperties().setFillStyle(
160
                IMarkerFillPropertiesStyle.SINGLE_CENTERED_SYMBOL
161
        );
162
      } catch (IOException e) {
163
        return null;
164
      }
165
    }
166
    return previewSymbol;
167
  }
168

  
169
  @Override
170
  public ILegend getLegend() {
171
    auxLegend.clear();
172
    fillSymbolListFromTable();
173

  
174
    theLegend = (VectorFilterExpressionLegend) auxLegend.cloneLegend();
175
    if (defaultSymbolPrev.get() != null) {
176
      theLegend.setDefaultSymbol(defaultSymbolPrev.get());
177
    }
178
    theLegend.useDefaultSymbol(chkDefaultValues.isSelected());
179
    return theLegend;
180
  }
181

  
182
  /**
183
   * Fills the list of symbols of the legend
184
   */
185
  private void fillSymbolListFromTable() {
186
    Object clave;
187
    ISymbol theSymbol;
188

  
189
    FLyrVect m = (FLyrVect) layer;
190
    try {
191

  
192
      if (auxLegend.getClassifyingFieldNames() != null) {
193
        String[] fNames = auxLegend.getClassifyingFieldNames();
194
        int[] fieldTypes = new int[auxLegend.getClassifyingFieldNames().length];
195

  
196
        FeatureStore fsto = (FeatureStore) m.getDataStore();
197
        FeatureType fty = fsto.getDefaultFeatureType();
198

  
199
        for (int i = 0; i < fNames.length; i++) {
200
          fieldTypes[i] = fty.getAttributeDescriptor(fNames[i]).getType();
201
        }
202

  
203
        auxLegend.setClassifyingFieldTypes(fieldTypes);
204
      }
205
    } catch (Exception e) {
206

  
207
    }
208

  
209
    auxLegend.useDefaultSymbol(chkDefaultValues.isSelected());
210

  
211
    for (int row = 0; row < symbolTable.getRowCount(); row++) {
212
      clave = symbolTable.getFieldValue(row, 1);
213
      theSymbol = (ISymbol) symbolTable.getFieldValue(row, 0);
214
      theSymbol.setDescription((String) symbolTable.getFieldValue(row, 2));
215
      auxLegend.addSymbol(clave, theSymbol);
216
    }
217
    if (chkDefaultValues.isSelected()) {
218
      if (defaultSymbolPrev.get() != null) {
219
        String description = VectorFilterExpressionLegend.I18N_DEFAULT;
220
        defaultSymbolPrev.get().setDescription(description);
221
        auxLegend.addSymbol(
222
                description, defaultSymbolPrev.get());
223
      }
224
    }
225

  
226
  }
227

  
228
  @Override
229
  public Class<VectorFilterExpressionLegend> getLegendClass() {
230
    return VectorFilterExpressionLegend.class;
231
  }
232

  
233
  @Override
234
  public JPanel getPanel() {
235
    return this;
236
  }
237

  
238
  @Override
239
  public Class<Categories> getParentClass() {
240
    return Categories.class;
241
  }
242

  
243
  @Override
244
  public String getTitle() {
245
    return Messages.getText("expressions");
246
  }
247

  
248
  @Override
249
  public boolean isSuitableFor(FLayer layer) {
250
    FLyrVect lVect = (FLyrVect) layer;
251
    try {
252
      return VectorFilterExpressionLegend.isPoint(lVect.getShapeType())
253
              || VectorFilterExpressionLegend.isLinear(lVect.getShapeType())
254
              || VectorFilterExpressionLegend.isPolygonal(lVect.getShapeType());
255
    } catch (Exception e) {
256
      return false;
257
    }
258

  
259
  }
260

  
261
  @Override
262
  public void setData(FLayer lyr, ILegend legend) {
263
    this.layer = (ClassifiableVectorial) lyr;
264
    shapeType = 0;
265

  
266
    try {
267
      shapeType = this.layer.getGeometryType().getType();
268
    } catch (ReadException e) {
269
      LOGGER.warn("Error while getting layer shp type", e);
270
      ApplicationLocator.getManager().message(
271
              Messages.getText("generating_intervals"),
272
              JOptionPane.ERROR_MESSAGE);
273
    }
274

  
275
    this.defaultSymbolPrev = SymbologySwingLocator.getSwingManager().createSymbolPickerController(
276
            this.btnDefaultValuesPreview, 
277
            null, 
278
            shapeType, 
279
            null
280
    );
281

  
282
    symbolTable = new SymbolTable(this.tblSymbols, this, "expressions", shapeType);
283
    doUpdateCellEditor();
284
    if (legend instanceof VectorFilterExpressionLegend) {
285

  
286
      auxLegend = (VectorFilterExpressionLegend) legend.cloneLegend();
287
      if (auxLegend.isUseDefaultSymbol()) {
288
        // Default must not be in table
289
        fillTableSkipDefault(auxLegend);
290
      } else {
291
        symbolTable.fillTableFromSymbolList(
292
                auxLegend.getSymbols(),
293
                auxLegend.getValues(),
294
                auxLegend.getDescriptions());
295
      }
296

  
297
    } else {
298
      auxLegend = new VectorFilterExpressionLegend();
299
      auxLegend.setShapeType(shapeType);
300
    }
301
    defaultSymbolPrev.set(auxLegend.getDefaultSymbol());
302
    this.chkDefaultValues.setSelected(auxLegend.isUseDefaultSymbol());
303
  }
304
  
305
  private void doUpdateCellEditor() {
306
      try {
307
        ExpressionFieldCellEditor cellEditor = new ExpressionFieldCellEditor(
308
                ((FLyrVect)layer).getFeatureStore()
309
        );
310
        symbolTable.setCellEditor(cellEditor);
311
      } catch(Exception ex) {
312
        LOGGER.debug("Can't update cell editors",ex);
313
      }    
314
  }
315

  
316

  
317
  private void doUp() {
318
    int[] indices = symbolTable.getSelectedRows();
319
    if (indices.length > 0) {
320
      int classIndex = indices[0];
321
      int targetPos = Math.max(0, classIndex - 1);
322
      symbolTable.moveUpRows(classIndex, targetPos, indices.length);
323
    }
324
  }
325

  
326
  private void doDown() {
327
    int[] indices = symbolTable.getSelectedRows();
328
    if (indices.length > 0) {
329
      int classIndex = indices[indices.length - 1];
330
      int targetPos = Math.min(symbolTable.getRowCount() - 1, classIndex + 1);
331
      symbolTable.moveDownRows(classIndex, targetPos, indices.length);
332
    }
333

  
334
  }
335

  
336
  private void doAdd() {
337
    FLyrVect vect = (FLyrVect) layer;
338
    final FeatureStore fsto = vect.getFeatureStore();
339
    final FeatureType fty = fsto.getDefaultFeatureTypeQuietly();
340
    final int shptype = fty.getDefaultGeometryAttribute().getGeomType().getType();
341
    final I18nManager i18n = ToolsLocator.getI18nManager();
342
    final ExpressionSymbolPanel esp = new ExpressionSymbolPanel(fsto, shptype, previewSymbol);
343
    final WindowManager_v2 windowManager = (WindowManager_v2) ToolsSwingLocator.getWindowManager();
344
    final Dialog dialog = windowManager.createDialog(
345
            esp,
346
            i18n.getTranslation("expression_creator"),
347
            "",
348
            WindowManager_v2.BUTTONS_OK_CANCEL
349
    );
350
    dialog.addActionListener((ActionEvent e1) -> {
351
      if (dialog.getAction() != WindowManager_v2.BUTTON_OK) {
352
        return;
353
      }
354
      String expr = esp.getExpression();
355
      if (StringUtils.isBlank(expr)) {
356
        ApplicationLocator.getManager().messageDialog(
357
                Messages.getText("error_validating_filter_query"),
358
                Messages.getText("error"),
359
                JOptionPane.ERROR_MESSAGE);
360
        return;
361
      }
362
      ISymbol sym = esp.getSymbol();
363
      this.addClassFieldNames(fty);
364

  
365
      auxLegend.addSymbol(expr, sym);
366
      symbolTable.removeAllItems();
367
      doUpdateCellEditor();
368
      fillTableSkipDefault(auxLegend);
369

  
370
      repaint();
371
    });
372
    dialog.show(WindowManager.MODE.DIALOG);
373
  }
374

  
375
  private void doRemove() {
376
    if (symbolTable.getSelectedRowElements() == null) {
377
      JOptionPane.showMessageDialog(this, Messages.getText("select_one_row"));
378
    } else {
379
      String my_expr = (String) symbolTable.getSelectedRowElements()[1];
380
      auxLegend.delSymbol(my_expr);
381
      symbolTable.removeAllItems();
382
      doUpdateCellEditor();
383
      fillTableSkipDefault(auxLegend);
384

  
385
      repaint();
386
    }
387
  }
388

  
389
  private void doRemoveAll() {
390
      auxLegend.clear();
391
      symbolTable.removeAllItems();
392
      doUpdateCellEditor();
393
      fillTableSkipDefault(auxLegend);
394

  
395
      repaint();
396
  }
397

  
398
  private void addClassFieldNames(FeatureType ft) {
399
    FeatureAttributeDescriptor[] atts = ft.getAttributeDescriptors();
400
    String[] nn = new String[atts.length];
401
    for (int i = 0; i < atts.length; i++) {
402
      nn[i] = atts[i].getName();
403
    }
404
    addClassFieldNames(nn);
405
  }
406

  
407
  /**
408
   * Adds new classifying field names to the legend when a new expression is
409
   * created or an existing one is modified
410
   *
411
   * @param fieldNamesExpression
412
   */
413
  private void addClassFieldNames(String[] fieldNamesExpression) {
414
    boolean appears;
415
    List<String> myFieldNames = new ArrayList<>();
416

  
417
    if (auxLegend.getClassifyingFieldNames() != null) {
418

  
419
      myFieldNames.addAll(Arrays.asList(auxLegend.getClassifyingFieldNames()));
420

  
421
      for (String fieldNamesExpression1 : fieldNamesExpression) {
422
        appears = false;
423
        for (String classifyingFieldName : auxLegend.getClassifyingFieldNames()) {
424
          if (classifyingFieldName.compareTo((String) fieldNamesExpression1) == 0) {
425
            appears = true;
426
          }
427
        }
428
        if (!appears) {
429
          myFieldNames.add((String) fieldNamesExpression1);
430
        }
431
      }
432
      auxLegend.setClassifyingFieldNames(
433
              myFieldNames.toArray(new String[myFieldNames.size()])
434
      );
435

  
436
    } else {
437
      for (String fieldNamesExpression1 : fieldNamesExpression) {
438
        myFieldNames.add((String) fieldNamesExpression1);
439
      }
440
      auxLegend.setClassifyingFieldNames(myFieldNames.toArray(new String[myFieldNames.size()]));
441
    }
442
  }
443

  
444
  @Override
445
  public ImageIcon getIcon() {
446
    ImageIcon icon = IconThemeHelper.getImageIcon("legend-overview-vector-filter-expression");
447
    return icon;
448
  }
449

  
450
  private void fillTableSkipDefault(VectorFilterExpressionLegend leg) {
451

  
452
    Object[] src_expr = leg.getValues();
453
    List<Integer> rem_ind = new ArrayList<>();
454
    for (int i = 0; i < src_expr.length; i++) {
455
      if (VectorFilterExpressionLegend.I18N_DEFAULT.
456
              compareToIgnoreCase((String) src_expr[i]) == 0) {
457
        rem_ind.add(i);
458
      }
459
    }
460
    ISymbol[] src_syms = leg.getSymbols();
461
    String[] src_descs = leg.getDescriptions();
462
    // Object[] src_expr
463

  
464
    List<ISymbol> syms = new ArrayList<>();
465
    List<Object> vals = new ArrayList<>();
466
    List<String> descs = new ArrayList<>();
467
    for (int i = 0; i < src_expr.length; i++) {
468
      if (!isIn(i, rem_ind)) {
469
        syms.add(src_syms[i]);
470
        vals.add(src_expr[i]);
471
        descs.add(src_descs[i]);
472
      }
473
    }
474
    symbolTable.fillTableFromSymbolList(
475
            syms.toArray(new ISymbol[0]),
476
            vals.toArray(new Object[0]),
477
            descs.toArray(new String[0]));
478
  }
479

  
480
  /**
481
   * @param i
482
   * @param rem_ind
483
   * @return
484
   */
485
  private boolean isIn(int n, List<Integer> list) {
486

  
487
    if (list == null || list.isEmpty()) {
488
      return false;
489
    }
490
    for (Integer item : list) {
491
      if( item!=null && item==n ) {
492
        return true;
493
      }
494
    }
495
    return false;
496
  }
497

  
498
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.240/src/main/java/org/gvsig/symbology/gui/layerproperties/ExpressionSymbolPanelView.xml
1
<?xml version="1.0" encoding="UTF-8"?>
2

  
3
<object classname="com.jeta.forms.store.memento.FormPackage">
4
 <at name="fileversion">
5
  <object classname="com.jeta.forms.store.memento.FormsVersion2">
6
   <at name="major">2</at>
7
   <at name="minor">0</at>
8
   <at name="sub">0</at>
9
  </object>
10
 </at>
11
 <at name="form">
12
  <object classname="com.jeta.forms.store.memento.FormMemento">
13
   <super classname="com.jeta.forms.store.memento.ComponentMemento">
14
    <at name="cellconstraints">
15
     <object classname="com.jeta.forms.store.memento.CellConstraintsMemento">
16
      <at name="column">1</at>
17
      <at name="row">1</at>
18
      <at name="colspan">1</at>
19
      <at name="rowspan">1</at>
20
      <at name="halign">default</at>
21
      <at name="valign">default</at>
22
      <at name="insets" object="insets">0,0,0,0</at>
23
     </object>
24
    </at>
25
    <at name="componentclass">com.jeta.forms.gui.form.FormComponent</at>
26
   </super>
27
   <at name="id">/home/jjdelcerro/datos/devel/org.gvsig.legend.vectorfilterexpression.app.mainplugin/src/main/java/org/gvsig/symbology/gui/layerproperties/ExpressionSymbolPanelView.xml</at>
28
   <at name="rowspecs">CENTER:2DLU:NONE,CENTER:DEFAULT:NONE,CENTER:2DLU:NONE,FILL:50PX:GROW(1.0),CENTER:2DLU:NONE,CENTER:DEFAULT:NONE,CENTER:2DLU:NONE,FILL:DEFAULT:NONE,CENTER:2DLU:NONE</at>
29
   <at name="colspecs">FILL:4DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:4DLU:NONE</at>
30
   <at name="components">
31
    <object classname="java.util.LinkedList">
32
     <item >
33
      <at name="value">
34
       <object classname="com.jeta.forms.store.memento.BeanMemento">
35
        <super classname="com.jeta.forms.store.memento.ComponentMemento">
36
         <at name="cellconstraints">
37
          <object classname="com.jeta.forms.store.memento.CellConstraintsMemento">
38
           <at name="column">2</at>
39
           <at name="row">2</at>
40
           <at name="colspan">1</at>
41
           <at name="rowspan">1</at>
42
           <at name="halign">default</at>
43
           <at name="valign">default</at>
44
           <at name="insets" object="insets">0,0,0,0</at>
45
          </object>
46
         </at>
47
         <at name="componentclass">com.jeta.forms.gui.form.StandardComponent</at>
48
        </super>
49
        <at name="jetabeanclass">com.jeta.forms.gui.beans.JETABean</at>
50
        <at name="beanclass">com.jeta.forms.components.separator.TitledSeparator</at>
51
        <at name="beanproperties">
52
         <object classname="com.jeta.forms.store.memento.PropertiesMemento">
53
          <at name="classname">com.jeta.forms.components.separator.TitledSeparator</at>
54
          <at name="properties">
55
           <object classname="com.jeta.forms.store.support.PropertyMap">
56
            <at name="border">
57
             <object classname="com.jeta.forms.store.properties.CompoundBorderProperty">
58
              <super classname="com.jeta.forms.store.properties.BorderProperty">
59
               <at name="name">border</at>
60
              </super>
61
              <at name="borders">
62
               <object classname="java.util.LinkedList">
63
                <item >
64
                 <at name="value">
65
                  <object classname="com.jeta.forms.store.properties.DefaultBorderProperty">
66
                   <super classname="com.jeta.forms.store.properties.BorderProperty">
67
                    <at name="name">border</at>
68
                   </super>
69
                  </object>
70
                 </at>
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff