source: josm/trunk/src/org/openstreetmap/josm/actions/CombineWayAction.java@ 12527

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

fix #10838 - add robustness if incomplete ways are selected

  • Property svn:eol-style set to native
File size: 10.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.actions;
3
4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
5import static org.openstreetmap.josm.tools.I18n.tr;
6import static org.openstreetmap.josm.tools.I18n.trn;
7
8import java.awt.event.ActionEvent;
9import java.awt.event.KeyEvent;
10import java.util.ArrayList;
11import java.util.Collection;
12import java.util.Collections;
13import java.util.LinkedHashSet;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.stream.Collectors;
17
18import javax.swing.JOptionPane;
19
20import org.openstreetmap.josm.Main;
21import org.openstreetmap.josm.command.ChangeCommand;
22import org.openstreetmap.josm.command.Command;
23import org.openstreetmap.josm.command.DeleteCommand;
24import org.openstreetmap.josm.command.SequenceCommand;
25import org.openstreetmap.josm.corrector.ReverseWayTagCorrector;
26import org.openstreetmap.josm.data.osm.DataSet;
27import org.openstreetmap.josm.data.osm.Node;
28import org.openstreetmap.josm.data.osm.NodeGraph;
29import org.openstreetmap.josm.data.osm.OsmPrimitive;
30import org.openstreetmap.josm.data.osm.TagCollection;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.data.preferences.BooleanProperty;
33import org.openstreetmap.josm.gui.ExtendedDialog;
34import org.openstreetmap.josm.gui.Notification;
35import org.openstreetmap.josm.gui.conflict.tags.CombinePrimitiveResolverDialog;
36import org.openstreetmap.josm.gui.util.GuiHelper;
37import org.openstreetmap.josm.tools.Pair;
38import org.openstreetmap.josm.tools.Shortcut;
39import org.openstreetmap.josm.tools.UserCancelException;
40
41/**
42 * Combines multiple ways into one.
43 * @since 213
44 */
45public class CombineWayAction extends JosmAction {
46
47 private static final BooleanProperty PROP_REVERSE_WAY = new BooleanProperty("tag-correction.reverse-way", true);
48
49 /**
50 * Constructs a new {@code CombineWayAction}.
51 */
52 public CombineWayAction() {
53 super(tr("Combine Way"), "combineway", tr("Combine several ways into one."),
54 Shortcut.registerShortcut("tools:combineway", tr("Tool: {0}", tr("Combine Way")), KeyEvent.VK_C, Shortcut.DIRECT), true);
55 putValue("help", ht("/Action/CombineWay"));
56 }
57
58 protected static boolean confirmChangeDirectionOfWays() {
59 return new ExtendedDialog(Main.parent,
60 tr("Change directions?"),
61 tr("Reverse and Combine"), tr("Cancel"))
62 .setButtonIcons("wayflip", "cancel")
63 .setContent(tr("The ways can not be combined in their current directions. "
64 + "Do you want to reverse some of them?"))
65 .toggleEnable("combineway-reverse")
66 .showDialog()
67 .getValue() == 1;
68 }
69
70 protected static void warnCombiningImpossible() {
71 String msg = tr("Could not combine ways<br>"
72 + "(They could not be merged into a single string of nodes)");
73 new Notification(msg)
74 .setIcon(JOptionPane.INFORMATION_MESSAGE)
75 .show();
76 }
77
78 protected static Way getTargetWay(Collection<Way> combinedWays) {
79 // init with an arbitrary way
80 Way targetWay = combinedWays.iterator().next();
81
82 // look for the first way already existing on
83 // the server
84 for (Way w : combinedWays) {
85 targetWay = w;
86 if (!w.isNew()) {
87 break;
88 }
89 }
90 return targetWay;
91 }
92
93 /**
94 * Combine multiple ways into one.
95 * @param ways the way to combine to one way
96 * @return null if ways cannot be combined. Otherwise returns the combined ways and the commands to combine
97 * @throws UserCancelException if the user cancelled a dialog.
98 */
99 public static Pair<Way, Command> combineWaysWorker(Collection<Way> ways) throws UserCancelException {
100
101 // prepare and clean the list of ways to combine
102 //
103 if (ways == null || ways.isEmpty())
104 return null;
105 ways.remove(null); // just in case - remove all null ways from the collection
106
107 // remove duplicates, preserving order
108 ways = new LinkedHashSet<>(ways);
109 // remove incomplete ways
110 ways.removeIf(OsmPrimitive::isIncomplete);
111 // we need at least two ways
112 if (ways.size() < 2)
113 return null;
114
115 List<DataSet> dataSets = ways.stream().map(Way::getDataSet).distinct().collect(Collectors.toList());
116 if (dataSets.size() != 1) {
117 throw new IllegalArgumentException("Cannot combine ways of multiple data sets.");
118 }
119
120 // try to build a new way which includes all the combined ways
121 NodeGraph graph = NodeGraph.createNearlyUndirectedGraphFromNodeWays(ways);
122 List<Node> path = graph.buildSpanningPath();
123 if (path == null) {
124 warnCombiningImpossible();
125 return null;
126 }
127 // check whether any ways have been reversed in the process
128 // and build the collection of tags used by the ways to combine
129 //
130 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
131
132 final List<Command> reverseWayTagCommands = new LinkedList<>();
133 List<Way> reversedWays = new LinkedList<>();
134 List<Way> unreversedWays = new LinkedList<>();
135 for (Way w: ways) {
136 // Treat zero or one-node ways as unreversed as Combine action action is a good way to fix them (see #8971)
137 if (w.getNodesCount() < 2 || (path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
138 unreversedWays.add(w);
139 } else {
140 reversedWays.add(w);
141 }
142 }
143 // reverse path if all ways have been reversed
144 if (unreversedWays.isEmpty()) {
145 Collections.reverse(path);
146 unreversedWays = reversedWays;
147 reversedWays = null;
148 }
149 if ((reversedWays != null) && !reversedWays.isEmpty()) {
150 if (!confirmChangeDirectionOfWays()) return null;
151 // filter out ways that have no direction-dependent tags
152 unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
153 reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
154 // reverse path if there are more reversed than unreversed ways with direction-dependent tags
155 if (reversedWays.size() > unreversedWays.size()) {
156 Collections.reverse(path);
157 List<Way> tempWays = unreversedWays;
158 unreversedWays = null;
159 reversedWays = tempWays;
160 }
161 // if there are still reversed ways with direction-dependent tags, reverse their tags
162 if (!reversedWays.isEmpty() && PROP_REVERSE_WAY.get()) {
163 List<Way> unreversedTagWays = new ArrayList<>(ways);
164 unreversedTagWays.removeAll(reversedWays);
165 ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
166 List<Way> reversedTagWays = new ArrayList<>(reversedWays.size());
167 for (Way w : reversedWays) {
168 Way wnew = new Way(w);
169 reversedTagWays.add(wnew);
170 reverseWayTagCommands.addAll(reverseWayTagCorrector.execute(w, wnew));
171 }
172 if (!reverseWayTagCommands.isEmpty()) {
173 // commands need to be executed for CombinePrimitiveResolverDialog
174 Main.main.undoRedo.add(new SequenceCommand(tr("Reverse Ways"), reverseWayTagCommands));
175 }
176 wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
177 wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
178 }
179 }
180
181 // create the new way and apply the new node list
182 //
183 Way targetWay = getTargetWay(ways);
184 Way modifiedTargetWay = new Way(targetWay);
185 modifiedTargetWay.setNodes(path);
186
187 final List<Command> resolution;
188 try {
189 resolution = CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, Collections.singleton(targetWay));
190 } finally {
191 if (!reverseWayTagCommands.isEmpty()) {
192 // undo reverseWayTagCorrector and merge into SequenceCommand below
193 Main.main.undoRedo.undo();
194 }
195 }
196
197 List<Command> cmds = new LinkedList<>();
198 List<Way> deletedWays = new LinkedList<>(ways);
199 deletedWays.remove(targetWay);
200
201 cmds.add(new ChangeCommand(dataSets.get(0), targetWay, modifiedTargetWay));
202 cmds.addAll(reverseWayTagCommands);
203 cmds.addAll(resolution);
204 cmds.add(new DeleteCommand(dataSets.get(0), deletedWays));
205 final Command sequenceCommand = new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
206 trn("Combine {0} way", "Combine {0} ways", ways.size(), ways.size()), cmds);
207
208 return new Pair<>(targetWay, sequenceCommand);
209 }
210
211 @Override
212 public void actionPerformed(ActionEvent event) {
213 final DataSet ds = getLayerManager().getEditDataSet();
214 if (ds == null)
215 return;
216 Collection<Way> selectedWays = ds.getSelectedWays();
217 if (selectedWays.size() < 2) {
218 new Notification(
219 tr("Please select at least two ways to combine."))
220 .setIcon(JOptionPane.INFORMATION_MESSAGE)
221 .setDuration(Notification.TIME_SHORT)
222 .show();
223 return;
224 }
225 // combine and update gui
226 Pair<Way, Command> combineResult;
227 try {
228 combineResult = combineWaysWorker(selectedWays);
229 } catch (UserCancelException ex) {
230 Main.trace(ex);
231 return;
232 }
233
234 if (combineResult == null)
235 return;
236 final Way selectedWay = combineResult.a;
237 Main.main.undoRedo.add(combineResult.b);
238 if (selectedWay != null) {
239 GuiHelper.runInEDT(() -> ds.setSelected(selectedWay));
240 }
241 }
242
243 @Override
244 protected void updateEnabledState() {
245 updateEnabledStateOnCurrentSelection();
246 }
247
248 @Override
249 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
250 int numWays = 0;
251 for (OsmPrimitive osm : selection) {
252 if (osm instanceof Way && !osm.isIncomplete() && ++numWays >= 2) {
253 break;
254 }
255 }
256 setEnabled(numWays >= 2);
257 }
258}
Note: See TracBrowser for help on using the repository browser.