source: josm/trunk/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java@ 12512

Last change on this file since 12512 was 12512, checked in by Don-vip, 7 years ago

fix #12870 - Undo while extrude causes exception

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