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

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

#close #5135 - allow undeleting without recreating object - patch by Upliner

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