Revision 8281

View differences:

org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.203/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.203</version>
9

  
10
    <parent>
11
        <groupId>org.gvsig</groupId>
12
        <artifactId>org.gvsig.desktop</artifactId>
13
        <version>2.0.402</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.203</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.203</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.203</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.203/buildNumber.properties
1
#Wed Nov 23 00:03:11 CET 2022
2
buildNumber=208
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.203/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.203/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.203/src/main/java/org/gvsig/symbology/gui/layerproperties/VectorFilterExpressionPanelView.java
1
package org.gvsig.symbology.gui.layerproperties;
2

  
3
import com.jeta.open.i18n.I18NUtils;
4
import com.jgoodies.forms.layout.CellConstraints;
5
import com.jgoodies.forms.layout.FormLayout;
6
import java.awt.BorderLayout;
7
import java.awt.Color;
8
import java.awt.ComponentOrientation;
9
import java.awt.Container;
10
import java.awt.Dimension;
11
import javax.swing.Box;
12
import javax.swing.ImageIcon;
13
import javax.swing.JButton;
14
import javax.swing.JCheckBox;
15
import javax.swing.JFrame;
16
import javax.swing.JPanel;
17
import javax.swing.JScrollPane;
18
import javax.swing.JTable;
19
import javax.swing.border.EmptyBorder;
20
import javax.swing.border.LineBorder;
21

  
22

  
23
public class VectorFilterExpressionPanelView extends JPanel
24
{
25
   JTable tblSymbols = new JTable();
26
   JCheckBox chkDefaultValues = new JCheckBox();
27
   JButton btnDefaultValuesPreview = new JButton();
28
   JButton btnUp = new JButton();
29
   JButton btnDown = new JButton();
30
   JButton btnAdd = new JButton();
31
   JButton btnRemove = new JButton();
32
   JButton btnRemoveAll = new JButton();
33

  
34
   /**
35
    * Default constructor
36
    */
37
   public VectorFilterExpressionPanelView()
38
   {
39
      initializePanel();
40
   }
41

  
42
   /**
43
    * Adds fill components to empty cells in the first row and first column of the grid.
44
    * This ensures that the grid spacing will be the same as shown in the designer.
45
    * @param cols an array of column indices in the first row where fill components should be added.
46
    * @param rows an array of row indices in the first column where fill components should be added.
47
    */
48
   void addFillComponents( Container panel, int[] cols, int[] rows )
49
   {
50
      Dimension filler = new Dimension(10,10);
51

  
52
      boolean filled_cell_11 = false;
53
      CellConstraints cc = new CellConstraints();
54
      if ( cols.length > 0 && rows.length > 0 )
55
      {
56
         if ( cols[0] == 1 && rows[0] == 1 )
57
         {
58
            /** add a rigid area  */
59
            panel.add( Box.createRigidArea( filler ), cc.xy(1,1) );
60
            filled_cell_11 = true;
61
         }
62
      }
63

  
64
      for( int index = 0; index < cols.length; index++ )
65
      {
66
         if ( cols[index] == 1 && filled_cell_11 )
67
         {
68
            continue;
69
         }
70
         panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) );
71
      }
72

  
73
      for( int index = 0; index < rows.length; index++ )
74
      {
75
         if ( rows[index] == 1 && filled_cell_11 )
76
         {
77
            continue;
78
         }
79
         panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) );
80
      }
81

  
82
   }
83

  
84
   /**
85
    * Helper method to load an image file from the CLASSPATH
86
    * @param imageName the package and name of the file to load relative to the CLASSPATH
87
    * @return an ImageIcon instance with the specified image file
88
    * @throws IllegalArgumentException if the image resource cannot be loaded.
89
    */
90
   public ImageIcon loadImage( String imageName )
91
   {
92
      try
93
      {
94
         ClassLoader classloader = getClass().getClassLoader();
95
         java.net.URL url = classloader.getResource( imageName );
96
         if ( url != null )
97
         {
98
            ImageIcon icon = new ImageIcon( url );
99
            return icon;
100
         }
101
      }
102
      catch( Exception e )
103
      {
104
         e.printStackTrace();
105
      }
106
      throw new IllegalArgumentException( "Unable to load image: " + imageName );
107
   }
108

  
109
   /**
110
    * Method for recalculating the component orientation for 
111
    * right-to-left Locales.
112
    * @param orientation the component orientation to be applied
113
    */
114
   public void applyComponentOrientation( ComponentOrientation orientation )
115
   {
116
      // Not yet implemented...
117
      // I18NUtils.applyComponentOrientation(this, orientation);
118
      super.applyComponentOrientation(orientation);
119
   }
120

  
121
   public JPanel createPanel()
122
   {
123
      JPanel jpanel1 = new JPanel();
124
      FormLayout formlayout1 = new FormLayout("FILL:4DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:4DLU:NONE,FILL:DEFAULT:NONE,FILL:4DLU:NONE","CENTER:2DLU:NONE,CENTER:DEFAULT:NONE,CENTER:2DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:2DLU:NONE,CENTER:DEFAULT:NONE,CENTER:2DLU:NONE");
125
      CellConstraints cc = new CellConstraints();
126
      jpanel1.setLayout(formlayout1);
127

  
128
      tblSymbols.setName("tblSymbols");
129
      JScrollPane jscrollpane1 = new JScrollPane();
130
      jscrollpane1.setViewportView(tblSymbols);
131
      jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
132
      jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
133
      jpanel1.add(jscrollpane1,cc.xy(2,4));
134

  
135
      jpanel1.add(createPanel1(),cc.xy(2,2));
136
      jpanel1.add(createPanel2(),cc.xy(4,4));
137
      jpanel1.add(createPanel3(),cc.xy(2,6));
138
      addFillComponents(jpanel1,new int[]{ 1,2,3,4,5 },new int[]{ 1,2,3,4,5,6,7 });
139
      return jpanel1;
140
   }
141

  
142
   public JPanel createPanel1()
143
   {
144
      JPanel jpanel1 = new JPanel();
145
      FormLayout formlayout1 = new FormLayout("FILL:DEFAULT:NONE,FILL:DEFAULT:NONE,FILL:100PX:NONE","CENTER:MAX(22PX;MIN):NONE");
146
      CellConstraints cc = new CellConstraints();
147
      jpanel1.setLayout(formlayout1);
148

  
149
      chkDefaultValues.setActionCommand("_Resto_de_valores");
150
      chkDefaultValues.setName("chkDefaultValues");
151
      chkDefaultValues.setText("resto_valores");
152
      jpanel1.add(chkDefaultValues,cc.xy(1,1));
153

  
154
      btnDefaultValuesPreview.setName("btnDefaultValuesPreview");
155
      LineBorder lineborder1 = new LineBorder(new Color(0,0,0),1,false);
156
      btnDefaultValuesPreview.setBorder(lineborder1);
157
      jpanel1.add(btnDefaultValuesPreview,new CellConstraints(3,1,1,1,CellConstraints.FILL,CellConstraints.FILL));
158

  
159
      addFillComponents(jpanel1,new int[]{ 2 },new int[0]);
160
      return jpanel1;
161
   }
162

  
163
   public JPanel createPanel2()
164
   {
165
      JPanel jpanel1 = new JPanel();
166
      FormLayout formlayout1 = new FormLayout("FILL:DEFAULT:NONE","CENTER:DEFAULT:NONE,CENTER:2DLU:NONE,CENTER:DEFAULT:NONE,FILL:DEFAULT:GROW(1.0)");
167
      CellConstraints cc = new CellConstraints();
168
      jpanel1.setLayout(formlayout1);
169

  
170
      btnUp.setActionCommand("...");
171
      btnUp.setName("btnUp");
172
      btnUp.setText("...");
173
      EmptyBorder emptyborder1 = new EmptyBorder(2,2,2,2);
174
      btnUp.setBorder(emptyborder1);
175
      jpanel1.add(btnUp,cc.xy(1,1));
176

  
177
      btnDown.setActionCommand("...");
178
      btnDown.setName("btnDown");
179
      btnDown.setText("...");
180
      EmptyBorder emptyborder2 = new EmptyBorder(2,2,2,2);
181
      btnDown.setBorder(emptyborder2);
182
      jpanel1.add(btnDown,cc.xy(1,3));
183

  
184
      addFillComponents(jpanel1,new int[0],new int[]{ 2,4 });
185
      return jpanel1;
186
   }
187

  
188
   public JPanel createPanel3()
189
   {
190
      JPanel jpanel1 = new JPanel();
191
      FormLayout formlayout1 = new FormLayout("FILL:DEFAULT:GROW(0.1),FILL:4DLU:NONE,FILL:DEFAULT:GROW(0.1),FILL:4DLU:NONE,FILL:DEFAULT:GROW(0.1),FILL:DEFAULT:GROW(1.0)","CENTER:DEFAULT:NONE");
192
      CellConstraints cc = new CellConstraints();
193
      jpanel1.setLayout(formlayout1);
194

  
195
      btnAdd.setActionCommand("JButton");
196
      btnAdd.setName("btnAdd");
197
      btnAdd.setText("Anadir");
198
      jpanel1.add(btnAdd,cc.xy(1,1));
199

  
200
      btnRemove.setActionCommand("JButton");
201
      btnRemove.setName("btnRemove");
202
      btnRemove.setText("Quitar");
203
      jpanel1.add(btnRemove,cc.xy(5,1));
204

  
205
      btnRemoveAll.setActionCommand("JButton");
206
      btnRemoveAll.setName("btnRemoveAll");
207
      btnRemoveAll.setText("Quitar_todos");
208
      jpanel1.add(btnRemoveAll,cc.xy(3,1));
209

  
210
      addFillComponents(jpanel1,new int[]{ 2,4,6 },new int[0]);
211
      return jpanel1;
212
   }
213

  
214
   /**
215
    * Initializer
216
    */
217
   protected void initializePanel()
218
   {
219
      setLayout(new BorderLayout());
220
      add(createPanel(), BorderLayout.CENTER);
221
   }
222

  
223

  
224
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.203/src/main/java/org/gvsig/symbology/gui/layerproperties/ExpressionSymbolPanel.java
1
package org.gvsig.symbology.gui.layerproperties;
2

  
3
import java.awt.BorderLayout;
4
import java.awt.Dimension;
5
import org.gvsig.expressionevaluator.Expression;
6
import org.gvsig.expressionevaluator.swing.JExpressionBuilder;
7
import org.gvsig.fmap.dal.feature.FeatureStore;
8
import org.gvsig.fmap.dal.swing.DALSwingLocator;
9
import org.gvsig.fmap.dal.swing.DataSwingManager;
10
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
11
import org.gvsig.tools.swing.api.ToolsSwingLocator;
12
import org.gvsig.tools.swing.api.ToolsSwingManager;
13
import org.gvsig.tools.swing.api.pickercontroller.PickerController;
14

  
15

  
16
public class ExpressionSymbolPanel extends ExpressionSymbolPanelView
17
  {
18

  
19
  private final FeatureStore store;
20
  private PickerController<ISymbol> pickerSymbolController;
21
  private JExpressionBuilder expressionPanel;
22
  private final ISymbol symbol;
23
  private final int symbolType;
24
  
25
  public ExpressionSymbolPanel(FeatureStore store,  int symbolType, ISymbol symbol) {
26
    this.store = store;
27
    this.symbolType = symbolType;
28
    this.symbol = symbol;
29
    this.initComponents();
30
  }
31

  
32
  private void initComponents() {
33
    ToolsSwingManager toolsSwingManager = ToolsSwingLocator.getToolsSwingManager();
34
    DataSwingManager dataSwingManager = DALSwingLocator.getDataSwingManager();
35
    
36
    toolsSwingManager.translate(this.lblExpression);
37
    toolsSwingManager.translate(this.lblSymbolAndDescriptor);
38
    
39
    this.expressionPanel = dataSwingManager.createQueryFilterExpresion(this.store);
40
    this.pnlExpression.setLayout(new BorderLayout());
41
    this.pnlExpression.add(expressionPanel.asJComponent(), BorderLayout.CENTER);
42
    
43
    this.pickerSymbolController = new SymbolPickerController(
44
            this.btnSymbolPreview, 
45
            this.txtSymbolDescription,
46
            this.symbolType,
47
            this.symbol
48
    );
49
    this.setPreferredSize(new Dimension(800,500));
50
  }
51
  
52
  public String getExpression() {
53
    Expression exp = this.expressionPanel.getExpression();
54
    if( exp == null ) {
55
      return null;
56
    }
57
    return exp.getPhrase();
58
  }
59

  
60
  public ISymbol getSymbol() {
61
      ISymbol theSymbol = this.pickerSymbolController.get();
62
      if( theSymbol == null ) {
63
        return null;
64
      }
65
      return theSymbol;
66
  }
67
  
68
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.203/src/main/java/org/gvsig/symbology/gui/layerproperties/SymbolPickerController.java
1
package org.gvsig.symbology.gui.layerproperties;
2

  
3
import java.awt.Dimension;
4
import java.awt.Graphics2D;
5
import java.awt.Rectangle;
6
import java.awt.event.ActionEvent;
7
import java.awt.event.ComponentAdapter;
8
import java.awt.event.ComponentEvent;
9
import java.awt.event.ComponentListener;
10
import java.awt.geom.AffineTransform;
11
import java.awt.image.BufferedImage;
12
import javax.swing.ImageIcon;
13
import javax.swing.JButton;
14
import javax.swing.JTextField;
15
import javax.swing.text.JTextComponent;
16
import org.gvsig.andami.ui.mdiManager.MDIManager;
17
import org.gvsig.app.ApplicationLocator;
18
import org.gvsig.app.gui.styling.SymbolSelector;
19
import org.gvsig.app.project.documents.view.legend.gui.ISymbolSelector;
20
import org.gvsig.fmap.mapcontext.MapContextLocator;
21
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
22
import org.gvsig.fmap.mapcontext.rendering.symbols.SymbolDrawingException;
23
import org.gvsig.tools.swing.api.pickercontroller.AbstractPickerController;
24

  
25
/**
26
 *
27
 * @author gvSIG Team
28
 */
29
@SuppressWarnings("UseSpecificCatch")
30
public class SymbolPickerController extends AbstractPickerController<ISymbol> {
31

  
32
  private final JButton btnPreview;
33
  private final JTextComponent txtDescription;
34
  private Dimension previewSize;
35
  private int geomType;
36
  private ISymbol symbol;
37

  
38
  SymbolPickerController(JButton btnPreview, JTextComponent txtDescription, int geomType, ISymbol symbol) {
39
    this.btnPreview = btnPreview;
40
    if( txtDescription==null ) {
41
      this.txtDescription = new JTextField();
42
    } else {
43
      this.txtDescription = txtDescription;
44
    }
45

  
46
    if (symbol == null) {
47
      this.symbol = MapContextLocator.getSymbolManager().createSymbol(geomType);
48
    }
49
    this.previewSize = null;
50
    this.btnPreview.addActionListener((ActionEvent e) -> {
51
      doSelectSymbol();
52
    });
53
    this.btnPreview.addComponentListener(new ComponentAdapter() {
54
      @Override
55
      public void componentResized(ComponentEvent e) {
56
        updatePreview();
57
      }      
58
    });
59
    this.set(this.symbol);
60
  }
61

  
62
  private void updatePreview() {
63
    int width = btnPreview.getWidth();
64
    int height = btnPreview.getHeight();
65
    if( width<5 || height<5 ) {
66
      return;
67
    }
68
    previewSize = new Dimension(width - 4, height - 4);
69
    this.btnPreview.setIcon(
70
            new ImageIcon(this.createPreview(this.previewSize, this.symbol))
71
    );
72
  }
73
  
74
  private BufferedImage createPreview(Dimension size, ISymbol symbol) {
75
    BufferedImage previewImage = new BufferedImage(
76
            size.width,
77
            size.height, 
78
            BufferedImage.TYPE_INT_ARGB
79
    );
80

  
81
    Graphics2D g2 = (Graphics2D) previewImage.createGraphics();
82
    if (g2 != null) {
83
      Rectangle bounds = new Rectangle(size.width, size.height);
84
      ISymbol prevSymbol = symbol;
85
      try {
86
        prevSymbol.drawInsideRectangle(g2, new AffineTransform(), bounds, null);
87
      } catch (Exception e) {
88
          try {
89
            prevSymbol = MapContextLocator.getSymbolManager().getWarningSymbol(
90
                    SymbolDrawingException.STR_UNSUPPORTED_SET_OF_SETTINGS,
91
                    symbol.getDescription(),
92
                    SymbolDrawingException.UNSUPPORTED_SET_OF_SETTINGS
93
            );
94
            prevSymbol.drawInsideRectangle(g2,g2.getTransform(),bounds,null);
95
          } catch (Exception e1) {
96
            LOG.debug("Can't create preview symbol",e1);
97
          }
98
      }
99
    }
100
    return previewImage;
101
  }
102

  
103
  private void doSelectSymbol() {
104
    MDIManager uiManager = ApplicationLocator.getManager().getUIManager();
105
    ISymbolSelector sSelect = SymbolSelector.createSymbolSelector(this.symbol, this.geomType);
106
    uiManager.addWindow(sSelect);
107
    if (sSelect.getSelectedObject() != null) {
108
      this.symbol = (ISymbol) sSelect.getSelectedObject();
109
      this.updatePreview();
110
    }
111
  }
112

  
113
  @Override
114
  public ISymbol get() {
115
    symbol.setDescription(this.txtDescription.getText());
116
    return symbol;
117
  }
118

  
119
  @Override
120
  public final void set(ISymbol symbol) {
121
      this.symbol = symbol;
122
      this.geomType = symbol.getSymbolType();
123
      this.txtDescription.setText(this.symbol.getDescription());
124
      this.updatePreview();
125
  }
126

  
127
  @Override
128
  public void coerceAndSet(Object o) {
129
    this.set((ISymbol) o);
130
  }
131

  
132
  @Override
133
  public void setEnabled(boolean enabled) {
134
    this.btnPreview.setEnabled(enabled);
135
    this.txtDescription.setEnabled(enabled);
136
  }
137

  
138
  @Override
139
  public boolean isEnabled() {
140
    return this.btnPreview.isEnabled();
141
  }
142

  
143
}
org.gvsig.legend.vectorfilterexpression.app.mainplugin/tags/org.gvsig.legend.vectorfilterexpression.app.mainplugin-1.0.203/src/main/java/org/gvsig/symbology/gui/layerproperties/VectorFilterExpressionPanel.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.BorderLayout;
27
import java.awt.Dimension;
28
import java.awt.event.ActionEvent;
29
import java.awt.event.ActionListener;
30
import java.io.File;
31
import java.io.IOException;
32
import java.util.ArrayList;
33
import java.util.List;
34

  
35
import javax.swing.BoxLayout;
36
import javax.swing.ImageIcon;
37
import javax.swing.JButton;
38
import javax.swing.JCheckBox;
39
import javax.swing.JOptionPane;
40
import javax.swing.JPanel;
41
import org.apache.commons.lang3.StringUtils;
42

  
43
import org.slf4j.Logger;
44
import org.slf4j.LoggerFactory;
45

  
46
import org.gvsig.andami.IconThemeHelper;
47
import org.gvsig.app.ApplicationLocator;
48
import org.gvsig.app.project.documents.view.legend.gui.Categories;
49
import org.gvsig.app.project.documents.view.legend.gui.ILegendPanel;
50
import org.gvsig.app.project.documents.view.legend.gui.JSymbolPreviewButton;
51
import org.gvsig.app.project.documents.view.legend.gui.SymbolTable;
52
import org.gvsig.fmap.dal.exception.ReadException;
53
import org.gvsig.fmap.dal.feature.Feature;
54
import org.gvsig.fmap.dal.feature.FeatureAttributeDescriptor;
55
import org.gvsig.fmap.dal.feature.FeatureStore;
56
import org.gvsig.fmap.dal.feature.FeatureType;
57
import org.gvsig.fmap.mapcontext.layers.FLayer;
58
import org.gvsig.fmap.mapcontext.layers.operations.ClassifiableVectorial;
59
import org.gvsig.fmap.mapcontext.layers.vectorial.FLyrVect;
60
import org.gvsig.fmap.mapcontext.rendering.legend.ILegend;
61
import org.gvsig.fmap.mapcontext.rendering.symbols.ISymbol;
62
import org.gvsig.gui.beans.swing.GridBagLayoutPanel;
63
import org.gvsig.gui.beans.swing.JBlank;
64
import org.gvsig.i18n.Messages;
65
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.fill.impl.PictureFillSymbol;
66
import org.gvsig.symbology.fmap.mapcontext.rendering.symbol.style.IMarkerFillPropertiesStyle;
67
import org.gvsig.symbology.fmap.rendering.VectorFilterExpressionLegend;
68
import org.gvsig.symbology.swing.SymbologySwingLocator;
69
import org.gvsig.tools.ToolsLocator;
70
import org.gvsig.tools.i18n.I18nManager;
71
import org.gvsig.tools.swing.api.ToolsSwingLocator;
72
import org.gvsig.tools.swing.api.usability.UsabilitySwingManager;
73
import org.gvsig.tools.swing.api.windowmanager.Dialog;
74
import org.gvsig.tools.swing.api.windowmanager.WindowManager;
75
import org.gvsig.tools.swing.api.windowmanager.WindowManager_v2;
76

  
77
/**
78
 * Implements the JPanel that shows the properties of a
79
 * VectorialFilterExpressionLegend
80
 * in order to allows the user to modify its characteristics
81
 *
82
 * @author gvSIG Team
83
 *
84
 */
85
public class VectorFilterExpressionPanel extends JPanel
86
implements ILegendPanel, ActionListener {
87

  
88
    private static final Logger logger = LoggerFactory.getLogger(
89
        VectorFilterExpressionPanel.class);
90

  
91
	private static final long serialVersionUID = -7187473609965942511L;
92
	private VectorFilterExpressionLegend theLegend;
93
	private VectorFilterExpressionLegend auxLegend;
94
	private ClassifiableVectorial layer;
95
	private PictureFillSymbol previewSymbol;
96
	private JPanel pnlCenter;
97
	private JPanel pnlMovBut;
98
	private SymbolTable symbolTable;
99
	private JButton btnAddExpression;
100
//	private JButton btnModExpression;
101
	private JButton btnRemoveExpression;
102
	private JButton moveUp;
103
	private JButton moveDown;
104
	private int shapeType;
105
	protected JCheckBox chkdefaultvalues = null;
106
	protected JSymbolPreviewButton defaultSymbolPrev;
107
	private GridBagLayoutPanel defaultSymbolPanel = new GridBagLayoutPanel();
108
	private UsabilitySwingManager usabilitySwingManager = ToolsSwingLocator.getUsabilitySwingManager();
109

  
110
	/**
111
	 * This is the default constructor
112
	 */
113
	public VectorFilterExpressionPanel() {
114
		super();
115
		initialize();
116
	}
117

  
118

  
119
	/**
120
	 * This method initializes this
121
	 */
122
	private void initialize() {
123

  
124
		pnlCenter = new JPanel();
125
		pnlCenter.setLayout(new BorderLayout());
126

  
127
		JPanel pnlButtons = new JPanel();
128
		btnAddExpression = usabilitySwingManager.createJButton(
129
		    Messages.getText("Anadir"));
130
		btnAddExpression.setActionCommand("NEW_EXPRESSION");
131
		btnAddExpression.addActionListener(this);
132
		pnlButtons.add(btnAddExpression);
133

  
134
//		btnModExpression = usabilitySwingManager.createJButton(
135
//		    Messages.getText("modify_filter_expression"));
136
//		btnModExpression.setActionCommand("MODIFY_EXPRESSION");
137
//		btnModExpression.addActionListener(this);
138
//		pnlButtons.add(btnModExpression);
139

  
140
		btnRemoveExpression = usabilitySwingManager.createJButton(
141
		    Messages.getText("Quitar"));
142
		btnRemoveExpression.setActionCommand("REMOVE");
143
		btnRemoveExpression.addActionListener(this);
144
		pnlButtons.add(btnRemoveExpression);
145
		defaultSymbolPanel.add(getChkDefaultvalues());
146
		pnlCenter.add(defaultSymbolPanel,BorderLayout.NORTH);
147

  
148
		this.setLayout(new BorderLayout());
149
		this.add(pnlCenter, BorderLayout.CENTER);
150
		this.add(pnlButtons, BorderLayout.SOUTH);
151

  
152

  
153
	}
154
	public void getDefaultSymbolPrev(int shapeType) {
155
		if(defaultSymbolPrev == null){
156
			defaultSymbolPrev = new JSymbolPreviewButton(shapeType);
157
			defaultSymbolPrev.setPreferredSize(new Dimension(110,20));
158
			defaultSymbolPanel.add(defaultSymbolPrev,null);
159
		}
160
	}
161

  
162
	public String getDescription() {
163
		return Messages.getText(
164
		    "shows_the_elements_of_the_layer_depending_on_the_value_of_a_filter_expression") + ".";
165
	}
166

  
167
	public ISymbol getIconSymbol() {
168
		if (previewSymbol == null) {
169
			try {
170
				previewSymbol = new PictureFillSymbol();
171
				previewSymbol.setImage( new File(
172
						this.getClass().getClassLoader().
173
						getResource("images" + File.separator
174
						    + "legend" + File.separator
175
						    + "legend-overview-vectorial-unique-value.png").
176
						getFile()).toURI().toURL());
177
				previewSymbol.getMarkerFillProperties().
178
				setFillStyle(
179
						IMarkerFillPropertiesStyle.SINGLE_CENTERED_SYMBOL);
180
			} catch (IOException e) {
181
				return null;
182
			}
183
		}
184
		return previewSymbol;
185
	}
186

  
187
	public ILegend getLegend() {
188
		auxLegend.clear();
189
		fillSymbolListFromTable();
190

  
191
		theLegend = (VectorFilterExpressionLegend) auxLegend.cloneLegend();
192
		if(defaultSymbolPrev.getSymbol() != null)
193
			theLegend.setDefaultSymbol(defaultSymbolPrev.getSymbol());
194

  
195
		theLegend.useDefaultSymbol(chkdefaultvalues.isSelected());
196
		return theLegend;
197
	}
198
	/**
199
	 * Fills the list of symbols of the legend
200
	 *
201
	 */
202
	private void fillSymbolListFromTable() {
203
		Object clave;
204
		ISymbol theSymbol;
205

  
206
		FLyrVect m = (FLyrVect) layer;
207
		try {
208

  
209
			if(auxLegend.getClassifyingFieldNames() != null) {
210
				String[] fNames= auxLegend.getClassifyingFieldNames();
211
				int[] fieldTypes  = new int[auxLegend.getClassifyingFieldNames().length];
212

  
213
				FeatureStore fsto = (FeatureStore) m.getDataStore();
214
				FeatureType fty = fsto.getDefaultFeatureType();
215

  
216
				for (int i = 0; i < fNames.length; i++) {
217
					fieldTypes[i] = fty.getAttributeDescriptor(fNames[i]).getType();
218
				}
219

  
220
				auxLegend.setClassifyingFieldTypes(fieldTypes);
221
			}
222
		} catch (Exception e) {
223

  
224
		}
225

  
226
		auxLegend.useDefaultSymbol(chkdefaultvalues.isSelected());
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff