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

Last change on this file since 9369 was 9346, checked in by simon04, 8 years ago

fix #10773 - Improve map status display for projected coordinate systems

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