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

Last change on this file since 10659 was 10657, checked in by Don-vip, 8 years ago

see #11390, see #12890 - use Java 8 Predicates

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