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

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

javadoc fixes for jdk8 compatibility

  • Property svn:eol-style set to native
File size: 40.8 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.Iterator;
13import java.util.LinkedHashSet;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18import java.util.concurrent.CopyOnWriteArrayList;
19import java.util.concurrent.locks.Lock;
20import java.util.concurrent.locks.ReadWriteLock;
21import java.util.concurrent.locks.ReentrantReadWriteLock;
22
23import org.openstreetmap.josm.Main;
24import org.openstreetmap.josm.data.Bounds;
25import org.openstreetmap.josm.data.SelectionChangedListener;
26import org.openstreetmap.josm.data.coor.EastNorth;
27import org.openstreetmap.josm.data.coor.LatLon;
28import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
29import org.openstreetmap.josm.data.osm.event.ChangesetIdChangedEvent;
30import org.openstreetmap.josm.data.osm.event.DataChangedEvent;
31import org.openstreetmap.josm.data.osm.event.DataSetListener;
32import org.openstreetmap.josm.data.osm.event.NodeMovedEvent;
33import org.openstreetmap.josm.data.osm.event.PrimitivesAddedEvent;
34import org.openstreetmap.josm.data.osm.event.PrimitivesRemovedEvent;
35import org.openstreetmap.josm.data.osm.event.RelationMembersChangedEvent;
36import org.openstreetmap.josm.data.osm.event.TagsChangedEvent;
37import org.openstreetmap.josm.data.osm.event.WayNodesChangedEvent;
38import org.openstreetmap.josm.data.projection.Projection;
39import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
40import org.openstreetmap.josm.gui.progress.ProgressMonitor;
41import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
42import org.openstreetmap.josm.tools.FilteredCollection;
43import org.openstreetmap.josm.tools.Predicate;
44import org.openstreetmap.josm.tools.SubclassFilteredCollection;
45import org.openstreetmap.josm.tools.Utils;
46
47/**
48 * DataSet is the data behind the application. It can consists of only a few points up to the whole
49 * osm database. DataSet's can be merged together, saved, (up/down/disk)loaded etc.
50 *
51 * Note that DataSet is not an osm-primitive and so has no key association but a few members to
52 * store some information.
53 *
54 * Dataset is threadsafe - accessing Dataset simultaneously from different threads should never
55 * lead to data corruption or ConccurentModificationException. However when for example one thread
56 * removes primitive and other thread try to add another primitive reffering to the removed primitive,
57 * DataIntegrityException will occur.
58 *
59 * To prevent such situations, read/write lock is provided. While read lock is used, it's guaranteed that
60 * Dataset will not change. Sample usage:
61 * <code>
62 * ds.getReadLock().lock();
63 * try {
64 * // .. do something with dataset
65 * } finally {
66 * ds.getReadLock().unlock();
67 * }
68 * </code>
69 *
70 * Write lock should be used in case of bulk operations. In addition to ensuring that other threads can't
71 * use dataset in the middle of modifications it also stops sending of dataset events. That's good for performance
72 * reasons - GUI can be updated after all changes are done.
73 * Sample usage:
74 * <code>
75 * ds.beginUpdate()
76 * try {
77 * // .. do modifications
78 * } finally {
79 * ds.endUpdate();
80 * }
81 * </code>
82 *
83 * Note that it is not necessary to call beginUpdate/endUpdate for every dataset modification - dataset will get locked
84 * automatically.
85 *
86 * Note that locks cannot be upgraded - if one threads use read lock and and then write lock, dead lock will occur - see #5814 for
87 * sample ticket
88 *
89 * @author imi
90 */
91public final class DataSet implements Cloneable, ProjectionChangeListener {
92
93 /**
94 * Maximum number of events that can be fired between beginUpdate/endUpdate to be send as single events (ie without DatasetChangedEvent)
95 */
96 private static final int MAX_SINGLE_EVENTS = 30;
97
98 /**
99 * Maximum number of events to kept between beginUpdate/endUpdate. When more events are created, that simple DatasetChangedEvent is sent)
100 */
101 private static final int MAX_EVENTS = 1000;
102
103 private Storage<OsmPrimitive> allPrimitives = new Storage<OsmPrimitive>(new Storage.PrimitiveIdHash(), true);
104 private Map<PrimitiveId, OsmPrimitive> primitivesMap = allPrimitives.foreignKey(new Storage.PrimitiveIdHash());
105 private CopyOnWriteArrayList<DataSetListener> listeners = new CopyOnWriteArrayList<DataSetListener>();
106
107 // provide means to highlight map elements that are not osm primitives
108 private Collection<WaySegment> highlightedVirtualNodes = new LinkedList<WaySegment>();
109 private Collection<WaySegment> highlightedWaySegments = new LinkedList<WaySegment>();
110
111 // Number of open calls to beginUpdate
112 private int updateCount;
113 // Events that occurred while dataset was locked but should be fired after write lock is released
114 private final List<AbstractDatasetChangedEvent> cachedEvents = new ArrayList<AbstractDatasetChangedEvent>();
115
116 private int highlightUpdateCount;
117
118 private boolean uploadDiscouraged = false;
119
120 private final ReadWriteLock lock = new ReentrantReadWriteLock();
121 private final Object selectionLock = new Object();
122
123 public DataSet() {
124 /*
125 * Transparently register as projection change lister. No need to explicitly remove the
126 * the listener, projection change listeners are managed as WeakReferences.
127 */
128 Main.addProjectionChangeListener(this);
129 }
130
131 public Lock getReadLock() {
132 return lock.readLock();
133 }
134
135 /**
136 * This method can be used to detect changes in highlight state of primitives. If highlighting was changed
137 * then the method will return different number.
138 * @return the current highlight counter
139 */
140 public int getHighlightUpdateCount() {
141 return highlightUpdateCount;
142 }
143
144 /**
145 * History of selections - shared by plugins and SelectionListDialog
146 */
147 private final LinkedList<Collection<? extends OsmPrimitive>> selectionHistory = new LinkedList<Collection<? extends OsmPrimitive>>();
148
149 /**
150 * Replies the history of JOSM selections
151 *
152 * @return list of history entries
153 */
154 public LinkedList<Collection<? extends OsmPrimitive>> getSelectionHistory() {
155 return selectionHistory;
156 }
157
158 /**
159 * Clears selection history list
160 */
161 public void clearSelectionHistory() {
162 selectionHistory.clear();
163 }
164
165 /**
166 * Maintain a list of used tags for autocompletion
167 */
168 private AutoCompletionManager autocomplete;
169
170 public AutoCompletionManager getAutoCompletionManager() {
171 if (autocomplete == null) {
172 autocomplete = new AutoCompletionManager(this);
173 addDataSetListener(autocomplete);
174 }
175 return autocomplete;
176 }
177
178 /**
179 * The API version that created this data set, if any.
180 */
181 private String version;
182
183 /**
184 * Replies the API version this dataset was created from. May be null.
185 *
186 * @return the API version this dataset was created from. May be null.
187 */
188 public String getVersion() {
189 return version;
190 }
191
192 /**
193 * Sets the API version this dataset was created from.
194 *
195 * @param version the API version, i.e. "0.5" or "0.6"
196 */
197 public void setVersion(String version) {
198 this.version = version;
199 }
200
201 public final boolean isUploadDiscouraged() {
202 return uploadDiscouraged;
203 }
204
205 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
206 this.uploadDiscouraged = uploadDiscouraged;
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 {@link #nodes}, {@link #ways}, or
371 * {@link #relations}. References from other primitives to this
372 * primitive are left unchanged.
373 *
374 * @param primitiveId the id of 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 {@link SelectionChangedListener} about the current selection in
425 * this dataset.
426 *
427 */
428 public void fireSelectionChanged(){
429 Collection<? extends OsmPrimitive> currentSelection = getAllSelected();
430 for (SelectionChangedListener l : selListeners) {
431 l.selectionChanged(currentSelection);
432 }
433 }
434
435 private Set<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, except deleted ones. May be empty, but not null.
471 *
472 * @return unmodifiable collection of primitives
473 */
474 public Collection<OsmPrimitive> getSelected() {
475 return new SubclassFilteredCollection<OsmPrimitive, OsmPrimitive>(getAllSelected(), OsmPrimitive.nonDeletedPredicate);
476 }
477
478 /**
479 * Replies an unmodifiable collection of primitives currently selected
480 * in this dataset, including deleted ones. May be empty, but not null.
481 *
482 * @return unmodifiable collection of primitives
483 */
484 public Collection<OsmPrimitive> getAllSelected() {
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 waySegments Collection of way segments
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 waySegments Collection of way segments
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 {@link 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 LinkedHashSet<OsmPrimitive> oldSelection = new LinkedHashSet<OsmPrimitive>(selectedPrimitives);
594 selectedPrimitives = new LinkedHashSet<OsmPrimitive>();
595 addSelected(selection, false);
596 changed = !oldSelection.equals(selectedPrimitives);
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 {@link 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 {@link 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 {@link 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 osm The collection of ids 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 &lt; 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 * Show message and stack trace in log in case primitive is not found
795 * @param primitiveId
796 * @return Primitive by id.
797 */
798 private OsmPrimitive getPrimitiveByIdChecked(PrimitiveId primitiveId) {
799 OsmPrimitive result = getPrimitiveById(primitiveId);
800 if (result == null) {
801 Main.warn(tr("JOSM expected to find primitive [{0} {1}] in dataset but it is not there. Please report this "
802 + "at http://josm.openstreetmap.de/. This is not a critical error, it should be safe to continue in your work.",
803 primitiveId.getType(), Long.toString(primitiveId.getUniqueId())));
804 Main.error(new Exception());
805 }
806
807 return result;
808 }
809
810 private void deleteWay(Way way) {
811 way.setNodes(null);
812 way.setDeleted(true);
813 }
814
815 /**
816 * removes all references from ways in this dataset to a particular node
817 *
818 * @param node the node
819 */
820 public void unlinkNodeFromWays(Node node) {
821 beginUpdate();
822 try {
823 for (Way way: ways) {
824 List<Node> wayNodes = way.getNodes();
825 if (wayNodes.remove(node)) {
826 if (wayNodes.size() < 2) {
827 deleteWay(way);
828 } else {
829 way.setNodes(wayNodes);
830 }
831 }
832 }
833 } finally {
834 endUpdate();
835 }
836 }
837
838 /**
839 * removes all references from relations in this dataset to this primitive
840 *
841 * @param primitive the primitive
842 */
843 public void unlinkPrimitiveFromRelations(OsmPrimitive primitive) {
844 beginUpdate();
845 try {
846 for (Relation relation : relations) {
847 List<RelationMember> members = relation.getMembers();
848
849 Iterator<RelationMember> it = members.iterator();
850 boolean removed = false;
851 while(it.hasNext()) {
852 RelationMember member = it.next();
853 if (member.getMember().equals(primitive)) {
854 it.remove();
855 removed = true;
856 }
857 }
858
859 if (removed) {
860 relation.setMembers(members);
861 }
862 }
863 } finally {
864 endUpdate();
865 }
866 }
867
868 /**
869 * removes all references from other primitives to the
870 * referenced primitive
871 *
872 * @param referencedPrimitive the referenced primitive
873 */
874 public void unlinkReferencesToPrimitive(OsmPrimitive referencedPrimitive) {
875 beginUpdate();
876 try {
877 if (referencedPrimitive instanceof Node) {
878 unlinkNodeFromWays((Node)referencedPrimitive);
879 unlinkPrimitiveFromRelations(referencedPrimitive);
880 } else {
881 unlinkPrimitiveFromRelations(referencedPrimitive);
882 }
883 } finally {
884 endUpdate();
885 }
886 }
887
888 /**
889 * Replies true if there is at least one primitive in this dataset with
890 * {@link OsmPrimitive#isModified()} == <code>true</code>.
891 *
892 * @return true if there is at least one primitive in this dataset with
893 * {@link OsmPrimitive#isModified()} == <code>true</code>.
894 */
895 public boolean isModified() {
896 for (OsmPrimitive p: allPrimitives) {
897 if (p.isModified())
898 return true;
899 }
900 return false;
901 }
902
903 private void reindexNode(Node node, LatLon newCoor, EastNorth eastNorth) {
904 if (!nodes.remove(node))
905 throw new RuntimeException("Reindexing node failed to remove");
906 node.setCoorInternal(newCoor, eastNorth);
907 if (!nodes.add(node))
908 throw new RuntimeException("Reindexing node failed to add");
909 for (OsmPrimitive primitive: node.getReferrers()) {
910 if (primitive instanceof Way) {
911 reindexWay((Way)primitive);
912 } else {
913 reindexRelation((Relation) primitive);
914 }
915 }
916 }
917
918 private void reindexWay(Way way) {
919 BBox before = way.getBBox();
920 if (!ways.remove(way))
921 throw new RuntimeException("Reindexing way failed to remove");
922 way.updatePosition();
923 if (!ways.add(way))
924 throw new RuntimeException("Reindexing way failed to add");
925 if (!way.getBBox().equals(before)) {
926 for (OsmPrimitive primitive: way.getReferrers()) {
927 reindexRelation((Relation)primitive);
928 }
929 }
930 }
931
932 private void reindexRelation(Relation relation) {
933 BBox before = relation.getBBox();
934 relation.updatePosition();
935 if (!before.equals(relation.getBBox())) {
936 for (OsmPrimitive primitive: relation.getReferrers()) {
937 reindexRelation((Relation) primitive);
938 }
939 }
940 }
941
942 public void addDataSetListener(DataSetListener dsl) {
943 listeners.addIfAbsent(dsl);
944 }
945
946 public void removeDataSetListener(DataSetListener dsl) {
947 listeners.remove(dsl);
948 }
949
950 /**
951 * Can be called before bigger changes on dataset. Events are disabled until {@link #endUpdate()}.
952 * {@link DataSetListener#dataChanged(DataChangedEvent event)} event is triggered after end of changes
953 * <br>
954 * Typical usecase should look like this:
955 * <pre>
956 * ds.beginUpdate();
957 * try {
958 * ...
959 * } finally {
960 * ds.endUpdate();
961 * }
962 * </pre>
963 */
964 public void beginUpdate() {
965 lock.writeLock().lock();
966 updateCount++;
967 }
968
969 /**
970 * @see DataSet#beginUpdate()
971 */
972 public void endUpdate() {
973 if (updateCount > 0) {
974 updateCount--;
975 if (updateCount == 0) {
976 List<AbstractDatasetChangedEvent> eventsCopy = new ArrayList<AbstractDatasetChangedEvent>(cachedEvents);
977 cachedEvents.clear();
978 lock.writeLock().unlock();
979
980 if (!eventsCopy.isEmpty()) {
981 lock.readLock().lock();
982 try {
983 if (eventsCopy.size() < MAX_SINGLE_EVENTS) {
984 for (AbstractDatasetChangedEvent event: eventsCopy) {
985 fireEventToListeners(event);
986 }
987 } else if (eventsCopy.size() == MAX_EVENTS) {
988 fireEventToListeners(new DataChangedEvent(this));
989 } else {
990 fireEventToListeners(new DataChangedEvent(this, eventsCopy));
991 }
992 } finally {
993 lock.readLock().unlock();
994 }
995 }
996 } else {
997 lock.writeLock().unlock();
998 }
999
1000 } else
1001 throw new AssertionError("endUpdate called without beginUpdate");
1002 }
1003
1004 private void fireEventToListeners(AbstractDatasetChangedEvent event) {
1005 for (DataSetListener listener: listeners) {
1006 event.fire(listener);
1007 }
1008 }
1009
1010 private void fireEvent(AbstractDatasetChangedEvent event) {
1011 if (updateCount == 0)
1012 throw new AssertionError("dataset events can be fired only when dataset is locked");
1013 if (cachedEvents.size() < MAX_EVENTS) {
1014 cachedEvents.add(event);
1015 }
1016 }
1017
1018 void firePrimitivesAdded(Collection<? extends OsmPrimitive> added, boolean wasIncomplete) {
1019 fireEvent(new PrimitivesAddedEvent(this, added, wasIncomplete));
1020 }
1021
1022 void firePrimitivesRemoved(Collection<? extends OsmPrimitive> removed, boolean wasComplete) {
1023 fireEvent(new PrimitivesRemovedEvent(this, removed, wasComplete));
1024 }
1025
1026 void fireTagsChanged(OsmPrimitive prim, Map<String, String> originalKeys) {
1027 fireEvent(new TagsChangedEvent(this, prim, originalKeys));
1028 }
1029
1030 void fireRelationMembersChanged(Relation r) {
1031 reindexRelation(r);
1032 fireEvent(new RelationMembersChangedEvent(this, r));
1033 }
1034
1035 void fireNodeMoved(Node node, LatLon newCoor, EastNorth eastNorth) {
1036 reindexNode(node, newCoor, eastNorth);
1037 fireEvent(new NodeMovedEvent(this, node));
1038 }
1039
1040 void fireWayNodesChanged(Way way) {
1041 reindexWay(way);
1042 fireEvent(new WayNodesChangedEvent(this, way));
1043 }
1044
1045 void fireChangesetIdChanged(OsmPrimitive primitive, int oldChangesetId, int newChangesetId) {
1046 fireEvent(new ChangesetIdChangedEvent(this, Collections.singletonList(primitive), oldChangesetId, newChangesetId));
1047 }
1048
1049 void fireHighlightingChanged(OsmPrimitive primitive) {
1050 highlightUpdateCount++;
1051 }
1052
1053 /**
1054 * Invalidates the internal cache of projected east/north coordinates.
1055 *
1056 * This method can be invoked after the globally configured projection method
1057 * changed.
1058 */
1059 public void invalidateEastNorthCache() {
1060 if (Main.getProjection() == null) return; // sanity check
1061 try {
1062 beginUpdate();
1063 for (Node n: Utils.filteredCollection(allPrimitives, Node.class)) {
1064 n.invalidateEastNorthCache();
1065 }
1066 } finally {
1067 endUpdate();
1068 }
1069 }
1070
1071 public void cleanupDeletedPrimitives() {
1072 beginUpdate();
1073 try {
1074 if (cleanupDeleted(nodes.iterator())
1075 | cleanupDeleted(ways.iterator())
1076 | cleanupDeleted(relations.iterator())) {
1077 fireSelectionChanged();
1078 }
1079 } finally {
1080 endUpdate();
1081 }
1082 }
1083
1084 private boolean cleanupDeleted(Iterator<? extends OsmPrimitive> it) {
1085 boolean changed = false;
1086 synchronized (selectionLock) {
1087 while (it.hasNext()) {
1088 OsmPrimitive primitive = it.next();
1089 if (primitive.isDeleted() && (!primitive.isVisible() || primitive.isNew())) {
1090 selectedPrimitives.remove(primitive);
1091 selectionSnapshot = null;
1092 allPrimitives.remove(primitive);
1093 primitive.setDataset(null);
1094 changed = true;
1095 it.remove();
1096 }
1097 }
1098 if (changed) {
1099 selectionSnapshot = null;
1100 }
1101 }
1102 return changed;
1103 }
1104
1105 /**
1106 * Removes all primitives from the dataset and resets the currently selected primitives
1107 * to the empty collection. Also notifies selection change listeners if necessary.
1108 *
1109 */
1110 public void clear() {
1111 beginUpdate();
1112 try {
1113 clearSelection();
1114 for (OsmPrimitive primitive:allPrimitives) {
1115 primitive.setDataset(null);
1116 }
1117 nodes.clear();
1118 ways.clear();
1119 relations.clear();
1120 allPrimitives.clear();
1121 } finally {
1122 endUpdate();
1123 }
1124 }
1125
1126 /**
1127 * Marks all "invisible" objects as deleted. These objects should be always marked as
1128 * deleted when downloaded from the server. They can be undeleted later if necessary.
1129 *
1130 */
1131 public void deleteInvisible() {
1132 for (OsmPrimitive primitive:allPrimitives) {
1133 if (!primitive.isVisible()) {
1134 primitive.setDeleted(true);
1135 }
1136 }
1137 }
1138
1139 /**
1140 * <p>Replies the list of data source bounds.</p>
1141 *
1142 * <p>Dataset maintains a list of data sources which have been merged into the
1143 * data set. Each of these sources can optionally declare a bounding box of the
1144 * data it supplied to the dataset.</p>
1145 *
1146 * <p>This method replies the list of defined (non {@code null}) bounding boxes.</p>
1147 *
1148 * @return the list of data source bounds. An empty list, if no non-null data source
1149 * bounds are defined.
1150 */
1151 public List<Bounds> getDataSourceBounds() {
1152 List<Bounds> ret = new ArrayList<Bounds>(dataSources.size());
1153 for (DataSource ds : dataSources) {
1154 if (ds.bounds != null) {
1155 ret.add(ds.bounds);
1156 }
1157 }
1158 return ret;
1159 }
1160
1161 /**
1162 * Moves all primitives and datasources from DataSet "from" to this DataSet
1163 * @param from The source DataSet
1164 */
1165 public void mergeFrom(DataSet from) {
1166 mergeFrom(from, null);
1167 }
1168
1169 /**
1170 * Moves all primitives and datasources from DataSet "from" to this DataSet
1171 * @param from The source DataSet
1172 */
1173 public void mergeFrom(DataSet from, ProgressMonitor progressMonitor) {
1174 if (from != null) {
1175 new DataSetMerger(this, from).merge(progressMonitor);
1176 dataSources.addAll(from.dataSources);
1177 from.dataSources.clear();
1178 }
1179 }
1180
1181 /* --------------------------------------------------------------------------------- */
1182 /* interface ProjectionChangeListner */
1183 /* --------------------------------------------------------------------------------- */
1184 @Override
1185 public void projectionChanged(Projection oldValue, Projection newValue) {
1186 invalidateEastNorthCache();
1187 }
1188}
Note: See TracBrowser for help on using the repository browser.