source: josm/trunk/src/org/openstreetmap/josm/gui/layer/markerlayer/MarkerLayer.java@ 12846

Last change on this file since 12846 was 12846, checked in by bastiK, 7 years ago

see #15229 - use Config.getPref() wherever possible

  • Property svn:eol-style set to native
File size: 20.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer.markerlayer;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.marktr;
6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
9import java.awt.Color;
10import java.awt.Component;
11import java.awt.Graphics2D;
12import java.awt.Point;
13import java.awt.event.ActionEvent;
14import java.awt.event.MouseAdapter;
15import java.awt.event.MouseEvent;
16import java.io.File;
17import java.net.URI;
18import java.net.URISyntaxException;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Comparator;
22import java.util.List;
23
24import javax.swing.AbstractAction;
25import javax.swing.Action;
26import javax.swing.Icon;
27import javax.swing.JCheckBoxMenuItem;
28import javax.swing.JOptionPane;
29
30import org.openstreetmap.josm.Main;
31import org.openstreetmap.josm.actions.RenameLayerAction;
32import org.openstreetmap.josm.data.Bounds;
33import org.openstreetmap.josm.data.coor.LatLon;
34import org.openstreetmap.josm.data.gpx.Extensions;
35import org.openstreetmap.josm.data.gpx.GpxConstants;
36import org.openstreetmap.josm.data.gpx.GpxData;
37import org.openstreetmap.josm.data.gpx.GpxLink;
38import org.openstreetmap.josm.data.gpx.WayPoint;
39import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
40import org.openstreetmap.josm.data.preferences.ColorProperty;
41import org.openstreetmap.josm.gui.MainApplication;
42import org.openstreetmap.josm.gui.MapView;
43import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
44import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
45import org.openstreetmap.josm.gui.layer.CustomizeColor;
46import org.openstreetmap.josm.gui.layer.GpxLayer;
47import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToMarkerLayer;
48import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToNextMarker;
49import org.openstreetmap.josm.gui.layer.JumpToMarkerActions.JumpToPreviousMarker;
50import org.openstreetmap.josm.gui.layer.Layer;
51import org.openstreetmap.josm.gui.layer.gpx.ConvertToDataLayerAction;
52import org.openstreetmap.josm.io.audio.AudioPlayer;
53import org.openstreetmap.josm.spi.preferences.Config;
54import org.openstreetmap.josm.tools.ImageProvider;
55import org.openstreetmap.josm.tools.Logging;
56import org.openstreetmap.josm.tools.Utils;
57
58/**
59 * A layer holding markers.
60 *
61 * Markers are GPS points with a name and, optionally, a symbol code attached;
62 * marker layers can be created from waypoints when importing raw GPS data,
63 * but they may also come from other sources.
64 *
65 * The symbol code is for future use.
66 *
67 * The data is read only.
68 */
69public class MarkerLayer extends Layer implements JumpToMarkerLayer {
70
71 /**
72 * A list of markers.
73 */
74 public final List<Marker> data;
75 private boolean mousePressed;
76 public GpxLayer fromLayer;
77 private Marker currentMarker;
78 public AudioMarker syncAudioMarker;
79
80 private static final Color DEFAULT_COLOR = Color.magenta;
81 private static final ColorProperty COLOR_PROPERTY = new ColorProperty(marktr("gps marker"), DEFAULT_COLOR);
82
83 /**
84 * Constructs a new {@code MarkerLayer}.
85 * @param indata The GPX data for this layer
86 * @param name The marker layer name
87 * @param associatedFile The associated GPX file
88 * @param fromLayer The associated GPX layer
89 */
90 public MarkerLayer(GpxData indata, String name, File associatedFile, GpxLayer fromLayer) {
91 super(name);
92 this.setAssociatedFile(associatedFile);
93 this.data = new ArrayList<>();
94 this.fromLayer = fromLayer;
95 double firstTime = -1.0;
96 String lastLinkedFile = "";
97
98 for (WayPoint wpt : indata.waypoints) {
99 /* calculate time differences in waypoints */
100 double time = wpt.time;
101 boolean wptHasLink = wpt.attr.containsKey(GpxConstants.META_LINKS);
102 if (firstTime < 0 && wptHasLink) {
103 firstTime = time;
104 for (GpxLink oneLink : wpt.<GpxLink>getCollection(GpxConstants.META_LINKS)) {
105 lastLinkedFile = oneLink.uri;
106 break;
107 }
108 }
109 if (wptHasLink) {
110 for (GpxLink oneLink : wpt.<GpxLink>getCollection(GpxConstants.META_LINKS)) {
111 String uri = oneLink.uri;
112 if (uri != null) {
113 if (!uri.equals(lastLinkedFile)) {
114 firstTime = time;
115 }
116 lastLinkedFile = uri;
117 break;
118 }
119 }
120 }
121 Double offset = null;
122 // If we have an explicit offset, take it.
123 // Otherwise, for a group of markers with the same Link-URI (e.g. an
124 // audio file) calculate the offset relative to the first marker of
125 // that group. This way the user can jump to the corresponding
126 // playback positions in a long audio track.
127 Extensions exts = (Extensions) wpt.get(GpxConstants.META_EXTENSIONS);
128 if (exts != null && exts.containsKey("offset")) {
129 try {
130 offset = Double.valueOf(exts.get("offset"));
131 } catch (NumberFormatException nfe) {
132 Logging.warn(nfe);
133 }
134 }
135 if (offset == null) {
136 offset = time - firstTime;
137 }
138 final Collection<Marker> markers = Marker.createMarkers(wpt, indata.storageFile, this, time, offset);
139 if (markers != null) {
140 data.addAll(markers);
141 }
142 }
143 }
144
145 @Override
146 public LayerPainter attachToMapView(MapViewEvent event) {
147 event.getMapView().addMouseListener(new MarkerMouseAdapter());
148
149 if (event.getMapView().playHeadMarker == null) {
150 event.getMapView().playHeadMarker = PlayHeadMarker.create();
151 }
152
153 return super.attachToMapView(event);
154 }
155
156 /**
157 * Return a static icon.
158 */
159 @Override
160 public Icon getIcon() {
161 return ImageProvider.get("layer", "marker_small");
162 }
163
164 @Override
165 protected ColorProperty getBaseColorProperty() {
166 return COLOR_PROPERTY;
167 }
168
169 /* for preferences */
170 public static Color getGenericColor() {
171 return COLOR_PROPERTY.get();
172 }
173
174 @Override
175 public void paint(Graphics2D g, MapView mv, Bounds box) {
176 boolean showTextOrIcon = isTextOrIconShown();
177 g.setColor(getColorProperty().get());
178
179 if (mousePressed) {
180 boolean mousePressedTmp = mousePressed;
181 Point mousePos = mv.getMousePosition(); // Get mouse position only when necessary (it's the slowest part of marker layer painting)
182 for (Marker mkr : data) {
183 if (mousePos != null && mkr.containsPoint(mousePos)) {
184 mkr.paint(g, mv, mousePressedTmp, showTextOrIcon);
185 mousePressedTmp = false;
186 }
187 }
188 } else {
189 for (Marker mkr : data) {
190 mkr.paint(g, mv, false, showTextOrIcon);
191 }
192 }
193 }
194
195 @Override
196 public String getToolTipText() {
197 return Integer.toString(data.size())+' '+trn("marker", "markers", data.size());
198 }
199
200 @Override
201 public void mergeFrom(Layer from) {
202 if (from instanceof MarkerLayer) {
203 data.addAll(((MarkerLayer) from).data);
204 data.sort(Comparator.comparingDouble(o -> o.time));
205 }
206 }
207
208 @Override public boolean isMergable(Layer other) {
209 return other instanceof MarkerLayer;
210 }
211
212 @Override public void visitBoundingBox(BoundingXYVisitor v) {
213 for (Marker mkr : data) {
214 v.visit(mkr);
215 }
216 }
217
218 @Override public Object getInfoComponent() {
219 return "<html>"+trn("{0} consists of {1} marker", "{0} consists of {1} markers",
220 data.size(), Utils.escapeReservedCharactersHTML(getName()), data.size()) + "</html>";
221 }
222
223 @Override public Action[] getMenuEntries() {
224 Collection<Action> components = new ArrayList<>();
225 components.add(LayerListDialog.getInstance().createShowHideLayerAction());
226 components.add(new ShowHideMarkerText(this));
227 components.add(LayerListDialog.getInstance().createDeleteLayerAction());
228 components.add(LayerListDialog.getInstance().createMergeLayerAction(this));
229 components.add(SeparatorLayerAction.INSTANCE);
230 components.add(new CustomizeColor(this));
231 components.add(SeparatorLayerAction.INSTANCE);
232 components.add(new SynchronizeAudio());
233 if (Config.getPref().getBoolean("marker.traceaudio", true)) {
234 components.add(new MoveAudio());
235 }
236 components.add(new JumpToNextMarker(this));
237 components.add(new JumpToPreviousMarker(this));
238 components.add(new ConvertToDataLayerAction.FromMarkerLayer(this));
239 components.add(new RenameLayerAction(getAssociatedFile(), this));
240 components.add(SeparatorLayerAction.INSTANCE);
241 components.add(new LayerListPopup.InfoAction(this));
242 return components.toArray(new Action[components.size()]);
243 }
244
245 public boolean synchronizeAudioMarkers(final AudioMarker startMarker) {
246 syncAudioMarker = startMarker;
247 if (syncAudioMarker != null && !data.contains(syncAudioMarker)) {
248 syncAudioMarker = null;
249 }
250 if (syncAudioMarker == null) {
251 // find the first audioMarker in this layer
252 for (Marker m : data) {
253 if (m instanceof AudioMarker) {
254 syncAudioMarker = (AudioMarker) m;
255 break;
256 }
257 }
258 }
259 if (syncAudioMarker == null)
260 return false;
261
262 // apply adjustment to all subsequent audio markers in the layer
263 double adjustment = AudioPlayer.position() - syncAudioMarker.offset; // in seconds
264 boolean seenStart = false;
265 try {
266 URI uri = syncAudioMarker.url().toURI();
267 for (Marker m : data) {
268 if (m == syncAudioMarker) {
269 seenStart = true;
270 }
271 if (seenStart && m instanceof AudioMarker) {
272 AudioMarker ma = (AudioMarker) m;
273 // Do not ever call URL.equals but use URI.equals instead to avoid Internet connection
274 // See http://michaelscharf.blogspot.fr/2006/11/javaneturlequals-and-hashcode-make.html for details
275 if (ma.url().toURI().equals(uri)) {
276 ma.adjustOffset(adjustment);
277 }
278 }
279 }
280 } catch (URISyntaxException e) {
281 Logging.warn(e);
282 }
283 return true;
284 }
285
286 public AudioMarker addAudioMarker(double time, LatLon coor) {
287 // find first audio marker to get absolute start time
288 double offset = 0.0;
289 AudioMarker am = null;
290 for (Marker m : data) {
291 if (m.getClass() == AudioMarker.class) {
292 am = (AudioMarker) m;
293 offset = time - am.time;
294 break;
295 }
296 }
297 if (am == null) {
298 JOptionPane.showMessageDialog(
299 Main.parent,
300 tr("No existing audio markers in this layer to offset from."),
301 tr("Error"),
302 JOptionPane.ERROR_MESSAGE
303 );
304 return null;
305 }
306
307 // make our new marker
308 AudioMarker newAudioMarker = new AudioMarker(coor,
309 null, AudioPlayer.url(), this, time, offset);
310
311 // insert it at the right place in a copy the collection
312 Collection<Marker> newData = new ArrayList<>();
313 am = null;
314 AudioMarker ret = newAudioMarker; // save to have return value
315 for (Marker m : data) {
316 if (m.getClass() == AudioMarker.class) {
317 am = (AudioMarker) m;
318 if (newAudioMarker != null && offset < am.offset) {
319 newAudioMarker.adjustOffset(am.syncOffset()); // i.e. same as predecessor
320 newData.add(newAudioMarker);
321 newAudioMarker = null;
322 }
323 }
324 newData.add(m);
325 }
326
327 if (newAudioMarker != null) {
328 if (am != null) {
329 newAudioMarker.adjustOffset(am.syncOffset()); // i.e. same as predecessor
330 }
331 newData.add(newAudioMarker); // insert at end
332 }
333
334 // replace the collection
335 data.clear();
336 data.addAll(newData);
337 return ret;
338 }
339
340 @Override
341 public void jumpToNextMarker() {
342 if (currentMarker == null) {
343 currentMarker = data.get(0);
344 } else {
345 boolean foundCurrent = false;
346 for (Marker m: data) {
347 if (foundCurrent) {
348 currentMarker = m;
349 break;
350 } else if (currentMarker == m) {
351 foundCurrent = true;
352 }
353 }
354 }
355 MainApplication.getMap().mapView.zoomTo(currentMarker);
356 }
357
358 @Override
359 public void jumpToPreviousMarker() {
360 if (currentMarker == null) {
361 currentMarker = data.get(data.size() - 1);
362 } else {
363 boolean foundCurrent = false;
364 for (int i = data.size() - 1; i >= 0; i--) {
365 Marker m = data.get(i);
366 if (foundCurrent) {
367 currentMarker = m;
368 break;
369 } else if (currentMarker == m) {
370 foundCurrent = true;
371 }
372 }
373 }
374 MainApplication.getMap().mapView.zoomTo(currentMarker);
375 }
376
377 public static void playAudio() {
378 playAdjacentMarker(null, true);
379 }
380
381 public static void playNextMarker() {
382 playAdjacentMarker(AudioMarker.recentlyPlayedMarker(), true);
383 }
384
385 public static void playPreviousMarker() {
386 playAdjacentMarker(AudioMarker.recentlyPlayedMarker(), false);
387 }
388
389 private static Marker getAdjacentMarker(Marker startMarker, boolean next, Layer layer) {
390 Marker previousMarker = null;
391 boolean nextTime = false;
392 if (layer.getClass() == MarkerLayer.class) {
393 MarkerLayer markerLayer = (MarkerLayer) layer;
394 for (Marker marker : markerLayer.data) {
395 if (marker == startMarker) {
396 if (next) {
397 nextTime = true;
398 } else {
399 if (previousMarker == null) {
400 previousMarker = startMarker; // if no previous one, play the first one again
401 }
402 return previousMarker;
403 }
404 } else if (marker.getClass() == AudioMarker.class) {
405 if (nextTime || startMarker == null)
406 return marker;
407 previousMarker = marker;
408 }
409 }
410 if (nextTime) // there was no next marker in that layer, so play the last one again
411 return startMarker;
412 }
413 return null;
414 }
415
416 private static void playAdjacentMarker(Marker startMarker, boolean next) {
417 if (!MainApplication.isDisplayingMapView())
418 return;
419 Marker m = null;
420 Layer l = MainApplication.getLayerManager().getActiveLayer();
421 if (l != null) {
422 m = getAdjacentMarker(startMarker, next, l);
423 }
424 if (m == null) {
425 for (Layer layer : MainApplication.getLayerManager().getLayers()) {
426 m = getAdjacentMarker(startMarker, next, layer);
427 if (m != null) {
428 break;
429 }
430 }
431 }
432 if (m != null) {
433 ((AudioMarker) m).play();
434 }
435 }
436
437 /**
438 * Get state of text display.
439 * @return <code>true</code> if text should be shown, <code>false</code> otherwise.
440 */
441 private boolean isTextOrIconShown() {
442 String current = Config.getPref().get("marker.show "+getName(), "show");
443 return "show".equalsIgnoreCase(current);
444 }
445
446 private final class MarkerMouseAdapter extends MouseAdapter {
447 @Override
448 public void mousePressed(MouseEvent e) {
449 if (e.getButton() != MouseEvent.BUTTON1)
450 return;
451 boolean mousePressedInButton = false;
452 for (Marker mkr : data) {
453 if (mkr.containsPoint(e.getPoint())) {
454 mousePressedInButton = true;
455 break;
456 }
457 }
458 if (!mousePressedInButton)
459 return;
460 mousePressed = true;
461 if (isVisible()) {
462 invalidate();
463 }
464 }
465
466 @Override
467 public void mouseReleased(MouseEvent ev) {
468 if (ev.getButton() != MouseEvent.BUTTON1 || !mousePressed)
469 return;
470 mousePressed = false;
471 if (!isVisible())
472 return;
473 for (Marker mkr : data) {
474 if (mkr.containsPoint(ev.getPoint())) {
475 mkr.actionPerformed(new ActionEvent(this, 0, null));
476 }
477 }
478 invalidate();
479 }
480 }
481
482 public static final class ShowHideMarkerText extends AbstractAction implements LayerAction {
483 private final transient MarkerLayer layer;
484
485 public ShowHideMarkerText(MarkerLayer layer) {
486 super(tr("Show Text/Icons"), ImageProvider.get("dialogs", "showhide"));
487 putValue(SHORT_DESCRIPTION, tr("Toggle visible state of the marker text and icons."));
488 putValue("help", ht("/Action/ShowHideTextIcons"));
489 this.layer = layer;
490 }
491
492 @Override
493 public void actionPerformed(ActionEvent e) {
494 Config.getPref().put("marker.show "+layer.getName(), layer.isTextOrIconShown() ? "hide" : "show");
495 layer.invalidate();
496 }
497
498 @Override
499 public Component createMenuComponent() {
500 JCheckBoxMenuItem showMarkerTextItem = new JCheckBoxMenuItem(this);
501 showMarkerTextItem.setState(layer.isTextOrIconShown());
502 return showMarkerTextItem;
503 }
504
505 @Override
506 public boolean supportLayers(List<Layer> layers) {
507 return layers.size() == 1 && layers.get(0) instanceof MarkerLayer;
508 }
509 }
510
511 private class SynchronizeAudio extends AbstractAction {
512
513 /**
514 * Constructs a new {@code SynchronizeAudio} action.
515 */
516 SynchronizeAudio() {
517 super(tr("Synchronize Audio"), ImageProvider.get("audio-sync"));
518 putValue("help", ht("/Action/SynchronizeAudio"));
519 }
520
521 @Override
522 public void actionPerformed(ActionEvent e) {
523 if (!AudioPlayer.paused()) {
524 JOptionPane.showMessageDialog(
525 Main.parent,
526 tr("You need to pause audio at the moment when you hear your synchronization cue."),
527 tr("Warning"),
528 JOptionPane.WARNING_MESSAGE
529 );
530 return;
531 }
532 AudioMarker recent = AudioMarker.recentlyPlayedMarker();
533 if (synchronizeAudioMarkers(recent)) {
534 JOptionPane.showMessageDialog(
535 Main.parent,
536 tr("Audio synchronized at point {0}.", syncAudioMarker.getText()),
537 tr("Information"),
538 JOptionPane.INFORMATION_MESSAGE
539 );
540 } else {
541 JOptionPane.showMessageDialog(
542 Main.parent,
543 tr("Unable to synchronize in layer being played."),
544 tr("Error"),
545 JOptionPane.ERROR_MESSAGE
546 );
547 }
548 }
549 }
550
551 private class MoveAudio extends AbstractAction {
552
553 MoveAudio() {
554 super(tr("Make Audio Marker at Play Head"), ImageProvider.get("addmarkers"));
555 putValue("help", ht("/Action/MakeAudioMarkerAtPlayHead"));
556 }
557
558 @Override
559 public void actionPerformed(ActionEvent e) {
560 if (!AudioPlayer.paused()) {
561 JOptionPane.showMessageDialog(
562 Main.parent,
563 tr("You need to have paused audio at the point on the track where you want the marker."),
564 tr("Warning"),
565 JOptionPane.WARNING_MESSAGE
566 );
567 return;
568 }
569 PlayHeadMarker playHeadMarker = MainApplication.getMap().mapView.playHeadMarker;
570 if (playHeadMarker == null)
571 return;
572 addAudioMarker(playHeadMarker.time, playHeadMarker.getCoor());
573 invalidate();
574 }
575 }
576}
Note: See TracBrowser for help on using the repository browser.