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

Last change on this file since 2291 was 2291, checked in by Gubaer, 15 years ago

Replaced OsmPrimtive.user by setters/getters

  • Property svn:eol-style set to native
File size: 24.2 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.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
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 // 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 DataSet.fireSelectionChanged(ds.getSelected());
336 }
337
338 /**
339 * Tries to hide the given popup
340 * @param popup
341 */
342 private final void popupHidePopup() {
343 popupLabels = null;
344 if(popup == null)
345 return;
346 final Popup staticPopup = popup;
347 popup = null;
348 EventQueue.invokeLater(new Runnable(){
349 public void run() { staticPopup.hide(); }});
350 }
351
352 /**
353 * Tries to show the given popup, can be hidden using popupHideOldPopup
354 * If an old popup exists, it will be automatically hidden
355 * @param popup
356 */
357 private final void popupShowPopup(Popup newPopup, List<JLabel> lbls) {
358 final Popup staticPopup = newPopup;
359 if(this.popup != null) {
360 // If an old popup exists, remove it when the new popup has been
361 // drawn to keep flickering to a minimum
362 final Popup staticOldPopup = this.popup;
363 EventQueue.invokeLater(new Runnable(){
364 public void run() {
365 staticPopup.show();
366 staticOldPopup.hide();
367 }
368 });
369 } else {
370 // There is no old popup
371 EventQueue.invokeLater(new Runnable(){
372 public void run() { staticPopup.show(); }});
373 }
374 this.popupLabels = lbls;
375 this.popup = newPopup;
376 }
377
378 /**
379 * This method should be called if the selection may have changed from
380 * outside of this class. This is the case when CTRL is pressed and the
381 * user clicks on the map instead of the popup.
382 */
383 private final void popupUpdateLabels() {
384 if(this.popup == null || this.popupLabels == null)
385 return;
386 for(JLabel l : this.popupLabels) {
387 l.validate();
388 }
389 }
390
391 /**
392 * Sets the colors for the given label depending on the selected status of
393 * the given OsmPrimitive
394 *
395 * @param lbl The label to color
396 * @param osm The primitive to derive the colors from
397 */
398 private final void popupSetLabelColors(JLabel lbl, OsmPrimitive osm) {
399 DataSet ds = Main.main.getCurrentDataSet();
400 if(ds.isSelected(osm)) {
401 lbl.setBackground(SystemColor.textHighlight);
402 lbl.setForeground(SystemColor.textHighlightText);
403 } else {
404 lbl.setBackground(SystemColor.control);
405 lbl.setForeground(SystemColor.controlText);
406 }
407 }
408
409 /**
410 * Builds the labels with all necessary listeners for the info popup for the
411 * given OsmPrimitive
412 * @param osm The primitive to create the label for
413 * @return
414 */
415 private final JLabel popupBuildPrimitiveLabels(final OsmPrimitive osm) {
416 final StringBuilder text = new StringBuilder();
417 String name = osm.getDisplayName(DefaultNameFormatter.getInstance());
418 if (osm.isNew() || osm.isModified()) {
419 name = "<i><b>"+ name + "*</b></i>";
420 }
421 text.append(name);
422
423 if (!osm.isNew()) {
424 text.append(" [id="+osm.getId()+"]");
425 }
426
427 if(osm.getUser() != null) {
428 text.append(" [" + tr("User:") + " " + osm.getUser().getName() + "]");
429 }
430
431 for (Entry<String, String> e1 : osm.entrySet()) {
432 text.append("<br>" + e1.getKey() + "=" + e1.getValue());
433 }
434
435 final JLabel l = new JLabel(
436 "<html>" +text.toString() + "</html>",
437 ImageProvider.get(OsmPrimitiveType.from(osm)),
438 JLabel.HORIZONTAL
439 ) {
440 // This is necessary so the label updates its colors when the
441 // selection is changed from the outside
442 @Override public void validate() {
443 super.validate();
444 popupSetLabelColors(this, osm);
445 }
446 };
447 l.setOpaque(true);
448 popupSetLabelColors(l, osm);
449 l.setFont(l.getFont().deriveFont(Font.PLAIN));
450 l.setVerticalTextPosition(JLabel.TOP);
451 l.setHorizontalAlignment(JLabel.LEFT);
452 l.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
453 l.addMouseListener(new MouseAdapter(){
454 @Override public void mouseEntered(MouseEvent e) {
455 l.setBackground(SystemColor.info);
456 l.setForeground(SystemColor.infoText);
457 }
458 @Override public void mouseExited(MouseEvent e) {
459 popupSetLabelColors(l, osm);
460 }
461 @Override public void mouseClicked(MouseEvent e) {
462 DataSet ds = Main.main.getCurrentDataSet();
463 // Let the user toggle the selection
464 ds.toggleSelected(osm);
465 DataSet.fireSelectionChanged(ds.getSelected());
466 l.validate();
467 }
468 });
469 // Sometimes the mouseEntered event is not catched, thus the label
470 // will not be highlighted, making it confusing. The MotionListener
471 // can correct this defect.
472 l.addMouseMotionListener(new MouseMotionListener() {
473 public void mouseMoved(MouseEvent e) {
474 l.setBackground(SystemColor.info);
475 l.setForeground(SystemColor.infoText);
476 }
477 public void mouseDragged(MouseEvent e) {
478 l.setBackground(SystemColor.info);
479 l.setForeground(SystemColor.infoText);
480 }
481 });
482 return l;
483 }
484 }
485
486 /**
487 * Everything, the collector is interested of. Access must be synchronized.
488 * @author imi
489 */
490 class MouseState {
491 Point mousePos;
492 int modifiers;
493 }
494 /**
495 * The last sent mouse movement event.
496 */
497 MouseState mouseState = new MouseState();
498
499 /**
500 * Construct a new MapStatus and attach it to the map view.
501 * @param mapFrame The MapFrame the status line is part of.
502 */
503 public MapStatus(final MapFrame mapFrame) {
504 this.mv = mapFrame.mapView;
505
506 // Listen for mouse movements and set the position text field
507 mv.addMouseMotionListener(new MouseMotionListener(){
508 public void mouseDragged(MouseEvent e) {
509 mouseMoved(e);
510 }
511 public void mouseMoved(MouseEvent e) {
512 if (mv.center == null)
513 return;
514 // Do not update the view if ctrl is pressed.
515 if ((e.getModifiersEx() & MouseEvent.CTRL_DOWN_MASK) == 0) {
516 CoordinateFormat mCord = CoordinateFormat.getDefaultFormat();
517 LatLon p = mv.getLatLon(e.getX(),e.getY());
518 latText.setText(p.latToString(mCord));
519 lonText.setText(p.lonToString(mCord));
520 }
521 }
522 });
523
524 setLayout(new GridBagLayout());
525 setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
526
527 add(latText, GBC.std());
528 add(lonText, GBC.std().insets(3,0,0,0));
529 add(headingText, GBC.std().insets(3,0,0,0));
530 add(angleText, GBC.std().insets(3,0,0,0));
531 add(distText, GBC.std().insets(3,0,0,0));
532
533 helpText.setEditable(false);
534 add(nameText, GBC.std().insets(3,0,0,0));
535 add(helpText, GBC.eol().insets(3,0,0,0).fill(GBC.HORIZONTAL));
536
537 // The background thread
538 final Collector collector = new Collector(mapFrame);
539 thread = new Thread(collector, "Map Status Collector");
540 thread.setDaemon(true);
541 thread.start();
542
543 // Listen to keyboard/mouse events for pressing/releasing alt key and
544 // inform the collector.
545 try {
546 Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener(){
547 public void eventDispatched(AWTEvent event) {
548 if (event instanceof ComponentEvent &&
549 ((ComponentEvent)event).getComponent() == mapFrame.mapView) {
550 synchronized (collector) {
551 mouseState.modifiers = ((InputEvent)event).getModifiersEx();
552 if (event instanceof MouseEvent) {
553 mouseState.mousePos = ((MouseEvent)event).getPoint();
554 }
555 collector.notify();
556 }
557 }
558 }
559 }, AWTEvent.KEY_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
560 } catch (SecurityException ex) {
561 mapFrame.mapView.addMouseMotionListener(new MouseMotionListener() {
562 public void mouseMoved(MouseEvent e) {
563 synchronized (collector) {
564 mouseState.modifiers = e.getModifiersEx();
565 mouseState.mousePos = e.getPoint();
566 collector.notify();
567 }
568 }
569
570 public void mouseDragged(MouseEvent e) {
571 mouseMoved(e);
572 }
573 });
574
575 mapFrame.mapView.addKeyListener(new KeyAdapter() {
576 @Override public void keyPressed(KeyEvent e) {
577 synchronized (collector) {
578 mouseState.modifiers = e.getModifiersEx();
579 collector.notify();
580 }
581 }
582
583 @Override public void keyReleased(KeyEvent e) {
584 keyPressed(e);
585 }
586 });
587 }
588 }
589
590 public String helpTopic() {
591 return "Statusline";
592 }
593
594 @Override
595 public void addMouseListener(MouseListener ml) {
596 //super.addMouseListener(ml);
597 lonText.addMouseListener(ml);
598 latText.addMouseListener(ml);
599 }
600
601 public void setHelpText(String t) {
602 helpText.setText(t);
603 helpText.setToolTipText(t);
604 }
605 public void setAngle(double a) {
606 angleText.setText(a < 0 ? "--" : Math.round(a*10)/10.0 + " °");
607 }
608 public void setHeading(double h) {
609 headingText.setText(h < 0 ? "--" : Math.round(h*10)/10.0 + " °");
610 }
611 public void setDist(double dist) {
612 String text = dist > 1000 ? (Math.round(dist/100)/10.0)+" km" : Math.round(dist*10)/10.0 +" m";
613 distText.setText(dist < 0 ? "--" : text);
614 }
615}
Note: See TracBrowser for help on using the repository browser.