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

Last change on this file since 3406 was 3406, checked in by bastiK, 14 years ago

fixed #5284 - change units at bottom of screen

  • Property svn:eol-style set to native
File size: 25.0 KB
Line 
1// License: GPL. See LICENSE file for details.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.AWTEvent;
7import java.awt.Color;
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.InputEvent;
19import java.awt.event.KeyAdapter;
20import java.awt.event.KeyEvent;
21import java.awt.event.MouseAdapter;
22import java.awt.event.MouseEvent;
23import java.awt.event.MouseListener;
24import java.awt.event.MouseMotionListener;
25import java.util.ArrayList;
26import java.util.Collection;
27import java.util.ConcurrentModificationException;
28import java.util.List;
29
30import javax.swing.BorderFactory;
31import javax.swing.JLabel;
32import javax.swing.JPanel;
33import javax.swing.JScrollPane;
34import javax.swing.JTextField;
35import javax.swing.Popup;
36import javax.swing.PopupFactory;
37
38import org.openstreetmap.josm.Main;
39import org.openstreetmap.josm.data.coor.CoordinateFormat;
40import org.openstreetmap.josm.data.coor.LatLon;
41import org.openstreetmap.josm.data.osm.DataSet;
42import org.openstreetmap.josm.data.osm.OsmPrimitive;
43import org.openstreetmap.josm.data.osm.OsmPrimitiveType;
44import org.openstreetmap.josm.gui.help.Helpful;
45import org.openstreetmap.josm.tools.GBC;
46import org.openstreetmap.josm.tools.ImageProvider;
47
48/**
49 * A component that manages some status information display about the map.
50 * It keeps a status line below the map up to date and displays some tooltip
51 * information if the user hold the mouse long enough at some point.
52 *
53 * All this is done in background to not disturb other processes.
54 *
55 * The background thread does not alter any data of the map (read only thread).
56 * Also it is rather fail safe. In case of some error in the data, it just does
57 * nothing instead of whining and complaining.
58 *
59 * @author imi
60 */
61public class MapStatus extends JPanel implements Helpful {
62
63 /**
64 * The MapView this status belongs to.
65 */
66 final MapView mv;
67 final Collector collector;
68
69 /**
70 * A small user interface component that consists of an image label and
71 * a fixed text content to the right of the image.
72 */
73 static class ImageLabel extends JPanel {
74 private JLabel tf;
75 private int chars;
76 public ImageLabel(String img, String tooltip, int chars) {
77 super();
78 setLayout(new GridBagLayout());
79 setBackground(Color.decode("#b8cfe5"));
80 add(new JLabel(ImageProvider.get("statusline/"+img+".png")), GBC.std().anchor(GBC.WEST).insets(0,1,1,0));
81 add(tf = new JLabel(), GBC.std().fill(GBC.BOTH).anchor(GBC.WEST).insets(2,1,1,0));
82 setToolTipText(tooltip);
83 this.chars = chars;
84 }
85 public void setText(String t) {
86 tf.setText(t);
87 }
88 @Override public Dimension getPreferredSize() {
89 return new Dimension(25 + chars*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getPreferredSize().height);
90 }
91 @Override public Dimension getMinimumSize() {
92 return new Dimension(25 + chars*tf.getFontMetrics(tf.getFont()).charWidth('0'), super.getMinimumSize().height);
93 }
94 }
95
96 ImageLabel lonText = new ImageLabel("lon", tr("The geographic longitude at the mouse pointer."), 11);
97 ImageLabel nameText = new ImageLabel("name", tr("The name of the object at the mouse pointer."), 20);
98 JTextField helpText = new JTextField();
99 ImageLabel latText = new ImageLabel("lat", tr("The geographic latitude at the mouse pointer."), 11);
100 ImageLabel angleText = new ImageLabel("angle", tr("The angle between the previous and the current way segment."), 6);
101 ImageLabel headingText = new ImageLabel("heading", tr("The (compass) heading of the line segment being drawn."), 6);
102 ImageLabel distText = new ImageLabel("dist", tr("The length of the new way segment being drawn."), 10);
103
104 /**
105 * This is the thread that runs in the background and collects the information displayed.
106 * It gets destroyed by MapFrame.java/destroy() when the MapFrame itself is destroyed.
107 */
108 public Thread thread;
109
110 /**
111 * The collector class that waits for notification and then update
112 * the display objects.
113 *
114 * @author imi
115 */
116 private final class Collector implements Runnable {
117 /**
118 * the mouse position of the previous iteration. This is used to show
119 * the popup until the cursor is moved.
120 */
121 private Point oldMousePos;
122 /**
123 * Contains the labels that are currently shown in the information
124 * popup
125 */
126 private List<JLabel> popupLabels = null;
127 /**
128 * The popup displayed to show additional information
129 */
130 private Popup popup;
131
132 private MapFrame parent;
133
134 public Collector(MapFrame parent) {
135 this.parent = parent;
136 }
137
138 /**
139 * Execution function for the Collector.
140 */
141 public void run() {
142 registerListeners();
143 try {
144 for (;;) {
145
146 MouseState ms = new MouseState();
147 synchronized (this) {
148 // TODO Would be better if the timeout wasn't necessary
149 try {wait(1000);} catch (InterruptedException e) {}
150 ms.modifiers = mouseState.modifiers;
151 ms.mousePos = mouseState.mousePos;
152 }
153 if (parent != Main.map)
154 return; // exit, if new parent.
155
156 // Do nothing, if required data is missing
157 if(ms.mousePos == null || mv.center == null) {
158 continue;
159 }
160
161 // Freeze display when holding down CTRL
162 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) {
163 // update the information popup's labels though, because
164 // the selection might have changed from the outside
165 popupUpdateLabels();
166 continue;
167 }
168
169 // This try/catch is a hack to stop the flooding bug reports about this.
170 // The exception needed to handle with in the first place, means that this
171 // access to the data need to be restarted, if the main thread modifies
172 // the data.
173 try {
174 // Set the text label in the bottom status bar
175 statusBarElementUpdate(ms);
176
177 // The popup != null check is required because a left-click
178 // produces several events as well, which would make this
179 // variable true. Of course we only want the popup to show
180 // if the middle mouse button has been pressed in the first
181 // place
182 boolean isAtOldPosition = (oldMousePos != null
183 && oldMousePos.equals(ms.mousePos)
184 && popup != null);
185 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0;
186
187 // Popup Information
188 // display them if the middle mouse button is pressed and
189 // keep them until the mouse is moved
190 if (middleMouseDown || isAtOldPosition)
191 {
192 Collection<OsmPrimitive> osms = mv.getAllNearest(ms.mousePos, OsmPrimitive.isUsablePredicate);
193
194 if (osms == null) {
195 continue;
196 }
197
198 final JPanel c = new JPanel(new GridBagLayout());
199 final JLabel lbl = new JLabel(
200 "<html>"+tr("Middle click again to cycle through.<br>"+
201 "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>",
202 null,
203 JLabel.HORIZONTAL
204 );
205 lbl.setHorizontalAlignment(JLabel.LEFT);
206 c.add(lbl, GBC.eol().insets(2, 0, 2, 0));
207
208 // Only cycle if the mouse has not been moved and the
209 // middle mouse button has been pressed at least twice
210 // (the reason for this is the popup != null check for
211 // isAtOldPosition, see above. This is a nice side
212 // effect though, because it does not change selection
213 // of the first middle click)
214 if(isAtOldPosition && middleMouseDown) {
215 // Hand down mouse modifiers so the SHIFT mod can be
216 // handled correctly (see funcion)
217 popupCycleSelection(osms, ms.modifiers);
218 }
219
220 // These labels may need to be updated from the outside
221 // so collect them
222 List<JLabel> lbls = new ArrayList<JLabel>();
223 for (final OsmPrimitive osm : osms) {
224 JLabel l = popupBuildPrimitiveLabels(osm);
225 lbls.add(l);
226 c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2));
227 }
228
229 popupShowPopup(popupCreatePopup(c, ms), lbls);
230 } else {
231 popupHidePopup();
232 }
233
234 oldMousePos = ms.mousePos;
235 } catch (ConcurrentModificationException x) {
236 //x.printStackTrace();
237 } catch (NullPointerException x) {
238 //x.printStackTrace();
239 }
240 }
241 } finally {
242 unregisterListeners();
243 }
244 }
245
246 /**
247 * Creates a popup for the given content next to the cursor. Tries to
248 * keep the popup on screen and shows a vertical scrollbar, if the
249 * screen is too small.
250 * @param content
251 * @param ms
252 * @return popup
253 */
254 private final Popup popupCreatePopup(Component content, MouseState ms) {
255 Point p = mv.getLocationOnScreen();
256 Dimension scrn = Toolkit.getDefaultToolkit().getScreenSize();
257
258 // Create a JScrollPane around the content, in case there's not
259 // enough space
260 JScrollPane sp = new JScrollPane(content);
261 sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
262 sp.setBorder(BorderFactory.createRaisedBevelBorder());
263 // Implement max-size content-independent
264 Dimension prefsize = sp.getPreferredSize();
265 int w = Math.min(prefsize.width, Math.min(800, (scrn.width/2) - 16));
266 int h = Math.min(prefsize.height, scrn.height - 10);
267 sp.setPreferredSize(new Dimension(w, h));
268
269 int xPos = p.x + ms.mousePos.x + 16;
270 // Display the popup to the left of the cursor if it would be cut
271 // off on its right, but only if more space is available
272 if(xPos + w > scrn.width && xPos > scrn.width/2) {
273 xPos = p.x + ms.mousePos.x - 4 - w;
274 }
275 int yPos = p.y + ms.mousePos.y + 16;
276 // Move the popup up if it would be cut off at its bottom but do not
277 // move it off screen on the top
278 if(yPos + h > scrn.height - 5) {
279 yPos = Math.max(5, scrn.height - h - 5);
280 }
281
282 PopupFactory pf = PopupFactory.getSharedInstance();
283 return pf.getPopup(mv, sp, xPos, yPos);
284 }
285
286 /**
287 * Calls this to update the element that is shown in the statusbar
288 * @param ms
289 */
290 private final void statusBarElementUpdate(MouseState ms) {
291 final OsmPrimitive osmNearest = mv.getNearest(ms.mousePos, OsmPrimitive.isUsablePredicate);
292 if (osmNearest != null) {
293 nameText.setText(osmNearest.getDisplayName(DefaultNameFormatter.getInstance()));
294 } else {
295 nameText.setText(tr("(no object)"));
296 }
297 }
298
299 /**
300 * Call this with a set of primitives to cycle through them. Method
301 * will automatically select the next item and update the map
302 * @param osms
303 * @param mouse modifiers
304 */
305 private final void popupCycleSelection(Collection<OsmPrimitive> osms, int mods) {
306 DataSet ds = Main.main.getCurrentDataSet();
307 // Find some items that are required for cycling through
308 OsmPrimitive firstItem = null;
309 OsmPrimitive firstSelected = null;
310 OsmPrimitive nextSelected = null;
311 for (final OsmPrimitive osm : osms) {
312 if(firstItem == null) {
313 firstItem = osm;
314 }
315 if(firstSelected != null && nextSelected == null) {
316 nextSelected = osm;
317 }
318 if(firstSelected == null && ds.isSelected(osm)) {
319 firstSelected = osm;
320 }
321 }
322
323 // Clear previous selection if SHIFT (add to selection) is not
324 // pressed. Cannot use "setSelected()" because it will cause a
325 // fireSelectionChanged event which is unnecessary at this point.
326 if((mods & MouseEvent.SHIFT_DOWN_MASK) == 0) {
327 ds.clearSelection();
328 }
329
330 // This will cycle through the available items.
331 if(firstSelected == null) {
332 ds.addSelected(firstItem);
333 } else {
334 ds.clearSelection(firstSelected);
335 if(nextSelected != null) {
336 ds.addSelected(nextSelected);
337 }
338 }
339 }
340
341 /**
342 * Tries to hide the given popup
343 * @param popup
344 */
345 private final void popupHidePopup() {
346 popupLabels = null;
347 if(popup == null)
348 return;
349 final Popup staticPopup = popup;
350 popup = null;
351 EventQueue.invokeLater(new Runnable(){
352 public void run() { staticPopup.hide(); }});
353 }
354
355 /**
356 * Tries to show the given popup, can be hidden using popupHideOldPopup
357 * If an old popup exists, it will be automatically hidden
358 * @param popup
359 */
360 private final void popupShowPopup(Popup newPopup, List<JLabel> lbls) {
361 final Popup staticPopup = newPopup;
362 if(this.popup != null) {
363 // If an old popup exists, remove it when the new popup has been
364 // drawn to keep flickering to a minimum
365 final Popup staticOldPopup = this.popup;
366 EventQueue.invokeLater(new Runnable(){
367 public void run() {
368 staticPopup.show();
369 staticOldPopup.hide();
370 }
371 });
372 } else {
373 // There is no old popup
374 EventQueue.invokeLater(new Runnable(){
375 public void run() { staticPopup.show(); }});
376 }
377 this.popupLabels = lbls;
378 this.popup = newPopup;
379 }
380
381 /**
382 * This method should be called if the selection may have changed from
383 * outside of this class. This is the case when CTRL is pressed and the
384 * user clicks on the map instead of the popup.
385 */
386 private final void popupUpdateLabels() {
387 if(this.popup == null || this.popupLabels == null)
388 return;
389 for(JLabel l : this.popupLabels) {
390 l.validate();
391 }
392 }
393
394 /**
395 * Sets the colors for the given label depending on the selected status of
396 * the given OsmPrimitive
397 *
398 * @param lbl The label to color
399 * @param osm The primitive to derive the colors from
400 */
401 private final void popupSetLabelColors(JLabel lbl, OsmPrimitive osm) {
402 DataSet ds = Main.main.getCurrentDataSet();
403 if(ds.isSelected(osm)) {
404 lbl.setBackground(SystemColor.textHighlight);
405 lbl.setForeground(SystemColor.textHighlightText);
406 } else {
407 lbl.setBackground(SystemColor.control);
408 lbl.setForeground(SystemColor.controlText);
409 }
410 }
411
412 /**
413 * Builds the labels with all necessary listeners for the info popup for the
414 * given OsmPrimitive
415 * @param osm The primitive to create the label for
416 * @return
417 */
418 private final JLabel popupBuildPrimitiveLabels(final OsmPrimitive osm) {
419 final StringBuilder text = new StringBuilder();
420 String name = osm.getDisplayName(DefaultNameFormatter.getInstance());
421 if (osm.isNewOrUndeleted() || osm.isModified()) {
422 name = "<i><b>"+ name + "*</b></i>";
423 }
424 text.append(name);
425
426 if (!osm.isNew()) {
427 text.append(" [id="+osm.getId()+"]");
428 }
429
430 if(osm.getUser() != null) {
431 text.append(" [" + tr("User:") + " " + osm.getUser().getName() + "]");
432 }
433
434 for (String key : osm.keySet()) {
435 text.append("<br>" + key + "=" + osm.get(key));
436 }
437
438 final JLabel l = new JLabel(
439 "<html>" +text.toString() + "</html>",
440 ImageProvider.get(OsmPrimitiveType.from(osm)),
441 JLabel.HORIZONTAL
442 ) {
443 // This is necessary so the label updates its colors when the
444 // selection is changed from the outside
445 @Override public void validate() {
446 super.validate();
447 popupSetLabelColors(this, osm);
448 }
449 };
450 l.setOpaque(true);
451 popupSetLabelColors(l, osm);
452 l.setFont(l.getFont().deriveFont(Font.PLAIN));
453 l.setVerticalTextPosition(JLabel.TOP);
454 l.setHorizontalAlignment(JLabel.LEFT);
455 l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
456 l.addMouseListener(new MouseAdapter(){
457 @Override public void mouseEntered(MouseEvent e) {
458 l.setBackground(SystemColor.info);
459 l.setForeground(SystemColor.infoText);
460 }
461 @Override public void mouseExited(MouseEvent e) {
462 popupSetLabelColors(l, osm);
463 }
464 @Override public void mouseClicked(MouseEvent e) {
465 DataSet ds = Main.main.getCurrentDataSet();
466 // Let the user toggle the selection
467 ds.toggleSelected(osm);
468 l.validate();
469 }
470 });
471 // Sometimes the mouseEntered event is not catched, thus the label
472 // will not be highlighted, making it confusing. The MotionListener
473 // can correct this defect.
474 l.addMouseMotionListener(new MouseMotionListener() {
475 public void mouseMoved(MouseEvent e) {
476 l.setBackground(SystemColor.info);
477 l.setForeground(SystemColor.infoText);
478 }
479 public void mouseDragged(MouseEvent e) {
480 l.setBackground(SystemColor.info);
481 l.setForeground(SystemColor.infoText);
482 }
483 });
484 return l;
485 }
486 }
487
488 /**
489 * Everything, the collector is interested of. Access must be synchronized.
490 * @author imi
491 */
492 static class MouseState {
493 Point mousePos;
494 int modifiers;
495 }
496 /**
497 * The last sent mouse movement event.
498 */
499 MouseState mouseState = new MouseState();
500
501 private AWTEventListener awtListener = new AWTEventListener() {
502 public void eventDispatched(AWTEvent event) {
503 if (event instanceof InputEvent &&
504 ((InputEvent)event).getComponent() == mv) {
505 synchronized (collector) {
506 mouseState.modifiers = ((InputEvent)event).getModifiersEx();
507 if (event instanceof MouseEvent) {
508 mouseState.mousePos = ((MouseEvent)event).getPoint();
509 }
510 collector.notify();
511 }
512 }
513 }
514 };
515
516 private MouseMotionListener mouseMotionListener = new MouseMotionListener() {
517 public void mouseMoved(MouseEvent e) {
518 synchronized (collector) {
519 mouseState.modifiers = e.getModifiersEx();
520 mouseState.mousePos = e.getPoint();
521 collector.notify();
522 }
523 }
524
525 public void mouseDragged(MouseEvent e) {
526 mouseMoved(e);
527 }
528 };
529
530 private KeyAdapter keyAdapter = new KeyAdapter() {
531 @Override public void keyPressed(KeyEvent e) {
532 synchronized (collector) {
533 mouseState.modifiers = e.getModifiersEx();
534 collector.notify();
535 }
536 }
537
538 @Override public void keyReleased(KeyEvent e) {
539 keyPressed(e);
540 }
541 };
542
543 private void registerListeners() {
544 // Listen to keyboard/mouse events for pressing/releasing alt key and
545 // inform the collector.
546 try {
547 Toolkit.getDefaultToolkit().addAWTEventListener(awtListener,
548 AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
549 } catch (SecurityException ex) {
550 mv.addMouseMotionListener(mouseMotionListener);
551 mv.addKeyListener(keyAdapter);
552 }
553 }
554
555 private void unregisterListeners() {
556 try {
557 Toolkit.getDefaultToolkit().removeAWTEventListener(awtListener);
558 } catch (SecurityException e) {
559 // Don't care, awtListener probably wasn't registered anyway
560 }
561 mv.removeMouseMotionListener(mouseMotionListener);
562 mv.removeKeyListener(keyAdapter);
563 }
564
565
566 /**
567 * Construct a new MapStatus and attach it to the map view.
568 * @param mapFrame The MapFrame the status line is part of.
569 */
570 public MapStatus(final MapFrame mapFrame) {
571 this.mv = mapFrame.mapView;
572 this.collector = new Collector(mapFrame);
573
574 lonText.addMouseListener(Main.main.menu.jumpToAct);
575 latText.addMouseListener(Main.main.menu.jumpToAct);
576
577 // Listen for mouse movements and set the position text field
578 mv.addMouseMotionListener(new MouseMotionListener(){
579 public void mouseDragged(MouseEvent e) {
580 mouseMoved(e);
581 }
582 public void mouseMoved(MouseEvent e) {
583 if (mv.center == null)
584 return;
585 // Do not update the view if ctrl is pressed.
586 if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0) {
587 CoordinateFormat mCord = CoordinateFormat.getDefaultFormat();
588 LatLon p = mv.getLatLon(e.getX(),e.getY());
589 latText.setText(p.latToString(mCord));
590 lonText.setText(p.lonToString(mCord));
591 }
592 }
593 });
594
595 setLayout(new GridBagLayout());
596 setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
597
598 add(latText, GBC.std());
599 add(lonText, GBC.std().insets(3,0,0,0));
600 add(headingText, GBC.std().insets(3,0,0,0));
601 add(angleText, GBC.std().insets(3,0,0,0));
602 add(distText, GBC.std().insets(3,0,0,0));
603
604 helpText.setEditable(false);
605 add(nameText, GBC.std().insets(3,0,0,0));
606 add(helpText, GBC.eol().insets(3,0,0,0).fill(GBC.HORIZONTAL));
607
608 // The background thread
609 thread = new Thread(collector, "Map Status Collector");
610 thread.setDaemon(true);
611 thread.start();
612 }
613
614 public String helpTopic() {
615 return "Statusline";
616 }
617
618 @Override
619 public synchronized void addMouseListener(MouseListener ml) {
620 //super.addMouseListener(ml);
621 lonText.addMouseListener(ml);
622 latText.addMouseListener(ml);
623 }
624
625 public void setHelpText(String t) {
626 helpText.setText(t);
627 helpText.setToolTipText(t);
628 }
629 public void setAngle(double a) {
630 angleText.setText(a < 0 ? "--" : Math.round(a*10)/10.0 + " °");
631 }
632 public void setHeading(double h) {
633 headingText.setText(h < 0 ? "--" : Math.round(h*10)/10.0 + " °");
634 }
635 public void setDist(double dist) {
636 distText.setText(dist < 0 ? "--" : NavigatableComponent.getDistText(dist));
637 }
638}
Note: See TracBrowser for help on using the repository browser.