source: josm/trunk/src/org/openstreetmap/josm/data/osm/DataSet.java@ 12672

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

see #15182 - move ConflictCollection from OsmDataLayer to DataSet. Simplifies some code where a data set is enough, and a layer is not needed

  • Property svn:eol-style set to native
File size: 47.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.osm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.geom.Area;
7import java.util.ArrayList;
8import java.util.Collection;
9import java.util.Collections;
10import java.util.HashMap;
11import java.util.HashSet;
12import java.util.Iterator;
13import java.util.LinkedList;
14import java.util.List;
15import java.util.Map;
16import java.util.Objects;
17import java.util.Set;
18import java.util.concurrent.CopyOnWriteArrayList;
19import java.util.concurrent.locks.Lock;
20import java.util.concurrent.locks.ReadWriteLock;
21import java.util.concurrent.locks.ReentrantReadWriteLock;
22import java.util.function.Function;
23import java.util.function.Predicate;
24import java.util.stream.Stream;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.data.Bounds;
28import org.openstreetmap.josm.data.Data;
29import org.openstreetmap.josm.data.DataSource;
30import org.openstreetmap.josm.data.ProjectionBounds;
31import org.openstreetmap.josm.data.SelectionChangedListener;
32import org.openstreetmap.josm.data.conflict.ConflictCollection;
33import org.openstreetmap.josm.data.coor.EastNorth;
34import org.openstreetmap.josm.data.coor.LatLon;
35import org.openstreetmap.josm.data.osm.DataSelectionListener.SelectionAddEvent;
36import org.openstreetmap.josm.data.osm.DataSelectionListener.SelectionChangeEvent;
37import org.openstreetmap.josm.data.osm.DataSelectionListener.SelectionRemoveEvent;
38import org.openstreetmap.josm.data.osm.DataSelectionListener.SelectionReplaceEvent;
39import org.openstreetmap.josm.data.osm.DataSelectionListener.SelectionToggleEvent;
40import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
41import org.openstreetmap.josm.data.osm.event.ChangesetIdChangedEvent;
42import org.openstreetmap.josm.data.osm.event.DataChangedEvent;
43import org.openstreetmap.josm.data.osm.event.DataSetListener;
44import org.openstreetmap.josm.data.osm.event.NodeMovedEvent;
45import org.openstreetmap.josm.data.osm.event.PrimitiveFlagsChangedEvent;
46import org.openstreetmap.josm.data.osm.event.PrimitivesAddedEvent;
47import org.openstreetmap.josm.data.osm.event.PrimitivesRemovedEvent;
48import org.openstreetmap.josm.data.osm.event.RelationMembersChangedEvent;
49import org.openstreetmap.josm.data.osm.event.SelectionEventManager;
50import org.openstreetmap.josm.data.osm.event.TagsChangedEvent;
51import org.openstreetmap.josm.data.osm.event.WayNodesChangedEvent;
52import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
53import org.openstreetmap.josm.data.projection.Projection;
54import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
55import org.openstreetmap.josm.gui.progress.ProgressMonitor;
56import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
57import org.openstreetmap.josm.tools.ListenerList;
58import org.openstreetmap.josm.tools.Logging;
59import org.openstreetmap.josm.tools.SubclassFilteredCollection;
60
61/**
62 * DataSet is the data behind the application. It can consists of only a few points up to the whole
63 * osm database. DataSet's can be merged together, saved, (up/down/disk)loaded etc.
64 *
65 * Note that DataSet is not an osm-primitive and so has no key association but a few members to
66 * store some information.
67 *
68 * Dataset is threadsafe - accessing Dataset simultaneously from different threads should never
69 * lead to data corruption or ConcurrentModificationException. However when for example one thread
70 * removes primitive and other thread try to add another primitive referring to the removed primitive,
71 * DataIntegrityException will occur.
72 *
73 * To prevent such situations, read/write lock is provided. While read lock is used, it's guaranteed that
74 * Dataset will not change. Sample usage:
75 * <code>
76 * ds.getReadLock().lock();
77 * try {
78 * // .. do something with dataset
79 * } finally {
80 * ds.getReadLock().unlock();
81 * }
82 * </code>
83 *
84 * Write lock should be used in case of bulk operations. In addition to ensuring that other threads can't
85 * use dataset in the middle of modifications it also stops sending of dataset events. That's good for performance
86 * reasons - GUI can be updated after all changes are done.
87 * Sample usage:
88 * <code>
89 * ds.beginUpdate()
90 * try {
91 * // .. do modifications
92 * } finally {
93 * ds.endUpdate();
94 * }
95 * </code>
96 *
97 * Note that it is not necessary to call beginUpdate/endUpdate for every dataset modification - dataset will get locked
98 * automatically.
99 *
100 * Note that locks cannot be upgraded - if one threads use read lock and and then write lock, dead lock will occur - see #5814 for
101 * sample ticket
102 *
103 * @author imi
104 */
105public final class DataSet extends QuadBucketPrimitiveStore implements Data, ProjectionChangeListener {
106
107 /**
108 * Upload policy.
109 *
110 * Determines if upload to the OSM server is intended, discouraged, or
111 * disabled / blocked.
112 */
113 public enum UploadPolicy {
114 /**
115 * Normal dataset, upload intended.
116 */
117 NORMAL("true"),
118 /**
119 * Upload discouraged, for example when using or distributing a private dataset.
120 */
121 DISCOURAGED("false"),
122 /**
123 * Upload blocked.
124 * Upload options completely disabled. Intended for special cases
125 * where a warning dialog is not enough, see #12731.
126 *
127 * For the user, it shouldn't be too easy to disable this flag.
128 */
129 BLOCKED("never");
130
131 final String xmlFlag;
132
133 UploadPolicy(String xmlFlag) {
134 this.xmlFlag = xmlFlag;
135 }
136
137 /**
138 * Get the corresponding value of the <code>upload='...'</code> XML-attribute
139 * in the .osm file.
140 * @return value of the <code>upload</code> attribute
141 */
142 public String getXmlFlag() {
143 return xmlFlag;
144 }
145 }
146
147 /**
148 * Maximum number of events that can be fired between beginUpdate/endUpdate to be send as single events (ie without DatasetChangedEvent)
149 */
150 private static final int MAX_SINGLE_EVENTS = 30;
151
152 /**
153 * Maximum number of events to kept between beginUpdate/endUpdate. When more events are created, that simple DatasetChangedEvent is sent)
154 */
155 private static final int MAX_EVENTS = 1000;
156
157 private final Storage<OsmPrimitive> allPrimitives = new Storage<>(new Storage.PrimitiveIdHash(), true);
158 private final Map<PrimitiveId, OsmPrimitive> primitivesMap = allPrimitives.foreignKey(new Storage.PrimitiveIdHash());
159 private final CopyOnWriteArrayList<DataSetListener> listeners = new CopyOnWriteArrayList<>();
160
161 // provide means to highlight map elements that are not osm primitives
162 private Collection<WaySegment> highlightedVirtualNodes = new LinkedList<>();
163 private Collection<WaySegment> highlightedWaySegments = new LinkedList<>();
164 private final ListenerList<HighlightUpdateListener> highlightUpdateListeners = ListenerList.create();
165
166 // Number of open calls to beginUpdate
167 private int updateCount;
168 // Events that occurred while dataset was locked but should be fired after write lock is released
169 private final List<AbstractDatasetChangedEvent> cachedEvents = new ArrayList<>();
170
171 private UploadPolicy uploadPolicy;
172
173 private final ReadWriteLock lock = new ReentrantReadWriteLock();
174
175 /**
176 * The mutex lock that is used to synchronize selection changes.
177 */
178 private final Object selectionLock = new Object();
179 /**
180 * The current selected primitives. This is always a unmodifiable set.
181 *
182 * The set should be ordered in the order in which the primitives have been added to the selection.
183 */
184 private Set<OsmPrimitive> currentSelectedPrimitives = Collections.emptySet();
185
186 /**
187 * A list of listeners that listen to selection changes on this layer.
188 */
189 private final ListenerList<DataSelectionListener> selectionListeners = ListenerList.create();
190
191 private Area cachedDataSourceArea;
192 private List<Bounds> cachedDataSourceBounds;
193
194 /**
195 * All data sources of this DataSet.
196 */
197 private final Collection<DataSource> dataSources = new LinkedList<>();
198
199 private final ConflictCollection conflicts = new ConflictCollection();
200
201 /**
202 * Constructs a new {@code DataSet}.
203 */
204 public DataSet() {
205 // Transparently register as projection change listener. No need to explicitly remove
206 // the listener, projection change listeners are managed as WeakReferences.
207 Main.addProjectionChangeListener(this);
208 addSelectionListener((DataSelectionListener) e -> fireDreprecatedSelectionChange(e.getSelection()));
209 }
210
211 /**
212 * Creates a new {@link DataSet}.
213 * @param copyFrom An other {@link DataSet} to copy the contents of this dataset from.
214 * @since 10346
215 */
216 public DataSet(DataSet copyFrom) {
217 this();
218 copyFrom.getReadLock().lock();
219 try {
220 Map<OsmPrimitive, OsmPrimitive> primMap = new HashMap<>();
221 for (Node n : copyFrom.getNodes()) {
222 Node newNode = new Node(n);
223 primMap.put(n, newNode);
224 addPrimitive(newNode);
225 }
226 for (Way w : copyFrom.getWays()) {
227 Way newWay = new Way(w);
228 primMap.put(w, newWay);
229 List<Node> newNodes = new ArrayList<>();
230 for (Node n: w.getNodes()) {
231 newNodes.add((Node) primMap.get(n));
232 }
233 newWay.setNodes(newNodes);
234 addPrimitive(newWay);
235 }
236 // Because relations can have other relations as members we first clone all relations
237 // and then get the cloned members
238 Collection<Relation> relations = copyFrom.getRelations();
239 for (Relation r : relations) {
240 Relation newRelation = new Relation(r);
241 newRelation.setMembers(null);
242 primMap.put(r, newRelation);
243 addPrimitive(newRelation);
244 }
245 for (Relation r : relations) {
246 Relation newRelation = (Relation) primMap.get(r);
247 List<RelationMember> newMembers = new ArrayList<>();
248 for (RelationMember rm: r.getMembers()) {
249 newMembers.add(new RelationMember(rm.getRole(), primMap.get(rm.getMember())));
250 }
251 newRelation.setMembers(newMembers);
252 }
253 for (DataSource source : copyFrom.dataSources) {
254 dataSources.add(new DataSource(source));
255 }
256 version = copyFrom.version;
257 uploadPolicy = copyFrom.uploadPolicy;
258 } finally {
259 copyFrom.getReadLock().unlock();
260 }
261 }
262
263 /**
264 * Adds a new data source.
265 * @param source data source to add
266 * @return {@code true} if the collection changed as a result of the call
267 * @since 11626
268 */
269 public synchronized boolean addDataSource(DataSource source) {
270 return addDataSources(Collections.singleton(source));
271 }
272
273 /**
274 * Adds new data sources.
275 * @param sources data sources to add
276 * @return {@code true} if the collection changed as a result of the call
277 * @since 11626
278 */
279 public synchronized boolean addDataSources(Collection<DataSource> sources) {
280 boolean changed = dataSources.addAll(sources);
281 if (changed) {
282 cachedDataSourceArea = null;
283 cachedDataSourceBounds = null;
284 }
285 return changed;
286 }
287
288 /**
289 * Returns the lock used for reading.
290 * @return the lock used for reading
291 */
292 public Lock getReadLock() {
293 return lock.readLock();
294 }
295
296 /**
297 * History of selections - shared by plugins and SelectionListDialog
298 */
299 private final LinkedList<Collection<? extends OsmPrimitive>> selectionHistory = new LinkedList<>();
300
301 /**
302 * Replies the history of JOSM selections
303 *
304 * @return list of history entries
305 */
306 public LinkedList<Collection<? extends OsmPrimitive>> getSelectionHistory() {
307 return selectionHistory;
308 }
309
310 /**
311 * Clears selection history list
312 */
313 public void clearSelectionHistory() {
314 selectionHistory.clear();
315 }
316
317 /**
318 * Maintains a list of used tags for autocompletion.
319 */
320 private AutoCompletionManager autocomplete;
321
322 /**
323 * Returns the autocompletion manager, which maintains a list of used tags for autocompletion.
324 * @return the autocompletion manager
325 */
326 public AutoCompletionManager getAutoCompletionManager() {
327 if (autocomplete == null) {
328 autocomplete = new AutoCompletionManager(this);
329 addDataSetListener(autocomplete);
330 }
331 return autocomplete;
332 }
333
334 /**
335 * The API version that created this data set, if any.
336 */
337 private String version;
338
339 /**
340 * Replies the API version this dataset was created from. May be null.
341 *
342 * @return the API version this dataset was created from. May be null.
343 */
344 public String getVersion() {
345 return version;
346 }
347
348 /**
349 * Sets the API version this dataset was created from.
350 *
351 * @param version the API version, i.e. "0.6"
352 */
353 public void setVersion(String version) {
354 this.version = version;
355 }
356
357 /**
358 * Determines if upload is being discouraged.
359 * (i.e. this dataset contains private data which should not be uploaded)
360 * @return {@code true} if upload is being discouraged, {@code false} otherwise
361 * @see #setUploadDiscouraged
362 * @deprecated use {@link #getUploadPolicy()}
363 */
364 @Deprecated
365 public boolean isUploadDiscouraged() {
366 return uploadPolicy == UploadPolicy.DISCOURAGED || uploadPolicy == UploadPolicy.BLOCKED;
367 }
368
369 /**
370 * Sets the "upload discouraged" flag.
371 * @param uploadDiscouraged {@code true} if this dataset contains private data which should not be uploaded
372 * @see #isUploadDiscouraged
373 * @deprecated use {@link #setUploadPolicy(UploadPolicy)}
374 */
375 @Deprecated
376 public void setUploadDiscouraged(boolean uploadDiscouraged) {
377 if (uploadPolicy != UploadPolicy.BLOCKED) {
378 this.uploadPolicy = uploadDiscouraged ? UploadPolicy.DISCOURAGED : UploadPolicy.NORMAL;
379 }
380 }
381
382 /**
383 * Get the upload policy.
384 * @return the upload policy
385 * @see #setUploadPolicy(UploadPolicy)
386 */
387 public UploadPolicy getUploadPolicy() {
388 return this.uploadPolicy;
389 }
390
391 /**
392 * Sets the upload policy.
393 * @param uploadPolicy the upload policy
394 * @see #getUploadPolicy()
395 */
396 public void setUploadPolicy(UploadPolicy uploadPolicy) {
397 this.uploadPolicy = uploadPolicy;
398 }
399
400 /**
401 * Holding bin for changeset tag information, to be applied when or if this is ever uploaded.
402 */
403 private final Map<String, String> changeSetTags = new HashMap<>();
404
405 /**
406 * Replies the set of changeset tags to be applied when or if this is ever uploaded.
407 * @return the set of changeset tags
408 * @see #addChangeSetTag
409 */
410 public Map<String, String> getChangeSetTags() {
411 return changeSetTags;
412 }
413
414 /**
415 * Adds a new changeset tag.
416 * @param k Key
417 * @param v Value
418 * @see #getChangeSetTags
419 */
420 public void addChangeSetTag(String k, String v) {
421 this.changeSetTags.put(k, v);
422 }
423
424 /**
425 * Gets a filtered collection of primitives matching the given predicate.
426 * @param <T> The primitive type.
427 * @param predicate The predicate to match
428 * @return The list of primtives.
429 * @since 10590
430 */
431 public <T extends OsmPrimitive> Collection<T> getPrimitives(Predicate<? super OsmPrimitive> predicate) {
432 return new SubclassFilteredCollection<>(allPrimitives, predicate);
433 }
434
435 /**
436 * Replies an unmodifiable collection of nodes in this dataset
437 *
438 * @return an unmodifiable collection of nodes in this dataset
439 */
440 public Collection<Node> getNodes() {
441 return getPrimitives(Node.class::isInstance);
442 }
443
444 @Override
445 public List<Node> searchNodes(BBox bbox) {
446 lock.readLock().lock();
447 try {
448 return super.searchNodes(bbox);
449 } finally {
450 lock.readLock().unlock();
451 }
452 }
453
454 /**
455 * Replies an unmodifiable collection of ways in this dataset
456 *
457 * @return an unmodifiable collection of ways in this dataset
458 */
459 public Collection<Way> getWays() {
460 return getPrimitives(Way.class::isInstance);
461 }
462
463 @Override
464 public List<Way> searchWays(BBox bbox) {
465 lock.readLock().lock();
466 try {
467 return super.searchWays(bbox);
468 } finally {
469 lock.readLock().unlock();
470 }
471 }
472
473 /**
474 * Searches for relations in the given bounding box.
475 * @param bbox the bounding box
476 * @return List of relations in the given bbox. Can be empty but not null
477 */
478 @Override
479 public List<Relation> searchRelations(BBox bbox) {
480 lock.readLock().lock();
481 try {
482 return super.searchRelations(bbox);
483 } finally {
484 lock.readLock().unlock();
485 }
486 }
487
488 /**
489 * Replies an unmodifiable collection of relations in this dataset
490 *
491 * @return an unmodifiable collection of relations in this dataset
492 */
493 public Collection<Relation> getRelations() {
494 return getPrimitives(Relation.class::isInstance);
495 }
496
497 /**
498 * Returns a collection containing all primitives of the dataset.
499 * @return A collection containing all primitives of the dataset. Data is not ordered
500 */
501 public Collection<OsmPrimitive> allPrimitives() {
502 return getPrimitives(o -> true);
503 }
504
505 /**
506 * Returns a collection containing all not-deleted primitives.
507 * @return A collection containing all not-deleted primitives.
508 * @see OsmPrimitive#isDeleted
509 */
510 public Collection<OsmPrimitive> allNonDeletedPrimitives() {
511 return getPrimitives(p -> !p.isDeleted());
512 }
513
514 /**
515 * Returns a collection containing all not-deleted complete primitives.
516 * @return A collection containing all not-deleted complete primitives.
517 * @see OsmPrimitive#isDeleted
518 * @see OsmPrimitive#isIncomplete
519 */
520 public Collection<OsmPrimitive> allNonDeletedCompletePrimitives() {
521 return getPrimitives(primitive -> !primitive.isDeleted() && !primitive.isIncomplete());
522 }
523
524 /**
525 * Returns a collection containing all not-deleted complete physical primitives.
526 * @return A collection containing all not-deleted complete physical primitives (nodes and ways).
527 * @see OsmPrimitive#isDeleted
528 * @see OsmPrimitive#isIncomplete
529 */
530 public Collection<OsmPrimitive> allNonDeletedPhysicalPrimitives() {
531 return getPrimitives(primitive -> !primitive.isDeleted() && !primitive.isIncomplete() && !(primitive instanceof Relation));
532 }
533
534 /**
535 * Returns a collection containing all modified primitives.
536 * @return A collection containing all modified primitives.
537 * @see OsmPrimitive#isModified
538 */
539 public Collection<OsmPrimitive> allModifiedPrimitives() {
540 return getPrimitives(OsmPrimitive::isModified);
541 }
542
543 /**
544 * Adds a primitive to the dataset.
545 *
546 * @param primitive the primitive.
547 */
548 @Override
549 public void addPrimitive(OsmPrimitive primitive) {
550 Objects.requireNonNull(primitive, "primitive");
551 beginUpdate();
552 try {
553 if (getPrimitiveById(primitive) != null)
554 throw new DataIntegrityProblemException(
555 tr("Unable to add primitive {0} to the dataset because it is already included", primitive.toString()));
556
557 allPrimitives.add(primitive);
558 primitive.setDataset(this);
559 primitive.updatePosition(); // Set cached bbox for way and relation (required for reindexWay and reindexRelation to work properly)
560 super.addPrimitive(primitive);
561 firePrimitivesAdded(Collections.singletonList(primitive), false);
562 } finally {
563 endUpdate();
564 }
565 }
566
567 /**
568 * Removes a primitive from the dataset. This method only removes the
569 * primitive form the respective collection of primitives managed
570 * by this dataset, i.e. from {@link #nodes}, {@link #ways}, or
571 * {@link #relations}. References from other primitives to this
572 * primitive are left unchanged.
573 *
574 * @param primitiveId the id of the primitive
575 */
576 public void removePrimitive(PrimitiveId primitiveId) {
577 beginUpdate();
578 try {
579 OsmPrimitive primitive = getPrimitiveByIdChecked(primitiveId);
580 if (primitive == null)
581 return;
582 removePrimitiveImpl(primitive);
583 firePrimitivesRemoved(Collections.singletonList(primitive), false);
584 } finally {
585 endUpdate();
586 }
587 }
588
589 private void removePrimitiveImpl(OsmPrimitive primitive) {
590 clearSelection(primitive.getPrimitiveId());
591 if (primitive.isSelected()) {
592 throw new DataIntegrityProblemException("Primitive was re-selected by a selection listener: " + primitive);
593 }
594 super.removePrimitive(primitive);
595 allPrimitives.remove(primitive);
596 primitive.setDataset(null);
597 }
598
599 @Override
600 protected void removePrimitive(OsmPrimitive primitive) {
601 beginUpdate();
602 try {
603 removePrimitiveImpl(primitive);
604 firePrimitivesRemoved(Collections.singletonList(primitive), false);
605 } finally {
606 endUpdate();
607 }
608 }
609
610 /*---------------------------------------------------
611 * SELECTION HANDLING
612 *---------------------------------------------------*/
613
614 /**
615 * Add a listener that listens to selection changes in this specific data set.
616 * @param listener The listener.
617 * @see #removeSelectionListener(DataSelectionListener)
618 * @see SelectionEventManager#addSelectionListener(SelectionChangedListener,
619 * org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode)
620 * To add a global listener.
621 */
622 public void addSelectionListener(DataSelectionListener listener) {
623 selectionListeners.addListener(listener);
624 }
625
626 /**
627 * Remove a listener that listens to selection changes in this specific data set.
628 * @param listener The listener.
629 * @see #addSelectionListener(DataSelectionListener)
630 */
631 public void removeSelectionListener(DataSelectionListener listener) {
632 selectionListeners.removeListener(listener);
633 }
634
635 /*---------------------------------------------------
636 * OLD SELECTION HANDLING
637 *---------------------------------------------------*/
638
639 /**
640 * A list of listeners to selection changed events. The list is static, as listeners register
641 * themselves for any dataset selection changes that occur, regardless of the current active
642 * dataset. (However, the selection does only change in the active layer)
643 */
644 private static final Collection<SelectionChangedListener> selListeners = new CopyOnWriteArrayList<>();
645
646 /**
647 * Adds a new selection listener.
648 * @param listener The selection listener to add
649 * @see #addSelectionListener(DataSelectionListener)
650 * @see SelectionEventManager#removeSelectionListener(SelectionChangedListener)
651 */
652 public static void addSelectionListener(SelectionChangedListener listener) {
653 ((CopyOnWriteArrayList<SelectionChangedListener>) selListeners).addIfAbsent(listener);
654 }
655
656 /**
657 * Removes a selection listener.
658 * @param listener The selection listener to remove
659 * @see #removeSelectionListener(DataSelectionListener)
660 * @see SelectionEventManager#removeSelectionListener(SelectionChangedListener)
661 */
662 public static void removeSelectionListener(SelectionChangedListener listener) {
663 selListeners.remove(listener);
664 }
665
666 /**
667 * Notifies all registered {@link SelectionChangedListener} about the current selection in
668 * this dataset.
669 * @deprecated You should never need to do this from the outside.
670 */
671 @Deprecated
672 public void fireSelectionChanged() {
673 fireDreprecatedSelectionChange(getAllSelected());
674 }
675
676 private static void fireDreprecatedSelectionChange(Collection<? extends OsmPrimitive> currentSelection) {
677 for (SelectionChangedListener l : selListeners) {
678 l.selectionChanged(currentSelection);
679 }
680 }
681
682 /**
683 * Returns selected nodes and ways.
684 * @return selected nodes and ways
685 */
686 public Collection<OsmPrimitive> getSelectedNodesAndWays() {
687 return new SubclassFilteredCollection<>(getSelected(), primitive -> primitive instanceof Node || primitive instanceof Way);
688 }
689
690 /**
691 * Returns an unmodifiable collection of *WaySegments* whose virtual
692 * nodes should be highlighted. WaySegments are used to avoid having
693 * to create a VirtualNode class that wouldn't have much purpose otherwise.
694 *
695 * @return unmodifiable collection of WaySegments
696 */
697 public Collection<WaySegment> getHighlightedVirtualNodes() {
698 return Collections.unmodifiableCollection(highlightedVirtualNodes);
699 }
700
701 /**
702 * Returns an unmodifiable collection of WaySegments that should be highlighted.
703 *
704 * @return unmodifiable collection of WaySegments
705 */
706 public Collection<WaySegment> getHighlightedWaySegments() {
707 return Collections.unmodifiableCollection(highlightedWaySegments);
708 }
709
710 /**
711 * Adds a listener that gets notified whenever way segment / virtual nodes highlights change.
712 * @param listener The Listener
713 * @since 12014
714 */
715 public void addHighlightUpdateListener(HighlightUpdateListener listener) {
716 highlightUpdateListeners.addListener(listener);
717 }
718
719 /**
720 * Removes a listener that was added with {@link #addHighlightUpdateListener(HighlightUpdateListener)}
721 * @param listener The Listener
722 * @since 12014
723 */
724 public void removeHighlightUpdateListener(HighlightUpdateListener listener) {
725 highlightUpdateListeners.removeListener(listener);
726 }
727
728 /**
729 * Replies an unmodifiable collection of primitives currently selected
730 * in this dataset, except deleted ones. May be empty, but not null.
731 *
732 * When iterating through the set it is ordered by the order in which the primitives were added to the selection.
733 *
734 * @return unmodifiable collection of primitives
735 */
736 public Collection<OsmPrimitive> getSelected() {
737 return new SubclassFilteredCollection<>(getAllSelected(), p -> !p.isDeleted());
738 }
739
740 /**
741 * Replies an unmodifiable collection of primitives currently selected
742 * in this dataset, including deleted ones. May be empty, but not null.
743 *
744 * When iterating through the set it is ordered by the order in which the primitives were added to the selection.
745 *
746 * @return unmodifiable collection of primitives
747 */
748 public Collection<OsmPrimitive> getAllSelected() {
749 return currentSelectedPrimitives;
750 }
751
752 /**
753 * Returns selected nodes.
754 * @return selected nodes
755 */
756 public Collection<Node> getSelectedNodes() {
757 return new SubclassFilteredCollection<>(getSelected(), Node.class::isInstance);
758 }
759
760 /**
761 * Returns selected ways.
762 * @return selected ways
763 */
764 public Collection<Way> getSelectedWays() {
765 return new SubclassFilteredCollection<>(getSelected(), Way.class::isInstance);
766 }
767
768 /**
769 * Returns selected relations.
770 * @return selected relations
771 */
772 public Collection<Relation> getSelectedRelations() {
773 return new SubclassFilteredCollection<>(getSelected(), Relation.class::isInstance);
774 }
775
776 /**
777 * Determines whether the selection is empty or not
778 * @return whether the selection is empty or not
779 */
780 public boolean selectionEmpty() {
781 return currentSelectedPrimitives.isEmpty();
782 }
783
784 /**
785 * Determines whether the given primitive is selected or not
786 * @param osm the primitive
787 * @return whether {@code osm} is selected or not
788 */
789 public boolean isSelected(OsmPrimitive osm) {
790 return currentSelectedPrimitives.contains(osm);
791 }
792
793 /**
794 * set what virtual nodes should be highlighted. Requires a Collection of
795 * *WaySegments* to avoid a VirtualNode class that wouldn't have much use
796 * otherwise.
797 * @param waySegments Collection of way segments
798 */
799 public void setHighlightedVirtualNodes(Collection<WaySegment> waySegments) {
800 if (highlightedVirtualNodes.isEmpty() && waySegments.isEmpty())
801 return;
802
803 highlightedVirtualNodes = waySegments;
804 fireHighlightingChanged();
805 }
806
807 /**
808 * set what virtual ways should be highlighted.
809 * @param waySegments Collection of way segments
810 */
811 public void setHighlightedWaySegments(Collection<WaySegment> waySegments) {
812 if (highlightedWaySegments.isEmpty() && waySegments.isEmpty())
813 return;
814
815 highlightedWaySegments = waySegments;
816 fireHighlightingChanged();
817 }
818
819 /**
820 * Sets the current selection to the primitives in <code>selection</code>.
821 * Notifies all {@link SelectionChangedListener} if <code>fireSelectionChangeEvent</code> is true.
822 *
823 * @param selection the selection
824 * @param fireSelectionChangeEvent true, if the selection change listeners are to be notified; false, otherwise
825 * @deprecated Use {@link #setSelected(Collection)} instead. To bee removed end of 2017. Does not seem to be used by plugins.
826 */
827 @Deprecated
828 public void setSelected(Collection<? extends PrimitiveId> selection, boolean fireSelectionChangeEvent) {
829 setSelected(selection);
830 }
831
832 /**
833 * Sets the current selection to the primitives in <code>selection</code>
834 * and notifies all {@link SelectionChangedListener}.
835 *
836 * @param selection the selection
837 */
838 public void setSelected(Collection<? extends PrimitiveId> selection) {
839 setSelected(selection.stream());
840 }
841
842 /**
843 * Sets the current selection to the primitives in <code>osm</code>
844 * and notifies all {@link SelectionChangedListener}.
845 *
846 * @param osm the primitives to set. <code>null</code> values are ignored for now, but this may be removed in the future.
847 */
848 public void setSelected(PrimitiveId... osm) {
849 setSelected(Stream.of(osm).filter(Objects::nonNull));
850 }
851
852 private void setSelected(Stream<? extends PrimitiveId> stream) {
853 doSelectionChange(old -> new SelectionReplaceEvent(this, old,
854 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
855 }
856
857 /**
858 * Adds the primitives in <code>selection</code> to the current selection
859 * and notifies all {@link SelectionChangedListener}.
860 *
861 * @param selection the selection
862 */
863 public void addSelected(Collection<? extends PrimitiveId> selection) {
864 addSelected(selection.stream());
865 }
866
867 /**
868 * Adds the primitives in <code>osm</code> to the current selection
869 * and notifies all {@link SelectionChangedListener}.
870 *
871 * @param osm the primitives to add
872 */
873 public void addSelected(PrimitiveId... osm) {
874 addSelected(Stream.of(osm));
875 }
876
877 private void addSelected(Stream<? extends PrimitiveId> stream) {
878 doSelectionChange(old -> new SelectionAddEvent(this, old,
879 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
880 }
881
882 /**
883 * Removes the selection from every value in the collection.
884 * @param osm The collection of ids to remove the selection from.
885 */
886 public void clearSelection(PrimitiveId... osm) {
887 clearSelection(Stream.of(osm));
888 }
889
890 /**
891 * Removes the selection from every value in the collection.
892 * @param list The collection of ids to remove the selection from.
893 */
894 public void clearSelection(Collection<? extends PrimitiveId> list) {
895 clearSelection(list.stream());
896 }
897
898 /**
899 * Clears the current selection.
900 */
901 public void clearSelection() {
902 setSelected(Stream.empty());
903 }
904
905 private void clearSelection(Stream<? extends PrimitiveId> stream) {
906 doSelectionChange(old -> new SelectionRemoveEvent(this, old,
907 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
908 }
909
910 /**
911 * Toggles the selected state of the given collection of primitives.
912 * @param osm The primitives to toggle
913 */
914 public void toggleSelected(Collection<? extends PrimitiveId> osm) {
915 toggleSelected(osm.stream());
916 }
917
918 /**
919 * Toggles the selected state of the given collection of primitives.
920 * @param osm The primitives to toggle
921 */
922 public void toggleSelected(PrimitiveId... osm) {
923 toggleSelected(Stream.of(osm));
924 }
925
926 private void toggleSelected(Stream<? extends PrimitiveId> stream) {
927 doSelectionChange(old -> new SelectionToggleEvent(this, old,
928 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
929 }
930
931 /**
932 * Do a selection change.
933 * <p>
934 * This is the only method that changes the current selection state.
935 * @param command A generator that generates the {@link SelectionChangeEvent} for the given base set of currently selected primitives.
936 * @return true iff the command did change the selection.
937 * @since 12048
938 */
939 private boolean doSelectionChange(Function<Set<OsmPrimitive>, SelectionChangeEvent> command) {
940 synchronized (selectionLock) {
941 SelectionChangeEvent event = command.apply(currentSelectedPrimitives);
942 if (event.isNop()) {
943 return false;
944 }
945 currentSelectedPrimitives = event.getSelection();
946 selectionListeners.fireEvent(l -> l.selectionChanged(event));
947 return true;
948 }
949 }
950
951 /**
952 * clear all highlights of virtual nodes
953 */
954 public void clearHighlightedVirtualNodes() {
955 setHighlightedVirtualNodes(new ArrayList<WaySegment>());
956 }
957
958 /**
959 * clear all highlights of way segments
960 */
961 public void clearHighlightedWaySegments() {
962 setHighlightedWaySegments(new ArrayList<WaySegment>());
963 }
964
965 @Override
966 public synchronized Area getDataSourceArea() {
967 if (cachedDataSourceArea == null) {
968 cachedDataSourceArea = Data.super.getDataSourceArea();
969 }
970 return cachedDataSourceArea;
971 }
972
973 @Override
974 public synchronized List<Bounds> getDataSourceBounds() {
975 if (cachedDataSourceBounds == null) {
976 cachedDataSourceBounds = Data.super.getDataSourceBounds();
977 }
978 return Collections.unmodifiableList(cachedDataSourceBounds);
979 }
980
981 @Override
982 public synchronized Collection<DataSource> getDataSources() {
983 return Collections.unmodifiableCollection(dataSources);
984 }
985
986 /**
987 * Returns a primitive with a given id from the data set. null, if no such primitive exists
988 *
989 * @param id uniqueId of the primitive. Might be &lt; 0 for newly created primitives
990 * @param type the type of the primitive. Must not be null.
991 * @return the primitive
992 * @throws NullPointerException if type is null
993 */
994 public OsmPrimitive getPrimitiveById(long id, OsmPrimitiveType type) {
995 return getPrimitiveById(new SimplePrimitiveId(id, type));
996 }
997
998 /**
999 * Returns a primitive with a given id from the data set. null, if no such primitive exists
1000 *
1001 * @param primitiveId type and uniqueId of the primitive. Might be &lt; 0 for newly created primitives
1002 * @return the primitive
1003 */
1004 public OsmPrimitive getPrimitiveById(PrimitiveId primitiveId) {
1005 return primitiveId != null ? primitivesMap.get(primitiveId) : null;
1006 }
1007
1008 /**
1009 * Show message and stack trace in log in case primitive is not found
1010 * @param primitiveId primitive id to look for
1011 * @return Primitive by id.
1012 */
1013 private OsmPrimitive getPrimitiveByIdChecked(PrimitiveId primitiveId) {
1014 OsmPrimitive result = getPrimitiveById(primitiveId);
1015 if (result == null && primitiveId != null) {
1016 Logging.warn(tr("JOSM expected to find primitive [{0} {1}] in dataset but it is not there. Please report this "
1017 + "at {2}. This is not a critical error, it should be safe to continue in your work.",
1018 primitiveId.getType(), Long.toString(primitiveId.getUniqueId()), Main.getJOSMWebsite()));
1019 Logging.error(new Exception());
1020 }
1021
1022 return result;
1023 }
1024
1025 private static void deleteWay(Way way) {
1026 way.setNodes(null);
1027 way.setDeleted(true);
1028 }
1029
1030 /**
1031 * Removes all references from ways in this dataset to a particular node.
1032 *
1033 * @param node the node
1034 * @return The set of ways that have been modified
1035 */
1036 public Set<Way> unlinkNodeFromWays(Node node) {
1037 Set<Way> result = new HashSet<>();
1038 beginUpdate();
1039 try {
1040 for (Way way : node.getParentWays()) {
1041 List<Node> wayNodes = way.getNodes();
1042 if (wayNodes.remove(node)) {
1043 if (wayNodes.size() < 2) {
1044 deleteWay(way);
1045 } else {
1046 way.setNodes(wayNodes);
1047 }
1048 result.add(way);
1049 }
1050 }
1051 } finally {
1052 endUpdate();
1053 }
1054 return result;
1055 }
1056
1057 /**
1058 * removes all references from relations in this dataset to this primitive
1059 *
1060 * @param primitive the primitive
1061 * @return The set of relations that have been modified
1062 */
1063 public Set<Relation> unlinkPrimitiveFromRelations(OsmPrimitive primitive) {
1064 Set<Relation> result = new HashSet<>();
1065 beginUpdate();
1066 try {
1067 for (Relation relation : getRelations()) {
1068 List<RelationMember> members = relation.getMembers();
1069
1070 Iterator<RelationMember> it = members.iterator();
1071 boolean removed = false;
1072 while (it.hasNext()) {
1073 RelationMember member = it.next();
1074 if (member.getMember().equals(primitive)) {
1075 it.remove();
1076 removed = true;
1077 }
1078 }
1079
1080 if (removed) {
1081 relation.setMembers(members);
1082 result.add(relation);
1083 }
1084 }
1085 } finally {
1086 endUpdate();
1087 }
1088 return result;
1089 }
1090
1091 /**
1092 * Removes all references from other primitives to the referenced primitive.
1093 *
1094 * @param referencedPrimitive the referenced primitive
1095 * @return The set of primitives that have been modified
1096 */
1097 public Set<OsmPrimitive> unlinkReferencesToPrimitive(OsmPrimitive referencedPrimitive) {
1098 Set<OsmPrimitive> result = new HashSet<>();
1099 beginUpdate();
1100 try {
1101 if (referencedPrimitive instanceof Node) {
1102 result.addAll(unlinkNodeFromWays((Node) referencedPrimitive));
1103 }
1104 result.addAll(unlinkPrimitiveFromRelations(referencedPrimitive));
1105 } finally {
1106 endUpdate();
1107 }
1108 return result;
1109 }
1110
1111 /**
1112 * Replies true if there is at least one primitive in this dataset with
1113 * {@link OsmPrimitive#isModified()} == <code>true</code>.
1114 *
1115 * @return true if there is at least one primitive in this dataset with
1116 * {@link OsmPrimitive#isModified()} == <code>true</code>.
1117 */
1118 public boolean isModified() {
1119 for (OsmPrimitive p: allPrimitives) {
1120 if (p.isModified())
1121 return true;
1122 }
1123 return false;
1124 }
1125
1126 /**
1127 * Adds a new data set listener.
1128 * @param dsl The data set listener to add
1129 */
1130 public void addDataSetListener(DataSetListener dsl) {
1131 listeners.addIfAbsent(dsl);
1132 }
1133
1134 /**
1135 * Removes a data set listener.
1136 * @param dsl The data set listener to remove
1137 */
1138 public void removeDataSetListener(DataSetListener dsl) {
1139 listeners.remove(dsl);
1140 }
1141
1142 /**
1143 * Can be called before bigger changes on dataset. Events are disabled until {@link #endUpdate()}.
1144 * {@link DataSetListener#dataChanged(DataChangedEvent event)} event is triggered after end of changes
1145 * <br>
1146 * Typical usecase should look like this:
1147 * <pre>
1148 * ds.beginUpdate();
1149 * try {
1150 * ...
1151 * } finally {
1152 * ds.endUpdate();
1153 * }
1154 * </pre>
1155 */
1156 public void beginUpdate() {
1157 lock.writeLock().lock();
1158 updateCount++;
1159 }
1160
1161 /**
1162 * @see DataSet#beginUpdate()
1163 */
1164 public void endUpdate() {
1165 if (updateCount > 0) {
1166 updateCount--;
1167 List<AbstractDatasetChangedEvent> eventsToFire = Collections.emptyList();
1168 if (updateCount == 0) {
1169 eventsToFire = new ArrayList<>(cachedEvents);
1170 cachedEvents.clear();
1171 }
1172
1173 if (!eventsToFire.isEmpty()) {
1174 lock.readLock().lock();
1175 lock.writeLock().unlock();
1176 try {
1177 if (eventsToFire.size() < MAX_SINGLE_EVENTS) {
1178 for (AbstractDatasetChangedEvent event: eventsToFire) {
1179 fireEventToListeners(event);
1180 }
1181 } else if (eventsToFire.size() == MAX_EVENTS) {
1182 fireEventToListeners(new DataChangedEvent(this));
1183 } else {
1184 fireEventToListeners(new DataChangedEvent(this, eventsToFire));
1185 }
1186 } finally {
1187 lock.readLock().unlock();
1188 }
1189 } else {
1190 lock.writeLock().unlock();
1191 }
1192
1193 } else
1194 throw new AssertionError("endUpdate called without beginUpdate");
1195 }
1196
1197 private void fireEventToListeners(AbstractDatasetChangedEvent event) {
1198 for (DataSetListener listener: listeners) {
1199 event.fire(listener);
1200 }
1201 }
1202
1203 private void fireEvent(AbstractDatasetChangedEvent event) {
1204 if (updateCount == 0)
1205 throw new AssertionError("dataset events can be fired only when dataset is locked");
1206 if (cachedEvents.size() < MAX_EVENTS) {
1207 cachedEvents.add(event);
1208 }
1209 }
1210
1211 void firePrimitivesAdded(Collection<? extends OsmPrimitive> added, boolean wasIncomplete) {
1212 fireEvent(new PrimitivesAddedEvent(this, added, wasIncomplete));
1213 }
1214
1215 void firePrimitivesRemoved(Collection<? extends OsmPrimitive> removed, boolean wasComplete) {
1216 fireEvent(new PrimitivesRemovedEvent(this, removed, wasComplete));
1217 }
1218
1219 void fireTagsChanged(OsmPrimitive prim, Map<String, String> originalKeys) {
1220 fireEvent(new TagsChangedEvent(this, prim, originalKeys));
1221 }
1222
1223 void fireRelationMembersChanged(Relation r) {
1224 reindexRelation(r);
1225 fireEvent(new RelationMembersChangedEvent(this, r));
1226 }
1227
1228 void fireNodeMoved(Node node, LatLon newCoor, EastNorth eastNorth) {
1229 reindexNode(node, newCoor, eastNorth);
1230 fireEvent(new NodeMovedEvent(this, node));
1231 }
1232
1233 void fireWayNodesChanged(Way way) {
1234 reindexWay(way);
1235 fireEvent(new WayNodesChangedEvent(this, way));
1236 }
1237
1238 void fireChangesetIdChanged(OsmPrimitive primitive, int oldChangesetId, int newChangesetId) {
1239 fireEvent(new ChangesetIdChangedEvent(this, Collections.singletonList(primitive), oldChangesetId, newChangesetId));
1240 }
1241
1242 void firePrimitiveFlagsChanged(OsmPrimitive primitive) {
1243 fireEvent(new PrimitiveFlagsChangedEvent(this, primitive));
1244 }
1245
1246 void fireHighlightingChanged() {
1247 HighlightUpdateListener.HighlightUpdateEvent e = new HighlightUpdateListener.HighlightUpdateEvent(this);
1248 highlightUpdateListeners.fireEvent(l -> l.highlightUpdated(e));
1249 }
1250
1251 /**
1252 * Invalidates the internal cache of projected east/north coordinates.
1253 *
1254 * This method can be invoked after the globally configured projection method
1255 * changed.
1256 */
1257 public void invalidateEastNorthCache() {
1258 if (Main.getProjection() == null) return; // sanity check
1259 beginUpdate();
1260 try {
1261 for (Node n: getNodes()) {
1262 n.invalidateEastNorthCache();
1263 }
1264 } finally {
1265 endUpdate();
1266 }
1267 }
1268
1269 /**
1270 * Cleanups all deleted primitives (really delete them from the dataset).
1271 */
1272 public void cleanupDeletedPrimitives() {
1273 beginUpdate();
1274 try {
1275 Collection<OsmPrimitive> toCleanUp = getPrimitives(
1276 primitive -> primitive.isDeleted() && (!primitive.isVisible() || primitive.isNew()));
1277 if (!toCleanUp.isEmpty()) {
1278 // We unselect them in advance to not fire a selection change for every primitive
1279 clearSelection(toCleanUp.stream().map(OsmPrimitive::getPrimitiveId));
1280 for (OsmPrimitive primitive : toCleanUp) {
1281 removePrimitiveImpl(primitive);
1282 }
1283 firePrimitivesRemoved(toCleanUp, false);
1284 }
1285 } finally {
1286 endUpdate();
1287 }
1288 }
1289
1290 /**
1291 * Removes all primitives from the dataset and resets the currently selected primitives
1292 * to the empty collection. Also notifies selection change listeners if necessary.
1293 */
1294 @Override
1295 public void clear() {
1296 beginUpdate();
1297 try {
1298 clearSelection();
1299 for (OsmPrimitive primitive:allPrimitives) {
1300 primitive.setDataset(null);
1301 }
1302 super.clear();
1303 allPrimitives.clear();
1304 } finally {
1305 endUpdate();
1306 }
1307 }
1308
1309 /**
1310 * Marks all "invisible" objects as deleted. These objects should be always marked as
1311 * deleted when downloaded from the server. They can be undeleted later if necessary.
1312 *
1313 */
1314 public void deleteInvisible() {
1315 for (OsmPrimitive primitive:allPrimitives) {
1316 if (!primitive.isVisible()) {
1317 primitive.setDeleted(true);
1318 }
1319 }
1320 }
1321
1322 /**
1323 * Moves all primitives and datasources from DataSet "from" to this DataSet.
1324 * @param from The source DataSet
1325 */
1326 public void mergeFrom(DataSet from) {
1327 mergeFrom(from, null);
1328 }
1329
1330 /**
1331 * Moves all primitives and datasources from DataSet "from" to this DataSet.
1332 * @param from The source DataSet
1333 * @param progressMonitor The progress monitor
1334 */
1335 public synchronized void mergeFrom(DataSet from, ProgressMonitor progressMonitor) {
1336 if (from != null) {
1337 new DataSetMerger(this, from).merge(progressMonitor);
1338 synchronized (from) {
1339 if (!from.dataSources.isEmpty()) {
1340 if (dataSources.addAll(from.dataSources)) {
1341 cachedDataSourceArea = null;
1342 cachedDataSourceBounds = null;
1343 }
1344 from.dataSources.clear();
1345 from.cachedDataSourceArea = null;
1346 from.cachedDataSourceBounds = null;
1347 }
1348 }
1349 }
1350 }
1351
1352 /**
1353 * Replies the set of conflicts currently managed in this layer.
1354 *
1355 * @return the set of conflicts currently managed in this layer
1356 * @since 12672
1357 */
1358 public ConflictCollection getConflicts() {
1359 return conflicts;
1360 }
1361
1362 /* --------------------------------------------------------------------------------- */
1363 /* interface ProjectionChangeListner */
1364 /* --------------------------------------------------------------------------------- */
1365 @Override
1366 public void projectionChanged(Projection oldValue, Projection newValue) {
1367 invalidateEastNorthCache();
1368 }
1369
1370 /**
1371 * Returns the data sources bounding box.
1372 * @return the data sources bounding box
1373 */
1374 public synchronized ProjectionBounds getDataSourceBoundingBox() {
1375 BoundingXYVisitor bbox = new BoundingXYVisitor();
1376 for (DataSource source : dataSources) {
1377 bbox.visit(source.bounds);
1378 }
1379 if (bbox.hasExtend()) {
1380 return bbox.getBounds();
1381 }
1382 return null;
1383 }
1384}
Note: See TracBrowser for help on using the repository browser.