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

Last change on this file since 3141 was 2906, checked in by mjulius, 14 years ago

remove OsmPrimitive.entrySet()
using keySet()/get() or getKeys() instead

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