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

Last change on this file since 3779 was 3754, checked in by stoecker, 13 years ago

some cleanups in help page marking

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