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

Last change on this file since 2871 was 2871, checked in by jttt, 14 years ago

Partially fix situation after last layer removal - most objects still stay in memory but at least there are less references and forgotten listeners

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