1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.actions.mapmode;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
|
---|
5 | import static org.openstreetmap.josm.tools.I18n.marktr;
|
---|
6 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
7 |
|
---|
8 | import java.awt.BasicStroke;
|
---|
9 | import java.awt.Color;
|
---|
10 | import java.awt.Cursor;
|
---|
11 | import java.awt.Graphics2D;
|
---|
12 | import java.awt.Point;
|
---|
13 | import java.awt.Rectangle;
|
---|
14 | import java.awt.Stroke;
|
---|
15 | import java.awt.event.ActionEvent;
|
---|
16 | import java.awt.event.KeyEvent;
|
---|
17 | import java.awt.event.MouseEvent;
|
---|
18 | import java.awt.geom.AffineTransform;
|
---|
19 | import java.awt.geom.GeneralPath;
|
---|
20 | import java.awt.geom.Line2D;
|
---|
21 | import java.awt.geom.NoninvertibleTransformException;
|
---|
22 | import java.awt.geom.Point2D;
|
---|
23 | import java.util.ArrayList;
|
---|
24 | import java.util.Collection;
|
---|
25 | import java.util.LinkedList;
|
---|
26 | import java.util.List;
|
---|
27 |
|
---|
28 | import javax.swing.JCheckBoxMenuItem;
|
---|
29 | import javax.swing.JMenuItem;
|
---|
30 |
|
---|
31 | import org.openstreetmap.josm.Main;
|
---|
32 | import org.openstreetmap.josm.actions.JosmAction;
|
---|
33 | import org.openstreetmap.josm.actions.MergeNodesAction;
|
---|
34 | import org.openstreetmap.josm.command.AddCommand;
|
---|
35 | import org.openstreetmap.josm.command.ChangeCommand;
|
---|
36 | import org.openstreetmap.josm.command.Command;
|
---|
37 | import org.openstreetmap.josm.command.MoveCommand;
|
---|
38 | import org.openstreetmap.josm.command.SequenceCommand;
|
---|
39 | import org.openstreetmap.josm.data.Bounds;
|
---|
40 | import org.openstreetmap.josm.data.coor.EastNorth;
|
---|
41 | import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
|
---|
42 | import org.openstreetmap.josm.data.osm.Node;
|
---|
43 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
44 | import org.openstreetmap.josm.data.osm.Way;
|
---|
45 | import org.openstreetmap.josm.data.osm.WaySegment;
|
---|
46 | import org.openstreetmap.josm.data.preferences.ColorProperty;
|
---|
47 | import org.openstreetmap.josm.gui.MainApplication;
|
---|
48 | import org.openstreetmap.josm.gui.MainMenu;
|
---|
49 | import org.openstreetmap.josm.gui.MapFrame;
|
---|
50 | import org.openstreetmap.josm.gui.MapView;
|
---|
51 | import org.openstreetmap.josm.gui.draw.MapViewPath;
|
---|
52 | import org.openstreetmap.josm.gui.draw.SymbolShape;
|
---|
53 | import org.openstreetmap.josm.gui.layer.Layer;
|
---|
54 | import org.openstreetmap.josm.gui.layer.MapViewPaintable;
|
---|
55 | import org.openstreetmap.josm.gui.layer.OsmDataLayer;
|
---|
56 | import org.openstreetmap.josm.gui.util.GuiHelper;
|
---|
57 | import org.openstreetmap.josm.gui.util.KeyPressReleaseListener;
|
---|
58 | import org.openstreetmap.josm.gui.util.ModifierExListener;
|
---|
59 | import org.openstreetmap.josm.tools.Geometry;
|
---|
60 | import org.openstreetmap.josm.tools.ImageProvider;
|
---|
61 | import org.openstreetmap.josm.tools.Logging;
|
---|
62 | import org.openstreetmap.josm.tools.Shortcut;
|
---|
63 |
|
---|
64 | /**
|
---|
65 | * Makes a rectangle from a line, or modifies a rectangle.
|
---|
66 | */
|
---|
67 | public class ExtrudeAction extends MapMode implements MapViewPaintable, KeyPressReleaseListener, ModifierExListener {
|
---|
68 |
|
---|
69 | enum Mode { extrude, translate, select, create_new, translate_node }
|
---|
70 |
|
---|
71 | private Mode mode = Mode.select;
|
---|
72 |
|
---|
73 | /**
|
---|
74 | * If {@code true}, when extruding create new node(s) even if segments are parallel.
|
---|
75 | */
|
---|
76 | private boolean alwaysCreateNodes;
|
---|
77 | private boolean nodeDragWithoutCtrl;
|
---|
78 |
|
---|
79 | private long mouseDownTime;
|
---|
80 | private transient WaySegment selectedSegment;
|
---|
81 | private transient Node selectedNode;
|
---|
82 | private Color mainColor;
|
---|
83 | private transient Stroke mainStroke;
|
---|
84 |
|
---|
85 | /** settings value whether shared nodes should be ignored or not */
|
---|
86 | private boolean ignoreSharedNodes;
|
---|
87 |
|
---|
88 | private boolean keepSegmentDirection;
|
---|
89 |
|
---|
90 | /**
|
---|
91 | * drawing settings for helper lines
|
---|
92 | */
|
---|
93 | private Color helperColor;
|
---|
94 | private transient Stroke helperStrokeDash;
|
---|
95 | private transient Stroke helperStrokeRA;
|
---|
96 |
|
---|
97 | private transient Stroke oldLineStroke;
|
---|
98 | private double symbolSize;
|
---|
99 | /**
|
---|
100 | * Possible directions to move to.
|
---|
101 | */
|
---|
102 | private transient List<ReferenceSegment> possibleMoveDirections;
|
---|
103 |
|
---|
104 |
|
---|
105 | /**
|
---|
106 | * Collection of nodes that is moved
|
---|
107 | */
|
---|
108 | private transient List<Node> movingNodeList;
|
---|
109 |
|
---|
110 | /**
|
---|
111 | * The direction that is currently active.
|
---|
112 | */
|
---|
113 | private transient ReferenceSegment activeMoveDirection;
|
---|
114 |
|
---|
115 | /**
|
---|
116 | * The position of the mouse cursor when the drag action was initiated.
|
---|
117 | */
|
---|
118 | private Point initialMousePos;
|
---|
119 | /**
|
---|
120 | * The time which needs to pass between click and release before something
|
---|
121 | * counts as a move, in milliseconds
|
---|
122 | */
|
---|
123 | private int initialMoveDelay = 200;
|
---|
124 | /**
|
---|
125 | * The minimal shift of mouse (in pixels) befire something counts as move
|
---|
126 | */
|
---|
127 | private int initialMoveThreshold = 1;
|
---|
128 |
|
---|
129 | /**
|
---|
130 | * The initial EastNorths of node1 and node2
|
---|
131 | */
|
---|
132 | private EastNorth initialN1en;
|
---|
133 | private EastNorth initialN2en;
|
---|
134 | /**
|
---|
135 | * The new EastNorths of node1 and node2
|
---|
136 | */
|
---|
137 | private EastNorth newN1en;
|
---|
138 | private EastNorth newN2en;
|
---|
139 |
|
---|
140 | /**
|
---|
141 | * the command that performed last move.
|
---|
142 | */
|
---|
143 | private transient MoveCommand moveCommand;
|
---|
144 | /**
|
---|
145 | * The command used for dual alignment movement.
|
---|
146 | * Needs to be separate, due to two nodes moving in different directions.
|
---|
147 | */
|
---|
148 | private transient MoveCommand moveCommand2;
|
---|
149 |
|
---|
150 | /** The cursor for the 'create_new' mode. */
|
---|
151 | private final Cursor cursorCreateNew;
|
---|
152 |
|
---|
153 | /** The cursor for the 'translate' mode. */
|
---|
154 | private final Cursor cursorTranslate;
|
---|
155 |
|
---|
156 | /** The cursor for the 'alwaysCreateNodes' submode. */
|
---|
157 | private final Cursor cursorCreateNodes;
|
---|
158 |
|
---|
159 | private static class ReferenceSegment {
|
---|
160 | public final EastNorth en;
|
---|
161 | public final EastNorth p1;
|
---|
162 | public final EastNorth p2;
|
---|
163 | public final boolean perpendicular;
|
---|
164 |
|
---|
165 | ReferenceSegment(EastNorth en, EastNorth p1, EastNorth p2, boolean perpendicular) {
|
---|
166 | this.en = en;
|
---|
167 | this.p1 = p1;
|
---|
168 | this.p2 = p2;
|
---|
169 | this.perpendicular = perpendicular;
|
---|
170 | }
|
---|
171 |
|
---|
172 | @Override
|
---|
173 | public String toString() {
|
---|
174 | return "ReferenceSegment[en=" + en + ", p1=" + p1 + ", p2=" + p2 + ", perp=" + perpendicular + ']';
|
---|
175 | }
|
---|
176 | }
|
---|
177 |
|
---|
178 | // Dual alignment mode stuff
|
---|
179 | /** {@code true}, if dual alignment mode is enabled. User wants following extrude to be dual aligned. */
|
---|
180 | private boolean dualAlignEnabled;
|
---|
181 | /** {@code true}, if dual alignment is active. User is dragging the mouse, required conditions are met.
|
---|
182 | * Treat {@link #mode} (extrude/translate/create_new) as dual aligned. */
|
---|
183 | private boolean dualAlignActive;
|
---|
184 | /** Dual alignment reference segments */
|
---|
185 | private transient ReferenceSegment dualAlignSegment1, dualAlignSegment2;
|
---|
186 | /** {@code true}, if new segment was collapsed */
|
---|
187 | private boolean dualAlignSegmentCollapsed;
|
---|
188 | // Dual alignment UI stuff
|
---|
189 | private final DualAlignChangeAction dualAlignChangeAction;
|
---|
190 | private final JCheckBoxMenuItem dualAlignCheckboxMenuItem;
|
---|
191 | private final transient Shortcut dualAlignShortcut;
|
---|
192 | private boolean useRepeatedShortcut;
|
---|
193 | private boolean ignoreNextKeyRelease;
|
---|
194 |
|
---|
195 | private class DualAlignChangeAction extends JosmAction {
|
---|
196 | DualAlignChangeAction() {
|
---|
197 | super(tr("Dual alignment"), /* ICON() */ "mapmode/extrude/dualalign",
|
---|
198 | tr("Switch dual alignment mode while extruding"), null, false);
|
---|
199 | putValue("help", ht("/Action/Extrude#DualAlign"));
|
---|
200 | }
|
---|
201 |
|
---|
202 | @Override
|
---|
203 | public void actionPerformed(ActionEvent e) {
|
---|
204 | toggleDualAlign();
|
---|
205 | }
|
---|
206 |
|
---|
207 | @Override
|
---|
208 | protected void updateEnabledState() {
|
---|
209 | MapFrame map = MainApplication.getMap();
|
---|
210 | setEnabled(map != null && map.mapMode instanceof ExtrudeAction);
|
---|
211 | }
|
---|
212 | }
|
---|
213 |
|
---|
214 | /**
|
---|
215 | * Creates a new ExtrudeAction
|
---|
216 | * @since 11713
|
---|
217 | */
|
---|
218 | public ExtrudeAction() {
|
---|
219 | super(tr("Extrude"), /* ICON(mapmode/) */ "extrude/extrude", tr("Create areas"),
|
---|
220 | Shortcut.registerShortcut("mapmode:extrude", tr("Mode: {0}", tr("Extrude")), KeyEvent.VK_X, Shortcut.DIRECT),
|
---|
221 | ImageProvider.getCursor("normal", "rectangle"));
|
---|
222 | putValue("help", ht("/Action/Extrude"));
|
---|
223 | cursorCreateNew = ImageProvider.getCursor("normal", "rectangle_plus");
|
---|
224 | cursorTranslate = ImageProvider.getCursor("normal", "rectangle_move");
|
---|
225 | cursorCreateNodes = ImageProvider.getCursor("normal", "rectangle_plussmall");
|
---|
226 |
|
---|
227 | dualAlignEnabled = false;
|
---|
228 | dualAlignChangeAction = new DualAlignChangeAction();
|
---|
229 | dualAlignCheckboxMenuItem = addDualAlignMenuItem();
|
---|
230 | dualAlignCheckboxMenuItem.getAction().setEnabled(false);
|
---|
231 | dualAlignCheckboxMenuItem.setState(dualAlignEnabled);
|
---|
232 | dualAlignShortcut = Shortcut.registerShortcut("mapmode:extrudedualalign",
|
---|
233 | tr("Mode: {0}", tr("Extrude Dual alignment")), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
|
---|
234 | readPreferences(); // to show prefernces in table before entering the mode
|
---|
235 | }
|
---|
236 |
|
---|
237 | @Override
|
---|
238 | public void destroy() {
|
---|
239 | super.destroy();
|
---|
240 | dualAlignChangeAction.destroy();
|
---|
241 | }
|
---|
242 |
|
---|
243 | private JCheckBoxMenuItem addDualAlignMenuItem() {
|
---|
244 | int n = Main.main.menu.editMenu.getItemCount();
|
---|
245 | for (int i = n-1; i > 0; i--) {
|
---|
246 | JMenuItem item = Main.main.menu.editMenu.getItem(i);
|
---|
247 | if (item != null && item.getAction() != null && item.getAction() instanceof DualAlignChangeAction) {
|
---|
248 | Main.main.menu.editMenu.remove(i);
|
---|
249 | }
|
---|
250 | }
|
---|
251 | return MainMenu.addWithCheckbox(Main.main.menu.editMenu, dualAlignChangeAction, MainMenu.WINDOW_MENU_GROUP.VOLATILE);
|
---|
252 | }
|
---|
253 |
|
---|
254 | // -------------------------------------------------------------------------
|
---|
255 | // Mode methods
|
---|
256 | // -------------------------------------------------------------------------
|
---|
257 |
|
---|
258 | @Override
|
---|
259 | public String getModeHelpText() {
|
---|
260 | StringBuilder rv;
|
---|
261 | if (mode == Mode.select) {
|
---|
262 | rv = new StringBuilder(tr("Drag a way segment to make a rectangle. Ctrl-drag to move a segment along its normal, " +
|
---|
263 | "Alt-drag to create a new rectangle, double click to add a new node."));
|
---|
264 | if (dualAlignEnabled) {
|
---|
265 | rv.append(' ').append(tr("Dual alignment active."));
|
---|
266 | if (dualAlignSegmentCollapsed)
|
---|
267 | rv.append(' ').append(tr("Segment collapsed due to its direction reversing."));
|
---|
268 | }
|
---|
269 | } else {
|
---|
270 | if (mode == Mode.translate)
|
---|
271 | rv = new StringBuilder(tr("Move a segment along its normal, then release the mouse button."));
|
---|
272 | else if (mode == Mode.translate_node)
|
---|
273 | rv = new StringBuilder(tr("Move the node along one of the segments, then release the mouse button."));
|
---|
274 | else if (mode == Mode.extrude || mode == Mode.create_new)
|
---|
275 | rv = new StringBuilder(tr("Draw a rectangle of the desired size, then release the mouse button."));
|
---|
276 | else {
|
---|
277 | Logging.warn("Extrude: unknown mode " + mode);
|
---|
278 | rv = new StringBuilder();
|
---|
279 | }
|
---|
280 | if (dualAlignActive) {
|
---|
281 | rv.append(' ').append(tr("Dual alignment active."));
|
---|
282 | if (dualAlignSegmentCollapsed) {
|
---|
283 | rv.append(' ').append(tr("Segment collapsed due to its direction reversing."));
|
---|
284 | }
|
---|
285 | }
|
---|
286 | }
|
---|
287 | return rv.toString();
|
---|
288 | }
|
---|
289 |
|
---|
290 | @Override
|
---|
291 | public boolean layerIsSupported(Layer l) {
|
---|
292 | return l instanceof OsmDataLayer;
|
---|
293 | }
|
---|
294 |
|
---|
295 | @Override
|
---|
296 | public void enterMode() {
|
---|
297 | super.enterMode();
|
---|
298 | MapFrame map = MainApplication.getMap();
|
---|
299 | map.mapView.addMouseListener(this);
|
---|
300 | map.mapView.addMouseMotionListener(this);
|
---|
301 | ignoreNextKeyRelease = true;
|
---|
302 | map.keyDetector.addKeyListener(this);
|
---|
303 | map.keyDetector.addModifierExListener(this);
|
---|
304 | }
|
---|
305 |
|
---|
306 | @Override
|
---|
307 | protected void readPreferences() {
|
---|
308 | initialMoveDelay = Main.pref.getInteger("edit.initial-move-delay", 200);
|
---|
309 | initialMoveThreshold = Main.pref.getInteger("extrude.initial-move-threshold", 1);
|
---|
310 | mainColor = new ColorProperty(marktr("Extrude: main line"), Color.RED).get();
|
---|
311 | helperColor = new ColorProperty(marktr("Extrude: helper line"), Color.ORANGE).get();
|
---|
312 | helperStrokeDash = GuiHelper.getCustomizedStroke(Main.pref.get("extrude.stroke.helper-line", "1 4"));
|
---|
313 | helperStrokeRA = new BasicStroke(1);
|
---|
314 | symbolSize = Main.pref.getDouble("extrude.angle-symbol-radius", 8);
|
---|
315 | nodeDragWithoutCtrl = Main.pref.getBoolean("extrude.drag-nodes-without-ctrl", false);
|
---|
316 | oldLineStroke = GuiHelper.getCustomizedStroke(Main.pref.get("extrude.ctrl.stroke.old-line", "1"));
|
---|
317 | mainStroke = GuiHelper.getCustomizedStroke(Main.pref.get("extrude.stroke.main", "3"));
|
---|
318 |
|
---|
319 | ignoreSharedNodes = Main.pref.getBoolean("extrude.ignore-shared-nodes", true);
|
---|
320 | dualAlignCheckboxMenuItem.getAction().setEnabled(true);
|
---|
321 | useRepeatedShortcut = Main.pref.getBoolean("extrude.dualalign.toggleOnRepeatedX", true);
|
---|
322 | keepSegmentDirection = Main.pref.getBoolean("extrude.dualalign.keep-segment-direction", true);
|
---|
323 | }
|
---|
324 |
|
---|
325 | @Override
|
---|
326 | public void exitMode() {
|
---|
327 | MapFrame map = MainApplication.getMap();
|
---|
328 | map.mapView.removeMouseListener(this);
|
---|
329 | map.mapView.removeMouseMotionListener(this);
|
---|
330 | map.mapView.removeTemporaryLayer(this);
|
---|
331 | dualAlignCheckboxMenuItem.getAction().setEnabled(false);
|
---|
332 | map.keyDetector.removeKeyListener(this);
|
---|
333 | map.keyDetector.removeModifierExListener(this);
|
---|
334 | super.exitMode();
|
---|
335 | }
|
---|
336 |
|
---|
337 | // -------------------------------------------------------------------------
|
---|
338 | // Event handlers
|
---|
339 | // -------------------------------------------------------------------------
|
---|
340 |
|
---|
341 | /**
|
---|
342 | * This method is called to indicate different modes via cursor when the Alt/Ctrl/Shift modifier is pressed,
|
---|
343 | */
|
---|
344 | @Override
|
---|
345 | public void modifiersExChanged(int modifiers) {
|
---|
346 | MapFrame map = MainApplication.getMap();
|
---|
347 | if (!MainApplication.isDisplayingMapView() || !map.mapView.isActiveLayerDrawable())
|
---|
348 | return;
|
---|
349 | updateKeyModifiersEx(modifiers);
|
---|
350 | if (mode == Mode.select) {
|
---|
351 | map.mapView.setNewCursor(ctrl ? cursorTranslate : alt ? cursorCreateNew : shift ? cursorCreateNodes : cursor, this);
|
---|
352 | }
|
---|
353 | }
|
---|
354 |
|
---|
355 | @Override
|
---|
356 | public void doKeyPressed(KeyEvent e) {
|
---|
357 | // Do nothing
|
---|
358 | }
|
---|
359 |
|
---|
360 | @Override
|
---|
361 | public void doKeyReleased(KeyEvent e) {
|
---|
362 | if (!dualAlignShortcut.isEvent(e) && !(useRepeatedShortcut && getShortcut().isEvent(e)))
|
---|
363 | return;
|
---|
364 | if (ignoreNextKeyRelease) {
|
---|
365 | ignoreNextKeyRelease = false;
|
---|
366 | } else {
|
---|
367 | toggleDualAlign();
|
---|
368 | }
|
---|
369 | }
|
---|
370 |
|
---|
371 | /**
|
---|
372 | * Toggles dual alignment mode.
|
---|
373 | */
|
---|
374 | private void toggleDualAlign() {
|
---|
375 | dualAlignEnabled = !dualAlignEnabled;
|
---|
376 | dualAlignCheckboxMenuItem.setState(dualAlignEnabled);
|
---|
377 | updateStatusLine();
|
---|
378 | }
|
---|
379 |
|
---|
380 | /**
|
---|
381 | * If the left mouse button is pressed over a segment or a node, switches
|
---|
382 | * to appropriate {@link #mode}, depending on Ctrl/Alt/Shift modifiers and
|
---|
383 | * {@link #dualAlignEnabled}.
|
---|
384 | * @param e current mouse event
|
---|
385 | */
|
---|
386 | @Override
|
---|
387 | public void mousePressed(MouseEvent e) {
|
---|
388 | MapFrame map = MainApplication.getMap();
|
---|
389 | if (!map.mapView.isActiveLayerVisible())
|
---|
390 | return;
|
---|
391 | if (!(Boolean) this.getValue("active"))
|
---|
392 | return;
|
---|
393 | if (e.getButton() != MouseEvent.BUTTON1)
|
---|
394 | return;
|
---|
395 |
|
---|
396 | requestFocusInMapView();
|
---|
397 | updateKeyModifiers(e);
|
---|
398 |
|
---|
399 | selectedNode = map.mapView.getNearestNode(e.getPoint(), OsmPrimitive::isSelectable);
|
---|
400 | selectedSegment = map.mapView.getNearestWaySegment(e.getPoint(), OsmPrimitive::isSelectable);
|
---|
401 |
|
---|
402 | // If nothing gets caught, stay in select mode
|
---|
403 | if (selectedSegment == null && selectedNode == null) return;
|
---|
404 |
|
---|
405 | if (selectedNode != null) {
|
---|
406 | if (ctrl || nodeDragWithoutCtrl) {
|
---|
407 | movingNodeList = new ArrayList<>();
|
---|
408 | movingNodeList.add(selectedNode);
|
---|
409 | calculatePossibleDirectionsByNode();
|
---|
410 | if (possibleMoveDirections.isEmpty()) {
|
---|
411 | // if no directions fould, do not enter dragging mode
|
---|
412 | return;
|
---|
413 | }
|
---|
414 | mode = Mode.translate_node;
|
---|
415 | dualAlignActive = false;
|
---|
416 | }
|
---|
417 | } else {
|
---|
418 | // Otherwise switch to another mode
|
---|
419 | if (dualAlignEnabled && checkDualAlignConditions()) {
|
---|
420 | dualAlignActive = true;
|
---|
421 | calculatePossibleDirectionsForDualAlign();
|
---|
422 | dualAlignSegmentCollapsed = false;
|
---|
423 | } else {
|
---|
424 | dualAlignActive = false;
|
---|
425 | calculatePossibleDirectionsBySegment();
|
---|
426 | }
|
---|
427 | if (ctrl) {
|
---|
428 | mode = Mode.translate;
|
---|
429 | movingNodeList = new ArrayList<>();
|
---|
430 | movingNodeList.add(selectedSegment.getFirstNode());
|
---|
431 | movingNodeList.add(selectedSegment.getSecondNode());
|
---|
432 | } else if (alt) {
|
---|
433 | mode = Mode.create_new;
|
---|
434 | // create a new segment and then select and extrude the new segment
|
---|
435 | getLayerManager().getEditDataSet().setSelected(selectedSegment.way);
|
---|
436 | alwaysCreateNodes = true;
|
---|
437 | } else {
|
---|
438 | mode = Mode.extrude;
|
---|
439 | getLayerManager().getEditDataSet().setSelected(selectedSegment.way);
|
---|
440 | alwaysCreateNodes = shift;
|
---|
441 | }
|
---|
442 | }
|
---|
443 |
|
---|
444 | // Signifies that nothing has happened yet
|
---|
445 | newN1en = null;
|
---|
446 | newN2en = null;
|
---|
447 | moveCommand = null;
|
---|
448 | moveCommand2 = null;
|
---|
449 |
|
---|
450 | map.mapView.addTemporaryLayer(this);
|
---|
451 |
|
---|
452 | updateStatusLine();
|
---|
453 | map.mapView.repaint();
|
---|
454 |
|
---|
455 | // Make note of time pressed
|
---|
456 | mouseDownTime = System.currentTimeMillis();
|
---|
457 |
|
---|
458 | // Make note of mouse position
|
---|
459 | initialMousePos = e.getPoint();
|
---|
460 | }
|
---|
461 |
|
---|
462 | /**
|
---|
463 | * Performs action depending on what {@link #mode} we're in.
|
---|
464 | * @param e current mouse event
|
---|
465 | */
|
---|
466 | @Override
|
---|
467 | public void mouseDragged(MouseEvent e) {
|
---|
468 | MapView mapView = MainApplication.getMap().mapView;
|
---|
469 | if (!mapView.isActiveLayerVisible())
|
---|
470 | return;
|
---|
471 |
|
---|
472 | // do not count anything as a drag if it lasts less than 100 milliseconds.
|
---|
473 | if (System.currentTimeMillis() - mouseDownTime < initialMoveDelay)
|
---|
474 | return;
|
---|
475 |
|
---|
476 | if (mode == Mode.select) {
|
---|
477 | // Just sit tight and wait for mouse to be released.
|
---|
478 | } else {
|
---|
479 | //move, create new and extrude mode - move the selected segment
|
---|
480 |
|
---|
481 | EastNorth mouseEn = mapView.getEastNorth(e.getPoint().x, e.getPoint().y);
|
---|
482 | EastNorth bestMovement = calculateBestMovementAndNewNodes(mouseEn);
|
---|
483 |
|
---|
484 | mapView.setNewCursor(Cursor.MOVE_CURSOR, this);
|
---|
485 |
|
---|
486 | if (dualAlignActive) {
|
---|
487 | if (mode == Mode.extrude || mode == Mode.create_new) {
|
---|
488 | // nothing here
|
---|
489 | } else if (mode == Mode.translate) {
|
---|
490 | EastNorth movement1 = newN1en.subtract(initialN1en);
|
---|
491 | EastNorth movement2 = newN2en.subtract(initialN2en);
|
---|
492 | // move nodes to new position
|
---|
493 | if (moveCommand == null || moveCommand2 == null) {
|
---|
494 | // make a new move commands
|
---|
495 | moveCommand = new MoveCommand(movingNodeList.get(0), movement1.getX(), movement1.getY());
|
---|
496 | moveCommand2 = new MoveCommand(movingNodeList.get(1), movement2.getX(), movement2.getY());
|
---|
497 | Command c = new SequenceCommand(tr("Extrude Way"), moveCommand, moveCommand2);
|
---|
498 | MainApplication.undoRedo.add(c);
|
---|
499 | } else {
|
---|
500 | // reuse existing move commands
|
---|
501 | moveCommand.moveAgainTo(movement1.getX(), movement1.getY());
|
---|
502 | moveCommand2.moveAgainTo(movement2.getX(), movement2.getY());
|
---|
503 | }
|
---|
504 | }
|
---|
505 | } else if (bestMovement != null) {
|
---|
506 | if (mode == Mode.extrude || mode == Mode.create_new) {
|
---|
507 | //nothing here
|
---|
508 | } else if (mode == Mode.translate_node || mode == Mode.translate) {
|
---|
509 | //move nodes to new position
|
---|
510 | if (moveCommand == null) {
|
---|
511 | //make a new move command
|
---|
512 | moveCommand = new MoveCommand(new ArrayList<OsmPrimitive>(movingNodeList), bestMovement);
|
---|
513 | MainApplication.undoRedo.add(moveCommand);
|
---|
514 | } else {
|
---|
515 | //reuse existing move command
|
---|
516 | moveCommand.moveAgainTo(bestMovement.getX(), bestMovement.getY());
|
---|
517 | }
|
---|
518 | }
|
---|
519 | }
|
---|
520 |
|
---|
521 | mapView.repaint();
|
---|
522 | }
|
---|
523 | }
|
---|
524 |
|
---|
525 | /**
|
---|
526 | * Does anything that needs to be done, then switches back to select mode.
|
---|
527 | * @param e current mouse event
|
---|
528 | */
|
---|
529 | @Override
|
---|
530 | public void mouseReleased(MouseEvent e) {
|
---|
531 |
|
---|
532 | MapView mapView = MainApplication.getMap().mapView;
|
---|
533 | if (!mapView.isActiveLayerVisible())
|
---|
534 | return;
|
---|
535 |
|
---|
536 | if (mode == Mode.select) {
|
---|
537 | // Nothing to be done
|
---|
538 | } else {
|
---|
539 | if (mode == Mode.create_new) {
|
---|
540 | if (e.getPoint().distance(initialMousePos) > initialMoveThreshold && newN1en != null) {
|
---|
541 | createNewRectangle();
|
---|
542 | }
|
---|
543 | } else if (mode == Mode.extrude) {
|
---|
544 | if (e.getClickCount() == 2 && e.getPoint().equals(initialMousePos)) {
|
---|
545 | // double click adds a new node
|
---|
546 | addNewNode(e);
|
---|
547 | } else if (e.getPoint().distance(initialMousePos) > initialMoveThreshold && newN1en != null && selectedSegment != null) {
|
---|
548 | try {
|
---|
549 | // main extrusion commands
|
---|
550 | performExtrusion();
|
---|
551 | } catch (DataIntegrityProblemException ex) {
|
---|
552 | // Can occur if calling undo while extruding, see #12870
|
---|
553 | Logging.error(ex);
|
---|
554 | }
|
---|
555 | }
|
---|
556 | } else if (mode == Mode.translate || mode == Mode.translate_node) {
|
---|
557 | //Commit translate
|
---|
558 | //the move command is already committed in mouseDragged
|
---|
559 | joinNodesIfCollapsed(movingNodeList);
|
---|
560 | }
|
---|
561 |
|
---|
562 | updateKeyModifiers(e);
|
---|
563 | // Switch back into select mode
|
---|
564 | mapView.setNewCursor(ctrl ? cursorTranslate : alt ? cursorCreateNew : shift ? cursorCreateNodes : cursor, this);
|
---|
565 | mapView.removeTemporaryLayer(this);
|
---|
566 | selectedSegment = null;
|
---|
567 | moveCommand = null;
|
---|
568 | mode = Mode.select;
|
---|
569 | dualAlignSegmentCollapsed = false;
|
---|
570 | updateStatusLine();
|
---|
571 | mapView.repaint();
|
---|
572 | }
|
---|
573 | }
|
---|
574 |
|
---|
575 | // -------------------------------------------------------------------------
|
---|
576 | // Custom methods
|
---|
577 | // -------------------------------------------------------------------------
|
---|
578 |
|
---|
579 | /**
|
---|
580 | * Inserts node into nearby segment.
|
---|
581 | * @param e current mouse point
|
---|
582 | */
|
---|
583 | private static void addNewNode(MouseEvent e) {
|
---|
584 | // Should maybe do the same as in DrawAction and fetch all nearby segments?
|
---|
585 | MapView mapView = MainApplication.getMap().mapView;
|
---|
586 | WaySegment ws = mapView.getNearestWaySegment(e.getPoint(), OsmPrimitive::isSelectable);
|
---|
587 | if (ws != null) {
|
---|
588 | Node n = new Node(mapView.getLatLon(e.getX(), e.getY()));
|
---|
589 | EastNorth a = ws.getFirstNode().getEastNorth();
|
---|
590 | EastNorth b = ws.getSecondNode().getEastNorth();
|
---|
591 | n.setEastNorth(Geometry.closestPointToSegment(a, b, n.getEastNorth()));
|
---|
592 | Way wnew = new Way(ws.way);
|
---|
593 | wnew.addNode(ws.lowerIndex+1, n);
|
---|
594 | SequenceCommand cmds = new SequenceCommand(tr("Add a new node to an existing way"),
|
---|
595 | new AddCommand(n), new ChangeCommand(ws.way, wnew));
|
---|
596 | MainApplication.undoRedo.add(cmds);
|
---|
597 | }
|
---|
598 | }
|
---|
599 |
|
---|
600 | /**
|
---|
601 | * Creates a new way that shares segment with selected way.
|
---|
602 | */
|
---|
603 | private void createNewRectangle() {
|
---|
604 | if (selectedSegment == null) return;
|
---|
605 | // crete a new rectangle
|
---|
606 | Collection<Command> cmds = new LinkedList<>();
|
---|
607 | Node third = new Node(newN2en);
|
---|
608 | Node fourth = new Node(newN1en);
|
---|
609 | Way wnew = new Way();
|
---|
610 | wnew.addNode(selectedSegment.getFirstNode());
|
---|
611 | wnew.addNode(selectedSegment.getSecondNode());
|
---|
612 | wnew.addNode(third);
|
---|
613 | if (!dualAlignSegmentCollapsed) {
|
---|
614 | // rectangle can degrade to triangle for dual alignment after collapsing
|
---|
615 | wnew.addNode(fourth);
|
---|
616 | }
|
---|
617 | // ... and close the way
|
---|
618 | wnew.addNode(selectedSegment.getFirstNode());
|
---|
619 | // undo support
|
---|
620 | cmds.add(new AddCommand(third));
|
---|
621 | if (!dualAlignSegmentCollapsed) {
|
---|
622 | cmds.add(new AddCommand(fourth));
|
---|
623 | }
|
---|
624 | cmds.add(new AddCommand(wnew));
|
---|
625 | Command c = new SequenceCommand(tr("Extrude Way"), cmds);
|
---|
626 | MainApplication.undoRedo.add(c);
|
---|
627 | getLayerManager().getEditDataSet().setSelected(wnew);
|
---|
628 | }
|
---|
629 |
|
---|
630 | /**
|
---|
631 | * Does actual extrusion of {@link #selectedSegment}.
|
---|
632 | * Uses {@link #initialN1en}, {@link #initialN2en} saved in calculatePossibleDirections* call
|
---|
633 | * Uses {@link #newN1en}, {@link #newN2en} calculated by {@link #calculateBestMovementAndNewNodes}
|
---|
634 | */
|
---|
635 | private void performExtrusion() {
|
---|
636 | // create extrusion
|
---|
637 | Collection<Command> cmds = new LinkedList<>();
|
---|
638 | Way wnew = new Way(selectedSegment.way);
|
---|
639 | boolean wayWasModified = false;
|
---|
640 | boolean wayWasSingleSegment = wnew.getNodesCount() == 2;
|
---|
641 | int insertionPoint = selectedSegment.lowerIndex + 1;
|
---|
642 |
|
---|
643 | //find if the new points overlap existing segments (in case of 90 degree angles)
|
---|
644 | Node prevNode = getPreviousNode(selectedSegment.lowerIndex);
|
---|
645 | boolean nodeOverlapsSegment = prevNode != null && Geometry.segmentsParallel(initialN1en, prevNode.getEastNorth(), initialN1en, newN1en);
|
---|
646 | // segmentAngleZero marks subset of nodeOverlapsSegment.
|
---|
647 | // nodeOverlapsSegment is true if angle between segments is 0 or PI, segmentAngleZero only if angle is 0
|
---|
648 | boolean segmentAngleZero = prevNode != null && Math.abs(Geometry.getCornerAngle(prevNode.getEastNorth(), initialN1en, newN1en)) < 1e-5;
|
---|
649 | boolean hasOtherWays = hasNodeOtherWays(selectedSegment.getFirstNode(), selectedSegment.way);
|
---|
650 | List<Node> changedNodes = new ArrayList<>();
|
---|
651 | if (nodeOverlapsSegment && !alwaysCreateNodes && !hasOtherWays) {
|
---|
652 | //move existing node
|
---|
653 | Node n1Old = selectedSegment.getFirstNode();
|
---|
654 | cmds.add(new MoveCommand(n1Old, Main.getProjection().eastNorth2latlon(newN1en)));
|
---|
655 | changedNodes.add(n1Old);
|
---|
656 | } else if (ignoreSharedNodes && segmentAngleZero && !alwaysCreateNodes && hasOtherWays) {
|
---|
657 | // replace shared node with new one
|
---|
658 | Node n1Old = selectedSegment.getFirstNode();
|
---|
659 | Node n1New = new Node(Main.getProjection().eastNorth2latlon(newN1en));
|
---|
660 | wnew.addNode(insertionPoint, n1New);
|
---|
661 | wnew.removeNode(n1Old);
|
---|
662 | wayWasModified = true;
|
---|
663 | cmds.add(new AddCommand(n1New));
|
---|
664 | changedNodes.add(n1New);
|
---|
665 | } else {
|
---|
666 | //introduce new node
|
---|
667 | Node n1New = new Node(Main.getProjection().eastNorth2latlon(newN1en));
|
---|
668 | wnew.addNode(insertionPoint, n1New);
|
---|
669 | wayWasModified = true;
|
---|
670 | insertionPoint++;
|
---|
671 | cmds.add(new AddCommand(n1New));
|
---|
672 | changedNodes.add(n1New);
|
---|
673 | }
|
---|
674 |
|
---|
675 | //find if the new points overlap existing segments (in case of 90 degree angles)
|
---|
676 | Node nextNode = getNextNode(selectedSegment.lowerIndex + 1);
|
---|
677 | nodeOverlapsSegment = nextNode != null && Geometry.segmentsParallel(initialN2en, nextNode.getEastNorth(), initialN2en, newN2en);
|
---|
678 | segmentAngleZero = nextNode != null && Math.abs(Geometry.getCornerAngle(nextNode.getEastNorth(), initialN2en, newN2en)) < 1e-5;
|
---|
679 | hasOtherWays = hasNodeOtherWays(selectedSegment.getSecondNode(), selectedSegment.way);
|
---|
680 |
|
---|
681 | if (nodeOverlapsSegment && !alwaysCreateNodes && !hasOtherWays) {
|
---|
682 | //move existing node
|
---|
683 | Node n2Old = selectedSegment.getSecondNode();
|
---|
684 | cmds.add(new MoveCommand(n2Old, Main.getProjection().eastNorth2latlon(newN2en)));
|
---|
685 | changedNodes.add(n2Old);
|
---|
686 | } else if (ignoreSharedNodes && segmentAngleZero && !alwaysCreateNodes && hasOtherWays) {
|
---|
687 | // replace shared node with new one
|
---|
688 | Node n2Old = selectedSegment.getSecondNode();
|
---|
689 | Node n2New = new Node(Main.getProjection().eastNorth2latlon(newN2en));
|
---|
690 | wnew.addNode(insertionPoint, n2New);
|
---|
691 | wnew.removeNode(n2Old);
|
---|
692 | wayWasModified = true;
|
---|
693 | cmds.add(new AddCommand(n2New));
|
---|
694 | changedNodes.add(n2New);
|
---|
695 | } else {
|
---|
696 | //introduce new node
|
---|
697 | Node n2New = new Node(Main.getProjection().eastNorth2latlon(newN2en));
|
---|
698 | wnew.addNode(insertionPoint, n2New);
|
---|
699 | wayWasModified = true;
|
---|
700 | cmds.add(new AddCommand(n2New));
|
---|
701 | changedNodes.add(n2New);
|
---|
702 | }
|
---|
703 |
|
---|
704 | //the way was a single segment, close the way
|
---|
705 | if (wayWasSingleSegment) {
|
---|
706 | wnew.addNode(selectedSegment.getFirstNode());
|
---|
707 | wayWasModified = true;
|
---|
708 | }
|
---|
709 | if (wayWasModified) {
|
---|
710 | // we only need to change the way if its node list was really modified
|
---|
711 | cmds.add(new ChangeCommand(selectedSegment.way, wnew));
|
---|
712 | }
|
---|
713 | Command c = new SequenceCommand(tr("Extrude Way"), cmds);
|
---|
714 | MainApplication.undoRedo.add(c);
|
---|
715 | joinNodesIfCollapsed(changedNodes);
|
---|
716 | }
|
---|
717 |
|
---|
718 | private void joinNodesIfCollapsed(List<Node> changedNodes) {
|
---|
719 | if (!dualAlignActive || newN1en == null || newN2en == null) return;
|
---|
720 | if (newN1en.distance(newN2en) > 1e-6) return;
|
---|
721 | // If the dual alignment moved two nodes to the same point, merge them
|
---|
722 | Node targetNode = MergeNodesAction.selectTargetNode(changedNodes);
|
---|
723 | Node locNode = MergeNodesAction.selectTargetLocationNode(changedNodes);
|
---|
724 | Command mergeCmd = MergeNodesAction.mergeNodes(MainApplication.getLayerManager().getEditLayer(), changedNodes, targetNode, locNode);
|
---|
725 | if (mergeCmd != null) {
|
---|
726 | MainApplication.undoRedo.add(mergeCmd);
|
---|
727 | } else {
|
---|
728 | // undo extruding command itself
|
---|
729 | MainApplication.undoRedo.undo();
|
---|
730 | }
|
---|
731 | }
|
---|
732 |
|
---|
733 | /**
|
---|
734 | * This method tests if {@code node} has other ways apart from the given one.
|
---|
735 | * @param node node to test
|
---|
736 | * @param myWay way known to contain this node
|
---|
737 | * @return {@code true} if {@code node} belongs only to {@code myWay}, false if there are more ways.
|
---|
738 | */
|
---|
739 | private static boolean hasNodeOtherWays(Node node, Way myWay) {
|
---|
740 | for (OsmPrimitive p : node.getReferrers()) {
|
---|
741 | if (p instanceof Way && p.isUsable() && p != myWay)
|
---|
742 | return true;
|
---|
743 | }
|
---|
744 | return false;
|
---|
745 | }
|
---|
746 |
|
---|
747 | /**
|
---|
748 | * Determines best movement from {@link #initialMousePos} to current mouse position,
|
---|
749 | * choosing one of the directions from {@link #possibleMoveDirections}.
|
---|
750 | * @param mouseEn current mouse position
|
---|
751 | * @return movement vector
|
---|
752 | */
|
---|
753 | private EastNorth calculateBestMovement(EastNorth mouseEn) {
|
---|
754 |
|
---|
755 | EastNorth initialMouseEn = MainApplication.getMap().mapView.getEastNorth(initialMousePos.x, initialMousePos.y);
|
---|
756 | EastNorth mouseMovement = mouseEn.subtract(initialMouseEn);
|
---|
757 |
|
---|
758 | double bestDistance = Double.POSITIVE_INFINITY;
|
---|
759 | EastNorth bestMovement = null;
|
---|
760 | activeMoveDirection = null;
|
---|
761 |
|
---|
762 | //find the best movement direction and vector
|
---|
763 | for (ReferenceSegment direction : possibleMoveDirections) {
|
---|
764 | EastNorth movement = calculateSegmentOffset(initialN1en, initialN2en, direction.en, mouseEn);
|
---|
765 | if (movement == null) {
|
---|
766 | //if direction parallel to segment.
|
---|
767 | continue;
|
---|
768 | }
|
---|
769 |
|
---|
770 | double distanceFromMouseMovement = movement.distance(mouseMovement);
|
---|
771 | if (bestDistance > distanceFromMouseMovement) {
|
---|
772 | bestDistance = distanceFromMouseMovement;
|
---|
773 | activeMoveDirection = direction;
|
---|
774 | bestMovement = movement;
|
---|
775 | }
|
---|
776 | }
|
---|
777 | return bestMovement;
|
---|
778 | }
|
---|
779 |
|
---|
780 | /***
|
---|
781 | * This method calculates offset amount by which to move the given segment
|
---|
782 | * perpendicularly for it to be in line with mouse position.
|
---|
783 | * @param segmentP1 segment's first point
|
---|
784 | * @param segmentP2 segment's second point
|
---|
785 | * @param moveDirection direction of movement
|
---|
786 | * @param targetPos mouse position
|
---|
787 | * @return offset amount of P1 and P2.
|
---|
788 | */
|
---|
789 | private static EastNorth calculateSegmentOffset(EastNorth segmentP1, EastNorth segmentP2, EastNorth moveDirection,
|
---|
790 | EastNorth targetPos) {
|
---|
791 | EastNorth intersectionPoint;
|
---|
792 | if (segmentP1.distanceSq(segmentP2) > 1e-7) {
|
---|
793 | intersectionPoint = Geometry.getLineLineIntersection(segmentP1, segmentP2, targetPos, targetPos.add(moveDirection));
|
---|
794 | } else {
|
---|
795 | intersectionPoint = Geometry.closestPointToLine(targetPos, targetPos.add(moveDirection), segmentP1);
|
---|
796 | }
|
---|
797 |
|
---|
798 | if (intersectionPoint == null)
|
---|
799 | return null;
|
---|
800 | else
|
---|
801 | //return distance form base to target position
|
---|
802 | return targetPos.subtract(intersectionPoint);
|
---|
803 | }
|
---|
804 |
|
---|
805 | /**
|
---|
806 | * Gathers possible move directions - perpendicular to the selected segment
|
---|
807 | * and parallel to neighboring segments.
|
---|
808 | */
|
---|
809 | private void calculatePossibleDirectionsBySegment() {
|
---|
810 | // remember initial positions for segment nodes.
|
---|
811 | initialN1en = selectedSegment.getFirstNode().getEastNorth();
|
---|
812 | initialN2en = selectedSegment.getSecondNode().getEastNorth();
|
---|
813 |
|
---|
814 | //add direction perpendicular to the selected segment
|
---|
815 | possibleMoveDirections = new ArrayList<>();
|
---|
816 | possibleMoveDirections.add(new ReferenceSegment(new EastNorth(
|
---|
817 | initialN1en.getY() - initialN2en.getY(),
|
---|
818 | initialN2en.getX() - initialN1en.getX()
|
---|
819 | ), initialN1en, initialN2en, true));
|
---|
820 |
|
---|
821 |
|
---|
822 | //add directions parallel to neighbor segments
|
---|
823 | Node prevNode = getPreviousNode(selectedSegment.lowerIndex);
|
---|
824 | if (prevNode != null) {
|
---|
825 | EastNorth en = prevNode.getEastNorth();
|
---|
826 | possibleMoveDirections.add(new ReferenceSegment(new EastNorth(
|
---|
827 | initialN1en.getX() - en.getX(),
|
---|
828 | initialN1en.getY() - en.getY()
|
---|
829 | ), initialN1en, en, false));
|
---|
830 | }
|
---|
831 |
|
---|
832 | Node nextNode = getNextNode(selectedSegment.lowerIndex + 1);
|
---|
833 | if (nextNode != null) {
|
---|
834 | EastNorth en = nextNode.getEastNorth();
|
---|
835 | possibleMoveDirections.add(new ReferenceSegment(new EastNorth(
|
---|
836 | initialN2en.getX() - en.getX(),
|
---|
837 | initialN2en.getY() - en.getY()
|
---|
838 | ), initialN2en, en, false));
|
---|
839 | }
|
---|
840 | }
|
---|
841 |
|
---|
842 | /**
|
---|
843 | * Gathers possible move directions - along all adjacent segments.
|
---|
844 | */
|
---|
845 | private void calculatePossibleDirectionsByNode() {
|
---|
846 | // remember initial positions for segment nodes.
|
---|
847 | initialN1en = selectedNode.getEastNorth();
|
---|
848 | initialN2en = initialN1en;
|
---|
849 | possibleMoveDirections = new ArrayList<>();
|
---|
850 | for (OsmPrimitive p: selectedNode.getReferrers()) {
|
---|
851 | if (p instanceof Way && p.isUsable()) {
|
---|
852 | for (Node neighbor: ((Way) p).getNeighbours(selectedNode)) {
|
---|
853 | EastNorth en = neighbor.getEastNorth();
|
---|
854 | possibleMoveDirections.add(new ReferenceSegment(new EastNorth(
|
---|
855 | initialN1en.getX() - en.getX(),
|
---|
856 | initialN1en.getY() - en.getY()
|
---|
857 | ), initialN1en, en, false));
|
---|
858 | }
|
---|
859 | }
|
---|
860 | }
|
---|
861 | }
|
---|
862 |
|
---|
863 | /**
|
---|
864 | * Checks dual alignment conditions:
|
---|
865 | * 1. selected segment has both neighboring segments,
|
---|
866 | * 2. selected segment is not parallel with neighboring segments.
|
---|
867 | * @return {@code true} if dual alignment conditions are satisfied
|
---|
868 | */
|
---|
869 | private boolean checkDualAlignConditions() {
|
---|
870 | Node prevNode = getPreviousNode(selectedSegment.lowerIndex);
|
---|
871 | Node nextNode = getNextNode(selectedSegment.lowerIndex + 1);
|
---|
872 | if (prevNode == null || nextNode == null) {
|
---|
873 | return false;
|
---|
874 | }
|
---|
875 |
|
---|
876 | EastNorth n1en = selectedSegment.getFirstNode().getEastNorth();
|
---|
877 | EastNorth n2en = selectedSegment.getSecondNode().getEastNorth();
|
---|
878 | if (n1en.distance(prevNode.getEastNorth()) < 1e-4 ||
|
---|
879 | n2en.distance(nextNode.getEastNorth()) < 1e-4) {
|
---|
880 | return false;
|
---|
881 | }
|
---|
882 |
|
---|
883 | boolean prevSegmentParallel = Geometry.segmentsParallel(n1en, prevNode.getEastNorth(), n1en, n2en);
|
---|
884 | boolean nextSegmentParallel = Geometry.segmentsParallel(n2en, nextNode.getEastNorth(), n1en, n2en);
|
---|
885 | return !prevSegmentParallel && !nextSegmentParallel;
|
---|
886 | }
|
---|
887 |
|
---|
888 | /**
|
---|
889 | * Gathers possible move directions - perpendicular to the selected segment only.
|
---|
890 | * Neighboring segments go to {@link #dualAlignSegment1} and {@link #dualAlignSegment2}.
|
---|
891 | */
|
---|
892 | private void calculatePossibleDirectionsForDualAlign() {
|
---|
893 | // remember initial positions for segment nodes.
|
---|
894 | initialN1en = selectedSegment.getFirstNode().getEastNorth();
|
---|
895 | initialN2en = selectedSegment.getSecondNode().getEastNorth();
|
---|
896 |
|
---|
897 | // add direction perpendicular to the selected segment
|
---|
898 | possibleMoveDirections = new ArrayList<>();
|
---|
899 | possibleMoveDirections.add(new ReferenceSegment(new EastNorth(
|
---|
900 | initialN1en.getY() - initialN2en.getY(),
|
---|
901 | initialN2en.getX() - initialN1en.getX()
|
---|
902 | ), initialN1en, initialN2en, true));
|
---|
903 |
|
---|
904 | // set neighboring segments
|
---|
905 | Node prevNode = getPreviousNode(selectedSegment.lowerIndex);
|
---|
906 | if (prevNode != null) {
|
---|
907 | EastNorth prevNodeEn = prevNode.getEastNorth();
|
---|
908 | dualAlignSegment1 = new ReferenceSegment(new EastNorth(
|
---|
909 | initialN1en.getX() - prevNodeEn.getX(),
|
---|
910 | initialN1en.getY() - prevNodeEn.getY()
|
---|
911 | ), initialN1en, prevNodeEn, false);
|
---|
912 | }
|
---|
913 |
|
---|
914 | Node nextNode = getNextNode(selectedSegment.lowerIndex + 1);
|
---|
915 | if (nextNode != null) {
|
---|
916 | EastNorth nextNodeEn = nextNode.getEastNorth();
|
---|
917 | dualAlignSegment2 = new ReferenceSegment(new EastNorth(
|
---|
918 | initialN2en.getX() - nextNodeEn.getX(),
|
---|
919 | initialN2en.getY() - nextNodeEn.getY()
|
---|
920 | ), initialN2en, nextNodeEn, false);
|
---|
921 | }
|
---|
922 | }
|
---|
923 |
|
---|
924 | /**
|
---|
925 | * Calculate newN1en, newN2en best suitable for given mouse coordinates
|
---|
926 | * For dual align, calculates positions of new nodes, aligning them to neighboring segments.
|
---|
927 | * Elsewhere, just adds the vetor returned by calculateBestMovement to {@link #initialN1en}, {@link #initialN2en}.
|
---|
928 | * @param mouseEn mouse coordinates
|
---|
929 | * @return best movement vector
|
---|
930 | */
|
---|
931 | private EastNorth calculateBestMovementAndNewNodes(EastNorth mouseEn) {
|
---|
932 | EastNorth bestMovement = calculateBestMovement(mouseEn);
|
---|
933 | EastNorth n1movedEn = initialN1en.add(bestMovement), n2movedEn;
|
---|
934 |
|
---|
935 | // find out the movement distance, in metres
|
---|
936 | double distance = Main.getProjection().eastNorth2latlon(initialN1en).greatCircleDistance(
|
---|
937 | Main.getProjection().eastNorth2latlon(n1movedEn));
|
---|
938 | MainApplication.getMap().statusLine.setDist(distance);
|
---|
939 | updateStatusLine();
|
---|
940 |
|
---|
941 | if (dualAlignActive) {
|
---|
942 | // new positions of selected segment's nodes, without applying dual alignment
|
---|
943 | n1movedEn = initialN1en.add(bestMovement);
|
---|
944 | n2movedEn = initialN2en.add(bestMovement);
|
---|
945 |
|
---|
946 | // calculate intersections of parallel shifted segment and the adjacent lines
|
---|
947 | newN1en = Geometry.getLineLineIntersection(n1movedEn, n2movedEn, dualAlignSegment1.p1, dualAlignSegment1.p2);
|
---|
948 | newN2en = Geometry.getLineLineIntersection(n1movedEn, n2movedEn, dualAlignSegment2.p1, dualAlignSegment2.p2);
|
---|
949 | if (newN1en == null || newN2en == null) return bestMovement;
|
---|
950 | if (keepSegmentDirection && isOppositeDirection(newN1en, newN2en, initialN1en, initialN2en)) {
|
---|
951 | EastNorth collapsedSegmentPosition = Geometry.getLineLineIntersection(dualAlignSegment1.p1, dualAlignSegment1.p2,
|
---|
952 | dualAlignSegment2.p1, dualAlignSegment2.p2);
|
---|
953 | newN1en = collapsedSegmentPosition;
|
---|
954 | newN2en = collapsedSegmentPosition;
|
---|
955 | dualAlignSegmentCollapsed = true;
|
---|
956 | } else {
|
---|
957 | dualAlignSegmentCollapsed = false;
|
---|
958 | }
|
---|
959 | } else {
|
---|
960 | newN1en = n1movedEn;
|
---|
961 | newN2en = initialN2en.add(bestMovement);
|
---|
962 | }
|
---|
963 | return bestMovement;
|
---|
964 | }
|
---|
965 |
|
---|
966 | /**
|
---|
967 | * Gets a node index from selected way before given index.
|
---|
968 | * @param index index of current node
|
---|
969 | * @return index of previous node or <code>-1</code> if there are no nodes there.
|
---|
970 | */
|
---|
971 | private int getPreviousNodeIndex(int index) {
|
---|
972 | if (index > 0)
|
---|
973 | return index - 1;
|
---|
974 | else if (selectedSegment.way.isClosed())
|
---|
975 | return selectedSegment.way.getNodesCount() - 2;
|
---|
976 | else
|
---|
977 | return -1;
|
---|
978 | }
|
---|
979 |
|
---|
980 | /**
|
---|
981 | * Gets a node from selected way before given index.
|
---|
982 | * @param index index of current node
|
---|
983 | * @return previous node or <code>null</code> if there are no nodes there.
|
---|
984 | */
|
---|
985 | private Node getPreviousNode(int index) {
|
---|
986 | int indexPrev = getPreviousNodeIndex(index);
|
---|
987 | if (indexPrev >= 0)
|
---|
988 | return selectedSegment.way.getNode(indexPrev);
|
---|
989 | else
|
---|
990 | return null;
|
---|
991 | }
|
---|
992 |
|
---|
993 |
|
---|
994 | /**
|
---|
995 | * Gets a node index from selected way after given index.
|
---|
996 | * @param index index of current node
|
---|
997 | * @return index of next node or <code>-1</code> if there are no nodes there.
|
---|
998 | */
|
---|
999 | private int getNextNodeIndex(int index) {
|
---|
1000 | int count = selectedSegment.way.getNodesCount();
|
---|
1001 | if (index < count - 1)
|
---|
1002 | return index + 1;
|
---|
1003 | else if (selectedSegment.way.isClosed())
|
---|
1004 | return 1;
|
---|
1005 | else
|
---|
1006 | return -1;
|
---|
1007 | }
|
---|
1008 |
|
---|
1009 | /**
|
---|
1010 | * Gets a node from selected way after given index.
|
---|
1011 | * @param index index of current node
|
---|
1012 | * @return next node or <code>null</code> if there are no nodes there.
|
---|
1013 | */
|
---|
1014 | private Node getNextNode(int index) {
|
---|
1015 | int indexNext = getNextNodeIndex(index);
|
---|
1016 | if (indexNext >= 0)
|
---|
1017 | return selectedSegment.way.getNode(indexNext);
|
---|
1018 | else
|
---|
1019 | return null;
|
---|
1020 | }
|
---|
1021 |
|
---|
1022 | // -------------------------------------------------------------------------
|
---|
1023 | // paint methods
|
---|
1024 | // -------------------------------------------------------------------------
|
---|
1025 |
|
---|
1026 | @Override
|
---|
1027 | public void paint(Graphics2D g, MapView mv, Bounds box) {
|
---|
1028 | Graphics2D g2 = g;
|
---|
1029 | if (mode == Mode.select) {
|
---|
1030 | // Nothing to do
|
---|
1031 | } else {
|
---|
1032 | if (newN1en != null) {
|
---|
1033 |
|
---|
1034 | EastNorth p1 = initialN1en;
|
---|
1035 | EastNorth p2 = initialN2en;
|
---|
1036 | EastNorth p3 = newN1en;
|
---|
1037 | EastNorth p4 = newN2en;
|
---|
1038 |
|
---|
1039 | Point2D normalUnitVector = activeMoveDirection != null ? getNormalUniVector() : null;
|
---|
1040 |
|
---|
1041 | if (mode == Mode.extrude || mode == Mode.create_new) {
|
---|
1042 | g2.setColor(mainColor);
|
---|
1043 | g2.setStroke(mainStroke);
|
---|
1044 | // Draw rectangle around new area.
|
---|
1045 | MapViewPath b = new MapViewPath(mv);
|
---|
1046 | b.moveTo(p1);
|
---|
1047 | b.lineTo(p3);
|
---|
1048 | b.lineTo(p4);
|
---|
1049 | b.lineTo(p2);
|
---|
1050 | b.lineTo(p1);
|
---|
1051 | g2.draw(b);
|
---|
1052 |
|
---|
1053 | if (dualAlignActive) {
|
---|
1054 | // Draw reference ways
|
---|
1055 | drawReferenceSegment(g2, mv, dualAlignSegment1);
|
---|
1056 | drawReferenceSegment(g2, mv, dualAlignSegment2);
|
---|
1057 | } else if (activeMoveDirection != null && normalUnitVector != null) {
|
---|
1058 | // Draw reference way
|
---|
1059 | drawReferenceSegment(g2, mv, activeMoveDirection);
|
---|
1060 |
|
---|
1061 | // Draw right angle marker on first node position, only when moving at right angle
|
---|
1062 | if (activeMoveDirection.perpendicular) {
|
---|
1063 | // mirror RightAngle marker, so it is inside the extrude
|
---|
1064 | double headingRefWS = activeMoveDirection.p1.heading(activeMoveDirection.p2);
|
---|
1065 | double headingMoveDir = Math.atan2(normalUnitVector.getY(), normalUnitVector.getX());
|
---|
1066 | double headingDiff = headingRefWS - headingMoveDir;
|
---|
1067 | if (headingDiff < 0)
|
---|
1068 | headingDiff += 2 * Math.PI;
|
---|
1069 | boolean mirrorRA = Math.abs(headingDiff - Math.PI) > 1e-5;
|
---|
1070 | Point pr1 = mv.getPoint(activeMoveDirection.p1);
|
---|
1071 | drawAngleSymbol(g2, pr1, normalUnitVector, mirrorRA);
|
---|
1072 | }
|
---|
1073 | }
|
---|
1074 | } else if (mode == Mode.translate || mode == Mode.translate_node) {
|
---|
1075 | g2.setColor(mainColor);
|
---|
1076 | if (p1.distance(p2) < 3) {
|
---|
1077 | g2.setStroke(mainStroke);
|
---|
1078 | g2.draw(new MapViewPath(mv).shapeAround(p1, SymbolShape.CIRCLE, symbolSize));
|
---|
1079 | } else {
|
---|
1080 | g2.setStroke(oldLineStroke);
|
---|
1081 | g2.draw(new MapViewPath(mv).moveTo(p1).lineTo(p2));
|
---|
1082 | }
|
---|
1083 |
|
---|
1084 | if (dualAlignActive) {
|
---|
1085 | // Draw reference ways
|
---|
1086 | drawReferenceSegment(g2, mv, dualAlignSegment1);
|
---|
1087 | drawReferenceSegment(g2, mv, dualAlignSegment2);
|
---|
1088 | } else if (activeMoveDirection != null) {
|
---|
1089 |
|
---|
1090 | g2.setColor(helperColor);
|
---|
1091 | g2.setStroke(helperStrokeDash);
|
---|
1092 | // Draw a guideline along the normal.
|
---|
1093 | Line2D normline;
|
---|
1094 | Point2D centerpoint = mv.getPoint2D(p1.interpolate(p2, .5));
|
---|
1095 | normline = createSemiInfiniteLine(centerpoint, normalUnitVector, g2);
|
---|
1096 | g2.draw(normline);
|
---|
1097 | // Draw right angle marker on initial position, only when moving at right angle
|
---|
1098 | if (activeMoveDirection.perpendicular) {
|
---|
1099 | // EastNorth units per pixel
|
---|
1100 | g2.setStroke(helperStrokeRA);
|
---|
1101 | g2.setColor(mainColor);
|
---|
1102 | drawAngleSymbol(g2, centerpoint, normalUnitVector, false);
|
---|
1103 | }
|
---|
1104 | }
|
---|
1105 | }
|
---|
1106 | }
|
---|
1107 | g2.setStroke(helperStrokeRA); // restore default stroke to prevent starnge occasional drawings
|
---|
1108 | }
|
---|
1109 | }
|
---|
1110 |
|
---|
1111 | private Point2D getNormalUniVector() {
|
---|
1112 | double fac = 1.0 / activeMoveDirection.en.length();
|
---|
1113 | // mult by factor to get unit vector.
|
---|
1114 | Point2D normalUnitVector = new Point2D.Double(activeMoveDirection.en.getX() * fac, activeMoveDirection.en.getY() * fac);
|
---|
1115 |
|
---|
1116 | // Check to see if our new N1 is in a positive direction with respect to the normalUnitVector.
|
---|
1117 | // Even if the x component is zero, we should still be able to discern using +0.0 and -0.0
|
---|
1118 | if (newN1en != null && ((newN1en.getX() > initialN1en.getX()) != (normalUnitVector.getX() > -0.0))) {
|
---|
1119 | // If not, use a sign-flipped version of the normalUnitVector.
|
---|
1120 | normalUnitVector = new Point2D.Double(-normalUnitVector.getX(), -normalUnitVector.getY());
|
---|
1121 | }
|
---|
1122 |
|
---|
1123 | //HACK: swap Y, because the target pixels are top down, but EastNorth is bottom-up.
|
---|
1124 | //This is normally done by MapView.getPoint, but it does not work on vectors.
|
---|
1125 | normalUnitVector.setLocation(normalUnitVector.getX(), -normalUnitVector.getY());
|
---|
1126 | return normalUnitVector;
|
---|
1127 | }
|
---|
1128 |
|
---|
1129 | /**
|
---|
1130 | * Determines if from1-to1 and from2-to2 vectors directions are opposite
|
---|
1131 | * @param from1 vector1 start
|
---|
1132 | * @param to1 vector1 end
|
---|
1133 | * @param from2 vector2 start
|
---|
1134 | * @param to2 vector2 end
|
---|
1135 | * @return true if from1-to1 and from2-to2 vectors directions are opposite
|
---|
1136 | */
|
---|
1137 | private static boolean isOppositeDirection(EastNorth from1, EastNorth to1, EastNorth from2, EastNorth to2) {
|
---|
1138 | return (from1.getX()-to1.getX())*(from2.getX()-to2.getX())
|
---|
1139 | +(from1.getY()-to1.getY())*(from2.getY()-to2.getY()) < 0;
|
---|
1140 | }
|
---|
1141 |
|
---|
1142 | /**
|
---|
1143 | * Draws right angle symbol at specified position.
|
---|
1144 | * @param g2 the Graphics2D object used to draw on
|
---|
1145 | * @param center center point of angle
|
---|
1146 | * @param normal vector of normal
|
---|
1147 | * @param mirror {@code true} if symbol should be mirrored by the normal
|
---|
1148 | */
|
---|
1149 | private void drawAngleSymbol(Graphics2D g2, Point2D center, Point2D normal, boolean mirror) {
|
---|
1150 | // EastNorth units per pixel
|
---|
1151 | double factor = 1.0/g2.getTransform().getScaleX();
|
---|
1152 | double raoffsetx = symbolSize*factor*normal.getX();
|
---|
1153 | double raoffsety = symbolSize*factor*normal.getY();
|
---|
1154 |
|
---|
1155 | double cx = center.getX(), cy = center.getY();
|
---|
1156 | double k = mirror ? -1 : 1;
|
---|
1157 | Point2D ra1 = new Point2D.Double(cx + raoffsetx, cy + raoffsety);
|
---|
1158 | Point2D ra3 = new Point2D.Double(cx - raoffsety*k, cy + raoffsetx*k);
|
---|
1159 | Point2D ra2 = new Point2D.Double(ra1.getX() - raoffsety*k, ra1.getY() + raoffsetx*k);
|
---|
1160 |
|
---|
1161 | GeneralPath ra = new GeneralPath();
|
---|
1162 | ra.moveTo((float) ra1.getX(), (float) ra1.getY());
|
---|
1163 | ra.lineTo((float) ra2.getX(), (float) ra2.getY());
|
---|
1164 | ra.lineTo((float) ra3.getX(), (float) ra3.getY());
|
---|
1165 | g2.setStroke(helperStrokeRA);
|
---|
1166 | g2.draw(ra);
|
---|
1167 | }
|
---|
1168 |
|
---|
1169 | /**
|
---|
1170 | * Draws given reference segment.
|
---|
1171 | * @param g2 the Graphics2D object used to draw on
|
---|
1172 | * @param mv map view
|
---|
1173 | * @param seg the reference segment
|
---|
1174 | */
|
---|
1175 | private void drawReferenceSegment(Graphics2D g2, MapView mv, ReferenceSegment seg) {
|
---|
1176 | g2.setColor(helperColor);
|
---|
1177 | g2.setStroke(helperStrokeDash);
|
---|
1178 | g2.draw(new MapViewPath(mv).moveTo(seg.p1).lineTo(seg.p2));
|
---|
1179 | }
|
---|
1180 |
|
---|
1181 | /**
|
---|
1182 | * Creates a new Line that extends off the edge of the viewport in one direction
|
---|
1183 | * @param start The start point of the line
|
---|
1184 | * @param unitvector A unit vector denoting the direction of the line
|
---|
1185 | * @param g the Graphics2D object it will be used on
|
---|
1186 | * @return created line
|
---|
1187 | */
|
---|
1188 | private static Line2D createSemiInfiniteLine(Point2D start, Point2D unitvector, Graphics2D g) {
|
---|
1189 | Rectangle bounds = g.getDeviceConfiguration().getBounds();
|
---|
1190 | try {
|
---|
1191 | AffineTransform invtrans = g.getTransform().createInverse();
|
---|
1192 | Point2D widthpoint = invtrans.deltaTransform(new Point2D.Double(bounds.width, 0), null);
|
---|
1193 | Point2D heightpoint = invtrans.deltaTransform(new Point2D.Double(0, bounds.height), null);
|
---|
1194 |
|
---|
1195 | // Here we should end up with a gross overestimate of the maximum viewport diagonal in what
|
---|
1196 | // Graphics2D calls 'user space'. Essentially a manhattan distance of manhattan distances.
|
---|
1197 | // This can be used as a safe length of line to generate which will always go off-viewport.
|
---|
1198 | double linelength = Math.abs(widthpoint.getX()) + Math.abs(widthpoint.getY())
|
---|
1199 | + Math.abs(heightpoint.getX()) + Math.abs(heightpoint.getY());
|
---|
1200 |
|
---|
1201 | return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * linelength), start.getY()
|
---|
1202 | + (unitvector.getY() * linelength)));
|
---|
1203 | } catch (NoninvertibleTransformException e) {
|
---|
1204 | Logging.debug(e);
|
---|
1205 | return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * 10), start.getY()
|
---|
1206 | + (unitvector.getY() * 10)));
|
---|
1207 | }
|
---|
1208 | }
|
---|
1209 | }
|
---|