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

Last change on this file since 11064 was 11064, checked in by stoecker, 8 years ago

fix #13682 - silently drop also converted_by

  • Property svn:eol-style set to native
File size: 47.4 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.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.HashMap;
13import java.util.HashSet;
14import java.util.LinkedHashSet;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Objects;
20import java.util.Set;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.actions.search.SearchCompiler;
24import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
25import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
26import org.openstreetmap.josm.data.osm.visitor.Visitor;
27import org.openstreetmap.josm.gui.mappaint.StyleCache;
28import org.openstreetmap.josm.tools.CheckParameterUtil;
29import org.openstreetmap.josm.tools.Utils;
30import org.openstreetmap.josm.tools.template_engine.TemplateEngineDataProvider;
31
32/**
33 * The base class for OSM objects ({@link Node}, {@link Way}, {@link Relation}).
34 *
35 * It can be created, deleted and uploaded to the OSM-Server.
36 *
37 * Although OsmPrimitive is designed as a base class, it is not to be meant to subclass
38 * it by any other than from the package {@link org.openstreetmap.josm.data.osm}. The available primitives are a fixed set that are given
39 * by the server environment and not an extendible data stuff.
40 *
41 * @author imi
42 */
43public abstract class OsmPrimitive extends AbstractPrimitive implements Comparable<OsmPrimitive>, TemplateEngineDataProvider {
44 private static final String SPECIAL_VALUE_ID = "id";
45 private static final String SPECIAL_VALUE_LOCAL_NAME = "localname";
46
47 /**
48 * An object can be disabled by the filter mechanism.
49 * Then it will show in a shade of gray on the map or it is completely
50 * hidden from the view.
51 * Disabled objects usually cannot be selected or modified
52 * while the filter is active.
53 */
54 protected static final int FLAG_DISABLED = 1 << 4;
55
56 /**
57 * This flag is only relevant if an object is disabled by the
58 * filter mechanism (i.e.&nbsp;FLAG_DISABLED is set).
59 * Then it indicates, whether it is completely hidden or
60 * just shown in gray color.
61 *
62 * When the primitive is not disabled, this flag should be
63 * unset as well (for efficient access).
64 */
65 protected static final int FLAG_HIDE_IF_DISABLED = 1 << 5;
66
67 /**
68 * Flag used internally by the filter mechanism.
69 */
70 protected static final int FLAG_DISABLED_TYPE = 1 << 6;
71
72 /**
73 * Flag used internally by the filter mechanism.
74 */
75 protected static final int FLAG_HIDDEN_TYPE = 1 << 7;
76
77 /**
78 * This flag is set if the primitive is a way and
79 * according to the tags, the direction of the way is important.
80 * (e.g. one way street.)
81 */
82 protected static final int FLAG_HAS_DIRECTIONS = 1 << 8;
83
84 /**
85 * If the primitive is tagged.
86 * Some trivial tags like source=* are ignored here.
87 */
88 protected static final int FLAG_TAGGED = 1 << 9;
89
90 /**
91 * This flag is only relevant if FLAG_HAS_DIRECTIONS is set.
92 * It shows, that direction of the arrows should be reversed.
93 * (E.g. oneway=-1.)
94 */
95 protected static final int FLAG_DIRECTION_REVERSED = 1 << 10;
96
97 /**
98 * When hovering over ways and nodes in add mode, the
99 * "target" objects are visually highlighted. This flag indicates
100 * that the primitive is currently highlighted.
101 */
102 protected static final int FLAG_HIGHLIGHTED = 1 << 11;
103
104 /**
105 * If the primitive is annotated with a tag such as note, fixme, etc.
106 * Match the "work in progress" tags in default map style.
107 */
108 protected static final int FLAG_ANNOTATED = 1 << 12;
109
110 /**
111 * A tagged way that matches this pattern has a direction.
112 * @see #FLAG_HAS_DIRECTIONS
113 */
114 static volatile Match directionKeys;
115
116 /**
117 * A tagged way that matches this pattern has a direction that is reversed.
118 * <p>
119 * This pattern should be a subset of {@link #directionKeys}
120 * @see #FLAG_DIRECTION_REVERSED
121 */
122 private static volatile Match reversedDirectionKeys;
123
124 static {
125 String reversedDirectionDefault = "oneway=\"-1\"";
126
127 String directionDefault = "oneway? | (aerialway=* -aerialway=station) | "+
128 "waterway=stream | waterway=river | waterway=ditch | waterway=drain | "+
129 "(\"piste:type\"=downhill & -area=yes) | (\"piste:type\"=sled & -area=yes) | (man_made=\"piste:halfpipe\" & -area=yes) | "+
130 "junction=roundabout | (highway=motorway & -oneway=no & -oneway=reversible) | "+
131 "(highway=motorway_link & -oneway=no & -oneway=reversible)";
132
133 reversedDirectionKeys = compileDirectionKeys("tags.reversed_direction", reversedDirectionDefault);
134 directionKeys = compileDirectionKeys("tags.direction", directionDefault);
135 }
136
137 /**
138 * Replies the sub-collection of {@link OsmPrimitive}s of type <code>type</code> present in
139 * another collection of {@link OsmPrimitive}s. The result collection is a list.
140 *
141 * If <code>list</code> is null, replies an empty list.
142 *
143 * @param <T> type of data (must be one of the {@link OsmPrimitive} types
144 * @param list the original list
145 * @param type the type to filter for
146 * @return the sub-list of OSM primitives of type <code>type</code>
147 */
148 public static <T extends OsmPrimitive> List<T> getFilteredList(Collection<OsmPrimitive> list, Class<T> type) {
149 if (list == null) return Collections.emptyList();
150 List<T> ret = new LinkedList<>();
151 for (OsmPrimitive p: list) {
152 if (type.isInstance(p)) {
153 ret.add(type.cast(p));
154 }
155 }
156 return ret;
157 }
158
159 /**
160 * Replies the sub-collection of {@link OsmPrimitive}s of type <code>type</code> present in
161 * another collection of {@link OsmPrimitive}s. The result collection is a set.
162 *
163 * If <code>list</code> is null, replies an empty set.
164 *
165 * @param <T> type of data (must be one of the {@link OsmPrimitive} types
166 * @param set the original collection
167 * @param type the type to filter for
168 * @return the sub-set of OSM primitives of type <code>type</code>
169 */
170 public static <T extends OsmPrimitive> Set<T> getFilteredSet(Collection<OsmPrimitive> set, Class<T> type) {
171 Set<T> ret = new LinkedHashSet<>();
172 if (set != null) {
173 for (OsmPrimitive p: set) {
174 if (type.isInstance(p)) {
175 ret.add(type.cast(p));
176 }
177 }
178 }
179 return ret;
180 }
181
182 /**
183 * Replies the collection of referring primitives for the primitives in <code>primitives</code>.
184 *
185 * @param primitives the collection of primitives.
186 * @return the collection of referring primitives for the primitives in <code>primitives</code>;
187 * empty set if primitives is null or if there are no referring primitives
188 */
189 public static Set<OsmPrimitive> getReferrer(Collection<? extends OsmPrimitive> primitives) {
190 Set<OsmPrimitive> ret = new HashSet<>();
191 if (primitives == null || primitives.isEmpty()) return ret;
192 for (OsmPrimitive p: primitives) {
193 ret.addAll(p.getReferrers());
194 }
195 return ret;
196 }
197
198 /**
199 * Creates a new primitive for the given id.
200 *
201 * If allowNegativeId is set, provided id can be &lt; 0 and will be set to primitive without any processing.
202 * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
203 * positive number.
204 *
205 * @param id the id
206 * @param allowNegativeId {@code true} to allow negative id
207 * @throws IllegalArgumentException if id &lt; 0 and allowNegativeId is false
208 */
209 protected OsmPrimitive(long id, boolean allowNegativeId) {
210 if (allowNegativeId) {
211 this.id = id;
212 } else {
213 if (id < 0)
214 throw new IllegalArgumentException(MessageFormat.format("Expected ID >= 0. Got {0}.", id));
215 else if (id == 0) {
216 this.id = generateUniqueId();
217 } else {
218 this.id = id;
219 }
220
221 }
222 this.version = 0;
223 this.setIncomplete(id > 0);
224 }
225
226 /**
227 * Creates a new primitive for the given id and version.
228 *
229 * If allowNegativeId is set, provided id can be &lt; 0 and will be set to primitive without any processing.
230 * If allowNegativeId is not set, then id will have to be 0 (in that case new unique id will be generated) or
231 * positive number.
232 *
233 * If id is not &gt; 0 version is ignored and set to 0.
234 *
235 * @param id the id
236 * @param version the version (positive integer)
237 * @param allowNegativeId {@code true} to allow negative id
238 * @throws IllegalArgumentException if id &lt; 0 and allowNegativeId is false
239 */
240 protected OsmPrimitive(long id, int version, boolean allowNegativeId) {
241 this(id, allowNegativeId);
242 this.version = id > 0 ? version : 0;
243 setIncomplete(id > 0 && version == 0);
244 }
245
246 /*----------
247 * MAPPAINT
248 *--------*/
249 public StyleCache mappaintStyle;
250 public int mappaintCacheIdx;
251
252 /* This should not be called from outside. Fixing the UI to add relevant
253 get/set functions calling this implicitely is preferred, so we can have
254 transparent cache handling in the future. */
255 public void clearCachedStyle() {
256 mappaintStyle = null;
257 }
258 /* end of mappaint data */
259
260 /*---------
261 * DATASET
262 *---------*/
263
264 /** the parent dataset */
265 private DataSet dataSet;
266
267 /**
268 * This method should never ever by called from somewhere else than Dataset.addPrimitive or removePrimitive methods
269 * @param dataSet the parent dataset
270 */
271 void setDataset(DataSet dataSet) {
272 if (this.dataSet != null && dataSet != null && this.dataSet != dataSet)
273 throw new DataIntegrityProblemException("Primitive cannot be included in more than one Dataset");
274 this.dataSet = dataSet;
275 }
276
277 /**
278 *
279 * @return DataSet this primitive is part of.
280 */
281 public DataSet getDataSet() {
282 return dataSet;
283 }
284
285 /**
286 * Throws exception if primitive is not part of the dataset
287 */
288 public void checkDataset() {
289 if (dataSet == null)
290 throw new DataIntegrityProblemException("Primitive must be part of the dataset: " + toString());
291 }
292
293 protected boolean writeLock() {
294 if (dataSet != null) {
295 dataSet.beginUpdate();
296 return true;
297 } else
298 return false;
299 }
300
301 protected void writeUnlock(boolean locked) {
302 if (locked) {
303 // It shouldn't be possible for dataset to become null because
304 // method calling setDataset would need write lock which is owned by this thread
305 dataSet.endUpdate();
306 }
307 }
308
309 /**
310 * Sets the id and the version of this primitive if it is known to the OSM API.
311 *
312 * Since we know the id and its version it can't be incomplete anymore. incomplete
313 * is set to false.
314 *
315 * @param id the id. &gt; 0 required
316 * @param version the version &gt; 0 required
317 * @throws IllegalArgumentException if id &lt;= 0
318 * @throws IllegalArgumentException if version &lt;= 0
319 * @throws DataIntegrityProblemException if id is changed and primitive was already added to the dataset
320 */
321 @Override
322 public void setOsmId(long id, int version) {
323 boolean locked = writeLock();
324 try {
325 if (id <= 0)
326 throw new IllegalArgumentException(tr("ID > 0 expected. Got {0}.", id));
327 if (version <= 0)
328 throw new IllegalArgumentException(tr("Version > 0 expected. Got {0}.", version));
329 if (dataSet != null && id != this.id) {
330 DataSet datasetCopy = dataSet;
331 // Reindex primitive
332 datasetCopy.removePrimitive(this);
333 this.id = id;
334 datasetCopy.addPrimitive(this);
335 }
336 super.setOsmId(id, version);
337 } finally {
338 writeUnlock(locked);
339 }
340 }
341
342 /**
343 * Clears the metadata, including id and version known to the OSM API.
344 * The id is a new unique id. The version, changeset and timestamp are set to 0.
345 * incomplete and deleted are set to false. It's preferred to use copy constructor with clearMetadata set to true instead
346 *
347 * <strong>Caution</strong>: Do not use this method on primitives which are already added to a {@link DataSet}.
348 *
349 * @throws DataIntegrityProblemException If primitive was already added to the dataset
350 * @since 6140
351 */
352 @Override
353 public void clearOsmMetadata() {
354 if (dataSet != null)
355 throw new DataIntegrityProblemException("Method cannot be called after primitive was added to the dataset");
356 super.clearOsmMetadata();
357 }
358
359 @Override
360 public void setUser(User user) {
361 boolean locked = writeLock();
362 try {
363 super.setUser(user);
364 } finally {
365 writeUnlock(locked);
366 }
367 }
368
369 @Override
370 public void setChangesetId(int changesetId) {
371 boolean locked = writeLock();
372 try {
373 int old = this.changesetId;
374 super.setChangesetId(changesetId);
375 if (dataSet != null) {
376 dataSet.fireChangesetIdChanged(this, old, changesetId);
377 }
378 } finally {
379 writeUnlock(locked);
380 }
381 }
382
383 @Override
384 public void setTimestamp(Date timestamp) {
385 boolean locked = writeLock();
386 try {
387 super.setTimestamp(timestamp);
388 } finally {
389 writeUnlock(locked);
390 }
391 }
392
393
394 /* -------
395 /* FLAGS
396 /* ------*/
397
398 private void updateFlagsNoLock(int flag, boolean value) {
399 super.updateFlags(flag, value);
400 }
401
402 @Override
403 protected final void updateFlags(int flag, boolean value) {
404 boolean locked = writeLock();
405 try {
406 updateFlagsNoLock(flag, value);
407 } finally {
408 writeUnlock(locked);
409 }
410 }
411
412 /**
413 * Make the primitive disabled (e.g.&nbsp;if a filter applies).
414 *
415 * To enable the primitive again, use unsetDisabledState.
416 * @param hidden if the primitive should be completely hidden from view or
417 * just shown in gray color.
418 * @return true, any flag has changed; false if you try to set the disabled
419 * state to the value that is already preset
420 */
421 public boolean setDisabledState(boolean hidden) {
422 boolean locked = writeLock();
423 try {
424 int oldFlags = flags;
425 updateFlagsNoLock(FLAG_DISABLED, true);
426 updateFlagsNoLock(FLAG_HIDE_IF_DISABLED, hidden);
427 return oldFlags != flags;
428 } finally {
429 writeUnlock(locked);
430 }
431 }
432
433 /**
434 * Remove the disabled flag from the primitive.
435 * Afterwards, the primitive is displayed normally and can be selected again.
436 * @return {@code true} if a change occurred
437 */
438 public boolean unsetDisabledState() {
439 boolean locked = writeLock();
440 try {
441 int oldFlags = flags;
442 updateFlagsNoLock(FLAG_DISABLED + FLAG_HIDE_IF_DISABLED, false);
443 return oldFlags != flags;
444 } finally {
445 writeUnlock(locked);
446 }
447 }
448
449 /**
450 * Set binary property used internally by the filter mechanism.
451 * @param isExplicit new "disabled type" flag value
452 */
453 public void setDisabledType(boolean isExplicit) {
454 updateFlags(FLAG_DISABLED_TYPE, isExplicit);
455 }
456
457 /**
458 * Set binary property used internally by the filter mechanism.
459 * @param isExplicit new "hidden type" flag value
460 */
461 public void setHiddenType(boolean isExplicit) {
462 updateFlags(FLAG_HIDDEN_TYPE, isExplicit);
463 }
464
465 /**
466 * Replies true, if this primitive is disabled. (E.g. a filter applies)
467 * @return {@code true} if this object has the "disabled" flag enabled
468 */
469 public boolean isDisabled() {
470 return (flags & FLAG_DISABLED) != 0;
471 }
472
473 /**
474 * Replies true, if this primitive is disabled and marked as completely hidden on the map.
475 * @return {@code true} if this object has both the "disabled" and "hide if disabled" flags enabled
476 */
477 public boolean isDisabledAndHidden() {
478 return ((flags & FLAG_DISABLED) != 0) && ((flags & FLAG_HIDE_IF_DISABLED) != 0);
479 }
480
481 /**
482 * Get binary property used internally by the filter mechanism.
483 * @return {@code true} if this object has the "hidden type" flag enabled
484 */
485 public boolean getHiddenType() {
486 return (flags & FLAG_HIDDEN_TYPE) != 0;
487 }
488
489 /**
490 * Get binary property used internally by the filter mechanism.
491 * @return {@code true} if this object has the "disabled type" flag enabled
492 */
493 public boolean getDisabledType() {
494 return (flags & FLAG_DISABLED_TYPE) != 0;
495 }
496
497 /**
498 * Determines if this object is selectable.
499 * @return {@code true} if this object is selectable
500 */
501 public boolean isSelectable() {
502 return (flags & (FLAG_DELETED + FLAG_INCOMPLETE + FLAG_DISABLED + FLAG_HIDE_IF_DISABLED)) == 0;
503 }
504
505 /**
506 * Determines if this object is drawable.
507 * @return {@code true} if this object is drawable
508 */
509 public boolean isDrawable() {
510 return (flags & (FLAG_DELETED + FLAG_INCOMPLETE + FLAG_HIDE_IF_DISABLED)) == 0;
511 }
512
513 @Override
514 public void setModified(boolean modified) {
515 boolean locked = writeLock();
516 try {
517 super.setModified(modified);
518 if (dataSet != null) {
519 dataSet.firePrimitiveFlagsChanged(this);
520 }
521 clearCachedStyle();
522 } finally {
523 writeUnlock(locked);
524 }
525 }
526
527 @Override
528 public void setVisible(boolean visible) {
529 boolean locked = writeLock();
530 try {
531 super.setVisible(visible);
532 clearCachedStyle();
533 } finally {
534 writeUnlock(locked);
535 }
536 }
537
538 @Override
539 public void setDeleted(boolean deleted) {
540 boolean locked = writeLock();
541 try {
542 super.setDeleted(deleted);
543 if (dataSet != null) {
544 if (deleted) {
545 dataSet.firePrimitivesRemoved(Collections.singleton(this), false);
546 } else {
547 dataSet.firePrimitivesAdded(Collections.singleton(this), false);
548 }
549 }
550 clearCachedStyle();
551 } finally {
552 writeUnlock(locked);
553 }
554 }
555
556 @Override
557 protected final void setIncomplete(boolean incomplete) {
558 boolean locked = writeLock();
559 try {
560 if (dataSet != null && incomplete != this.isIncomplete()) {
561 if (incomplete) {
562 dataSet.firePrimitivesRemoved(Collections.singletonList(this), true);
563 } else {
564 dataSet.firePrimitivesAdded(Collections.singletonList(this), true);
565 }
566 }
567 super.setIncomplete(incomplete);
568 } finally {
569 writeUnlock(locked);
570 }
571 }
572
573 /**
574 * Determines whether the primitive is selected
575 * @return whether the primitive is selected
576 * @see DataSet#isSelected(OsmPrimitive)
577 */
578 public boolean isSelected() {
579 return dataSet != null && dataSet.isSelected(this);
580 }
581
582 /**
583 * Determines if this primitive is a member of a selected relation.
584 * @return {@code true} if this primitive is a member of a selected relation, {@code false} otherwise
585 */
586 public boolean isMemberOfSelected() {
587 if (referrers == null)
588 return false;
589 if (referrers instanceof OsmPrimitive)
590 return referrers instanceof Relation && ((OsmPrimitive) referrers).isSelected();
591 for (OsmPrimitive ref : (OsmPrimitive[]) referrers) {
592 if (ref instanceof Relation && ref.isSelected())
593 return true;
594 }
595 return false;
596 }
597
598 /**
599 * Determines if this primitive is an outer member of a selected multipolygon relation.
600 * @return {@code true} if this primitive is an outer member of a selected multipolygon relation, {@code false} otherwise
601 * @since 7621
602 */
603 public boolean isOuterMemberOfSelected() {
604 if (referrers == null)
605 return false;
606 if (referrers instanceof OsmPrimitive) {
607 return isOuterMemberOfMultipolygon((OsmPrimitive) referrers);
608 }
609 for (OsmPrimitive ref : (OsmPrimitive[]) referrers) {
610 if (isOuterMemberOfMultipolygon(ref))
611 return true;
612 }
613 return false;
614 }
615
616 private boolean isOuterMemberOfMultipolygon(OsmPrimitive ref) {
617 if (ref instanceof Relation && ref.isSelected() && ((Relation) ref).isMultipolygon()) {
618 for (RelationMember rm : ((Relation) ref).getMembersFor(Collections.singleton(this))) {
619 if ("outer".equals(rm.getRole())) {
620 return true;
621 }
622 }
623 }
624 return false;
625 }
626
627 /**
628 * Updates the highlight flag for this primitive.
629 * @param highlighted The new highlight flag.
630 */
631 public void setHighlighted(boolean highlighted) {
632 if (isHighlighted() != highlighted) {
633 updateFlags(FLAG_HIGHLIGHTED, highlighted);
634 if (dataSet != null) {
635 dataSet.fireHighlightingChanged();
636 }
637 }
638 }
639
640 /**
641 * Checks if the highlight flag for this primitive was set
642 * @return The highlight flag.
643 */
644 public boolean isHighlighted() {
645 return (flags & FLAG_HIGHLIGHTED) != 0;
646 }
647
648 /*---------------------------------------------------
649 * WORK IN PROGRESS, UNINTERESTING AND DIRECTION KEYS
650 *--------------------------------------------------*/
651
652 private static volatile Collection<String> workinprogress;
653 private static volatile Collection<String> uninteresting;
654 private static volatile Collection<String> discardable;
655
656 /**
657 * Returns a list of "uninteresting" keys that do not make an object
658 * "tagged". Entries that end with ':' are causing a whole namespace to be considered
659 * "uninteresting". Only the first level namespace is considered.
660 * Initialized by isUninterestingKey()
661 * @return The list of uninteresting keys.
662 */
663 public static Collection<String> getUninterestingKeys() {
664 if (uninteresting == null) {
665 List<String> l = new LinkedList<>(Arrays.asList(
666 "source", "source_ref", "source:", "comment",
667 "converted_by", "watch", "watch:",
668 "description", "attribution"));
669 l.addAll(getDiscardableKeys());
670 l.addAll(getWorkInProgressKeys());
671 uninteresting = Main.pref.getCollection("tags.uninteresting", l);
672 }
673 return uninteresting;
674 }
675
676 /**
677 * Returns a list of keys which have been deemed uninteresting to the point
678 * that they can be silently removed from data which is being edited.
679 * @return The list of discardable keys.
680 */
681 public static Collection<String> getDiscardableKeys() {
682 if (discardable == null) {
683 discardable = Main.pref.getCollection("tags.discardable",
684 Arrays.asList(
685 "created_by",
686 "converted_by",
687 "geobase:datasetName",
688 "geobase:uuid",
689 "KSJ2:ADS",
690 "KSJ2:ARE",
691 "KSJ2:AdminArea",
692 "KSJ2:COP_label",
693 "KSJ2:DFD",
694 "KSJ2:INT",
695 "KSJ2:INT_label",
696 "KSJ2:LOC",
697 "KSJ2:LPN",
698 "KSJ2:OPC",
699 "KSJ2:PubFacAdmin",
700 "KSJ2:RAC",
701 "KSJ2:RAC_label",
702 "KSJ2:RIC",
703 "KSJ2:RIN",
704 "KSJ2:WSC",
705 "KSJ2:coordinate",
706 "KSJ2:curve_id",
707 "KSJ2:curve_type",
708 "KSJ2:filename",
709 "KSJ2:lake_id",
710 "KSJ2:lat",
711 "KSJ2:long",
712 "KSJ2:river_id",
713 "odbl",
714 "odbl:note",
715 "SK53_bulk:load",
716 "sub_sea:type",
717 "tiger:source",
718 "tiger:separated",
719 "tiger:tlid",
720 "tiger:upload_uuid",
721 "yh:LINE_NAME",
722 "yh:LINE_NUM",
723 "yh:STRUCTURE",
724 "yh:TOTYUMONO",
725 "yh:TYPE",
726 "yh:WIDTH",
727 "yh:WIDTH_RANK"
728 ));
729 }
730 return discardable;
731 }
732
733 /**
734 * Returns a list of "work in progress" keys that do not make an object
735 * "tagged" but "annotated".
736 * @return The list of work in progress keys.
737 * @since 5754
738 */
739 public static Collection<String> getWorkInProgressKeys() {
740 if (workinprogress == null) {
741 workinprogress = Main.pref.getCollection("tags.workinprogress",
742 Arrays.asList("note", "fixme", "FIXME"));
743 }
744 return workinprogress;
745 }
746
747 /**
748 * Determines if key is considered "uninteresting".
749 * @param key The key to check
750 * @return true if key is considered "uninteresting".
751 */
752 public static boolean isUninterestingKey(String key) {
753 getUninterestingKeys();
754 if (uninteresting.contains(key))
755 return true;
756 int pos = key.indexOf(':');
757 if (pos > 0)
758 return uninteresting.contains(key.substring(0, pos + 1));
759 return false;
760 }
761
762 /**
763 * Returns {@link #getKeys()} for which {@code key} does not fulfill {@link #isUninterestingKey}.
764 * @return A map of interesting tags
765 */
766 public Map<String, String> getInterestingTags() {
767 Map<String, String> result = new HashMap<>();
768 String[] keys = this.keys;
769 if (keys != null) {
770 for (int i = 0; i < keys.length; i += 2) {
771 if (!isUninterestingKey(keys[i])) {
772 result.put(keys[i], keys[i + 1]);
773 }
774 }
775 }
776 return result;
777 }
778
779 private static Match compileDirectionKeys(String prefName, String defaultValue) throws AssertionError {
780 try {
781 return SearchCompiler.compile(Main.pref.get(prefName, defaultValue));
782 } catch (ParseError e) {
783 Main.error(e, "Unable to compile pattern for " + prefName + ", trying default pattern:");
784 }
785
786 try {
787 return SearchCompiler.compile(defaultValue);
788 } catch (ParseError e2) {
789 throw new AssertionError("Unable to compile default pattern for direction keys: " + e2.getMessage(), e2);
790 }
791 }
792
793 private void updateTagged() {
794 for (String key: keySet()) {
795 // 'area' is not really uninteresting (putting it in that list may have unpredictable side effects)
796 // but it's clearly not enough to consider an object as tagged (see #9261)
797 if (!isUninterestingKey(key) && !"area".equals(key)) {
798 updateFlagsNoLock(FLAG_TAGGED, true);
799 return;
800 }
801 }
802 updateFlagsNoLock(FLAG_TAGGED, false);
803 }
804
805 private void updateAnnotated() {
806 for (String key: keySet()) {
807 if (getWorkInProgressKeys().contains(key)) {
808 updateFlagsNoLock(FLAG_ANNOTATED, true);
809 return;
810 }
811 }
812 updateFlagsNoLock(FLAG_ANNOTATED, false);
813 }
814
815 /**
816 * Determines if this object is considered "tagged". To be "tagged", an object
817 * must have one or more "interesting" tags. "created_by" and "source"
818 * are typically considered "uninteresting" and do not make an object
819 * "tagged".
820 * @return true if this object is considered "tagged"
821 */
822 public boolean isTagged() {
823 return (flags & FLAG_TAGGED) != 0;
824 }
825
826 /**
827 * Determines if this object is considered "annotated". To be "annotated", an object
828 * must have one or more "work in progress" tags, such as "note" or "fixme".
829 * @return true if this object is considered "annotated"
830 * @since 5754
831 */
832 public boolean isAnnotated() {
833 return (flags & FLAG_ANNOTATED) != 0;
834 }
835
836 private void updateDirectionFlags() {
837 boolean hasDirections = false;
838 boolean directionReversed = false;
839 if (reversedDirectionKeys.match(this)) {
840 hasDirections = true;
841 directionReversed = true;
842 }
843 if (directionKeys.match(this)) {
844 hasDirections = true;
845 }
846
847 updateFlagsNoLock(FLAG_DIRECTION_REVERSED, directionReversed);
848 updateFlagsNoLock(FLAG_HAS_DIRECTIONS, hasDirections);
849 }
850
851 /**
852 * true if this object has direction dependent tags (e.g. oneway)
853 * @return {@code true} if this object has direction dependent tags
854 */
855 public boolean hasDirectionKeys() {
856 return (flags & FLAG_HAS_DIRECTIONS) != 0;
857 }
858
859 /**
860 * true if this object has the "reversed diretion" flag enabled
861 * @return {@code true} if this object has the "reversed diretion" flag enabled
862 */
863 public boolean reversedDirection() {
864 return (flags & FLAG_DIRECTION_REVERSED) != 0;
865 }
866
867 /*------------
868 * Keys handling
869 ------------*/
870
871 @Override
872 public final void setKeys(TagMap keys) {
873 boolean locked = writeLock();
874 try {
875 super.setKeys(keys);
876 } finally {
877 writeUnlock(locked);
878 }
879 }
880
881 @Override
882 public final void setKeys(Map<String, String> keys) {
883 boolean locked = writeLock();
884 try {
885 super.setKeys(keys);
886 } finally {
887 writeUnlock(locked);
888 }
889 }
890
891 @Override
892 public final void put(String key, String value) {
893 boolean locked = writeLock();
894 try {
895 super.put(key, value);
896 } finally {
897 writeUnlock(locked);
898 }
899 }
900
901 @Override
902 public final void remove(String key) {
903 boolean locked = writeLock();
904 try {
905 super.remove(key);
906 } finally {
907 writeUnlock(locked);
908 }
909 }
910
911 @Override
912 public final void removeAll() {
913 boolean locked = writeLock();
914 try {
915 super.removeAll();
916 } finally {
917 writeUnlock(locked);
918 }
919 }
920
921 @Override
922 protected void keysChangedImpl(Map<String, String> originalKeys) {
923 clearCachedStyle();
924 if (dataSet != null) {
925 for (OsmPrimitive ref : getReferrers()) {
926 ref.clearCachedStyle();
927 }
928 }
929 updateDirectionFlags();
930 updateTagged();
931 updateAnnotated();
932 if (dataSet != null) {
933 dataSet.fireTagsChanged(this, originalKeys);
934 }
935 }
936
937 /*------------
938 * Referrers
939 ------------*/
940
941 private Object referrers;
942
943 /**
944 * Add new referrer. If referrer is already included then no action is taken
945 * @param referrer The referrer to add
946 */
947 protected void addReferrer(OsmPrimitive referrer) {
948 if (referrers == null) {
949 referrers = referrer;
950 } else if (referrers instanceof OsmPrimitive) {
951 if (referrers != referrer) {
952 referrers = new OsmPrimitive[] {(OsmPrimitive) referrers, referrer};
953 }
954 } else {
955 for (OsmPrimitive primitive:(OsmPrimitive[]) referrers) {
956 if (primitive == referrer)
957 return;
958 }
959 referrers = Utils.addInArrayCopy((OsmPrimitive[]) referrers, referrer);
960 }
961 }
962
963 /**
964 * Remove referrer. No action is taken if referrer is not registered
965 * @param referrer The referrer to remove
966 */
967 protected void removeReferrer(OsmPrimitive referrer) {
968 if (referrers instanceof OsmPrimitive) {
969 if (referrers == referrer) {
970 referrers = null;
971 }
972 } else if (referrers instanceof OsmPrimitive[]) {
973 OsmPrimitive[] orig = (OsmPrimitive[]) referrers;
974 int idx = -1;
975 for (int i = 0; i < orig.length; i++) {
976 if (orig[i] == referrer) {
977 idx = i;
978 break;
979 }
980 }
981 if (idx == -1)
982 return;
983
984 if (orig.length == 2) {
985 referrers = orig[1-idx]; // idx is either 0 or 1, take the other
986 } else { // downsize the array
987 OsmPrimitive[] smaller = new OsmPrimitive[orig.length-1];
988 System.arraycopy(orig, 0, smaller, 0, idx);
989 System.arraycopy(orig, idx+1, smaller, idx, smaller.length-idx);
990 referrers = smaller;
991 }
992 }
993 }
994
995 /**
996 * Find primitives that reference this primitive. Returns only primitives that are included in the same
997 * dataset as this primitive. <br>
998 *
999 * For example following code will add wnew as referer to all nodes of existingWay, but this method will
1000 * not return wnew because it's not part of the dataset <br>
1001 *
1002 * <code>Way wnew = new Way(existingWay)</code>
1003 *
1004 * @param allowWithoutDataset If true, method will return empty list if primitive is not part of the dataset. If false,
1005 * exception will be thrown in this case
1006 *
1007 * @return a collection of all primitives that reference this primitive.
1008 */
1009 public final List<OsmPrimitive> getReferrers(boolean allowWithoutDataset) {
1010 // Returns only referrers that are members of the same dataset (primitive can have some fake references, for example
1011 // when way is cloned
1012
1013 if (dataSet == null && allowWithoutDataset)
1014 return Collections.emptyList();
1015
1016 checkDataset();
1017 Object referrers = this.referrers;
1018 List<OsmPrimitive> result = new ArrayList<>();
1019 if (referrers != null) {
1020 if (referrers instanceof OsmPrimitive) {
1021 OsmPrimitive ref = (OsmPrimitive) referrers;
1022 if (ref.dataSet == dataSet) {
1023 result.add(ref);
1024 }
1025 } else {
1026 for (OsmPrimitive o:(OsmPrimitive[]) referrers) {
1027 if (dataSet == o.dataSet) {
1028 result.add(o);
1029 }
1030 }
1031 }
1032 }
1033 return result;
1034 }
1035
1036 public final List<OsmPrimitive> getReferrers() {
1037 return getReferrers(false);
1038 }
1039
1040 /**
1041 * <p>Visits {@code visitor} for all referrers.</p>
1042 *
1043 * @param visitor the visitor. Ignored, if null.
1044 */
1045 public void visitReferrers(Visitor visitor) {
1046 if (visitor == null) return;
1047 if (this.referrers == null)
1048 return;
1049 else if (this.referrers instanceof OsmPrimitive) {
1050 OsmPrimitive ref = (OsmPrimitive) this.referrers;
1051 if (ref.dataSet == dataSet) {
1052 ref.accept(visitor);
1053 }
1054 } else if (this.referrers instanceof OsmPrimitive[]) {
1055 OsmPrimitive[] refs = (OsmPrimitive[]) this.referrers;
1056 for (OsmPrimitive ref: refs) {
1057 if (ref.dataSet == dataSet) {
1058 ref.accept(visitor);
1059 }
1060 }
1061 }
1062 }
1063
1064 /**
1065 Return true, if this primitive is referred by at least n ways
1066 @param n Minimal number of ways to return true. Must be positive
1067 * @return {@code true} if this primitive is referred by at least n ways
1068 */
1069 public final boolean isReferredByWays(int n) {
1070 // Count only referrers that are members of the same dataset (primitive can have some fake references, for example
1071 // when way is cloned
1072 Object referrers = this.referrers;
1073 if (referrers == null) return false;
1074 checkDataset();
1075 if (referrers instanceof OsmPrimitive)
1076 return n <= 1 && referrers instanceof Way && ((OsmPrimitive) referrers).dataSet == dataSet;
1077 else {
1078 int counter = 0;
1079 for (OsmPrimitive o : (OsmPrimitive[]) referrers) {
1080 if (dataSet == o.dataSet && o instanceof Way) {
1081 if (++counter >= n)
1082 return true;
1083 }
1084 }
1085 return false;
1086 }
1087 }
1088
1089 /*-----------------
1090 * OTHER METHODS
1091 *----------------*/
1092
1093 /**
1094 * Implementation of the visitor scheme. Subclasses have to call the correct
1095 * visitor function.
1096 * @param visitor The visitor from which the visit() function must be called.
1097 */
1098 public abstract void accept(Visitor visitor);
1099
1100 /**
1101 * Get and write all attributes from the parameter. Does not fire any listener, so
1102 * use this only in the data initializing phase
1103 * @param other other primitive
1104 */
1105 public void cloneFrom(OsmPrimitive other) {
1106 // write lock is provided by subclasses
1107 if (id != other.id && dataSet != null)
1108 throw new DataIntegrityProblemException("Osm id cannot be changed after primitive was added to the dataset");
1109
1110 super.cloneFrom(other);
1111 clearCachedStyle();
1112 }
1113
1114 /**
1115 * Merges the technical and semantical attributes from <code>other</code> onto this.
1116 *
1117 * Both this and other must be new, or both must be assigned an OSM ID. If both this and <code>other</code>
1118 * have an assigend OSM id, the IDs have to be the same.
1119 *
1120 * @param other the other primitive. Must not be null.
1121 * @throws IllegalArgumentException if other is null.
1122 * @throws DataIntegrityProblemException if either this is new and other is not, or other is new and this is not
1123 * @throws DataIntegrityProblemException if other isn't new and other.getId() != this.getId()
1124 */
1125 public void mergeFrom(OsmPrimitive other) {
1126 boolean locked = writeLock();
1127 try {
1128 CheckParameterUtil.ensureParameterNotNull(other, "other");
1129 if (other.isNew() ^ isNew())
1130 throw new DataIntegrityProblemException(
1131 tr("Cannot merge because either of the participating primitives is new and the other is not"));
1132 if (!other.isNew() && other.getId() != id)
1133 throw new DataIntegrityProblemException(
1134 tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId()));
1135
1136 setKeys(other.hasKeys() ? other.getKeys() : null);
1137 timestamp = other.timestamp;
1138 version = other.version;
1139 setIncomplete(other.isIncomplete());
1140 flags = other.flags;
1141 user = other.user;
1142 changesetId = other.changesetId;
1143 } finally {
1144 writeUnlock(locked);
1145 }
1146 }
1147
1148 /**
1149 * Replies true if other isn't null and has the same interesting tags (key/value-pairs) as this.
1150 *
1151 * @param other the other object primitive
1152 * @return true if other isn't null and has the same interesting tags (key/value-pairs) as this.
1153 */
1154 public boolean hasSameInterestingTags(OsmPrimitive other) {
1155 return (keys == null && other.keys == null)
1156 || getInterestingTags().equals(other.getInterestingTags());
1157 }
1158
1159 /**
1160 * Replies true if this primitive and other are equal with respect to their semantic attributes.
1161 * <ol>
1162 * <li>equal id</li>
1163 * <li>both are complete or both are incomplete</li>
1164 * <li>both have the same tags</li>
1165 * </ol>
1166 * @param other other primitive to compare
1167 * @return true if this primitive and other are equal with respect to their semantic attributes.
1168 */
1169 public final boolean hasEqualSemanticAttributes(OsmPrimitive other) {
1170 return hasEqualSemanticAttributes(other, true);
1171 }
1172
1173 boolean hasEqualSemanticAttributes(final OsmPrimitive other, final boolean testInterestingTagsOnly) {
1174 if (!isNew() && id != other.id)
1175 return false;
1176 if (isIncomplete() ^ other.isIncomplete()) // exclusive or operator for performance (see #7159)
1177 return false;
1178 return testInterestingTagsOnly ? hasSameInterestingTags(other) : getKeys().equals(other.getKeys());
1179 }
1180
1181 /**
1182 * Replies true if this primitive and other are equal with respect to their technical attributes.
1183 * The attributes:
1184 * <ol>
1185 * <li>deleted</li>
1186 * <li>modified</li>
1187 * <li>timestamp</li>
1188 * <li>version</li>
1189 * <li>visible</li>
1190 * <li>user</li>
1191 * </ol>
1192 * have to be equal
1193 * @param other the other primitive
1194 * @return true if this primitive and other are equal with respect to their technical attributes
1195 */
1196 public boolean hasEqualTechnicalAttributes(OsmPrimitive other) {
1197 if (other == null) return false;
1198
1199 return isDeleted() == other.isDeleted()
1200 && isModified() == other.isModified()
1201 && timestamp == other.timestamp
1202 && version == other.version
1203 && isVisible() == other.isVisible()
1204 && Objects.equals(user, other.user)
1205 && changesetId == other.changesetId;
1206 }
1207
1208 /**
1209 * Loads (clone) this primitive from provided PrimitiveData
1210 * @param data The object which should be cloned
1211 */
1212 public void load(PrimitiveData data) {
1213 // Write lock is provided by subclasses
1214 setKeys(data.hasKeys() ? data.getKeys() : null);
1215 setRawTimestamp(data.getRawTimestamp());
1216 user = data.getUser();
1217 setChangesetId(data.getChangesetId());
1218 setDeleted(data.isDeleted());
1219 setModified(data.isModified());
1220 setIncomplete(data.isIncomplete());
1221 version = data.getVersion();
1222 }
1223
1224 /**
1225 * Save parameters of this primitive to the transport object
1226 * @return The saved object data
1227 */
1228 public abstract PrimitiveData save();
1229
1230 /**
1231 * Save common parameters of primitives to the transport object
1232 * @param data The object to save the data into
1233 */
1234 protected void saveCommonAttributes(PrimitiveData data) {
1235 data.setId(id);
1236 data.setKeys(hasKeys() ? getKeys() : null);
1237 data.setRawTimestamp(getRawTimestamp());
1238 data.setUser(user);
1239 data.setDeleted(isDeleted());
1240 data.setModified(isModified());
1241 data.setVisible(isVisible());
1242 data.setIncomplete(isIncomplete());
1243 data.setChangesetId(changesetId);
1244 data.setVersion(version);
1245 }
1246
1247 /**
1248 * Fetch the bounding box of the primitive
1249 * @return Bounding box of the object
1250 */
1251 public abstract BBox getBBox();
1252
1253 /**
1254 * Called by Dataset to update cached position information of primitive (bbox, cached EarthNorth, ...)
1255 */
1256 public abstract void updatePosition();
1257
1258 /*----------------
1259 * OBJECT METHODS
1260 *---------------*/
1261
1262 @Override
1263 protected String getFlagsAsString() {
1264 StringBuilder builder = new StringBuilder(super.getFlagsAsString());
1265
1266 if (isDisabled()) {
1267 if (isDisabledAndHidden()) {
1268 builder.append('h');
1269 } else {
1270 builder.append('d');
1271 }
1272 }
1273 if (isTagged()) {
1274 builder.append('T');
1275 }
1276 if (hasDirectionKeys()) {
1277 if (reversedDirection()) {
1278 builder.append('<');
1279 } else {
1280 builder.append('>');
1281 }
1282 }
1283 return builder.toString();
1284 }
1285
1286 /**
1287 * Equal, if the id (and class) is equal.
1288 *
1289 * An primitive is equal to its incomplete counter part.
1290 */
1291 @Override
1292 public boolean equals(Object obj) {
1293 if (this == obj) {
1294 return true;
1295 } else if (obj == null || getClass() != obj.getClass()) {
1296 return false;
1297 } else {
1298 OsmPrimitive that = (OsmPrimitive) obj;
1299 return id == that.id;
1300 }
1301 }
1302
1303 /**
1304 * Return the id plus the class type encoded as hashcode or super's hashcode if id is 0.
1305 *
1306 * An primitive has the same hashcode as its incomplete counterpart.
1307 */
1308 @Override
1309 public int hashCode() {
1310 return Long.hashCode(id);
1311 }
1312
1313 /**
1314 * Replies the display name of a primitive formatted by <code>formatter</code>
1315 * @param formatter formatter to use
1316 *
1317 * @return the display name
1318 */
1319 public abstract String getDisplayName(NameFormatter formatter);
1320
1321 @Override
1322 public Collection<String> getTemplateKeys() {
1323 Collection<String> keySet = keySet();
1324 List<String> result = new ArrayList<>(keySet.size() + 2);
1325 result.add(SPECIAL_VALUE_ID);
1326 result.add(SPECIAL_VALUE_LOCAL_NAME);
1327 result.addAll(keySet);
1328 return result;
1329 }
1330
1331 @Override
1332 public Object getTemplateValue(String name, boolean special) {
1333 if (special) {
1334 String lc = name.toLowerCase(Locale.ENGLISH);
1335 if (SPECIAL_VALUE_ID.equals(lc))
1336 return getId();
1337 else if (SPECIAL_VALUE_LOCAL_NAME.equals(lc))
1338 return getLocalName();
1339 else
1340 return null;
1341
1342 } else
1343 return getIgnoreCase(name);
1344 }
1345
1346 @Override
1347 public boolean evaluateCondition(Match condition) {
1348 return condition.match(this);
1349 }
1350
1351 /**
1352 * Replies the set of referring relations
1353 * @param primitives primitives to fetch relations from
1354 *
1355 * @return the set of referring relations
1356 */
1357 public static Set<Relation> getParentRelations(Collection<? extends OsmPrimitive> primitives) {
1358 Set<Relation> ret = new HashSet<>();
1359 for (OsmPrimitive w : primitives) {
1360 ret.addAll(OsmPrimitive.getFilteredList(w.getReferrers(), Relation.class));
1361 }
1362 return ret;
1363 }
1364
1365 /**
1366 * Determines if this primitive has tags denoting an area.
1367 * @return {@code true} if this primitive has tags denoting an area, {@code false} otherwise.
1368 * @since 6491
1369 */
1370 public final boolean hasAreaTags() {
1371 return hasKey("landuse")
1372 || "yes".equals(get("area"))
1373 || "riverbank".equals(get("waterway"))
1374 || hasKey("natural")
1375 || hasKey("amenity")
1376 || hasKey("leisure")
1377 || hasKey("building")
1378 || hasKey("building:part");
1379 }
1380
1381 /**
1382 * Determines if this primitive semantically concerns an area.
1383 * @return {@code true} if this primitive semantically concerns an area, according to its type, geometry and tags, {@code false} otherwise.
1384 * @since 6491
1385 */
1386 public abstract boolean concernsArea();
1387
1388 /**
1389 * Tests if this primitive lies outside of the downloaded area of its {@link DataSet}.
1390 * @return {@code true} if this primitive lies outside of the downloaded area
1391 */
1392 public abstract boolean isOutsideDownloadArea();
1393
1394 /**
1395 * Determines if this object is a relation and behaves as a multipolygon.
1396 * @return {@code true} if it is a real mutlipolygon or a boundary relation
1397 * @since 10716
1398 */
1399 public boolean isMultipolygon() {
1400 return false;
1401 }
1402}
Note: See TracBrowser for help on using the repository browser.