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

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

Rework console output:

  • new log level "error"
  • Replace nearly all calls to system.out and system.err to Main.(error|warn|info|debug)
  • Remove some unnecessary debug output
  • Some messages are modified (removal of "Info", "Warning", "Error" from the message itself -> notable i18n impact but limited to console error messages not seen by the majority of users, so that's ok)
  • Property svn:eol-style set to native
File size: 36.1 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.AWTEvent;
8import java.awt.Component;
9import java.awt.Cursor;
10import java.awt.Dimension;
11import java.awt.EventQueue;
12import java.awt.Font;
13import java.awt.GridBagLayout;
14import java.awt.Point;
15import java.awt.SystemColor;
16import java.awt.Toolkit;
17import java.awt.event.AWTEventListener;
18import java.awt.event.ActionEvent;
19import java.awt.event.InputEvent;
20import java.awt.event.KeyAdapter;
21import java.awt.event.KeyEvent;
22import java.awt.event.MouseAdapter;
23import java.awt.event.MouseEvent;
24import java.awt.event.MouseListener;
25import java.awt.event.MouseMotionListener;
26import java.util.ArrayList;
27import java.util.Collection;
28import java.util.ConcurrentModificationException;
29import java.util.List;
30import java.util.TreeSet;
31
32import javax.swing.AbstractAction;
33import javax.swing.BorderFactory;
34import javax.swing.JCheckBoxMenuItem;
35import javax.swing.JLabel;
36import javax.swing.JMenuItem;
37import javax.swing.JPanel;
38import javax.swing.JPopupMenu;
39import javax.swing.JProgressBar;
40import javax.swing.JScrollPane;
41import javax.swing.Popup;
42import javax.swing.PopupFactory;
43import javax.swing.UIManager;
44import javax.swing.event.PopupMenuEvent;
45import javax.swing.event.PopupMenuListener;
46
47import org.openstreetmap.josm.Main;
48import org.openstreetmap.josm.data.coor.CoordinateFormat;
49import org.openstreetmap.josm.data.coor.LatLon;
50import org.openstreetmap.josm.data.osm.DataSet;
51import org.openstreetmap.josm.data.osm.OsmPrimitive;
52import org.openstreetmap.josm.data.osm.Way;
53import org.openstreetmap.josm.gui.NavigatableComponent.SoMChangeListener;
54import org.openstreetmap.josm.gui.help.Helpful;
55import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
56import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
57import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor.ProgressMonitorDialog;
58import org.openstreetmap.josm.gui.util.GuiHelper;
59import org.openstreetmap.josm.gui.widgets.ImageLabel;
60import org.openstreetmap.josm.gui.widgets.JosmTextField;
61import org.openstreetmap.josm.tools.Destroyable;
62import org.openstreetmap.josm.tools.GBC;
63import org.openstreetmap.josm.tools.ImageProvider;
64
65/**
66 * A component that manages some status information display about the map.
67 * It keeps a status line below the map up to date and displays some tooltip
68 * information if the user hold the mouse long enough at some point.
69 *
70 * All this is done in background to not disturb other processes.
71 *
72 * The background thread does not alter any data of the map (read only thread).
73 * Also it is rather fail safe. In case of some error in the data, it just does
74 * nothing instead of whining and complaining.
75 *
76 * @author imi
77 */
78public class MapStatus extends JPanel implements Helpful, Destroyable {
79
80 /**
81 * The MapView this status belongs to.
82 */
83 final MapView mv;
84 final Collector collector;
85
86 public class BackgroundProgressMonitor implements ProgressMonitorDialog {
87
88 private String title;
89 private String customText;
90
91 private void updateText() {
92 if (customText != null && !customText.isEmpty()) {
93 progressBar.setToolTipText(tr("{0} ({1})", title, customText));
94 } else {
95 progressBar.setToolTipText(title);
96 }
97 }
98
99 @Override
100 public void setVisible(boolean visible) {
101 progressBar.setVisible(visible);
102 }
103
104 @Override
105 public void updateProgress(int progress) {
106 progressBar.setValue(progress);
107 progressBar.repaint();
108 MapStatus.this.doLayout();
109 }
110
111 @Override
112 public void setCustomText(String text) {
113 this.customText = text;
114 updateText();
115 }
116
117 @Override
118 public void setCurrentAction(String text) {
119 this.title = text;
120 updateText();
121 }
122
123 @Override
124 public void setIndeterminate(boolean newValue) {
125 UIManager.put("ProgressBar.cycleTime", UIManager.getInt("ProgressBar.repaintInterval") * 100);
126 progressBar.setIndeterminate(newValue);
127 }
128
129 @Override
130 public void appendLogMessage(String message) {
131 if (message != null && !message.isEmpty()) {
132 Main.info("appendLogMessage not implemented for background tasks. Message was: " + message);
133 }
134 }
135
136 }
137
138 final ImageLabel lonText = new ImageLabel("lon", tr("The geographic longitude at the mouse pointer."), 11);
139 final ImageLabel nameText = new ImageLabel("name", tr("The name of the object at the mouse pointer."), 20);
140 final JosmTextField helpText = new JosmTextField();
141 final ImageLabel latText = new ImageLabel("lat", tr("The geographic latitude at the mouse pointer."), 11);
142 final ImageLabel angleText = new ImageLabel("angle", tr("The angle between the previous and the current way segment."), 6);
143 final ImageLabel headingText = new ImageLabel("heading", tr("The (compass) heading of the line segment being drawn."), 6);
144 final ImageLabel distText = new ImageLabel("dist", tr("The length of the new way segment being drawn."), 10);
145 final JProgressBar progressBar = new JProgressBar();
146 public final BackgroundProgressMonitor progressMonitor = new BackgroundProgressMonitor();
147
148 private final MouseListener jumpToOnLeftClick;
149 private final SoMChangeListener somListener;
150
151 private double distValue; // Distance value displayed in distText, stored if refresh needed after a change of system of measurement
152
153 /**
154 * This is the thread that runs in the background and collects the information displayed.
155 * It gets destroyed by destroy() when the MapFrame itself is destroyed.
156 */
157 private Thread thread;
158
159 private final List<StatusTextHistory> statusText = new ArrayList<StatusTextHistory>();
160
161 private static class StatusTextHistory {
162 final Object id;
163 final String text;
164
165 public StatusTextHistory(Object id, String text) {
166 this.id = id;
167 this.text = text;
168 }
169
170 @Override
171 public boolean equals(Object obj) {
172 return obj instanceof StatusTextHistory && ((StatusTextHistory)obj).id == id;
173 }
174
175 @Override
176 public int hashCode() {
177 return System.identityHashCode(id);
178 }
179 }
180
181 /**
182 * The collector class that waits for notification and then update
183 * the display objects.
184 *
185 * @author imi
186 */
187 private final class Collector implements Runnable {
188 /**
189 * the mouse position of the previous iteration. This is used to show
190 * the popup until the cursor is moved.
191 */
192 private Point oldMousePos;
193 /**
194 * Contains the labels that are currently shown in the information
195 * popup
196 */
197 private List<JLabel> popupLabels = null;
198 /**
199 * The popup displayed to show additional information
200 */
201 private Popup popup;
202
203 private MapFrame parent;
204
205 public Collector(MapFrame parent) {
206 this.parent = parent;
207 }
208
209 /**
210 * Execution function for the Collector.
211 */
212 @Override
213 public void run() {
214 registerListeners();
215 try {
216 for (;;) {
217
218 final MouseState ms = new MouseState();
219 synchronized (this) {
220 // TODO Would be better if the timeout wasn't necessary
221 try {wait(1000);} catch (InterruptedException e) {}
222 ms.modifiers = mouseState.modifiers;
223 ms.mousePos = mouseState.mousePos;
224 }
225 if (parent != Main.map)
226 return; // exit, if new parent.
227
228 // Do nothing, if required data is missing
229 if(ms.mousePos == null || mv.center == null) {
230 continue;
231 }
232
233 try {
234 EventQueue.invokeAndWait(new Runnable() {
235
236 @Override
237 public void run() {
238 // Freeze display when holding down CTRL
239 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) {
240 // update the information popup's labels though, because
241 // the selection might have changed from the outside
242 popupUpdateLabels();
243 return;
244 }
245
246 // This try/catch is a hack to stop the flooding bug reports about this.
247 // The exception needed to handle with in the first place, means that this
248 // access to the data need to be restarted, if the main thread modifies
249 // the data.
250 DataSet ds = null;
251 // The popup != null check is required because a left-click
252 // produces several events as well, which would make this
253 // variable true. Of course we only want the popup to show
254 // if the middle mouse button has been pressed in the first
255 // place
256 boolean mouseNotMoved = oldMousePos != null
257 && oldMousePos.equals(ms.mousePos);
258 boolean isAtOldPosition = mouseNotMoved && popup != null;
259 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0;
260 try {
261 ds = mv.getCurrentDataSet();
262 if (ds != null) {
263 // This is not perfect, if current dataset was changed during execution, the lock would be useless
264 if(isAtOldPosition && middleMouseDown) {
265 // Write lock is necessary when selecting in popupCycleSelection
266 // locks can not be upgraded -> if do read lock here and write lock later (in OsmPrimitive.updateFlags)
267 // then always occurs deadlock (#5814)
268 ds.beginUpdate();
269 } else {
270 ds.getReadLock().lock();
271 }
272 }
273
274 // Set the text label in the bottom status bar
275 // "if mouse moved only" was added to stop heap growing
276 if (!mouseNotMoved) {
277 statusBarElementUpdate(ms);
278 }
279
280
281 // Popup Information
282 // display them if the middle mouse button is pressed and
283 // keep them until the mouse is moved
284 if (middleMouseDown || isAtOldPosition)
285 {
286 Collection<OsmPrimitive> osms = mv.getAllNearest(ms.mousePos, OsmPrimitive.isUsablePredicate);
287
288 if (osms == null)
289 return;
290
291 final JPanel c = new JPanel(new GridBagLayout());
292 final JLabel lbl = new JLabel(
293 "<html>"+tr("Middle click again to cycle through.<br>"+
294 "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>",
295 null,
296 JLabel.HORIZONTAL
297 );
298 lbl.setHorizontalAlignment(JLabel.LEFT);
299 c.add(lbl, GBC.eol().insets(2, 0, 2, 0));
300
301 // Only cycle if the mouse has not been moved and the
302 // middle mouse button has been pressed at least twice
303 // (the reason for this is the popup != null check for
304 // isAtOldPosition, see above. This is a nice side
305 // effect though, because it does not change selection
306 // of the first middle click)
307 if(isAtOldPosition && middleMouseDown) {
308 // Hand down mouse modifiers so the SHIFT mod can be
309 // handled correctly (see funcion)
310 popupCycleSelection(osms, ms.modifiers);
311 }
312
313 // These labels may need to be updated from the outside
314 // so collect them
315 List<JLabel> lbls = new ArrayList<JLabel>(osms.size());
316 for (final OsmPrimitive osm : osms) {
317 JLabel l = popupBuildPrimitiveLabels(osm);
318 lbls.add(l);
319 c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2));
320 }
321
322 popupShowPopup(popupCreatePopup(c, ms), lbls);
323 } else {
324 popupHidePopup();
325 }
326
327 oldMousePos = ms.mousePos;
328 } catch (ConcurrentModificationException x) {
329 //x.printStackTrace();
330 } catch (NullPointerException x) {
331 //x.printStackTrace();
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 } catch (Exception e) {
344
345 }
346 }
347 } finally {
348 unregisterListeners();
349 }
350 }
351
352 /**
353 * Creates a popup for the given content next to the cursor. Tries to
354 * keep the popup on screen and shows a vertical scrollbar, if the
355 * screen is too small.
356 * @param content
357 * @param ms
358 * @return popup
359 */
360 private Popup popupCreatePopup(Component content, MouseState ms) {
361 Point p = mv.getLocationOnScreen();
362 Dimension scrn = Toolkit.getDefaultToolkit().getScreenSize();
363
364 // Create a JScrollPane around the content, in case there's not
365 // enough space
366 JScrollPane sp = new JScrollPane(content);
367 sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
368 sp.setBorder(BorderFactory.createRaisedBevelBorder());
369 // Implement max-size content-independent
370 Dimension prefsize = sp.getPreferredSize();
371 int w = Math.min(prefsize.width, Math.min(800, (scrn.width/2) - 16));
372 int h = Math.min(prefsize.height, scrn.height - 10);
373 sp.setPreferredSize(new Dimension(w, h));
374
375 int xPos = p.x + ms.mousePos.x + 16;
376 // Display the popup to the left of the cursor if it would be cut
377 // off on its right, but only if more space is available
378 if(xPos + w > scrn.width && xPos > scrn.width/2) {
379 xPos = p.x + ms.mousePos.x - 4 - w;
380 }
381 int yPos = p.y + ms.mousePos.y + 16;
382 // Move the popup up if it would be cut off at its bottom but do not
383 // move it off screen on the top
384 if(yPos + h > scrn.height - 5) {
385 yPos = Math.max(5, scrn.height - h - 5);
386 }
387
388 PopupFactory pf = PopupFactory.getSharedInstance();
389 return pf.getPopup(mv, sp, xPos, yPos);
390 }
391
392 /**
393 * Calls this to update the element that is shown in the statusbar
394 * @param ms
395 */
396 private void statusBarElementUpdate(MouseState ms) {
397 final OsmPrimitive osmNearest = mv.getNearestNodeOrWay(ms.mousePos, OsmPrimitive.isUsablePredicate, false);
398 if (osmNearest != null) {
399 nameText.setText(osmNearest.getDisplayName(DefaultNameFormatter.getInstance()));
400 } else {
401 nameText.setText(tr("(no object)"));
402 }
403 }
404
405 /**
406 * Call this with a set of primitives to cycle through them. Method
407 * will automatically select the next item and update the map
408 * @param osms primitives to cycle through
409 * @param mods modifiers (i.e. control keys)
410 */
411 private void popupCycleSelection(Collection<OsmPrimitive> osms, int mods) {
412 DataSet ds = Main.main.getCurrentDataSet();
413 // Find some items that are required for cycling through
414 OsmPrimitive firstItem = null;
415 OsmPrimitive firstSelected = null;
416 OsmPrimitive nextSelected = null;
417 for (final OsmPrimitive osm : osms) {
418 if(firstItem == null) {
419 firstItem = osm;
420 }
421 if(firstSelected != null && nextSelected == null) {
422 nextSelected = osm;
423 }
424 if(firstSelected == null && ds.isSelected(osm)) {
425 firstSelected = osm;
426 }
427 }
428
429 // Clear previous selection if SHIFT (add to selection) is not
430 // pressed. Cannot use "setSelected()" because it will cause a
431 // fireSelectionChanged event which is unnecessary at this point.
432 if((mods & MouseEvent.SHIFT_DOWN_MASK) == 0) {
433 ds.clearSelection();
434 }
435
436 // This will cycle through the available items.
437 if(firstSelected == null) {
438 ds.addSelected(firstItem);
439 } else {
440 ds.clearSelection(firstSelected);
441 if(nextSelected != null) {
442 ds.addSelected(nextSelected);
443 }
444 }
445 }
446
447 /**
448 * Tries to hide the given popup
449 */
450 private void popupHidePopup() {
451 popupLabels = null;
452 if(popup == null)
453 return;
454 final Popup staticPopup = popup;
455 popup = null;
456 EventQueue.invokeLater(new Runnable(){
457 @Override
458 public void run() {
459 staticPopup.hide();
460 }});
461 }
462
463 /**
464 * Tries to show the given popup, can be hidden using {@link #popupHidePopup}
465 * If an old popup exists, it will be automatically hidden
466 * @param newPopup popup to show
467 * @param lbls lables to show (see {@link #popupLabels})
468 */
469 private void popupShowPopup(Popup newPopup, List<JLabel> lbls) {
470 final Popup staticPopup = newPopup;
471 if(this.popup != null) {
472 // If an old popup exists, remove it when the new popup has been
473 // drawn to keep flickering to a minimum
474 final Popup staticOldPopup = this.popup;
475 EventQueue.invokeLater(new Runnable(){
476 @Override public void run() {
477 staticPopup.show();
478 staticOldPopup.hide();
479 }
480 });
481 } else {
482 // There is no old popup
483 EventQueue.invokeLater(new Runnable(){
484 @Override public void run() { staticPopup.show(); }});
485 }
486 this.popupLabels = lbls;
487 this.popup = newPopup;
488 }
489
490 /**
491 * This method should be called if the selection may have changed from
492 * outside of this class. This is the case when CTRL is pressed and the
493 * user clicks on the map instead of the popup.
494 */
495 private void popupUpdateLabels() {
496 if(this.popup == null || this.popupLabels == null)
497 return;
498 for(JLabel l : this.popupLabels) {
499 l.validate();
500 }
501 }
502
503 /**
504 * Sets the colors for the given label depending on the selected status of
505 * the given OsmPrimitive
506 *
507 * @param lbl The label to color
508 * @param osm The primitive to derive the colors from
509 */
510 private void popupSetLabelColors(JLabel lbl, OsmPrimitive osm) {
511 DataSet ds = Main.main.getCurrentDataSet();
512 if(ds.isSelected(osm)) {
513 lbl.setBackground(SystemColor.textHighlight);
514 lbl.setForeground(SystemColor.textHighlightText);
515 } else {
516 lbl.setBackground(SystemColor.control);
517 lbl.setForeground(SystemColor.controlText);
518 }
519 }
520
521 /**
522 * Builds the labels with all necessary listeners for the info popup for the
523 * given OsmPrimitive
524 * @param osm The primitive to create the label for
525 * @return labels for info popup
526 */
527 private JLabel popupBuildPrimitiveLabels(final OsmPrimitive osm) {
528 final StringBuilder text = new StringBuilder();
529 String name = osm.getDisplayName(DefaultNameFormatter.getInstance());
530 if (osm.isNewOrUndeleted() || osm.isModified()) {
531 name = "<i><b>"+ name + "*</b></i>";
532 }
533 text.append(name);
534
535 boolean idShown = Main.pref.getBoolean("osm-primitives.showid");
536 // fix #7557 - do not show ID twice
537
538 if (!osm.isNew() && !idShown) {
539 text.append(" [id="+osm.getId()+"]");
540 }
541
542 if(osm.getUser() != null) {
543 text.append(" [" + tr("User:") + " " + osm.getUser().getName() + "]");
544 }
545
546 for (String key : osm.keySet()) {
547 text.append("<br>" + key + "=" + osm.get(key));
548 }
549
550 final JLabel l = new JLabel(
551 "<html>" +text.toString() + "</html>",
552 ImageProvider.get(osm.getDisplayType()),
553 JLabel.HORIZONTAL
554 ) {
555 // This is necessary so the label updates its colors when the
556 // selection is changed from the outside
557 @Override public void validate() {
558 super.validate();
559 popupSetLabelColors(this, osm);
560 }
561 };
562 l.setOpaque(true);
563 popupSetLabelColors(l, osm);
564 l.setFont(l.getFont().deriveFont(Font.PLAIN));
565 l.setVerticalTextPosition(JLabel.TOP);
566 l.setHorizontalAlignment(JLabel.LEFT);
567 l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
568 l.addMouseListener(new MouseAdapter(){
569 @Override public void mouseEntered(MouseEvent e) {
570 l.setBackground(SystemColor.info);
571 l.setForeground(SystemColor.infoText);
572 }
573 @Override public void mouseExited(MouseEvent e) {
574 popupSetLabelColors(l, osm);
575 }
576 @Override public void mouseClicked(MouseEvent e) {
577 DataSet ds = Main.main.getCurrentDataSet();
578 // Let the user toggle the selection
579 ds.toggleSelected(osm);
580 l.validate();
581 }
582 });
583 // Sometimes the mouseEntered event is not catched, thus the label
584 // will not be highlighted, making it confusing. The MotionListener
585 // can correct this defect.
586 l.addMouseMotionListener(new MouseMotionListener() {
587 @Override public void mouseMoved(MouseEvent e) {
588 l.setBackground(SystemColor.info);
589 l.setForeground(SystemColor.infoText);
590 }
591 @Override public void mouseDragged(MouseEvent e) {
592 l.setBackground(SystemColor.info);
593 l.setForeground(SystemColor.infoText);
594 }
595 });
596 return l;
597 }
598 }
599
600 /**
601 * Everything, the collector is interested of. Access must be synchronized.
602 * @author imi
603 */
604 static class MouseState {
605 Point mousePos;
606 int modifiers;
607 }
608 /**
609 * The last sent mouse movement event.
610 */
611 MouseState mouseState = new MouseState();
612
613 private AWTEventListener awtListener = new AWTEventListener() {
614 @Override
615 public void eventDispatched(AWTEvent event) {
616 if (event instanceof InputEvent &&
617 ((InputEvent)event).getComponent() == mv) {
618 synchronized (collector) {
619 mouseState.modifiers = ((InputEvent)event).getModifiersEx();
620 if (event instanceof MouseEvent) {
621 mouseState.mousePos = ((MouseEvent)event).getPoint();
622 }
623 collector.notify();
624 }
625 }
626 }
627 };
628
629 private MouseMotionListener mouseMotionListener = new MouseMotionListener() {
630 @Override
631 public void mouseMoved(MouseEvent e) {
632 synchronized (collector) {
633 mouseState.modifiers = e.getModifiersEx();
634 mouseState.mousePos = e.getPoint();
635 collector.notify();
636 }
637 }
638
639 @Override
640 public void mouseDragged(MouseEvent e) {
641 mouseMoved(e);
642 }
643 };
644
645 private KeyAdapter keyAdapter = new KeyAdapter() {
646 @Override public void keyPressed(KeyEvent e) {
647 synchronized (collector) {
648 mouseState.modifiers = e.getModifiersEx();
649 collector.notify();
650 }
651 }
652
653 @Override public void keyReleased(KeyEvent e) {
654 keyPressed(e);
655 }
656 };
657
658 private void registerListeners() {
659 // Listen to keyboard/mouse events for pressing/releasing alt key and
660 // inform the collector.
661 try {
662 Toolkit.getDefaultToolkit().addAWTEventListener(awtListener,
663 AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
664 } catch (SecurityException ex) {
665 mv.addMouseMotionListener(mouseMotionListener);
666 mv.addKeyListener(keyAdapter);
667 }
668 }
669
670 private void unregisterListeners() {
671 try {
672 Toolkit.getDefaultToolkit().removeAWTEventListener(awtListener);
673 } catch (SecurityException e) {
674 // Don't care, awtListener probably wasn't registered anyway
675 }
676 mv.removeMouseMotionListener(mouseMotionListener);
677 mv.removeKeyListener(keyAdapter);
678 }
679
680
681 /**
682 * Construct a new MapStatus and attach it to the map view.
683 * @param mapFrame The MapFrame the status line is part of.
684 */
685 public MapStatus(final MapFrame mapFrame) {
686 this.mv = mapFrame.mapView;
687 this.collector = new Collector(mapFrame);
688
689 // Context menu of status bar
690 setComponentPopupMenu(new JPopupMenu() {
691 JCheckBoxMenuItem doNotHide = new JCheckBoxMenuItem(new AbstractAction(tr("Do not hide status bar")) {
692 @Override public void actionPerformed(ActionEvent e) {
693 boolean sel = ((JCheckBoxMenuItem) e.getSource()).getState();
694 Main.pref.put("statusbar.always-visible", sel);
695 }
696 });
697 JMenuItem jumpButton;
698 {
699 jumpButton = add(Main.main.menu.jumpToAct);
700 addPopupMenuListener(new PopupMenuListener() {
701 @Override
702 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
703 Component invoker = ((JPopupMenu)e.getSource()).getInvoker();
704 jumpButton.setVisible(invoker == latText || invoker == lonText);
705 doNotHide.setSelected(Main.pref.getBoolean("statusbar.always-visible", true));
706 }
707 @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
708 @Override public void popupMenuCanceled(PopupMenuEvent e) {}
709 });
710 add(doNotHide);
711 }
712 });
713
714 // also show Jump To dialog on mouse click (except context menu)
715 jumpToOnLeftClick = new MouseAdapter() {
716 @Override
717 public void mouseClicked(MouseEvent e) {
718 if (e.getButton() != MouseEvent.BUTTON3) {
719 Main.main.menu.jumpToAct.showJumpToDialog();
720 }
721 }
722 };
723
724 // Listen for mouse movements and set the position text field
725 mv.addMouseMotionListener(new MouseMotionListener(){
726 @Override
727 public void mouseDragged(MouseEvent e) {
728 mouseMoved(e);
729 }
730 @Override
731 public void mouseMoved(MouseEvent e) {
732 if (mv.center == null)
733 return;
734 // Do not update the view if ctrl is pressed.
735 if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0) {
736 CoordinateFormat mCord = CoordinateFormat.getDefaultFormat();
737 LatLon p = mv.getLatLon(e.getX(),e.getY());
738 latText.setText(p.latToString(mCord));
739 lonText.setText(p.lonToString(mCord));
740 }
741 }
742 });
743
744 setLayout(new GridBagLayout());
745 setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
746
747 latText.setInheritsPopupMenu(true);
748 lonText.setInheritsPopupMenu(true);
749 headingText.setInheritsPopupMenu(true);
750 //angleText.setInheritsPopupMenu(true);
751 distText.setInheritsPopupMenu(true);
752 nameText.setInheritsPopupMenu(true);
753 //helpText.setInheritsPopupMenu(true);
754 //progressBar.setInheritsPopupMenu(true);
755
756 add(latText, GBC.std());
757 add(lonText, GBC.std().insets(3,0,0,0));
758 add(headingText, GBC.std().insets(3,0,0,0));
759 add(angleText, GBC.std().insets(3,0,0,0));
760 add(distText, GBC.std().insets(3,0,0,0));
761
762 distText.addMouseListener(new MouseAdapter() {
763 private final List<String> soms = new ArrayList<String>(new TreeSet<String>(NavigatableComponent.SYSTEMS_OF_MEASUREMENT.keySet()));
764
765 @Override
766 public void mouseClicked(MouseEvent e) {
767 String som = ProjectionPreference.PROP_SYSTEM_OF_MEASUREMENT.get();
768 String newsom = soms.get((soms.indexOf(som)+1)%soms.size());
769 NavigatableComponent.setSystemOfMeasurement(newsom);
770 }
771 });
772
773 NavigatableComponent.addSoMChangeListener(somListener = new SoMChangeListener() {
774 @Override public void systemOfMeasurementChanged(String oldSoM, String newSoM) {
775 setDist(distValue);
776 }
777 });
778
779 latText.addMouseListener(jumpToOnLeftClick);
780 lonText.addMouseListener(jumpToOnLeftClick);
781
782 helpText.setEditable(false);
783 add(nameText, GBC.std().insets(3,0,0,0));
784 add(helpText, GBC.std().insets(3,0,0,0).fill(GBC.HORIZONTAL));
785
786 progressBar.setMaximum(PleaseWaitProgressMonitor.PROGRESS_BAR_MAX);
787 progressBar.setVisible(false);
788 GBC gbc = GBC.eol();
789 gbc.ipadx = 100;
790 add(progressBar,gbc);
791 progressBar.addMouseListener(new MouseAdapter() {
792 @Override
793 public void mouseClicked(MouseEvent e) {
794 PleaseWaitProgressMonitor monitor = Main.currentProgressMonitor;
795 if (monitor != null) {
796 monitor.showForegroundDialog();
797 }
798 }
799 });
800
801 // The background thread
802 thread = new Thread(collector, "Map Status Collector");
803 thread.setDaemon(true);
804 thread.start();
805 }
806
807 public JPanel getAnglePanel() {
808 return angleText;
809 }
810
811 @Override
812 public String helpTopic() {
813 return ht("/Statusline");
814 }
815
816 @Override
817 public synchronized void addMouseListener(MouseListener ml) {
818 //super.addMouseListener(ml);
819 lonText.addMouseListener(ml);
820 latText.addMouseListener(ml);
821 }
822
823 public void setHelpText(String t) {
824 setHelpText(null, t);
825 }
826 public void setHelpText(Object id, final String text) {
827
828 StatusTextHistory entry = new StatusTextHistory(id, text);
829
830 statusText.remove(entry);
831 statusText.add(entry);
832
833 GuiHelper.runInEDT(new Runnable() {
834 @Override
835 public void run() {
836 helpText.setText(text);
837 helpText.setToolTipText(text);
838 }
839 });
840 }
841 public void resetHelpText(Object id) {
842 if (statusText.isEmpty())
843 return;
844
845 StatusTextHistory entry = new StatusTextHistory(id, null);
846 if (statusText.get(statusText.size() - 1).equals(entry)) {
847 if (statusText.size() == 1) {
848 setHelpText("");
849 } else {
850 StatusTextHistory history = statusText.get(statusText.size() - 2);
851 setHelpText(history.id, history.text);
852 }
853 }
854 statusText.remove(entry);
855 }
856 public void setAngle(double a) {
857 angleText.setText(a < 0 ? "--" : Math.round(a*10)/10.0 + " \u00B0");
858 }
859 public void setHeading(double h) {
860 headingText.setText(h < 0 ? "--" : Math.round(h*10)/10.0 + " \u00B0");
861 }
862 /**
863 * Sets the distance text to the given value
864 * @param dist The distance value to display, in meters
865 */
866 public void setDist(double dist) {
867 distValue = dist;
868 distText.setText(dist < 0 ? "--" : NavigatableComponent.getDistText(dist));
869 }
870 /**
871 * Sets the distance text to the total sum of given ways length
872 * @param ways The ways to consider for the total distance
873 * @since 5991
874 */
875 public void setDist(Collection<Way> ways) {
876 double dist = -1;
877 // Compute total length of selected way(s) until an arbitrary limit set to 250 ways
878 // in order to prevent performance issue if a large number of ways are selected (old behaviour kept in that case, see #8403)
879 int maxWays = Math.max(1, Main.pref.getInteger("selection.max-ways-for-statusline", 250));
880 if (!ways.isEmpty() && ways.size() <= maxWays) {
881 dist = 0.0;
882 for (Way w : ways) {
883 dist += w.getLength();
884 }
885 }
886 setDist(dist);
887 }
888 public void activateAnglePanel(boolean activeFlag) {
889 angleText.setBackground(activeFlag ? ImageLabel.backColorActive : ImageLabel.backColor);
890 }
891
892 @Override
893 public void destroy() {
894 NavigatableComponent.removeSoMChangeListener(somListener);
895
896 // MapFrame gets destroyed when the last layer is removed, but the status line background
897 // thread that collects the information doesn't get destroyed automatically.
898 if (thread != null) {
899 try {
900 thread.interrupt();
901 } catch (Exception e) {
902 e.printStackTrace();
903 }
904 }
905 }
906}
Note: See TracBrowser for help on using the repository browser.