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

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

fix #10483 - drastic improvement of data consistency test performance

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