source: josm/trunk/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java@ 11553

Last change on this file since 11553 was 11553, checked in by Don-vip, 7 years ago

refactor handling of null values - use Java 8 Optional where possible

  • Property svn:eol-style set to native
File size: 19.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer.markerlayer;
3
4import java.awt.AlphaComposite;
5import java.awt.Color;
6import java.awt.Graphics;
7import java.awt.Graphics2D;
8import java.awt.Point;
9import java.awt.event.ActionEvent;
10import java.awt.image.BufferedImage;
11import java.io.File;
12import java.net.MalformedURLException;
13import java.net.URL;
14import java.text.DateFormat;
15import java.text.SimpleDateFormat;
16import java.util.ArrayList;
17import java.util.Arrays;
18import java.util.Collection;
19import java.util.Collections;
20import java.util.Date;
21import java.util.HashMap;
22import java.util.LinkedList;
23import java.util.List;
24import java.util.Map;
25import java.util.Optional;
26import java.util.TimeZone;
27
28import javax.swing.ImageIcon;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
32import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
33import org.openstreetmap.josm.data.coor.CachedLatLon;
34import org.openstreetmap.josm.data.coor.EastNorth;
35import org.openstreetmap.josm.data.coor.LatLon;
36import org.openstreetmap.josm.data.gpx.Extensions;
37import org.openstreetmap.josm.data.gpx.GpxConstants;
38import org.openstreetmap.josm.data.gpx.GpxLink;
39import org.openstreetmap.josm.data.gpx.WayPoint;
40import org.openstreetmap.josm.data.preferences.CachedProperty;
41import org.openstreetmap.josm.data.preferences.IntegerProperty;
42import org.openstreetmap.josm.gui.MapView;
43import org.openstreetmap.josm.tools.ImageProvider;
44import org.openstreetmap.josm.tools.Utils;
45import org.openstreetmap.josm.tools.template_engine.ParseError;
46import org.openstreetmap.josm.tools.template_engine.TemplateEngineDataProvider;
47import org.openstreetmap.josm.tools.template_engine.TemplateEntry;
48import org.openstreetmap.josm.tools.template_engine.TemplateParser;
49
50/**
51 * Basic marker class. Requires a position, and supports
52 * a custom icon and a name.
53 *
54 * This class is also used to create appropriate Marker-type objects
55 * when waypoints are imported.
56 *
57 * It hosts a public list object, named makers, containing implementations of
58 * the MarkerMaker interface. Whenever a Marker needs to be created, each
59 * object in makers is called with the waypoint parameters (Lat/Lon and tag
60 * data), and the first one to return a Marker object wins.
61 *
62 * By default, one the list contains one default "Maker" implementation that
63 * will create AudioMarkers for .wav files, ImageMarkers for .png/.jpg/.jpeg
64 * files, and WebMarkers for everything else. (The creation of a WebMarker will
65 * fail if there's no valid URL in the <link> tag, so it might still make sense
66 * to add Makers for such waypoints at the end of the list.)
67 *
68 * The default implementation only looks at the value of the <link> tag inside
69 * the <wpt> tag of the GPX file.
70 *
71 * <h2>HowTo implement a new Marker</h2>
72 * <ul>
73 * <li> Subclass Marker or ButtonMarker and override <code>containsPoint</code>
74 * if you like to respond to user clicks</li>
75 * <li> Override paint, if you want a custom marker look (not "a label and a symbol")</li>
76 * <li> Implement MarkerCreator to return a new instance of your marker class</li>
77 * <li> In you plugin constructor, add an instance of your MarkerCreator
78 * implementation either on top or bottom of Marker.markerProducers.
79 * Add at top, if your marker should overwrite an current marker or at bottom
80 * if you only add a new marker style.</li>
81 * </ul>
82 *
83 * @author Frederik Ramm
84 */
85public class Marker implements TemplateEngineDataProvider {
86
87 public static final class TemplateEntryProperty extends CachedProperty<TemplateEntry> {
88 // This class is a bit complicated because it supports both global and per layer settings. I've added per layer settings because
89 // GPXSettingsPanel had possibility to set waypoint label but then I've realized that markers use different layer then gpx data
90 // so per layer settings is useless. Anyway it's possible to specify marker layer pattern in Einstein preferences and maybe somebody
91 // will make gui for it so I'm keeping it here
92
93 private static final Map<String, TemplateEntryProperty> CACHE = new HashMap<>();
94
95 // Legacy code - convert label from int to template engine expression
96 private static final IntegerProperty PROP_LABEL = new IntegerProperty("draw.rawgps.layer.wpt", 0);
97
98 private static String getDefaultLabelPattern() {
99 switch (PROP_LABEL.get()) {
100 case 1:
101 return LABEL_PATTERN_NAME;
102 case 2:
103 return LABEL_PATTERN_DESC;
104 case 0:
105 case 3:
106 return LABEL_PATTERN_AUTO;
107 default:
108 return "";
109 }
110 }
111
112 public static TemplateEntryProperty forMarker(String layerName) {
113 String key = "draw.rawgps.layer.wpt.pattern";
114 if (layerName != null) {
115 key += '.' + layerName;
116 }
117 TemplateEntryProperty result = CACHE.get(key);
118 if (result == null) {
119 String defaultValue = layerName == null ? getDefaultLabelPattern() : "";
120 TemplateEntryProperty parent = layerName == null ? null : forMarker(null);
121 result = new TemplateEntryProperty(key, defaultValue, parent);
122 CACHE.put(key, result);
123 }
124 return result;
125 }
126
127 public static TemplateEntryProperty forAudioMarker(String layerName) {
128 String key = "draw.rawgps.layer.audiowpt.pattern";
129 if (layerName != null) {
130 key += '.' + layerName;
131 }
132 TemplateEntryProperty result = CACHE.get(key);
133 if (result == null) {
134 String defaultValue = layerName == null ? "?{ '{name}' | '{desc}' | '{" + Marker.MARKER_FORMATTED_OFFSET + "}' }" : "";
135 TemplateEntryProperty parent = layerName == null ? null : forAudioMarker(null);
136 result = new TemplateEntryProperty(key, defaultValue, parent);
137 CACHE.put(key, result);
138 }
139 return result;
140 }
141
142 private final TemplateEntryProperty parent;
143
144 private TemplateEntryProperty(String key, String defaultValue, TemplateEntryProperty parent) {
145 super(key, defaultValue);
146 this.parent = parent;
147 updateValue(); // Needs to be called because parent wasn't know in super constructor
148 }
149
150 @Override
151 protected TemplateEntry fromString(String s) {
152 try {
153 return new TemplateParser(s).parse();
154 } catch (ParseError e) {
155 Main.debug(e);
156 Main.warn("Unable to parse template engine pattern ''{0}'' for property {1}. Using default (''{2}'') instead",
157 s, getKey(), super.getDefaultValueAsString());
158 return getDefaultValue();
159 }
160 }
161
162 @Override
163 public String getDefaultValueAsString() {
164 if (parent == null)
165 return super.getDefaultValueAsString();
166 else
167 return parent.getAsString();
168 }
169
170 @Override
171 public void preferenceChanged(PreferenceChangeEvent e) {
172 if (e.getKey().equals(key) || (parent != null && e.getKey().equals(parent.getKey()))) {
173 updateValue();
174 }
175 }
176 }
177
178 /**
179 * Plugins can add their Marker creation stuff at the bottom or top of this list
180 * (depending on whether they want to override default behaviour or just add new
181 * stuff).
182 */
183 public static final List<MarkerProducers> markerProducers = new LinkedList<>();
184
185 // Add one Marker specifying the default behaviour.
186 static {
187 Marker.markerProducers.add((wpt, relativePath, parentLayer, time, offset) -> {
188 String uri = null;
189 // cheapest way to check whether "link" object exists and is a non-empty collection of GpxLink objects...
190 Collection<GpxLink> links = wpt.<GpxLink>getCollection(GpxConstants.META_LINKS);
191 if (links != null) {
192 for (GpxLink oneLink : links) {
193 uri = oneLink.uri;
194 break;
195 }
196 }
197
198 URL url = uriToUrl(uri, relativePath);
199 String urlStr = url == null ? "" : url.toString();
200 String symbolName = Optional.ofNullable(wpt.getString("symbol")).orElseGet(() -> wpt.getString(GpxConstants.PT_SYM));
201 // text marker is returned in every case, see #10208
202 final Marker marker = new Marker(wpt.getCoor(), wpt, symbolName, parentLayer, time, offset);
203 if (url == null) {
204 return Collections.singleton(marker);
205 } else if (urlStr.endsWith(".wav")) {
206 final AudioMarker audioMarker = new AudioMarker(wpt.getCoor(), wpt, url, parentLayer, time, offset);
207 Extensions exts = (Extensions) wpt.get(GpxConstants.META_EXTENSIONS);
208 if (exts != null && exts.containsKey("offset")) {
209 try {
210 audioMarker.syncOffset = Double.parseDouble(exts.get("sync-offset"));
211 } catch (NumberFormatException nfe) {
212 Main.warn(nfe);
213 }
214 }
215 return Arrays.asList(marker, audioMarker);
216 } else if (urlStr.endsWith(".png") || urlStr.endsWith(".jpg") || urlStr.endsWith(".jpeg") || urlStr.endsWith(".gif")) {
217 return Arrays.asList(marker, new ImageMarker(wpt.getCoor(), url, parentLayer, time, offset));
218 } else {
219 return Arrays.asList(marker, new WebMarker(wpt.getCoor(), url, parentLayer, time, offset));
220 }
221 });
222 }
223
224 private static URL uriToUrl(String uri, File relativePath) {
225 URL url = null;
226 if (uri != null) {
227 try {
228 url = new URL(uri);
229 } catch (MalformedURLException e) {
230 // Try a relative file:// url, if the link is not in an URL-compatible form
231 if (relativePath != null) {
232 url = Utils.fileToURL(new File(relativePath.getParentFile(), uri));
233 }
234 }
235 }
236 return url;
237 }
238
239 /**
240 * Returns an object of class Marker or one of its subclasses
241 * created from the parameters given.
242 *
243 * @param wpt waypoint data for marker
244 * @param relativePath An path to use for constructing relative URLs or
245 * <code>null</code> for no relative URLs
246 * @param parentLayer the <code>MarkerLayer</code> that will contain the created <code>Marker</code>
247 * @param time time of the marker in seconds since epoch
248 * @param offset double in seconds as the time offset of this marker from
249 * the GPX file from which it was derived (if any).
250 * @return a new Marker object
251 */
252 public static Collection<Marker> createMarkers(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) {
253 for (MarkerProducers maker : Marker.markerProducers) {
254 final Collection<Marker> markers = maker.createMarkers(wpt, relativePath, parentLayer, time, offset);
255 if (markers != null)
256 return markers;
257 }
258 return null;
259 }
260
261 public static final String MARKER_OFFSET = "waypointOffset";
262 public static final String MARKER_FORMATTED_OFFSET = "formattedWaypointOffset";
263
264 public static final String LABEL_PATTERN_AUTO = "?{ '{name} ({desc})' | '{name} ({cmt})' | '{name}' | '{desc}' | '{cmt}' }";
265 public static final String LABEL_PATTERN_NAME = "{name}";
266 public static final String LABEL_PATTERN_DESC = "{desc}";
267
268 private final DateFormat timeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
269 private final TemplateEngineDataProvider dataProvider;
270 private final String text;
271
272 protected final ImageIcon symbol;
273 private BufferedImage redSymbol;
274 public final MarkerLayer parentLayer;
275 /** Absolute time of marker in seconds since epoch */
276 public double time;
277 /** Time offset in seconds from the gpx point from which it was derived, may be adjusted later to sync with other data, so not final */
278 public double offset;
279
280 private String cachedText;
281 private int textVersion = -1;
282 private CachedLatLon coor;
283
284 private boolean erroneous;
285
286 public Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String iconName, MarkerLayer parentLayer,
287 double time, double offset) {
288 this(ll, dataProvider, null, iconName, parentLayer, time, offset);
289 }
290
291 public Marker(LatLon ll, String text, String iconName, MarkerLayer parentLayer, double time, double offset) {
292 this(ll, null, text, iconName, parentLayer, time, offset);
293 }
294
295 private Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String text, String iconName, MarkerLayer parentLayer,
296 double time, double offset) {
297 timeFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
298 setCoor(ll);
299
300 this.offset = offset;
301 this.time = time;
302 /* tell icon checking that we expect these names to exist */
303 // /* ICON(markers/) */"Bridge"
304 // /* ICON(markers/) */"Crossing"
305 this.symbol = iconName != null ? ImageProvider.getIfAvailable("markers", iconName) : null;
306 this.parentLayer = parentLayer;
307
308 this.dataProvider = dataProvider;
309 this.text = text;
310 }
311
312 /**
313 * Convert Marker to WayPoint so it can be exported to a GPX file.
314 *
315 * Override in subclasses to add all necessary attributes.
316 *
317 * @return the corresponding WayPoint with all relevant attributes
318 */
319 public WayPoint convertToWayPoint() {
320 WayPoint wpt = new WayPoint(getCoor());
321 wpt.put("time", timeFormatter.format(new Date(Math.round(time * 1000))));
322 if (text != null) {
323 wpt.addExtension("text", text);
324 } else if (dataProvider != null) {
325 for (String key : dataProvider.getTemplateKeys()) {
326 Object value = dataProvider.getTemplateValue(key, false);
327 if (value != null && GpxConstants.WPT_KEYS.contains(key)) {
328 wpt.put(key, value);
329 }
330 }
331 }
332 return wpt;
333 }
334
335 /**
336 * Sets the marker's coordinates.
337 * @param coor The marker's coordinates (lat/lon)
338 */
339 public final void setCoor(LatLon coor) {
340 this.coor = new CachedLatLon(coor);
341 }
342
343 /**
344 * Returns the marker's coordinates.
345 * @return The marker's coordinates (lat/lon)
346 */
347 public final LatLon getCoor() {
348 return coor;
349 }
350
351 /**
352 * Sets the marker's projected coordinates.
353 * @param eastNorth The marker's projected coordinates (easting/northing)
354 */
355 public final void setEastNorth(EastNorth eastNorth) {
356 this.coor = new CachedLatLon(eastNorth);
357 }
358
359 /**
360 * Returns the marker's projected coordinates.
361 * @return The marker's projected coordinates (easting/northing)
362 */
363 public final EastNorth getEastNorth() {
364 return coor.getEastNorth();
365 }
366
367 /**
368 * Checks whether the marker display area contains the given point.
369 * Markers not interested in mouse clicks may always return false.
370 *
371 * @param p The point to check
372 * @return <code>true</code> if the marker "hotspot" contains the point.
373 */
374 public boolean containsPoint(Point p) {
375 return false;
376 }
377
378 /**
379 * Called when the mouse is clicked in the marker's hotspot. Never
380 * called for markers which always return false from containsPoint.
381 *
382 * @param ev A dummy ActionEvent
383 */
384 public void actionPerformed(ActionEvent ev) {
385 // Do nothing
386 }
387
388 /**
389 * Paints the marker.
390 * @param g graphics context
391 * @param mv map view
392 * @param mousePressed true if the left mouse button is pressed
393 * @param showTextOrIcon true if text and icon shall be drawn
394 */
395 public void paint(Graphics g, MapView mv, boolean mousePressed, boolean showTextOrIcon) {
396 Point screen = mv.getPoint(getEastNorth());
397 if (symbol != null && showTextOrIcon) {
398 paintIcon(mv, g, screen.x-symbol.getIconWidth()/2, screen.y-symbol.getIconHeight()/2);
399 } else {
400 g.drawLine(screen.x-2, screen.y-2, screen.x+2, screen.y+2);
401 g.drawLine(screen.x+2, screen.y-2, screen.x-2, screen.y+2);
402 }
403
404 String labelText = getText();
405 if ((labelText != null) && showTextOrIcon) {
406 g.drawString(labelText, screen.x+4, screen.y+2);
407 }
408 }
409
410 protected void paintIcon(MapView mv, Graphics g, int x, int y) {
411 if (!erroneous) {
412 symbol.paintIcon(mv, g, x, y);
413 } else {
414 if (redSymbol == null) {
415 int width = symbol.getIconWidth();
416 int height = symbol.getIconHeight();
417
418 redSymbol = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
419 Graphics2D gbi = redSymbol.createGraphics();
420 gbi.drawImage(symbol.getImage(), 0, 0, null);
421 gbi.setColor(Color.RED);
422 gbi.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.666f));
423 gbi.fillRect(0, 0, width, height);
424 gbi.dispose();
425 }
426 g.drawImage(redSymbol, x, y, mv);
427 }
428 }
429
430 protected TemplateEntryProperty getTextTemplate() {
431 return TemplateEntryProperty.forMarker(parentLayer.getName());
432 }
433
434 /**
435 * Returns the Text which should be displayed, depending on chosen preference
436 * @return Text of the label
437 */
438 public String getText() {
439 if (text != null)
440 return text;
441 else {
442 TemplateEntryProperty property = getTextTemplate();
443 if (property.getUpdateCount() != textVersion) {
444 TemplateEntry templateEntry = property.get();
445 StringBuilder sb = new StringBuilder();
446 templateEntry.appendText(sb, this);
447
448 cachedText = sb.toString();
449 textVersion = property.getUpdateCount();
450 }
451 return cachedText;
452 }
453 }
454
455 @Override
456 public Collection<String> getTemplateKeys() {
457 Collection<String> result;
458 if (dataProvider != null) {
459 result = dataProvider.getTemplateKeys();
460 } else {
461 result = new ArrayList<>();
462 }
463 result.add(MARKER_FORMATTED_OFFSET);
464 result.add(MARKER_OFFSET);
465 return result;
466 }
467
468 private String formatOffset() {
469 int wholeSeconds = (int) (offset + 0.5);
470 if (wholeSeconds < 60)
471 return Integer.toString(wholeSeconds);
472 else if (wholeSeconds < 3600)
473 return String.format("%d:%02d", wholeSeconds / 60, wholeSeconds % 60);
474 else
475 return String.format("%d:%02d:%02d", wholeSeconds / 3600, (wholeSeconds % 3600)/60, wholeSeconds % 60);
476 }
477
478 @Override
479 public Object getTemplateValue(String name, boolean special) {
480 if (MARKER_FORMATTED_OFFSET.equals(name))
481 return formatOffset();
482 else if (MARKER_OFFSET.equals(name))
483 return offset;
484 else if (dataProvider != null)
485 return dataProvider.getTemplateValue(name, special);
486 else
487 return null;
488 }
489
490 @Override
491 public boolean evaluateCondition(Match condition) {
492 throw new UnsupportedOperationException();
493 }
494
495 /**
496 * Determines if this marker is erroneous.
497 * @return {@code true} if this markers has any kind of error, {@code false} otherwise
498 * @since 6299
499 */
500 public final boolean isErroneous() {
501 return erroneous;
502 }
503
504 /**
505 * Sets this marker erroneous or not.
506 * @param erroneous {@code true} if this markers has any kind of error, {@code false} otherwise
507 * @since 6299
508 */
509 public final void setErroneous(boolean erroneous) {
510 this.erroneous = erroneous;
511 if (!erroneous) {
512 redSymbol = null;
513 }
514 }
515}
Note: See TracBrowser for help on using the repository browser.