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