]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/gui/map/MapCanvas.java
Version 20.4, May 2021
[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(false);
263                 _sidePanel.setVisible(false);
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         private void zoomToFit()
341         {
342                 _latRange = _track.getLatRange();
343                 _lonRange = _track.getLonRange();
344                 _xRange = new DoubleRange(MapUtils.getXFromLongitude(_lonRange.getMinimum()),
345                         MapUtils.getXFromLongitude(_lonRange.getMaximum()));
346                 _yRange = new DoubleRange(MapUtils.getYFromLatitude(_latRange.getMinimum()),
347                         MapUtils.getYFromLatitude(_latRange.getMaximum()));
348                 _mapPosition.zoomToXY(_xRange.getMinimum(), _xRange.getMaximum(), _yRange.getMinimum(), _yRange.getMaximum(),
349                         getWidth(), getHeight());
350         }
351
352
353         /**
354          * Paint method
355          * @see java.awt.Canvas#paint(java.awt.Graphics)
356          */
357         public void paint(Graphics inG)
358         {
359                 super.paint(inG);
360                 if (_mapImage != null && (_mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())) {
361                         _mapImage = null;
362                 }
363                 if (_track.getNumPoints() > 0)
364                 {
365                         // Check for autopan if enabled / necessary
366                         if (_autopanCheckBox.isSelected())
367                         {
368                                 int selectedPoint = _selection.getCurrentPointIndex();
369                                 if (selectedPoint >= 0 && _dragFromX == -1 && selectedPoint != _prevSelectedPoint)
370                                 {
371                                         autopanToPoint(selectedPoint);
372                                 }
373                                 _prevSelectedPoint = selectedPoint;
374                         }
375
376                         // Draw the map contents if necessary
377                         if (_mapImage == null || _recalculate)
378                         {
379                                 paintMapContents();
380                                 _scaleBar.updateScale(_mapPosition.getZoom(), _mapPosition.getYFromPixels(0, 0));
381                         }
382                         // Draw the prepared image onto the panel
383                         if (_mapImage != null) {
384                                 inG.drawImage(_mapImage, 0, 0, getWidth(), getHeight(), null);
385                         }
386
387                         switch (_drawMode)
388                         {
389                                 case MODE_DRAG_POINT:
390                                         drawDragLines(inG, _selection.getCurrentPointIndex()-1, _selection.getCurrentPointIndex()+1);
391                                         break;
392
393                                 case MODE_CREATE_MIDPOINT:
394                                         drawDragLines(inG, _clickedPoint-1, _clickedPoint);
395                                         break;
396
397                                 case MODE_ZOOM_RECT:
398                                 case MODE_MARK_RECTANGLE:
399                                         if (_dragFromX != -1 && _dragFromY != -1)
400                                         {
401                                                 // Draw the zoom rectangle if necessary
402                                                 inG.setColor(Color.RED);
403                                                 inG.drawLine(_dragFromX, _dragFromY, _dragFromX, _dragToY);
404                                                 inG.drawLine(_dragFromX, _dragFromY, _dragToX, _dragFromY);
405                                                 inG.drawLine(_dragToX, _dragFromY, _dragToX, _dragToY);
406                                                 inG.drawLine(_dragFromX, _dragToY, _dragToX, _dragToY);
407                                         }
408                                         break;
409
410                                 case MODE_DRAW_POINTS_CONT:
411                                         // draw line to mouse position to show drawing mode
412                                         inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
413                                         int prevIndex = _track.getNumPoints()-1;
414                                         int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(prevIndex));
415                                         int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(prevIndex));
416                                         inG.drawLine(px, py, _dragToX, _dragToY);
417                                         break;
418                         }
419                 }
420                 else
421                 {
422                         inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
423                         inG.fillRect(0, 0, getWidth(), getHeight());
424                         inG.setColor(COLOR_MESSAGES);
425                         inG.drawString(I18nManager.getText("display.nodata"), 50, getHeight()/2);
426                         _scaleBar.updateScale(-1, 0);
427                 }
428                 // Draw slider etc on top
429                 paintChildren(inG);
430         }
431
432         /**
433          * @return true if the currently selected point is visible, false if off-screen or nothing selected
434          */
435         private boolean isCurrentPointVisible()
436         {
437                 if (_trackInfo.getCurrentPoint() == null) {return false;}
438                 final int selectedPoint = _selection.getCurrentPointIndex();
439                 final int xFromCentre = Math.abs(_mapPosition.getXFromCentre(_track.getX(selectedPoint)));
440                 if (xFromCentre > (getWidth()/2)) {return false;}
441                 final int yFromCentre = Math.abs(_mapPosition.getYFromCentre(_track.getY(selectedPoint)));
442                 return yFromCentre < (getHeight()/2);
443         }
444
445         /**
446          * If the specified point isn't visible, pan to it
447          * @param inIndex index of selected point
448          */
449         private void autopanToPoint(int inIndex)
450         {
451                 int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inIndex));
452                 int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inIndex));
453                 int panX = 0;
454                 int panY = 0;
455                 if (px < PAN_DISTANCE) {
456                         panX = px - AUTOPAN_DISTANCE;
457                 }
458                 else if (px > (getWidth()-PAN_DISTANCE)) {
459                         panX = AUTOPAN_DISTANCE + px - getWidth();
460                 }
461                 if (py < (2*PAN_DISTANCE)) {
462                         panY = py - AUTOPAN_DISTANCE;
463                 }
464                 if (py > (getHeight()-PAN_DISTANCE)) {
465                         panY = AUTOPAN_DISTANCE + py - getHeight();
466                 }
467                 if (panX != 0 || panY != 0) {
468                         _mapPosition.pan(panX, panY);
469                 }
470         }
471
472         /**
473          * Paint the map tiles and the points on to the _mapImage
474          */
475         private void paintMapContents()
476         {
477                 if (_mapImage == null || _mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())
478                 {
479                         _mapImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
480                 }
481
482                 Graphics g = _mapImage.getGraphics();
483                 // Set antialiasing according to config
484                 ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
485                         Config.getConfigBoolean(Config.KEY_ANTIALIAS) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
486                 // Clear to background
487                 g.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
488                 g.fillRect(0, 0, getWidth(), getHeight());
489
490                 // Check whether maps are on or not
491                 final boolean showMap = Config.getConfigBoolean(Config.KEY_SHOW_MAP);
492                 _mapCheckBox.setSelected(showMap);
493                 // Check whether disk cache is on or not
494                 final boolean usingDiskCache = Config.getConfigString(Config.KEY_DISK_CACHE) != null;
495                 // Show tip to recommend setting up a cache
496                 if (showMap && !usingDiskCache && Config.getConfigBoolean(Config.KEY_ONLINE_MODE))
497                 {
498                         SwingUtilities.invokeLater(new Runnable() {
499                                 public void run() {
500                                         _app.showTip(TipManager.Tip_UseAMapCache);
501                                 }
502                         });
503                 }
504
505                 // reset error message
506                 if (!showMap) {_shownOsmErrorAlready = false;}
507                 _recalculate = false;
508                 // Only get map tiles if selected
509                 if (showMap)
510                 {
511                         // init tile cacher
512                         _tileManager.centreMap(_mapPosition.getZoom(), _mapPosition.getCentreTileX(), _mapPosition.getCentreTileY());
513
514                         boolean loadingFailed = false;
515                         if (_mapImage == null) return;
516
517                         if (_tileManager.isOverzoomed())
518                         {
519                                 // display overzoom message
520                                 g.setColor(COLOR_MESSAGES);
521                                 g.drawString(I18nManager.getText("map.overzoom"), 50, getHeight()/2);
522                         }
523                         else
524                         {
525                                 int numLayers = _tileManager.getNumLayers();
526                                 // Loop over tiles drawing each one
527                                 int[] tileIndices = _mapPosition.getTileIndices(getWidth(), getHeight());
528                                 int[] pixelOffsets = _mapPosition.getDisplayOffsets(getWidth(), getHeight());
529                                 for (int tileX = tileIndices[0]; tileX <= tileIndices[1] && !loadingFailed; tileX++)
530                                 {
531                                         int x = (tileX - tileIndices[0]) * 256 - pixelOffsets[0];
532                                         for (int tileY = tileIndices[2]; tileY <= tileIndices[3]; tileY++)
533                                         {
534                                                 int y = (tileY - tileIndices[2]) * 256 - pixelOffsets[1];
535                                                 // Loop over layers
536                                                 for (int l=0; l<numLayers; l++)
537                                                 {
538                                                         Image image = _tileManager.getTile(l, tileX, tileY, true);
539                                                         if (image != null) {
540                                                                 g.drawImage(image, x, y, 256, 256, null);
541                                                         }
542                                                 }
543                                         }
544                                 }
545
546                                 // Make maps brighter / fainter according to slider
547                                 final int brightnessIndex = Math.max(1, _transparencySlider.getValue()) - 1;
548                                 if (brightnessIndex > 0)
549                                 {
550                                         final int[] alphas = {0, 40, 80, 120, 160, 210};
551                                         Color bgColor = Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND);
552                                         bgColor = new Color(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), alphas[brightnessIndex]);
553                                         g.setColor(bgColor);
554                                         g.fillRect(0, 0, getWidth(), getHeight());
555                                 }
556                         }
557                 }
558
559                 // Work out track opacity according to slider
560                 final float[] opacities = {1.0f, 0.75f, 0.5f, 0.3f, 0.15f, 0.0f};
561                 float trackOpacity = 1.0f;
562                 if (_transparencySlider.getValue() < 0) {
563                         trackOpacity = opacities[-1 - _transparencySlider.getValue()];
564                 }
565
566                 if (trackOpacity > 0.0f)
567                 {
568                         // Paint the track points on top
569                         boolean pointsPainted = true;
570                         try
571                         {
572                                 if (trackOpacity > 0.9f)
573                                 {
574                                         // Track is fully opaque, just draw it directly
575                                         pointsPainted = paintPoints(g);
576                                         _trackImage = null;
577                                 }
578                                 else
579                                 {
580                                         // Track is partly transparent, so use a separate BufferedImage
581                                         if (_trackImage == null || _trackImage.getWidth() != getWidth() || _trackImage.getHeight() != getHeight())
582                                         {
583                                                 _trackImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
584                                         }
585                                         // Clear to transparent
586                                         Graphics2D gTrack = _trackImage.createGraphics();
587                                         gTrack.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
588                                         gTrack.fillRect(0, 0, getWidth(), getHeight());
589                                         gTrack.setPaintMode();
590                                         // Draw the track onto this separate image
591                                         pointsPainted = paintPoints(gTrack);
592                                         ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, trackOpacity));
593                                         g.drawImage(_trackImage, 0, 0, null);
594                                 }
595                         }
596                         catch (NullPointerException npe) {} // ignore, probably due to data being changed during drawing
597                         catch (ArrayIndexOutOfBoundsException obe) {} // also ignore
598
599                         // Zoom to fit if no points found
600                         if (!pointsPainted && _checkBounds)
601                         {
602                                 zoomToFit();
603                                 _recalculate = true;
604                                 repaint();
605                         }
606                 }
607
608                 // free g
609                 g.dispose();
610
611                 _checkBounds = false;
612                 // enable / disable transparency slider
613                 _transparencySlider.setEnabled(showMap);
614         }
615
616
617         /**
618          * Paint the points using the given graphics object
619          * @param inG Graphics object to use for painting
620          * @return true if any points or lines painted
621          */
622         private boolean paintPoints(Graphics inG)
623         {
624                 // Set up colours
625                 final ColourScheme cs = Config.getColourScheme();
626                 final Color pointColour  = cs.getColour(ColourScheme.IDX_POINT);
627                 final Color rangeColour  = cs.getColour(ColourScheme.IDX_SELECTION);
628                 final Color currentColour = cs.getColour(ColourScheme.IDX_PRIMARY);
629                 final Color secondColour = cs.getColour(ColourScheme.IDX_SECONDARY);
630                 final Color textColour   = cs.getColour(ColourScheme.IDX_TEXT);
631                 final PointColourer pointColourer = _app.getPointColourer();
632
633                 final int winWidth  = getWidth();
634                 final int winHeight = getHeight();
635                 final int halfWinWidth  = winWidth / 2;
636                 final int halfWinHeight = winHeight / 2;
637
638                 final int numPoints = _track.getNumPoints();
639                 final int[] xPixels = new int[numPoints];
640                 final int[] yPixels = new int[numPoints];
641
642                 final int pointSeparationForArrowsSqd = 350;
643                 final int pointSeparation1dForArrows = (int) (Math.sqrt(pointSeparationForArrowsSqd) * 0.7);
644
645                 // try to set line width for painting
646                 if (inG instanceof Graphics2D)
647                 {
648                         int lineWidth = Config.getConfigInt(Config.KEY_LINE_WIDTH);
649                         if (lineWidth < 1 || lineWidth > 4) {lineWidth = 2;}
650                         ((Graphics2D) inG).setStroke(new BasicStroke(lineWidth));
651                 }
652
653                 boolean pointsPainted = false;
654                 // draw track points
655                 inG.setColor(pointColour);
656                 int prevX = -1, prevY = -1;
657                 final int connectState = _connectCheckBox.getCurrentState();
658                 final boolean drawLines = (connectState != 3);  // 0, 1 or 2
659                 final boolean drawPoints = (connectState != 1); // 0, 2 or 3
660                 final boolean drawArrows = (connectState == 0); // 0
661
662                 boolean prevPointVisible = false, currPointVisible = false;
663                 boolean anyWaypoints = false;
664                 boolean isWaypoint = false;
665                 boolean drawnLastArrow = false; // avoid painting arrows on adjacent lines, looks too busy
666                 for (int i=0; i<numPoints; i++)
667                 {
668                         // Calculate pixel position of point from its x, y coordinates
669                         int px = halfWinWidth  + _mapPosition.getXFromCentre(_track.getX(i));
670                         int py = halfWinHeight + _mapPosition.getYFromCentre(_track.getY(i));
671                         px = wrapLongitudeValue(px, winWidth, _mapPosition.getZoom());
672                         // Remember these calculated pixel values so they don't have to be recalculated
673                         xPixels[i] = px; yPixels[i] = py;
674
675                         currPointVisible = px >= 0 && px < winWidth && py >= 0 && py < winHeight;
676                         isWaypoint = _track.getPoint(i).isWaypoint();
677                         anyWaypoints = anyWaypoints || isWaypoint;
678                         if (!isWaypoint)
679                         {
680                                 if (currPointVisible || (drawLines && prevPointVisible))
681                                 {
682                                         // For track points, work out which colour to use
683                                         if (_track.getPoint(i).getDeleteFlag()) {
684                                                 inG.setColor(currentColour);
685                                         }
686                                         else if (pointColourer != null)
687                                         {  // use the point colourer if there is one
688                                                 Color trackColour = pointColourer.getColour(i);
689                                                 inG.setColor(trackColour);
690                                         }
691                                         else
692                                         {
693                                                 inG.setColor(pointColour);
694                                         }
695
696                                         // Draw rectangle for track point if it's visible
697                                         if (currPointVisible)
698                                         {
699                                                 if (drawPoints) {
700                                                         inG.drawRect(px-2, py-2, 3, 3);
701                                                 }
702                                                 pointsPainted = true;
703                                         }
704                                 }
705
706                                 // Connect track points if either of them are visible
707                                 if (drawLines
708                                  && (currPointVisible || prevPointVisible)
709                                  && !(prevX == -1 && prevY == -1)
710                                  && !_track.getPoint(i).getSegmentStart())
711                                 {
712                                         inG.drawLine(prevX, prevY, px, py);
713                                         pointsPainted = true;
714
715                                         // Now consider whether we need to draw an arrow as well
716                                         if (drawArrows
717                                          && !drawnLastArrow
718                                          && (Math.abs(prevX-px) > pointSeparation1dForArrows || Math.abs(prevY-py) > pointSeparation1dForArrows))
719                                         {
720                                                 final double pointSeparationSqd = (prevX-px) * (prevX-px) + (prevY-py) * (prevY-py);
721                                                 if (pointSeparationSqd > pointSeparationForArrowsSqd)
722                                                 {
723                                                         final double midX = (prevX + px) / 2.0;
724                                                         final double midY = (prevY + py) / 2.0;
725                                                         final boolean midPointVisible = midX >= 0 && midX < winWidth && midY >= 0 && midY < winHeight;
726                                                         if (midPointVisible)
727                                                         {
728                                                                 final double alpha = Math.atan2(py - prevY, px - prevX);
729                                                                 //System.out.println("Draw arrow from (" + prevX + "," + prevY + ") to (" + px + "," + py
730                                                                 //      + ") with angle" + (int) (alpha * 180/Math.PI));
731                                                                 final double MID_TO_VERTEX = 3.0;
732                                                                 final double arrowX = MID_TO_VERTEX * Math.cos(alpha);
733                                                                 final double arrowY = MID_TO_VERTEX * Math.sin(alpha);
734                                                                 final double vertexX = midX + arrowX;
735                                                                 final double vertexY = midY + arrowY;
736                                                                 inG.drawLine((int)(midX-arrowX-2*arrowY), (int)(midY-arrowY+2*arrowX), (int)vertexX, (int)vertexY);
737                                                                 inG.drawLine((int)(midX-arrowX+2*arrowY), (int)(midY-arrowY-2*arrowX), (int)vertexX, (int)vertexY);
738                                                         }
739                                                         drawnLastArrow = midPointVisible;
740                                                 }
741                                         }
742                                         else
743                                         {
744                                                 drawnLastArrow = false;
745                                         }
746                                 }
747                                 prevX = px; prevY = py;
748                         }
749                         prevPointVisible = currPointVisible;
750                 }
751
752                 // Loop over points, just drawing blobs for waypoints
753                 inG.setColor(textColour);
754                 FontMetrics fm = inG.getFontMetrics();
755                 int nameHeight = fm.getHeight();
756                 if (anyWaypoints)
757                 {
758                         int numWaypoints = 0;
759                         for (int i=0; i<_track.getNumPoints(); i++)
760                         {
761                                 if (_track.getPoint(i).isWaypoint())
762                                 {
763                                         int px = xPixels[i];
764                                         int py = yPixels[i];
765                                         if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
766                                         {
767                                                 if (_waypointIconDefinition == null)
768                                                 {
769                                                         inG.fillRect(px-3, py-3, 6, 6);
770                                                 }
771                                                 else
772                                                 {
773                                                         ImageIcon icon = _waypointIconDefinition.getImageIcon();
774                                                         if (icon != null)
775                                                         {
776                                                                 inG.drawImage(icon.getImage(), px-_waypointIconDefinition.getXOffset(),
777                                                                         py-_waypointIconDefinition.getYOffset(), null);
778                                                         }
779                                                 }
780                                                 pointsPainted = true;
781                                                 numWaypoints++;
782                                         }
783                                 }
784                         }
785                         // Take more care with waypoint names if less than 100 are visible
786                         final int numNameSteps = (numWaypoints > 100 ? 1 : 4);
787                         final int numPointSteps = (numWaypoints > 1000 ? 2 : 1);
788
789                         // Loop over points again, now draw names for waypoints
790                         int[] nameXs = {0, 0, 0, 0};
791                         int[] nameYs = {0, 0, 0, 0};
792                         for (int i=0; i<_track.getNumPoints(); i += numPointSteps)
793                         {
794                                 if (_track.getPoint(i).isWaypoint())
795                                 {
796                                         int px = xPixels[i];
797                                         int py = yPixels[i];
798                                         if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
799                                         {
800                                                 // Figure out where to draw waypoint name so it doesn't obscure track
801                                                 String waypointName = _track.getPoint(i).getWaypointName();
802                                                 int nameWidth = fm.stringWidth(waypointName);
803                                                 boolean drawnName = false;
804                                                 // Make arrays for coordinates right left up down
805                                                 nameXs[0] = px + 2; nameXs[1] = px - nameWidth - 2;
806                                                 nameXs[2] = nameXs[3] = px - nameWidth/2;
807                                                 nameYs[0] = nameYs[1] = py + (nameHeight/2);
808                                                 nameYs[2] = py - 2; nameYs[3] = py + nameHeight + 2;
809                                                 for (int extraSpace = 0; extraSpace < numNameSteps && !drawnName; extraSpace++)
810                                                 {
811                                                         // Shift arrays for coordinates right left up down
812                                                         nameXs[0] += 3; nameXs[1] -= 3;
813                                                         nameYs[2] -= 3; nameYs[3] += 3;
814                                                         // Check each direction in turn right left up down
815                                                         for (int a=0; a<4; a++)
816                                                         {
817                                                                 if (nameXs[a] > 0 && (nameXs[a] + nameWidth) < winWidth
818                                                                         && nameYs[a] < winHeight && (nameYs[a] - nameHeight) > 0
819                                                                         && !MapUtils.overlapsPoints(_mapImage, nameXs[a], nameYs[a], nameWidth, nameHeight, textColour))
820                                                                 {
821                                                                         // Found a rectangle to fit - draw name here and quit
822                                                                         inG.drawString(waypointName, nameXs[a], nameYs[a]);
823                                                                         drawnName = true;
824                                                                         break;
825                                                                 }
826                                                         }
827                                                 }
828                                         }
829                                 }
830                         }
831                 }
832                 // Loop over points, drawing blobs for photo / audio points
833                 inG.setColor(secondColour);
834                 for (int i=0; i<_track.getNumPoints(); i++)
835                 {
836                         if (_track.getPoint(i).hasMedia())
837                         {
838                                 int px = xPixels[i];
839                                 int py = yPixels[i];
840                                 if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
841                                 {
842                                         inG.drawRect(px-1, py-1, 2, 2);
843                                         inG.drawRect(px-2, py-2, 4, 4);
844                                         pointsPainted = true;
845                                 }
846                         }
847                 }
848
849                 // Draw selected range
850                 if (_selection.hasRangeSelected())
851                 {
852                         inG.setColor(rangeColour);
853                         for (int i=_selection.getStart(); i<=_selection.getEnd(); i++)
854                         {
855                                 int px = xPixels[i];
856                                 int py = yPixels[i];
857                                 inG.drawRect(px-1, py-1, 2, 2);
858                         }
859                 }
860
861                 // Draw crosshairs at selected point
862                 int selectedPoint = _selection.getCurrentPointIndex();
863                 if (selectedPoint >= 0)
864                 {
865                         int px = xPixels[selectedPoint];
866                         int py = yPixels[selectedPoint];
867                         inG.setColor(currentColour);
868                         // crosshairs
869                         inG.drawLine(px, 0, px, winHeight);
870                         inG.drawLine(0, py, winWidth, py);
871                 }
872                 // Return the number of points painted
873                 return pointsPainted;
874         }
875
876         /**
877          * Wrap the given pixel value if appropriate and possible
878          * @param inPx Pixel x coordinate
879          * @param inWinWidth window width in pixels
880          * @param inZoom zoom level
881          * @return modified pixel x coordinate
882          */
883         private static int wrapLongitudeValue(int inPx, int inWinWidth, int inZoom)
884         {
885                 if (inPx > inWinWidth)
886                 {
887                         // Pixel is too far right, could we wrap it back onto the screen?
888                         int px = inPx;
889                         while (px > inWinWidth) {
890                                 px -= (256 << inZoom);
891                         }
892                         if (px >= 0) {
893                                 return px; // successfully wrapped back onto the screen
894                         }
895                 }
896                 else if (inPx < 0)
897                 {
898                         // Pixel is too far left, could we wrap it back onto the screen?
899                         int px = inPx;
900                         while (px < 0) {
901                                 px += (256 << inZoom);
902                         }
903                         if (px < inWinWidth) {
904                                 return px; // successfully wrapped back onto the screen
905                         }
906                 }
907                 // Either it's already on the screen or couldn't be wrapped
908                 return inPx;
909         }
910
911         /**
912          * Draw the lines while dragging a point
913          * @param inG graphics object
914          * @param inPrevIndex index of point to draw from
915          * @param inNextIndex index of point to draw to
916          */
917         private void drawDragLines(Graphics inG, int inPrevIndex, int inNextIndex)
918         {
919                 inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
920                 // line from prev point to cursor
921                 if (inPrevIndex > -1 && !_track.getPoint(inPrevIndex+1).getSegmentStart())
922                 {
923                         final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inPrevIndex));
924                         final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inPrevIndex));
925                         inG.drawLine(px, py, _dragToX, _dragToY);
926                 }
927                 if (inNextIndex < _track.getNumPoints() && !_track.getPoint(inNextIndex).getSegmentStart())
928                 {
929                         final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inNextIndex));
930                         final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inNextIndex));
931                         inG.drawLine(px, py, _dragToX, _dragToY);
932                 }
933         }
934
935         /**
936          * Inform that tiles have been updated and the map can be repainted
937          * @param inIsOk true if data loaded ok, false for error
938          */
939         public void tilesUpdated(boolean inIsOk)
940         {
941                 synchronized(this)
942                 {
943                         // Show message if loading failed (but not too many times)
944                         if (!inIsOk && !_shownOsmErrorAlready && _mapCheckBox.isSelected())
945                         {
946                                 _shownOsmErrorAlready = true;
947                                 // use separate thread to show message about failing to load osm images
948                                 new Thread(new Runnable() {
949                                         public void run() {
950                                                 try {Thread.sleep(500);} catch (InterruptedException ie) {}
951                                                 _app.showErrorMessage("error.osmimage.dialogtitle", "error.osmimage.failed");
952                                         }
953                                 }).start();
954                         }
955                         _recalculate = true;
956                         repaint();
957                 }
958         }
959
960         /**
961          * Zoom out, if not already at minimum zoom
962          */
963         public void zoomOut()
964         {
965                 _mapPosition.zoomOut();
966                 _recalculate = true;
967                 repaint();
968         }
969
970         /**
971          * Zoom in, if not already at maximum zoom
972          */
973         public void zoomIn()
974         {
975                 // See if selected point is currently visible, if so (and autopan on) then autopan after zoom to keep it visible
976                 boolean wasVisible = _autopanCheckBox.isSelected() && isCurrentPointVisible();
977                 _mapPosition.zoomIn();
978                 if (wasVisible && !isCurrentPointVisible()) {
979                         autopanToPoint(_selection.getCurrentPointIndex());
980                 }
981                 _recalculate = true;
982                 repaint();
983         }
984
985         /**
986          * Pan map
987          * @param inDeltaX x shift
988          * @param inDeltaY y shift
989          */
990         public void panMap(int inDeltaX, int inDeltaY)
991         {
992                 _mapPosition.pan(inDeltaX, inDeltaY);
993                 _recalculate = true;
994                 repaint();
995         }
996
997         /**
998          * Create a DataPoint object from the given click coordinates
999          * @param inX x coordinate of click
1000          * @param inY y coordinate of click
1001          * @return DataPoint with given coordinates and no altitude
1002          */
1003         private DataPoint createPointFromClick(int inX, int inY)
1004         {
1005                 double lat = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(inY, getHeight()));
1006                 double lon = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(inX, getWidth()));
1007                 return new DataPoint(new Latitude(lat, Coordinate.FORMAT_NONE),
1008                         new Longitude(lon, Coordinate.FORMAT_NONE), null);
1009         }
1010
1011         /**
1012          * Move a DataPoint object to the given mouse coordinates
1013          * @param startX start x coordinate of mouse
1014          * @param startY start y coordinate of mouse
1015          * @param endX end x coordinate of mouse
1016          * @param endY end y coordinate of mouse
1017          */
1018         private void movePointToMouse(int startX, int startY, int endX, int endY )
1019         {
1020                 double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(startY, getHeight()));
1021                 double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(startX, getWidth()));
1022                 double lat_delta = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(endY, getHeight())) - lat1;
1023                 double lon_delta = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(endX, getWidth())) - lon1;
1024
1025                 DataPoint point = _trackInfo.getCurrentPoint();
1026                 if (point == null) {
1027                         return;
1028                 }
1029
1030                 // Make lists for edit and undo, and add each changed field in turn
1031                 FieldEditList editList = new FieldEditList();
1032                 FieldEditList undoList = new FieldEditList();
1033
1034                 // Check field list
1035                 FieldList fieldList = _track.getFieldList();
1036                 int numFields = fieldList.getNumFields();
1037                 for (int i=0; i<numFields; i++)
1038                 {
1039                         Field field = fieldList.getField(i);
1040                         if (field == Field.LATITUDE) {
1041                                 editList.addEdit(new FieldEdit(field, Double.toString(point.getLatitude().getDouble() + lat_delta)));
1042                                 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LATITUDE)));
1043                         }
1044                         else if (field == Field.LONGITUDE) {
1045                                 editList.addEdit(new FieldEdit(field, Double.toString(point.getLongitude().getDouble() + lon_delta)));
1046                                 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LONGITUDE)));
1047                         }
1048                 }
1049                 _app.completePointEdit(editList, undoList);
1050         }
1051
1052
1053         /**
1054          * @see javax.swing.JComponent#getMinimumSize()
1055          */
1056         public Dimension getMinimumSize()
1057         {
1058                 final Dimension minSize = new Dimension(512, 300);
1059                 return minSize;
1060         }
1061
1062         /**
1063          * @see javax.swing.JComponent#getPreferredSize()
1064          */
1065         public Dimension getPreferredSize()
1066         {
1067                 return getMinimumSize();
1068         }
1069
1070
1071         /**
1072          * Respond to mouse click events
1073          * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1074          */
1075         public void mouseClicked(MouseEvent inE)
1076         {
1077                 if (_track != null && _track.getNumPoints() > 0)
1078                 {
1079                         // select point if it's a left-click
1080                         if (!inE.isMetaDown())
1081                         {
1082                                 if (inE.getClickCount() == 1)
1083                                 {
1084                                         // single click
1085                                         if (_drawMode == MODE_DEFAULT)
1086                                         {
1087                                                 int pointIndex = _clickedPoint;
1088                                                 if (pointIndex == INDEX_UNKNOWN)
1089                                                 {
1090                                                         // index hasn't been calculated yet
1091                                                         pointIndex = _track.getNearestPointIndex(
1092                                                          _mapPosition.getXFromPixels(inE.getX(), getWidth()),
1093                                                          _mapPosition.getYFromPixels(inE.getY(), getHeight()),
1094                                                          _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY), false);
1095                                                 }
1096                                                 // Extend selection for shift-click
1097                                                 if (inE.isShiftDown()) {
1098                                                         _trackInfo.extendSelection(pointIndex);
1099                                                 }
1100                                                 else {
1101                                                         _trackInfo.selectPoint(pointIndex);
1102                                                 }
1103                                         }
1104                                         else if (_drawMode == MODE_DRAW_POINTS_START)
1105                                         {
1106                                                 _app.createPoint(createPointFromClick(inE.getX(), inE.getY()));
1107                                                 _dragToX = inE.getX();
1108                                                 _dragToY = inE.getY();
1109                                                 _drawMode = MODE_DRAW_POINTS_CONT;
1110                                         }
1111                                         else if (_drawMode == MODE_DRAW_POINTS_CONT)
1112                                         {
1113                                                 DataPoint point = createPointFromClick(inE.getX(), inE.getY());
1114                                                 _app.createPoint(point, false); // not a new segment
1115                                         }
1116                                 }
1117                                 else if (inE.getClickCount() == 2)
1118                                 {
1119                                         // double click
1120                                         if (_drawMode == MODE_DEFAULT) {
1121                                                 panMap(inE.getX() - getWidth()/2, inE.getY() - getHeight()/2);
1122                                                 zoomIn();
1123                                         }
1124                                         else if (_drawMode == MODE_DRAW_POINTS_START || _drawMode == MODE_DRAW_POINTS_CONT) {
1125                                                 _drawMode = MODE_DEFAULT;
1126                                         }
1127                                 }
1128                         }
1129                         else
1130                         {
1131                                 // show the popup menu for right-clicks
1132                                 _popupMenuX = inE.getX();
1133                                 _popupMenuY = inE.getY();
1134                                 _popup.show(this, _popupMenuX, _popupMenuY);
1135                         }
1136                 }
1137                 // Reset app mode
1138                 _app.setCurrentMode(App.AppMode.NORMAL);
1139                 if (_drawMode == MODE_MARK_RECTANGLE) _drawMode = MODE_DEFAULT;
1140         }
1141
1142         /**
1143          * Ignore mouse enter events
1144          * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1145          */
1146         public void mouseEntered(MouseEvent inE)
1147         {
1148                 // ignore
1149         }
1150
1151         /**
1152          * Ignore mouse exited events
1153          * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1154          */
1155         public void mouseExited(MouseEvent inE)
1156         {
1157                 // ignore
1158         }
1159
1160         /**
1161          * React to mouse pressed events to initiate a point drag
1162          * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1163          */
1164         public void mousePressed(MouseEvent inE)
1165         {
1166                 _clickedPoint = INDEX_UNKNOWN;
1167                 if (_track == null || _track.getNumPoints() <= 0)
1168                         return;
1169                 if (!inE.isMetaDown())
1170                 {
1171                         // Left mouse drag - check if point is near; if so select it for dragging
1172                         if (_drawMode == MODE_DEFAULT)
1173                         {
1174                                 /* Drag points if edit mode is enabled OR ALT is pressed */
1175                                 if (_editmodeCheckBox.isSelected() || inE.isAltDown() || inE.isAltGraphDown())
1176                                 {
1177                                         final double clickX = _mapPosition.getXFromPixels(inE.getX(), getWidth());
1178                                         final double clickY = _mapPosition.getYFromPixels(inE.getY(), getHeight());
1179                                         final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1180                                         _clickedPoint = _track.getNearestPointIndex(clickX, clickY, clickSens, false);
1181
1182                                         if (_clickedPoint >= 0)
1183                                         {
1184                                                 // TODO: maybe use another color of the cross or remove the cross while dragging???
1185
1186                                                 _trackInfo.selectPoint(_clickedPoint);
1187                                                 if (_trackInfo.getCurrentPoint() != null)
1188                                                 {
1189                                                         _drawMode = MODE_DRAG_POINT;
1190                                                         _dragFromX = _dragToX = inE.getX();
1191                                                         _dragFromY = _dragToY = inE.getY();
1192                                                 }
1193                                         }
1194                                         else
1195                                         {
1196                                                 // Not a click on a point, so check half-way between two (connected) trackpoints
1197                                                 int midpointIndex = _midpoints.getNearestPointIndex(clickX, clickY, clickSens);
1198                                                 if (midpointIndex > 0)
1199                                                 {
1200                                                         _drawMode = MODE_CREATE_MIDPOINT;
1201                                                         _clickedPoint = midpointIndex;
1202                                                         _dragFromX = _dragToX = inE.getX();
1203                                                         _dragFromY = _dragToY = inE.getY();
1204                                                 }
1205                                         }
1206                                 }
1207                         }
1208                 }
1209                 // else right-press ignored
1210         }
1211
1212         /**
1213          * Respond to mouse released events
1214          * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1215          */
1216         public void mouseReleased(MouseEvent inE)
1217         {
1218                 _recalculate = true;
1219
1220                 if (_drawMode == MODE_DRAG_POINT)
1221                 {
1222                         if (Math.abs(_dragToX - _dragFromX) > 2
1223                                 || Math.abs(_dragToY - _dragFromY) > 2)
1224                         {
1225                                 movePointToMouse(_dragFromX, _dragFromY, _dragToX, _dragToY );
1226                         }
1227                         _drawMode = MODE_DEFAULT;
1228                 }
1229                 else if (_drawMode == MODE_CREATE_MIDPOINT)
1230                 {
1231                         _drawMode = MODE_DEFAULT;
1232                         _app.createPoint(createPointFromClick(_dragToX, _dragToY), _clickedPoint);
1233                 }
1234                 else if (_drawMode == MODE_ZOOM_RECT)
1235                 {
1236                         if (Math.abs(_dragToX - _dragFromX) > 20
1237                          && Math.abs(_dragToY - _dragFromY) > 20)
1238                         {
1239                                 _mapPosition.zoomToPixels(_dragFromX, _dragToX, _dragFromY, _dragToY, getWidth(), getHeight());
1240                         }
1241                         _drawMode = MODE_DEFAULT;
1242                 }
1243                 else if (_drawMode == MODE_MARK_RECTANGLE)
1244                 {
1245                         // Reset app mode
1246                         _app.setCurrentMode(App.AppMode.NORMAL);
1247                         _drawMode = MODE_DEFAULT;
1248                         // Call a function to mark the points
1249                         MarkPointsInRectangleFunction marker = (MarkPointsInRectangleFunction) FunctionLibrary.FUNCTION_MARK_IN_RECTANGLE;
1250                         double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragFromX, getWidth()));
1251                         double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragFromY, getHeight()));
1252                         double lon2 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragToX, getWidth()));
1253                         double lat2 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragToY, getHeight()));
1254                         // Invalidate rectangle if pixel coords are (-1,-1)
1255                         if (_dragFromX < 0 || _dragFromY < 0) {
1256                                 lon1 = lon2;
1257                                 lat1 = lat2;
1258                         }
1259                         marker.setRectCoords(lon1, lat1, lon2, lat2);
1260                         marker.begin();
1261                 }
1262                 _dragFromX = _dragFromY = -1;
1263                 repaint();
1264         }
1265
1266         /**
1267          * Respond to mouse drag events
1268          * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1269          */
1270         public void mouseDragged(MouseEvent inE)
1271         {
1272                 // Note: One would expect inE.isMetaDown() to give information about whether this is a
1273                 //       drag with the right mouse button or not - but since java 9 this is buggy,
1274                 //       so we use the beautifully-named getModifiersEx() instead.
1275                 //       And logically BUTTON3 refers to the secondary mouse button, not the tertiary one!
1276                 final boolean isRightDrag = (inE.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0;
1277                 if (isRightDrag)
1278                 {
1279                         // Right-click and drag - update rectangle
1280                         _drawMode = MODE_ZOOM_RECT;
1281                         if (_dragFromX == -1) {
1282                                 _dragFromX = inE.getX();
1283                                 _dragFromY = inE.getY();
1284                         }
1285                         _dragToX = inE.getX();
1286                         _dragToY = inE.getY();
1287                         repaint();
1288                 }
1289                 else
1290                 {
1291                         // Left mouse drag - decide whether to drag the point, drag the
1292                         // marking rectangle or pan the map
1293                         if (_drawMode == MODE_DRAG_POINT || _drawMode == MODE_CREATE_MIDPOINT)
1294                         {
1295                                 // move point
1296                                 _dragToX = inE.getX();
1297                                 _dragToY = inE.getY();
1298                                 _recalculate = true;
1299                                 repaint();
1300                         }
1301                         else if (_drawMode == MODE_MARK_RECTANGLE)
1302                         {
1303                                 // draw a rectangle for marking points
1304                                 if (_dragFromX == -1) {
1305                                         _dragFromX = inE.getX();
1306                                         _dragFromY = inE.getY();
1307                                 }
1308                                 _dragToX = inE.getX();
1309                                 _dragToY = inE.getY();
1310                                 repaint();
1311                         }
1312                         else
1313                         {
1314                                 // regular left-drag pans map by appropriate amount
1315                                 if (_dragFromX != -1)
1316                                 {
1317                                         panMap(_dragFromX - inE.getX(), _dragFromY - inE.getY());
1318                                 }
1319                                 _dragFromX = _dragToX = inE.getX();
1320                                 _dragFromY = _dragToY = inE.getY();
1321                         }
1322                 }
1323         }
1324
1325         /**
1326          * Respond to mouse move events without button pressed
1327          * @param inEvent ignored
1328          */
1329         public void mouseMoved(MouseEvent inEvent)
1330         {
1331                 boolean useCrosshairs = false;
1332                 boolean useResize     = false;
1333                 // Ignore unless we're drawing points
1334                 if (_drawMode == MODE_DRAW_POINTS_CONT)
1335                 {
1336                         _dragToX = inEvent.getX();
1337                         _dragToY = inEvent.getY();
1338                         repaint();
1339                 }
1340                 else if (_drawMode == MODE_MARK_RECTANGLE) {
1341                         useResize = true;
1342                 }
1343                 else if (_editmodeCheckBox.isSelected() || inEvent.isAltDown() || inEvent.isAltGraphDown())
1344                 {
1345                         // Try to find a point or a midpoint at this location, and if there is one
1346                         // then change the cursor to crosshairs
1347                         final double clickX = _mapPosition.getXFromPixels(inEvent.getX(), getWidth());
1348                         final double clickY = _mapPosition.getYFromPixels(inEvent.getY(), getHeight());
1349                         final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1350                         useCrosshairs = (_track.getNearestPointIndex(clickX, clickY, clickSens, false) >= 0
1351                                 || _midpoints.getNearestPointIndex(clickX, clickY, clickSens) >= 0
1352                         );
1353                 }
1354                 if (useCrosshairs && !isCursorSet()) {
1355                         setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
1356                 }
1357                 else if (useResize && !isCursorSet()) {
1358                         setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1359                 }
1360                 else if (!useCrosshairs && !useResize && isCursorSet()) {
1361                         setCursor(null);
1362                 }
1363         }
1364
1365         /**
1366          * Respond to status bar message from broker
1367          * @param inMessage message, ignored
1368          */
1369         public void actionCompleted(String inMessage)
1370         {
1371                 // ignore
1372         }
1373
1374         /**
1375          * Respond to data updated message from broker
1376          * @param inUpdateType type of update
1377          */
1378         public void dataUpdated(byte inUpdateType)
1379         {
1380                 _recalculate = true;
1381                 if ((inUpdateType & DataSubscriber.DATA_ADDED_OR_REMOVED) > 0) {
1382                         _checkBounds = true;
1383                 }
1384                 if ((inUpdateType & DataSubscriber.MAPSERVER_CHANGED) > 0)
1385                 {
1386                         // Get the selected map source index and pass to tile manager
1387                         _tileManager.setMapSource(Config.getConfigInt(Config.KEY_MAPSOURCE_INDEX));
1388                         final int wpType = Config.getConfigInt(Config.KEY_WAYPOINT_ICONS);
1389                         if (wpType == WpIconLibrary.WAYPT_DEFAULT)
1390                         {
1391                                 _waypointIconDefinition = null;
1392                         }
1393                         else
1394                         {
1395                                 final int wpSize = Config.getConfigInt(Config.KEY_WAYPOINT_ICON_SIZE);
1396                                 _waypointIconDefinition = WpIconLibrary.getIconDefinition(wpType, wpSize);
1397                         }
1398                 }
1399                 if ((inUpdateType & (DataSubscriber.DATA_ADDED_OR_REMOVED + DataSubscriber.DATA_EDITED)) > 0) {
1400                         _midpoints.updateData(_track);
1401                 }
1402                 // See if rect mode has been activated
1403                 if (_app.getCurrentMode() == App.AppMode.DRAWRECT)
1404                 {
1405                         _drawMode = MODE_MARK_RECTANGLE;
1406                         if (!isCursorSet()) {
1407                                 setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1408                         }
1409                 }
1410                 repaint();
1411                 // enable or disable components
1412                 boolean hasData = _track.getNumPoints() > 0;
1413                 _topPanel.setVisible(hasData);
1414                 _sidePanel.setVisible(hasData);
1415                 // grab focus for the key presses
1416                 this.requestFocus();
1417         }
1418
1419         /**
1420          * Respond to key presses on the map canvas
1421          * @param inE key event
1422          */
1423         public void keyPressed(KeyEvent inE)
1424         {
1425                 int code = inE.getKeyCode();
1426                 int currPointIndex = _selection.getCurrentPointIndex();
1427                 // Check for Ctrl key (for Linux/Win) or meta key (Clover key for Mac)
1428                 if (inE.isControlDown() || inE.isMetaDown())
1429                 {
1430                         // Shift as well makes things faster
1431                         final int pointIncrement = inE.isShiftDown()?3:1;
1432                         // Check for arrow keys to zoom in and out
1433                         if (code == KeyEvent.VK_UP)
1434                                 zoomIn();
1435                         else if (code == KeyEvent.VK_DOWN)
1436                                 zoomOut();
1437                         // Key nav for next/prev point
1438                         else if (code == KeyEvent.VK_LEFT && currPointIndex > 0)
1439                                 _trackInfo.incrementPointIndex(-pointIncrement);
1440                         else if (code == KeyEvent.VK_RIGHT)
1441                                 _trackInfo.incrementPointIndex(pointIncrement);
1442                         else if (code == KeyEvent.VK_PAGE_UP)
1443                                 _trackInfo.selectPoint(Checker.getPreviousSegmentStart(
1444                                         _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1445                         else if (code == KeyEvent.VK_PAGE_DOWN)
1446                                 _trackInfo.selectPoint(Checker.getNextSegmentStart(
1447                                         _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1448                         // Check for home and end
1449                         else if (code == KeyEvent.VK_HOME)
1450                                 _trackInfo.selectPoint(0);
1451                         else if (code == KeyEvent.VK_END)
1452                                 _trackInfo.selectPoint(_trackInfo.getTrack().getNumPoints()-1);
1453                 }
1454                 else
1455                 {
1456                         // Check for arrow keys to pan
1457                         int upwardsPan = 0;
1458                         if (code == KeyEvent.VK_UP)
1459                                 upwardsPan = -PAN_DISTANCE;
1460                         else if (code == KeyEvent.VK_DOWN)
1461                                 upwardsPan = PAN_DISTANCE;
1462                         int rightwardsPan = 0;
1463                         if (code == KeyEvent.VK_RIGHT)
1464                                 rightwardsPan = PAN_DISTANCE;
1465                         else if (code == KeyEvent.VK_LEFT)
1466                                 rightwardsPan = -PAN_DISTANCE;
1467                         panMap(rightwardsPan, upwardsPan);
1468                         // Check for escape
1469                         if (code == KeyEvent.VK_ESCAPE)
1470                                 _drawMode = MODE_DEFAULT;
1471                         // Check for backspace key to delete current point (delete key already handled by menu)
1472                         else if (code == KeyEvent.VK_BACK_SPACE && currPointIndex >= 0) {
1473                                 _app.deleteCurrentPoint();
1474                         }
1475                 }
1476         }
1477
1478         /**
1479          * @param inE key released event, ignored
1480          */
1481         public void keyReleased(KeyEvent e)
1482         {
1483                 // ignore
1484         }
1485
1486         /**
1487          * @param inE key typed event, ignored
1488          */
1489         public void keyTyped(KeyEvent inE)
1490         {
1491                 // ignore
1492         }
1493
1494         /**
1495          * @param inE mouse wheel event indicating scroll direction
1496          */
1497         public void mouseWheelMoved(MouseWheelEvent inE)
1498         {
1499                 int clicks = inE.getWheelRotation();
1500                 if (clicks < 0) {
1501                         panMap((inE.getX() - getWidth()/2)/2, (inE.getY() - getHeight()/2)/2);
1502                         zoomIn();
1503                 }
1504                 else if (clicks > 0) {
1505                         panMap(-(inE.getX() - getWidth()/2), -(inE.getY() - getHeight()/2));
1506                         zoomOut();
1507                 }
1508         }
1509
1510         /**
1511          * @return current map position
1512          */
1513         public MapPosition getMapPosition()
1514         {
1515                 return _mapPosition;
1516         }
1517 }