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

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

fix #8951 - fix clearing of primitive metadata

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