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

Last change on this file since 4895 was 4895, checked in by stoecker, 12 years ago

remove deprecation

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