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

Last change on this file since 2575 was 2575, checked in by stoecker, 14 years ago

include utilsplugin, fix #4086

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