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