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

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

fix unit tests, PMD violation

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