1 package tim.prune.gui.map;
4 import java.awt.event.*;
5 import java.awt.image.BufferedImage;
8 import javax.swing.event.ChangeEvent;
9 import javax.swing.event.ChangeListener;
12 import tim.prune.DataSubscriber;
13 import tim.prune.FunctionLibrary;
14 import tim.prune.I18nManager;
15 import tim.prune.UpdateMessageBroker;
16 import tim.prune.config.ColourScheme;
17 import tim.prune.config.Config;
18 import tim.prune.data.*;
19 import tim.prune.function.compress.MarkPointsInRectangleFunction;
20 import tim.prune.function.edit.FieldEdit;
21 import tim.prune.function.edit.FieldEditList;
22 import tim.prune.gui.IconManager;
23 import tim.prune.gui.MultiStateCheckBox;
24 import tim.prune.gui.colour.PointColourer;
25 import tim.prune.tips.TipManager;
28 * Class for the map canvas, to display a background map and draw on it
30 public class MapCanvas extends JPanel implements MouseListener, MouseMotionListener, DataSubscriber,
31 KeyListener, MouseWheelListener, TileConsumer
33 /** App object for callbacks */
34 private App _app = null;
36 private Track _track = null;
37 /** TrackInfo object */
38 private TrackInfo _trackInfo = null;
39 /** Selection object */
40 private Selection _selection = null;
41 /** Object to keep track of midpoints */
42 private MidpointData _midpoints = null;
43 /** Index of point clicked at mouseDown */
44 private int _clickedPoint = -1;
45 /** Previously selected point */
46 private int _prevSelectedPoint = -1;
48 private MapTileManager _tileManager = new MapTileManager(this);
49 /** Image to display */
50 private BufferedImage _mapImage = null;
51 /** Second image for drawing track (only needed for alpha blending) */
52 private BufferedImage _trackImage = null;
53 /** Slider for transparency */
54 private JSlider _transparencySlider = null;
55 /** Checkbox for scale bar */
56 private JCheckBox _scaleCheckBox = null;
57 /** Checkbox for maps */
58 private JCheckBox _mapCheckBox = null;
59 /** Checkbox for autopan */
60 private JCheckBox _autopanCheckBox = null;
61 /** Checkbox for connecting track points */
62 private MultiStateCheckBox _connectCheckBox = null;
63 /** Checkbox for enable edit mode */
64 private JCheckBox _editmodeCheckBox = null;
65 /** Right-click popup menu */
66 private JPopupMenu _popup = null;
67 /** Top component panel */
68 private JPanel _topPanel = null;
69 /** Side component panel */
70 private JPanel _sidePanel = null;
72 private ScaleBar _scaleBar = null;
74 private DoubleRange _latRange = null, _lonRange = null;
75 private DoubleRange _xRange = null, _yRange = null;
76 private boolean _recalculate = false;
77 /** Flag to check bounds on next paint */
78 private boolean _checkBounds = false;
80 private MapPosition _mapPosition = null;
81 /** coordinates of drag from point */
82 private int _dragFromX = -1, _dragFromY = -1;
83 /** coordinates of drag to point */
84 private int _dragToX = -1, _dragToY = -1;
85 /** coordinates of popup menu */
86 private int _popupMenuX = -1, _popupMenuY = -1;
87 /** Flag to prevent showing too often the error message about loading maps */
88 private boolean _shownOsmErrorAlready = false;
89 /** Current drawing mode */
90 private int _drawMode = MODE_DEFAULT;
91 /** Current waypoint icon definition */
92 WpIconDefinition _waypointIconDefinition = null;
94 /** Constant for click sensitivity when selecting nearest point */
95 private static final int CLICK_SENSITIVITY = 10;
96 /** Constant for pan distance from key presses */
97 private static final int PAN_DISTANCE = 20;
98 /** Constant for pan distance from autopan */
99 private static final int AUTOPAN_DISTANCE = 75;
102 private static final Color COLOR_MESSAGES = Color.GRAY;
105 private static final int MODE_DEFAULT = 0;
106 private static final int MODE_ZOOM_RECT = 1;
107 private static final int MODE_DRAW_POINTS_START = 2;
108 private static final int MODE_DRAW_POINTS_CONT = 3;
109 private static final int MODE_DRAG_POINT = 4;
110 private static final int MODE_CREATE_MIDPOINT = 5;
111 private static final int MODE_MARK_RECTANGLE = 6;
113 private static final int INDEX_UNKNOWN = -2;
118 * @param inApp App object for callbacks
119 * @param inTrackInfo track info object
121 public MapCanvas(App inApp, TrackInfo inTrackInfo)
124 _trackInfo = inTrackInfo;
125 _track = inTrackInfo.getTrack();
126 _selection = inTrackInfo.getSelection();
127 _midpoints = new MidpointData();
128 _mapPosition = new MapPosition();
129 addMouseListener(this);
130 addMouseMotionListener(this);
131 addMouseWheelListener(this);
132 addKeyListener(this);
134 // Make listener for changes to controls
135 ItemListener itemListener = new ItemListener() {
136 public void itemStateChanged(ItemEvent e)
142 // Make special listener for changes to map checkbox
143 ItemListener mapCheckListener = new ItemListener() {
144 public void itemStateChanged(ItemEvent e)
146 _tileManager.clearMemoryCaches();
148 Config.setConfigBoolean(Config.KEY_SHOW_MAP, e.getStateChange() == ItemEvent.SELECTED);
149 UpdateMessageBroker.informSubscribers(); // to let menu know
150 // If the track is only partially visible and you turn the map off, make the track fully visible again
151 if (e.getStateChange() == ItemEvent.DESELECTED && _transparencySlider.getValue() < 0) {
152 _transparencySlider.setValue(0);
156 _topPanel = new OverlayPanel();
157 _topPanel.setLayout(new FlowLayout());
158 // Make slider for transparency
159 _transparencySlider = new JSlider(-6, 6, 0);
160 _transparencySlider.setPreferredSize(new Dimension(100, 20));
161 _transparencySlider.setMajorTickSpacing(1);
162 _transparencySlider.setSnapToTicks(true);
163 _transparencySlider.setOpaque(false);
164 _transparencySlider.setValue(0);
165 _transparencySlider.addChangeListener(new ChangeListener() {
166 public void stateChanged(ChangeEvent e)
168 int val = _transparencySlider.getValue();
169 if (val == 1 || val == -1)
170 _transparencySlider.setValue(0);
177 _transparencySlider.setFocusable(false); // stop slider from stealing keyboard focus
178 _topPanel.add(_transparencySlider);
179 // Add checkbox button for enabling scale bar
180 _scaleCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.SCALEBAR_BUTTON), true);
181 _scaleCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.SCALEBAR_BUTTON_ON));
182 _scaleCheckBox.setOpaque(false);
183 _scaleCheckBox.setToolTipText(I18nManager.getText("menu.map.showscalebar"));
184 _scaleCheckBox.addItemListener(new ItemListener() {
185 public void itemStateChanged(ItemEvent e) {
186 _scaleBar.setVisible(_scaleCheckBox.isSelected());
189 _scaleCheckBox.setFocusable(false); // stop button from stealing keyboard focus
190 _topPanel.add(_scaleCheckBox);
191 // Add checkbox button for enabling maps or not
192 _mapCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.MAP_BUTTON), false);
193 _mapCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.MAP_BUTTON_ON));
194 _mapCheckBox.setOpaque(false);
195 _mapCheckBox.setToolTipText(I18nManager.getText("menu.map.showmap"));
196 _mapCheckBox.addItemListener(mapCheckListener);
197 _mapCheckBox.setFocusable(false); // stop button from stealing keyboard focus
198 _topPanel.add(_mapCheckBox);
199 // Add checkbox button for enabling autopan or not
200 _autopanCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.AUTOPAN_BUTTON), true);
201 _autopanCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.AUTOPAN_BUTTON_ON));
202 _autopanCheckBox.setOpaque(false);
203 _autopanCheckBox.setToolTipText(I18nManager.getText("menu.map.autopan"));
204 _autopanCheckBox.addItemListener(itemListener);
205 _autopanCheckBox.setFocusable(false); // stop button from stealing keyboard focus
206 _topPanel.add(_autopanCheckBox);
207 // Add checkbox button for connecting points or not
208 _connectCheckBox = new MultiStateCheckBox(4);
209 _connectCheckBox.setIcon(0, IconManager.getImageIcon(IconManager.POINTS_WITH_ARROWS_BUTTON));
210 _connectCheckBox.setIcon(1, IconManager.getImageIcon(IconManager.POINTS_HIDDEN_BUTTON));
211 _connectCheckBox.setIcon(2, IconManager.getImageIcon(IconManager.POINTS_CONNECTED_BUTTON));
212 _connectCheckBox.setIcon(3, IconManager.getImageIcon(IconManager.POINTS_DISCONNECTED_BUTTON));
213 _connectCheckBox.setCurrentState(0);
214 _connectCheckBox.setOpaque(false);
215 _connectCheckBox.setToolTipText(I18nManager.getText("menu.map.connect"));
216 _connectCheckBox.addItemListener(itemListener);
217 _connectCheckBox.setFocusable(false); // stop button from stealing keyboard focus
218 _topPanel.add(_connectCheckBox);
220 // Add checkbox button for edit mode or not
221 _editmodeCheckBox = new JCheckBox(IconManager.getImageIcon(IconManager.EDIT_MODE_BUTTON), false);
222 _editmodeCheckBox.setSelectedIcon(IconManager.getImageIcon(IconManager.EDIT_MODE_BUTTON_ON));
223 _editmodeCheckBox.setOpaque(false);
224 _editmodeCheckBox.setToolTipText(I18nManager.getText("menu.map.editmode"));
225 _editmodeCheckBox.addItemListener(itemListener);
226 _editmodeCheckBox.setFocusable(false); // stop button from stealing keyboard focus
227 _topPanel.add(_editmodeCheckBox);
229 // Add zoom in, zoom out buttons
230 _sidePanel = new OverlayPanel();
231 _sidePanel.setLayout(new BoxLayout(_sidePanel, BoxLayout.Y_AXIS));
232 JButton zoomInButton = new JButton(IconManager.getImageIcon(IconManager.ZOOM_IN_BUTTON));
233 zoomInButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
234 zoomInButton.setContentAreaFilled(false);
235 zoomInButton.setToolTipText(I18nManager.getText("menu.map.zoomin"));
236 zoomInButton.addActionListener(new ActionListener() {
237 public void actionPerformed(ActionEvent e)
242 zoomInButton.setFocusable(false); // stop button from stealing keyboard focus
243 _sidePanel.add(zoomInButton);
244 JButton zoomOutButton = new JButton(IconManager.getImageIcon(IconManager.ZOOM_OUT_BUTTON));
245 zoomOutButton.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
246 zoomOutButton.setContentAreaFilled(false);
247 zoomOutButton.setToolTipText(I18nManager.getText("menu.map.zoomout"));
248 zoomOutButton.addActionListener(new ActionListener() {
249 public void actionPerformed(ActionEvent e)
254 zoomOutButton.setFocusable(false); // stop button from stealing keyboard focus
255 _sidePanel.add(zoomOutButton);
257 // Bottom panel for scale bar
258 _scaleBar = new ScaleBar();
260 // add control panels to this one
261 setLayout(new BorderLayout());
262 _topPanel.setVisible(false);
263 _sidePanel.setVisible(false);
264 add(_topPanel, BorderLayout.NORTH);
265 add(_sidePanel, BorderLayout.WEST);
266 add(_scaleBar, BorderLayout.SOUTH);
269 // Get currently selected map from Config, pass to MapTileManager
270 _tileManager.setMapSource(Config.getConfigInt(Config.KEY_MAPSOURCE_INDEX));
271 // Update display settings
272 dataUpdated(MAPSERVER_CHANGED);
277 * Make the popup menu for right-clicking the map
279 private void makePopup()
281 _popup = new JPopupMenu();
282 JMenuItem zoomInItem = new JMenuItem(I18nManager.getText("menu.map.zoomin"));
283 zoomInItem.addActionListener(new ActionListener() {
284 public void actionPerformed(ActionEvent e)
286 panMap((_popupMenuX - getWidth()/2)/2, (_popupMenuY - getHeight()/2)/2);
289 _popup.add(zoomInItem);
290 JMenuItem zoomOutItem = new JMenuItem(I18nManager.getText("menu.map.zoomout"));
291 zoomOutItem.addActionListener(new ActionListener() {
292 public void actionPerformed(ActionEvent e)
294 panMap(-(_popupMenuX - getWidth()/2), -(_popupMenuY - getHeight()/2));
297 _popup.add(zoomOutItem);
298 JMenuItem zoomFullItem = new JMenuItem(I18nManager.getText("menu.map.zoomfull"));
299 zoomFullItem.addActionListener(new ActionListener() {
300 public void actionPerformed(ActionEvent e)
306 _popup.add(zoomFullItem);
307 _popup.addSeparator();
309 JMenuItem setMapBgItem = new JMenuItem(
310 I18nManager.getText(FunctionLibrary.FUNCTION_SET_MAP_BG.getNameKey()));
311 setMapBgItem.addActionListener(new ActionListener() {
312 public void actionPerformed(ActionEvent e)
314 FunctionLibrary.FUNCTION_SET_MAP_BG.begin();
316 _popup.add(setMapBgItem);
318 JMenuItem newPointItem = new JMenuItem(I18nManager.getText("menu.map.newpoint"));
319 newPointItem.addActionListener(new ActionListener() {
320 public void actionPerformed(ActionEvent e)
322 _app.createPoint(createPointFromClick(_popupMenuX, _popupMenuY));
324 _popup.add(newPointItem);
326 JMenuItem drawPointsItem = new JMenuItem(I18nManager.getText("menu.map.drawpoints"));
327 drawPointsItem.addActionListener(new ActionListener() {
328 public void actionPerformed(ActionEvent e)
330 _drawMode = MODE_DRAW_POINTS_START;
333 _popup.add(drawPointsItem);
338 * Zoom to fit the current data area
340 private void zoomToFit()
342 _latRange = _track.getLatRange();
343 _lonRange = _track.getLonRange();
344 _xRange = new DoubleRange(MapUtils.getXFromLongitude(_lonRange.getMinimum()),
345 MapUtils.getXFromLongitude(_lonRange.getMaximum()));
346 _yRange = new DoubleRange(MapUtils.getYFromLatitude(_latRange.getMinimum()),
347 MapUtils.getYFromLatitude(_latRange.getMaximum()));
348 _mapPosition.zoomToXY(
349 _xRange.getMinimum(), _xRange.getMaximum(),
350 _yRange.getMinimum(), _yRange.getMaximum(),
351 getWidth(), getHeight(),
352 _tileManager.getMaxZoomLevel());
358 * @see java.awt.Canvas#paint(java.awt.Graphics)
360 public void paint(Graphics inG)
363 if (_mapImage != null && (_mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())) {
366 if (_track.getNumPoints() > 0)
368 // Check for autopan if enabled / necessary
369 if (_autopanCheckBox.isSelected())
371 int selectedPoint = _selection.getCurrentPointIndex();
372 if (selectedPoint >= 0 && _dragFromX == -1 && selectedPoint != _prevSelectedPoint)
374 autopanToPoint(selectedPoint);
376 _prevSelectedPoint = selectedPoint;
379 // Draw the map contents if necessary
380 if (_mapImage == null || _recalculate)
383 _scaleBar.updateScale(_mapPosition.getZoom(), _mapPosition.getYFromPixels(0, 0));
385 // Draw the prepared image onto the panel
386 if (_mapImage != null) {
387 inG.drawImage(_mapImage, 0, 0, getWidth(), getHeight(), null);
392 case MODE_DRAG_POINT:
393 drawDragLines(inG, _selection.getCurrentPointIndex()-1, _selection.getCurrentPointIndex()+1);
396 case MODE_CREATE_MIDPOINT:
397 drawDragLines(inG, _clickedPoint-1, _clickedPoint);
401 case MODE_MARK_RECTANGLE:
402 if (_dragFromX != -1 && _dragFromY != -1)
404 // Draw the zoom rectangle if necessary
405 inG.setColor(Color.RED);
406 inG.drawLine(_dragFromX, _dragFromY, _dragFromX, _dragToY);
407 inG.drawLine(_dragFromX, _dragFromY, _dragToX, _dragFromY);
408 inG.drawLine(_dragToX, _dragFromY, _dragToX, _dragToY);
409 inG.drawLine(_dragFromX, _dragToY, _dragToX, _dragToY);
413 case MODE_DRAW_POINTS_CONT:
414 // draw line to mouse position to show drawing mode
415 inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
416 int prevIndex = _track.getNumPoints()-1;
417 int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(prevIndex));
418 int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(prevIndex));
419 inG.drawLine(px, py, _dragToX, _dragToY);
425 inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
426 inG.fillRect(0, 0, getWidth(), getHeight());
427 inG.setColor(COLOR_MESSAGES);
428 inG.drawString(I18nManager.getText("display.nodata"), 50, getHeight()/2);
429 _scaleBar.updateScale(-1, 0);
431 // Draw slider etc on top
436 * @return true if the currently selected point is visible, false if off-screen or nothing selected
438 private boolean isCurrentPointVisible()
440 if (_trackInfo.getCurrentPoint() == null) {return false;}
441 final int selectedPoint = _selection.getCurrentPointIndex();
442 final int xFromCentre = Math.abs(_mapPosition.getXFromCentre(_track.getX(selectedPoint)));
443 if (xFromCentre > (getWidth()/2)) {return false;}
444 final int yFromCentre = Math.abs(_mapPosition.getYFromCentre(_track.getY(selectedPoint)));
445 return yFromCentre < (getHeight()/2);
449 * If the specified point isn't visible, pan to it
450 * @param inIndex index of selected point
452 private void autopanToPoint(int inIndex)
454 int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inIndex));
455 int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inIndex));
458 if (px < PAN_DISTANCE) {
459 panX = px - AUTOPAN_DISTANCE;
461 else if (px > (getWidth()-PAN_DISTANCE)) {
462 panX = AUTOPAN_DISTANCE + px - getWidth();
464 if (py < (2*PAN_DISTANCE)) {
465 panY = py - AUTOPAN_DISTANCE;
467 if (py > (getHeight()-PAN_DISTANCE)) {
468 panY = AUTOPAN_DISTANCE + py - getHeight();
470 if (panX != 0 || panY != 0) {
471 _mapPosition.pan(panX, panY);
476 * Paint the map tiles and the points on to the _mapImage
478 private void paintMapContents()
480 if (_mapImage == null || _mapImage.getWidth() != getWidth() || _mapImage.getHeight() != getHeight())
482 _mapImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
485 Graphics g = _mapImage.getGraphics();
486 // Set antialiasing according to config
487 ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
488 Config.getConfigBoolean(Config.KEY_ANTIALIAS) ? RenderingHints.VALUE_ANTIALIAS_ON : RenderingHints.VALUE_ANTIALIAS_OFF);
489 // Clear to background
490 g.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND));
491 g.fillRect(0, 0, getWidth(), getHeight());
493 // Check whether maps are on or not
494 final boolean showMap = Config.getConfigBoolean(Config.KEY_SHOW_MAP);
495 _mapCheckBox.setSelected(showMap);
496 // Check whether disk cache is on or not
497 final boolean usingDiskCache = Config.getConfigString(Config.KEY_DISK_CACHE) != null;
498 // Show tip to recommend setting up a cache
499 if (showMap && !usingDiskCache && Config.getConfigBoolean(Config.KEY_ONLINE_MODE))
501 SwingUtilities.invokeLater(new Runnable() {
503 _app.showTip(TipManager.Tip_UseAMapCache);
508 // reset error message
509 if (!showMap) {_shownOsmErrorAlready = false;}
510 _recalculate = false;
511 // Only get map tiles if selected
515 _tileManager.centreMap(_mapPosition.getZoom(), _mapPosition.getCentreTileX(), _mapPosition.getCentreTileY());
517 boolean loadingFailed = false;
518 if (_mapImage == null) return;
520 if (_tileManager.isOverzoomed())
522 // display overzoom message
523 g.setColor(COLOR_MESSAGES);
524 g.drawString(I18nManager.getText("map.overzoom"), 50, getHeight()/2);
528 int numLayers = _tileManager.getNumLayers();
529 // Loop over tiles drawing each one
530 int[] tileIndices = _mapPosition.getTileIndices(getWidth(), getHeight());
531 int[] pixelOffsets = _mapPosition.getDisplayOffsets(getWidth(), getHeight());
532 for (int tileX = tileIndices[0]; tileX <= tileIndices[1] && !loadingFailed; tileX++)
534 int x = (tileX - tileIndices[0]) * 256 - pixelOffsets[0];
535 for (int tileY = tileIndices[2]; tileY <= tileIndices[3]; tileY++)
537 int y = (tileY - tileIndices[2]) * 256 - pixelOffsets[1];
539 for (int l=0; l<numLayers; l++)
541 Image image = _tileManager.getTile(l, tileX, tileY, true);
543 g.drawImage(image, x, y, 256, 256, null);
549 // Make maps brighter / fainter according to slider
550 final int brightnessIndex = Math.max(1, _transparencySlider.getValue()) - 1;
551 if (brightnessIndex > 0)
553 final int[] alphas = {0, 40, 80, 120, 160, 210};
554 Color bgColor = Config.getColourScheme().getColour(ColourScheme.IDX_BACKGROUND);
555 bgColor = new Color(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), alphas[brightnessIndex]);
557 g.fillRect(0, 0, getWidth(), getHeight());
562 // Work out track opacity according to slider
563 final float[] opacities = {1.0f, 0.75f, 0.5f, 0.3f, 0.15f, 0.0f};
564 float trackOpacity = 1.0f;
565 if (_transparencySlider.getValue() < 0) {
566 trackOpacity = opacities[-1 - _transparencySlider.getValue()];
569 if (trackOpacity > 0.0f)
571 // Paint the track points on top
572 boolean pointsPainted = true;
575 if (trackOpacity > 0.9f)
577 // Track is fully opaque, just draw it directly
578 pointsPainted = paintPoints(g);
583 // Track is partly transparent, so use a separate BufferedImage
584 if (_trackImage == null || _trackImage.getWidth() != getWidth() || _trackImage.getHeight() != getHeight())
586 _trackImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
588 // Clear to transparent
589 Graphics2D gTrack = _trackImage.createGraphics();
590 gTrack.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
591 gTrack.fillRect(0, 0, getWidth(), getHeight());
592 gTrack.setPaintMode();
593 // Draw the track onto this separate image
594 pointsPainted = paintPoints(gTrack);
595 ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, trackOpacity));
596 g.drawImage(_trackImage, 0, 0, null);
599 catch (NullPointerException npe) {} // ignore, probably due to data being changed during drawing
600 catch (ArrayIndexOutOfBoundsException obe) {} // also ignore
602 // Zoom to fit if no points found
603 if (!pointsPainted && _checkBounds)
614 _checkBounds = false;
615 // enable / disable transparency slider
616 _transparencySlider.setEnabled(showMap);
621 * Paint the points using the given graphics object
622 * @param inG Graphics object to use for painting
623 * @return true if any points or lines painted
625 private boolean paintPoints(Graphics inG)
628 final ColourScheme cs = Config.getColourScheme();
629 final Color pointColour = cs.getColour(ColourScheme.IDX_POINT);
630 final Color rangeColour = cs.getColour(ColourScheme.IDX_SELECTION);
631 final Color currentColour = cs.getColour(ColourScheme.IDX_PRIMARY);
632 final Color secondColour = cs.getColour(ColourScheme.IDX_SECONDARY);
633 final Color textColour = cs.getColour(ColourScheme.IDX_TEXT);
634 final PointColourer pointColourer = _app.getPointColourer();
636 final int winWidth = getWidth();
637 final int winHeight = getHeight();
638 final int halfWinWidth = winWidth / 2;
639 final int halfWinHeight = winHeight / 2;
641 final int numPoints = _track.getNumPoints();
642 final int[] xPixels = new int[numPoints];
643 final int[] yPixels = new int[numPoints];
645 final int pointSeparationForArrowsSqd = 350;
646 final int pointSeparation1dForArrows = (int) (Math.sqrt(pointSeparationForArrowsSqd) * 0.7);
648 // try to set line width for painting
649 if (inG instanceof Graphics2D)
651 int lineWidth = Config.getConfigInt(Config.KEY_LINE_WIDTH);
652 if (lineWidth < 1 || lineWidth > 4) {lineWidth = 2;}
653 ((Graphics2D) inG).setStroke(new BasicStroke(lineWidth));
656 boolean pointsPainted = false;
658 inG.setColor(pointColour);
659 int prevX = -1, prevY = -1;
660 final int connectState = _connectCheckBox.getCurrentState();
661 final boolean drawLines = (connectState != 3); // 0, 1 or 2
662 final boolean drawPoints = (connectState != 1); // 0, 2 or 3
663 final boolean drawArrows = (connectState == 0); // 0
665 boolean prevPointVisible = false, currPointVisible = false;
666 boolean anyWaypoints = false;
667 boolean isWaypoint = false;
668 boolean drawnLastArrow = false; // avoid painting arrows on adjacent lines, looks too busy
669 for (int i=0; i<numPoints; i++)
671 // Calculate pixel position of point from its x, y coordinates
672 int px = halfWinWidth + _mapPosition.getXFromCentre(_track.getX(i));
673 int py = halfWinHeight + _mapPosition.getYFromCentre(_track.getY(i));
674 px = wrapLongitudeValue(px, winWidth, _mapPosition.getZoom());
675 // Remember these calculated pixel values so they don't have to be recalculated
676 xPixels[i] = px; yPixels[i] = py;
678 currPointVisible = px >= 0 && px < winWidth && py >= 0 && py < winHeight;
679 isWaypoint = _track.getPoint(i).isWaypoint();
680 anyWaypoints = anyWaypoints || isWaypoint;
683 if (currPointVisible || (drawLines && prevPointVisible))
685 // For track points, work out which colour to use
686 if (_track.getPoint(i).getDeleteFlag()) {
687 inG.setColor(currentColour);
689 else if (pointColourer != null)
690 { // use the point colourer if there is one
691 Color trackColour = pointColourer.getColour(i);
692 inG.setColor(trackColour);
696 inG.setColor(pointColour);
699 // Draw rectangle for track point if it's visible
700 if (currPointVisible)
703 inG.drawRect(px-2, py-2, 3, 3);
705 pointsPainted = true;
709 // Connect track points if either of them are visible
711 && (currPointVisible || prevPointVisible)
712 && !(prevX == -1 && prevY == -1)
713 && !_track.getPoint(i).getSegmentStart())
715 inG.drawLine(prevX, prevY, px, py);
716 pointsPainted = true;
718 // Now consider whether we need to draw an arrow as well
721 && (Math.abs(prevX-px) > pointSeparation1dForArrows || Math.abs(prevY-py) > pointSeparation1dForArrows))
723 final double pointSeparationSqd = (prevX-px) * (prevX-px) + (prevY-py) * (prevY-py);
724 if (pointSeparationSqd > pointSeparationForArrowsSqd)
726 final double midX = (prevX + px) / 2;
727 final double midY = (prevY + py) / 2;
728 final boolean midPointVisible = midX >= 0 && midX < winWidth && midY >= 0 && midY < winHeight;
731 final double alpha = Math.atan2(py - prevY, px - prevX);
732 //System.out.println("Draw arrow from (" + prevX + "," + prevY + ") to (" + px + "," + py
733 // + ") with angle" + (int) (alpha * 180/Math.PI));
734 final double MID_TO_VERTEX = 3.0;
735 final double arrowX = MID_TO_VERTEX * Math.cos(alpha);
736 final double arrowY = MID_TO_VERTEX * Math.sin(alpha);
737 final double vertexX = midX + arrowX;
738 final double vertexY = midY + arrowY;
739 inG.drawLine((int)(midX-arrowX-2*arrowY), (int)(midY-arrowY+2*arrowX), (int)vertexX, (int)vertexY);
740 inG.drawLine((int)(midX-arrowX+2*arrowY), (int)(midY-arrowY-2*arrowX), (int)vertexX, (int)vertexY);
742 drawnLastArrow = midPointVisible;
747 drawnLastArrow = false;
750 prevX = px; prevY = py;
752 prevPointVisible = currPointVisible;
755 // Loop over points, just drawing blobs for waypoints
756 inG.setColor(textColour);
757 FontMetrics fm = inG.getFontMetrics();
758 int nameHeight = fm.getHeight();
761 int numWaypoints = 0;
762 for (int i=0; i<_track.getNumPoints(); i++)
764 if (_track.getPoint(i).isWaypoint())
768 if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
770 if (_waypointIconDefinition == null)
772 inG.fillRect(px-3, py-3, 6, 6);
776 ImageIcon icon = _waypointIconDefinition.getImageIcon();
779 inG.drawImage(icon.getImage(), px-_waypointIconDefinition.getXOffset(),
780 py-_waypointIconDefinition.getYOffset(), null);
783 pointsPainted = true;
788 // Take more care with waypoint names if less than 100 are visible
789 final int numNameSteps = (numWaypoints > 100 ? 1 : 4);
790 final int numPointSteps = (numWaypoints > 1000 ? 2 : 1);
792 // Loop over points again, now draw names for waypoints
793 int[] nameXs = {0, 0, 0, 0};
794 int[] nameYs = {0, 0, 0, 0};
795 for (int i=0; i<_track.getNumPoints(); i += numPointSteps)
797 if (_track.getPoint(i).isWaypoint())
801 if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
803 // Figure out where to draw waypoint name so it doesn't obscure track
804 String waypointName = _track.getPoint(i).getWaypointName();
805 int nameWidth = fm.stringWidth(waypointName);
806 boolean drawnName = false;
807 // Make arrays for coordinates right left up down
808 nameXs[0] = px + 2; nameXs[1] = px - nameWidth - 2;
809 nameXs[2] = nameXs[3] = px - nameWidth/2;
810 nameYs[0] = nameYs[1] = py + (nameHeight/2);
811 nameYs[2] = py - 2; nameYs[3] = py + nameHeight + 2;
812 for (int extraSpace = 0; extraSpace < numNameSteps && !drawnName; extraSpace++)
814 // Shift arrays for coordinates right left up down
815 nameXs[0] += 3; nameXs[1] -= 3;
816 nameYs[2] -= 3; nameYs[3] += 3;
817 // Check each direction in turn right left up down
818 for (int a=0; a<4; a++)
820 if (nameXs[a] > 0 && (nameXs[a] + nameWidth) < winWidth
821 && nameYs[a] < winHeight && (nameYs[a] - nameHeight) > 0
822 && !MapUtils.overlapsPoints(_mapImage, nameXs[a], nameYs[a], nameWidth, nameHeight, textColour))
824 // Found a rectangle to fit - draw name here and quit
825 inG.drawString(waypointName, nameXs[a], nameYs[a]);
835 // Loop over points, drawing blobs for photo / audio points
836 inG.setColor(secondColour);
837 for (int i=0; i<_track.getNumPoints(); i++)
839 if (_track.getPoint(i).hasMedia())
843 if (px >= 0 && px < winWidth && py >= 0 && py < winHeight)
845 inG.drawRect(px-1, py-1, 2, 2);
846 inG.drawRect(px-2, py-2, 4, 4);
847 pointsPainted = true;
852 // Draw selected range
853 if (_selection.hasRangeSelected())
855 inG.setColor(rangeColour);
856 for (int i=_selection.getStart(); i<=_selection.getEnd(); i++)
860 inG.drawRect(px-1, py-1, 2, 2);
864 // Draw crosshairs at selected point
865 int selectedPoint = _selection.getCurrentPointIndex();
866 if (selectedPoint >= 0)
868 int px = xPixels[selectedPoint];
869 int py = yPixels[selectedPoint];
870 inG.setColor(currentColour);
872 inG.drawLine(px, 0, px, winHeight);
873 inG.drawLine(0, py, winWidth, py);
875 // Return the number of points painted
876 return pointsPainted;
880 * Wrap the given pixel value if appropriate and possible
881 * @param inPx Pixel x coordinate
882 * @param inWinWidth window width in pixels
883 * @param inZoom zoom level
884 * @return modified pixel x coordinate
886 private static int wrapLongitudeValue(int inPx, int inWinWidth, int inZoom)
888 if (inPx > inWinWidth)
890 // Pixel is too far right, could we wrap it back onto the screen?
892 while (px > inWinWidth) {
893 px -= (256 << inZoom);
896 return px; // successfully wrapped back onto the screen
901 // Pixel is too far left, could we wrap it back onto the screen?
904 px += (256 << inZoom);
906 if (px < inWinWidth) {
907 return px; // successfully wrapped back onto the screen
910 // Either it's already on the screen or couldn't be wrapped
915 * Draw the lines while dragging a point
916 * @param inG graphics object
917 * @param inPrevIndex index of point to draw from
918 * @param inNextIndex index of point to draw to
920 private void drawDragLines(Graphics inG, int inPrevIndex, int inNextIndex)
922 inG.setColor(Config.getColourScheme().getColour(ColourScheme.IDX_POINT));
923 // line from prev point to cursor
924 if (inPrevIndex > -1 && !_track.getPoint(inPrevIndex+1).getSegmentStart())
926 final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inPrevIndex));
927 final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inPrevIndex));
928 inG.drawLine(px, py, _dragToX, _dragToY);
930 if (inNextIndex < _track.getNumPoints() && !_track.getPoint(inNextIndex).getSegmentStart())
932 final int px = getWidth() / 2 + _mapPosition.getXFromCentre(_track.getX(inNextIndex));
933 final int py = getHeight() / 2 + _mapPosition.getYFromCentre(_track.getY(inNextIndex));
934 inG.drawLine(px, py, _dragToX, _dragToY);
939 * Inform that tiles have been updated and the map can be repainted
940 * @param inIsOk true if data loaded ok, false for error
942 public void tilesUpdated(boolean inIsOk)
946 // Show message if loading failed (but not too many times)
947 if (!inIsOk && !_shownOsmErrorAlready && _mapCheckBox.isSelected())
949 _shownOsmErrorAlready = true;
950 // use separate thread to show message about failing to load osm images
951 new Thread(new Runnable() {
953 try {Thread.sleep(500);} catch (InterruptedException ie) {}
954 _app.showErrorMessage("error.osmimage.dialogtitle", "error.osmimage.failed");
964 * Zoom out, if not already at minimum zoom
966 public void zoomOut()
968 _mapPosition.zoomOut();
974 * Zoom in, if not already at maximum zoom
978 // See if selected point is currently visible, if so (and autopan on) then autopan after zoom to keep it visible
979 boolean wasVisible = _autopanCheckBox.isSelected() && isCurrentPointVisible();
980 _mapPosition.zoomIn();
981 if (wasVisible && !isCurrentPointVisible()) {
982 autopanToPoint(_selection.getCurrentPointIndex());
990 * @param inDeltaX x shift
991 * @param inDeltaY y shift
993 public void panMap(int inDeltaX, int inDeltaY)
995 _mapPosition.pan(inDeltaX, inDeltaY);
1001 * Create a DataPoint object from the given click coordinates
1002 * @param inX x coordinate of click
1003 * @param inY y coordinate of click
1004 * @return DataPoint with given coordinates and no altitude
1006 private DataPoint createPointFromClick(int inX, int inY)
1008 double lat = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(inY, getHeight()));
1009 double lon = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(inX, getWidth()));
1010 return new DataPoint(new Latitude(lat, Coordinate.FORMAT_NONE),
1011 new Longitude(lon, Coordinate.FORMAT_NONE), null);
1015 * Move a DataPoint object to the given mouse coordinates
1016 * @param startX start x coordinate of mouse
1017 * @param startY start y coordinate of mouse
1018 * @param endX end x coordinate of mouse
1019 * @param endY end y coordinate of mouse
1021 private void movePointToMouse(int startX, int startY, int endX, int endY )
1023 double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(startY, getHeight()));
1024 double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(startX, getWidth()));
1025 double lat_delta = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(endY, getHeight())) - lat1;
1026 double lon_delta = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(endX, getWidth())) - lon1;
1028 DataPoint point = _trackInfo.getCurrentPoint();
1029 if (point == null) {
1033 // Make lists for edit and undo, and add each changed field in turn
1034 FieldEditList editList = new FieldEditList();
1035 FieldEditList undoList = new FieldEditList();
1038 FieldList fieldList = _track.getFieldList();
1039 int numFields = fieldList.getNumFields();
1040 for (int i=0; i<numFields; i++)
1042 Field field = fieldList.getField(i);
1043 if (field == Field.LATITUDE) {
1044 editList.addEdit(new FieldEdit(field, Double.toString(point.getLatitude().getDouble() + lat_delta)));
1045 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LATITUDE)));
1047 else if (field == Field.LONGITUDE) {
1048 editList.addEdit(new FieldEdit(field, Double.toString(point.getLongitude().getDouble() + lon_delta)));
1049 undoList.addEdit(new FieldEdit(field, point.getFieldValue(Field.LONGITUDE)));
1052 _app.completePointEdit(editList, undoList);
1057 * @see javax.swing.JComponent#getMinimumSize()
1059 public Dimension getMinimumSize()
1061 final Dimension minSize = new Dimension(512, 300);
1066 * @see javax.swing.JComponent#getPreferredSize()
1068 public Dimension getPreferredSize()
1070 return getMinimumSize();
1075 * Respond to mouse click events
1076 * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
1078 public void mouseClicked(MouseEvent inE)
1080 if (_track != null && _track.getNumPoints() > 0)
1082 // select point if it's a left-click
1083 if (!inE.isMetaDown())
1085 if (inE.getClickCount() == 1)
1088 if (_drawMode == MODE_DEFAULT)
1090 int pointIndex = _clickedPoint;
1091 if (pointIndex == INDEX_UNKNOWN)
1093 // index hasn't been calculated yet
1094 pointIndex = _track.getNearestPointIndex(
1095 _mapPosition.getXFromPixels(inE.getX(), getWidth()),
1096 _mapPosition.getYFromPixels(inE.getY(), getHeight()),
1097 _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY), false);
1099 // Extend selection for shift-click
1100 if (inE.isShiftDown()) {
1101 _trackInfo.extendSelection(pointIndex);
1104 _trackInfo.selectPoint(pointIndex);
1107 else if (_drawMode == MODE_DRAW_POINTS_START)
1109 _app.createPoint(createPointFromClick(inE.getX(), inE.getY()));
1110 _dragToX = inE.getX();
1111 _dragToY = inE.getY();
1112 _drawMode = MODE_DRAW_POINTS_CONT;
1114 else if (_drawMode == MODE_DRAW_POINTS_CONT)
1116 DataPoint point = createPointFromClick(inE.getX(), inE.getY());
1117 _app.createPoint(point, false); // not a new segment
1120 else if (inE.getClickCount() == 2)
1123 if (_drawMode == MODE_DEFAULT) {
1124 panMap(inE.getX() - getWidth()/2, inE.getY() - getHeight()/2);
1127 else if (_drawMode == MODE_DRAW_POINTS_START || _drawMode == MODE_DRAW_POINTS_CONT) {
1128 _drawMode = MODE_DEFAULT;
1134 // show the popup menu for right-clicks
1135 _popupMenuX = inE.getX();
1136 _popupMenuY = inE.getY();
1137 _popup.show(this, _popupMenuX, _popupMenuY);
1141 _app.setCurrentMode(App.AppMode.NORMAL);
1142 if (_drawMode == MODE_MARK_RECTANGLE) _drawMode = MODE_DEFAULT;
1146 * Ignore mouse enter events
1147 * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
1149 public void mouseEntered(MouseEvent inE)
1155 * Ignore mouse exited events
1156 * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
1158 public void mouseExited(MouseEvent inE)
1164 * React to mouse pressed events to initiate a point drag
1165 * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
1167 public void mousePressed(MouseEvent inE)
1169 _clickedPoint = INDEX_UNKNOWN;
1170 if (_track == null || _track.getNumPoints() <= 0)
1172 if (!inE.isMetaDown())
1174 // Left mouse drag - check if point is near; if so select it for dragging
1175 if (_drawMode == MODE_DEFAULT)
1177 /* Drag points if edit mode is enabled OR ALT is pressed */
1178 if (_editmodeCheckBox.isSelected() || inE.isAltDown() || inE.isAltGraphDown())
1180 final double clickX = _mapPosition.getXFromPixels(inE.getX(), getWidth());
1181 final double clickY = _mapPosition.getYFromPixels(inE.getY(), getHeight());
1182 final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1183 _clickedPoint = _track.getNearestPointIndex(clickX, clickY, clickSens, false);
1185 if (_clickedPoint >= 0)
1187 // TODO: maybe use another color of the cross or remove the cross while dragging???
1189 _trackInfo.selectPoint(_clickedPoint);
1190 if (_trackInfo.getCurrentPoint() != null)
1192 _drawMode = MODE_DRAG_POINT;
1193 _dragFromX = _dragToX = inE.getX();
1194 _dragFromY = _dragToY = inE.getY();
1199 // Not a click on a point, so check half-way between two (connected) trackpoints
1200 int midpointIndex = _midpoints.getNearestPointIndex(clickX, clickY, clickSens);
1201 if (midpointIndex > 0)
1203 _drawMode = MODE_CREATE_MIDPOINT;
1204 _clickedPoint = midpointIndex;
1205 _dragFromX = _dragToX = inE.getX();
1206 _dragFromY = _dragToY = inE.getY();
1212 // else right-press ignored
1216 * Respond to mouse released events
1217 * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
1219 public void mouseReleased(MouseEvent inE)
1221 _recalculate = true;
1223 if (_drawMode == MODE_DRAG_POINT)
1225 if (Math.abs(_dragToX - _dragFromX) > 2
1226 || Math.abs(_dragToY - _dragFromY) > 2)
1228 movePointToMouse(_dragFromX, _dragFromY, _dragToX, _dragToY );
1230 _drawMode = MODE_DEFAULT;
1232 else if (_drawMode == MODE_CREATE_MIDPOINT)
1234 _drawMode = MODE_DEFAULT;
1235 _app.createPoint(createPointFromClick(_dragToX, _dragToY), _clickedPoint);
1237 else if (_drawMode == MODE_ZOOM_RECT)
1239 if (Math.abs(_dragToX - _dragFromX) > 20
1240 && Math.abs(_dragToY - _dragFromY) > 20)
1242 _mapPosition.zoomToPixels(_dragFromX, _dragToX, _dragFromY, _dragToY, getWidth(), getHeight());
1244 _drawMode = MODE_DEFAULT;
1246 else if (_drawMode == MODE_MARK_RECTANGLE)
1249 _app.setCurrentMode(App.AppMode.NORMAL);
1250 _drawMode = MODE_DEFAULT;
1251 // Call a function to mark the points
1252 MarkPointsInRectangleFunction marker = (MarkPointsInRectangleFunction) FunctionLibrary.FUNCTION_MARK_IN_RECTANGLE;
1253 double lon1 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragFromX, getWidth()));
1254 double lat1 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragFromY, getHeight()));
1255 double lon2 = MapUtils.getLongitudeFromX(_mapPosition.getXFromPixels(_dragToX, getWidth()));
1256 double lat2 = MapUtils.getLatitudeFromY(_mapPosition.getYFromPixels(_dragToY, getHeight()));
1257 // Invalidate rectangle if pixel coords are (-1,-1)
1258 if (_dragFromX < 0 || _dragFromY < 0) {
1262 marker.setRectCoords(lon1, lat1, lon2, lat2);
1265 _dragFromX = _dragFromY = -1;
1270 * Respond to mouse drag events
1271 * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
1273 public void mouseDragged(MouseEvent inE)
1275 // Note: One would expect inE.isMetaDown() to give information about whether this is a
1276 // drag with the right mouse button or not - but since java 9 this is buggy,
1277 // so we use the beautifully-named getModifiersEx() instead.
1278 // And logically BUTTON3 refers to the secondary mouse button, not the tertiary one!
1279 final boolean isRightDrag = (inE.getModifiersEx() & InputEvent.BUTTON3_DOWN_MASK) > 0;
1282 // Right-click and drag - update rectangle
1283 _drawMode = MODE_ZOOM_RECT;
1284 if (_dragFromX == -1) {
1285 _dragFromX = inE.getX();
1286 _dragFromY = inE.getY();
1288 _dragToX = inE.getX();
1289 _dragToY = inE.getY();
1294 // Left mouse drag - decide whether to drag the point, drag the
1295 // marking rectangle or pan the map
1296 if (_drawMode == MODE_DRAG_POINT || _drawMode == MODE_CREATE_MIDPOINT)
1299 _dragToX = inE.getX();
1300 _dragToY = inE.getY();
1301 _recalculate = true;
1304 else if (_drawMode == MODE_MARK_RECTANGLE)
1306 // draw a rectangle for marking points
1307 if (_dragFromX == -1) {
1308 _dragFromX = inE.getX();
1309 _dragFromY = inE.getY();
1311 _dragToX = inE.getX();
1312 _dragToY = inE.getY();
1317 // regular left-drag pans map by appropriate amount
1318 if (_dragFromX != -1)
1320 panMap(_dragFromX - inE.getX(), _dragFromY - inE.getY());
1322 _dragFromX = _dragToX = inE.getX();
1323 _dragFromY = _dragToY = inE.getY();
1329 * Respond to mouse move events without button pressed
1330 * @param inEvent ignored
1332 public void mouseMoved(MouseEvent inEvent)
1334 boolean useCrosshairs = false;
1335 boolean useResize = false;
1336 // Ignore unless we're drawing points
1337 if (_drawMode == MODE_DRAW_POINTS_CONT)
1339 _dragToX = inEvent.getX();
1340 _dragToY = inEvent.getY();
1343 else if (_drawMode == MODE_MARK_RECTANGLE) {
1346 else if (_editmodeCheckBox.isSelected() || inEvent.isAltDown() || inEvent.isAltGraphDown())
1348 // Try to find a point or a midpoint at this location, and if there is one
1349 // then change the cursor to crosshairs
1350 final double clickX = _mapPosition.getXFromPixels(inEvent.getX(), getWidth());
1351 final double clickY = _mapPosition.getYFromPixels(inEvent.getY(), getHeight());
1352 final double clickSens = _mapPosition.getBoundsFromPixels(CLICK_SENSITIVITY);
1353 useCrosshairs = (_track.getNearestPointIndex(clickX, clickY, clickSens, false) >= 0
1354 || _midpoints.getNearestPointIndex(clickX, clickY, clickSens) >= 0
1357 if (useCrosshairs && !isCursorSet()) {
1358 setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
1360 else if (useResize && !isCursorSet()) {
1361 setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1363 else if (!useCrosshairs && !useResize && isCursorSet()) {
1369 * Respond to status bar message from broker
1370 * @param inMessage message, ignored
1372 public void actionCompleted(String inMessage)
1378 * Respond to data updated message from broker
1379 * @param inUpdateType type of update
1381 public void dataUpdated(byte inUpdateType)
1383 _recalculate = true;
1384 if ((inUpdateType & DataSubscriber.DATA_ADDED_OR_REMOVED) > 0) {
1385 _checkBounds = true;
1387 if ((inUpdateType & DataSubscriber.MAPSERVER_CHANGED) > 0)
1389 // Get the selected map source index and pass to tile manager
1390 _tileManager.setMapSource(Config.getConfigInt(Config.KEY_MAPSOURCE_INDEX));
1391 final int wpType = Config.getConfigInt(Config.KEY_WAYPOINT_ICONS);
1392 if (wpType == WpIconLibrary.WAYPT_DEFAULT)
1394 _waypointIconDefinition = null;
1398 final int wpSize = Config.getConfigInt(Config.KEY_WAYPOINT_ICON_SIZE);
1399 _waypointIconDefinition = WpIconLibrary.getIconDefinition(wpType, wpSize);
1402 if ((inUpdateType & (DataSubscriber.DATA_ADDED_OR_REMOVED + DataSubscriber.DATA_EDITED)) > 0) {
1403 _midpoints.updateData(_track);
1405 // See if rect mode has been activated
1406 if (_app.getCurrentMode() == App.AppMode.DRAWRECT)
1408 _drawMode = MODE_MARK_RECTANGLE;
1409 if (!isCursorSet()) {
1410 setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
1414 // enable or disable components
1415 boolean hasData = _track.getNumPoints() > 0;
1416 _topPanel.setVisible(hasData);
1417 _sidePanel.setVisible(hasData);
1418 // grab focus for the key presses
1419 this.requestFocus();
1423 * Respond to key presses on the map canvas
1424 * @param inE key event
1426 public void keyPressed(KeyEvent inE)
1428 int code = inE.getKeyCode();
1429 int currPointIndex = _selection.getCurrentPointIndex();
1430 // Check for Ctrl key (for Linux/Win) or meta key (Clover key for Mac)
1431 if (inE.isControlDown() || inE.isMetaDown())
1433 // Shift as well makes things faster
1434 final int pointIncrement = inE.isShiftDown()?3:1;
1435 // Check for arrow keys to zoom in and out
1436 if (code == KeyEvent.VK_UP)
1438 else if (code == KeyEvent.VK_DOWN)
1440 // Key nav for next/prev point
1441 else if (code == KeyEvent.VK_LEFT && currPointIndex > 0)
1442 _trackInfo.incrementPointIndex(-pointIncrement);
1443 else if (code == KeyEvent.VK_RIGHT)
1444 _trackInfo.incrementPointIndex(pointIncrement);
1445 else if (code == KeyEvent.VK_PAGE_UP)
1446 _trackInfo.selectPoint(Checker.getPreviousSegmentStart(
1447 _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1448 else if (code == KeyEvent.VK_PAGE_DOWN)
1449 _trackInfo.selectPoint(Checker.getNextSegmentStart(
1450 _trackInfo.getTrack(), _trackInfo.getSelection().getCurrentPointIndex()));
1451 // Check for home and end
1452 else if (code == KeyEvent.VK_HOME)
1453 _trackInfo.selectPoint(0);
1454 else if (code == KeyEvent.VK_END)
1455 _trackInfo.selectPoint(_trackInfo.getTrack().getNumPoints()-1);
1459 // Check for arrow keys to pan
1461 if (code == KeyEvent.VK_UP)
1462 upwardsPan = -PAN_DISTANCE;
1463 else if (code == KeyEvent.VK_DOWN)
1464 upwardsPan = PAN_DISTANCE;
1465 int rightwardsPan = 0;
1466 if (code == KeyEvent.VK_RIGHT)
1467 rightwardsPan = PAN_DISTANCE;
1468 else if (code == KeyEvent.VK_LEFT)
1469 rightwardsPan = -PAN_DISTANCE;
1470 panMap(rightwardsPan, upwardsPan);
1472 if (code == KeyEvent.VK_ESCAPE)
1473 _drawMode = MODE_DEFAULT;
1474 // Check for backspace key to delete current point (delete key already handled by menu)
1475 else if (code == KeyEvent.VK_BACK_SPACE && currPointIndex >= 0) {
1476 _app.deleteCurrentPoint();
1482 * @param inE key released event, ignored
1484 public void keyReleased(KeyEvent e)
1490 * @param inE key typed event, ignored
1492 public void keyTyped(KeyEvent inE)
1498 * @param inE mouse wheel event indicating scroll direction
1500 public void mouseWheelMoved(MouseWheelEvent inE)
1502 int clicks = inE.getWheelRotation();
1504 panMap((inE.getX() - getWidth()/2)/2, (inE.getY() - getHeight()/2)/2);
1507 else if (clicks > 0) {
1508 panMap(-(inE.getX() - getWidth()/2), -(inE.getY() - getHeight()/2));
1514 * @return current map position
1516 public MapPosition getMapPosition()
1518 return _mapPosition;