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