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

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

see #15310 - remove most of deprecated APIs

  • Property svn:eol-style set to native
File size: 46.6 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 * Adds a primitive to the dataset.
521 *
522 * @param primitive the primitive.
523 */
524 @Override
525 public void addPrimitive(OsmPrimitive primitive) {
526 Objects.requireNonNull(primitive, "primitive");
527 beginUpdate();
528 try {
529 if (getPrimitiveById(primitive) != null)
530 throw new DataIntegrityProblemException(
531 tr("Unable to add primitive {0} to the dataset because it is already included", primitive.toString()));
532
533 allPrimitives.add(primitive);
534 primitive.setDataset(this);
535 primitive.updatePosition(); // Set cached bbox for way and relation (required for reindexWay and reindexRelation to work properly)
536 super.addPrimitive(primitive);
537 firePrimitivesAdded(Collections.singletonList(primitive), false);
538 } finally {
539 endUpdate();
540 }
541 }
542
543 /**
544 * Removes a primitive from the dataset. This method only removes the
545 * primitive form the respective collection of primitives managed
546 * by this dataset, i.e. from {@link #nodes}, {@link #ways}, or
547 * {@link #relations}. References from other primitives to this
548 * primitive are left unchanged.
549 *
550 * @param primitiveId the id of the primitive
551 */
552 public void removePrimitive(PrimitiveId primitiveId) {
553 beginUpdate();
554 try {
555 OsmPrimitive primitive = getPrimitiveByIdChecked(primitiveId);
556 if (primitive == null)
557 return;
558 removePrimitiveImpl(primitive);
559 firePrimitivesRemoved(Collections.singletonList(primitive), false);
560 } finally {
561 endUpdate();
562 }
563 }
564
565 private void removePrimitiveImpl(OsmPrimitive primitive) {
566 clearSelection(primitive.getPrimitiveId());
567 if (primitive.isSelected()) {
568 throw new DataIntegrityProblemException("Primitive was re-selected by a selection listener: " + primitive);
569 }
570 super.removePrimitive(primitive);
571 allPrimitives.remove(primitive);
572 primitive.setDataset(null);
573 }
574
575 @Override
576 protected void removePrimitive(OsmPrimitive primitive) {
577 beginUpdate();
578 try {
579 removePrimitiveImpl(primitive);
580 firePrimitivesRemoved(Collections.singletonList(primitive), false);
581 } finally {
582 endUpdate();
583 }
584 }
585
586 /*---------------------------------------------------
587 * SELECTION HANDLING
588 *---------------------------------------------------*/
589
590 /**
591 * Add a listener that listens to selection changes in this specific data set.
592 * @param listener The listener.
593 * @see #removeSelectionListener(DataSelectionListener)
594 * @see SelectionEventManager#addSelectionListener(SelectionChangedListener,
595 * org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode)
596 * To add a global listener.
597 */
598 public void addSelectionListener(DataSelectionListener listener) {
599 selectionListeners.addListener(listener);
600 }
601
602 /**
603 * Remove a listener that listens to selection changes in this specific data set.
604 * @param listener The listener.
605 * @see #addSelectionListener(DataSelectionListener)
606 */
607 public void removeSelectionListener(DataSelectionListener listener) {
608 selectionListeners.removeListener(listener);
609 }
610
611 /*---------------------------------------------------
612 * OLD SELECTION HANDLING
613 *---------------------------------------------------*/
614
615 /**
616 * A list of listeners to selection changed events. The list is static, as listeners register
617 * themselves for any dataset selection changes that occur, regardless of the current active
618 * dataset. (However, the selection does only change in the active layer)
619 */
620 private static final Collection<SelectionChangedListener> selListeners = new CopyOnWriteArrayList<>();
621
622 /**
623 * Adds a new selection listener.
624 * @param listener The selection listener to add
625 * @see #addSelectionListener(DataSelectionListener)
626 * @see SelectionEventManager#removeSelectionListener(SelectionChangedListener)
627 */
628 public static void addSelectionListener(SelectionChangedListener listener) {
629 ((CopyOnWriteArrayList<SelectionChangedListener>) selListeners).addIfAbsent(listener);
630 }
631
632 /**
633 * Removes a selection listener.
634 * @param listener The selection listener to remove
635 * @see #removeSelectionListener(DataSelectionListener)
636 * @see SelectionEventManager#removeSelectionListener(SelectionChangedListener)
637 */
638 public static void removeSelectionListener(SelectionChangedListener listener) {
639 selListeners.remove(listener);
640 }
641
642 private static void fireSelectionChange(Collection<? extends OsmPrimitive> currentSelection) {
643 for (SelectionChangedListener l : selListeners) {
644 l.selectionChanged(currentSelection);
645 }
646 }
647
648 /**
649 * Returns selected nodes and ways.
650 * @return selected nodes and ways
651 */
652 public Collection<OsmPrimitive> getSelectedNodesAndWays() {
653 return new SubclassFilteredCollection<>(getSelected(), primitive -> primitive instanceof Node || primitive instanceof Way);
654 }
655
656 /**
657 * Returns an unmodifiable collection of *WaySegments* whose virtual
658 * nodes should be highlighted. WaySegments are used to avoid having
659 * to create a VirtualNode class that wouldn't have much purpose otherwise.
660 *
661 * @return unmodifiable collection of WaySegments
662 */
663 public Collection<WaySegment> getHighlightedVirtualNodes() {
664 return Collections.unmodifiableCollection(highlightedVirtualNodes);
665 }
666
667 /**
668 * Returns an unmodifiable collection of WaySegments that should be highlighted.
669 *
670 * @return unmodifiable collection of WaySegments
671 */
672 public Collection<WaySegment> getHighlightedWaySegments() {
673 return Collections.unmodifiableCollection(highlightedWaySegments);
674 }
675
676 /**
677 * Adds a listener that gets notified whenever way segment / virtual nodes highlights change.
678 * @param listener The Listener
679 * @since 12014
680 */
681 public void addHighlightUpdateListener(HighlightUpdateListener listener) {
682 highlightUpdateListeners.addListener(listener);
683 }
684
685 /**
686 * Removes a listener that was added with {@link #addHighlightUpdateListener(HighlightUpdateListener)}
687 * @param listener The Listener
688 * @since 12014
689 */
690 public void removeHighlightUpdateListener(HighlightUpdateListener listener) {
691 highlightUpdateListeners.removeListener(listener);
692 }
693
694 /**
695 * Replies an unmodifiable collection of primitives currently selected
696 * in this dataset, except deleted ones. May be empty, but not null.
697 *
698 * When iterating through the set it is ordered by the order in which the primitives were added to the selection.
699 *
700 * @return unmodifiable collection of primitives
701 */
702 public Collection<OsmPrimitive> getSelected() {
703 return new SubclassFilteredCollection<>(getAllSelected(), p -> !p.isDeleted());
704 }
705
706 /**
707 * Replies an unmodifiable collection of primitives currently selected
708 * in this dataset, including deleted ones. May be empty, but not null.
709 *
710 * When iterating through the set it is ordered by the order in which the primitives were added to the selection.
711 *
712 * @return unmodifiable collection of primitives
713 */
714 public Collection<OsmPrimitive> getAllSelected() {
715 return currentSelectedPrimitives;
716 }
717
718 /**
719 * Returns selected nodes.
720 * @return selected nodes
721 */
722 public Collection<Node> getSelectedNodes() {
723 return new SubclassFilteredCollection<>(getSelected(), Node.class::isInstance);
724 }
725
726 /**
727 * Returns selected ways.
728 * @return selected ways
729 */
730 public Collection<Way> getSelectedWays() {
731 return new SubclassFilteredCollection<>(getSelected(), Way.class::isInstance);
732 }
733
734 /**
735 * Returns selected relations.
736 * @return selected relations
737 */
738 public Collection<Relation> getSelectedRelations() {
739 return new SubclassFilteredCollection<>(getSelected(), Relation.class::isInstance);
740 }
741
742 /**
743 * Determines whether the selection is empty or not
744 * @return whether the selection is empty or not
745 */
746 public boolean selectionEmpty() {
747 return currentSelectedPrimitives.isEmpty();
748 }
749
750 /**
751 * Determines whether the given primitive is selected or not
752 * @param osm the primitive
753 * @return whether {@code osm} is selected or not
754 */
755 public boolean isSelected(OsmPrimitive osm) {
756 return currentSelectedPrimitives.contains(osm);
757 }
758
759 /**
760 * set what virtual nodes should be highlighted. Requires a Collection of
761 * *WaySegments* to avoid a VirtualNode class that wouldn't have much use
762 * otherwise.
763 * @param waySegments Collection of way segments
764 */
765 public void setHighlightedVirtualNodes(Collection<WaySegment> waySegments) {
766 if (highlightedVirtualNodes.isEmpty() && waySegments.isEmpty())
767 return;
768
769 highlightedVirtualNodes = waySegments;
770 fireHighlightingChanged();
771 }
772
773 /**
774 * set what virtual ways should be highlighted.
775 * @param waySegments Collection of way segments
776 */
777 public void setHighlightedWaySegments(Collection<WaySegment> waySegments) {
778 if (highlightedWaySegments.isEmpty() && waySegments.isEmpty())
779 return;
780
781 highlightedWaySegments = waySegments;
782 fireHighlightingChanged();
783 }
784
785 /**
786 * Sets the current selection to the primitives in <code>selection</code>
787 * and notifies all {@link SelectionChangedListener}.
788 *
789 * @param selection the selection
790 */
791 public void setSelected(Collection<? extends PrimitiveId> selection) {
792 setSelected(selection.stream());
793 }
794
795 /**
796 * Sets the current selection to the primitives in <code>osm</code>
797 * and notifies all {@link SelectionChangedListener}.
798 *
799 * @param osm the primitives to set. <code>null</code> values are ignored for now, but this may be removed in the future.
800 */
801 public void setSelected(PrimitiveId... osm) {
802 setSelected(Stream.of(osm).filter(Objects::nonNull));
803 }
804
805 private void setSelected(Stream<? extends PrimitiveId> stream) {
806 doSelectionChange(old -> new SelectionReplaceEvent(this, old,
807 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
808 }
809
810 /**
811 * Adds the primitives in <code>selection</code> to the current selection
812 * and notifies all {@link SelectionChangedListener}.
813 *
814 * @param selection the selection
815 */
816 public void addSelected(Collection<? extends PrimitiveId> selection) {
817 addSelected(selection.stream());
818 }
819
820 /**
821 * Adds the primitives in <code>osm</code> to the current selection
822 * and notifies all {@link SelectionChangedListener}.
823 *
824 * @param osm the primitives to add
825 */
826 public void addSelected(PrimitiveId... osm) {
827 addSelected(Stream.of(osm));
828 }
829
830 private void addSelected(Stream<? extends PrimitiveId> stream) {
831 doSelectionChange(old -> new SelectionAddEvent(this, old,
832 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
833 }
834
835 /**
836 * Removes the selection from every value in the collection.
837 * @param osm The collection of ids to remove the selection from.
838 */
839 public void clearSelection(PrimitiveId... osm) {
840 clearSelection(Stream.of(osm));
841 }
842
843 /**
844 * Removes the selection from every value in the collection.
845 * @param list The collection of ids to remove the selection from.
846 */
847 public void clearSelection(Collection<? extends PrimitiveId> list) {
848 clearSelection(list.stream());
849 }
850
851 /**
852 * Clears the current selection.
853 */
854 public void clearSelection() {
855 setSelected(Stream.empty());
856 }
857
858 private void clearSelection(Stream<? extends PrimitiveId> stream) {
859 doSelectionChange(old -> new SelectionRemoveEvent(this, old,
860 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
861 }
862
863 /**
864 * Toggles the selected state of the given collection of primitives.
865 * @param osm The primitives to toggle
866 */
867 public void toggleSelected(Collection<? extends PrimitiveId> osm) {
868 toggleSelected(osm.stream());
869 }
870
871 /**
872 * Toggles the selected state of the given collection of primitives.
873 * @param osm The primitives to toggle
874 */
875 public void toggleSelected(PrimitiveId... osm) {
876 toggleSelected(Stream.of(osm));
877 }
878
879 private void toggleSelected(Stream<? extends PrimitiveId> stream) {
880 doSelectionChange(old -> new SelectionToggleEvent(this, old,
881 stream.map(this::getPrimitiveByIdChecked).filter(Objects::nonNull)));
882 }
883
884 /**
885 * Do a selection change.
886 * <p>
887 * This is the only method that changes the current selection state.
888 * @param command A generator that generates the {@link SelectionChangeEvent} for the given base set of currently selected primitives.
889 * @return true iff the command did change the selection.
890 * @since 12048
891 */
892 private boolean doSelectionChange(Function<Set<OsmPrimitive>, SelectionChangeEvent> command) {
893 synchronized (selectionLock) {
894 SelectionChangeEvent event = command.apply(currentSelectedPrimitives);
895 if (event.isNop()) {
896 return false;
897 }
898 currentSelectedPrimitives = event.getSelection();
899 selectionListeners.fireEvent(l -> l.selectionChanged(event));
900 return true;
901 }
902 }
903
904 /**
905 * clear all highlights of virtual nodes
906 */
907 public void clearHighlightedVirtualNodes() {
908 setHighlightedVirtualNodes(new ArrayList<WaySegment>());
909 }
910
911 /**
912 * clear all highlights of way segments
913 */
914 public void clearHighlightedWaySegments() {
915 setHighlightedWaySegments(new ArrayList<WaySegment>());
916 }
917
918 @Override
919 public synchronized Area getDataSourceArea() {
920 if (cachedDataSourceArea == null) {
921 cachedDataSourceArea = Data.super.getDataSourceArea();
922 }
923 return cachedDataSourceArea;
924 }
925
926 @Override
927 public synchronized List<Bounds> getDataSourceBounds() {
928 if (cachedDataSourceBounds == null) {
929 cachedDataSourceBounds = Data.super.getDataSourceBounds();
930 }
931 return Collections.unmodifiableList(cachedDataSourceBounds);
932 }
933
934 @Override
935 public synchronized Collection<DataSource> getDataSources() {
936 return Collections.unmodifiableCollection(dataSources);
937 }
938
939 /**
940 * Returns a primitive with a given id from the data set. null, if no such primitive exists
941 *
942 * @param id uniqueId of the primitive. Might be &lt; 0 for newly created primitives
943 * @param type the type of the primitive. Must not be null.
944 * @return the primitive
945 * @throws NullPointerException if type is null
946 */
947 public OsmPrimitive getPrimitiveById(long id, OsmPrimitiveType type) {
948 return getPrimitiveById(new SimplePrimitiveId(id, type));
949 }
950
951 /**
952 * Returns a primitive with a given id from the data set. null, if no such primitive exists
953 *
954 * @param primitiveId type and uniqueId of the primitive. Might be &lt; 0 for newly created primitives
955 * @return the primitive
956 */
957 public OsmPrimitive getPrimitiveById(PrimitiveId primitiveId) {
958 return primitiveId != null ? primitivesMap.get(primitiveId) : null;
959 }
960
961 /**
962 * Show message and stack trace in log in case primitive is not found
963 * @param primitiveId primitive id to look for
964 * @return Primitive by id.
965 */
966 private OsmPrimitive getPrimitiveByIdChecked(PrimitiveId primitiveId) {
967 OsmPrimitive result = getPrimitiveById(primitiveId);
968 if (result == null && primitiveId != null) {
969 Logging.warn(tr("JOSM expected to find primitive [{0} {1}] in dataset but it is not there. Please report this "
970 + "at {2}. This is not a critical error, it should be safe to continue in your work.",
971 primitiveId.getType(), Long.toString(primitiveId.getUniqueId()), Main.getJOSMWebsite()));
972 Logging.error(new Exception());
973 }
974
975 return result;
976 }
977
978 private static void deleteWay(Way way) {
979 way.setNodes(null);
980 way.setDeleted(true);
981 }
982
983 /**
984 * Removes all references from ways in this dataset to a particular node.
985 *
986 * @param node the node
987 * @return The set of ways that have been modified
988 */
989 public Set<Way> unlinkNodeFromWays(Node node) {
990 Set<Way> result = new HashSet<>();
991 beginUpdate();
992 try {
993 for (Way way : node.getParentWays()) {
994 List<Node> wayNodes = way.getNodes();
995 if (wayNodes.remove(node)) {
996 if (wayNodes.size() < 2) {
997 deleteWay(way);
998 } else {
999 way.setNodes(wayNodes);
1000 }
1001 result.add(way);
1002 }
1003 }
1004 } finally {
1005 endUpdate();
1006 }
1007 return result;
1008 }
1009
1010 /**
1011 * removes all references from relations in this dataset to this primitive
1012 *
1013 * @param primitive the primitive
1014 * @return The set of relations that have been modified
1015 */
1016 public Set<Relation> unlinkPrimitiveFromRelations(OsmPrimitive primitive) {
1017 Set<Relation> result = new HashSet<>();
1018 beginUpdate();
1019 try {
1020 for (Relation relation : getRelations()) {
1021 List<RelationMember> members = relation.getMembers();
1022
1023 Iterator<RelationMember> it = members.iterator();
1024 boolean removed = false;
1025 while (it.hasNext()) {
1026 RelationMember member = it.next();
1027 if (member.getMember().equals(primitive)) {
1028 it.remove();
1029 removed = true;
1030 }
1031 }
1032
1033 if (removed) {
1034 relation.setMembers(members);
1035 result.add(relation);
1036 }
1037 }
1038 } finally {
1039 endUpdate();
1040 }
1041 return result;
1042 }
1043
1044 /**
1045 * Removes all references from other primitives to the referenced primitive.
1046 *
1047 * @param referencedPrimitive the referenced primitive
1048 * @return The set of primitives that have been modified
1049 */
1050 public Set<OsmPrimitive> unlinkReferencesToPrimitive(OsmPrimitive referencedPrimitive) {
1051 Set<OsmPrimitive> result = new HashSet<>();
1052 beginUpdate();
1053 try {
1054 if (referencedPrimitive instanceof Node) {
1055 result.addAll(unlinkNodeFromWays((Node) referencedPrimitive));
1056 }
1057 result.addAll(unlinkPrimitiveFromRelations(referencedPrimitive));
1058 } finally {
1059 endUpdate();
1060 }
1061 return result;
1062 }
1063
1064 /**
1065 * Replies true if there is at least one primitive in this dataset with
1066 * {@link OsmPrimitive#isModified()} == <code>true</code>.
1067 *
1068 * @return true if there is at least one primitive in this dataset with
1069 * {@link OsmPrimitive#isModified()} == <code>true</code>.
1070 */
1071 public boolean isModified() {
1072 for (OsmPrimitive p: allPrimitives) {
1073 if (p.isModified())
1074 return true;
1075 }
1076 return false;
1077 }
1078
1079 /**
1080 * Replies true if there is at least one primitive in this dataset which requires to be uploaded to server.
1081 * @return true if there is at least one primitive in this dataset which requires to be uploaded to server
1082 * @since 13161
1083 */
1084 public boolean requiresUploadToServer() {
1085 for (OsmPrimitive p: allPrimitives) {
1086 if (APIOperation.of(p) != null)
1087 return true;
1088 }
1089 return false;
1090 }
1091
1092 /**
1093 * Adds a new data set listener.
1094 * @param dsl The data set listener to add
1095 */
1096 public void addDataSetListener(DataSetListener dsl) {
1097 listeners.addIfAbsent(dsl);
1098 }
1099
1100 /**
1101 * Removes a data set listener.
1102 * @param dsl The data set listener to remove
1103 */
1104 public void removeDataSetListener(DataSetListener dsl) {
1105 listeners.remove(dsl);
1106 }
1107
1108 /**
1109 * Can be called before bigger changes on dataset. Events are disabled until {@link #endUpdate()}.
1110 * {@link DataSetListener#dataChanged(DataChangedEvent event)} event is triggered after end of changes
1111 * <br>
1112 * Typical usecase should look like this:
1113 * <pre>
1114 * ds.beginUpdate();
1115 * try {
1116 * ...
1117 * } finally {
1118 * ds.endUpdate();
1119 * }
1120 * </pre>
1121 */
1122 public void beginUpdate() {
1123 lock.writeLock().lock();
1124 updateCount++;
1125 }
1126
1127 /**
1128 * @see DataSet#beginUpdate()
1129 */
1130 public void endUpdate() {
1131 if (updateCount > 0) {
1132 updateCount--;
1133 List<AbstractDatasetChangedEvent> eventsToFire = Collections.emptyList();
1134 if (updateCount == 0) {
1135 eventsToFire = new ArrayList<>(cachedEvents);
1136 cachedEvents.clear();
1137 }
1138
1139 if (!eventsToFire.isEmpty()) {
1140 lock.readLock().lock();
1141 lock.writeLock().unlock();
1142 try {
1143 if (eventsToFire.size() < MAX_SINGLE_EVENTS) {
1144 for (AbstractDatasetChangedEvent event: eventsToFire) {
1145 fireEventToListeners(event);
1146 }
1147 } else if (eventsToFire.size() == MAX_EVENTS) {
1148 fireEventToListeners(new DataChangedEvent(this));
1149 } else {
1150 fireEventToListeners(new DataChangedEvent(this, eventsToFire));
1151 }
1152 } finally {
1153 lock.readLock().unlock();
1154 }
1155 } else {
1156 lock.writeLock().unlock();
1157 }
1158
1159 } else
1160 throw new AssertionError("endUpdate called without beginUpdate");
1161 }
1162
1163 private void fireEventToListeners(AbstractDatasetChangedEvent event) {
1164 for (DataSetListener listener: listeners) {
1165 event.fire(listener);
1166 }
1167 }
1168
1169 private void fireEvent(AbstractDatasetChangedEvent event) {
1170 if (updateCount == 0)
1171 throw new AssertionError("dataset events can be fired only when dataset is locked");
1172 if (cachedEvents.size() < MAX_EVENTS) {
1173 cachedEvents.add(event);
1174 }
1175 }
1176
1177 void firePrimitivesAdded(Collection<? extends OsmPrimitive> added, boolean wasIncomplete) {
1178 fireEvent(new PrimitivesAddedEvent(this, added, wasIncomplete));
1179 }
1180
1181 void firePrimitivesRemoved(Collection<? extends OsmPrimitive> removed, boolean wasComplete) {
1182 fireEvent(new PrimitivesRemovedEvent(this, removed, wasComplete));
1183 }
1184
1185 void fireTagsChanged(OsmPrimitive prim, Map<String, String> originalKeys) {
1186 fireEvent(new TagsChangedEvent(this, prim, originalKeys));
1187 }
1188
1189 void fireRelationMembersChanged(Relation r) {
1190 reindexRelation(r);
1191 fireEvent(new RelationMembersChangedEvent(this, r));
1192 }
1193
1194 void fireNodeMoved(Node node, LatLon newCoor, EastNorth eastNorth) {
1195 reindexNode(node, newCoor, eastNorth);
1196 fireEvent(new NodeMovedEvent(this, node));
1197 }
1198
1199 void fireWayNodesChanged(Way way) {
1200 reindexWay(way);
1201 fireEvent(new WayNodesChangedEvent(this, way));
1202 }
1203
1204 void fireChangesetIdChanged(OsmPrimitive primitive, int oldChangesetId, int newChangesetId) {
1205 fireEvent(new ChangesetIdChangedEvent(this, Collections.singletonList(primitive), oldChangesetId, newChangesetId));
1206 }
1207
1208 void firePrimitiveFlagsChanged(OsmPrimitive primitive) {
1209 fireEvent(new PrimitiveFlagsChangedEvent(this, primitive));
1210 }
1211
1212 void fireHighlightingChanged() {
1213 HighlightUpdateListener.HighlightUpdateEvent e = new HighlightUpdateListener.HighlightUpdateEvent(this);
1214 highlightUpdateListeners.fireEvent(l -> l.highlightUpdated(e));
1215 }
1216
1217 /**
1218 * Invalidates the internal cache of projected east/north coordinates.
1219 *
1220 * This method can be invoked after the globally configured projection method
1221 * changed.
1222 */
1223 public void invalidateEastNorthCache() {
1224 if (Main.getProjection() == null) return; // sanity check
1225 beginUpdate();
1226 try {
1227 for (Node n: getNodes()) {
1228 n.invalidateEastNorthCache();
1229 }
1230 } finally {
1231 endUpdate();
1232 }
1233 }
1234
1235 /**
1236 * Cleanups all deleted primitives (really delete them from the dataset).
1237 */
1238 public void cleanupDeletedPrimitives() {
1239 beginUpdate();
1240 try {
1241 Collection<OsmPrimitive> toCleanUp = getPrimitives(
1242 primitive -> primitive.isDeleted() && (!primitive.isVisible() || primitive.isNew()));
1243 if (!toCleanUp.isEmpty()) {
1244 // We unselect them in advance to not fire a selection change for every primitive
1245 clearSelection(toCleanUp.stream().map(OsmPrimitive::getPrimitiveId));
1246 for (OsmPrimitive primitive : toCleanUp) {
1247 removePrimitiveImpl(primitive);
1248 }
1249 firePrimitivesRemoved(toCleanUp, false);
1250 }
1251 } finally {
1252 endUpdate();
1253 }
1254 }
1255
1256 /**
1257 * Removes all primitives from the dataset and resets the currently selected primitives
1258 * to the empty collection. Also notifies selection change listeners if necessary.
1259 */
1260 @Override
1261 public void clear() {
1262 beginUpdate();
1263 try {
1264 clearSelection();
1265 for (OsmPrimitive primitive:allPrimitives) {
1266 primitive.setDataset(null);
1267 }
1268 super.clear();
1269 allPrimitives.clear();
1270 } finally {
1271 endUpdate();
1272 }
1273 }
1274
1275 /**
1276 * Marks all "invisible" objects as deleted. These objects should be always marked as
1277 * deleted when downloaded from the server. They can be undeleted later if necessary.
1278 *
1279 */
1280 public void deleteInvisible() {
1281 for (OsmPrimitive primitive:allPrimitives) {
1282 if (!primitive.isVisible()) {
1283 primitive.setDeleted(true);
1284 }
1285 }
1286 }
1287
1288 /**
1289 * Moves all primitives and datasources from DataSet "from" to this DataSet.
1290 * @param from The source DataSet
1291 */
1292 public void mergeFrom(DataSet from) {
1293 mergeFrom(from, null);
1294 }
1295
1296 /**
1297 * Moves all primitives and datasources from DataSet "from" to this DataSet.
1298 * @param from The source DataSet
1299 * @param progressMonitor The progress monitor
1300 */
1301 public synchronized void mergeFrom(DataSet from, ProgressMonitor progressMonitor) {
1302 if (from != null) {
1303 new DataSetMerger(this, from).merge(progressMonitor);
1304 synchronized (from) {
1305 if (!from.dataSources.isEmpty()) {
1306 if (dataSources.addAll(from.dataSources)) {
1307 cachedDataSourceArea = null;
1308 cachedDataSourceBounds = null;
1309 }
1310 from.dataSources.clear();
1311 from.cachedDataSourceArea = null;
1312 from.cachedDataSourceBounds = null;
1313 }
1314 }
1315 }
1316 }
1317
1318 /**
1319 * Replies the set of conflicts currently managed in this layer.
1320 *
1321 * @return the set of conflicts currently managed in this layer
1322 * @since 12672
1323 */
1324 public ConflictCollection getConflicts() {
1325 return conflicts;
1326 }
1327
1328 /**
1329 * Returns the name of this data set (optional).
1330 * @return the name of this data set. Can be {@code null}
1331 * @since 12718
1332 */
1333 public String getName() {
1334 return name;
1335 }
1336
1337 /**
1338 * Sets the name of this data set.
1339 * @param name the new name of this data set. Can be {@code null} to reset it
1340 * @since 12718
1341 */
1342 public void setName(String name) {
1343 this.name = name;
1344 }
1345
1346 /* --------------------------------------------------------------------------------- */
1347 /* interface ProjectionChangeListner */
1348 /* --------------------------------------------------------------------------------- */
1349 @Override
1350 public void projectionChanged(Projection oldValue, Projection newValue) {
1351 invalidateEastNorthCache();
1352 }
1353
1354 /**
1355 * Returns the data sources bounding box.
1356 * @return the data sources bounding box
1357 */
1358 public synchronized ProjectionBounds getDataSourceBoundingBox() {
1359 BoundingXYVisitor bbox = new BoundingXYVisitor();
1360 for (DataSource source : dataSources) {
1361 bbox.visit(source.bounds);
1362 }
1363 if (bbox.hasExtend()) {
1364 return bbox.getBounds();
1365 }
1366 return null;
1367 }
1368}
Note: See TracBrowser for help on using the repository browser.