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

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

i18n updated, fixed files to reduce problems when applying patches, fix #4017

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