source: josm/trunk/src/org/openstreetmap/josm/command/PurgeCommand.java@ 12711

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

see #15182 - refactor PurgeAction/PurgeCommand to avoid unneeded dependence on action

  • Property svn:eol-style set to native
File size: 17.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.command;
3
4import static org.openstreetmap.josm.tools.I18n.trn;
5
6import java.util.ArrayList;
7import java.util.Collection;
8import java.util.HashMap;
9import java.util.HashSet;
10import java.util.Iterator;
11import java.util.List;
12import java.util.Map;
13import java.util.Objects;
14import java.util.Set;
15
16import javax.swing.Icon;
17
18import org.openstreetmap.josm.Main;
19import org.openstreetmap.josm.data.conflict.Conflict;
20import org.openstreetmap.josm.data.conflict.ConflictCollection;
21import org.openstreetmap.josm.data.osm.DataSet;
22import org.openstreetmap.josm.data.osm.Node;
23import org.openstreetmap.josm.data.osm.NodeData;
24import org.openstreetmap.josm.data.osm.OsmPrimitive;
25import org.openstreetmap.josm.data.osm.PrimitiveData;
26import org.openstreetmap.josm.data.osm.PrimitiveId;
27import org.openstreetmap.josm.data.osm.Relation;
28import org.openstreetmap.josm.data.osm.RelationData;
29import org.openstreetmap.josm.data.osm.RelationMember;
30import org.openstreetmap.josm.data.osm.Storage;
31import org.openstreetmap.josm.data.osm.Way;
32import org.openstreetmap.josm.data.osm.WayData;
33import org.openstreetmap.josm.gui.layer.OsmDataLayer;
34import org.openstreetmap.josm.tools.ImageProvider;
35
36/**
37 * Command, to purge a list of primitives.
38 */
39public class PurgeCommand extends Command {
40 protected List<OsmPrimitive> toPurge;
41 protected Storage<PrimitiveData> makeIncompleteData;
42
43 protected Map<PrimitiveId, PrimitiveData> makeIncompleteDataByPrimId;
44
45 protected final ConflictCollection purgedConflicts = new ConflictCollection();
46
47 /**
48 * Constructs a new {@code PurgeCommand} (handles conflicts).
49 * This command relies on a number of consistency conditions:
50 * - makeIncomplete must be a subset of toPurge.
51 * - Each primitive, that is in toPurge but not in makeIncomplete, must have all its referrers in toPurge.
52 * - Each element of makeIncomplete must not be new and must have only referrers that are either a relation or included in toPurge.
53 * @param layer OSM data layer
54 * @param toPurge primitives to purge
55 * @param makeIncomplete primitives to make incomplete
56 */
57 public PurgeCommand(OsmDataLayer layer, Collection<OsmPrimitive> toPurge, Collection<OsmPrimitive> makeIncomplete) {
58 super(layer);
59 init(toPurge, makeIncomplete);
60 }
61
62 /**
63 * Constructs a new {@code PurgeCommand} (does not handle conflicts).
64 * This command relies on a number of consistency conditions:
65 * - makeIncomplete must be a subset of toPurge.
66 * - Each primitive, that is in toPurge but not in makeIncomplete, must have all its referrers in toPurge.
67 * - Each element of makeIncomplete must not be new and must have only referrers that are either a relation or included in toPurge.
68 * @param data OSM data set
69 * @param toPurge primitives to purge
70 * @param makeIncomplete primitives to make incomplete
71 * @since 11240
72 */
73 public PurgeCommand(DataSet data, Collection<OsmPrimitive> toPurge, Collection<OsmPrimitive> makeIncomplete) {
74 super(data);
75 init(toPurge, makeIncomplete);
76 }
77
78 private void init(Collection<OsmPrimitive> toPurge, Collection<OsmPrimitive> makeIncomplete) {
79 /**
80 * The topological sort is to avoid missing way nodes and missing
81 * relation members when adding primitives back to the dataset on undo.
82 *
83 * The same should hold for normal execution, but at time of writing
84 * there seem to be no such consistency checks when removing primitives.
85 * (It is done in a save manner, anyway.)
86 */
87 this.toPurge = topoSort(toPurge);
88 saveIncomplete(makeIncomplete);
89 }
90
91 protected final void saveIncomplete(Collection<OsmPrimitive> makeIncomplete) {
92 makeIncompleteData = new Storage<>(new Storage.PrimitiveIdHash());
93 makeIncompleteDataByPrimId = makeIncompleteData.foreignKey(new Storage.PrimitiveIdHash());
94
95 for (OsmPrimitive osm : makeIncomplete) {
96 makeIncompleteData.add(osm.save());
97 }
98 }
99
100 @Override
101 public boolean executeCommand() {
102 getAffectedDataSet().beginUpdate();
103 try {
104 purgedConflicts.get().clear();
105 // unselect primitives in advance to not fire a selection change for every one of them
106 getAffectedDataSet().clearSelection(toPurge);
107 // Loop from back to front to keep referential integrity.
108 for (int i = toPurge.size()-1; i >= 0; --i) {
109 OsmPrimitive osm = toPurge.get(i);
110 if (makeIncompleteDataByPrimId.containsKey(osm)) {
111 // we could simply set the incomplete flag
112 // but that would not free memory in case the
113 // user clears undo/redo buffer after purge
114 PrimitiveData empty;
115 switch(osm.getType()) {
116 case NODE: empty = new NodeData(); break;
117 case WAY: empty = new WayData(); break;
118 case RELATION: empty = new RelationData(); break;
119 default: throw new AssertionError();
120 }
121 empty.setId(osm.getUniqueId());
122 empty.setIncomplete(true);
123 osm.load(empty);
124 } else {
125 getAffectedDataSet().removePrimitive(osm);
126 Conflict<?> conflict = getAffectedDataSet().getConflicts().getConflictForMy(osm);
127 if (conflict != null) {
128 purgedConflicts.add(conflict);
129 getAffectedDataSet().getConflicts().remove(conflict);
130 }
131 }
132 }
133 } finally {
134 getAffectedDataSet().endUpdate();
135 }
136 return true;
137 }
138
139 @Override
140 public void undoCommand() {
141 if (getAffectedDataSet() == null)
142 return;
143
144 for (OsmPrimitive osm : toPurge) {
145 PrimitiveData data = makeIncompleteDataByPrimId.get(osm);
146 if (data != null) {
147 if (getAffectedDataSet().getPrimitiveById(osm) != osm)
148 throw new AssertionError(
149 String.format("Primitive %s has been made incomplete when purging, but it cannot be found on undo.", osm));
150 osm.load(data);
151 } else {
152 if (getAffectedDataSet().getPrimitiveById(osm) != null)
153 throw new AssertionError(String.format("Primitive %s was removed when purging, but is still there on undo", osm));
154 getAffectedDataSet().addPrimitive(osm);
155 }
156 }
157
158 for (Conflict<?> conflict : purgedConflicts) {
159 getAffectedDataSet().getConflicts().add(conflict);
160 }
161 }
162
163 /**
164 * Sorts a collection of primitives such that for each object
165 * its referrers come later in the sorted collection.
166 * @param sel collection of primitives to sort
167 * @return sorted list
168 */
169 public static List<OsmPrimitive> topoSort(Collection<OsmPrimitive> sel) {
170 Set<OsmPrimitive> in = new HashSet<>(sel);
171
172 List<OsmPrimitive> out = new ArrayList<>(in.size());
173
174 // Nodes not deleted in the first pass
175 Set<OsmPrimitive> remainingNodes = new HashSet<>(in.size());
176
177 /**
178 * First add nodes that have no way referrer.
179 */
180 outer:
181 for (Iterator<OsmPrimitive> it = in.iterator(); it.hasNext();) {
182 OsmPrimitive u = it.next();
183 if (u instanceof Node) {
184 Node n = (Node) u;
185 for (OsmPrimitive ref : n.getReferrers()) {
186 if (ref instanceof Way && in.contains(ref)) {
187 it.remove();
188 remainingNodes.add(n);
189 continue outer;
190 }
191 }
192 it.remove();
193 out.add(n);
194 }
195 }
196
197 /**
198 * Then add all ways, each preceded by its (remaining) nodes.
199 */
200 for (Iterator<OsmPrimitive> it = in.iterator(); it.hasNext();) {
201 OsmPrimitive u = it.next();
202 if (u instanceof Way) {
203 Way w = (Way) u;
204 it.remove();
205 for (Node n : w.getNodes()) {
206 if (remainingNodes.contains(n)) {
207 remainingNodes.remove(n);
208 out.add(n);
209 }
210 }
211 out.add(w);
212 }
213 }
214
215 if (!remainingNodes.isEmpty())
216 throw new AssertionError("topo sort algorithm failed (nodes remaining)");
217
218 /**
219 * Rest are relations. Do topological sorting on a DAG where each
220 * arrow points from child to parent. (Because it is faster to
221 * loop over getReferrers() than getMembers().)
222 */
223 @SuppressWarnings({ "unchecked", "rawtypes" })
224 Set<Relation> inR = (Set) in;
225
226 Map<Relation, Integer> numChilds = new HashMap<>();
227
228 // calculate initial number of childs
229 for (Relation r : inR) {
230 numChilds.put(r, 0);
231 }
232 for (Relation r : inR) {
233 for (OsmPrimitive parent : r.getReferrers()) {
234 if (!(parent instanceof Relation))
235 throw new AssertionError();
236 Integer i = numChilds.get(parent);
237 if (i != null) {
238 numChilds.put((Relation) parent, i+1);
239 }
240 }
241 }
242 Set<Relation> childlessR = new HashSet<>();
243 for (Relation r : inR) {
244 if (numChilds.get(r).equals(0)) {
245 childlessR.add(r);
246 }
247 }
248
249 List<Relation> outR = new ArrayList<>(inR.size());
250 while (!childlessR.isEmpty()) {
251 // Identify one childless Relation and let it virtually die. This makes other relations childless.
252 Iterator<Relation> it = childlessR.iterator();
253 Relation next = it.next();
254 it.remove();
255 outR.add(next);
256
257 for (OsmPrimitive parentPrim : next.getReferrers()) {
258 Relation parent = (Relation) parentPrim;
259 Integer i = numChilds.get(parent);
260 if (i != null) {
261 numChilds.put(parent, i-1);
262 if (i-1 == 0) {
263 childlessR.add(parent);
264 }
265 }
266 }
267 }
268
269 if (outR.size() != inR.size())
270 throw new AssertionError("topo sort algorithm failed");
271
272 out.addAll(outR);
273
274 return out;
275 }
276
277 @Override
278 public String getDescriptionText() {
279 return trn("Purged {0} object", "Purged {0} objects", toPurge.size(), toPurge.size());
280 }
281
282 @Override
283 public Icon getDescriptionIcon() {
284 return ImageProvider.get("data", "purge");
285 }
286
287 @Override
288 public Collection<? extends OsmPrimitive> getParticipatingPrimitives() {
289 return toPurge;
290 }
291
292 @Override
293 public void fillModifiedData(Collection<OsmPrimitive> modified, Collection<OsmPrimitive> deleted, Collection<OsmPrimitive> added) {
294 // Do nothing
295 }
296
297 @Override
298 public int hashCode() {
299 return Objects.hash(super.hashCode(), toPurge, makeIncompleteData, makeIncompleteDataByPrimId, purgedConflicts, getAffectedDataSet());
300 }
301
302 @Override
303 public boolean equals(Object obj) {
304 if (this == obj) return true;
305 if (obj == null || getClass() != obj.getClass()) return false;
306 if (!super.equals(obj)) return false;
307 PurgeCommand that = (PurgeCommand) obj;
308 return Objects.equals(toPurge, that.toPurge) &&
309 Objects.equals(makeIncompleteData, that.makeIncompleteData) &&
310 Objects.equals(makeIncompleteDataByPrimId, that.makeIncompleteDataByPrimId) &&
311 Objects.equals(purgedConflicts, that.purgedConflicts);
312 }
313
314 /**
315 * Creates a new {@code PurgeCommand} to purge selected OSM primitives.
316 * @param layer optional osm data layer, can be null
317 * @param sel selected OSM primitives
318 * @param toPurgeAdditionally optional list that will be filled with primitives to be purged that have not been in the selection
319 * @return command to purge selected OSM primitives
320 * @since 12688
321 */
322 public static PurgeCommand build(OsmDataLayer layer, Collection<OsmPrimitive> sel, List<OsmPrimitive> toPurgeAdditionally) {
323 Set<OsmPrimitive> toPurge = new HashSet<>(sel);
324 // finally, contains all objects that are purged
325 Set<OsmPrimitive> toPurgeChecked = new HashSet<>();
326
327 // Add referrer, unless the object to purge is not new and the parent is a relation
328 Set<OsmPrimitive> toPurgeRecursive = new HashSet<>();
329 while (!toPurge.isEmpty()) {
330
331 for (OsmPrimitive osm: toPurge) {
332 for (OsmPrimitive parent: osm.getReferrers()) {
333 if (toPurge.contains(parent) || toPurgeChecked.contains(parent) || toPurgeRecursive.contains(parent)) {
334 continue;
335 }
336 if (parent instanceof Way || (parent instanceof Relation && osm.isNew())) {
337 if (toPurgeAdditionally != null) {
338 toPurgeAdditionally.add(parent);
339 }
340 toPurgeRecursive.add(parent);
341 }
342 }
343 toPurgeChecked.add(osm);
344 }
345 toPurge = toPurgeRecursive;
346 toPurgeRecursive = new HashSet<>();
347 }
348
349 // Subset of toPurgeChecked. Marks primitives that remain in the dataset, but incomplete.
350 Set<OsmPrimitive> makeIncomplete = new HashSet<>();
351
352 // Find the objects that will be incomplete after purging.
353 // At this point, all parents of new to-be-purged primitives are
354 // also to-be-purged and
355 // all parents of not-new to-be-purged primitives are either
356 // to-be-purged or of type relation.
357 TOP:
358 for (OsmPrimitive child : toPurgeChecked) {
359 if (child.isNew()) {
360 continue;
361 }
362 for (OsmPrimitive parent : child.getReferrers()) {
363 if (parent instanceof Relation && !toPurgeChecked.contains(parent)) {
364 makeIncomplete.add(child);
365 continue TOP;
366 }
367 }
368 }
369
370 // Add untagged way nodes. Do not add nodes that have other referrers not yet to-be-purged.
371 if (Main.pref.getBoolean("purge.add_untagged_waynodes", true)) {
372 Set<OsmPrimitive> wayNodes = new HashSet<>();
373 for (OsmPrimitive osm : toPurgeChecked) {
374 if (osm instanceof Way) {
375 Way w = (Way) osm;
376 NODE:
377 for (Node n : w.getNodes()) {
378 if (n.isTagged() || toPurgeChecked.contains(n)) {
379 continue;
380 }
381 for (OsmPrimitive ref : n.getReferrers()) {
382 if (ref != w && !toPurgeChecked.contains(ref)) {
383 continue NODE;
384 }
385 }
386 wayNodes.add(n);
387 }
388 }
389 }
390 toPurgeChecked.addAll(wayNodes);
391 if (toPurgeAdditionally != null) {
392 toPurgeAdditionally.addAll(wayNodes);
393 }
394 }
395
396 if (Main.pref.getBoolean("purge.add_relations_with_only_incomplete_members", true)) {
397 Set<Relation> relSet = new HashSet<>();
398 for (OsmPrimitive osm : toPurgeChecked) {
399 for (OsmPrimitive parent : osm.getReferrers()) {
400 if (parent instanceof Relation
401 && !(toPurgeChecked.contains(parent))
402 && hasOnlyIncompleteMembers((Relation) parent, toPurgeChecked, relSet)) {
403 relSet.add((Relation) parent);
404 }
405 }
406 }
407
408 // Add higher level relations (list gets extended while looping over it)
409 List<Relation> relLst = new ArrayList<>(relSet);
410 for (int i = 0; i < relLst.size(); ++i) { // foreach loop not applicable since list gets extended while looping over it
411 for (OsmPrimitive parent : relLst.get(i).getReferrers()) {
412 if (!(toPurgeChecked.contains(parent))
413 && hasOnlyIncompleteMembers((Relation) parent, toPurgeChecked, relLst)) {
414 relLst.add((Relation) parent);
415 }
416 }
417 }
418 relSet = new HashSet<>(relLst);
419 toPurgeChecked.addAll(relSet);
420 if (toPurgeAdditionally != null) {
421 toPurgeAdditionally.addAll(relSet);
422 }
423 }
424
425 return layer != null ? new PurgeCommand(layer, toPurgeChecked, makeIncomplete)
426 : new PurgeCommand(toPurgeChecked.iterator().next().getDataSet(), toPurgeChecked, makeIncomplete);
427 }
428
429 private static boolean hasOnlyIncompleteMembers(
430 Relation r, Collection<OsmPrimitive> toPurge, Collection<? extends OsmPrimitive> moreToPurge) {
431 for (RelationMember m : r.getMembers()) {
432 if (!m.getMember().isIncomplete() && !toPurge.contains(m.getMember()) && !moreToPurge.contains(m.getMember()))
433 return false;
434 }
435 return true;
436 }
437}
Note: See TracBrowser for help on using the repository browser.