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

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

close #3516: clarify-middle-click-message.java, patch by avar

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