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