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