001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.mappaint.mapcss;
003
004import java.lang.reflect.Method;
005import java.text.MessageFormat;
006import java.util.Arrays;
007import java.util.EnumSet;
008import java.util.Map;
009import java.util.Objects;
010import java.util.Set;
011import java.util.function.BiFunction;
012import java.util.function.IntFunction;
013import java.util.function.Predicate;
014import java.util.regex.Pattern;
015import java.util.regex.PatternSyntaxException;
016
017import org.openstreetmap.josm.data.osm.Node;
018import org.openstreetmap.josm.data.osm.OsmPrimitive;
019import org.openstreetmap.josm.data.osm.OsmUtils;
020import org.openstreetmap.josm.data.osm.Relation;
021import org.openstreetmap.josm.data.osm.Tag;
022import org.openstreetmap.josm.data.osm.Way;
023import org.openstreetmap.josm.data.osm.search.SearchCompiler.InDataSourceArea;
024import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
025import org.openstreetmap.josm.gui.mappaint.Cascade;
026import org.openstreetmap.josm.gui.mappaint.ElemStyles;
027import org.openstreetmap.josm.gui.mappaint.Environment;
028import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.Context;
029import org.openstreetmap.josm.gui.mappaint.mapcss.Condition.ToTagConvertable;
030import org.openstreetmap.josm.tools.CheckParameterUtil;
031import org.openstreetmap.josm.tools.JosmRuntimeException;
032import org.openstreetmap.josm.tools.Utils;
033
034/**
035 * Factory to generate {@link Condition}s.
036 * @since 10837 (Extracted from Condition)
037 */
038public final class ConditionFactory {
039
040    private ConditionFactory() {
041        // Hide default constructor for utils classes
042    }
043
044    /**
045     * Create a new condition that checks the key and the value of the object.
046     * @param k The key.
047     * @param v The reference value
048     * @param op The operation to use when comparing the value
049     * @param context The type of context to use.
050     * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
051     * @return The new condition.
052     * @throws MapCSSException if the arguments are incorrect
053     */
054    public static Condition createKeyValueCondition(String k, String v, Op op, Context context, boolean considerValAsKey) {
055        switch (context) {
056        case PRIMITIVE:
057            if (KeyValueRegexpCondition.SUPPORTED_OPS.contains(op) && !considerValAsKey) {
058                try {
059                    return new KeyValueRegexpCondition(k, v, op, false);
060                } catch (PatternSyntaxException e) {
061                    throw new MapCSSException(e);
062                }
063            }
064            if (!considerValAsKey && op.equals(Op.EQ))
065                return new SimpleKeyValueCondition(k, v);
066            return new KeyValueCondition(k, v, op, considerValAsKey);
067        case LINK:
068            if (considerValAsKey)
069                throw new MapCSSException("''considerValAsKey'' not supported in LINK context");
070            if ("role".equalsIgnoreCase(k))
071                return new RoleCondition(v, op);
072            else if ("index".equalsIgnoreCase(k))
073                return new IndexCondition(v, op);
074            else
075                throw new MapCSSException(
076                        MessageFormat.format("Expected key ''role'' or ''index'' in link context. Got ''{0}''.", k));
077
078        default: throw new AssertionError();
079        }
080    }
081
082    /**
083     * Create a condition in which the key and the value need to match a given regexp
084     * @param k The key regexp
085     * @param v The value regexp
086     * @param op The operation to use when comparing the key and the value.
087     * @return The new condition.
088     */
089    public static Condition createRegexpKeyRegexpValueCondition(String k, String v, Op op) {
090        return new RegexpKeyValueRegexpCondition(k, v, op);
091    }
092
093    /**
094     * Creates a condition that checks the given key.
095     * @param k The key to test for
096     * @param not <code>true</code> to invert the match
097     * @param matchType The match type to check for.
098     * @param context The context this rule is found in.
099     * @return the new condition.
100     */
101    public static Condition createKeyCondition(String k, boolean not, KeyMatchType matchType, Context context) {
102        switch (context) {
103        case PRIMITIVE:
104            return new KeyCondition(k, not, matchType);
105        case LINK:
106            if (matchType != null)
107                throw new MapCSSException("Question mark operator ''?'' and regexp match not supported in LINK context");
108            if (not)
109                return new RoleCondition(k, Op.NEQ);
110            else
111                return new RoleCondition(k, Op.EQ);
112
113        default: throw new AssertionError();
114        }
115    }
116
117    /**
118     * Create a new pseudo class condition
119     * @param id The id of the pseudo class
120     * @param not <code>true</code> to invert the condition
121     * @param context The context the class is found in.
122     * @return The new condition
123     */
124    public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
125        return PseudoClassCondition.createPseudoClassCondition(id, not, context);
126    }
127
128    /**
129     * Create a new class condition
130     * @param id The id of the class to match
131     * @param not <code>true</code> to invert the condition
132     * @param context Ignored
133     * @return The new condition
134     */
135    public static ClassCondition createClassCondition(String id, boolean not, Context context) {
136        return new ClassCondition(id, not);
137    }
138
139    /**
140     * Create a new condition that a expression needs to be fulfilled
141     * @param e the expression to check
142     * @param context Ignored
143     * @return The new condition
144     */
145    public static ExpressionCondition createExpressionCondition(Expression e, Context context) {
146        return new ExpressionCondition(e);
147    }
148
149    /**
150     * This is the operation that {@link KeyValueCondition} uses to match.
151     */
152    public enum Op {
153        /** The value equals the given reference. */
154        EQ(Objects::equals),
155        /** The value does not equal the reference. */
156        NEQ(EQ),
157        /** The value is greater than or equal to the given reference value (as float). */
158        GREATER_OR_EQUAL(comparisonResult -> comparisonResult >= 0),
159        /** The value is greater than the given reference value (as float). */
160        GREATER(comparisonResult -> comparisonResult > 0),
161        /** The value is less than or equal to the given reference value (as float). */
162        LESS_OR_EQUAL(comparisonResult -> comparisonResult <= 0),
163        /** The value is less than the given reference value (as float). */
164        LESS(comparisonResult -> comparisonResult < 0),
165        /** The reference is treated as regular expression and the value needs to match it. */
166        REGEX((test, prototype) -> Pattern.compile(prototype).matcher(test).find()),
167        /** The reference is treated as regular expression and the value needs to not match it. */
168        NREGEX(REGEX),
169        /** The reference is treated as a list separated by ';'. Spaces around the ; are ignored.
170         *  The value needs to be equal one of the list elements. */
171        ONE_OF((test, prototype) -> Arrays.asList(test.split("\\s*;\\s*")).contains(prototype)),
172        /** The value needs to begin with the reference string. */
173        BEGINS_WITH(String::startsWith),
174        /** The value needs to end with the reference string. */
175        ENDS_WITH(String::endsWith),
176        /** The value needs to contain the reference string. */
177        CONTAINS(String::contains);
178
179        static final Set<Op> NEGATED_OPS = EnumSet.of(NEQ, NREGEX);
180
181        private final BiFunction<String, String, Boolean> function;
182
183        private final boolean negated;
184
185        /**
186         * Create a new string operation.
187         * @param func The function to apply during {@link #eval(String, String)}.
188         */
189        Op(BiFunction<String, String, Boolean> func) {
190            this.function = func;
191            negated = false;
192        }
193
194        /**
195         * Create a new float operation that compares two float values
196         * @param comparatorResult A function to mapt the result of the comparison
197         */
198        Op(IntFunction<Boolean> comparatorResult) {
199            this.function = (test, prototype) -> {
200                float testFloat;
201                try {
202                    testFloat = Float.parseFloat(test);
203                } catch (NumberFormatException e) {
204                    return Boolean.FALSE;
205                }
206                float prototypeFloat = Float.parseFloat(prototype);
207
208                int res = Float.compare(testFloat, prototypeFloat);
209                return comparatorResult.apply(res);
210            };
211            negated = false;
212        }
213
214        /**
215         * Create a new Op by negating an other op.
216         * @param negate inverse operation
217         */
218        Op(Op negate) {
219            this.function = (a, b) -> !negate.function.apply(a, b);
220            negated = true;
221        }
222
223        /**
224         * Evaluates a value against a reference string.
225         * @param testString The value. May be <code>null</code>
226         * @param prototypeString The reference string-
227         * @return <code>true</code> if and only if this operation matches for the given value/reference pair.
228         */
229        public boolean eval(String testString, String prototypeString) {
230            if (testString == null)
231                return negated;
232            else
233                return function.apply(testString, prototypeString);
234        }
235    }
236
237    /**
238     * Most common case of a KeyValueCondition, this is the basic key=value case.
239     *
240     * Extra class for performance reasons.
241     */
242    public static class SimpleKeyValueCondition implements Condition, ToTagConvertable {
243        /**
244         * The key to search for.
245         */
246        public final String k;
247        /**
248         * The value to search for.
249         */
250        public final String v;
251
252        /**
253         * Create a new SimpleKeyValueCondition.
254         * @param k The key
255         * @param v The value.
256         */
257        public SimpleKeyValueCondition(String k, String v) {
258            this.k = k;
259            this.v = v;
260        }
261
262        @Override
263        public boolean applies(Environment e) {
264            return v.equals(e.osm.get(k));
265        }
266
267        @Override
268        public Tag asTag(OsmPrimitive primitive) {
269            return new Tag(k, v);
270        }
271
272        @Override
273        public String toString() {
274            return '[' + k + '=' + v + ']';
275        }
276
277    }
278
279    /**
280     * <p>Represents a key/value condition which is either applied to a primitive.</p>
281     *
282     */
283    public static class KeyValueCondition implements Condition, ToTagConvertable {
284        /**
285         * The key to search for.
286         */
287        public final String k;
288        /**
289         * The value to search for.
290         */
291        public final String v;
292        /**
293         * The key/value match operation.
294         */
295        public final Op op;
296        /**
297         * If this flag is set, {@link #v} is treated as a key and the value is the value set for that key.
298         */
299        public final boolean considerValAsKey;
300
301        /**
302         * <p>Creates a key/value-condition.</p>
303         *
304         * @param k the key
305         * @param v the value
306         * @param op the operation
307         * @param considerValAsKey whether to consider {@code v} as another key and compare the values of key {@code k} and key {@code v}.
308         */
309        public KeyValueCondition(String k, String v, Op op, boolean considerValAsKey) {
310            this.k = k;
311            this.v = v;
312            this.op = op;
313            this.considerValAsKey = considerValAsKey;
314        }
315
316        @Override
317        public boolean applies(Environment env) {
318            return op.eval(env.osm.get(k), considerValAsKey ? env.osm.get(v) : v);
319        }
320
321        @Override
322        public Tag asTag(OsmPrimitive primitive) {
323            return new Tag(k, v);
324        }
325
326        @Override
327        public String toString() {
328            return '[' + k + '\'' + op + '\'' + v + ']';
329        }
330    }
331
332    /**
333     * This condition requires a fixed key to match a given regexp
334     */
335    public static class KeyValueRegexpCondition extends KeyValueCondition {
336        protected static final Set<Op> SUPPORTED_OPS = EnumSet.of(Op.REGEX, Op.NREGEX);
337
338        final Pattern pattern;
339
340        /**
341         * Constructs a new {@code KeyValueRegexpCondition}.
342         * @param k key
343         * @param v value
344         * @param op operation
345         * @param considerValAsKey must be false
346         * @throws PatternSyntaxException if the value syntax is invalid
347         */
348        public KeyValueRegexpCondition(String k, String v, Op op, boolean considerValAsKey) {
349            super(k, v, op, considerValAsKey);
350            CheckParameterUtil.ensureThat(!considerValAsKey, "considerValAsKey is not supported");
351            CheckParameterUtil.ensureThat(SUPPORTED_OPS.contains(op), "Op must be REGEX or NREGEX");
352            this.pattern = Pattern.compile(v);
353        }
354
355        protected boolean matches(Environment env) {
356            final String value = env.osm.get(k);
357            return value != null && pattern.matcher(value).find();
358        }
359
360        @Override
361        public boolean applies(Environment env) {
362            if (Op.REGEX.equals(op)) {
363                return matches(env);
364            } else if (Op.NREGEX.equals(op)) {
365                return !matches(env);
366            } else {
367                throw new IllegalStateException();
368            }
369        }
370    }
371
372    /**
373     * A condition that checks that a key with the matching pattern has a value with the matching pattern.
374     */
375    public static class RegexpKeyValueRegexpCondition extends KeyValueRegexpCondition {
376
377        final Pattern keyPattern;
378
379        /**
380         * Create a condition in which the key and the value need to match a given regexp
381         * @param k The key regexp
382         * @param v The value regexp
383         * @param op The operation to use when comparing the key and the value.
384         */
385        public RegexpKeyValueRegexpCondition(String k, String v, Op op) {
386            super(k, v, op, false);
387            this.keyPattern = Pattern.compile(k);
388        }
389
390        @Override
391        protected boolean matches(Environment env) {
392            for (Map.Entry<String, String> kv: env.osm.getKeys().entrySet()) {
393                if (keyPattern.matcher(kv.getKey()).find() && pattern.matcher(kv.getValue()).find()) {
394                    return true;
395                }
396            }
397            return false;
398        }
399    }
400
401    /**
402     * Role condition.
403     */
404    public static class RoleCondition implements Condition {
405        final String role;
406        final Op op;
407
408        /**
409         * Constructs a new {@code RoleCondition}.
410         * @param role role
411         * @param op operation
412         */
413        public RoleCondition(String role, Op op) {
414            this.role = role;
415            this.op = op;
416        }
417
418        @Override
419        public boolean applies(Environment env) {
420            String testRole = env.getRole();
421            if (testRole == null) return false;
422            return op.eval(testRole, role);
423        }
424    }
425
426    /**
427     * Index condition.
428     */
429    public static class IndexCondition implements Condition {
430        final String index;
431        final Op op;
432
433        /**
434         * Constructs a new {@code IndexCondition}.
435         * @param index index
436         * @param op operation
437         */
438        public IndexCondition(String index, Op op) {
439            this.index = index;
440            this.op = op;
441        }
442
443        @Override
444        public boolean applies(Environment env) {
445            if (env.index == null) return false;
446            if (index.startsWith("-")) {
447                return env.count != null && op.eval(Integer.toString(env.index - env.count), index);
448            } else {
449                return op.eval(Integer.toString(env.index + 1), index);
450            }
451        }
452    }
453
454    /**
455     * This defines how {@link KeyCondition} matches a given key.
456     */
457    public enum KeyMatchType {
458        /**
459         * The key needs to be equal to the given label.
460         */
461        EQ,
462        /**
463         * The key needs to have a true value (yes, ...)
464         * @see OsmUtils#isTrue(String)
465         */
466        TRUE,
467        /**
468         * The key needs to have a false value (no, ...)
469         * @see OsmUtils#isFalse(String)
470         */
471        FALSE,
472        /**
473         * The key needs to match the given regular expression.
474         */
475        REGEX
476    }
477
478    /**
479     * <p>KeyCondition represent one of the following conditions in either the link or the
480     * primitive context:</p>
481     * <pre>
482     *     ["a label"]  PRIMITIVE:   the primitive has a tag "a label"
483     *                  LINK:        the parent is a relation and it has at least one member with the role
484     *                               "a label" referring to the child
485     *
486     *     [!"a label"]  PRIMITIVE:  the primitive doesn't have a tag "a label"
487     *                   LINK:       the parent is a relation but doesn't have a member with the role
488     *                               "a label" referring to the child
489     *
490     *     ["a label"?]  PRIMITIVE:  the primitive has a tag "a label" whose value evaluates to a true-value
491     *                   LINK:       not supported
492     *
493     *     ["a label"?!] PRIMITIVE:  the primitive has a tag "a label" whose value evaluates to a false-value
494     *                   LINK:       not supported
495     * </pre>
496     */
497    public static class KeyCondition implements Condition, ToTagConvertable {
498
499        /**
500         * The key name.
501         */
502        public final String label;
503        /**
504         * If we should negate the result of the match.
505         */
506        public final boolean negateResult;
507        /**
508         * Describes how to match the label against the key.
509         * @see KeyMatchType
510         */
511        public final KeyMatchType matchType;
512        /**
513         * A predicate used to match a the regexp against the key. Only used if the match type is regexp.
514         */
515        public final Predicate<String> containsPattern;
516
517        /**
518         * Creates a new KeyCondition
519         * @param label The key name (or regexp) to use.
520         * @param negateResult If we should negate the result.,
521         * @param matchType The match type.
522         */
523        public KeyCondition(String label, boolean negateResult, KeyMatchType matchType) {
524            this.label = label;
525            this.negateResult = negateResult;
526            this.matchType = matchType == null ? KeyMatchType.EQ : matchType;
527            this.containsPattern = KeyMatchType.REGEX.equals(matchType)
528                    ? Pattern.compile(label).asPredicate()
529                    : null;
530        }
531
532        @Override
533        public boolean applies(Environment e) {
534            switch(e.getContext()) {
535            case PRIMITIVE:
536                switch (matchType) {
537                case TRUE:
538                    return e.osm.isKeyTrue(label) ^ negateResult;
539                case FALSE:
540                    return e.osm.isKeyFalse(label) ^ negateResult;
541                case REGEX:
542                    return e.osm.keySet().stream().anyMatch(containsPattern) ^ negateResult;
543                default:
544                    return e.osm.hasKey(label) ^ negateResult;
545                }
546            case LINK:
547                Utils.ensure(false, "Illegal state: KeyCondition not supported in LINK context");
548                return false;
549            default: throw new AssertionError();
550            }
551        }
552
553        /**
554         * Get the matched key and the corresponding value.
555         * <p>
556         * WARNING: This ignores {@link #negateResult}.
557         * <p>
558         * WARNING: For regexp, the regular expression is returned instead of a key if the match failed.
559         * @param p The primitive to get the value from.
560         * @return The tag.
561         */
562        @Override
563        public Tag asTag(OsmPrimitive p) {
564            String key = label;
565            if (KeyMatchType.REGEX.equals(matchType)) {
566                key = p.keySet().stream().filter(containsPattern).findAny().orElse(key);
567            }
568            return new Tag(key, p.get(key));
569        }
570
571        @Override
572        public String toString() {
573            return '[' + (negateResult ? "!" : "") + label + ']';
574        }
575    }
576
577    /**
578     * Class condition.
579     */
580    public static class ClassCondition implements Condition {
581
582        /** Class identifier */
583        public final String id;
584        final boolean not;
585
586        /**
587         * Constructs a new {@code ClassCondition}.
588         * @param id id
589         * @param not negation or not
590         */
591        public ClassCondition(String id, boolean not) {
592            this.id = id;
593            this.not = not;
594        }
595
596        @Override
597        public boolean applies(Environment env) {
598            Cascade cascade = env.getCascade(env.layer);
599            return cascade != null && (not ^ cascade.containsKey(id));
600        }
601
602        @Override
603        public String toString() {
604            return (not ? "!" : "") + '.' + id;
605        }
606    }
607
608    /**
609     * Like <a href="http://www.w3.org/TR/css3-selectors/#pseudo-classes">CSS pseudo classes</a>, MapCSS pseudo classes
610     * are written in lower case with dashes between words.
611     */
612    public static final class PseudoClasses {
613
614        private PseudoClasses() {
615            // Hide default constructor for utilities classes
616        }
617
618        /**
619         * {@code closed} tests whether the way is closed or the relation is a closed multipolygon
620         * @param e MapCSS environment
621         * @return {@code true} if the way is closed or the relation is a closed multipolygon
622         */
623        static boolean closed(Environment e) { // NO_UCD (unused code)
624            if (e.osm instanceof Way && ((Way) e.osm).isClosed())
625                return true;
626            return e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon();
627        }
628
629        /**
630         * {@code :modified} tests whether the object has been modified.
631         * @param e MapCSS environment
632         * @return {@code true} if the object has been modified
633         * @see OsmPrimitive#isModified()
634         */
635        static boolean modified(Environment e) { // NO_UCD (unused code)
636            return e.osm.isModified() || e.osm.isNewOrUndeleted();
637        }
638
639        /**
640         * {@code ;new} tests whether the object is new.
641         * @param e MapCSS environment
642         * @return {@code true} if the object is new
643         * @see OsmPrimitive#isNew()
644         */
645        static boolean _new(Environment e) { // NO_UCD (unused code)
646            return e.osm.isNew();
647        }
648
649        /**
650         * {@code :connection} tests whether the object is a connection node.
651         * @param e MapCSS environment
652         * @return {@code true} if the object is a connection node
653         * @see Node#isConnectionNode()
654         */
655        static boolean connection(Environment e) { // NO_UCD (unused code)
656            return e.osm instanceof Node && e.osm.getDataSet() != null && ((Node) e.osm).isConnectionNode();
657        }
658
659        /**
660         * {@code :tagged} tests whether the object is tagged.
661         * @param e MapCSS environment
662         * @return {@code true} if the object is tagged
663         * @see OsmPrimitive#isTagged()
664         */
665        static boolean tagged(Environment e) { // NO_UCD (unused code)
666            return e.osm.isTagged();
667        }
668
669        /**
670         * {@code :same-tags} tests whether the object has the same tags as its child/parent.
671         * @param e MapCSS environment
672         * @return {@code true} if the object has the same tags as its child/parent
673         * @see OsmPrimitive#hasSameInterestingTags(OsmPrimitive)
674         */
675        static boolean sameTags(Environment e) { // NO_UCD (unused code)
676            return e.osm.hasSameInterestingTags(Utils.firstNonNull(e.child, e.parent));
677        }
678
679        /**
680         * {@code :area-style} tests whether the object has an area style. This is useful for validators.
681         * @param e MapCSS environment
682         * @return {@code true} if the object has an area style
683         * @see ElemStyles#hasAreaElemStyle(OsmPrimitive, boolean)
684         */
685        static boolean areaStyle(Environment e) { // NO_UCD (unused code)
686            // only for validator
687            return ElemStyles.hasAreaElemStyle(e.osm, false);
688        }
689
690        /**
691         * {@code unconnected}: tests whether the object is a unconnected node.
692         * @param e MapCSS environment
693         * @return {@code true} if the object is a unconnected node
694         */
695        static boolean unconnected(Environment e) { // NO_UCD (unused code)
696            return e.osm instanceof Node && ((Node) e.osm).getParentWays().isEmpty();
697        }
698
699        /**
700         * {@code righthandtraffic} checks if there is right-hand traffic at the current location.
701         * @param e MapCSS environment
702         * @return {@code true} if there is right-hand traffic at the current location
703         * @see ExpressionFactory.Functions#is_right_hand_traffic(Environment)
704         */
705        static boolean righthandtraffic(Environment e) { // NO_UCD (unused code)
706            return ExpressionFactory.Functions.is_right_hand_traffic(e);
707        }
708
709        /**
710         * {@code clockwise} whether the way is closed and oriented clockwise,
711         * or non-closed and the 1st, 2nd and last node are in clockwise order.
712         * @param e MapCSS environment
713         * @return {@code true} if the way clockwise
714         * @see ExpressionFactory.Functions#is_clockwise(Environment)
715         */
716        static boolean clockwise(Environment e) { // NO_UCD (unused code)
717            return ExpressionFactory.Functions.is_clockwise(e);
718        }
719
720        /**
721         * {@code anticlockwise} whether the way is closed and oriented anticlockwise,
722         * or non-closed and the 1st, 2nd and last node are in anticlockwise order.
723         * @param e MapCSS environment
724         * @return {@code true} if the way clockwise
725         * @see ExpressionFactory.Functions#is_anticlockwise(Environment)
726         */
727        static boolean anticlockwise(Environment e) { // NO_UCD (unused code)
728            return ExpressionFactory.Functions.is_anticlockwise(e);
729        }
730
731        /**
732         * {@code unclosed-multipolygon} tests whether the object is an unclosed multipolygon.
733         * @param e MapCSS environment
734         * @return {@code true} if the object is an unclosed multipolygon
735         */
736        static boolean unclosed_multipolygon(Environment e) { // NO_UCD (unused code)
737            return e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() &&
738                    !e.osm.isIncomplete() && !((Relation) e.osm).hasIncompleteMembers() &&
739                    !MultipolygonCache.getInstance().get((Relation) e.osm).getOpenEnds().isEmpty();
740        }
741
742        private static final Predicate<OsmPrimitive> IN_DOWNLOADED_AREA = new InDataSourceArea(false);
743
744        /**
745         * {@code in-downloaded-area} tests whether the object is within source area ("downloaded area").
746         * @param e MapCSS environment
747         * @return {@code true} if the object is within source area ("downloaded area")
748         * @see InDataSourceArea
749         */
750        static boolean inDownloadedArea(Environment e) { // NO_UCD (unused code)
751            return IN_DOWNLOADED_AREA.test(e.osm);
752        }
753
754        static boolean completely_downloaded(Environment e) { // NO_UCD (unused code)
755            if (e.osm instanceof Relation) {
756                return !((Relation) e.osm).hasIncompleteMembers();
757            } else {
758                return true;
759            }
760        }
761
762        static boolean closed2(Environment e) { // NO_UCD (unused code)
763            if (e.osm instanceof Way && ((Way) e.osm).isClosed())
764                return true;
765            if (e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon())
766                return MultipolygonCache.getInstance().get((Relation) e.osm).getOpenEnds().isEmpty();
767            return false;
768        }
769
770        static boolean selected(Environment e) { // NO_UCD (unused code)
771            if (e.mc != null) {
772                e.mc.getCascade(e.layer).setDefaultSelectedHandling(false);
773            }
774            return e.osm.isSelected();
775        }
776    }
777
778    /**
779     * Pseudo class condition.
780     */
781    public static class PseudoClassCondition implements Condition {
782
783        final Method method;
784        final boolean not;
785
786        protected PseudoClassCondition(Method method, boolean not) {
787            this.method = method;
788            this.not = not;
789        }
790
791        /**
792         * Create a new pseudo class condition
793         * @param id The id of the pseudo class
794         * @param not <code>true</code> to invert the condition
795         * @param context The context the class is found in.
796         * @return The new condition
797         */
798        public static PseudoClassCondition createPseudoClassCondition(String id, boolean not, Context context) {
799            CheckParameterUtil.ensureThat(!"sameTags".equals(id) || Context.LINK.equals(context), "sameTags only supported in LINK context");
800            if ("open_end".equals(id)) {
801                return new OpenEndPseudoClassCondition(not);
802            }
803            final Method method = getMethod(id);
804            if (method != null) {
805                return new PseudoClassCondition(method, not);
806            }
807            throw new MapCSSException("Invalid pseudo class specified: " + id);
808        }
809
810        protected static Method getMethod(String id) {
811            String cleanId = id.replaceAll("-|_", "");
812            for (Method method : PseudoClasses.class.getDeclaredMethods()) {
813                // for backwards compatibility, consider :sameTags == :same-tags == :same_tags (#11150)
814                final String methodName = method.getName().replaceAll("-|_", "");
815                if (methodName.equalsIgnoreCase(cleanId)) {
816                    return method;
817                }
818            }
819            return null;
820        }
821
822        @Override
823        public boolean applies(Environment e) {
824            try {
825                return not ^ (Boolean) method.invoke(null, e);
826            } catch (ReflectiveOperationException ex) {
827                throw new JosmRuntimeException(ex);
828            }
829        }
830
831        @Override
832        public String toString() {
833            return (not ? "!" : "") + ':' + method.getName();
834        }
835    }
836
837    /**
838     * Open end pseudo class condition.
839     */
840    public static class OpenEndPseudoClassCondition extends PseudoClassCondition {
841        /**
842         * Constructs a new {@code OpenEndPseudoClassCondition}.
843         * @param not negation or not
844         */
845        public OpenEndPseudoClassCondition(boolean not) {
846            super(null, not);
847        }
848
849        @Override
850        public boolean applies(Environment e) {
851            return true;
852        }
853    }
854
855    /**
856     * A condition that is fulfilled whenever the expression is evaluated to be true.
857     */
858    public static class ExpressionCondition implements Condition {
859
860        final Expression e;
861
862        /**
863         * Constructs a new {@code ExpressionFactory}
864         * @param e expression
865         */
866        public ExpressionCondition(Expression e) {
867            this.e = e;
868        }
869
870        @Override
871        public boolean applies(Environment env) {
872            Boolean b = Cascade.convertTo(e.evaluate(env), Boolean.class);
873            return b != null && b;
874        }
875
876        @Override
877        public String toString() {
878            return '[' + e.toString() + ']';
879        }
880    }
881}