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

Last change on this file since 10608 was 10608, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

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