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

Last change on this file since 12414 was 12329, checked in by michael2402, 7 years ago

See #14854: Selection change listeners should not re-add the primitives that are removed to the selection.

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