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

Last change on this file since 2123 was 2109, checked in by stoecker, 15 years ago

applied #3441 - patch by xeen - improve middle click to allow better selections

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