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