source: josm/trunk/src/org/openstreetmap/josm/gui/MapStatus.java@ 12968

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

see #15229 - move remaining classes to spi.preferences package, to make it self-contained

  • extract event listener classes from Preferences (duplicated, for smooth transition)
  • move *Setting classes
  • Property svn:eol-style set to native
File size: 45.4 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
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;
7
8import java.awt.AWTEvent;
9import java.awt.Color;
10import java.awt.Component;
11import java.awt.Cursor;
12import java.awt.Dimension;
13import java.awt.EventQueue;
14import java.awt.Font;
15import java.awt.GridBagLayout;
16import java.awt.Point;
17import java.awt.SystemColor;
18import java.awt.Toolkit;
19import java.awt.event.AWTEventListener;
20import java.awt.event.ActionEvent;
21import java.awt.event.ComponentAdapter;
22import java.awt.event.ComponentEvent;
23import java.awt.event.InputEvent;
24import java.awt.event.KeyAdapter;
25import java.awt.event.KeyEvent;
26import java.awt.event.MouseAdapter;
27import java.awt.event.MouseEvent;
28import java.awt.event.MouseListener;
29import java.awt.event.MouseMotionListener;
30import java.lang.reflect.InvocationTargetException;
31import java.text.DecimalFormat;
32import java.util.ArrayList;
33import java.util.Collection;
34import java.util.ConcurrentModificationException;
35import java.util.List;
36import java.util.Objects;
37import java.util.TreeSet;
38import java.util.concurrent.BlockingQueue;
39import java.util.concurrent.LinkedBlockingQueue;
40
41import javax.swing.AbstractAction;
42import javax.swing.BorderFactory;
43import javax.swing.JCheckBoxMenuItem;
44import javax.swing.JLabel;
45import javax.swing.JMenuItem;
46import javax.swing.JPanel;
47import javax.swing.JPopupMenu;
48import javax.swing.JProgressBar;
49import javax.swing.JScrollPane;
50import javax.swing.JSeparator;
51import javax.swing.Popup;
52import javax.swing.PopupFactory;
53import javax.swing.UIManager;
54import javax.swing.event.PopupMenuEvent;
55import javax.swing.event.PopupMenuListener;
56
57import org.openstreetmap.josm.Main;
58import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
59import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
60import org.openstreetmap.josm.data.SystemOfMeasurement;
61import org.openstreetmap.josm.data.SystemOfMeasurement.SoMChangeListener;
62import org.openstreetmap.josm.data.coor.LatLon;
63import org.openstreetmap.josm.data.coor.conversion.CoordinateFormatManager;
64import org.openstreetmap.josm.data.coor.conversion.DMSCoordinateFormat;
65import org.openstreetmap.josm.data.coor.conversion.ICoordinateFormat;
66import org.openstreetmap.josm.data.coor.conversion.ProjectedCoordinateFormat;
67import org.openstreetmap.josm.data.osm.DataSet;
68import org.openstreetmap.josm.data.osm.DefaultNameFormatter;
69import org.openstreetmap.josm.data.osm.OsmPrimitive;
70import org.openstreetmap.josm.data.osm.Way;
71import org.openstreetmap.josm.data.preferences.AbstractProperty;
72import org.openstreetmap.josm.data.preferences.BooleanProperty;
73import org.openstreetmap.josm.data.preferences.ColorProperty;
74import org.openstreetmap.josm.data.preferences.DoubleProperty;
75import org.openstreetmap.josm.gui.help.Helpful;
76import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
77import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor.ProgressMonitorDialog;
78import org.openstreetmap.josm.gui.util.GuiHelper;
79import org.openstreetmap.josm.gui.widgets.ImageLabel;
80import org.openstreetmap.josm.gui.widgets.JosmTextField;
81import org.openstreetmap.josm.spi.preferences.Config;
82import org.openstreetmap.josm.tools.Destroyable;
83import org.openstreetmap.josm.tools.GBC;
84import org.openstreetmap.josm.tools.ImageProvider;
85import org.openstreetmap.josm.tools.Logging;
86import org.openstreetmap.josm.tools.Utils;
87
88/**
89 * A component that manages some status information display about the map.
90 * It keeps a status line below the map up to date and displays some tooltip
91 * information if the user hold the mouse long enough at some point.
92 *
93 * All this is done in background to not disturb other processes.
94 *
95 * The background thread does not alter any data of the map (read only thread).
96 * Also it is rather fail safe. In case of some error in the data, it just does
97 * nothing instead of whining and complaining.
98 *
99 * @author imi
100 */
101public final class MapStatus extends JPanel implements Helpful, Destroyable, PreferenceChangedListener, SoMChangeListener {
102
103 private final DecimalFormat DECIMAL_FORMAT = new DecimalFormat(Config.getPref().get("statusbar.decimal-format", "0.0"));
104 private static final AbstractProperty<Double> DISTANCE_THRESHOLD = new DoubleProperty("statusbar.distance-threshold", 0.01).cached();
105
106 private static final AbstractProperty<Boolean> SHOW_ID = new BooleanProperty("osm-primitives.showid", false);
107
108 /**
109 * Property for map status background color.
110 * @since 6789
111 */
112 public static final ColorProperty PROP_BACKGROUND_COLOR = new ColorProperty(
113 marktr("Status bar background"), "#b8cfe5");
114
115 /**
116 * Property for map status background color (active state).
117 * @since 6789
118 */
119 public static final ColorProperty PROP_ACTIVE_BACKGROUND_COLOR = new ColorProperty(
120 marktr("Status bar background: active"), "#aaff5e");
121
122 /**
123 * Property for map status foreground color.
124 * @since 6789
125 */
126 public static final ColorProperty PROP_FOREGROUND_COLOR = new ColorProperty(
127 marktr("Status bar foreground"), Color.black);
128
129 /**
130 * Property for map status foreground color (active state).
131 * @since 6789
132 */
133 public static final ColorProperty PROP_ACTIVE_FOREGROUND_COLOR = new ColorProperty(
134 marktr("Status bar foreground: active"), Color.black);
135
136 /**
137 * The MapView this status belongs to.
138 */
139 private final MapView mv;
140 private final transient Collector collector;
141
142 static final class ShowMonitorDialogMouseAdapter extends MouseAdapter {
143 @Override
144 public void mouseClicked(MouseEvent e) {
145 PleaseWaitProgressMonitor monitor = PleaseWaitProgressMonitor.getCurrent();
146 if (monitor != null) {
147 monitor.showForegroundDialog();
148 }
149 }
150 }
151
152 static final class JumpToOnLeftClickMouseAdapter extends MouseAdapter {
153 @Override
154 public void mouseClicked(MouseEvent e) {
155 if (e.getButton() != MouseEvent.BUTTON3) {
156 MainApplication.getMenu().jumpToAct.showJumpToDialog();
157 }
158 }
159 }
160
161 /**
162 * The progress monitor that is used to display the progress if the user selects to run in background
163 */
164 public class BackgroundProgressMonitor implements ProgressMonitorDialog {
165
166 private String title;
167 private String customText;
168
169 private void updateText() {
170 if (customText != null && !customText.isEmpty()) {
171 progressBar.setToolTipText(tr("{0} ({1})", title, customText));
172 } else {
173 progressBar.setToolTipText(title);
174 }
175 }
176
177 @Override
178 public void setVisible(boolean visible) {
179 progressBar.setVisible(visible);
180 }
181
182 @Override
183 public void updateProgress(int progress) {
184 progressBar.setValue(progress);
185 progressBar.repaint();
186 MapStatus.this.doLayout();
187 }
188
189 @Override
190 public void setCustomText(String text) {
191 this.customText = text;
192 updateText();
193 }
194
195 @Override
196 public void setCurrentAction(String text) {
197 this.title = text;
198 updateText();
199 }
200
201 @Override
202 public void setIndeterminate(boolean newValue) {
203 UIManager.put("ProgressBar.cycleTime", UIManager.getInt("ProgressBar.repaintInterval") * 100);
204 progressBar.setIndeterminate(newValue);
205 }
206
207 @Override
208 public void appendLogMessage(String message) {
209 if (message != null && !message.isEmpty()) {
210 Logging.info("appendLogMessage not implemented for background tasks. Message was: " + message);
211 }
212 }
213
214 }
215
216 /** The {@link ICoordinateFormat} set in the previous update */
217 private transient ICoordinateFormat previousCoordinateFormat;
218 private final ImageLabel latText = new ImageLabel("lat",
219 null, DMSCoordinateFormat.INSTANCE.latToString(LatLon.SOUTH_POLE).length(), PROP_BACKGROUND_COLOR.get());
220 private final ImageLabel lonText = new ImageLabel("lon",
221 null, DMSCoordinateFormat.INSTANCE.lonToString(new LatLon(0, 180)).length(), PROP_BACKGROUND_COLOR.get());
222 private final ImageLabel headingText = new ImageLabel("heading",
223 tr("The (compass) heading of the line segment being drawn."),
224 DECIMAL_FORMAT.format(360).length() + 1, PROP_BACKGROUND_COLOR.get());
225 private final ImageLabel angleText = new ImageLabel("angle",
226 tr("The angle between the previous and the current way segment."),
227 DECIMAL_FORMAT.format(360).length() + 1, PROP_BACKGROUND_COLOR.get());
228 private final ImageLabel distText = new ImageLabel("dist",
229 tr("The length of the new way segment being drawn."), 10, PROP_BACKGROUND_COLOR.get());
230 private final ImageLabel nameText = new ImageLabel("name",
231 tr("The name of the object at the mouse pointer."), getNameLabelCharacterCount(Main.parent), PROP_BACKGROUND_COLOR.get());
232 private final JosmTextField helpText = new JosmTextField();
233 private final JProgressBar progressBar = new JProgressBar();
234 private final transient ComponentAdapter mvComponentAdapter;
235 /**
236 * The progress monitor for displaying a background progress
237 */
238 public final transient BackgroundProgressMonitor progressMonitor = new BackgroundProgressMonitor();
239
240 // Distance value displayed in distText, stored if refresh needed after a change of system of measurement
241 private double distValue;
242
243 // Determines if angle panel is enabled or not
244 private boolean angleEnabled;
245
246 /**
247 * This is the thread that runs in the background and collects the information displayed.
248 * It gets destroyed by destroy() when the MapFrame itself is destroyed.
249 */
250 private final transient Thread thread;
251
252 private final transient List<StatusTextHistory> statusText = new ArrayList<>();
253
254 protected static final class StatusTextHistory {
255 private final Object id;
256 private final String text;
257
258 StatusTextHistory(Object id, String text) {
259 this.id = id;
260 this.text = text;
261 }
262
263 @Override
264 public boolean equals(Object obj) {
265 return obj instanceof StatusTextHistory && ((StatusTextHistory) obj).id == id;
266 }
267
268 @Override
269 public int hashCode() {
270 return System.identityHashCode(id);
271 }
272 }
273
274 /**
275 * The collector class that waits for notification and then update the display objects.
276 *
277 * @author imi
278 */
279 private final class Collector implements Runnable {
280 private final class CollectorWorker implements Runnable {
281 private final MouseState ms;
282
283 private CollectorWorker(MouseState ms) {
284 this.ms = ms;
285 }
286
287 @Override
288 public void run() {
289 // Freeze display when holding down CTRL
290 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) {
291 // update the information popup's labels though, because the selection might have changed from the outside
292 popupUpdateLabels();
293 return;
294 }
295
296 // This try/catch is a hack to stop the flooding bug reports about this.
297 // The exception needed to handle with in the first place, means that this
298 // access to the data need to be restarted, if the main thread modifies the data.
299 DataSet ds = null;
300 // The popup != null check is required because a left-click produces several events as well,
301 // which would make this variable true. Of course we only want the popup to show
302 // if the middle mouse button has been pressed in the first place
303 boolean mouseNotMoved = oldMousePos != null && oldMousePos.equals(ms.mousePos);
304 boolean isAtOldPosition = mouseNotMoved && popup != null;
305 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0;
306
307 ds = mv.getLayerManager().getEditDataSet();
308 if (ds != null) {
309 // This is not perfect, if current dataset was changed during execution, the lock would be useless
310 if (isAtOldPosition && middleMouseDown) {
311 // Write lock is necessary when selecting in popupCycleSelection
312 // locks can not be upgraded -> if do read lock here and write lock later
313 // (in OsmPrimitive.updateFlags) then always occurs deadlock (#5814)
314 ds.beginUpdate();
315 } else {
316 ds.getReadLock().lock();
317 }
318 }
319 try {
320 // Set the text label in the bottom status bar
321 // "if mouse moved only" was added to stop heap growing
322 if (!mouseNotMoved) {
323 statusBarElementUpdate(ms);
324 }
325
326 // Popup Information
327 // display them if the middle mouse button is pressed and keep them until the mouse is moved
328 if (middleMouseDown || isAtOldPosition) {
329 Collection<OsmPrimitive> osms = mv.getAllNearest(ms.mousePos, OsmPrimitive::isSelectable);
330
331 final JPanel c = new JPanel(new GridBagLayout());
332 final JLabel lbl = new JLabel(
333 "<html>"+tr("Middle click again to cycle through.<br>"+
334 "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>",
335 null,
336 JLabel.HORIZONTAL
337 );
338 lbl.setHorizontalAlignment(JLabel.LEFT);
339 c.add(lbl, GBC.eol().insets(2, 0, 2, 0));
340
341 // Only cycle if the mouse has not been moved and the middle mouse button has been pressed at least
342 // twice (the reason for this is the popup != null check for isAtOldPosition, see above.
343 // This is a nice side effect though, because it does not change selection of the first middle click)
344 if (isAtOldPosition && middleMouseDown) {
345 // Hand down mouse modifiers so the SHIFT mod can be handled correctly (see function)
346 popupCycleSelection(osms, ms.modifiers);
347 }
348
349 // These labels may need to be updated from the outside so collect them
350 List<JLabel> lbls = new ArrayList<>(osms.size());
351 for (final OsmPrimitive osm : osms) {
352 JLabel l = popupBuildPrimitiveLabels(osm);
353 lbls.add(l);
354 c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2));
355 }
356
357 popupShowPopup(popupCreatePopup(c, ms), lbls);
358 } else {
359 popupHidePopup();
360 }
361
362 oldMousePos = ms.mousePos;
363 } catch (ConcurrentModificationException ex) {
364 Logging.warn(ex);
365 } finally {
366 if (ds != null) {
367 if (isAtOldPosition && middleMouseDown) {
368 ds.endUpdate();
369 } else {
370 ds.getReadLock().unlock();
371 }
372 }
373 }
374 }
375 }
376
377 /**
378 * the mouse position of the previous iteration. This is used to show
379 * the popup until the cursor is moved.
380 */
381 private Point oldMousePos;
382 /**
383 * Contains the labels that are currently shown in the information
384 * popup
385 */
386 private List<JLabel> popupLabels;
387 /**
388 * The popup displayed to show additional information
389 */
390 private Popup popup;
391
392 private final MapFrame parent;
393
394 private final BlockingQueue<MouseState> incomingMouseState = new LinkedBlockingQueue<>();
395
396 private Point lastMousePos;
397
398 Collector(MapFrame parent) {
399 this.parent = parent;
400 }
401
402 /**
403 * Execution function for the Collector.
404 */
405 @Override
406 public void run() {
407 registerListeners();
408 try {
409 for (;;) {
410 try {
411 final MouseState ms = incomingMouseState.take();
412 if (parent != MainApplication.getMap())
413 return; // exit, if new parent.
414
415 // Do nothing, if required data is missing
416 if (ms.mousePos == null || mv.getCenter() == null) {
417 continue;
418 }
419
420 EventQueue.invokeAndWait(new CollectorWorker(ms));
421 } catch (InvocationTargetException e) {
422 Logging.warn(e);
423 }
424 }
425 } catch (InterruptedException e) {
426 // Occurs frequently during JOSM shutdown, log set to trace only
427 Logging.trace("InterruptedException in "+MapStatus.class.getSimpleName());
428 Thread.currentThread().interrupt();
429 } finally {
430 unregisterListeners();
431 }
432 }
433
434 /**
435 * Creates a popup for the given content next to the cursor. Tries to
436 * keep the popup on screen and shows a vertical scrollbar, if the
437 * screen is too small.
438 * @param content popup content
439 * @param ms mouse state
440 * @return popup
441 */
442 private Popup popupCreatePopup(Component content, MouseState ms) {
443 Point p = mv.getLocationOnScreen();
444 Dimension scrn = GuiHelper.getScreenSize();
445
446 // Create a JScrollPane around the content, in case there's not enough space
447 JScrollPane sp = GuiHelper.embedInVerticalScrollPane(content);
448 sp.setBorder(BorderFactory.createRaisedBevelBorder());
449 // Implement max-size content-independent
450 Dimension prefsize = sp.getPreferredSize();
451 int w = Math.min(prefsize.width, Math.min(800, (scrn.width/2) - 16));
452 int h = Math.min(prefsize.height, scrn.height - 10);
453 sp.setPreferredSize(new Dimension(w, h));
454
455 int xPos = p.x + ms.mousePos.x + 16;
456 // Display the popup to the left of the cursor if it would be cut
457 // off on its right, but only if more space is available
458 if (xPos + w > scrn.width && xPos > scrn.width/2) {
459 xPos = p.x + ms.mousePos.x - 4 - w;
460 }
461 int yPos = p.y + ms.mousePos.y + 16;
462 // Move the popup up if it would be cut off at its bottom but do not
463 // move it off screen on the top
464 if (yPos + h > scrn.height - 5) {
465 yPos = Math.max(5, scrn.height - h - 5);
466 }
467
468 PopupFactory pf = PopupFactory.getSharedInstance();
469 return pf.getPopup(mv, sp, xPos, yPos);
470 }
471
472 /**
473 * Calls this to update the element that is shown in the statusbar
474 * @param ms mouse state
475 */
476 private void statusBarElementUpdate(MouseState ms) {
477 final OsmPrimitive osmNearest = mv.getNearestNodeOrWay(ms.mousePos, OsmPrimitive::isUsable, false);
478 if (osmNearest != null) {
479 nameText.setText(osmNearest.getDisplayName(DefaultNameFormatter.getInstance()));
480 } else {
481 nameText.setText(tr("(no object)"));
482 }
483 }
484
485 /**
486 * Call this with a set of primitives to cycle through them. Method
487 * will automatically select the next item and update the map
488 * @param osms primitives to cycle through
489 * @param mods modifiers (i.e. control keys)
490 */
491 private void popupCycleSelection(Collection<OsmPrimitive> osms, int mods) {
492 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
493 // Find some items that are required for cycling through
494 OsmPrimitive firstItem = null;
495 OsmPrimitive firstSelected = null;
496 OsmPrimitive nextSelected = null;
497 for (final OsmPrimitive osm : osms) {
498 if (firstItem == null) {
499 firstItem = osm;
500 }
501 if (firstSelected != null && nextSelected == null) {
502 nextSelected = osm;
503 }
504 if (firstSelected == null && ds.isSelected(osm)) {
505 firstSelected = osm;
506 }
507 }
508
509 // Clear previous selection if SHIFT (add to selection) is not
510 // pressed. Cannot use "setSelected()" because it will cause a
511 // fireSelectionChanged event which is unnecessary at this point.
512 if ((mods & MouseEvent.SHIFT_DOWN_MASK) == 0) {
513 ds.clearSelection();
514 }
515
516 // This will cycle through the available items.
517 if (firstSelected != null) {
518 ds.clearSelection(firstSelected);
519 if (nextSelected != null) {
520 ds.addSelected(nextSelected);
521 }
522 } else if (firstItem != null) {
523 ds.addSelected(firstItem);
524 }
525 }
526
527 /**
528 * Tries to hide the given popup
529 */
530 private void popupHidePopup() {
531 popupLabels = null;
532 if (popup == null)
533 return;
534 final Popup staticPopup = popup;
535 popup = null;
536 EventQueue.invokeLater(staticPopup::hide);
537 }
538
539 /**
540 * Tries to show the given popup, can be hidden using {@link #popupHidePopup}
541 * If an old popup exists, it will be automatically hidden
542 * @param newPopup popup to show
543 * @param lbls lables to show (see {@link #popupLabels})
544 */
545 private void popupShowPopup(Popup newPopup, List<JLabel> lbls) {
546 final Popup staticPopup = newPopup;
547 if (this.popup != null) {
548 // If an old popup exists, remove it when the new popup has been drawn to keep flickering to a minimum
549 final Popup staticOldPopup = this.popup;
550 EventQueue.invokeLater(() -> {
551 staticPopup.show();
552 staticOldPopup.hide();
553 });
554 } else {
555 // There is no old popup
556 EventQueue.invokeLater(staticPopup::show);
557 }
558 this.popupLabels = lbls;
559 this.popup = newPopup;
560 }
561
562 /**
563 * This method should be called if the selection may have changed from
564 * outside of this class. This is the case when CTRL is pressed and the
565 * user clicks on the map instead of the popup.
566 */
567 private void popupUpdateLabels() {
568 if (this.popup == null || this.popupLabels == null)
569 return;
570 for (JLabel l : this.popupLabels) {
571 l.validate();
572 }
573 }
574
575 /**
576 * Sets the colors for the given label depending on the selected status of
577 * the given OsmPrimitive
578 *
579 * @param lbl The label to color
580 * @param osm The primitive to derive the colors from
581 */
582 private void popupSetLabelColors(JLabel lbl, OsmPrimitive osm) {
583 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
584 if (ds.isSelected(osm)) {
585 lbl.setBackground(SystemColor.textHighlight);
586 lbl.setForeground(SystemColor.textHighlightText);
587 } else {
588 lbl.setBackground(SystemColor.control);
589 lbl.setForeground(SystemColor.controlText);
590 }
591 }
592
593 /**
594 * Builds the labels with all necessary listeners for the info popup for the
595 * given OsmPrimitive
596 * @param osm The primitive to create the label for
597 * @return labels for info popup
598 */
599 private JLabel popupBuildPrimitiveLabels(final OsmPrimitive osm) {
600 final StringBuilder text = new StringBuilder(32);
601 String name = Utils.escapeReservedCharactersHTML(osm.getDisplayName(DefaultNameFormatter.getInstance()));
602 if (osm.isNewOrUndeleted() || osm.isModified()) {
603 name = "<i><b>"+ name + "*</b></i>";
604 }
605 text.append(name);
606
607 boolean idShown = SHOW_ID.get();
608 // fix #7557 - do not show ID twice
609
610 if (!osm.isNew() && !idShown) {
611 text.append(" [id=").append(osm.getId()).append(']');
612 }
613
614 if (osm.getUser() != null) {
615 text.append(" [").append(tr("User:")).append(' ')
616 .append(Utils.escapeReservedCharactersHTML(osm.getUser().getName())).append(']');
617 }
618
619 for (String key : osm.keySet()) {
620 text.append("<br>").append(key).append('=').append(osm.get(key));
621 }
622
623 final JLabel l = new JLabel(
624 "<html>" + text.toString() + "</html>",
625 ImageProvider.get(osm.getDisplayType()),
626 JLabel.HORIZONTAL
627 ) {
628 // This is necessary so the label updates its colors when the
629 // selection is changed from the outside
630 @Override
631 public void validate() {
632 super.validate();
633 popupSetLabelColors(this, osm);
634 }
635 };
636 l.setOpaque(true);
637 popupSetLabelColors(l, osm);
638 l.setFont(l.getFont().deriveFont(Font.PLAIN));
639 l.setVerticalTextPosition(JLabel.TOP);
640 l.setHorizontalAlignment(JLabel.LEFT);
641 l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
642 l.addMouseListener(new MouseAdapter() {
643 @Override
644 public void mouseEntered(MouseEvent e) {
645 l.setBackground(SystemColor.info);
646 l.setForeground(SystemColor.infoText);
647 }
648
649 @Override
650 public void mouseExited(MouseEvent e) {
651 popupSetLabelColors(l, osm);
652 }
653
654 @Override
655 public void mouseClicked(MouseEvent e) {
656 DataSet ds = MainApplication.getLayerManager().getEditDataSet();
657 // Let the user toggle the selection
658 ds.toggleSelected(osm);
659 l.validate();
660 }
661 });
662 // Sometimes the mouseEntered event is not catched, thus the label
663 // will not be highlighted, making it confusing. The MotionListener can correct this defect.
664 l.addMouseMotionListener(new MouseMotionListener() {
665 @Override
666 public void mouseMoved(MouseEvent e) {
667 l.setBackground(SystemColor.info);
668 l.setForeground(SystemColor.infoText);
669 }
670
671 @Override
672 public void mouseDragged(MouseEvent e) {
673 mouseMoved(e);
674 }
675 });
676 return l;
677 }
678
679 /**
680 * Called whenever the mouse position or modifiers changed.
681 * @param mousePos The new mouse position. <code>null</code> if it did not change.
682 * @param modifiers The new modifiers.
683 */
684 public synchronized void updateMousePosition(Point mousePos, int modifiers) {
685 if (mousePos != null) {
686 lastMousePos = mousePos;
687 }
688 MouseState ms = new MouseState(lastMousePos, modifiers);
689 // remove mouse states that are in the queue. Our mouse state is newer.
690 incomingMouseState.clear();
691 if (!incomingMouseState.offer(ms)) {
692 Logging.warn("Unable to handle new MouseState: " + ms);
693 }
694 }
695 }
696
697 /**
698 * Everything, the collector is interested of. Access must be synchronized.
699 * @author imi
700 */
701 private static class MouseState {
702 private final Point mousePos;
703 private final int modifiers;
704
705 MouseState(Point mousePos, int modifiers) {
706 this.mousePos = mousePos;
707 this.modifiers = modifiers;
708 }
709 }
710
711 private final transient AWTEventListener awtListener;
712
713 private final transient MouseMotionListener mouseMotionListener = new MouseMotionListener() {
714 @Override
715 public void mouseMoved(MouseEvent e) {
716 synchronized (collector) {
717 collector.updateMousePosition(e.getPoint(), e.getModifiersEx());
718 }
719 }
720
721 @Override
722 public void mouseDragged(MouseEvent e) {
723 mouseMoved(e);
724 }
725 };
726
727 private final transient KeyAdapter keyAdapter = new KeyAdapter() {
728 @Override public void keyPressed(KeyEvent e) {
729 synchronized (collector) {
730 collector.updateMousePosition(null, e.getModifiersEx());
731 }
732 }
733
734 @Override public void keyReleased(KeyEvent e) {
735 keyPressed(e);
736 }
737 };
738
739 private void registerListeners() {
740 // Listen to keyboard/mouse events for pressing/releasing alt key and inform the collector.
741 try {
742 Toolkit.getDefaultToolkit().addAWTEventListener(awtListener,
743 AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
744 } catch (SecurityException ex) {
745 Logging.trace(ex);
746 mv.addMouseMotionListener(mouseMotionListener);
747 mv.addKeyListener(keyAdapter);
748 }
749 }
750
751 private void unregisterListeners() {
752 try {
753 Toolkit.getDefaultToolkit().removeAWTEventListener(awtListener);
754 } catch (SecurityException e) {
755 // Don't care, awtListener probably wasn't registered anyway
756 Logging.trace(e);
757 }
758 mv.removeMouseMotionListener(mouseMotionListener);
759 mv.removeKeyListener(keyAdapter);
760 }
761
762 private class MapStatusPopupMenu extends JPopupMenu {
763
764 private final JMenuItem jumpButton = add(MainApplication.getMenu().jumpToAct);
765
766 /** Icons for selecting {@link SystemOfMeasurement} */
767 private final Collection<JCheckBoxMenuItem> somItems = new ArrayList<>();
768 /** Icons for selecting {@link ICoordinateFormat} */
769 private final Collection<JCheckBoxMenuItem> coordinateFormatItems = new ArrayList<>();
770
771 private final JSeparator separator = new JSeparator();
772
773 private final JMenuItem doNotHide = new JCheckBoxMenuItem(new AbstractAction(tr("Do not hide status bar")) {
774 @Override
775 public void actionPerformed(ActionEvent e) {
776 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
777 Config.getPref().putBoolean("statusbar.always-visible", sel);
778 }
779 });
780
781 MapStatusPopupMenu() {
782 for (final String key : new TreeSet<>(SystemOfMeasurement.ALL_SYSTEMS.keySet())) {
783 JCheckBoxMenuItem item = new JCheckBoxMenuItem(new AbstractAction(key) {
784 @Override
785 public void actionPerformed(ActionEvent e) {
786 updateSystemOfMeasurement(key);
787 }
788 });
789 somItems.add(item);
790 add(item);
791 }
792 for (final ICoordinateFormat format : CoordinateFormatManager.getCoordinateFormats()) {
793 JCheckBoxMenuItem item = new JCheckBoxMenuItem(new AbstractAction(format.getDisplayName()) {
794 @Override
795 public void actionPerformed(ActionEvent e) {
796 CoordinateFormatManager.setCoordinateFormat(format);
797 }
798 });
799 coordinateFormatItems.add(item);
800 add(item);
801 }
802
803 add(separator);
804 add(doNotHide);
805
806 addPopupMenuListener(new PopupMenuListener() {
807 @Override
808 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
809 Component invoker = ((JPopupMenu) e.getSource()).getInvoker();
810 jumpButton.setVisible(latText.equals(invoker) || lonText.equals(invoker));
811 String currentSOM = SystemOfMeasurement.PROP_SYSTEM_OF_MEASUREMENT.get();
812 for (JMenuItem item : somItems) {
813 item.setSelected(item.getText().equals(currentSOM));
814 item.setVisible(distText.equals(invoker));
815 }
816 final String currentCorrdinateFormat = CoordinateFormatManager.getDefaultFormat().getDisplayName();
817 for (JMenuItem item : coordinateFormatItems) {
818 item.setSelected(currentCorrdinateFormat.equals(item.getText()));
819 item.setVisible(latText.equals(invoker) || lonText.equals(invoker));
820 }
821 separator.setVisible(distText.equals(invoker) || latText.equals(invoker) || lonText.equals(invoker));
822 doNotHide.setSelected(Config.getPref().getBoolean("statusbar.always-visible", true));
823 }
824
825 @Override
826 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
827 // Do nothing
828 }
829
830 @Override
831 public void popupMenuCanceled(PopupMenuEvent e) {
832 // Do nothing
833 }
834 });
835 }
836 }
837
838 /**
839 * Construct a new MapStatus and attach it to the map view.
840 * @param mapFrame The MapFrame the status line is part of.
841 */
842 public MapStatus(final MapFrame mapFrame) {
843 this.mv = mapFrame.mapView;
844 this.collector = new Collector(mapFrame);
845 this.awtListener = event -> {
846 if (event instanceof InputEvent &&
847 ((InputEvent) event).getComponent() == mv) {
848 synchronized (collector) {
849 int modifiers = ((InputEvent) event).getModifiersEx();
850 Point mousePos = null;
851 if (event instanceof MouseEvent) {
852 mousePos = ((MouseEvent) event).getPoint();
853 }
854 collector.updateMousePosition(mousePos, modifiers);
855 }
856 }
857 };
858
859 // Context menu of status bar
860 setComponentPopupMenu(new MapStatusPopupMenu());
861
862 // also show Jump To dialog on mouse click (except context menu)
863 MouseListener jumpToOnLeftClick = new JumpToOnLeftClickMouseAdapter();
864
865 // Listen for mouse movements and set the position text field
866 mv.addMouseMotionListener(new MouseMotionListener() {
867 @Override
868 public void mouseDragged(MouseEvent e) {
869 mouseMoved(e);
870 }
871
872 @Override
873 public void mouseMoved(MouseEvent e) {
874 if (mv.getCenter() == null)
875 return;
876 // Do not update the view if ctrl is pressed.
877 if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0) {
878 ICoordinateFormat mCord = CoordinateFormatManager.getDefaultFormat();
879 LatLon p = mv.getLatLon(e.getX(), e.getY());
880 latText.setText(mCord.latToString(p));
881 lonText.setText(mCord.lonToString(p));
882 if (Objects.equals(previousCoordinateFormat, mCord)) {
883 // do nothing
884 } else if (ProjectedCoordinateFormat.INSTANCE.equals(mCord)) {
885 latText.setIcon("northing");
886 lonText.setIcon("easting");
887 latText.setToolTipText(tr("The northing at the mouse pointer."));
888 lonText.setToolTipText(tr("The easting at the mouse pointer."));
889 previousCoordinateFormat = mCord;
890 } else {
891 latText.setIcon("lat");
892 lonText.setIcon("lon");
893 latText.setToolTipText(tr("The geographic latitude at the mouse pointer."));
894 lonText.setToolTipText(tr("The geographic longitude at the mouse pointer."));
895 previousCoordinateFormat = mCord;
896 }
897 }
898 }
899 });
900
901 setLayout(new GridBagLayout());
902 setBorder(BorderFactory.createEmptyBorder(1, 2, 1, 2));
903
904 latText.setInheritsPopupMenu(true);
905 lonText.setInheritsPopupMenu(true);
906 headingText.setInheritsPopupMenu(true);
907 distText.setInheritsPopupMenu(true);
908 nameText.setInheritsPopupMenu(true);
909
910 add(latText, GBC.std());
911 add(lonText, GBC.std().insets(3, 0, 0, 0));
912 add(headingText, GBC.std().insets(3, 0, 0, 0));
913 add(angleText, GBC.std().insets(3, 0, 0, 0));
914 add(distText, GBC.std().insets(3, 0, 0, 0));
915
916 if (Config.getPref().getBoolean("statusbar.change-system-of-measurement-on-click", true)) {
917 distText.addMouseListener(new MouseAdapter() {
918 private final List<String> soms = new ArrayList<>(new TreeSet<>(SystemOfMeasurement.ALL_SYSTEMS.keySet()));
919
920 @Override
921 public void mouseClicked(MouseEvent e) {
922 if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
923 String som = SystemOfMeasurement.PROP_SYSTEM_OF_MEASUREMENT.get();
924 String newsom = soms.get((soms.indexOf(som)+1) % soms.size());
925 updateSystemOfMeasurement(newsom);
926 }
927 }
928 });
929 }
930
931 SystemOfMeasurement.addSoMChangeListener(this);
932
933 latText.addMouseListener(jumpToOnLeftClick);
934 lonText.addMouseListener(jumpToOnLeftClick);
935
936 helpText.setEditable(false);
937 add(nameText, GBC.std().insets(3, 0, 0, 0));
938 add(helpText, GBC.std().insets(3, 0, 0, 0).fill(GBC.HORIZONTAL));
939
940 progressBar.setMaximum(PleaseWaitProgressMonitor.PROGRESS_BAR_MAX);
941 progressBar.setVisible(false);
942 GBC gbc = GBC.eol();
943 gbc.ipadx = 100;
944 add(progressBar, gbc);
945 progressBar.addMouseListener(new ShowMonitorDialogMouseAdapter());
946
947 Config.getPref().addPreferenceChangeListener(this);
948
949 mvComponentAdapter = new ComponentAdapter() {
950 @Override
951 public void componentResized(ComponentEvent e) {
952 nameText.setCharCount(getNameLabelCharacterCount(Main.parent));
953 revalidate();
954 }
955 };
956 mv.addComponentListener(mvComponentAdapter);
957
958 // The background thread
959 thread = new Thread(collector, "Map Status Collector");
960 thread.setDaemon(true);
961 thread.start();
962 }
963
964 @Override
965 public void systemOfMeasurementChanged(String oldSoM, String newSoM) {
966 setDist(distValue);
967 }
968
969 /**
970 * Updates the system of measurement and displays a notification.
971 * @param newsom The new system of measurement to set
972 * @since 6960
973 */
974 public void updateSystemOfMeasurement(String newsom) {
975 SystemOfMeasurement.setSystemOfMeasurement(newsom);
976 if (Config.getPref().getBoolean("statusbar.notify.change-system-of-measurement", true)) {
977 new Notification(tr("System of measurement changed to {0}", newsom))
978 .setDuration(Notification.TIME_SHORT)
979 .show();
980 }
981 }
982
983 /**
984 * Gets the panel that displays the angle
985 * @return The angle panel
986 */
987 public JPanel getAnglePanel() {
988 return angleText;
989 }
990
991 @Override
992 public String helpTopic() {
993 return ht("/StatusBar");
994 }
995
996 @Override
997 public synchronized void addMouseListener(MouseListener ml) {
998 lonText.addMouseListener(ml);
999 latText.addMouseListener(ml);
1000 }
1001
1002 /**
1003 * Sets the help text in the status panel
1004 * @param text The text
1005 */
1006 public void setHelpText(String text) {
1007 setHelpText(null, text);
1008 }
1009
1010 /**
1011 * Sets the help status text to display
1012 * @param id The object that caused the status update (or a id object it selects). May be <code>null</code>
1013 * @param text The text
1014 */
1015 public synchronized void setHelpText(Object id, final String text) {
1016 StatusTextHistory entry = new StatusTextHistory(id, text);
1017
1018 statusText.remove(entry);
1019 statusText.add(entry);
1020
1021 GuiHelper.runInEDT(() -> {
1022 helpText.setText(text);
1023 helpText.setToolTipText(text);
1024 });
1025 }
1026
1027 /**
1028 * Removes a help text and restores the previous one
1029 * @param id The id passed to {@link #setHelpText(Object, String)}
1030 */
1031 public synchronized void resetHelpText(Object id) {
1032 if (statusText.isEmpty())
1033 return;
1034
1035 StatusTextHistory entry = new StatusTextHistory(id, null);
1036 if (statusText.get(statusText.size() - 1).equals(entry)) {
1037 if (statusText.size() == 1) {
1038 setHelpText("");
1039 } else {
1040 StatusTextHistory history = statusText.get(statusText.size() - 2);
1041 setHelpText(history.id, history.text);
1042 }
1043 }
1044 statusText.remove(entry);
1045 }
1046
1047 /**
1048 * Sets the angle to display in the angle panel
1049 * @param a The angle
1050 */
1051 public void setAngle(double a) {
1052 angleText.setText(a < 0 ? "--" : DECIMAL_FORMAT.format(a) + " \u00B0");
1053 }
1054
1055 /**
1056 * Sets the heading to display in the heading panel
1057 * @param h The heading
1058 */
1059 public void setHeading(double h) {
1060 headingText.setText(h < 0 ? "--" : DECIMAL_FORMAT.format(h) + " \u00B0");
1061 }
1062
1063 /**
1064 * Sets the distance text to the given value
1065 * @param dist The distance value to display, in meters
1066 */
1067 public void setDist(double dist) {
1068 distValue = dist;
1069 distText.setText(dist < 0 ? "--" : NavigatableComponent.getDistText(dist, DECIMAL_FORMAT, DISTANCE_THRESHOLD.get()));
1070 }
1071
1072 /**
1073 * Sets the distance text to the total sum of given ways length
1074 * @param ways The ways to consider for the total distance
1075 * @since 5991
1076 */
1077 public void setDist(Collection<Way> ways) {
1078 double dist = -1;
1079 // Compute total length of selected way(s) until an arbitrary limit set to 250 ways
1080 // in order to prevent performance issue if a large number of ways are selected (old behaviour kept in that case, see #8403)
1081 int maxWays = Math.max(1, Config.getPref().getInt("selection.max-ways-for-statusline", 250));
1082 if (!ways.isEmpty() && ways.size() <= maxWays) {
1083 dist = 0.0;
1084 for (Way w : ways) {
1085 dist += w.getLength();
1086 }
1087 }
1088 setDist(dist);
1089 }
1090
1091 /**
1092 * Activates the angle panel.
1093 * @param activeFlag {@code true} to activate it, {@code false} to deactivate it
1094 */
1095 public void activateAnglePanel(boolean activeFlag) {
1096 angleEnabled = activeFlag;
1097 refreshAnglePanel();
1098 }
1099
1100 private void refreshAnglePanel() {
1101 angleText.setBackground(angleEnabled ? PROP_ACTIVE_BACKGROUND_COLOR.get() : PROP_BACKGROUND_COLOR.get());
1102 angleText.setForeground(angleEnabled ? PROP_ACTIVE_FOREGROUND_COLOR.get() : PROP_FOREGROUND_COLOR.get());
1103 }
1104
1105 @Override
1106 public void destroy() {
1107 SystemOfMeasurement.removeSoMChangeListener(this);
1108 Config.getPref().removePreferenceChangeListener(this);
1109 mv.removeComponentListener(mvComponentAdapter);
1110
1111 // MapFrame gets destroyed when the last layer is removed, but the status line background
1112 // thread that collects the information doesn't get destroyed automatically.
1113 if (thread != null) {
1114 try {
1115 thread.interrupt();
1116 } catch (SecurityException e) {
1117 Logging.error(e);
1118 }
1119 }
1120 }
1121
1122 @Override
1123 public void preferenceChanged(PreferenceChangeEvent e) {
1124 String key = e.getKey();
1125 if (key.startsWith("color.")) {
1126 key = key.substring("color.".length());
1127 if (PROP_BACKGROUND_COLOR.getKey().equals(key) || PROP_FOREGROUND_COLOR.getKey().equals(key)) {
1128 for (ImageLabel il : new ImageLabel[]{latText, lonText, headingText, distText, nameText}) {
1129 il.setBackground(PROP_BACKGROUND_COLOR.get());
1130 il.setForeground(PROP_FOREGROUND_COLOR.get());
1131 }
1132 refreshAnglePanel();
1133 } else if (PROP_ACTIVE_BACKGROUND_COLOR.getKey().equals(key) || PROP_ACTIVE_FOREGROUND_COLOR.getKey().equals(key)) {
1134 refreshAnglePanel();
1135 }
1136 }
1137 }
1138
1139 /**
1140 * Loads all colors from preferences.
1141 * @since 6789
1142 */
1143 public static void getColors() {
1144 PROP_BACKGROUND_COLOR.get();
1145 PROP_FOREGROUND_COLOR.get();
1146 PROP_ACTIVE_BACKGROUND_COLOR.get();
1147 PROP_ACTIVE_FOREGROUND_COLOR.get();
1148 }
1149
1150 private static int getNameLabelCharacterCount(Component parent) {
1151 int w = parent != null ? parent.getWidth() : 800;
1152 return Math.min(80, 20 + Math.max(0, w-1280) * 60 / (1920-1280));
1153 }
1154}
Note: See TracBrowser for help on using the repository browser.