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

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

extract NodeGraph and NodePair from CombineWayAction to data.osm package

  • Property svn:eol-style set to native
File size: 10.1 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
110 List<DataSet> dataSets = ways.stream().map(Way::getDataSet).distinct().collect(Collectors.toList());
111 if (dataSets.size() != 1) {
112 throw new IllegalArgumentException("Cannot combine ways of multiple data sets.");
113 }
114
115 // try to build a new way which includes all the combined ways
116 NodeGraph graph = NodeGraph.createNearlyUndirectedGraphFromNodeWays(ways);
117 List<Node> path = graph.buildSpanningPath();
118 if (path == null) {
119 warnCombiningImpossible();
120 return null;
121 }
122 // check whether any ways have been reversed in the process
123 // and build the collection of tags used by the ways to combine
124 //
125 TagCollection wayTags = TagCollection.unionOfAllPrimitives(ways);
126
127 final List<Command> reverseWayTagCommands = new LinkedList<>();
128 List<Way> reversedWays = new LinkedList<>();
129 List<Way> unreversedWays = new LinkedList<>();
130 for (Way w: ways) {
131 // Treat zero or one-node ways as unreversed as Combine action action is a good way to fix them (see #8971)
132 if (w.getNodesCount() < 2 || (path.indexOf(w.getNode(0)) + 1) == path.lastIndexOf(w.getNode(1))) {
133 unreversedWays.add(w);
134 } else {
135 reversedWays.add(w);
136 }
137 }
138 // reverse path if all ways have been reversed
139 if (unreversedWays.isEmpty()) {
140 Collections.reverse(path);
141 unreversedWays = reversedWays;
142 reversedWays = null;
143 }
144 if ((reversedWays != null) && !reversedWays.isEmpty()) {
145 if (!confirmChangeDirectionOfWays()) return null;
146 // filter out ways that have no direction-dependent tags
147 unreversedWays = ReverseWayTagCorrector.irreversibleWays(unreversedWays);
148 reversedWays = ReverseWayTagCorrector.irreversibleWays(reversedWays);
149 // reverse path if there are more reversed than unreversed ways with direction-dependent tags
150 if (reversedWays.size() > unreversedWays.size()) {
151 Collections.reverse(path);
152 List<Way> tempWays = unreversedWays;
153 unreversedWays = null;
154 reversedWays = tempWays;
155 }
156 // if there are still reversed ways with direction-dependent tags, reverse their tags
157 if (!reversedWays.isEmpty() && PROP_REVERSE_WAY.get()) {
158 List<Way> unreversedTagWays = new ArrayList<>(ways);
159 unreversedTagWays.removeAll(reversedWays);
160 ReverseWayTagCorrector reverseWayTagCorrector = new ReverseWayTagCorrector();
161 List<Way> reversedTagWays = new ArrayList<>(reversedWays.size());
162 for (Way w : reversedWays) {
163 Way wnew = new Way(w);
164 reversedTagWays.add(wnew);
165 reverseWayTagCommands.addAll(reverseWayTagCorrector.execute(w, wnew));
166 }
167 if (!reverseWayTagCommands.isEmpty()) {
168 // commands need to be executed for CombinePrimitiveResolverDialog
169 Main.main.undoRedo.add(new SequenceCommand(tr("Reverse Ways"), reverseWayTagCommands));
170 }
171 wayTags = TagCollection.unionOfAllPrimitives(reversedTagWays);
172 wayTags.add(TagCollection.unionOfAllPrimitives(unreversedTagWays));
173 }
174 }
175
176 // create the new way and apply the new node list
177 //
178 Way targetWay = getTargetWay(ways);
179 Way modifiedTargetWay = new Way(targetWay);
180 modifiedTargetWay.setNodes(path);
181
182 final List<Command> resolution;
183 try {
184 resolution = CombinePrimitiveResolverDialog.launchIfNecessary(wayTags, ways, Collections.singleton(targetWay));
185 } finally {
186 if (!reverseWayTagCommands.isEmpty()) {
187 // undo reverseWayTagCorrector and merge into SequenceCommand below
188 Main.main.undoRedo.undo();
189 }
190 }
191
192 List<Command> cmds = new LinkedList<>();
193 List<Way> deletedWays = new LinkedList<>(ways);
194 deletedWays.remove(targetWay);
195
196 cmds.add(new ChangeCommand(dataSets.get(0), targetWay, modifiedTargetWay));
197 cmds.addAll(reverseWayTagCommands);
198 cmds.addAll(resolution);
199 cmds.add(new DeleteCommand(dataSets.get(0), deletedWays));
200 final Command sequenceCommand = new SequenceCommand(/* for correct i18n of plural forms - see #9110 */
201 trn("Combine {0} way", "Combine {0} ways", ways.size(), ways.size()), cmds);
202
203 return new Pair<>(targetWay, sequenceCommand);
204 }
205
206 @Override
207 public void actionPerformed(ActionEvent event) {
208 final DataSet ds = getLayerManager().getEditDataSet();
209 if (ds == null)
210 return;
211 Collection<Way> selectedWays = ds.getSelectedWays();
212 if (selectedWays.size() < 2) {
213 new Notification(
214 tr("Please select at least two ways to combine."))
215 .setIcon(JOptionPane.INFORMATION_MESSAGE)
216 .setDuration(Notification.TIME_SHORT)
217 .show();
218 return;
219 }
220 // combine and update gui
221 Pair<Way, Command> combineResult;
222 try {
223 combineResult = combineWaysWorker(selectedWays);
224 } catch (UserCancelException ex) {
225 Main.trace(ex);
226 return;
227 }
228
229 if (combineResult == null)
230 return;
231 final Way selectedWay = combineResult.a;
232 Main.main.undoRedo.add(combineResult.b);
233 if (selectedWay != null) {
234 GuiHelper.runInEDT(() -> ds.setSelected(selectedWay));
235 }
236 }
237
238 @Override
239 protected void updateEnabledState() {
240 updateEnabledStateOnCurrentSelection();
241 }
242
243 @Override
244 protected void updateEnabledState(Collection<? extends OsmPrimitive> selection) {
245 int numWays = 0;
246 for (OsmPrimitive osm : selection) {
247 if (osm instanceof Way) {
248 numWays++;
249 }
250 }
251 setEnabled(numWays >= 2);
252 }
253}
Note: See TracBrowser for help on using the repository browser.