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

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

convention - An open curly brace should be located at the end of a line

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