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

Last change on this file since 2127 was 2127, checked in by xeen, 15 years ago

close #3480

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