source: josm/trunk/src/org/openstreetmap/josm/actions/SplitWayAction.java@ 12279

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

sonar - squid:S3878 - Arrays should not be created for varargs parameters

  • Property svn:eol-style set to native
File size: 32.9 KB
RevLine 
[6380]1// License: GPL. For details, see LICENSE file.
[626]2package org.openstreetmap.josm.actions;
3
[2412]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[626]5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
[8886]8import java.awt.Component;
[8897]9import java.awt.GridBagLayout;
[626]10import java.awt.event.ActionEvent;
11import java.awt.event.KeyEvent;
12import java.util.ArrayList;
[4254]13import java.util.Arrays;
[626]14import java.util.Collection;
[5570]15import java.util.Collections;
[626]16import java.util.HashSet;
17import java.util.Iterator;
18import java.util.LinkedList;
19import java.util.List;
[11553]20import java.util.Optional;
[626]21import java.util.Set;
[9245]22import java.util.concurrent.atomic.AtomicInteger;
[626]23
[8886]24import javax.swing.DefaultListCellRenderer;
25import javax.swing.JLabel;
26import javax.swing.JList;
[626]27import javax.swing.JOptionPane;
[8886]28import javax.swing.JPanel;
29import javax.swing.ListSelectionModel;
[626]30
31import org.openstreetmap.josm.Main;
32import org.openstreetmap.josm.command.AddCommand;
33import org.openstreetmap.josm.command.ChangeCommand;
34import org.openstreetmap.josm.command.Command;
35import org.openstreetmap.josm.command.SequenceCommand;
36import org.openstreetmap.josm.data.osm.Node;
37import org.openstreetmap.josm.data.osm.OsmPrimitive;
[2521]38import org.openstreetmap.josm.data.osm.PrimitiveId;
[626]39import org.openstreetmap.josm.data.osm.Relation;
[668]40import org.openstreetmap.josm.data.osm.RelationMember;
[626]41import org.openstreetmap.josm.data.osm.Way;
[8886]42import org.openstreetmap.josm.data.osm.WaySegment;
[1990]43import org.openstreetmap.josm.gui.DefaultNameFormatter;
[8886]44import org.openstreetmap.josm.gui.ExtendedDialog;
[6130]45import org.openstreetmap.josm.gui.Notification;
[3152]46import org.openstreetmap.josm.gui.layer.OsmDataLayer;
47import org.openstreetmap.josm.tools.CheckParameterUtil;
[8897]48import org.openstreetmap.josm.tools.GBC;
[1084]49import org.openstreetmap.josm.tools.Shortcut;
[626]50
51/**
52 * Splits a way into multiple ways (all identical except for their node list).
[1023]53 *
[626]54 * Ways are just split at the selected nodes. The nodes remain in their
55 * original order. Selected nodes at the end of a way are ignored.
56 */
[1820]57public class SplitWayAction extends JosmAction {
[626]58
[5401]59 /**
60 * Represents the result of a {@link SplitWayAction}
61 * @see SplitWayAction#splitWay
62 * @see SplitWayAction#split
63 */
[2521]64 public static class SplitWayResult {
65 private final Command command;
66 private final List<? extends PrimitiveId> newSelection;
[8931]67 private final Way originalWay;
68 private final List<Way> newWays;
[2521]69
[5401]70 /**
[8540]71 * @param command The command to be performed to split the way (which is saved for later retrieval with {@link #getCommand})
72 * @param newSelection The new list of selected primitives ids (which is saved for later retrieval with {@link #getNewSelection})
73 * @param originalWay The original way being split (which is saved for later retrieval with {@link #getOriginalWay})
74 * @param newWays The resulting new ways (which is saved for later retrieval with {@link #getOriginalWay})
[5401]75 */
[3152]76 public SplitWayResult(Command command, List<? extends PrimitiveId> newSelection, Way originalWay, List<Way> newWays) {
[2521]77 this.command = command;
78 this.newSelection = newSelection;
[3152]79 this.originalWay = originalWay;
80 this.newWays = newWays;
[2521]81 }
82
[5401]83 /**
84 * Replies the command to be performed to split the way
85 * @return The command to be performed to split the way
86 */
[2521]87 public Command getCommand() {
88 return command;
89 }
90
[5401]91 /**
92 * Replies the new list of selected primitives ids
93 * @return The new list of selected primitives ids
94 */
[2521]95 public List<? extends PrimitiveId> getNewSelection() {
96 return newSelection;
97 }
[3152]98
[5401]99 /**
100 * Replies the original way being split
101 * @return The original way being split
102 */
[3152]103 public Way getOriginalWay() {
104 return originalWay;
105 }
106
[5401]107 /**
108 * Replies the resulting new ways
109 * @return The resulting new ways
110 */
[3152]111 public List<Way> getNewWays() {
112 return newWays;
113 }
[2521]114 }
115
[1169]116 /**
117 * Create a new SplitWayAction.
118 */
119 public SplitWayAction() {
120 super(tr("Split Way"), "splitway", tr("Split a way at the selected node."),
[4982]121 Shortcut.registerShortcut("tools:splitway", tr("Tool: {0}", tr("Split Way")), KeyEvent.VK_P, Shortcut.DIRECT), true);
[2323]122 putValue("help", ht("/Action/SplitWay"));
[1169]123 }
[626]124
[1169]125 /**
126 * Called when the action is executed.
127 *
128 * This method performs an expensive check whether the selection clearly defines one
129 * of the split actions outlined above, and if yes, calls the splitWay method.
130 */
[6084]131 @Override
[1169]132 public void actionPerformed(ActionEvent e) {
[626]133
[9245]134 if (SegmentToKeepSelectionDialog.DISPLAY_COUNT.get() > 0) {
135 new Notification(tr("Cannot split since another split operation is already in progress"))
136 .setIcon(JOptionPane.WARNING_MESSAGE).show();
137 return;
138 }
139
[10382]140 Collection<OsmPrimitive> selection = getLayerManager().getEditDataSet().getSelected();
[626]141
[3152]142 List<Node> selectedNodes = OsmPrimitive.getFilteredList(selection, Node.class);
143 List<Way> selectedWays = OsmPrimitive.getFilteredList(selection, Way.class);
[3392]144 List<Way> applicableWays = getApplicableWays(selectedWays, selectedNodes);
[3152]145
[3392]146 if (applicableWays == null) {
[6130]147 new Notification(
148 tr("The current selection cannot be used for splitting - no node is selected."))
149 .setIcon(JOptionPane.WARNING_MESSAGE)
150 .show();
[1169]151 return;
[3392]152 } else if (applicableWays.isEmpty()) {
[6130]153 new Notification(
154 tr("The selected nodes do not share the same way."))
155 .setIcon(JOptionPane.WARNING_MESSAGE)
156 .show();
[3392]157 return;
[1169]158 }
[626]159
[8276]160 // If several ways have been found, remove ways that doesn't have selected
161 // node in the middle
[5401]162 if (applicableWays.size() > 1) {
[8276]163 for (Iterator<Way> it = applicableWays.iterator(); it.hasNext();) {
164 Way w = it.next();
165 for (Node n : selectedNodes) {
166 if (!w.isInnerNode(n)) {
167 it.remove();
168 break;
[1169]169 }
170 }
[8276]171 }
[3392]172 }
[626]173
[3392]174 if (applicableWays.isEmpty()) {
[6130]175 new Notification(
[3392]176 trn("The selected node is not in the middle of any way.",
[6130]177 "The selected nodes are not in the middle of any way.",
178 selectedNodes.size()))
179 .setIcon(JOptionPane.WARNING_MESSAGE)
180 .show();
[3392]181 return;
182 } else if (applicableWays.size() > 1) {
[6130]183 new Notification(
[3392]184 trn("There is more than one way using the node you selected. Please select the way also.",
[6130]185 "There is more than one way using the nodes you selected. Please select the way also.",
186 selectedNodes.size()))
187 .setIcon(JOptionPane.WARNING_MESSAGE)
188 .show();
[3392]189 return;
190 }
[626]191
[3392]192 // Finally, applicableWays contains only one perfect way
[8886]193 final Way selectedWay = applicableWays.get(0);
194 final List<List<Node>> wayChunks = buildSplitChunks(selectedWay, selectedNodes);
[3156]195 if (wayChunks != null) {
[10448]196 List<Relation> selectedRelations = OsmPrimitive.getFilteredList(selection, Relation.class);
[8886]197 final List<OsmPrimitive> sel = new ArrayList<>(selectedWays.size() + selectedRelations.size());
[3392]198 sel.addAll(selectedWays);
199 sel.addAll(selectedRelations);
[8886]200
201 final List<Way> newWays = createNewWaysFromChunks(selectedWay, wayChunks);
[8955]202 final Way wayToKeep = Strategy.keepLongestChunk().determineWayToKeep(newWays);
[8886]203
[8978]204 if (ExpertToggleAction.isExpert() && !selectedWay.isNew()) {
[8886]205 final ExtendedDialog dialog = new SegmentToKeepSelectionDialog(selectedWay, newWays, wayToKeep, sel);
[8978]206 dialog.toggleEnable("way.split.segment-selection-dialog");
207 if (!dialog.toggleCheckState()) {
208 dialog.setModal(false);
209 dialog.showDialog();
210 return; // splitting is performed in SegmentToKeepSelectionDialog.buttonAction()
211 }
[8886]212 }
[10131]213 if (wayToKeep != null) {
[10382]214 final SplitWayResult result = doSplitWay(getLayerManager().getEditLayer(), selectedWay, wayToKeep, newWays, sel);
[10131]215 Main.main.undoRedo.add(result.getCommand());
[11737]216 if (!result.getNewSelection().isEmpty()) {
217 getLayerManager().getEditDataSet().setSelected(result.getNewSelection());
218 }
[10131]219 }
[3156]220 }
[1169]221 }
[626]222
[8276]223 /**
[8886]224 * A dialog to query which way segment should reuse the history of the way to split.
225 */
226 static class SegmentToKeepSelectionDialog extends ExtendedDialog {
[9245]227 static final AtomicInteger DISPLAY_COUNT = new AtomicInteger();
[10254]228 final transient Way selectedWay;
229 final transient List<Way> newWays;
[8886]230 final JList<Way> list;
[10254]231 final transient List<OsmPrimitive> selection;
232 final transient Way wayToKeep;
[8886]233
234 SegmentToKeepSelectionDialog(Way selectedWay, List<Way> newWays, Way wayToKeep, List<OsmPrimitive> selection) {
235 super(Main.parent, tr("Which way segment should reuse the history of {0}?", selectedWay.getId()),
236 new String[]{tr("Ok"), tr("Cancel")}, true);
237
238 this.selectedWay = selectedWay;
239 this.newWays = newWays;
240 this.selection = selection;
[8988]241 this.wayToKeep = wayToKeep;
[8886]242 this.list = new JList<>(newWays.toArray(new Way[newWays.size()]));
[8988]243 configureList();
[8886]244
[12279]245 setButtonIcons("ok", "cancel");
[8897]246 final JPanel pane = new JPanel(new GridBagLayout());
247 pane.add(new JLabel(getTitle()), GBC.eol().fill(GBC.HORIZONTAL));
248 pane.add(list, GBC.eop().fill(GBC.HORIZONTAL));
[8886]249 setContent(pane);
[9245]250 setDefaultCloseOperation(HIDE_ON_CLOSE);
[8886]251 }
252
[8978]253 private void configureList() {
[8886]254 list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
[10601]255 list.addListSelectionListener(e -> {
256 final Way selected = list.getSelectedValue();
[11452]257 if (selected != null && Main.isDisplayingMapView() && selected.getNodesCount() > 1) {
[10601]258 final Collection<WaySegment> segments = new ArrayList<>(selected.getNodesCount() - 1);
259 final Iterator<Node> it = selected.getNodes().iterator();
260 Node previousNode = it.next();
261 while (it.hasNext()) {
262 final Node node = it.next();
263 segments.add(WaySegment.forNodePair(selectedWay, previousNode, node));
264 previousNode = node;
[8886]265 }
[10601]266 setHighlightedWaySegments(segments);
[8886]267 }
268 });
[11343]269 list.setCellRenderer(new SegmentListCellRenderer());
[8886]270 }
271
272 protected void setHighlightedWaySegments(Collection<WaySegment> segments) {
273 selectedWay.getDataSet().setHighlightedWaySegments(segments);
274 Main.map.mapView.repaint();
275 }
276
277 @Override
278 public void setVisible(boolean visible) {
279 super.setVisible(visible);
280 if (visible) {
[9245]281 DISPLAY_COUNT.incrementAndGet();
[8988]282 list.setSelectedValue(wayToKeep, true);
[8886]283 } else {
284 setHighlightedWaySegments(Collections.<WaySegment>emptyList());
[9245]285 DISPLAY_COUNT.decrementAndGet();
[8886]286 }
287 }
288
289 @Override
290 protected void buttonAction(int buttonIndex, ActionEvent evt) {
291 super.buttonAction(buttonIndex, evt);
[8978]292 toggleSaveState(); // necessary since #showDialog() does not handle it due to the non-modal dialog
[8886]293 if (getValue() == 1) {
[10448]294 SplitWayResult result = doSplitWay(Main.getLayerManager().getEditLayer(),
295 selectedWay, list.getSelectedValue(), newWays, selection);
[8886]296 Main.main.undoRedo.add(result.getCommand());
[11737]297 if (!result.getNewSelection().isEmpty()) {
298 Main.getLayerManager().getEditDataSet().setSelected(result.getNewSelection());
299 }
[8886]300 }
301 }
302 }
303
[11343]304 static class SegmentListCellRenderer extends DefaultListCellRenderer {
305 @Override
306 public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
307 final Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
308 final String name = DefaultNameFormatter.getInstance().format((Way) value);
309 // get rid of id from DefaultNameFormatter.decorateNameWithId()
310 final String nameWithoutId = name
311 .replace(tr(" [id: {0}]", ((Way) value).getId()), "")
312 .replace(tr(" [id: {0}]", ((Way) value).getUniqueId()), "");
313 ((JLabel) c).setText(tr("Segment {0}: {1}", index + 1, nameWithoutId));
314 return c;
315 }
316 }
317
[8886]318 /**
[8955]319 * Determines which way chunk should reuse the old id and its history
320 *
321 * @since 8954
[10599]322 * @since 10599 (functional interface)
[8886]323 */
[10599]324 @FunctionalInterface
325 public interface Strategy {
[8955]326
327 /**
328 * Determines which way chunk should reuse the old id and its history.
329 *
330 * @param wayChunks the way chunks
331 * @return the way to keep
332 */
[10599]333 Way determineWayToKeep(Iterable<Way> wayChunks);
[8955]334
335 /**
336 * Returns a strategy which selects the way chunk with the highest node count to keep.
[9230]337 * @return strategy which selects the way chunk with the highest node count to keep
[8955]338 */
[10599]339 static Strategy keepLongestChunk() {
340 return wayChunks -> {
[8955]341 Way wayToKeep = null;
342 for (Way i : wayChunks) {
343 if (wayToKeep == null || i.getNodesCount() > wayToKeep.getNodesCount()) {
344 wayToKeep = i;
345 }
346 }
347 return wayToKeep;
[10599]348 };
[8886]349 }
[8955]350
351 /**
352 * Returns a strategy which selects the first way chunk.
[9230]353 * @return strategy which selects the first way chunk
[8955]354 */
[10599]355 static Strategy keepFirstChunk() {
356 return wayChunks -> wayChunks.iterator().next();
[8955]357 }
[8886]358 }
359
360 /**
361 * Determine which ways to split.
[8276]362 * @param selectedWays List of user selected ways.
363 * @param selectedNodes List of user selected nodes.
364 * @return List of ways to split
365 */
[10074]366 static List<Way> getApplicableWays(List<Way> selectedWays, List<Node> selectedNodes) {
[3392]367 if (selectedNodes.isEmpty())
368 return null;
369
[10074]370 // Special case - one of the selected ways touches (not cross) way that we want to split
[5570]371 if (selectedNodes.size() == 1) {
372 Node n = selectedNodes.get(0);
[12031]373 List<Way> referredWays = n.getParentWays();
[5570]374 Way inTheMiddle = null;
[10775]375 for (Way w: referredWays) {
[8276]376 // Need to look at all nodes see #11184 for a case where node n is
377 // firstNode, lastNode and also in the middle
378 if (selectedWays.contains(w) && w.isInnerNode(n)) {
[5570]379 if (inTheMiddle == null) {
380 inTheMiddle = w;
381 } else {
382 inTheMiddle = null;
383 break;
384 }
385 }
386 }
[8276]387 if (inTheMiddle != null)
[5570]388 return Collections.singletonList(inTheMiddle);
389 }
390
[3392]391 // List of ways shared by all nodes
[10074]392 return UnJoinNodeWayAction.getApplicableWays(selectedWays, selectedNodes);
[1169]393 }
[626]394
[1169]395 /**
[3152]396 * Splits the nodes of {@code wayToSplit} into a list of node sequences
397 * which are separated at the nodes in {@code splitPoints}.
[3156]398 *
[3152]399 * This method displays warning messages if {@code wayToSplit} and/or
400 * {@code splitPoints} aren't consistent.
[3156]401 *
[3152]402 * Returns null, if building the split chunks fails.
[3156]403 *
[3152]404 * @param wayToSplit the way to split. Must not be null.
405 * @param splitPoints the nodes where the way is split. Must not be null.
406 * @return the list of chunks
[1169]407 */
[8510]408 public static List<List<Node>> buildSplitChunks(Way wayToSplit, List<Node> splitPoints) {
[3152]409 CheckParameterUtil.ensureParameterNotNull(wayToSplit, "wayToSplit");
410 CheckParameterUtil.ensureParameterNotNull(splitPoints, "splitPoints");
[626]411
[7005]412 Set<Node> nodeSet = new HashSet<>(splitPoints);
413 List<List<Node>> wayChunks = new LinkedList<>();
414 List<Node> currentWayChunk = new ArrayList<>();
[1169]415 wayChunks.add(currentWayChunk);
[626]416
[3152]417 Iterator<Node> it = wayToSplit.getNodes().iterator();
[1169]418 while (it.hasNext()) {
419 Node currentNode = it.next();
420 boolean atEndOfWay = currentWayChunk.isEmpty() || !it.hasNext();
421 currentWayChunk.add(currentNode);
422 if (nodeSet.contains(currentNode) && !atEndOfWay) {
[7005]423 currentWayChunk = new ArrayList<>();
[1169]424 currentWayChunk.add(currentNode);
425 wayChunks.add(currentWayChunk);
426 }
427 }
[626]428
[1169]429 // Handle circular ways specially.
430 // If you split at a circular way at two nodes, you just want to split
431 // it at these points, not also at the former endpoint.
432 // So if the last node is the same first node, join the last and the
433 // first way chunk.
434 List<Node> lastWayChunk = wayChunks.get(wayChunks.size() - 1);
435 if (wayChunks.size() >= 2
436 && wayChunks.get(0).get(0) == lastWayChunk.get(lastWayChunk.size() - 1)
437 && !nodeSet.contains(wayChunks.get(0).get(0))) {
438 if (wayChunks.size() == 2) {
[6130]439 new Notification(
440 tr("You must select two or more nodes to split a circular way."))
441 .setIcon(JOptionPane.WARNING_MESSAGE)
442 .show();
[3152]443 return null;
[1169]444 }
445 lastWayChunk.remove(lastWayChunk.size() - 1);
446 lastWayChunk.addAll(wayChunks.get(0));
447 wayChunks.remove(wayChunks.size() - 1);
448 wayChunks.set(0, lastWayChunk);
449 }
[626]450
[1169]451 if (wayChunks.size() < 2) {
[10662]452 if (wayChunks.get(0).get(0) == wayChunks.get(0).get(wayChunks.get(0).size() - 1)) {
[6130]453 new Notification(
454 tr("You must select two or more nodes to split a circular way."))
455 .setIcon(JOptionPane.WARNING_MESSAGE)
456 .show();
[1809]457 } else {
[6130]458 new Notification(
459 tr("The way cannot be split at the selected nodes. (Hint: Select nodes in the middle of the way.)"))
460 .setIcon(JOptionPane.WARNING_MESSAGE)
461 .show();
[1809]462 }
[3152]463 return null;
[1169]464 }
[3152]465 return wayChunks;
[2521]466 }
467
[3152]468 /**
[8886]469 * Creates new way objects for the way chunks and transfers the keys from the original way.
470 * @param way the original way whose keys are transferred
471 * @param wayChunks the way chunks
472 * @return the new way objects
473 */
474 protected static List<Way> createNewWaysFromChunks(Way way, Iterable<List<Node>> wayChunks) {
475 final List<Way> newWays = new ArrayList<>();
476 for (List<Node> wayChunk : wayChunks) {
477 Way wayToAdd = new Way();
478 wayToAdd.setKeys(way.getKeys());
479 wayToAdd.setNodes(wayChunk);
480 newWays.add(wayToAdd);
481 }
482 return newWays;
483 }
484
485 /**
[5401]486 * Splits the way {@code way} into chunks of {@code wayChunks} and replies
487 * the result of this process in an instance of {@link SplitWayResult}.
488 *
489 * Note that changes are not applied to the data yet. You have to
490 * submit the command in {@link SplitWayResult#getCommand()} first,
491 * i.e. {@code Main.main.undoredo.add(result.getCommand())}.
492 *
493 * @param layer the layer which the way belongs to. Must not be null.
494 * @param way the way to split. Must not be null.
495 * @param wayChunks the list of way chunks into the way is split. Must not be null.
496 * @param selection The list of currently selected primitives
497 * @return the result from the split operation
[3152]498 */
[8540]499 public static SplitWayResult splitWay(OsmDataLayer layer, Way way, List<List<Node>> wayChunks,
500 Collection<? extends OsmPrimitive> selection) {
[8955]501 return splitWay(layer, way, wayChunks, selection, Strategy.keepLongestChunk());
502 }
503
504 /**
505 * Splits the way {@code way} into chunks of {@code wayChunks} and replies
506 * the result of this process in an instance of {@link SplitWayResult}.
507 * The {@link org.openstreetmap.josm.actions.SplitWayAction.Strategy} is used to determine which
508 * way chunk should reuse the old id and its history.
509 *
510 * Note that changes are not applied to the data yet. You have to
511 * submit the command in {@link SplitWayResult#getCommand()} first,
512 * i.e. {@code Main.main.undoredo.add(result.getCommand())}.
513 *
514 * @param layer the layer which the way belongs to. Must not be null.
515 * @param way the way to split. Must not be null.
516 * @param wayChunks the list of way chunks into the way is split. Must not be null.
517 * @param selection The list of currently selected primitives
518 * @param splitStrategy The strategy used to determine which way chunk should reuse the old id and its history
519 * @return the result from the split operation
520 * @since 8954
521 */
522 public static SplitWayResult splitWay(OsmDataLayer layer, Way way, List<List<Node>> wayChunks,
523 Collection<? extends OsmPrimitive> selection, Strategy splitStrategy) {
[1169]524 // build a list of commands, and also a new selection list
[8886]525 final List<OsmPrimitive> newSelection = new ArrayList<>(selection.size() + wayChunks.size());
[3392]526 newSelection.addAll(selection);
[1023]527
[8886]528 // Create all potential new ways
529 final List<Way> newWays = createNewWaysFromChunks(way, wayChunks);
530
531 // Determine which part reuses the existing way
[8955]532 final Way wayToKeep = splitStrategy.determineWayToKeep(newWays);
[8886]533
[10131]534 return wayToKeep != null ? doSplitWay(layer, way, wayToKeep, newWays, newSelection) : null;
[8886]535 }
536
537 static SplitWayResult doSplitWay(OsmDataLayer layer, Way way, Way wayToKeep, List<Way> newWays,
538 List<OsmPrimitive> newSelection) {
539
540 Collection<Command> commandList = new ArrayList<>(newWays.size());
[4254]541 Collection<String> nowarnroles = Main.pref.getCollection("way.split.roles.nowarn",
[5041]542 Arrays.asList("outer", "inner", "forward", "backward", "north", "south", "east", "west"));
[1023]543
[11737]544 final boolean isMapModeDraw = Main.map != null && Main.map.mapMode == Main.map.mapModeDraw;
545
[8886]546 // Change the original way
547 final Way changedWay = new Way(way);
548 changedWay.setNodes(wayToKeep.getNodes());
[11240]549 commandList.add(layer != null ? new ChangeCommand(layer, way, changedWay) : new ChangeCommand(way.getDataSet(), way, changedWay));
[11737]550 if (!isMapModeDraw && !newSelection.contains(way)) {
[3392]551 newSelection.add(way);
552 }
[8965]553 final int indexOfWayToKeep = newWays.indexOf(wayToKeep);
[8886]554 newWays.remove(wayToKeep);
[626]555
[11737]556 if (!isMapModeDraw) {
557 newSelection.addAll(newWays);
558 }
[8886]559 for (Way wayToAdd : newWays) {
[11240]560 commandList.add(layer != null ? new AddCommand(layer, wayToAdd) : new AddCommand(way.getDataSet(), wayToAdd));
[1169]561 }
[8886]562
[3152]563 boolean warnmerole = false;
564 boolean warnme = false;
[1169]565 // now copy all relations to new way also
[1814]566
[2521]567 for (Relation r : OsmPrimitive.getFilteredList(way.getReferrers(), Relation.class)) {
[2120]568 if (!r.isUsable()) {
[1809]569 continue;
570 }
[1600]571 Relation c = null;
[11553]572 String type = Optional.ofNullable(r.get("type")).orElse("");
[1600]573
[10001]574 int ic = 0;
575 int ir = 0;
[2764]576 List<RelationMember> relationMembers = r.getMembers();
577 for (RelationMember rm: relationMembers) {
[10662]578 if (rm.isWay() && rm.getMember() == way) {
[2628]579 boolean insert = true;
[9442]580 if ("restriction".equals(type) || "destination_sign".equals(type)) {
[2628]581 /* this code assumes the restriction is correct. No real error checking done */
582 String role = rm.getRole();
[8510]583 if ("from".equals(role) || "to".equals(role)) {
[9968]584 OsmPrimitive via = findVia(r, type);
[7005]585 List<Node> nodes = new ArrayList<>();
[7534]586 if (via != null) {
587 if (via instanceof Node) {
[8510]588 nodes.add((Node) via);
[7534]589 } else if (via instanceof Way) {
[8510]590 nodes.add(((Way) via).lastNode());
591 nodes.add(((Way) via).firstNode());
[2628]592 }
593 }
594 Way res = null;
[7534]595 for (Node n : nodes) {
[8510]596 if (changedWay.isFirstLastNode(n)) {
[2628]597 res = way;
598 }
599 }
[7534]600 if (res == null) {
[2628]601 for (Way wayToAdd : newWays) {
[8510]602 for (Node n : nodes) {
603 if (wayToAdd.isFirstLastNode(n)) {
[2628]604 res = wayToAdd;
605 }
606 }
607 }
[7534]608 if (res != null) {
[2628]609 if (c == null) {
610 c = new Relation(r);
611 }
612 c.addMember(new RelationMember(role, res));
613 c.removeMembersFor(way);
614 insert = false;
615 }
[2764]616 } else {
617 insert = false;
[2628]618 }
[8510]619 } else if (!"via".equals(role)) {
[1706]620 warnme = true;
[2764]621 }
[7534]622 } else if (!("route".equals(type)) && !("multipolygon".equals(type))) {
[2628]623 warnme = true;
624 }
625 if (c == null) {
626 c = new Relation(r);
627 }
[1600]628
[7534]629 if (insert) {
[4254]630 if (rm.hasRole() && !nowarnroles.contains(rm.getRole())) {
[2764]631 warnmerole = true;
632 }
633
634 Boolean backwards = null;
635 int k = 1;
[10001]636 while (ir - k >= 0 || ir + k < relationMembers.size()) {
637 if ((ir - k >= 0) && relationMembers.get(ir - k).isWay()) {
638 Way w = relationMembers.get(ir - k).getWay();
[10662]639 if ((w.lastNode() == way.firstNode()) || w.firstNode() == way.firstNode()) {
[8846]640 backwards = Boolean.FALSE;
[10662]641 } else if ((w.firstNode() == way.lastNode()) || w.lastNode() == way.lastNode()) {
[8846]642 backwards = Boolean.TRUE;
[2764]643 }
644 break;
645 }
[10001]646 if ((ir + k < relationMembers.size()) && relationMembers.get(ir + k).isWay()) {
647 Way w = relationMembers.get(ir + k).getWay();
[10662]648 if ((w.lastNode() == way.firstNode()) || w.firstNode() == way.firstNode()) {
[8846]649 backwards = Boolean.TRUE;
[10662]650 } else if ((w.firstNode() == way.lastNode()) || w.lastNode() == way.lastNode()) {
[8846]651 backwards = Boolean.FALSE;
[2764]652 }
653 break;
654 }
[2792]655 k++;
[2764]656 }
657
[10001]658 int j = ic;
[8965]659 final List<Way> waysToAddBefore = newWays.subList(0, indexOfWayToKeep);
660 for (Way wayToAdd : waysToAddBefore) {
[1930]661 RelationMember em = new RelationMember(rm.getRole(), wayToAdd);
[1609]662 j++;
[8965]663 if (Boolean.TRUE.equals(backwards)) {
[10001]664 c.addMember(ic + 1, em);
[8965]665 } else {
666 c.addMember(j - 1, em);
667 }
668 }
669 final List<Way> waysToAddAfter = newWays.subList(indexOfWayToKeep, newWays.size());
670 for (Way wayToAdd : waysToAddAfter) {
671 RelationMember em = new RelationMember(rm.getRole(), wayToAdd);
672 j++;
673 if (Boolean.TRUE.equals(backwards)) {
[10001]674 c.addMember(ic, em);
[1809]675 } else {
[1951]676 c.addMember(j, em);
[1809]677 }
[1169]678 }
[10001]679 ic = j;
[1169]680 }
681 }
[10001]682 ic++;
683 ir++;
[1169]684 }
[1600]685
[1809]686 if (c != null) {
[11240]687 commandList.add(layer != null ? new ChangeCommand(layer, r, c) : new ChangeCommand(r.getDataSet(), r, c));
[1809]688 }
[1169]689 }
[2381]690 if (warnmerole) {
[6130]691 new Notification(
692 tr("A role based relation membership was copied to all new ways.<br>You should verify this and correct it when necessary."))
693 .setIcon(JOptionPane.WARNING_MESSAGE)
694 .show();
[2381]695 } else if (warnme) {
[6130]696 new Notification(
697 tr("A relation membership was copied to all new ways.<br>You should verify this and correct it when necessary."))
698 .setIcon(JOptionPane.WARNING_MESSAGE)
699 .show();
[1809]700 }
[626]701
[3152]702 return new SplitWayResult(
703 new SequenceCommand(
[6507]704 /* for correct i18n of plural forms - see #9110 */
[9872]705 trn("Split way {0} into {1} part", "Split way {0} into {1} parts", newWays.size() + 1,
706 way.getDisplayName(DefaultNameFormatter.getInstance()), newWays.size() + 1),
[3152]707 commandList
[5570]708 ),
709 newSelection,
710 way,
711 newWays
712 );
[1169]713 }
[626]714
[9968]715 static OsmPrimitive findVia(Relation r, String type) {
716 for (RelationMember rmv : r.getMembers()) {
717 if (("restriction".equals(type) && "via".equals(rmv.getRole()))
718 || ("destination_sign".equals(type) && rmv.hasRole("sign", "intersection"))) {
719 return rmv.getMember();
720 }
721 }
722 return null;
723 }
724
[3152]725 /**
726 * Splits the way {@code way} at the nodes in {@code atNodes} and replies
[5266]727 * the result of this process in an instance of {@link SplitWayResult}.
[3156]728 *
[3152]729 * Note that changes are not applied to the data yet. You have to
[5266]730 * submit the command in {@link SplitWayResult#getCommand()} first,
[3152]731 * i.e. {@code Main.main.undoredo.add(result.getCommand())}.
[3156]732 *
[3152]733 * Replies null if the way couldn't be split at the given nodes.
[3156]734 *
[3152]735 * @param layer the layer which the way belongs to. Must not be null.
736 * @param way the way to split. Must not be null.
737 * @param atNodes the list of nodes where the way is split. Must not be null.
[5401]738 * @param selection The list of currently selected primitives
[3152]739 * @return the result from the split operation
740 */
[6889]741 public static SplitWayResult split(OsmDataLayer layer, Way way, List<Node> atNodes, Collection<? extends OsmPrimitive> selection) {
[3152]742 List<List<Node>> chunks = buildSplitChunks(way, atNodes);
[10174]743 return chunks != null ? splitWay(layer, way, chunks, selection) : null;
[3152]744 }
745
[1820]746 @Override
747 protected void updateEnabledState() {
[10548]748 updateEnabledStateOnCurrentSelection();
[2256]749 }
750
751 @Override
752 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
753 if (selection == null) {
754 setEnabled(false);
[1820]755 return;
756 }
[3392]757 for (OsmPrimitive primitive: selection) {
758 if (primitive instanceof Node) {
759 setEnabled(true); // Selection still can be wrong, but let SplitWayAction process and tell user what's wrong
760 return;
761 }
762 }
763 setEnabled(false);
[1169]764 }
[626]765}
Note: See TracBrowser for help on using the repository browser.