Revision 35329

View differences:

branches/v2_0_0_prep/libraries/org.gvsig.symbology/org.gvsig.symbology.lib/org.gvsig.symbology.lib.impl/src/main/java/org/gvsig/symbology/fmap/mapcontext/rendering/legend/impl/AbstractVectorialLegend.java
93 93
 * @author 2009- <a href="cordinyana@gvsig.org">C?sar Ordi?ana</a> - gvSIG team
94 94
 */
95 95
public abstract class AbstractVectorialLegend extends AbstractLegend implements
96
		IVectorLegend {
96
IVectorLegend {
97 97

  
98
	public static final String VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME = "VectorialLegend";
98
    public static final String VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME = "VectorialLegend";
99 99

  
100
	private static final String FIELD_HAS_ZSORT = "hasZSort";
101
	private static final String FIELD_SHAPETYPE = "shapeType";
102
	private static final String FIELD_DEFAULT_SYMBOL = "defaultSymbol";
100
    private static final String FIELD_HAS_ZSORT = "hasZSort";
101
    private static final String FIELD_SHAPETYPE = "shapeType";
102
    private static final String FIELD_DEFAULT_SYMBOL = "defaultSymbol";
103 103

  
104
	private static final GeometryManager geomManager = GeometryLocator
105
			.getGeometryManager();
104
    private static final GeometryManager geomManager = GeometryLocator
105
    .getGeometryManager();
106 106

  
107
	protected ZSort zSort;
107
    protected ZSort zSort;
108 108

  
109
	public ZSort getZSort() {
110
		return zSort;
111
	}
109
    public ZSort getZSort() {
110
        return zSort;
111
    }
112 112

  
113
	public void setZSort(ZSort zSort) {
114
		if (zSort == null) {
115
			removeLegendListener(this.zSort);
116
		}
117
		this.zSort = zSort;
118
		addLegendListener(zSort);
119
	}
113
    public void setZSort(ZSort zSort) {
114
        if (zSort == null) {
115
            removeLegendListener(this.zSort);
116
        }
117
        this.zSort = zSort;
118
        addLegendListener(zSort);
119
    }
120
    
121
    @SuppressWarnings("unchecked")
122
    public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
123
        Cancellable cancel, double scale, Map queryParameters,
124
        ICoordTrans coordTrans, FeatureStore featureStore)
125
    throws LegendException {
126
        double dpi = MapContext.getScreenDPI();
127
        draw(image, g, viewPort, cancel, scale, queryParameters, coordTrans,
128
            featureStore, null, dpi);
129
    }
130
    
131
    @SuppressWarnings("unchecked")
132
    public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
133
        Cancellable cancel, double scale, Map queryParameters,
134
        ICoordTrans coordTrans, FeatureStore featureStore, FeatureQuery featureQuery)
135
    throws LegendException {
136
        double dpi = MapContext.getScreenDPI();
137
        draw(image, g, viewPort, cancel, scale, queryParameters, coordTrans,
138
            featureStore, featureQuery, dpi);
139
    }
120 140

  
121
	@SuppressWarnings("unchecked")
122
	public void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
123
			Cancellable cancel, double scale, Map queryParameters,
124
			ICoordTrans coordTrans, FeatureStore featureStore, Evaluator evaluator)
125
			throws LegendException {
126
		double dpi = MapContext.getScreenDPI();
127
		draw(image, g, viewPort, cancel, scale, queryParameters, coordTrans,
128
				featureStore, evaluator, dpi);
129
	}
141
    @SuppressWarnings("unchecked")
142
    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
143
        double scale, Map queryParameters, ICoordTrans coordTrans,
144
        FeatureStore featureStore, PrintAttributes properties)
145
    throws LegendException {
146
        print(g, viewPort, cancel, scale, queryParameters, coordTrans,
147
            featureStore, null, properties);
148
    }
149
    
150
    @SuppressWarnings("unchecked")
151
    public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
152
        double scale, Map queryParameters, ICoordTrans coordTrans,
153
        FeatureStore featureStore, FeatureQuery featureQuery, PrintAttributes properties)
154
    throws LegendException {
155
        double dpi = 72;
130 156

  
131
	@SuppressWarnings("unchecked")
132
	public void print(Graphics2D g, ViewPort viewPort, Cancellable cancel,
133
			double scale, Map queryParameters, ICoordTrans coordTrans,
134
			FeatureStore featureStore, Evaluator evaluator, PrintAttributes properties)
135
			throws LegendException {
136
		double dpi = 72;
157
        int resolution = properties.getPrintQuality();
137 158

  
138
		int resolution = properties.getPrintQuality();
159
        if (resolution == PrintAttributes.PRINT_QUALITY_NORMAL) {
160
            dpi = 300;
161
        } else if (resolution == PrintAttributes.PRINT_QUALITY_HIGH) {
162
            dpi = 600;
163
        } else if (resolution == PrintAttributes.PRINT_QUALITY_DRAFT) {
164
            dpi = 72;
165
        }
139 166

  
140
		if (resolution == PrintAttributes.PRINT_QUALITY_NORMAL) {
141
			dpi = 300;
142
		} else if (resolution == PrintAttributes.PRINT_QUALITY_HIGH) {
143
			dpi = 600;
144
		} else if (resolution == PrintAttributes.PRINT_QUALITY_DRAFT) {
145
			dpi = 72;
146
		}
167
        FeatureSet featureSet = null;
168
        DisposableIterator it = null;
169
        try {
170
            ZSort zSort = getZSort();
147 171

  
148
		FeatureSet featureSet = null;
149
		DisposableIterator it = null;
150
		try {
151
			ZSort zSort = getZSort();
172
            // if layer has map levels it will use a ZSort
173
            boolean useZSort = zSort != null && zSort.isUsingZSort();
152 174

  
153
			// if layer has map levels it will use a ZSort
154
			boolean useZSort = zSort != null && zSort.isUsingZSort();
175
            int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
176
            for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
177
                // Get the iterator over the visible features
178
                String[] fieldNames = getRequiredFeatureAttributeNames(featureStore);
155 179

  
156
			int mapLevelCount = (useZSort) ? zSort.getLevelCount() : 1;
157
			for (int mapPass = 0; mapPass < mapLevelCount; mapPass++) {
158
				// Get the iterator over the visible features
159
				String[] fieldNames = getRequiredFeatureAttributeNames(featureStore);
180
                if (featureQuery == null){
181
                    featureQuery = featureStore.createFeatureQuery();
182
                }
183
                featureQuery.setAttributeNames(fieldNames);
184
                featureQuery.setScale(scale);
160 185

  
161
				FeatureQuery featureQuery = featureStore.createFeatureQuery();
162
				featureQuery.setAttributeNames(fieldNames);
163
				featureQuery.setScale(scale);
186
                ContainsEnvelopeEvaluator iee = new ContainsEnvelopeEvaluator(
187
                    viewPort.getAdjustedEnvelope(),
188
                    viewPort.getProjection(),
189
                    featureStore.getDefaultFeatureType(), featureStore
190
                    .getDefaultFeatureType()
191
                    .getDefaultGeometryAttributeName());
192
                featureQuery.addFilter(iee); 
193
                featureSet = featureStore.getFeatureSet(featureQuery);
194
                it = featureSet.fastIterator();
164 195

  
165
				ContainsEnvelopeEvaluator iee = new ContainsEnvelopeEvaluator(
166
						viewPort.getAdjustedEnvelope(),
167
						viewPort.getProjection(),
168
						featureStore.getDefaultFeatureType(), featureStore
169
								.getDefaultFeatureType()
170
								.getDefaultGeometryAttributeName());
171
				featureQuery.addFilter(iee);
172
				featureQuery.addFilter(evaluator);
173
				featureSet = featureStore.getFeatureSet(featureQuery);
174
				it = featureSet.fastIterator();
196
                // Iteration over each feature
197
                while (!cancel.isCanceled() && it.hasNext()) {
198
                    Feature feat = (Feature) it.next();
199
                    Geometry geom = feat.getDefaultGeometry();
175 200

  
176
				// Iteration over each feature
177
				while (!cancel.isCanceled() && it.hasNext()) {
178
					Feature feat = (Feature) it.next();
179
					Geometry geom = feat.getDefaultGeometry();
201
                    // retrieve the symbol associated to such feature
202
                    ISymbol sym = getSymbolByFeature(feat);
203
                    if (sym == null) {
204
                        continue;
205
                    }
206
                    if (useZSort) {
207
                        int[] symLevels = zSort.getLevels(sym);
208
                        if (symLevels != null) {
180 209

  
181
					// retrieve the symbol associated to such feature
182
					ISymbol sym = getSymbolByFeature(feat);
183
					if (sym == null) {
184
						continue;
185
					}
186
					if (useZSort) {
187
						int[] symLevels = zSort.getLevels(sym);
188
						if (symLevels != null) {
210
                            // Check if this symbol is a multilayer
211
                            if (sym instanceof IMultiLayerSymbol) {
212
                                // if so, get the layer corresponding to the
213
                                // current level. If none, continue to next
214
                                // iteration
215
                                IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
216
                                for (int i = 0; i < mlSym.getLayerCount(); i++) {
217
                                    ISymbol mySym = mlSym.getLayer(i);
218
                                    if (symLevels[i] == mapPass) {
219
                                        sym = mySym;
220
                                        break;
221
                                    }
222
                                }
189 223

  
190
							// Check if this symbol is a multilayer
191
							if (sym instanceof IMultiLayerSymbol) {
192
								// if so, get the layer corresponding to the
193
								// current level. If none, continue to next
194
								// iteration
195
								IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
196
								for (int i = 0; i < mlSym.getLayerCount(); i++) {
197
									ISymbol mySym = mlSym.getLayer(i);
198
									if (symLevels[i] == mapPass) {
199
										sym = mySym;
200
										break;
201
									}
202
								}
224
                            } else {
225
                                // else, just draw the symbol in its level
226
                                if (symLevels[0] != mapPass) {
227
                                    continue;
228
                                }
229
                            }
230
                        }
231
                    }
203 232

  
204
							} else {
205
								// else, just draw the symbol in its level
206
								if (symLevels[0] != mapPass) {
207
									continue;
208
								}
209
							}
210
						}
211
					}
233
                    // Check if this symbol is sized with CartographicSupport
234
                    CartographicSupport csSym = null;
235
                    int symbolType = sym.getSymbolType();
212 236

  
213
					// Check if this symbol is sized with CartographicSupport
214
					CartographicSupport csSym = null;
215
					int symbolType = sym.getSymbolType();
237
                    if (symbolType == Geometry.TYPES.POINT
238
                        || symbolType == Geometry.TYPES.CURVE
239
                        || sym instanceof CartographicSupport) {
216 240

  
217
					if (symbolType == Geometry.TYPES.POINT
218
							|| symbolType == Geometry.TYPES.CURVE
219
							|| sym instanceof CartographicSupport) {
241
                        csSym = (CartographicSupport) sym;
242
                    }
220 243

  
221
						csSym = (CartographicSupport) sym;
222
					}
244
                    DrawOperationContext doc = new DrawOperationContext();
245
                    doc.setGraphics(g);
246
                    doc.setViewPort(viewPort);
247
                    if (csSym == null) {
248
                        doc.setSymbol(sym);
249
                    } else {
250
                        doc.setDPI(dpi);
251
                        doc.setCancellable(cancel);
252
                        doc.setSymbol((ISymbol) csSym);
253
                    }
254
                    geom.invokeOperation(DrawInts.CODE, doc);
255
                }
256
            }
257
        } catch (ReadException e) {
258
            throw new LegendDrawingException(e);
259
        } catch (GeometryOperationNotSupportedException e) {
260
            throw new LegendDrawingException(e);
261
        } catch (GeometryOperationException e) {
262
            throw new LegendDrawingException(e);
263
        } catch (DataException e) {
264
            throw new LegendDrawingException(e);
265
        } catch (MapContextException e) {
266
            throw new LegendDrawingException(e);
267
        } finally {
268
            if (it != null) {
269
                it.dispose();
270
            }
271
            if (featureSet != null) {
272
                featureSet.dispose();
273
            }
274
        }
275
    }
223 276

  
224
					DrawOperationContext doc = new DrawOperationContext();
225
					doc.setGraphics(g);
226
					doc.setViewPort(viewPort);
227
					if (csSym == null) {
228
						doc.setSymbol(sym);
229
					} else {
230
						doc.setDPI(dpi);
231
						doc.setCancellable(cancel);
232
						doc.setSymbol((ISymbol) csSym);
233
					}
234
					geom.invokeOperation(DrawInts.CODE, doc);
235
				}
236
			}
237
		} catch (ReadException e) {
238
			throw new LegendDrawingException(e);
239
		} catch (GeometryOperationNotSupportedException e) {
240
			throw new LegendDrawingException(e);
241
		} catch (GeometryOperationException e) {
242
			throw new LegendDrawingException(e);
243
		} catch (DataException e) {
244
			throw new LegendDrawingException(e);
245
		} catch (MapContextException e) {
246
			throw new LegendDrawingException(e);
247
		} finally {
248
			if (it != null) {
249
				it.dispose();
250
			}
251
			if (featureSet != null) {
252
				featureSet.dispose();
253
			}
254
		}
255
	}
277
    /**
278
     * Draws the features from the {@link FeatureStore}, filtered with the scale
279
     * and the query parameters, with the symbols of the legend.
280
     */
281
    @SuppressWarnings("unchecked")
282
    protected void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
283
        Cancellable cancel, double scale, Map queryParameters,
284
        ICoordTrans coordTrans, FeatureStore featureStore, FeatureQuery featureQuery, double dpi)
285
    throws LegendException {
256 286

  
257
	/**
258
	 * Draws the features from the {@link FeatureStore}, filtered with the scale
259
	 * and the query parameters, with the symbols of the legend.
260
	 */
261
	@SuppressWarnings("unchecked")
262
	protected void draw(BufferedImage image, Graphics2D g, ViewPort viewPort,
263
			Cancellable cancel, double scale, Map queryParameters,
264
			ICoordTrans coordTrans, FeatureStore featureStore, Evaluator evaluator, double dpi)
265
			throws LegendException {
287
        SimpleTaskStatus taskStatus = null;
288
        try {
289
            taskStatus = ToolsLocator.getTaskStatusManager()
290
            .creteDefaultSimpleTaskStatus(featureStore.getName());
291
            taskStatus.add();
292
            if (!getDefaultSymbol().isShapeVisible()) {
293
                return;
294
            }
266 295

  
267
		SimpleTaskStatus taskStatus = null;
268
		try {
269
			taskStatus = ToolsLocator.getTaskStatusManager()
270
					.creteDefaultSimpleTaskStatus(featureStore.getName());
271
			taskStatus.add();
272
			if (!getDefaultSymbol().isShapeVisible()) {
273
				return;
274
			}
296
            if (cancel.isCanceled()) {
297
                return;
298
            }
275 299

  
276
			if (cancel.isCanceled()) {
277
				return;
278
			}
300
            IProjection dataProjection;
301
            Envelope reprojectedDataEnvelop;
279 302

  
280
			IProjection dataProjection;
281
			Envelope reprojectedDataEnvelop;
303
            try {
304
                if (coordTrans == null) {
305
                    dataProjection = featureStore.getDefaultFeatureType()
306
                    .getDefaultSRS();
282 307

  
283
			try {
284
				if (coordTrans == null) {
285
					dataProjection = featureStore.getDefaultFeatureType()
286
							.getDefaultSRS();
308
                    // If the data does not provide a projection, use the
309
                    // current
310
                    // view one
311
                    if (dataProjection == null) {
312
                        dataProjection = viewPort.getProjection();
313
                    }
287 314

  
288
					// If the data does not provide a projection, use the
289
					// current
290
					// view one
291
					if (dataProjection == null) {
292
						dataProjection = viewPort.getProjection();
293
					}
315
                    reprojectedDataEnvelop = featureStore.getEnvelope();
316
                } else {
317
                    dataProjection = coordTrans.getPOrig();
294 318

  
295
					reprojectedDataEnvelop = featureStore.getEnvelope();
296
				} else {
297
					dataProjection = coordTrans.getPOrig();
319
                    reprojectedDataEnvelop = featureStore.getEnvelope()
320
                    .convert(coordTrans);
321
                }
322
            } catch (DataException e) {
323
                throw new LegendDrawingException(e);
324
            }
298 325

  
299
					reprojectedDataEnvelop = featureStore.getEnvelope()
300
							.convert(coordTrans);
301
				}
302
			} catch (DataException e) {
303
				throw new LegendDrawingException(e);
304
			}
326
            // Gets the view envelope
327
            Envelope viewPortEnvelope = viewPort.getAdjustedEnvelope();
305 328

  
306
			// Gets the view envelope
307
			Envelope viewPortEnvelope = viewPort.getAdjustedEnvelope();
329
            // Gets the data envelope with the viewport SRS
330
            Envelope myEnvelope = reprojectedDataEnvelop;
308 331

  
309
			// Gets the data envelope with the viewport SRS
310
			Envelope myEnvelope = reprojectedDataEnvelop;
332
            // TODO: in some cases, the legend may need a different check to
333
            // decide if the data must be drawn or not
334
            // Checks if the viewport envelope intersects with the data envelope
335
            if (!viewPortEnvelope.intersects(myEnvelope)) {
336
                // The data is not visible in the current viewport, do nothing.
337
                return;
338
            }
311 339

  
312
			// TODO: in some cases, the legend may need a different check to
313
			// decide if the data must be drawn or not
314
			// Checks if the viewport envelope intersects with the data envelope
315
			if (!viewPortEnvelope.intersects(myEnvelope)) {
316
				// The data is not visible in the current viewport, do nothing.
317
				return;
318
			}
340
            // Check if all the data is contained into the viewport envelope
341
            boolean containsAll = viewPortEnvelope.contains(myEnvelope);
319 342

  
320
			// Check if all the data is contained into the viewport envelope
321
			boolean containsAll = viewPortEnvelope.contains(myEnvelope);
343
            // Create the drawing notification to be reused on each iteration
344
            DefaultFeatureDrawnNotification drawnNotification = new DefaultFeatureDrawnNotification();
322 345

  
323
			// Create the drawing notification to be reused on each iteration
324
			DefaultFeatureDrawnNotification drawnNotification = new DefaultFeatureDrawnNotification();
346
            if (cancel.isCanceled()) {
347
                return;
348
            }
325 349

  
326
			if (cancel.isCanceled()) {
327
				return;
328
			}
350
            FeatureSet featureSet = null;
351
            try {
352
                taskStatus.message("Retrieve selection");
353
                FeatureSelection selection = featureStore.getFeatureSelection();
329 354

  
330
			FeatureSet featureSet = null;
331
			try {
332
				taskStatus.message("Retrieve selection");
333
				FeatureSelection selection = featureStore.getFeatureSelection();
355
                if (featureQuery == null){
356
                    featureQuery = featureStore.createFeatureQuery();
357
                }
358
                
359
                completeQuery(featureStore, featureQuery, scale,
360
                    queryParameters, coordTrans, dataProjection,
361
                    viewPortEnvelope, containsAll);
334 362

  
335
				FeatureQuery featureQuery = createQuery(featureStore, evaluator, scale,
336
						queryParameters, coordTrans, dataProjection,
337
						viewPortEnvelope, containsAll);
363
                taskStatus.message("Retrieve data");
364
                featureSet = featureStore.getFeatureSet(featureQuery);
338 365

  
339
				taskStatus.message("Retrieve data");
340
				featureSet = featureStore.getFeatureSet(featureQuery);
366
                if (cancel.isCanceled()) {
367
                    return;
368
                }
341 369

  
342
				if (cancel.isCanceled()) {
343
					return;
344
				}
370
                taskStatus.message("Drawing");
371
                drawFeatures(image, g, viewPort, cancel, coordTrans, dpi,
372
                    drawnNotification, featureSet, selection);
345 373

  
346
				taskStatus.message("Drawing");
347
				drawFeatures(image, g, viewPort, cancel, coordTrans, dpi,
348
						drawnNotification, featureSet, selection);
374
            } catch (BaseException e) {
375
                throw new LegendDrawingException(e);
376
            } finally {
377
                if (featureSet != null) {
378
                    featureSet.dispose();
379
                }
380
            }
381
        } finally {
382
            if (taskStatus != null) {
383
                taskStatus.terminate();
384
                taskStatus.remove();
385
                taskStatus = null;
386
            }
387
        }
349 388

  
350
			} catch (BaseException e) {
351
				throw new LegendDrawingException(e);
352
			} finally {
353
				if (featureSet != null) {
354
					featureSet.dispose();
355
				}
356
			}
357
		} finally {
358
			if (taskStatus != null) {
359
				taskStatus.terminate();
360
				taskStatus.remove();
361
				taskStatus = null;
362
			}
363
		}
389
    }
364 390

  
365
	}
391
    /**
392
     * Complete a {@link FeatureQuery} to load the {@link Feature}s to draw.
393
     */
394
    @SuppressWarnings("unchecked")
395
    private FeatureQuery completeQuery(FeatureStore featureStore, FeatureQuery featureQuery, double scale,
396
        Map queryParameters, ICoordTrans coordTrans,
397
        IProjection dataProjection, Envelope viewPortEnvelope,
398
        boolean containsAll) throws DataException {
366 399

  
367
	/**
368
	 * Creates a {@link FeatureQuery} to load the {@link Feature}s to draw.
369
	 */
370
	@SuppressWarnings("unchecked")
371
	private FeatureQuery createQuery(FeatureStore featureStore, Evaluator evaluator, double scale,
372
			Map queryParameters, ICoordTrans coordTrans,
373
			IProjection dataProjection, Envelope viewPortEnvelope,
374
			boolean containsAll) throws DataException {
400
        featureQuery.setScale(scale);
401
        
402
        //Adds the attributes
403
        String[] fieldNames = getRequiredFeatureAttributeNames(featureStore);
404
        for (int i=0 ; i<fieldNames.length ;i++){
405
            featureQuery.addAttributeName(fieldNames[i]);
406
        }       
407
        
408
        // TODO: Mobile has it's own IntersectsEnvelopeEvaluator
409
        if (!containsAll) {
410
            // Gets the viewport envelope with the data SRS
411
            Envelope viewPortEnvelopeInMyProj = viewPortEnvelope;
412
            // FIXME
413
            if (coordTrans != null) {
414
                viewPortEnvelopeInMyProj = viewPortEnvelope.convert(coordTrans
415
                    .getInverted());
416
            }
375 417

  
376
		FeatureQuery featureQuery = featureStore.createFeatureQuery();
377
		featureQuery.setScale(scale);
378
		String[] fieldNames = getRequiredFeatureAttributeNames(featureStore);
379
		featureQuery.setAttributeNames(fieldNames);
380
		// TODO: Mobile has it's own IntersectsEnvelopeEvaluator
381
		if (!containsAll) {
382
			// Gets the viewport envelope with the data SRS
383
			Envelope viewPortEnvelopeInMyProj = viewPortEnvelope;
384
			// FIXME
385
			if (coordTrans != null) {
386
				viewPortEnvelopeInMyProj = viewPortEnvelope.convert(coordTrans
387
						.getInverted());
388
			}
418
            if (dataProjection == null) {
419
                throw new IllegalArgumentException(
420
                "Error, the projection parameter value is null");
421
            }
389 422

  
390
			if (dataProjection == null) {
391
				throw new IllegalArgumentException(
392
						"Error, the projection parameter value is null");
393
			}
423
            IntersectsEnvelopeEvaluator iee = new IntersectsEnvelopeEvaluator(
424
                viewPortEnvelopeInMyProj, dataProjection,
425
                featureStore.getDefaultFeatureType(), featureStore
426
                .getDefaultFeatureType()
427
                .getDefaultGeometryAttributeName());
428
            featureQuery.addFilter(iee);			
429
        }
430
        if (queryParameters != null) {
431
            Iterator iterEntry = queryParameters.entrySet().iterator();
432
            Entry entry;
433
            while (iterEntry.hasNext()) {
434
                entry = (Entry) iterEntry.next();
435
                featureQuery.setQueryParameter((String) entry.getKey(),
436
                    entry.getValue());
437
            }
438
        }	
439
        return featureQuery;
440
    }
394 441

  
395
			IntersectsEnvelopeEvaluator iee = new IntersectsEnvelopeEvaluator(
396
					viewPortEnvelopeInMyProj, dataProjection,
397
					featureStore.getDefaultFeatureType(), featureStore
398
							.getDefaultFeatureType()
399
							.getDefaultGeometryAttributeName());
400
			featureQuery.addFilter(iee);
401
			featureQuery.addFilter(evaluator);
402
		}
403
		if (queryParameters != null) {
404
			Iterator iterEntry = queryParameters.entrySet().iterator();
405
			Entry entry;
406
			while (iterEntry.hasNext()) {
407
				entry = (Entry) iterEntry.next();
408
				featureQuery.setQueryParameter((String) entry.getKey(),
409
						entry.getValue());
410
			}
411
		}
412
		return featureQuery;
413
	}
442
    /**
443
     * Draws the features from the {@link FeatureSet}, with the symbols of the
444
     * legend.
445
     */
446
    private void drawFeatures(BufferedImage image, Graphics2D g,
447
        ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
448
        double dpi, DefaultFeatureDrawnNotification drawnNotification,
449
        FeatureSet featureSet, FeatureSelection selection)
450
    throws BaseException {
451
        if (isUseZSort()) {
452
            drawFeaturesMultiLayer(image, g, viewPort, cancel, coordTrans, dpi,
453
                drawnNotification, featureSet, selection);
454
        } else {
455
            drawFeaturesSingleLayer(image, g, viewPort, cancel, coordTrans,
456
                dpi, drawnNotification, featureSet, selection);
457
        }
458
    }
414 459

  
415
	/**
416
	 * Draws the features from the {@link FeatureSet}, with the symbols of the
417
	 * legend.
418
	 */
419
	private void drawFeatures(BufferedImage image, Graphics2D g,
420
			ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
421
			double dpi, DefaultFeatureDrawnNotification drawnNotification,
422
			FeatureSet featureSet, FeatureSelection selection)
423
			throws BaseException {
424
		if (isUseZSort()) {
425
			drawFeaturesMultiLayer(image, g, viewPort, cancel, coordTrans, dpi,
426
					drawnNotification, featureSet, selection);
427
		} else {
428
			drawFeaturesSingleLayer(image, g, viewPort, cancel, coordTrans,
429
					dpi, drawnNotification, featureSet, selection);
430
		}
431
	}
460
    /**
461
     * Draws the features from the {@link FeatureSet}, with the symbols of the
462
     * legend, using a single drawing layer.
463
     */
464
    private void drawFeaturesSingleLayer(final BufferedImage image,
465
        final Graphics2D g, final ViewPort viewPort,
466
        final Cancellable cancel, final ICoordTrans coordTrans,
467
        final double dpi,
468
        final DefaultFeatureDrawnNotification drawnNotification,
469
        FeatureSet featureSet, final FeatureSelection selection)
470
    throws BaseException {
432 471

  
433
	/**
434
	 * Draws the features from the {@link FeatureSet}, with the symbols of the
435
	 * legend, using a single drawing layer.
436
	 */
437
	private void drawFeaturesSingleLayer(final BufferedImage image,
438
			final Graphics2D g, final ViewPort viewPort,
439
			final Cancellable cancel, final ICoordTrans coordTrans,
440
			final double dpi,
441
			final DefaultFeatureDrawnNotification drawnNotification,
442
			FeatureSet featureSet, final FeatureSelection selection)
443
			throws BaseException {
472
        try {
473
            featureSet.accept(new Visitor() {
474
                public void visit(Object obj) throws VisitCanceledException,
475
                BaseException {
476
                    Feature feat = (Feature) obj;
477
                    drawFeatureSingleLayer(image, g, viewPort, cancel,
478
                        coordTrans, dpi, drawnNotification, feat, selection);
479
                }
480
            });
444 481

  
445
		try {
446
			featureSet.accept(new Visitor() {
447
				public void visit(Object obj) throws VisitCanceledException,
448
						BaseException {
449
					Feature feat = (Feature) obj;
450
					drawFeatureSingleLayer(image, g, viewPort, cancel,
451
							coordTrans, dpi, drawnNotification, feat, selection);
452
				}
453
			});
482
        } catch (ConcurrentDataModificationException e) {
483
            cancel.setCanceled(true);
484
            return;
485
        }
486
    }
454 487

  
455
		} catch (ConcurrentDataModificationException e) {
456
			cancel.setCanceled(true);
457
			return;
458
		}
459
	}
488
    /**
489
     * Draws a Feature with the symbols of the legend, using a single drawing
490
     * layer.
491
     */
492
    private void drawFeatureSingleLayer(BufferedImage image, Graphics2D g,
493
        ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
494
        double dpi, DefaultFeatureDrawnNotification drawnNotification,
495
        Feature feat, FeatureSelection selection)
496
    throws MapContextException, CreateGeometryException {
460 497

  
461
	/**
462
	 * Draws a Feature with the symbols of the legend, using a single drawing
463
	 * layer.
464
	 */
465
	private void drawFeatureSingleLayer(BufferedImage image, Graphics2D g,
466
			ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
467
			double dpi, DefaultFeatureDrawnNotification drawnNotification,
468
			Feature feat, FeatureSelection selection)
469
			throws MapContextException, CreateGeometryException {
498
        Geometry geom = feat.getDefaultGeometry();
499
        if (geom == null) {
500
            return;
501
        }
470 502

  
471
		Geometry geom = feat.getDefaultGeometry();
472
		if (geom == null) {
473
			return;
474
		}
503
        if (geom.getType() == Geometry.TYPES.NULL) {
504
            return;
505
        }
475 506

  
476
		if (geom.getType() == Geometry.TYPES.NULL) {
477
			return;
478
		}
507
        ISymbol sym = getSymbol(feat, selection);
508
        if (sym == null) {
509
            return;
510
        }
479 511

  
480
		ISymbol sym = getSymbol(feat, selection);
481
		if (sym == null) {
482
			return;
483
		}
512
        if (coordTrans != null) {
513
            geom = geom.cloneGeometry();
514
            geom.reProject(coordTrans);
515
        }
484 516

  
485
		if (coordTrans != null) {
486
			geom = geom.cloneGeometry();
487
			geom.reProject(coordTrans);
488
		}
517
        if (cancel.isCanceled()) {
518
            return;
519
        }
489 520

  
490
		if (cancel.isCanceled()) {
491
			return;
492
		}
521
        drawGeometry(geom, image, feat, sym, viewPort, g, dpi, cancel);
493 522

  
494
		drawGeometry(geom, image, feat, sym, viewPort, g, dpi, cancel);
523
        // Notify the drawing observers
524
        drawnNotification.setFeature(feat);
525
        drawnNotification.setDrawnGeometry(geom);
526
        notifyObservers(drawnNotification);
527
    }
495 528

  
496
		// Notify the drawing observers
497
		drawnNotification.setFeature(feat);
498
		drawnNotification.setDrawnGeometry(geom);
499
		notifyObservers(drawnNotification);
500
	}
529
    /**
530
     * Draws the features from the {@link FeatureSet}, with the symbols of the
531
     * legend, using a multiple drawing layer.
532
     */
533
    private void drawFeaturesMultiLayer(BufferedImage image, Graphics2D g,
534
        ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
535
        double dpi, DefaultFeatureDrawnNotification drawnNotification,
536
        FeatureSet featureSet, FeatureSelection selection)
537
    throws MapContextException, CreateGeometryException, DataException {
501 538

  
502
	/**
503
	 * Draws the features from the {@link FeatureSet}, with the symbols of the
504
	 * legend, using a multiple drawing layer.
505
	 */
506
	private void drawFeaturesMultiLayer(BufferedImage image, Graphics2D g,
507
			ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
508
			double dpi, DefaultFeatureDrawnNotification drawnNotification,
509
			FeatureSet featureSet, FeatureSelection selection)
510
			throws MapContextException, CreateGeometryException, DataException {
539
        // -- visual FX stuff
540
        long time = System.currentTimeMillis();
511 541

  
512
		// -- visual FX stuff
513
		long time = System.currentTimeMillis();
542
        boolean bSymbolLevelError = false;
543
        // render temporary map each screenRefreshRate milliseconds;
544
        int screenRefreshDelay = (int) ((1D / MapContext.getDrawFrameRate()) * 3 * 1000);
545
        BufferedImage[] imageLevels = null;
546
        Graphics2D[] graphics = null;
514 547

  
515
		boolean bSymbolLevelError = false;
516
		// render temporary map each screenRefreshRate milliseconds;
517
		int screenRefreshDelay = (int) ((1D / MapContext.getDrawFrameRate()) * 3 * 1000);
518
		BufferedImage[] imageLevels = null;
519
		Graphics2D[] graphics = null;
548
        imageLevels = new BufferedImage[getZSort().getLevelCount()];
549
        graphics = new Graphics2D[imageLevels.length];
550
        for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
520 551

  
521
		imageLevels = new BufferedImage[getZSort().getLevelCount()];
522
		graphics = new Graphics2D[imageLevels.length];
523
		for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
552
            imageLevels[i] = CompatLocator.getGraphicsUtils()
553
            .createBufferedImage(image.getWidth(), image.getHeight(),
554
                image.getType());
524 555

  
525
			imageLevels[i] = CompatLocator.getGraphicsUtils()
526
					.createBufferedImage(image.getWidth(), image.getHeight(),
527
							image.getType());
556
            graphics[i] = imageLevels[i].createGraphics();
557
            graphics[i].setTransform(g.getTransform());
558
            graphics[i].setRenderingHints(g.getRenderingHints());
559
        }
560
        // -- end visual FX stuff
528 561

  
529
			graphics[i] = imageLevels[i].createGraphics();
530
			graphics[i].setTransform(g.getTransform());
531
			graphics[i].setRenderingHints(g.getRenderingHints());
532
		}
533
		// -- end visual FX stuff
562
        DisposableIterator it = null;
563
        try {
564
            it = featureSet.fastIterator();
565
            // Iteration over each feature
566
            while (it.hasNext()) {
567
                if (cancel.isCanceled()) {
568
                    return;
569
                }
570
                Feature feat = (Feature) it.next();
534 571

  
535
		DisposableIterator it = null;
536
		try {
537
			it = featureSet.fastIterator();
538
			// Iteration over each feature
539
			while (it.hasNext()) {
540
				if (cancel.isCanceled()) {
541
					return;
542
				}
543
				Feature feat = (Feature) it.next();
572
                bSymbolLevelError |= drawFeatureMultiLayer(image, g, viewPort,
573
                    cancel, coordTrans, dpi, drawnNotification, selection,
574
                    time, screenRefreshDelay, imageLevels, graphics, feat);
544 575

  
545
				bSymbolLevelError |= drawFeatureMultiLayer(image, g, viewPort,
546
						cancel, coordTrans, dpi, drawnNotification, selection,
547
						time, screenRefreshDelay, imageLevels, graphics, feat);
576
            }
577
        } catch (ConcurrentDataModificationException e) {
578
            cancel.setCanceled(true);
579
            return;
580
        } finally {
581
            if (it != null) {
582
                it.dispose();
583
            }
584
        }
548 585

  
549
			}
550
		} catch (ConcurrentDataModificationException e) {
551
			cancel.setCanceled(true);
552
			return;
553
		} finally {
554
			if (it != null) {
555
				it.dispose();
556
			}
557
		}
586
        g.drawImage(image, 0, 0, null);
558 587

  
559
		g.drawImage(image, 0, 0, null);
588
        Point2D offset = viewPort.getOffset();
589
        CompatLocator.getGraphicsUtils().translate(g, offset.getX(),
590
            offset.getY());
560 591

  
561
		Point2D offset = viewPort.getOffset();
562
		CompatLocator.getGraphicsUtils().translate(g, offset.getX(),
563
				offset.getY());
592
        for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
593
            g.drawImage(imageLevels[i], 0, 0, null);
594
            imageLevels[i] = null;
595
            graphics[i] = null;
596
        }
564 597

  
565
		for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
566
			g.drawImage(imageLevels[i], 0, 0, null);
567
			imageLevels[i] = null;
568
			graphics[i] = null;
569
		}
598
        CompatLocator.getGraphicsUtils().translate(g, -offset.getX(),
599
            -offset.getY());
570 600

  
571
		CompatLocator.getGraphicsUtils().translate(g, -offset.getX(),
572
				-offset.getY());
601
        imageLevels = null;
602
        graphics = null;
573 603

  
574
		imageLevels = null;
575
		graphics = null;
604
        if (bSymbolLevelError) {
605
            setZSort(null);
606
        }
607
    }
576 608

  
577
		if (bSymbolLevelError) {
578
			setZSort(null);
579
		}
580
	}
609
    /**
610
     * Draws a Feature with the symbols of the legend, using a multiple drawing
611
     * layer.
612
     */
613
    private boolean drawFeatureMultiLayer(BufferedImage image, Graphics2D g,
614
        ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
615
        double dpi, DefaultFeatureDrawnNotification drawnNotification,
616
        FeatureSelection selection, long time, int screenRefreshDelay,
617
        BufferedImage[] imageLevels, Graphics2D[] graphics, Feature feat)
618
    throws MapContextException, CreateGeometryException {
581 619

  
582
	/**
583
	 * Draws a Feature with the symbols of the legend, using a multiple drawing
584
	 * layer.
585
	 */
586
	private boolean drawFeatureMultiLayer(BufferedImage image, Graphics2D g,
587
			ViewPort viewPort, Cancellable cancel, ICoordTrans coordTrans,
588
			double dpi, DefaultFeatureDrawnNotification drawnNotification,
589
			FeatureSelection selection, long time, int screenRefreshDelay,
590
			BufferedImage[] imageLevels, Graphics2D[] graphics, Feature feat)
591
			throws MapContextException, CreateGeometryException {
620
        Geometry geom = feat.getDefaultGeometry();
621
        boolean bSymbolLevelError = false;
622
        long drawingTime = time;
592 623

  
593
		Geometry geom = feat.getDefaultGeometry();
594
		boolean bSymbolLevelError = false;
595
		long drawingTime = time;
624
        if (geom.getType() == Geometry.TYPES.NULL) {
625
            return false;
626
        }
596 627

  
597
		if (geom.getType() == Geometry.TYPES.NULL) {
598
			return false;
599
		}
628
        ISymbol sym = getSymbol(feat, selection);
600 629

  
601
		ISymbol sym = getSymbol(feat, selection);
630
        if (sym == null) {
631
            return false;
632
        }
602 633

  
603
		if (sym == null) {
604
			return false;
605
		}
634
        if (coordTrans != null) {
635
            geom = geom.cloneGeometry();
636
            geom.reProject(coordTrans);
637
        }
606 638

  
607
		if (coordTrans != null) {
608
			geom = geom.cloneGeometry();
609
			geom.reProject(coordTrans);
610
		}
639
        if (cancel.isCanceled()) {
640
            return false;
641
        }
611 642

  
612
		if (cancel.isCanceled()) {
613
			return false;
614
		}
643
        // Check if this symbol is a multilayer
644
        int[] symLevels = getZSort().getLevels(sym);
645
        if (sym instanceof IMultiLayerSymbol) {
646
            // if so, treat each of its layers as a single
647
            // symbol
648
            // in its corresponding map level
649
            IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
650
            for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
651
                ISymbol mySym = mlSym.getLayer(i);
652
                int symbolLevel = 0;
653
                if (symLevels != null) {
654
                    symbolLevel = symLevels[i];
655
                } else {
656
                    /*
657
                     * an error occured when managing symbol levels some of the
658
                     * legend changed events regarding the symbols did not
659
                     * finish satisfactory and the legend is now inconsistent.
660
                     * For this drawing, it will finish as it was at the bottom
661
                     * (level 0) but, when done, the ZSort will be reset to
662
                     * avoid app crashes. This is a bug that has to be fixed.
663
                     */
664
                    bSymbolLevelError = true;
665
                }
666
                drawGeometry(geom, imageLevels[symbolLevel], feat, mySym,
667
                    viewPort, graphics[symbolLevel], dpi, cancel);
668
            }
669
        } else {
670
            // else, just draw the symbol in its level
671
            int symbolLevel = 0;
672
            if (symLevels != null) {
673
                symbolLevel = symLevels[0];
674
            }
675
            drawGeometry(geom, imageLevels[symbolLevel], feat, sym, viewPort,
676
                graphics[symbolLevel], dpi, cancel);
677
        }
615 678

  
616
		// Check if this symbol is a multilayer
617
		int[] symLevels = getZSort().getLevels(sym);
618
		if (sym instanceof IMultiLayerSymbol) {
619
			// if so, treat each of its layers as a single
620
			// symbol
621
			// in its corresponding map level
622
			IMultiLayerSymbol mlSym = (IMultiLayerSymbol) sym;
623
			for (int i = 0; !cancel.isCanceled() && i < mlSym.getLayerCount(); i++) {
624
				ISymbol mySym = mlSym.getLayer(i);
625
				int symbolLevel = 0;
626
				if (symLevels != null) {
627
					symbolLevel = symLevels[i];
628
				} else {
629
					/*
630
					 * an error occured when managing symbol levels some of the
631
					 * legend changed events regarding the symbols did not
632
					 * finish satisfactory and the legend is now inconsistent.
633
					 * For this drawing, it will finish as it was at the bottom
634
					 * (level 0) but, when done, the ZSort will be reset to
635
					 * avoid app crashes. This is a bug that has to be fixed.
636
					 */
637
					bSymbolLevelError = true;
638
				}
639
				drawGeometry(geom, imageLevels[symbolLevel], feat, mySym,
640
						viewPort, graphics[symbolLevel], dpi, cancel);
641
			}
642
		} else {
643
			// else, just draw the symbol in its level
644
			int symbolLevel = 0;
645
			if (symLevels != null) {
646
				symbolLevel = symLevels[0];
647
			}
648
			drawGeometry(geom, imageLevels[symbolLevel], feat, sym, viewPort,
649
					graphics[symbolLevel], dpi, cancel);
650
		}
679
        // -- visual FX stuff
680
        // Cuando el offset!=0 se est? dibujando sobre el
681
        // Layout y por tanto no tiene que ejecutar el
682
        // siguiente c?digo.
683
        Point2D offset = viewPort.getOffset();
684
        if (offset.getX() == 0 && offset.getY() == 0) {
685
            if ((System.currentTimeMillis() - drawingTime) > screenRefreshDelay) {
651 686

  
652
		// -- visual FX stuff
653
		// Cuando el offset!=0 se est? dibujando sobre el
654
		// Layout y por tanto no tiene que ejecutar el
655
		// siguiente c?digo.
656
		Point2D offset = viewPort.getOffset();
657
		if (offset.getX() == 0 && offset.getY() == 0) {
658
			if ((System.currentTimeMillis() - drawingTime) > screenRefreshDelay) {
687
                BufferedImage virtualBim = CompatLocator.getGraphicsUtils()
688
                .createBufferedImage(image.getWidth(),
689
                    image.getHeight(), BufferedImage.TYPE_INT_ARGB);
659 690

  
660
				BufferedImage virtualBim = CompatLocator.getGraphicsUtils()
661
						.createBufferedImage(image.getWidth(),
662
								image.getHeight(), BufferedImage.TYPE_INT_ARGB);
691
                Graphics2D virtualGraphics = virtualBim.createGraphics();
692
                virtualGraphics.drawImage(image, 0, 0, null);
693
                for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
694
                    virtualGraphics.drawImage(imageLevels[i], 0, 0, null);
695
                }
696
                g.clearRect(0, 0, image.getWidth(), image.getHeight());
697
                g.drawImage(virtualBim, 0, 0, null);
698
                drawingTime = System.currentTimeMillis();
699
            }
700
            // -- end visual FX stuff
663 701

  
664
				Graphics2D virtualGraphics = virtualBim.createGraphics();
665
				virtualGraphics.drawImage(image, 0, 0, null);
666
				for (int i = 0; !cancel.isCanceled() && i < imageLevels.length; i++) {
667
					virtualGraphics.drawImage(imageLevels[i], 0, 0, null);
668
				}
669
				g.clearRect(0, 0, image.getWidth(), image.getHeight());
670
				g.drawImage(virtualBim, 0, 0, null);
671
				drawingTime = System.currentTimeMillis();
672
			}
673
			// -- end visual FX stuff
702
        }
703
        // Notify the drawing observers
704
        drawnNotification.setFeature(feat);
705
        drawnNotification.setDrawnGeometry(geom);
706
        notifyObservers(drawnNotification);
707
        return bSymbolLevelError;
708
    }
674 709

  
675
		}
676
		// Notify the drawing observers
677
		drawnNotification.setFeature(feat);
678
		drawnNotification.setDrawnGeometry(geom);
679
		notifyObservers(drawnNotification);
680
		return bSymbolLevelError;
681
	}
710
    /**
711
     * Returns the symbol to use to draw a {@link Feature} taking into account
712
     * if it is selected.
713
     */
714
    private ISymbol getSymbol(Feature feat, FeatureSelection selection)
715
    throws MapContextException {
716
        // retrieve the symbol associated to such feature
717
        ISymbol sym = getSymbolByFeature(feat);
682 718

  
683
	/**
684
	 * Returns the symbol to use to draw a {@link Feature} taking into account
685
	 * if it is selected.
686
	 */
687
	private ISymbol getSymbol(Feature feat, FeatureSelection selection)
688
			throws MapContextException {
689
		// retrieve the symbol associated to such feature
690
		ISymbol sym = getSymbolByFeature(feat);
719
        if (sym != null && selection.isSelected(feat)) {
720
            sym = sym.getSymbolForSelection();
721
        }
722
        return sym;
723
    }
691 724

  
692
		if (sym != null && selection.isSelected(feat)) {
693
			sym = sym.getSymbolForSelection();
694
		}
695
		return sym;
696
	}
725
    /**
726
     * Returns if the legend is using a ZSort.
727
     */
728
    private boolean isUseZSort() {
729
        return getZSort() != null && getZSort().isUsingZSort();
730
    }
697 731

  
698
	/**
699
	 * Returns if the legend is using a ZSort.
700
	 */
701
	private boolean isUseZSort() {
702
		return getZSort() != null && getZSort().isUsingZSort();
703
	}
732
    /**
733
     * Draws a {@link Geometry} using the given {@link ISymbol}, over the
734
     * {@link Graphics2D} object.
735
     */
736
    private void drawGeometry(Geometry geom, BufferedImage image,
737
        Feature feature, ISymbol symbol, ViewPort viewPort,
738
        Graphics2D graphics, double dpi, Cancellable cancellable)
739
    throws CreateGeometryException {
704 740

  
705
	/**
706
	 * Draws a {@link Geometry} using the given {@link ISymbol}, over the
707
	 * {@link Graphics2D} object.
708
	 */
709
	private void drawGeometry(Geometry geom, BufferedImage image,
710
			Feature feature, ISymbol symbol, ViewPort viewPort,
711
			Graphics2D graphics, double dpi, Cancellable cancellable)
712
			throws CreateGeometryException {
741
        if (geom instanceof Aggregate) {
742
            drawAggregate((Aggregate) geom, image, feature, symbol, viewPort,
743
                graphics, dpi, cancellable);
744
        } else {
745
            boolean bDrawCartographicSupport = false;
746
            if (symbol instanceof CartographicSupport) {
747
                bDrawCartographicSupport = ((CartographicSupport) symbol)
748
                .getUnit() != -1;
749
            }
713 750

  
714
		if (geom instanceof Aggregate) {
715
			drawAggregate((Aggregate) geom, image, feature, symbol, viewPort,
716
					graphics, dpi, cancellable);
717
		} else {
718
			boolean bDrawCartographicSupport = false;
719
			if (symbol instanceof CartographicSupport) {
720
				bDrawCartographicSupport = ((CartographicSupport) symbol)
721
						.getUnit() != -1;
722
			}
751
            double previousSize = 0.0d;
723 752

  
724
			double previousSize = 0.0d;
753
            if (bDrawCartographicSupport) {
754
                // make the symbol to resize itself with the current rendering
755
                // context
756
                previousSize = ((CartographicSupport) symbol)
757
                .toCartographicSize(viewPort, dpi, geom);
758
            }
725 759

  
726
			if (bDrawCartographicSupport) {
727
				// make the symbol to resize itself with the current rendering
728
				// context
729
				previousSize = ((CartographicSupport) symbol)
730
						.toCartographicSize(viewPort, dpi, geom);
731
			}
760
            try {
761
                // draw it as normally
762
                double[] dot = new double[2];
763
                boolean onePoint = symbol.isOneDotOrPixel(geom, dot, viewPort,
764
                    (int) dpi);
732 765

  
733
			try {
734
				// draw it as normally
735
				double[] dot = new double[2];
736
				boolean onePoint = symbol.isOneDotOrPixel(geom, dot, viewPort,
737
						(int) dpi);
766
                if (onePoint) {
767
                    if (dot[0] < 0 || dot[1] < 0 || dot[0] >= image.getWidth()
768
                        || dot[1] >= image.getHeight()) {
769
                        return;
770
                    }
771
                    // FIXME: setRgb should change to draw
772
                    image.setRGB((int) dot[0], (int) dot[1],
773
                        symbol.getOnePointRgb());
774
                } else {
775
                    Geometry decimatedShape = transformToInts(geom,
776
                        viewPort.getAffineTransform());
777
                    symbol.draw(graphics, viewPort.getAffineTransform(),
778
                        decimatedShape, feature, cancellable);
779
                }
738 780

  
739
				if (onePoint) {
740
					if (dot[0] < 0 || dot[1] < 0 || dot[0] >= image.getWidth()
741
							|| dot[1] >= image.getHeight()) {
742
						return;
743
					}
744
					// FIXME: setRgb should change to draw
745
					image.setRGB((int) dot[0], (int) dot[1],
746
							symbol.getOnePointRgb());
747
				} else {
748
					Geometry decimatedShape = transformToInts(geom,
749
							viewPort.getAffineTransform());
750
					symbol.draw(graphics, viewPort.getAffineTransform(),
751
							decimatedShape, feature, cancellable);
752
				}
781
            } finally {
782
                if (bDrawCartographicSupport) {
783
                    // restore previous size
784
                    ((CartographicSupport) symbol).setCartographicSize(
785
                        previousSize, geom);
786
                }
787
            }
788
        }
789
    }
753 790

  
754
			} finally {
755
				if (bDrawCartographicSupport) {
756
					// restore previous size
757
					((CartographicSupport) symbol).setCartographicSize(
758
							previousSize, geom);
759
				}
760
			}
761
		}
762
	}
791
    /**
792
     * Draws an {@link Aggregate} using the given {@link ISymbol}, over the
793
     * {@link Graphics2D} object.
794
     */
795
    private void drawAggregate(Aggregate aggregate, BufferedImage image,
796
        Feature feature, ISymbol symbol, ViewPort viewPort,
797
        Graphics2D graphics, double dpi, Cancellable cancellable)
798
    throws CreateGeometryException {
799
        for (int i = 0; i < aggregate.getPrimitivesNumber(); i++) {
800
            Geometry prim = aggregate.getPrimitiveAt(i);
801
            drawGeometry(prim, image, feature, symbol, viewPort, graphics, dpi,
802
                cancellable);
803
        }
804
    }
763 805

  
764
	/**
765
	 * Draws an {@link Aggregate} using the given {@link ISymbol}, over the
766
	 * {@link Graphics2D} object.
767
	 */
768
	private void drawAggregate(Aggregate aggregate, BufferedImage image,
769
			Feature feature, ISymbol symbol, ViewPort viewPort,
770
			Graphics2D graphics, double dpi, Cancellable cancellable)
771
			throws CreateGeometryException {
772
		for (int i = 0; i < aggregate.getPrimitivesNumber(); i++) {
773
			Geometry prim = aggregate.getPrimitiveAt(i);
774
			drawGeometry(prim, image, feature, symbol, viewPort, graphics, dpi,
775
					cancellable);
776
		}
777
	}
778

  
779
	/**
780
	 * Transforms a Geometry from map coordinates to the view coordinates.
781
	 */
782
	private Geometry transformToInts(Geometry gp, AffineTransform at)
783
			throws CreateGeometryException {
784
		GeometryOperationContext geometryOperationContext = new GeometryOperationContext();
785
		geometryOperationContext.setAttribute(ToIntsGeometryOperation.PARAM, at);
786
		try {
806
    /**
807
     * Transforms a Geometry from map coordinates to the view coordinates.
808
     */
809
    private Geometry transformToInts(Geometry gp, AffineTransform at)
810
    throws CreateGeometryException {
811
        GeometryOperationContext geometryOperationContext = new GeometryOperationContext();
812
        geometryOperationContext.setAttribute(ToIntsGeometryOperation.PARAM, at);
813
        try {
787 814
            return (Geometry) gp.invokeOperation(ToIntsGeometryOperation.CODE, geometryOperationContext);
788 815
        } catch (GeometryOperationNotSupportedException e) {
789
          throw new CreateGeometryException(gp.getType(), gp.getGeometryType().getSubType(), e);
816
            throw new CreateGeometryException(gp.getType(), gp.getGeometryType().getSubType(), e);
790 817
        } catch (GeometryOperationException e) {
791 818
            throw new CreateGeometryException(gp.getType(), gp.getGeometryType().getSubType(), e);
792 819
        }	    
793
	}
820
    }
794 821

  
795
	public Object clone() throws CloneNotSupportedException {
796
		AbstractVectorialLegend clone = (AbstractVectorialLegend) super.clone();
822
    public Object clone() throws CloneNotSupportedException {
823
        AbstractVectorialLegend clone = (AbstractVectorialLegend) super.clone();
797 824

  
798
		// Clone zSort
799
		ZSort zSort = getZSort();
800
		if (zSort != null) {
801
			clone.setZSort(new ZSort(clone));
802
		}
803
		return clone;
804
	}
825
        // Clone zSort
826
        ZSort zSort = getZSort();
827
        if (zSort != null) {
828
            clone.setZSort(new ZSort(clone));
829
        }
830
        return clone;
831
    }
805 832

  
806
	public void loadFromState(PersistentState state)
807
			throws PersistenceException {
808
		// Set parent properties
809
		super.loadFromState(state);
810
		// Set own properties
833
    public void loadFromState(PersistentState state)
834
    throws PersistenceException {
835
        // Set parent properties
836
        super.loadFromState(state);
837
        // Set own properties
811 838

  
812
		setShapeType(state.getInt(FIELD_SHAPETYPE));
813
		if (state.getBoolean(FIELD_HAS_ZSORT)) {
814
			setZSort(new ZSort(this));
815
		}
816
		setDefaultSymbol((ISymbol) state.get(FIELD_DEFAULT_SYMBOL));
817
	}
839
        setShapeType(state.getInt(FIELD_SHAPETYPE));
840
        if (state.getBoolean(FIELD_HAS_ZSORT)) {
841
            setZSort(new ZSort(this));
842
        }
843
        setDefaultSymbol((ISymbol) state.get(FIELD_DEFAULT_SYMBOL));
844
    }
818 845

  
819
	public void saveToState(PersistentState state) throws PersistenceException {
820
		// Save parent properties
821
		super.saveToState(state);
822
		// Save own properties
823
		state.set(FIELD_SHAPETYPE, getShapeType());
824
		state.set(FIELD_HAS_ZSORT, this.zSort != null);
825
		state.set(FIELD_DEFAULT_SYMBOL, getDefaultSymbol());
826
	}
846
    public void saveToState(PersistentState state) throws PersistenceException {
847
        // Save parent properties
848
        super.saveToState(state);
849
        // Save own properties
850
        state.set(FIELD_SHAPETYPE, getShapeType());
851
        state.set(FIELD_HAS_ZSORT, this.zSort != null);
852
        state.set(FIELD_DEFAULT_SYMBOL, getDefaultSymbol());
853
    }
827 854

  
828
	public static class RegisterPersistence implements Callable {
855
    public static class RegisterPersistence implements Callable {
829 856

  
830
		public Object call() throws Exception {
831
			PersistenceManager manager = ToolsLocator.getPersistenceManager();
832
			if (manager
833
					.getDefinition(VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME) == null) {
834
				DynStruct definition = manager.addDefinition(
835
						AbstractVectorialLegend.class,
836
						VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME,
837
						VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME
838
								+ " persistence definition", null, null);
839
				// Extend the Legend base definition
840
				definition.extend(manager
841
						.getDefinition(LEGEND_PERSISTENCE_DEFINITION_NAME));
857
        public Object call() throws Exception {
858
            PersistenceManager manager = ToolsLocator.getPersistenceManager();
859
            if (manager
860
                .getDefinition(VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME) == null) {
861
                DynStruct definition = manager.addDefinition(
862
                    AbstractVectorialLegend.class,
863
                    VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME,
864
                    VECTORIAL_LEGEND_PERSISTENCE_DEFINITION_NAME
865
                    + " persistence definition", null, null);
866
                // Extend the Legend base definition
867
                definition.extend(manager
868
                    .getDefinition(LEGEND_PERSISTENCE_DEFINITION_NAME));
842 869

  
843
				// Shapetype
844
				definition.addDynFieldInt(FIELD_SHAPETYPE).setMandatory(true);
845
				// ZSort
846
				definition.addDynFieldBoolean(FIELD_HAS_ZSORT).setMandatory(
847
						true);
848
				// Default symbol
849
				definition.addDynFieldObject(FIELD_DEFAULT_SYMBOL)
850
						.setClassOfValue(ISymbol.class).setMandatory(true);
851
			}
852
			return Boolean.TRUE;
853
		}
870
                // Shapetype
871
                definition.addDynFieldInt(FIELD_SHAPETYPE).setMandatory(true);
872
                // ZSort
873
                definition.addDynFieldBoolean(FIELD_HAS_ZSORT).setMandatory(
874
                    true);
875
                // Default symbol
876
                definition.addDynFieldObject(FIELD_DEFAULT_SYMBOL)
877
                .setClassOfValue(ISymbol.class).setMandatory(true);
878
            }
879
            return Boolean.TRUE;
880
        }
854 881

  
855
	}
882
    }
856 883

  
857
	/**
858
	 * Returns the names of the {@link Feature} attributes required for the
859
	 * {@link ILegend} to operate.
860
	 * 
861
	 * @param featureStore
862
	 *            the store where the {@link Feature}s belong to
863
	 * @return the names of required {@link Feature} attribute names
864
	 * @throws DataException
865
	 *             if there is an error getting the attribute names
866
	 */
867
	protected abstract String[] getRequiredFeatureAttributeNames(
868
			FeatureStore featureStore) throws DataException;
884
    /**
885
     * Returns the names of the {@link Feature} attributes required for the
886
     * {@link ILegend} to operate.
887
     * 
888
     * @param featureStore
889
     *            the store where the {@link Feature}s belong to
890
     * @return the names of required {@link Feature} attribute names
891
     * @throws DataException
892
     *             if there is an error getting the attribute names
893
     */
894
    protected abstract String[] getRequiredFeatureAttributeNames(
895
        FeatureStore featureStore) throws DataException;
869 896
}
branches/v2_0_0_prep/libraries/libFMap_mapcontext/src-test/org/gvsig/fmap/mapcontext/impl/DefaultMapContextManagerTest.java
36 36
import org.gvsig.fmap.crs.CRSFactory;
37 37
import org.gvsig.fmap.dal.exception.ReadException;
38 38
import org.gvsig.fmap.dal.feature.Feature;
39
import org.gvsig.fmap.dal.feature.FeatureQuery;
39 40
import org.gvsig.fmap.dal.feature.FeatureStore;
40 41
import org.gvsig.fmap.mapcontext.MapContext;
41 42
import org.gvsig.fmap.mapcontext.MapContextDrawer;
......
62 63
 * @author <a href="mailto:cordinyana@gvsig.org">C?sar Ordi?ana</a>
63 64
 */
64 65
public class DefaultMapContextManagerTest extends
65
		AbstractLibraryAutoInitTestCase {
66
AbstractLibraryAutoInitTestCase {
66 67

  
67
	private DefaultMapContextManager manager;
68
    private DefaultMapContextManager manager;
68 69

  
69
	protected void doSetUp() throws Exception {
70
		manager = new DefaultMapContextManager();
71
		
72
		manager.registerLegend("DummyLegend", DummyVectorLegend.class);
73
		manager.setDefaultVectorLegend("DummyLegend");
74
		manager.registerLegendReader("Dummy", DummyLegendReader.class);
75
		manager.registerLegendWriter("DummyLegend", "Dummy", DummyLegendWriter.class);
76
	}
70
    protected void doSetUp() throws Exception {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff