001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Cursor;
007import java.awt.Point;
008import java.awt.event.ActionEvent;
009import java.awt.event.InputEvent;
010import java.awt.event.KeyEvent;
011import java.awt.event.MouseAdapter;
012import java.awt.event.MouseEvent;
013import java.awt.event.MouseWheelEvent;
014import java.util.ArrayList;
015import java.util.Optional;
016
017import javax.swing.AbstractAction;
018
019import org.openstreetmap.gui.jmapviewer.JMapViewer;
020import org.openstreetmap.josm.actions.mapmode.SelectAction;
021import org.openstreetmap.josm.data.coor.EastNorth;
022import org.openstreetmap.josm.data.preferences.BooleanProperty;
023import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
024import org.openstreetmap.josm.spi.preferences.Config;
025import org.openstreetmap.josm.spi.preferences.PreferenceChangeEvent;
026import org.openstreetmap.josm.spi.preferences.PreferenceChangedListener;
027import org.openstreetmap.josm.tools.Destroyable;
028import org.openstreetmap.josm.tools.Pair;
029import org.openstreetmap.josm.tools.PlatformManager;
030import org.openstreetmap.josm.tools.Shortcut;
031
032/**
033 * Enables moving of the map by holding down the right mouse button and drag
034 * the mouse. Also, enables zooming by the mouse wheel.
035 *
036 * @author imi
037 */
038public class MapMover extends MouseAdapter implements Destroyable {
039
040    /**
041     * Zoom wheel is reversed.
042     */
043    public static final BooleanProperty PROP_ZOOM_REVERSE_WHEEL = new BooleanProperty("zoom.reverse-wheel", false);
044
045    static {
046        new JMapViewerUpdater();
047    }
048
049    private static class JMapViewerUpdater implements PreferenceChangedListener {
050
051        JMapViewerUpdater() {
052            Config.getPref().addPreferenceChangeListener(this);
053            updateJMapViewer();
054        }
055
056        @Override
057        public void preferenceChanged(PreferenceChangeEvent e) {
058            if (MapMover.PROP_ZOOM_REVERSE_WHEEL.getKey().equals(e.getKey())) {
059                updateJMapViewer();
060            }
061        }
062
063        private static void updateJMapViewer() {
064            JMapViewer.zoomReverseWheel = MapMover.PROP_ZOOM_REVERSE_WHEEL.get();
065        }
066    }
067
068    private final class ZoomerAction extends AbstractAction {
069        private final String action;
070
071        ZoomerAction(String action) {
072            this(action, "MapMover.Zoomer." + action);
073        }
074
075        ZoomerAction(String action, String name) {
076            this.action = action;
077            putValue(NAME, name);
078        }
079
080        @Override
081        public void actionPerformed(ActionEvent e) {
082            if (".".equals(action) || ",".equals(action)) {
083                Point mouse = Optional.ofNullable(nc.getMousePosition()).orElseGet(
084                    () -> new Point((int) nc.getBounds().getCenterX(), (int) nc.getBounds().getCenterY()));
085                mouseWheelMoved(new MouseWheelEvent(nc, e.getID(), e.getWhen(), e.getModifiers(), mouse.x, mouse.y, 0, false,
086                        MouseWheelEvent.WHEEL_UNIT_SCROLL, 1, ",".equals(action) ? -1 : 1));
087            } else {
088                EastNorth center = nc.getCenter();
089                EastNorth newcenter = nc.getEastNorth(nc.getWidth()/2+nc.getWidth()/5, nc.getHeight()/2+nc.getHeight()/5);
090                switch (action) {
091                case "left":
092                    nc.zoomTo(new EastNorth(2*center.east()-newcenter.east(), center.north()));
093                    break;
094                case "right":
095                    nc.zoomTo(new EastNorth(newcenter.east(), center.north()));
096                    break;
097                case "up":
098                    nc.zoomTo(new EastNorth(center.east(), 2*center.north()-newcenter.north()));
099                    break;
100                case "down":
101                    nc.zoomTo(new EastNorth(center.east(), newcenter.north()));
102                    break;
103                case "center":
104                    Optional.ofNullable(nc.getMousePosition()).ifPresent(p -> nc.zoomTo(nc.getEastNorth(p.x, p.y))); 
105                    break;
106                default: // Do nothing
107                }
108            }
109        }
110    }
111
112    /**
113     * The point in the map that was the under the mouse point
114     * when moving around started.
115     *
116     * This is <code>null</code> if movement is not active
117     */
118    private MapViewPoint mousePosMoveStart;
119
120    /**
121     * The map to move around.
122     */
123    private final NavigatableComponent nc;
124
125    private final ArrayList<Pair<ZoomerAction, Shortcut>> registeredShortcuts = new ArrayList<>();
126
127    /**
128     * Constructs a new {@code MapMover}.
129     * @param navComp the navigable component
130     * @since 11713
131     */
132    public MapMover(NavigatableComponent navComp) {
133        this.nc = navComp;
134        nc.addMouseListener(this);
135        nc.addMouseMotionListener(this);
136        nc.addMouseWheelListener(this);
137
138        registerActionShortcut(new ZoomerAction("right"),
139                Shortcut.registerShortcut("system:movefocusright", tr("Map: {0}", tr("Move right")), KeyEvent.VK_RIGHT, Shortcut.CTRL));
140
141        registerActionShortcut(new ZoomerAction("left"),
142                Shortcut.registerShortcut("system:movefocusleft", tr("Map: {0}", tr("Move left")), KeyEvent.VK_LEFT, Shortcut.CTRL));
143
144        registerActionShortcut(new ZoomerAction("up"),
145                Shortcut.registerShortcut("system:movefocusup", tr("Map: {0}", tr("Move up")), KeyEvent.VK_UP, Shortcut.CTRL));
146        registerActionShortcut(new ZoomerAction("down"),
147                Shortcut.registerShortcut("system:movefocusdown", tr("Map: {0}", tr("Move down")), KeyEvent.VK_DOWN, Shortcut.CTRL));
148        registerActionShortcut(new ZoomerAction("center"),
149                Shortcut.registerShortcut("view:centeratmouse", tr("Map: {0}", tr("Center view at mouse position")),
150                KeyEvent.VK_HOME, Shortcut.CTRL));
151
152        // see #10592 - Disable these alternate shortcuts on OS X because of conflict with system shortcut
153        if (!PlatformManager.isPlatformOsx()) {
154            registerActionShortcut(new ZoomerAction(",", "MapMover.Zoomer.in"),
155                    Shortcut.registerShortcut("view:zoominalternate", tr("Map: {0}", tr("Zoom In")), KeyEvent.VK_COMMA, Shortcut.CTRL));
156
157            registerActionShortcut(new ZoomerAction(".", "MapMover.Zoomer.out"),
158                    Shortcut.registerShortcut("view:zoomoutalternate", tr("Map: {0}", tr("Zoom Out")), KeyEvent.VK_PERIOD, Shortcut.CTRL));
159        }
160    }
161
162    private void registerActionShortcut(ZoomerAction action, Shortcut shortcut) {
163        MainApplication.registerActionShortcut(action, shortcut);
164        registeredShortcuts.add(new Pair<>(action, shortcut));
165    }
166
167    /**
168     * Determines if a map move is in progress.
169     * @return {@code true} if a map move is in progress
170     * @since 13987
171     */
172    public boolean movementInProgress() {
173        return mousePosMoveStart != null;
174    }
175
176    /**
177     * If the right (and only the right) mouse button is pressed, move the map.
178     */
179    @Override
180    public void mouseDragged(MouseEvent e) {
181        int offMask = InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK;
182        boolean allowMovement = (e.getModifiersEx() & (InputEvent.BUTTON3_DOWN_MASK | offMask)) == InputEvent.BUTTON3_DOWN_MASK;
183        if (PlatformManager.isPlatformOsx()) {
184            MapFrame map = MainApplication.getMap();
185            int macMouseMask = InputEvent.CTRL_DOWN_MASK | InputEvent.BUTTON1_DOWN_MASK;
186            boolean macMovement = e.getModifiersEx() == macMouseMask;
187            boolean allowedMode = !map.mapModeSelect.equals(map.mapMode)
188                              || SelectAction.Mode.SELECT == map.mapModeSelect.getMode();
189            allowMovement |= macMovement && allowedMode;
190        }
191        if (allowMovement) {
192            doMoveForDrag(e);
193        } else {
194            endMovement();
195        }
196    }
197
198    private void doMoveForDrag(MouseEvent e) {
199        if (!movementInProgress()) {
200            startMovement(e);
201        }
202        EastNorth center = nc.getCenter();
203        EastNorth mouseCenter = nc.getEastNorth(e.getX(), e.getY());
204        nc.zoomTo(mousePosMoveStart.getEastNorth().add(center).subtract(mouseCenter));
205    }
206
207    /**
208     * Start the movement, if it was the 3rd button (right button).
209     */
210    @Override
211    public void mousePressed(MouseEvent e) {
212        int offMask = InputEvent.BUTTON1_DOWN_MASK | InputEvent.BUTTON2_DOWN_MASK;
213        int macMouseMask = InputEvent.CTRL_DOWN_MASK | InputEvent.BUTTON1_DOWN_MASK;
214        if ((e.getButton() == MouseEvent.BUTTON3 && (e.getModifiersEx() & offMask) == 0) ||
215                (PlatformManager.isPlatformOsx() && e.getModifiersEx() == macMouseMask)) {
216            startMovement(e);
217        }
218    }
219
220    /**
221     * Change the cursor back to it's pre-move cursor.
222     */
223    @Override
224    public void mouseReleased(MouseEvent e) {
225        if (e.getButton() == MouseEvent.BUTTON3 || (PlatformManager.isPlatformOsx() && e.getButton() == MouseEvent.BUTTON1)) {
226            endMovement();
227        }
228    }
229
230    /**
231     * Start movement by setting a new cursor and remember the current mouse
232     * position.
233     * @param e The mouse event that leat to the movement from.
234     */
235    private void startMovement(MouseEvent e) {
236        if (movementInProgress()) {
237            return;
238        }
239        mousePosMoveStart = nc.getState().getForView(e.getX(), e.getY());
240        nc.setNewCursor(Cursor.MOVE_CURSOR, this);
241    }
242
243    /**
244     * End the movement. Setting back the cursor and clear the movement variables
245     */
246    private void endMovement() {
247        if (!movementInProgress()) {
248            return;
249        }
250        nc.resetCursor(this);
251        mousePosMoveStart = null;
252        // Repaint only. Labels refresh on the next still frame
253        nc.repaint();
254    }
255
256    /**
257     * Zoom the map by 1/5th of current zoom per wheel-delta.
258     * @param e The wheel event.
259     */
260    @Override
261    public void mouseWheelMoved(MouseWheelEvent e) {
262        int rotation = Boolean.TRUE.equals(PROP_ZOOM_REVERSE_WHEEL.get()) ? -e.getWheelRotation() : e.getWheelRotation();
263        nc.zoomManyTimes(e.getX(), e.getY(), rotation);
264    }
265
266    /**
267     * Emulates dragging on Mac OSX.
268     */
269    @Override
270    public void mouseMoved(MouseEvent e) {
271        if (!movementInProgress()) {
272            return;
273        }
274        // Mac OSX simulates with  ctrl + mouse 1  the second mouse button hence no dragging events get fired.
275        // Is only the selected mouse button pressed?
276        if (PlatformManager.isPlatformOsx()) {
277            if (e.getModifiersEx() == InputEvent.CTRL_DOWN_MASK) {
278                doMoveForDrag(e);
279            } else {
280                endMovement();
281            }
282        }
283    }
284
285    @Override
286    public void destroy() {
287        for (Pair<ZoomerAction, Shortcut> shortcut : registeredShortcuts) {
288            MainApplication.unregisterActionShortcut(shortcut.a, shortcut.b);
289        }
290    }
291}