]> gitweb.fperrin.net Git - GpsPrune.git/blob - tim/prune/gui/map/MapCanvas.java
Version 17, September 2014
[GpsPrune.git] / tim / prune / gui / map / MapCanvas.java
1 package tim.prune.gui.map;
2
3 import java.awt.AlphaComposite;
4 import java.awt.BasicStroke;
5 import java.awt.BorderLayout;
6 import java.awt.Color;
7 import java.awt.Cursor;
8 import java.awt.Dimension;
9 import java.awt.FlowLayout;
10 import java.awt.FontMetrics;
11 import java.awt.Graphics;
12 import java.awt.Graphics2D;
13 import java.awt.Image;
14 import java.awt.event.ActionEvent;
15 import java.awt.event.ActionListener;
16 import java.awt.event.ItemEvent;
17 import java.awt.event.ItemListener;
18 import java.awt.event.KeyEvent;
19 import java.awt.event.KeyListener;
20 import java.awt.event.MouseEvent;
21 import java.awt.event.MouseListener;
22 import java.awt.event.MouseMotionListener;
23 import java.awt.event.MouseWheelEvent;
24 import java.awt.event.MouseWheelListener;
25 import java.awt.image.BufferedImage;
26
27 import javax.swing.BorderFactory;
28 import javax.swing.BoxLayout;
29 import javax.swing.JButton;
30 import javax.swing.JCheckBox;
31 import javax.swing.JMenuItem;
32 import javax.swing.JPanel;
33 import javax.swing.JPopupMenu;
34 import javax.swing.JSlider;
35 import javax.swing.SwingUtilities;
36 import javax.swing.event.ChangeEvent;
37 import javax.swing.event.ChangeListener;
38
39 import tim.prune.App;
40 import tim.prune.DataSubscriber;
41 import tim.prune.FunctionLibrary;
42 import tim.prune.I18nManager;
43 import tim.prune.UpdateMessageBroker;
44 import tim.prune.config.ColourScheme;
45 import tim.prune.config.Config;
46 import tim.prune.data.Checker;
47 import tim.prune.data.Coordinate;
48 import tim.prune.data.DataPoint;
49 import tim.prune.data.DoubleRange;
50 import tim.prune.data.Field;
51 import tim.prune.data.FieldList;
52 import tim.prune.data.Latitude;
53 import tim.prune.data.Longitude;
54 import tim.prune.data.MidpointData;
55 import tim.prune.data.Selection;
56 import tim.prune.data.Track;
57 import tim.prune.data.TrackInfo;
58 import tim.prune.function.compress.MarkPointsInRectangleFunction;
59 import tim.prune.function.edit.FieldEdit;
60 import tim.prune.function.edit.FieldEditList;
61 import tim.prune.gui.IconManager;
62 import tim.prune.gui.colour.PointColourer;
63 import tim.prune.tips.TipManager;
64
65 /**
66  * Class for the map canvas, to display a background map and draw on it
67  */
68 public class MapCanvas extends JPanel implements MouseListener, MouseMotionListener, DataSubscriber,
69         KeyListener, MouseWheelListener, TileConsumer
70 {
71         /** App object for callbacks */
72         private App _app = null;
73         /** Track object */
74         private Track _track = null;
75         /** TrackInfo object */
76         private TrackInfo _trackInfo = null;
77         /** Selection object */
78         private Selection _selection = null;
79         /** Object to keep track of midpoints */
80         private MidpointData _midpoints = null;
81         /** Index of point clicked at mouseDown */
82         private int _clickedPoint = -1;
83         /** Previously selected point */
84         private int _prevSelectedPoint = -1;
85         /** Tile manager */
86         private MapTileManager _tileManager = new MapTileManager(this);
87         /** Image to display */
88         private BufferedImage _mapImage = null;
89         /** Second image for drawing track (only needed for alpha blending) */
90         private BufferedImage _trackImage = null;
91         /** Slider for transparency */
92         private JSlider _transparencySlider = null;
93         /** Checkbox for scale bar */
94         private JCheckBox _scaleCheckBox = null;
95         /** Checkbox for maps */
96         private JCheckBox _mapCheckBox = null;
97         /** Checkbox for autopan */
98         private JCheckBox _autopanCheckBox = null;
99         /** Checkbox for connecting track points */
100         private JCheckBox _connectCheckBox = null;
101         /** Checkbox for enable edit mode */
102         private JCheckBox _editmodeCheckBox = null;
103         /** Right-click popup menu */
104         private JPopupMenu _popup = null;
105         /** Top component panel */
106         private JPanel _topPanel = null;
107         /** Side component panel */
108         private JPanel _sidePanel = null;
109         /** Scale bar */
110         private ScaleBar _scaleBar = null;
111         /* Data */
112         private DoubleRange _latRange = null, _lonRange = null;
113         private DoubleRange _xRange = null, _yRange = null;
114         private boolean _recalculate = false;
115         /** Flag to check bounds on next paint */
116         private boolean _checkBounds = false;
117         /** Map position */
118         private MapPosition _mapPosition = null;
119         /** coordinates of drag from point */
120         private int _dragFromX = -1, _dragFromY = -1;
121         /** coordinates of drag to point */
122         private int _dragToX = -1, _dragToY = -1;
123         /** coordinates of popup menu */
124         private int _popupMenuX = -1, _popupMenuY = -1;
125         /** Flag to prevent showing too often the error message about loading maps */
126         private boolean _shownOsmErrorAlready = false;
127         /** Current drawing mode */
128         private int _drawMode = MODE_DEFAULT;
129
130         /** Constant for click sensitivity when selecting nearest point */
131         private static final int CLICK_SENSITIVITY = 10;
132         /** Constant for pan distance from key presses */
133         private static final int PAN_DISTANCE = 20;
134         /** Constant for pan distance from autopan */
135         private static final int AUTOPAN_DISTANCE = 75;
136
137         // Colours
138         private static final Color COLOR_MESSAGES   = Color.GRAY;
139
140         // Drawing modes
141         private static final int MODE_DEFAULT = 0;
142         private static final int MODE_ZOOM_RECT = 1;
143         private static final int MODE_DRAW_POINTS_START = 2;
144         private static final int MODE_DRAW_POINTS_CONT = 3;
145         private static final int MODE_DRAG_POINT = 4;
146         private static final int MODE_CREATE_MIDPOINT = 5;
147         private static final int MODE_MARK_RECTANGLE = 6;
148
149         private static final int INDEX_UNKNOWN  = -2;
150
151
152         /**
153          * Constructor
154          * @param inApp App object for callbacks
155          * @param inTrackInfo track info object
156          */
157         public MapCanvas(App inApp, TrackInfo inTrackInfo)
158         {
159                 _app = inApp;
160                 _trackInfo = inTrackInfo;
161                 _track = inTrackInfo.getTrack();
162                 _selection = inTrackInfo.getSelection();
163                 _midpoints = new MidpointData();
164                 _mapPosition = new MapPosition();
165                 addMouseListener(this);
166                 addMouseMotionListener(this);
167                 addMouseWheelListener(this);
168                 addKeyListener(this);
169
170                 // Make listener for changes to controls
171                 ItemListener itemListener = new ItemListener() {
172                         public void itemStateChanged(ItemEvent e)
173                         {
174                                 _recalculate = true;
175                                 repaint();
176                         }
177                 };
178                 // Make special listener for changes to map checkbox
179                 ItemListener mapCheckListener = new ItemListener() {
180                         public void itemStateChanged(ItemEvent e)
181                         {
182                                 _tileManager.clearMemoryCaches();
183                                 _recalculate = true;
184                                 Config.setConfigBoolean(Config.KEY_SHOW_MAP, e.getStateChange() == ItemEvent.SELECTED);
185                                 UpdateMessageBroker.informSubscribers(); // to let menu know
186                                 // If the track is only partially visible and you turn the map off, make the track fully visible again
187                                 if (e.getStateChange() == ItemEvent.DESELECTED && _transparencySlider.getValue() < 0) {
188                                         _transparencySlider.setValue(0);
189                                 }
190                         }
191                 };
192                 _topPanel = new OverlayPanel();
193                 _topPanel.setLayout(new FlowLayout());
194                 // Make slider for transparency
195                 _transparencySlider = new JSlider(-6, 6, 0);
196                 _transparencySlider.setPreferredSize(new Dimension(100, 20));
197                 _transparencySlider.setMajorTickSpacing(1);
198                 _transparencySlider.setSnapToTicks(true);
199                 _transparencySlider.setOpaque(false);
200                 _transparencySlider.setValue(0);
201                 _transparencySlider.addChangeListener(new ChangeListener() {
202                         public void stateChanged(ChangeEvent e)
203                         {
204                                 int val = _transparencySlider.getValue();
205                                 if (val == 1 || val == -1)
206                                         _transparencySlider.setValue(0);
207                                 else {
208                                         _recalculate = true;
209                                         repaint();
210                                 }
211                         }
212                 });
213                 _transparencySlider.setFocusable(false); // stop slider from stealing keyboard focus
214                 _topPanel.add(_transparencySlider);
215                 // Add checkbox button for enabling scale bar
216                 _scaleCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.SCALEBAR_BUTTON), true);
217                 _scaleCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.SCALEBAR_BUTTON_ON));
218                 _scaleCheckBox.setOpaque(false);
219                 _scaleCheckBox.setToolTipText(I18nManager.getText("menu.map.showscalebar"));
220                 _scaleCheckBox.addItemListener(new ItemListener() {
221                         public void itemStateChanged(ItemEvent e) {
222                                 _scaleBar.setVisible(_scaleCheckBox.isSelected());
223                         }
224                 });
225                 _scaleCheckBox.setFocusable(false); // stop button from stealing keyboard focus
226                 _topPanel.add(_scaleCheckBox);
227                 // Add checkbox button for enabling maps or not
228                 _mapCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.MAP_BUTTON), false);
229                 _mapCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.MAP_BUTTON_ON));
230                 _mapCheckBox.setOpaque(false);
231                 _mapCheckBox.setToolTipText(I18nManager.getText("menu.map.showmap"));
232                 _mapCheckBox.addItemListener(mapCheckListener);
233                 _mapCheckBox.setFocusable(false); // stop button from stealing keyboard focus
234                 _topPanel.add(_mapCheckBox);
235                 // Add checkbox button for enabling autopan or not
236                 _autopanCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.AUTOPAN_BUTTON), true);
237                 _autopanCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.AUTOPAN_BUTTON_ON));
238                 _autopanCheckBox.setOpaque(false);
239                 _autopanCheckBox.setToolTipText(I18nManager.getText("menu.map.autopan"));
240                 _autopanCheckBox.addItemListener(itemListener);
241                 _autopanCheckBox.setFocusable(false); // stop button from stealing keyboard focus
242                 _topPanel.add(_autopanCheckBox);
243                 // Add checkbox button for connecting points or not
244                 _connectCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.POINTS_DISCONNECTED_BUTTON), true);
245                 _connectCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.POINTS_CONNECTED_BUTTON));
246                 _connectCheckBox.setOpaque(false);
247                 _connectCheckBox.setToolTipText(I18nManager.getText("menu.map.connect"));
248                 _connectCheckBox.addItemListener(itemListener);
249                 _connectCheckBox.setFocusable(false); // stop button from stealing keyboard focus
250                 _topPanel.add(_connectCheckBox);
251
252                 // Add checkbox button for edit mode or not
253                 _editmodeCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.EDIT_MODE_BUTTON), false);
254                 _editmodeCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.EDIT_MODE_BUTTON_ON));
255                 _editmodeCheckBox.setOpaque(false);
256                 _editmodeCheckBox.setToolTipText(I18nManager.getText("menu.map.editmode"));
257                 _editmodeCheckBox.addItemListener(itemListener);
258                 _editmodeCheckBox.setFocusable(false); // stop button from stealing keyboard focus
259                 _topPanel.add(_editmodeCheckBox);
260
261                 // Add zoom in, zoom out buttons
262                 _sidePanel = new OverlayPanel();
263                 _sidePanel.setLayout(new BoxLayout(_sidePanel, BoxLayout.Y_AXIS));
264                 JButton zoomInButton = new JButton(IconManager.getImageIcon(IconManager.ZOOM_IN_BUTTON));
265                 zoomInButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
266                 zoomInButton.setContentAreaFilled(false);
267                 zoomInButton.setToolTipText(I18nManager.getText("menu.map.zoomin"));
268                 zoomInButton.addActionListener(new ActionListener() {
269                         public void actionPerformed(ActionEvent e)
270                         {
271                                 zoomIn();
272                         }
273                 });
274                 zoomInButton.setFocusable(false); // stop button from stealing keyboard focus
275                 _sidePanel.add(zoomInButton);
276                 JButton zoomOutButton = new JButton(IconManager.getImageIcon(IconManager.ZOOM_OUT_BUTTON));
277                 zoomOutButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
278                 zoomOutButton.setContentAreaFilled(false);
279                 zoomOutButton.setToolTipText(I18nManager.getText("menu.map.zoomout"));
280                 zoomOutButton.addActionListener(new ActionListener() {
281                         public void actionPerformed(ActionEvent e)
282                         {
283                                 zoomOut();
284                         }
285                 });
286                 zoomOutButton.setFocusable(false); // stop button from stealing keyboard focus
287                 _sidePanel.add(zoomOutButton);
288
289                 // Bottom panel for scale bar
290                 _scaleBar = new ScaleBar();
291
292                 // add control panels to this one
293                 setLayout(new BorderLayout());
294                 _topPanel.setVisible(false);
295                 _sidePanel.setVisible(false);
296                 add(_topPanel, BorderLayout.NORTH);
297                 add(_sidePanel, BorderLayout.WEST);
298                 add(_scaleBar, BorderLayout.SOUTH);
299                 // Make popup menu
300                 makePopup();
301                 // Get currently selected map from Config, pass to MapTileManager
302                 _tileManager.setMapSource(Config.getConfigInt(Config.KEY_MAPSOURCE_INDEX));
303         }
304
305
306         /**
307          * Make the popup menu for right-clicking the map
308          */
309         private void makePopup()
310         {
311                 _popup = new JPopupMenu();
312                 JMenuItem zoomInItem = new JMenuItem(I18nManager.getText("menu.map.zoomin"));
313                 zoomInItem.addActionListener(new ActionListener() {
314                         public void actionPerformed(ActionEvent e)
315                         {
316                                 panMap((_popupMenuX - getWidth()/2)/2, (_popupMenuY - getHeight()/2)/2);
317                                 zoomIn();
318                         }});
319                 _popup.add(zoomInItem);
320                 JMenuItem zoomOutItem = new JMenuItem(I18nManager.getText("menu.map.zoomout"));
321                 zoomOutItem.addActionListener(new ActionListener() {
322                         public void actionPerformed(ActionEvent e)
323                         {
324                                 panMap(-(_popupMenuX - getWidth()/2), -(_popupMenuY - getHeight()/2));
325                                 zoomOut();
326                         }});
327                 _popup.add(zoomOutItem);
328                 JMenuItem zoomFullItem = new JMenuItem(I18nManager.getText("menu.map.zoomfull"));
329                 zoomFullItem.addActionListener(new ActionListener() {
330                         public void actionPerformed(ActionEvent e)
331                         {
332                                 zoomToFit();
333                                 _recalculate = true;
334                                 repaint();
335                         }});
336                 _popup.add(zoomFullItem);
337                 _popup.addSeparator();
338                 // Set background
339                 JMenuItem setMapBgItem = new JMenuItem(
340                         I18nManager.getText(FunctionLibrary.FUNCTION_SET_MAP_BG.getNameKey()));
341                 setMapBgItem.addActionListener(new ActionListener() {
342                         public void actionPerformed(ActionEvent e)
343                         {
344                                 FunctionLibrary.FUNCTION_SET_MAP_BG.begin();
345                         }});
346                 _popup.add(setMapBgItem);
347                 // new point option
348                 JMenuItem newPointItem = new JMenuItem(I18nManager.getText("menu.map.newpoint"));
349                 newPointItem.addActionListener(new ActionListener() {
350                         public void actionPerformed(ActionEvent e)
351                         {
352                                 _app.createPoint(createPointFromClick(_popupMenuX, _popupMenuY));
353                         }});
354                 _popup.add(newPointItem);
355                 // draw point series
356                 JMenuItem drawPointsItem = new JMenuItem(I18nManager.getText("menu.map.drawpoints"));
357                 drawPointsItem.addActionListener(new ActionListener() {
358                         public void actionPerformed(ActionEvent e)
359                         {
360                                 _drawMode = MODE_DRAW_POINTS_START;
361                         }
362                 });
363                 _popup.add(drawPointsItem);
364         }
365
366
367         /**
368          * Zoom to fit the current data area
369          */
370         private void zoomToFit()
371         {
372                 _latRange = _track.getLatRange();
373                 _lonRange = _track.getLonRange();
374                 _xRange = new DoubleRange(MapUtils.getXFromLongitude(_lonRange.getMinimum()),
375                         MapUtils.getXFromLongitude(_lonRange.getMaximum()));
376                 _yRange = new DoubleRange(MapUtils.getYFromLatitude(_latRange.getMinimum()),
377                         MapUtils.getYFromLatitude(_latRange.getMaximum()));
378                 _mapPosition.zoomToXY(_xRange.getMinimum(), _xRange.getMaximum(), _yRange.getMinimum(), _yRange.getMaximum(),
379                         getWidth(), getHeight());
380         }
381
382
383         /**
384          * Paint method
385          * @see java.awt.Canvas#paint(java.awt.Graphics)
386          */
387         public void paint(Graphics inG)
388         {
389                 super.paint(inG);
390                 if (_mapImage != null && (_mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())) {
391                         _mapImage = null;
392                 }
393                 if (_track.getNumPoints() > 0)
394                 {
395                         // Check for autopan if enabled / necessary
396                         if (_autopanCheckBox.isSelected())
397                         {
398                                 int selectedPoint = _selection.getCurrentPointIndex();
399                                 if (selectedPoint >= 0 && _dragFromX == -1 && selectedPoint != _prevSelectedPoint)
400                                 {
401                                         autopanToPoint(selectedPoint);
402                                 }
403                                 _prevSelectedPoint = selectedPoint;
404                         }
405
406                         // Draw the map contents if necessary
407                         if ((_mapImage == null || _recalculate))
408                         {
409                                 paintMapContents();
410                                 _scaleBar.updateScale(_mapPosition.getZoom(), _mapPosition.getYFromPixels(0, 0));
411                         }
412                         // Draw the prepared image onto the panel
413                         if (_mapImage != null) {
414                                 inG.drawImage(_mapImage, 0, 0, getWidth(), getHeight(), null);
415                         }
416
417                         switch (_drawMode)
418                         {
419                                 case MODE_DRAG_POINT:
420                                         drawDragLines(inG, _selection.getCurrentPointIndex()-1, _selection.getCurrentPointIndex()+1);
421                                         break;
422
423                                 case MODE_CREATE_MIDPOINT:
424                                         drawDragLines(inG, _clickedPoint-1, _clickedPoint);
425                                         break;
426
427                                 case MODE_ZOOM_RECT:
428                                 case MODE_MARK_RECTANGLE:
429                                         if (_dragFromX != -1 && _dragFromY != -1)
430                                         {
431                                                 // Draw the zoom rectangle if necessary
432                                                 inG.setColor(Color.RED);
433                                                 inG.drawLine(_dragFromX, _dragFromY, _dragFromX, _dragToY);
434                                                 inG.drawLine(_dragFromX, _dragFromY, _dragToX, _dragFromY);
435                                                 inG.drawLine(_dragToX, _dragFromY, _dragToX, _dragToY);
436                                                 inG.drawLine(_dragFromX, _dragToY, _dragToX, _dragToY);
437                                         }
438                                         break;
439
440                                 case MODE_DRAW_POINTS_CONT:
441                                         // draw line to mouse position to show drawing mode
442                                         inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
443                                         int prevIndex = _track.getNumPoints()-1;
444                                         int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(prevIndex));
445                                         int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(prevIndex));
446                                         inG.drawLine(px, py, _dragToX, _dragToY);
447                                         break;
448                         }
449                 }
450                 else
451                 {
452                         inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
453                         inG.fillRect(0, 0, getWidth(), getHeight());
454                         inG.setColor(COLOR_MESSAGES);
455                         inG.drawString(I18nManager.getText("display.nodata"), 50, getHeight()/2);
456                         _scaleBar.updateScale(-1, 0);
457                 }
458                 // Draw slider etc on top
459                 paintChildren(inG);
460         }
461
462         /**
463          * @return true if the currently selected point is visible, false if off-screen or nothing selected
464          */
465         private boolean isCurrentPointVisible()
466         {
467                 if (_trackInfo.getCurrentPoint() == null) {return false;}
468                 final int selectedPoint = _selection.getCurrentPointIndex();
469                 final int xFromCentre = Math.abs(_mapPosition.getXFromCentre(_track.getX(selectedPoint)));
470                 if (xFromCentre > (getWidth()/2)) {return false;}
471                 final int yFromCentre = Math.abs(_mapPosition.getYFromCentre(_track.getY(selectedPoint)));
472                 return yFromCentre < (getHeight()/2);
473         }
474
475         /**
476          * If the specified point isn't visible, pan to it
477          * @param inIndex index of selected point
478          */
479         private void autopanToPoint(int inIndex)
480         {
481                 int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inIndex));
482                 int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inIndex));
483                 int panX = 0;
484                 int panY = 0;
485                 if (px < PAN_DISTANCE) {
486                         panX = px - AUTOPAN_DISTANCE;
487                 }
488                 else if (px > (getWidth()-PAN_DISTANCE)) {
489                         panX = AUTOPAN_DISTANCE + px - getWidth();
490                 }
491                 if (py < (2*PAN_DISTANCE)) {
492                         panY = py - AUTOPAN_DISTANCE;
493                 }
494                 if (py > (getHeight()-PAN_DISTANCE)) {
495                         panY = AUTOPAN_DISTANCE + py - getHeight();
496                 }
497                 if (panX != 0 || panY != 0) {
498                         _mapPosition.pan(panX, panY);
499                 }
500         }
501
502         /**
503          * Paint the map tiles and the points on to the _mapImage
504          */
505         private void paintMapContents()
506         {
507                 if (_mapImage == null || _mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())
508                 {
509                         _mapImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
510                 }
511
512                 // Clear map
513                 Graphics g = _mapImage.getGraphics();
514                 // Clear to background
515                 g.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
516                 g.fillRect(0, 0, getWidth(), getHeight());
517
518                 // Check whether maps are on or not
519                 final boolean showMap = Config.getConfigBoolean(Config.KEY_SHOW_MAP);
520                 _mapCheckBox.setSelected(showMap);
521                 // Check whether disk cache is on or not
522                 final boolean usingDiskCache = Config.getConfigString(Config.KEY_DISK_CACHE) != null;
523                 // Show tip to recommend setting up a cache
524                 if (showMap && !usingDiskCache && Config.getConfigBoolean(Config.KEY_ONLINE_MODE))
525                 {
526                         SwingUtilities.invokeLater(new Runnable() {
527                                 public void run() {
528                                         _app.showTip(TipManager.Tip_UseAMapCache);
529                                 }
530                         });
531                 }
532
533                 // reset error message
534                 if (!showMap) {_shownOsmErrorAlready = false;}
535                 _recalculate = false;
536                 // Only get map tiles if selected
537                 if (showMap)
538                 {
539                         // init tile cacher
540                         _tileManager.centreMap(_mapPosition.getZoom(), _mapPosition.getCentreTileX(), _mapPosition.getCentreTileY());
541
542                         boolean loadingFailed = false;
543                         if (_mapImage == null) return;
544
545                         if (_tileManager.isOverzoomed())
546                         {
547                                 // display overzoom message
548                                 g.setColor(COLOR_MESSAGES);
549                                 g.drawString(I18nManager.getText("map.overzoom"), 50, getHeight()/2);
550                         }
551                         else
552                         {
553                                 int numLayers = _tileManager.getNumLayers();
554                                 // Loop over tiles drawing each one
555                                 int[] tileIndices = _mapPosition.getTileIndices(getWidth(), getHeight());
556                                 int[] pixelOffsets = _mapPosition.getDisplayOffsets(getWidth(), getHeight());
557                                 for (int tileX = tileIndices[0]; tileX <= tileIndices[1] && !loadingFailed; tileX++)
558                                 {
559                                         int x = (tileX - tileIndices[0]) * 256 - pixelOffsets[0];
560                                         for (int tileY = tileIndices[2]; tileY <= tileIndices[3]; tileY++)
561                                         {
562                                                 int y = (tileY - tileIndices[2]) * 256 - pixelOffsets[1];
563                                                 // Loop over layers
564                                                 for (int l=0; l<numLayers; l++)
565                                                 {
566                                                         Image image = _tileManager.getTile(l, tileX, tileY, true);
567                                                         if (image != null) {
568                                                                 g.drawImage(image, x, y, 256, 256, null);
569                                                         }
570                                                 }
571                                         }
572                                 }
573
574                                 // Make maps brighter / fainter according to slider
575                                 final int brightnessIndex = Math.max(1, _transparencySlider.getValue()) - 1;
576                                 if (brightnessIndex > 0)
577                                 {
578                                         final int[] alphas = {0, 40, 80, 120, 160, 210};
579                                         Color bgColor = Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND);
580                                         bgColor = new Color(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), alphas[brightnessIndex]);
581                                         g.setColor(bgColor);
582                                         g.fillRect(0, 0, getWidth(), getHeight());
583                                 }
584                         }
585                 }
586
587                 // Work out track opacity according to slider
588                 final float[] opacities = {1.0f, 0.75f, 0.5f, 0.3f, 0.15f, 0.0f};
589                 float trackOpacity = 1.0f;
590                 if (_transparencySlider.getValue() < 0) {
591                         trackOpacity = opacities[-1 - _transparencySlider.getValue()];
592                 }
593
594                 if (trackOpacity > 0.0f)
595                 {
596                         // Paint the track points on top
597                         int pointsPainted = 1;
598                         try
599                         {
600                                 if (trackOpacity > 0.9f)
601                                 {
602                                         // Track is fully opaque, just draw it directly
603                                         pointsPainted = paintPoints(g);
604                                         _trackImage = null;
605                                 }
606                                 else
607                                 {
608                                         // Track is partly transparent, so use a separate BufferedImage
609                                         if (_trackImage == null || _trackImage.getWidth() != getWidth() || _trackImage.getHeight() != getHeight())
610                                         {
611                                                 _trackImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
612                                         }
613                                         // Clear to transparent
614                                         Graphics2D gTrack = _trackImage.createGraphics();
615                                         gTrack.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
616                                         gTrack.fillRect(0, 0, getWidth(), getHeight());
617                                         gTrack.setPaintMode();
618                                         // Draw the track onto this separate image
619                                         pointsPainted = paintPoints(gTrack);
620                                         ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, trackOpacity));
621                                         g.drawImage(_trackImage, 0, 0, null);
622                                 }
623                         }
624                         catch (NullPointerException npe) {} // ignore, probably due to data being changed during drawing
625                         catch (ArrayIndexOutOfBoundsException obe) {} // also ignore
626
627                         // Zoom to fit if no points found
628                         if (pointsPainted <= 0 && _checkBounds)
629                         {
630                                 zoomToFit();
631                                 _recalculate = true;
632                                 repaint();
633                         }
634                 }
635
636                 // free g
637                 g.dispose();
638
639                 _checkBounds = false;
640                 // enable / disable transparency slider
641                 _transparencySlider.setEnabled(showMap);
642         }
643
644
645         /**
646          * Paint the points using the given graphics object
647          * @param inG Graphics object to use for painting
648          * @return number of points painted, if any
649          */
650         private int paintPoints(Graphics inG)
651         {
652                 // Set up colours
653                 final ColourScheme cs = Config.getColourScheme();
654                 final Color pointColour  = cs.getColour(ColourScheme.IDX_POINT);
655                 final Color rangeColour  = cs.getColour(ColourScheme.IDX_SELECTION);
656                 final Color currentColour = cs.getColour(ColourScheme.IDX_PRIMARY);
657                 final Color secondColour = cs.getColour(ColourScheme.IDX_SECONDARY);
658                 final Color textColour   = cs.getColour(ColourScheme.IDX_TEXT);
659                 final PointColourer pointColourer = _app.getPointColourer();
660
661                 final int winWidth  = getWidth();
662                 final int winHeight = getHeight();
663                 final int halfWinWidth  = winWidth / 2;
664                 final int halfWinHeight = winHeight / 2;
665
666                 final int numPoints = _track.getNumPoints();
667                 final int[] xPixels = new int[numPoints];
668                 final int[] yPixels = new int[numPoints];
669
670                 // try to set line width for painting
671                 if (inG instanceof Graphics2D)
672                 {
673                         int lineWidth = Config.getConfigInt(Config.KEY_LINE_WIDTH);
674                         if (lineWidth < 1 || lineWidth > 4) {lineWidth = 2;}
675                         ((Graphics2D) inG).setStroke(new BasicStroke(lineWidth));
676                 }
677                 int pointsPainted = 0;
678                 // draw track points
679                 inG.setColor(pointColour);
680                 int prevX = -1, prevY = -1;
681                 boolean connectPoints = _connectCheckBox.isSelected();
682                 boolean prevPointVisible = false, currPointVisible = false;
683                 boolean anyWaypoints = false;
684                 boolean isWaypoint = false;
685                 for (int i=0; i<numPoints; i++)
686                 {
687                         // Calculate pixel position of point from its x, y coordinates
688                         int px = halfWinWidth  + _mapPosition.getXFromCentre(_track.getX(i));
689                         int py = halfWinHeight + _mapPosition.getYFromCentre(_track.getY(i));
690                         px = wrapLongitudeValue(px, winWidth, _mapPosition.getZoom());
691                         // Remember these calculated pixel values so they don't have to be recalculated
692                         xPixels[i] = px; yPixels[i] = py;
693
694                         currPointVisible = px >= 0 && px < winWidth && py >= 0 && py < winHeight;
695                         isWaypoint = _track.getPoint(i).isWaypoint();
696                         anyWaypoints = anyWaypoints || isWaypoint;
697                         if (!isWaypoint)
698                         {
699                                 if (currPointVisible || prevPointVisible)
700                                 {
701                                         // For track points, work out which colour to use
702                                         if (_track.getPoint(i).getDeleteFlag()) {
703                                                 inG.setColor(currentColour);
704                                         }
705                                         else if (pointColourer != null)
706                                         {  // use the point colourer if there is one
707                                                 Color trackColour = pointColourer.getColour(i);
708                                                 inG.setColor(trackColour);
709                                         }
710                                         else
711                                         {
712                                                 inG.setColor(pointColour);
713                                         }
714
715                                         // Draw rectangle for track point if it's visible
716                                         if (currPointVisible)
717                                         {
718                                                 inG.drawRect(px-2, py-2, 3, 3);
719                                                 pointsPainted++;
720                                         }
721                                 }
722
723                                 // Connect track points if either of them are visible
724                                 if (connectPoints && !(prevX == -1 && prevY == -1)
725                                  && !_track.getPoint(i).getSegmentStart())
726                                 {
727                                         inG.drawLine(prevX, prevY, px, py);
728                                 }
729                                 prevX = px; prevY = py;
730                         }
731                         prevPointVisible = currPointVisible;
732                 }
733
734                 // Loop over points, just drawing blobs for waypoints
735                 inG.setColor(textColour);
736                 FontMetrics fm = inG.getFontMetrics();
737                 int nameHeight = fm.getHeight();
738                 if (anyWaypoints)
739                 {
740                         int numWaypoints = 0;
741                         for (int i=0; i<_track.getNumPoints(); i++)
742                         {
743                                 if (_track.getPoint(i).isWaypoint())
744                                 {
745                                         int px = xPixels[i];
746                                         int py = yPixels[i];
747                                         if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
748                                         {
749                                                 inG.fillRect(px-3, py-3, 6, 6);
750                                                 pointsPainted++;
751                                                 numWaypoints++;
752                                         }
753                                 }
754                         }
755                         // Take more care with waypoint names if less than 100 are visible
756                         final int numNameSteps = (numWaypoints > 100 ? 1 : 4);
757                         final int numPointSteps = (numWaypoints > 1000 ? 2 : 1);
758
759                         // Loop over points again, now draw names for waypoints
760                         int[] nameXs = {0, 0, 0, 0};
761                         int[] nameYs = {0, 0, 0, 0};
762                         for (int i=0; i<_track.getNumPoints(); i += numPointSteps)
763                         {
764                                 if (_track.getPoint(i).isWaypoint())
765                                 {
766                                         int px = xPixels[i];
767                                         int py = yPixels[i];
768                                         if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
769                                         {
770                                                 // Figure out where to draw waypoint name so it doesn't obscure track
771                                                 String waypointName = _track.getPoint(i).getWaypointName();
772                                                 int nameWidth = fm.stringWidth(waypointName);
773                                                 boolean drawnName = false;
774                                                 // Make arrays for coordinates right left up down
775                                                 nameXs[0] = px + 2; nameXs[1] = px - nameWidth - 2;
776                                                 nameXs[2] = nameXs[3] = px - nameWidth/2;
777                                                 nameYs[0] = nameYs[1] = py + (nameHeight/2);
778                                                 nameYs[2] = py - 2; nameYs[3] = py + nameHeight + 2;
779                                                 for (int extraSpace = 0; extraSpace < numNameSteps && !drawnName; extraSpace++)
780                                                 {
781                                                         // Shift arrays for coordinates right left up down
782                                                         nameXs[0] += 3; nameXs[1] -= 3;
783                                                         nameYs[2] -= 3; nameYs[3] += 3;
784                                                         // Check each direction in turn right left up down
785                                                         for (int a=0; a<4; a++)
786                                                         {
787                                                                 if (nameXs[a] > 0 && (nameXs[a] + nameWidth) < winWidth
788                                                                         && nameYs[a] < winHeight && (nameYs[a] - nameHeight) > 0
789                                                                         && !MapUtils.overlapsPoints(_mapImage, nameXs[a], nameYs[a], nameWidth, nameHeight, textColour))
790                                                                 {
791                                                                         // Found a rectangle to fit - draw name here and quit
792                                                                         inG.drawString(waypointName, nameXs[a], nameYs[a]);
793                                                                         drawnName = true;
794                                                                         break;
795                                                                 }
796                                                         }
797                                                 }
798                                         }
799                                 }
800                         }
801                 }
802                 // Loop over points, drawing blobs for photo / audio points
803                 inG.setColor(secondColour);
804                 for (int i=0; i<_track.getNumPoints(); i++)
805                 {
806                         if (_track.getPoint(i).hasMedia())
807                         {
808                                 int px = xPixels[i];
809                                 int py = yPixels[i];
810                                 if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
811                                 {
812                                         inG.drawRect(px-1, py-1, 2, 2);
813                                         inG.drawRect(px-2, py-2, 4, 4);
814                                         pointsPainted++;
815                                 }
816                         }
817                 }
818
819                 // Draw selected range
820                 if (_selection.hasRangeSelected())
821                 {
822                         inG.setColor(rangeColour);
823                         for (int i=_selection.getStart(); i<=_selection.getEnd(); i++)
824                         {
825                                 int px = xPixels[i];
826                                 int py = yPixels[i];
827                                 inG.drawRect(px-1, py-1, 2, 2);
828                         }
829                 }
830
831                 // Draw crosshairs at selected point
832                 int selectedPoint = _selection.getCurrentPointIndex();
833                 if (selectedPoint >= 0)
834                 {
835                         int px = xPixels[selectedPoint];
836                         int py = yPixels[selectedPoint];
837                         inG.setColor(currentColour);
838                         // crosshairs
839                         inG.drawLine(px, 0, px, winHeight);
840                         inG.drawLine(0, py, winWidth, py);
841                 }
842                 // Return the number of points painted
843                 return pointsPainted;
844         }
845
846         /**
847          * Wrap the given pixel value if appropriate and possible
848          * @param inPx Pixel x coordinate
849          * @param inWinWidth window width in pixels
850          * @param inZoom zoom level
851          * @return modified pixel x coordinate
852          */
853         private static int wrapLongitudeValue(int inPx, int inWinWidth, int inZoom)
854         {
855                 if (inPx > inWinWidth)
856                 {
857                         // Pixel is too far right, could we wrap it back onto the screen?
858                         int px = inPx;
859                         while (px > inWinWidth) {
860                                 px -= (256 << inZoom);
861                         }
862                         if (px >= 0) {
863                                 return px; // successfully wrapped back onto the screen
864                         }
865                 }
866                 else if (inPx < 0)
867                 {
868                         // Pixel is too far left, could we wrap it back onto the screen?
869                         int px = inPx;
870                         while (px < 0) {
871                                 px += (256 << inZoom);
872                         }
873                         if (px < inWinWidth) {
874                                 return px; // successfully wrapped back onto the screen
875                         }
876                 }
877                 // Either it's already on the screen or couldn't be wrapped
878                 return inPx;
879         }
880
881         /**
882          * Draw the lines while dragging a point
883          * @param inG graphics object
884          * @param inPrevIndex index of point to draw from
885          * @param inNextIndex index of point to draw to
886          */
887         private void drawDragLines(Graphics inG, int inPrevIndex, int inNextIndex)
888         {
889                 inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
890                 // line from prev point to cursor
891                 if (inPrevIndex > -1 && !_track.getPoint(inPrevIndex+1).getSegmentStart())
892                 {
893                         final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inPrevIndex));
894                         final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inPrevIndex));
895                         inG.drawLine(px, py, _dragToX, _dragToY);
896                 }
897                 if (inNextIndex < _track.getNumPoints() && !_track.getPoint(inNextIndex).getSegmentStart())
898                 {
899                         final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inNextIndex));
900                         final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inNextIndex));
901                         inG.drawLine(px, py, _dragToX, _dragToY);
902                 }
903         }
904
905         /**
906          * Inform that tiles have been updated and the map can be repainted
907          * @param inIsOk true if data loaded ok, false for error
908          */
909         public void tilesUpdated(boolean inIsOk)
910         {
911                 synchronized(this)
912                 {
913                         // Show message if loading failed (but not too many times)
914                         if (!inIsOk && !_shownOsmErrorAlready && _mapCheckBox.isSelected())
915                         {
916                                 _shownOsmErrorAlready = true;
917                                 // use separate thread to show message about failing to load osm images
918                                 new Thread(new Runnable() {
919                                         public void run() {
920                                                 try {Thread.sleep(500);} catch (InterruptedException ie) {}
921                                                 _app.showErrorMessage("error.osmimage.dialogtitle", "error.osmimage.failed");
922                                         }
923                                 }).start();
924                         }
925                         _recalculate = true;
926                         repaint();
927                 }
928         }
929
930         /**
931          * Zoom out, if not already at minimum zoom
932          */
933         public void zoomOut()
934         {
935                 _mapPosition.zoomOut();
936                 _recalculate = true;
937                 repaint();
938         }
939
940         /**
941          * Zoom in, if not already at maximum zoom
942          */
943         public void zoomIn()
944         {
945                 // See if selected point is currently visible, if so (and autopan on) then autopan after zoom to keep it visible
946                 boolean wasVisible = _autopanCheckBox.isSelected() && isCurrentPointVisible();
947                 _mapPosition.zoomIn();
948                 if (wasVisible && !isCurrentPointVisible()) {
949                         autopanToPoint(_selection.getCurrentPointIndex());
950                 }
951                 _recalculate = true;
952                 repaint();
953         }
954
955         /**
956          * Pan map
957          * @param inDeltaX x shift
958          * @param inDeltaY y shift
959          */
960         public void panMap(int inDeltaX, int inDeltaY)
961         {
962                 _mapPosition.pan(inDeltaX, inDeltaY);
963                 _recalculate = true;
964                 repaint();
965         }
966
967         /**
968          * Create a DataPoint object from the given click coordinates
969          * @param inX x coordinate of click
970          * @param inY y coordinate of click
971          * @return DataPoint with given coordinates and no altitude
972          */
973         private DataPoint createPointFromClick(int inX, int inY)
974         {
975                 double lat = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(inY, getHeight()));
976                 double lon = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(inX, getWidth()));
977                 return new DataPoint(new Latitude(lat, Coordinate.FORMAT_NONE),
978                         new Longitude(lon, Coordinate.FORMAT_NONE), null);
979         }
980
981         /**
982          * Move a DataPoint object to the given mouse coordinates
983          * @param startX start x coordinate of mouse
984          * @param startY start y coordinate of mouse
985          * @param endX end x coordinate of mouse
986          * @param endY end y coordinate of mouse
987          */
988         private void movePointToMouse(int startX, int startY, int endX, int endY )
989         {
990                 double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(startY, getHeight()));
991                 double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(startX, getWidth()));
992                 double lat_delta = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(endY, getHeight())) - lat1;
993                 double lon_delta = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(endX, getWidth())) - lon1;
994
995                 DataPoint point = _trackInfo.getCurrentPoint();
996                 if (point == null) {
997                         return;
998                 }
999
1000                 // Make lists for edit and undo, and add each changed field in turn
1001                 FieldEditList editList = new FieldEditList();
1002                 FieldEditList undoList = new FieldEditList();
1003
1004                 // Check field list
1005                 FieldList fieldList = _track.getFieldList();
1006                 int numFields = fieldList.getNumFields();
1007                 for (int i=0; i<numFields; i++)
1008                 {
1009                         Field field = fieldList.getField(i);
1010                         if (field == Field.LATITUDE) {
1011                                 editList.addEdit(new FieldEdit(field, Double.toString(point.getLatitude().getDouble() + lat_delta)));
1012                                 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LATITUDE)));
1013                         }
1014                         else if (field == Field.LONGITUDE) {
1015                                 editList.addEdit(new FieldEdit(field, Double.toString(point.getLongitude().getDouble() + lon_delta)));
1016                                 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LONGITUDE)));
1017                         }
1018                 }
1019                 _app.completePointEdit(editList, undoList);
1020         }
1021
1022
1023         /**
1024          * @see javax.swing.JComponent#getMinimumSize()
1025          */
1026         public Dimension getMinimumSize()
1027         {
1028                 final Dimension minSize = new Dimension(512, 300);
1029                 return minSize;
1030         }
1031
1032         /**
1033          * @see javax.swing.JComponent#getPreferredSize()
1034          */
1035         public Dimension getPreferredSize()
1036         {
1037                 return getMinimumSize();
1038         }
1039
1040
1041         /**
1042          * Respond to mouse click events
1043          * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1044          */
1045         public void mouseClicked(MouseEvent inE)
1046         {
1047                 if (_track != null && _track.getNumPoints() > 0)
1048                 {
1049                          // select point if it's a left-click
1050                         if (!inE.isMetaDown())
1051                         {
1052                                 if (inE.getClickCount() == 1)
1053                                 {
1054                                         // single click
1055                                         if (_drawMode == MODE_DEFAULT)
1056                                         {
1057                                                 int pointIndex = _clickedPoint;
1058                                                 if (pointIndex == INDEX_UNKNOWN)
1059                                                 {
1060                                                         // index hasn't been calculated yet
1061                                                         pointIndex = _track.getNearestPointIndex(
1062                                                          _mapPosition.getXFromPixels(inE.getX(), getWidth()),
1063                                                          _mapPosition.getYFromPixels(inE.getY(), getHeight()),
1064                                                          _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY), false);
1065                                                 }
1066                                                 // Extend selection for shift-click
1067                                                 if (inE.isShiftDown()) {
1068                                                         _trackInfo.extendSelection(pointIndex);
1069                                                 }
1070                                                 else {
1071                                                         _trackInfo.selectPoint(pointIndex);
1072                                                 }
1073                                         }
1074                                         else if (_drawMode == MODE_DRAW_POINTS_START)
1075                                         {
1076                                                 _app.createPoint(createPointFromClick(inE.getX(), inE.getY()));
1077                                                 _dragToX = inE.getX();
1078                                                 _dragToY = inE.getY();
1079                                                 _drawMode = MODE_DRAW_POINTS_CONT;
1080                                         }
1081                                         else if (_drawMode == MODE_DRAW_POINTS_CONT)
1082                                         {
1083                                                 DataPoint point = createPointFromClick(inE.getX(), inE.getY());
1084                                                 _app.createPoint(point, false); // not a new segment
1085                                         }
1086                                 }
1087                                 else if (inE.getClickCount() == 2)
1088                                 {
1089                                         // double click
1090                                         if (_drawMode == MODE_DEFAULT) {
1091                                                 panMap(inE.getX() - getWidth()/2, inE.getY() - getHeight()/2);
1092                                                 zoomIn();
1093                                         }
1094                                         else if (_drawMode == MODE_DRAW_POINTS_START || _drawMode == MODE_DRAW_POINTS_CONT) {
1095                                                 _drawMode = MODE_DEFAULT;
1096                                         }
1097                                 }
1098                         }
1099                         else
1100                         {
1101                                 // show the popup menu for right-clicks
1102                                 _popupMenuX = inE.getX();
1103                                 _popupMenuY = inE.getY();
1104                                 _popup.show(this, _popupMenuX, _popupMenuY);
1105                         }
1106                 }
1107                 // Reset app mode
1108                 _app.setCurrentMode(App.AppMode.NORMAL);
1109                 if (_drawMode == MODE_MARK_RECTANGLE) _drawMode = MODE_DEFAULT;
1110         }
1111
1112         /**
1113          * Ignore mouse enter events
1114          * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1115          */
1116         public void mouseEntered(MouseEvent inE)
1117         {
1118                 // ignore
1119         }
1120
1121         /**
1122          * Ignore mouse exited events
1123          * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1124          */
1125         public void mouseExited(MouseEvent inE)
1126         {
1127                 // ignore
1128         }
1129
1130         /**
1131          * React to mouse pressed events to initiate a point drag
1132          * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1133          */
1134         public void mousePressed(MouseEvent inE)
1135         {
1136                 _clickedPoint = INDEX_UNKNOWN;
1137                 if (_track == null || _track.getNumPoints() <= 0)
1138                         return;
1139                 if (!inE.isMetaDown())
1140                 {
1141                         // Left mouse drag - check if point is near; if so select it for dragging
1142                         if (_drawMode == MODE_DEFAULT)
1143                         {
1144                                 /* Drag points if edit mode is enabled OR ALT is pressed */
1145                                 if (_editmodeCheckBox.isSelected() || inE.isAltDown() || inE.isAltGraphDown())
1146                                 {
1147                                         final double clickX = _mapPosition.getXFromPixels(inE.getX(), getWidth());
1148                                         final double clickY = _mapPosition.getYFromPixels(inE.getY(), getHeight());
1149                                         final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1150                                         _clickedPoint = _track.getNearestPointIndex(clickX, clickY, clickSens, false);
1151
1152                                         if (_clickedPoint >= 0)
1153                                         {
1154                                                 // TODO: maybe use another color of the cross or remove the cross while dragging???
1155
1156                                                 _trackInfo.selectPoint(_clickedPoint);
1157                                                 if (_trackInfo.getCurrentPoint() != null)
1158                                                 {
1159                                                         _drawMode = MODE_DRAG_POINT;
1160                                                         _dragFromX = _dragToX = inE.getX();
1161                                                         _dragFromY = _dragToY = inE.getY();
1162                                                 }
1163                                         }
1164                                         else
1165                                         {
1166                                                 // Not a click on a point, so check half-way between two (connected) trackpoints
1167                                                 int midpointIndex = _midpoints.getNearestPointIndex(clickX, clickY, clickSens);
1168                                                 if (midpointIndex > 0)
1169                                                 {
1170                                                         _drawMode = MODE_CREATE_MIDPOINT;
1171                                                         _clickedPoint = midpointIndex;
1172                                                         _dragFromX = _dragToX = inE.getX();
1173                                                         _dragFromY = _dragToY = inE.getY();
1174                                                 }
1175                                         }
1176                                 }
1177                         }
1178                 }
1179                 // else right-press ignored
1180         }
1181
1182         /**
1183          * Respond to mouse released events
1184          * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1185          */
1186         public void mouseReleased(MouseEvent inE)
1187         {
1188                 _recalculate = true;
1189
1190                 if (_drawMode == MODE_DRAG_POINT)
1191                 {
1192                         if (Math.abs(_dragToX - _dragFromX) > 2
1193                                 || Math.abs(_dragToY - _dragFromY) > 2)
1194                         {
1195                                 movePointToMouse(_dragFromX, _dragFromY, _dragToX, _dragToY );
1196                         }
1197                         _drawMode = MODE_DEFAULT;
1198                 }
1199                 else if (_drawMode == MODE_CREATE_MIDPOINT)
1200                 {
1201                         _drawMode = MODE_DEFAULT;
1202                         _app.createPoint(createPointFromClick(_dragToX, _dragToY), _clickedPoint);
1203                 }
1204                 else if (_drawMode == MODE_ZOOM_RECT)
1205                 {
1206                         if (Math.abs(_dragToX - _dragFromX) > 20
1207                          && Math.abs(_dragToY - _dragFromY) > 20)
1208                         {
1209                                 _mapPosition.zoomToPixels(_dragFromX, _dragToX, _dragFromY, _dragToY, getWidth(), getHeight());
1210                         }
1211                         _drawMode = MODE_DEFAULT;
1212                 }
1213                 else if (_drawMode == MODE_MARK_RECTANGLE)
1214                 {
1215                         // Reset app mode
1216                         _app.setCurrentMode(App.AppMode.NORMAL);
1217                         _drawMode = MODE_DEFAULT;
1218                         // Call a function to mark the points
1219                         MarkPointsInRectangleFunction marker = (MarkPointsInRectangleFunction) FunctionLibrary.FUNCTION_MARK_IN_RECTANGLE;
1220                         double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragFromX, getWidth()));
1221                         double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragFromY, getHeight()));
1222                         double lon2 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragToX, getWidth()));
1223                         double lat2 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragToY, getHeight()));
1224                         // Invalidate rectangle if pixel coords are (-1,-1)
1225                         if (_dragFromX < 0 || _dragFromY < 0) {
1226                                 lon1 = lon2;
1227                                 lat1 = lat2;
1228                         }
1229                         marker.setRectCoords(lon1, lat1, lon2, lat2);
1230                         marker.begin();
1231                 }
1232                 _dragFromX = _dragFromY = -1;
1233                 repaint();
1234         }
1235
1236         /**
1237          * Respond to mouse drag events
1238          * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1239          */
1240         public void mouseDragged(MouseEvent inE)
1241         {
1242                 if (!inE.isMetaDown())
1243                 {
1244                         // Left mouse drag - either drag the point or pan the map
1245                         if (_drawMode == MODE_DRAG_POINT || _drawMode == MODE_CREATE_MIDPOINT)
1246                         {
1247                                 // move point
1248                                 _dragToX = inE.getX();
1249                                 _dragToY = inE.getY();
1250                                 _recalculate = true;
1251                                 repaint();
1252                         }
1253                         else if (_drawMode == MODE_MARK_RECTANGLE)
1254                         {
1255                                 // draw a rectangle for marking points
1256                                 if (_dragFromX == -1) {
1257                                         _dragFromX = inE.getX();
1258                                         _dragFromY = inE.getY();
1259                                 }
1260                                 _dragToX = inE.getX();
1261                                 _dragToY = inE.getY();
1262                                 repaint();
1263                         }
1264                         else
1265                         {
1266                                 // regular left-drag pans map by appropriate amount
1267                                 if (_dragFromX != -1)
1268                                 {
1269                                         panMap(_dragFromX - inE.getX(), _dragFromY - inE.getY());
1270                                 }
1271                                 _dragFromX = _dragToX = inE.getX();
1272                                 _dragFromY = _dragToY = inE.getY();
1273                         }
1274                 }
1275                 else
1276                 {
1277                         // Right-click and drag - update rectangle
1278                         _drawMode = MODE_ZOOM_RECT;
1279                         if (_dragFromX == -1) {
1280                                 _dragFromX = inE.getX();
1281                                 _dragFromY = inE.getY();
1282                         }
1283                         _dragToX = inE.getX();
1284                         _dragToY = inE.getY();
1285                         repaint();
1286                 }
1287         }
1288
1289         /**
1290          * Respond to mouse move events without button pressed
1291          * @param inEvent ignored
1292          */
1293         public void mouseMoved(MouseEvent inEvent)
1294         {
1295                 boolean useCrosshairs = false;
1296                 boolean useResize     = false;
1297                 // Ignore unless we're drawing points
1298                 if (_drawMode == MODE_DRAW_POINTS_CONT)
1299                 {
1300                         _dragToX = inEvent.getX();
1301                         _dragToY = inEvent.getY();
1302                         repaint();
1303                 }
1304                 else if (_drawMode == MODE_MARK_RECTANGLE) {
1305                         useResize = true;
1306                 }
1307                 else if (_editmodeCheckBox.isSelected() || inEvent.isAltDown() || inEvent.isAltGraphDown())
1308                 {
1309                         // Try to find a point or a midpoint at this location, and if there is one
1310                         // then change the cursor to crosshairs
1311                         final double clickX = _mapPosition.getXFromPixels(inEvent.getX(), getWidth());
1312                         final double clickY = _mapPosition.getYFromPixels(inEvent.getY(), getHeight());
1313                         final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1314                         useCrosshairs = (_track.getNearestPointIndex(clickX, clickY, clickSens, false) >= 0
1315                                 || _midpoints.getNearestPointIndex(clickX, clickY, clickSens) >= 0
1316                         );
1317                 }
1318                 if (useCrosshairs && !isCursorSet()) {
1319                         setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
1320                 }
1321                 else if (useResize && !isCursorSet()) {
1322                         setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1323                 }
1324                 else if (!useCrosshairs && !useResize && isCursorSet()) {
1325                         setCursor(null);
1326                 }
1327         }
1328
1329         /**
1330          * Respond to status bar message from broker
1331          * @param inMessage message, ignored
1332          */
1333         public void actionCompleted(String inMessage)
1334         {
1335                 // ignore
1336         }
1337
1338         /**
1339          * Respond to data updated message from broker
1340          * @param inUpdateType type of update
1341          */
1342         public void dataUpdated(byte inUpdateType)
1343         {
1344                 _recalculate = true;
1345                 if ((inUpdateType & DataSubscriber.DATA_ADDED_OR_REMOVED) > 0) {
1346                         _checkBounds = true;
1347                 }
1348                 if ((inUpdateType & DataSubscriber.MAPSERVER_CHANGED) > 0) {
1349                         // Get the selected map source index and pass to tile manager
1350                         _tileManager.setMapSource(Config.getConfigInt(Config.KEY_MAPSOURCE_INDEX));
1351                 }
1352                 if ((inUpdateType & (DataSubscriber.DATA_ADDED_OR_REMOVED + DataSubscriber.DATA_EDITED)) > 0) {
1353                         _midpoints.updateData(_track);
1354                 }
1355                 // See if rect mode has been activated
1356                 if (_app.getCurrentMode() == App.AppMode.DRAWRECT)
1357                 {
1358                         _drawMode = MODE_MARK_RECTANGLE;
1359                         if (!isCursorSet()) {
1360                                 setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1361                         }
1362                 }
1363                 repaint();
1364                 // enable or disable components
1365                 boolean hasData = _track.getNumPoints() > 0;
1366                 _topPanel.setVisible(hasData);
1367                 _sidePanel.setVisible(hasData);
1368                 // grab focus for the key presses
1369                 this.requestFocus();
1370         }
1371
1372         /**
1373          * Respond to key presses on the map canvas
1374          * @param inE key event
1375          */
1376         public void keyPressed(KeyEvent inE)
1377         {
1378                 int code = inE.getKeyCode();
1379                 int currPointIndex = _selection.getCurrentPointIndex();
1380                 // Check for Ctrl key (for Linux/Win) or meta key (Clover key for Mac)
1381                 if (inE.isControlDown() || inE.isMetaDown())
1382                 {
1383                         // Shift as well makes things faster
1384                         final int pointIncrement = inE.isShiftDown()?3:1;
1385                         // Check for arrow keys to zoom in and out
1386                         if (code == KeyEvent.VK_UP)
1387                                 zoomIn();
1388                         else if (code == KeyEvent.VK_DOWN)
1389                                 zoomOut();
1390                         // Key nav for next/prev point
1391                         else if (code == KeyEvent.VK_LEFT && currPointIndex > 0)
1392                                 _trackInfo.incrementPointIndex(-pointIncrement);
1393                         else if (code == KeyEvent.VK_RIGHT)
1394                                 _trackInfo.incrementPointIndex(pointIncrement);
1395                         else if (code == KeyEvent.VK_PAGE_UP)
1396                                 _trackInfo.selectPoint(Checker.getPreviousSegmentStart(
1397                                         _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1398                         else if (code == KeyEvent.VK_PAGE_DOWN)
1399                                 _trackInfo.selectPoint(Checker.getNextSegmentStart(
1400                                         _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1401                         // Check for home and end
1402                         else if (code == KeyEvent.VK_HOME)
1403                                 _trackInfo.selectPoint(0);
1404                         else if (code == KeyEvent.VK_END)
1405                                 _trackInfo.selectPoint(_trackInfo.getTrack().getNumPoints()-1);
1406                 }
1407                 else
1408                 {
1409                         // Check for arrow keys to pan
1410                         int upwardsPan = 0;
1411                         if (code == KeyEvent.VK_UP)
1412                                 upwardsPan = -PAN_DISTANCE;
1413                         else if (code == KeyEvent.VK_DOWN)
1414                                 upwardsPan = PAN_DISTANCE;
1415                         int rightwardsPan = 0;
1416                         if (code == KeyEvent.VK_RIGHT)
1417                                 rightwardsPan = PAN_DISTANCE;
1418                         else if (code == KeyEvent.VK_LEFT)
1419                                 rightwardsPan = -PAN_DISTANCE;
1420                         panMap(rightwardsPan, upwardsPan);
1421                         // Check for escape
1422                         if (code == KeyEvent.VK_ESCAPE)
1423                                 _drawMode = MODE_DEFAULT;
1424                         // Check for backspace key to delete current point (delete key already handled by menu)
1425                         else if (code == KeyEvent.VK_BACK_SPACE && currPointIndex >= 0) {
1426                                 _app.deleteCurrentPoint();
1427                         }
1428                 }
1429         }
1430
1431         /**
1432          * @param inE key released event, ignored
1433          */
1434         public void keyReleased(KeyEvent e)
1435         {
1436                 // ignore
1437         }
1438
1439         /**
1440          * @param inE key typed event, ignored
1441          */
1442         public void keyTyped(KeyEvent inE)
1443         {
1444                 // ignore
1445         }
1446
1447         /**
1448          * @param inE mouse wheel event indicating scroll direction
1449          */
1450         public void mouseWheelMoved(MouseWheelEvent inE)
1451         {
1452                 int clicks = inE.getWheelRotation();
1453                 if (clicks < 0) {
1454                         panMap((inE.getX() - getWidth()/2)/2, (inE.getY() - getHeight()/2)/2);
1455                         zoomIn();
1456                 }
1457                 else if (clicks > 0) {
1458                         panMap(-(inE.getX() - getWidth()/2), -(inE.getY() - getHeight()/2));
1459                         zoomOut();
1460                 }
1461         }
1462
1463         /**
1464          * @return current map position
1465          */
1466         public MapPosition getMapPosition()
1467         {
1468                 return _mapPosition;
1469         }
1470 }