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