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

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

see #4043 - Have an 'upload prohibited' flag in .osm files

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