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

Last change on this file since 13388 was 13309, checked in by Don-vip, 6 years ago

fix #15766, see #15688 - fix performance regression introduced in r13229 when drawing a way of many nodes while the filter dialog is open

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