source: josm/trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitive.java@ 4612

Last change on this file since 4612 was 4612, checked in by bastiK, 12 years ago

see #7027 - internal structures for preferences (expect some problems next few days)

  • Property svn:eol-style set to native
File size: 37.6 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.text.MessageFormat;
7import java.util.ArrayList;
8import java.util.Arrays;
9import java.util.Collection;
10import java.util.Collections;
11import java.util.Date;
12import java.util.HashSet;
13import java.util.LinkedHashSet;
14import java.util.LinkedList;
15import java.util.List;
16import java.util.Map;
17import java.util.Set;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.actions.search.SearchCompiler;
21import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
22import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
23import org.openstreetmap.josm.data.osm.visitor.Visitor;
24import org.openstreetmap.josm.gui.mappaint.StyleCache;
25import org.openstreetmap.josm.tools.CheckParameterUtil;
26import org.openstreetmap.josm.tools.Predicate;
27import org.openstreetmap.josm.tools.template_engine.TemplateEngineDataProvider;
28
29/**
30 * An OSM primitive can be associated with a key/value pair. It can be created, deleted
31 * and updated within the OSM-Server.
32 *
33 * Although OsmPrimitive is designed as a base class, it is not to be meant to subclass
34 * it by any other than from the package {@link org.openstreetmap.josm.data.osm}. The available primitives are a fixed set that are given
35 * by the server environment and not an extendible data stuff.
36 *
37 * @author imi
38 */
39abstract public class OsmPrimitive extends AbstractPrimitive implements Comparable<OsmPrimitive>, TemplateEngineDataProvider {
40 private static final String SPECIAL_VALUE_ID = "id";
41 private static final String SPECIAL_VALUE_LOCAL_NAME = "localname";
42
43
44 /**
45 * An object can be disabled by the filter mechanism.
46 * Then it will show in a shade of gray on the map or it is completely
47 * hidden from the view.
48 * Disabled objects usually cannot be selected or modified
49 * while the filter is active.
50 */
51 protected static final int FLAG_DISABLED = 1 << 4;
52
53 /**
54 * This flag is only relevant if an object is disabled by the
55 * filter mechanism (i.e. FLAG_DISABLED is set).
56 * Then it indicates, whether it is completely hidden or
57 * just shown in gray color.
58 *
59 * When the primitive is not disabled, this flag should be
60 * unset as well (for efficient access).
61 */
62 protected static final int FLAG_HIDE_IF_DISABLED = 1 << 5;
63
64 /**
65 * This flag is set if the primitive is a way and
66 * according to the tags, the direction of the way is important.
67 * (e.g. one way street.)
68 */
69 protected static final int FLAG_HAS_DIRECTIONS = 1 << 6;
70
71 /**
72 * If the primitive is tagged.
73 * Some trivial tags like source=* are ignored here.
74 */
75 protected static final int FLAG_TAGGED = 1 << 7;
76
77 /**
78 * This flag is only relevant if FLAG_HAS_DIRECTIONS is set.
79 * It shows, that direction of the arrows should be reversed.
80 * (E.g. oneway=-1.)
81 */
82 protected static final int FLAG_DIRECTION_REVERSED = 1 << 8;
83
84 /**
85 * When hovering over ways and nodes in add mode, the
86 * "target" objects are visually highlighted. This flag indicates
87 * that the primitive is currently highlighted.
88 */
89 protected static final int FLAG_HIGHLIGHTED = 1 << 9;
90
91 /**
92 * Replies the sub-collection of {@see OsmPrimitive}s of type <code>type</code> present in
93 * another collection of {@see OsmPrimitive}s. The result collection is a list.
94 *
95 * If <code>list</code> is null, replies an empty list.
96 *
97 * @param <T>
98 * @param list the original list
99 * @param type the type to filter for
100 * @return the sub-list of OSM primitives of type <code>type</code>
101 */
102 static public <T extends OsmPrimitive> List<T> getFilteredList(Collection<OsmPrimitive> list, Class<T> type) {
103 if (list == null) return Collections.emptyList();
104 List<T> ret = new LinkedList<T>();
105 for(OsmPrimitive p: list) {
106 if (type.isInstance(p)) {
107 ret.add(type.cast(p));
108 }
109 }
110 return ret;
111 }
112
113 /**
114 * Replies the sub-collection of {@see OsmPrimitive}s of type <code>type</code> present in
115 * another collection of {@see OsmPrimitive}s. The result collection is a set.
116 *
117 * If <code>list</code> is null, replies an empty set.
118 *
119 * @param <T>
120 * @param list the original collection
121 * @param type the type to filter for
122 * @return the sub-set of OSM primitives of type <code>type</code>
123 */
124 static public <T extends OsmPrimitive> LinkedHashSet<T> getFilteredSet(Collection<OsmPrimitive> set, Class<T> type) {
125 LinkedHashSet<T> ret = new LinkedHashSet<T>();
126 if (set != null) {
127 for(OsmPrimitive p: set) {
128 if (type.isInstance(p)) {
129 ret.add(type.cast(p));
130 }
131 }
132 }
133 return ret;
134 }
135
136 /**
137 * Replies the collection of referring primitives for the primitives in <code>primitives</code>.
138 *
139 * @param primitives the collection of primitives.
140 * @return the collection of referring primitives for the primitives in <code>primitives</code>;
141 * empty set if primitives is null or if there are no referring primitives
142 */
143 static public Set<OsmPrimitive> getReferrer(Collection<? extends OsmPrimitive> primitives) {
144 HashSet<OsmPrimitive> ret = new HashSet<OsmPrimitive>();
145 if (primitives == null || primitives.isEmpty()) return ret;
146 for (OsmPrimitive p: primitives) {
147 ret.addAll(p.getReferrers());
148 }
149 return ret;
150 }
151
152 /**
153 * Some predicates, that describe conditions on primitives.
154 */
155 public static final Predicate<OsmPrimitive> isUsablePredicate = new Predicate<OsmPrimitive>() {
156 @Override public boolean evaluate(OsmPrimitive primitive) {
157 return primitive.isUsable();
158 }
159 };
160
161 public static final Predicate<OsmPrimitive> isSelectablePredicate = new Predicate<OsmPrimitive>() {
162 @Override public boolean evaluate(OsmPrimitive primitive) {
163 return primitive.isSelectable();
164 }
165 };
166
167 public static final Predicate<OsmPrimitive> nonDeletedPredicate = new Predicate<OsmPrimitive>() {
168 @Override public boolean evaluate(OsmPrimitive primitive) {
169 return !primitive.isDeleted();
170 }
171 };
172
173 public static final Predicate<OsmPrimitive> nonDeletedCompletePredicate = new Predicate<OsmPrimitive>() {
174 @Override public boolean evaluate(OsmPrimitive primitive) {
175 return !primitive.isDeleted() && !primitive.isIncomplete();
176 }
177 };
178
179 public static final Predicate<OsmPrimitive> nonDeletedPhysicalPredicate = new Predicate<OsmPrimitive>() {
180 @Override public boolean evaluate(OsmPrimitive primitive) {
181 return !primitive.isDeleted() && !primitive.isIncomplete() && !(primitive instanceof Relation);
182 }
183 };
184
185 public static final Predicate<OsmPrimitive> modifiedPredicate = new Predicate<OsmPrimitive>() {
186 @Override public boolean evaluate(OsmPrimitive primitive) {
187 return primitive.isModified();
188 }
189 };
190
191 public static final Predicate<OsmPrimitive> nodePredicate = new Predicate<OsmPrimitive>() {
192 @Override public boolean evaluate(OsmPrimitive primitive) {
193 return primitive.getClass() == Node.class;
194 }
195 };
196
197 public static final Predicate<OsmPrimitive> wayPredicate = new Predicate<OsmPrimitive>() {
198 @Override public boolean evaluate(OsmPrimitive primitive) {
199 return primitive.getClass() == Way.class;
200 }
201 };
202
203 public static final Predicate<OsmPrimitive> relationPredicate = new Predicate<OsmPrimitive>() {
204 @Override public boolean evaluate(OsmPrimitive primitive) {
205 return primitive.getClass() == Relation.class;
206 }
207 };
208
209 public static final Predicate<OsmPrimitive> allPredicate = new Predicate<OsmPrimitive>() {
210 @Override public boolean evaluate(OsmPrimitive primitive) {
211 return true;
212 }
213 };
214
215 /**
216 * Creates a new primitive for the given id.
217 *
218 * If allowNegativeId is set, provided id can be < 0 and will be set to primitive without any processing.
219 * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
220 * positive number.
221 *
222 * @param id the id
223 * @param allowNegativeId
224 * @throws IllegalArgumentException thrown if id < 0 and allowNegativeId is false
225 */
226 protected OsmPrimitive(long id, boolean allowNegativeId) throws IllegalArgumentException {
227 if (allowNegativeId) {
228 this.id = id;
229 } else {
230 if (id < 0)
231 throw new IllegalArgumentException(MessageFormat.format("Expected ID >= 0. Got {0}.", id));
232 else if (id == 0) {
233 this.id = generateUniqueId();
234 } else {
235 this.id = id;
236 }
237
238 }
239 this.version = 0;
240 this.setIncomplete(id > 0);
241 }
242
243 /**
244 * Creates a new primitive for the given id and version.
245 *
246 * If allowNegativeId is set, provided id can be < 0 and will be set to primitive without any processing.
247 * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
248 * positive number.
249 *
250 * If id is not > 0 version is ignored and set to 0.
251 *
252 * @param id
253 * @param version
254 * @param allowNegativeId
255 * @throws IllegalArgumentException thrown if id < 0 and allowNegativeId is false
256 */
257 protected OsmPrimitive(long id, int version, boolean allowNegativeId) throws IllegalArgumentException {
258 this(id, allowNegativeId);
259 this.version = (id > 0 ? version : 0);
260 setIncomplete(id > 0 && version == 0);
261 }
262
263
264 /*----------
265 * MAPPAINT
266 *--------*/
267 public StyleCache mappaintStyle = null;
268 public int mappaintCacheIdx;
269
270 /* This should not be called from outside. Fixing the UI to add relevant
271 get/set functions calling this implicitely is preferred, so we can have
272 transparent cache handling in the future. */
273 public void clearCachedStyle()
274 {
275 mappaintStyle = null;
276 }
277 /* end of mappaint data */
278
279 /*---------
280 * DATASET
281 *---------*/
282
283 /** the parent dataset */
284 private DataSet dataSet;
285
286 /**
287 * This method should never ever by called from somewhere else than Dataset.addPrimitive or removePrimitive methods
288 * @param dataSet
289 */
290 void setDataset(DataSet dataSet) {
291 if (this.dataSet != null && dataSet != null && this.dataSet != dataSet)
292 throw new DataIntegrityProblemException("Primitive cannot be included in more than one Dataset");
293 this.dataSet = dataSet;
294 }
295
296 /**
297 *
298 * @return DataSet this primitive is part of.
299 */
300 public DataSet getDataSet() {
301 return dataSet;
302 }
303
304 /**
305 * Throws exception if primitive is not part of the dataset
306 */
307 public void checkDataset() {
308 if (dataSet == null)
309 throw new DataIntegrityProblemException("Primitive must be part of the dataset: " + toString());
310 }
311
312 protected boolean writeLock() {
313 if (dataSet != null) {
314 dataSet.beginUpdate();
315 return true;
316 } else
317 return false;
318 }
319
320 protected void writeUnlock(boolean locked) {
321 if (locked) {
322 // It shouldn't be possible for dataset to become null because method calling setDataset would need write lock which is owned by this thread
323 dataSet.endUpdate();
324 }
325 }
326
327 /**
328 * Sets the id and the version of this primitive if it is known to the OSM API.
329 *
330 * Since we know the id and its version it can't be incomplete anymore. incomplete
331 * is set to false.
332 *
333 * @param id the id. > 0 required
334 * @param version the version > 0 required
335 * @throws IllegalArgumentException thrown if id <= 0
336 * @throws IllegalArgumentException thrown if version <= 0
337 * @throws DataIntegrityProblemException If id is changed and primitive was already added to the dataset
338 */
339 @Override
340 public void setOsmId(long id, int version) {
341 boolean locked = writeLock();
342 try {
343 if (id <= 0)
344 throw new IllegalArgumentException(tr("ID > 0 expected. Got {0}.", id));
345 if (version <= 0)
346 throw new IllegalArgumentException(tr("Version > 0 expected. Got {0}.", version));
347 if (dataSet != null && id != this.id) {
348 DataSet datasetCopy = dataSet;
349 // Reindex primitive
350 datasetCopy.removePrimitive(this);
351 this.id = id;
352 datasetCopy.addPrimitive(this);
353 }
354 super.setOsmId(id, version);
355 } finally {
356 writeUnlock(locked);
357 }
358 }
359
360 /**
361 * Clears the id and version known to the OSM API. The id and the version is set to 0.
362 * incomplete is set to false. It's preferred to use copy constructor with clearId set to true instead
363 * of calling this method.
364 *
365 * <strong>Caution</strong>: Do not use this method on primitives which are already added to a {@see DataSet}.
366 *
367 * @throws DataIntegrityProblemException If primitive was already added to the dataset
368 */
369 @Override
370 public void clearOsmId() {
371 if (dataSet != null)
372 throw new DataIntegrityProblemException("Method cannot be called after primitive was added to the dataset");
373 super.clearOsmId();
374 }
375
376 @Override
377 public void setUser(User user) {
378 boolean locked = writeLock();
379 try {
380 super.setUser(user);
381 } finally {
382 writeUnlock(locked);
383 }
384 }
385
386 @Override
387 public void setChangesetId(int changesetId) throws IllegalStateException, IllegalArgumentException {
388 boolean locked = writeLock();
389 try {
390 int old = this.changesetId;
391 super.setChangesetId(changesetId);
392 if (dataSet != null) {
393 dataSet.fireChangesetIdChanged(this, old, changesetId);
394 }
395 } finally {
396 writeUnlock(locked);
397 }
398 }
399
400 @Override
401 public void setTimestamp(Date timestamp) {
402 boolean locked = writeLock();
403 try {
404 super.setTimestamp(timestamp);
405 } finally {
406 writeUnlock(locked);
407 }
408 }
409
410
411 /* -------
412 /* FLAGS
413 /* ------*/
414
415 private void updateFlagsNoLock (int flag, boolean value) {
416 super.updateFlags(flag, value);
417 }
418
419 @Override
420 protected final void updateFlags(int flag, boolean value) {
421 boolean locked = writeLock();
422 try {
423 updateFlagsNoLock(flag, value);
424 } finally {
425 writeUnlock(locked);
426 }
427 }
428
429 /**
430 * Make the primitive disabled (e.g. if a filter applies).
431 * To enable the primitive again, use unsetDisabledState.
432 * @param hide if the primitive should be completely hidden from view or
433 * just shown in gray color.
434 */
435 public boolean setDisabledState(boolean hide) {
436 boolean locked = writeLock();
437 try {
438 int oldFlags = flags;
439 updateFlagsNoLock(FLAG_DISABLED, true);
440 updateFlagsNoLock(FLAG_HIDE_IF_DISABLED, hide);
441 return oldFlags != flags;
442 } finally {
443 writeUnlock(locked);
444 }
445 }
446
447 /**
448 * Remove the disabled flag from the primitive.
449 * Afterwards, the primitive is displayed normally and can be selected
450 * again.
451 */
452 public boolean unsetDisabledState() {
453 boolean locked = writeLock();
454 try {
455 int oldFlags = flags;
456 updateFlagsNoLock(FLAG_DISABLED + FLAG_HIDE_IF_DISABLED, false);
457 return oldFlags != flags;
458 } finally {
459 writeUnlock(locked);
460 }
461 }
462
463 /**
464 * Replies true, if this primitive is disabled. (E.g. a filter
465 * applies)
466 */
467 public boolean isDisabled() {
468 return (flags & FLAG_DISABLED) != 0;
469 }
470
471 /**
472 * Replies true, if this primitive is disabled and marked as
473 * completely hidden on the map.
474 */
475 public boolean isDisabledAndHidden() {
476 return (((flags & FLAG_DISABLED) != 0) && ((flags & FLAG_HIDE_IF_DISABLED) != 0));
477 }
478
479 @Deprecated
480 public boolean isFiltered() {
481 return isDisabledAndHidden();
482 }
483
484
485 public boolean isSelectable() {
486 return (flags & (FLAG_DELETED + FLAG_INCOMPLETE + FLAG_DISABLED + FLAG_HIDE_IF_DISABLED)) == 0;
487 }
488
489 public boolean isDrawable() {
490 return (flags & (FLAG_DELETED + FLAG_INCOMPLETE + FLAG_HIDE_IF_DISABLED)) == 0;
491 }
492
493 @Override
494 public void setVisible(boolean visible) throws IllegalStateException {
495 boolean locked = writeLock();
496 try {
497 super.setVisible(visible);
498 } finally {
499 writeUnlock(locked);
500 }
501 }
502
503 @Override
504 public void setDeleted(boolean deleted) {
505 boolean locked = writeLock();
506 try {
507 super.setDeleted(deleted);
508 if (dataSet != null) {
509 if (deleted) {
510 dataSet.firePrimitivesRemoved(Collections.singleton(this), false);
511 } else {
512 dataSet.firePrimitivesAdded(Collections.singleton(this), false);
513 }
514 }
515 } finally {
516 writeUnlock(locked);
517 }
518 }
519
520 @Override
521 protected void setIncomplete(boolean incomplete) {
522 boolean locked = writeLock();
523 try {
524 if (dataSet != null && incomplete != this.isIncomplete()) {
525 if (incomplete) {
526 dataSet.firePrimitivesRemoved(Collections.singletonList(this), true);
527 } else {
528 dataSet.firePrimitivesAdded(Collections.singletonList(this), true);
529 }
530 }
531 super.setIncomplete(incomplete);
532 } finally {
533 writeUnlock(locked);
534 }
535 }
536
537 public boolean isSelected() {
538 return dataSet != null && dataSet.isSelected(this);
539 }
540
541 public boolean isMemberOfSelected() {
542 if (referrers == null)
543 return false;
544 if (referrers instanceof OsmPrimitive)
545 return referrers instanceof Relation && ((OsmPrimitive) referrers).isSelected();
546 for (OsmPrimitive ref : (OsmPrimitive[]) referrers) {
547 if (ref instanceof Relation && ref.isSelected())
548 return true;
549 }
550 return false;
551 }
552
553 public void setHighlighted(boolean highlighted) {
554 if (isHighlighted() != highlighted) {
555 updateFlags(FLAG_HIGHLIGHTED, highlighted);
556 if (dataSet != null) {
557 dataSet.fireHighlightingChanged(this);
558 }
559 }
560 }
561
562 public boolean isHighlighted() {
563 return (flags & FLAG_HIGHLIGHTED) != 0;
564 }
565
566 /*----------------------------------
567 * UNINTERESTING AND DIRECTION KEYS
568 *----------------------------------*/
569
570
571 private static volatile Collection<String> uninteresting = null;
572 /**
573 * Contains a list of "uninteresting" keys that do not make an object
574 * "tagged". Entries that end with ':' are causing a whole namespace to be considered
575 * "uninteresting". Only the first level namespace is considered.
576 * Initialized by isUninterestingKey()
577 */
578 public static Collection<String> getUninterestingKeys() {
579 if (uninteresting == null) {
580 uninteresting = Main.pref.getCollection("tags.uninteresting",
581 Arrays.asList(new String[]{"source", "source_ref", "source:", "note", "comment",
582 "converted_by", "created_by", "watch", "watch:", "fixme", "FIXME",
583 "description", "attribution"}));
584 }
585 return uninteresting;
586 }
587
588 /**
589 * Returns true if key is considered "uninteresting".
590 */
591 public static boolean isUninterestingKey(String key) {
592 getUninterestingKeys();
593 if (uninteresting.contains(key))
594 return true;
595 int pos = key.indexOf(':');
596 if (pos > 0)
597 return uninteresting.contains(key.substring(0, pos + 1));
598 return false;
599 }
600
601 private static volatile Match directionKeys = null;
602 private static volatile Match reversedDirectionKeys = null;
603
604 /**
605 * Contains a list of direction-dependent keys that make an object
606 * direction dependent.
607 * Initialized by checkDirectionTagged()
608 */
609 static {
610 // FIXME: incline=\"-*\" search pattern does not work.
611 String reversedDirectionDefault = "oneway=\"-1\" | incline=down | incline=\"-*\"";
612
613 String directionDefault = "oneway? | incline=* | aerialway=* | "+
614 "waterway=stream | waterway=river | waterway=canal | waterway=drain | waterway=rapids | "+
615 "\"piste:type\"=downhill | \"piste:type\"=sled | man_made=\"piste:halfpipe\" | "+
616 "junction=roundabout";
617
618 try {
619 reversedDirectionKeys = SearchCompiler.compile(Main.pref.get("tags.reversed_direction", reversedDirectionDefault), false, false);
620 } catch (ParseError e) {
621 System.err.println("Unable to compile pattern for tags.reversed_direction, trying default pattern: " + e.getMessage());
622
623 try {
624 reversedDirectionKeys = SearchCompiler.compile(reversedDirectionDefault, false, false);
625 } catch (ParseError e2) {
626 throw new AssertionError("Unable to compile default pattern for direction keys: " + e2.getMessage());
627 }
628 }
629 try {
630 directionKeys = SearchCompiler.compile(Main.pref.get("tags.direction", directionDefault), false, false);
631 } catch (ParseError e) {
632 System.err.println("Unable to compile pattern for tags.direction, trying default pattern: " + e.getMessage());
633
634 try {
635 directionKeys = SearchCompiler.compile(directionDefault, false, false);
636 } catch (ParseError e2) {
637 throw new AssertionError("Unable to compile default pattern for direction keys: " + e2.getMessage());
638 }
639 }
640 }
641
642 private void updateTagged() {
643 if (keys != null) {
644 for (String key: keySet()) {
645 if (!isUninterestingKey(key)) {
646 updateFlagsNoLock(FLAG_TAGGED, true);
647 return;
648 }
649 }
650 }
651 updateFlagsNoLock(FLAG_TAGGED, false);
652 }
653
654 /**
655 * true if this object is considered "tagged". To be "tagged", an object
656 * must have one or more "interesting" tags. "created_by" and "source"
657 * are typically considered "uninteresting" and do not make an object
658 * "tagged".
659 */
660 public boolean isTagged() {
661 return (flags & FLAG_TAGGED) != 0;
662 }
663
664 private void updateDirectionFlags() {
665 boolean hasDirections = false;
666 boolean directionReversed = false;
667 if (reversedDirectionKeys.match(this)) {
668 hasDirections = true;
669 directionReversed = true;
670 }
671 if (directionKeys.match(this)) {
672 hasDirections = true;
673 }
674
675 updateFlagsNoLock(FLAG_DIRECTION_REVERSED, directionReversed);
676 updateFlagsNoLock(FLAG_HAS_DIRECTIONS, hasDirections);
677 }
678
679 /**
680 * true if this object has direction dependent tags (e.g. oneway)
681 */
682 public boolean hasDirectionKeys() {
683 return (flags & FLAG_HAS_DIRECTIONS) != 0;
684 }
685
686 public boolean reversedDirection() {
687 return (flags & FLAG_DIRECTION_REVERSED) != 0;
688 }
689
690 /*------------
691 * Keys handling
692 ------------*/
693
694 @Override
695 public final void setKeys(Map<String, String> keys) {
696 boolean locked = writeLock();
697 try {
698 super.setKeys(keys);
699 } finally {
700 writeUnlock(locked);
701 }
702 }
703
704 @Override
705 public final void put(String key, String value) {
706 boolean locked = writeLock();
707 try {
708 super.put(key, value);
709 } finally {
710 writeUnlock(locked);
711 }
712 }
713
714 @Override
715 public final void remove(String key) {
716 boolean locked = writeLock();
717 try {
718 super.remove(key);
719 } finally {
720 writeUnlock(locked);
721 }
722 }
723
724 @Override
725 public final void removeAll() {
726 boolean locked = writeLock();
727 try {
728 super.removeAll();
729 } finally {
730 writeUnlock(locked);
731 }
732 }
733
734 @Override
735 protected final void keysChangedImpl(Map<String, String> originalKeys) {
736 clearCachedStyle();
737 if (dataSet != null) {
738 for (OsmPrimitive ref : getReferrers()) {
739 ref.clearCachedStyle();
740 }
741 }
742 updateDirectionFlags();
743 updateTagged();
744 if (dataSet != null) {
745 dataSet.fireTagsChanged(this, originalKeys);
746 }
747 }
748
749 /*------------
750 * Referrers
751 ------------*/
752
753 private Object referrers;
754
755 /**
756 * Add new referrer. If referrer is already included then no action is taken
757 * @param referrer
758 */
759 protected void addReferrer(OsmPrimitive referrer) {
760 // Based on methods from josm-ng
761 if (referrers == null) {
762 referrers = referrer;
763 } else if (referrers instanceof OsmPrimitive) {
764 if (referrers != referrer) {
765 referrers = new OsmPrimitive[] { (OsmPrimitive)referrers, referrer };
766 }
767 } else {
768 for (OsmPrimitive primitive:(OsmPrimitive[])referrers) {
769 if (primitive == referrer)
770 return;
771 }
772 OsmPrimitive[] orig = (OsmPrimitive[])referrers;
773 OsmPrimitive[] bigger = new OsmPrimitive[orig.length+1];
774 System.arraycopy(orig, 0, bigger, 0, orig.length);
775 bigger[orig.length] = referrer;
776 referrers = bigger;
777 }
778 }
779
780 /**
781 * Remove referrer. No action is taken if referrer is not registered
782 * @param referrer
783 */
784 protected void removeReferrer(OsmPrimitive referrer) {
785 // Based on methods from josm-ng
786 if (referrers instanceof OsmPrimitive) {
787 if (referrers == referrer) {
788 referrers = null;
789 }
790 } else if (referrers instanceof OsmPrimitive[]) {
791 OsmPrimitive[] orig = (OsmPrimitive[])referrers;
792 int idx = -1;
793 for (int i=0; i<orig.length; i++) {
794 if (orig[i] == referrer) {
795 idx = i;
796 break;
797 }
798 }
799 if (idx == -1)
800 return;
801
802 if (orig.length == 2) {
803 referrers = orig[1-idx]; // idx is either 0 or 1, take the other
804 } else { // downsize the array
805 OsmPrimitive[] smaller = new OsmPrimitive[orig.length-1];
806 System.arraycopy(orig, 0, smaller, 0, idx);
807 System.arraycopy(orig, idx+1, smaller, idx, smaller.length-idx);
808 referrers = smaller;
809 }
810 }
811 }
812 /**
813 * Find primitives that reference this primitive. Returns only primitives that are included in the same
814 * dataset as this primitive. <br>
815 *
816 * For example following code will add wnew as referer to all nodes of existingWay, but this method will
817 * not return wnew because it's not part of the dataset <br>
818 *
819 * <code>Way wnew = new Way(existingWay)</code>
820 *
821 * @return a collection of all primitives that reference this primitive.
822 */
823
824 public final List<OsmPrimitive> getReferrers() {
825 // Method copied from OsmPrimitive in josm-ng
826 // Returns only referrers that are members of the same dataset (primitive can have some fake references, for example
827 // when way is cloned
828 checkDataset();
829 Object referrers = this.referrers;
830 List<OsmPrimitive> result = new ArrayList<OsmPrimitive>();
831 if (referrers != null) {
832 if (referrers instanceof OsmPrimitive) {
833 OsmPrimitive ref = (OsmPrimitive)referrers;
834 if (ref.dataSet == dataSet) {
835 result.add(ref);
836 }
837 } else {
838 for (OsmPrimitive o:(OsmPrimitive[])referrers) {
839 if (dataSet == o.dataSet) {
840 result.add(o);
841 }
842 }
843 }
844 }
845 return result;
846 }
847
848 /**
849 * <p>Visits {@code visitor} for all referrers.</p>
850 *
851 * @param visitor the visitor. Ignored, if null.
852 */
853 public void visitReferrers(Visitor visitor){
854 if (visitor == null) return;
855 if (this.referrers == null)
856 return;
857 else if (this.referrers instanceof OsmPrimitive) {
858 OsmPrimitive ref = (OsmPrimitive) this.referrers;
859 if (ref.dataSet == dataSet) {
860 ref.visit(visitor);
861 }
862 } else if (this.referrers instanceof OsmPrimitive[]) {
863 OsmPrimitive[] refs = (OsmPrimitive[]) this.referrers;
864 for (OsmPrimitive ref: refs) {
865 if (ref.dataSet == dataSet) {
866 ref.visit(visitor);
867 }
868 }
869 }
870 }
871
872 /**
873 Return true, if this primitive is referred by at least n ways
874 @param n Minimal number of ways to return true. Must be positive
875 */
876 public final boolean isReferredByWays(int n) {
877 // Count only referrers that are members of the same dataset (primitive can have some fake references, for example
878 // when way is cloned
879 Object referrers = this.referrers;
880 if (referrers == null) return false;
881 checkDataset();
882 if (referrers instanceof OsmPrimitive)
883 return n<=1 && referrers instanceof Way && ((OsmPrimitive)referrers).dataSet == dataSet;
884 else {
885 int counter=0;
886 for (OsmPrimitive o : (OsmPrimitive[])referrers) {
887 if (dataSet == o.dataSet && o instanceof Way) {
888 if (++counter >= n)
889 return true;
890 }
891 }
892 return false;
893 }
894 }
895
896
897 /*-----------------
898 * OTHER METHODS
899 *----------------/
900
901 /**
902 * Implementation of the visitor scheme. Subclasses have to call the correct
903 * visitor function.
904 * @param visitor The visitor from which the visit() function must be called.
905 */
906 abstract public void visit(Visitor visitor);
907
908 /**
909 * Get and write all attributes from the parameter. Does not fire any listener, so
910 * use this only in the data initializing phase
911 */
912 public void cloneFrom(OsmPrimitive other) {
913 // write lock is provided by subclasses
914 if (id != other.id && dataSet != null)
915 throw new DataIntegrityProblemException("Osm id cannot be changed after primitive was added to the dataset");
916
917 super.cloneFrom(other);
918 clearCachedStyle();
919 }
920
921 /**
922 * Merges the technical and semantical attributes from <code>other</code> onto this.
923 *
924 * Both this and other must be new, or both must be assigned an OSM ID. If both this and <code>other</code>
925 * have an assigend OSM id, the IDs have to be the same.
926 *
927 * @param other the other primitive. Must not be null.
928 * @throws IllegalArgumentException thrown if other is null.
929 * @throws DataIntegrityProblemException thrown if either this is new and other is not, or other is new and this is not
930 * @throws DataIntegrityProblemException thrown if other isn't new and other.getId() != this.getId()
931 */
932 public void mergeFrom(OsmPrimitive other) {
933 boolean locked = writeLock();
934 try {
935 CheckParameterUtil.ensureParameterNotNull(other, "other");
936 if (other.isNew() ^ isNew())
937 throw new DataIntegrityProblemException(tr("Cannot merge because either of the participating primitives is new and the other is not"));
938 if (! other.isNew() && other.getId() != id)
939 throw new DataIntegrityProblemException(tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId()));
940
941 setKeys(other.getKeys());
942 timestamp = other.timestamp;
943 version = other.version;
944 setIncomplete(other.isIncomplete());
945 flags = other.flags;
946 user= other.user;
947 changesetId = other.changesetId;
948 } finally {
949 writeUnlock(locked);
950 }
951 }
952
953 /**
954 * Replies true if this primitive and other are equal with respect to their
955 * semantic attributes.
956 * <ol>
957 * <li>equal id</ol>
958 * <li>both are complete or both are incomplete</li>
959 * <li>both have the same tags</li>
960 * </ol>
961 * @param other
962 * @return true if this primitive and other are equal with respect to their
963 * semantic attributes.
964 */
965 public boolean hasEqualSemanticAttributes(OsmPrimitive other) {
966 if (!isNew() && id != other.id)
967 return false;
968 if (isIncomplete() && ! other.isIncomplete() || !isIncomplete() && other.isIncomplete())
969 return false;
970 // can't do an equals check on the internal keys array because it is not ordered
971 //
972 return hasSameTags(other);
973 }
974
975 /**
976 * Replies true if this primitive and other are equal with respect to their
977 * technical attributes. The attributes:
978 * <ol>
979 * <li>deleted</ol>
980 * <li>modified</ol>
981 * <li>timestamp</ol>
982 * <li>version</ol>
983 * <li>visible</ol>
984 * <li>user</ol>
985 * </ol>
986 * have to be equal
987 * @param other the other primitive
988 * @return true if this primitive and other are equal with respect to their
989 * technical attributes
990 */
991 public boolean hasEqualTechnicalAttributes(OsmPrimitive other) {
992 if (other == null) return false;
993
994 return
995 isDeleted() == other.isDeleted()
996 && isModified() == other.isModified()
997 && timestamp == other.timestamp
998 && version == other.version
999 && isVisible() == other.isVisible()
1000 && (user == null ? other.user==null : user==other.user)
1001 && changesetId == other.changesetId;
1002 }
1003
1004 /**
1005 * Loads (clone) this primitive from provided PrimitiveData
1006 * @param data
1007 */
1008 public void load(PrimitiveData data) {
1009 // Write lock is provided by subclasses
1010 setKeys(data.getKeys());
1011 setTimestamp(data.getTimestamp());
1012 user = data.getUser();
1013 setChangesetId(data.getChangesetId());
1014 setDeleted(data.isDeleted());
1015 setModified(data.isModified());
1016 setIncomplete(data.isIncomplete());
1017 version = data.getVersion();
1018 }
1019
1020 /**
1021 * Save parameters of this primitive to the transport object
1022 * @return
1023 */
1024 public abstract PrimitiveData save();
1025
1026 protected void saveCommonAttributes(PrimitiveData data) {
1027 data.setId(id);
1028 data.setKeys(getKeys());
1029 data.setTimestamp(getTimestamp());
1030 data.setUser(user);
1031 data.setDeleted(isDeleted());
1032 data.setModified(isModified());
1033 data.setVisible(isVisible());
1034 data.setIncomplete(isIncomplete());
1035 data.setChangesetId(changesetId);
1036 data.setVersion(version);
1037 }
1038
1039 public abstract BBox getBBox();
1040
1041 /**
1042 * Called by Dataset to update cached position information of primitive (bbox, cached EarthNorth, ...)
1043 */
1044 public abstract void updatePosition();
1045
1046 /*----------------
1047 * OBJECT METHODS
1048 *---------------*/
1049
1050 @Override
1051 protected String getFlagsAsString() {
1052 StringBuilder builder = new StringBuilder(super.getFlagsAsString());
1053
1054 if (isDisabled()) {
1055 if (isDisabledAndHidden()) {
1056 builder.append("h");
1057 } else {
1058 builder.append("d");
1059 }
1060 }
1061 if (isTagged()) {
1062 builder.append("T");
1063 }
1064 if (hasDirectionKeys()) {
1065 if (reversedDirection()) {
1066 builder.append("<");
1067 } else {
1068 builder.append(">");
1069 }
1070 }
1071 return builder.toString();
1072 }
1073
1074 /**
1075 * Equal, if the id (and class) is equal.
1076 *
1077 * An primitive is equal to its incomplete counter part.
1078 */
1079 @Override public boolean equals(Object obj) {
1080 if (obj instanceof OsmPrimitive)
1081 return ((OsmPrimitive)obj).id == id && obj.getClass() == getClass();
1082 return false;
1083 }
1084
1085 /**
1086 * Return the id plus the class type encoded as hashcode or super's hashcode if id is 0.
1087 *
1088 * An primitive has the same hashcode as its incomplete counterpart.
1089 */
1090 @Override public final int hashCode() {
1091 return (int)id;
1092 }
1093
1094 /**
1095 * Replies the display name of a primitive formatted by <code>formatter</code>
1096 *
1097 * @return the display name
1098 */
1099 public abstract String getDisplayName(NameFormatter formatter);
1100
1101 @Override
1102 public Collection<String> getTemplateKeys() {
1103 Collection<String> keySet = keySet();
1104 List<String> result = new ArrayList<String>(keySet.size() + 2);
1105 result.add(SPECIAL_VALUE_ID);
1106 result.add(SPECIAL_VALUE_LOCAL_NAME);
1107 result.addAll(keySet);
1108 return result;
1109 }
1110
1111 @Override
1112 public Object getTemplateValue(String name, boolean special) {
1113 if (special) {
1114 String lc = name.toLowerCase();
1115 if (SPECIAL_VALUE_ID.equals(lc))
1116 return getId();
1117 else if (SPECIAL_VALUE_LOCAL_NAME.equals(lc))
1118 return getLocalName();
1119 else
1120 return null;
1121
1122 } else
1123 return getIgnoreCase(name);
1124 }
1125
1126 @Override
1127 public boolean evaluateCondition(Match condition) {
1128 return condition.match(this);
1129 }
1130
1131}
Note: See TracBrowser for help on using the repository browser.