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

Last change on this file since 12718 was 12718, checked in by Don-vip, 3 weeks ago

see #13036 - see #15229 - see #15182 - make Commands depends only on a DataSet, not a Layer. This removes a lot of GUI dependencies

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