source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/ExpressionFactory.java@ 11247

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

see #9400 - see #10387 - see #12914 - initial implementation of boundaries file, replacing left-right-hand-traffic.osm, discourage contributors to use operator=RFF and operator=ERDF in France (territories rules must be manually eabled on existing installations)

  • Property svn:eol-style set to native
File size: 50.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint.mapcss;
3
4import java.awt.Color;
5import java.lang.annotation.ElementType;
6import java.lang.annotation.Retention;
7import java.lang.annotation.RetentionPolicy;
8import java.lang.annotation.Target;
9import java.lang.reflect.Array;
10import java.lang.reflect.InvocationTargetException;
11import java.lang.reflect.Method;
12import java.nio.charset.StandardCharsets;
13import java.util.ArrayList;
14import java.util.Arrays;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.List;
18import java.util.Locale;
19import java.util.Objects;
20import java.util.Set;
21import java.util.TreeSet;
22import java.util.function.Function;
23import java.util.regex.Matcher;
24import java.util.regex.Pattern;
25import java.util.zip.CRC32;
26
27import org.openstreetmap.josm.Main;
28import org.openstreetmap.josm.actions.search.SearchCompiler;
29import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
30import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
31import org.openstreetmap.josm.data.coor.LatLon;
32import org.openstreetmap.josm.data.osm.Node;
33import org.openstreetmap.josm.data.osm.OsmPrimitive;
34import org.openstreetmap.josm.data.osm.Way;
35import org.openstreetmap.josm.gui.mappaint.Cascade;
36import org.openstreetmap.josm.gui.mappaint.Environment;
37import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
38import org.openstreetmap.josm.gui.util.RotationAngle;
39import org.openstreetmap.josm.io.XmlWriter;
40import org.openstreetmap.josm.tools.AlphanumComparator;
41import org.openstreetmap.josm.tools.ColorHelper;
42import org.openstreetmap.josm.tools.Geometry;
43import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
44import org.openstreetmap.josm.tools.SubclassFilteredCollection;
45import org.openstreetmap.josm.tools.Territories;
46import org.openstreetmap.josm.tools.Utils;
47
48/**
49 * Factory to generate {@link Expression}s.
50 * <p>
51 * See {@link #createFunctionExpression}.
52 */
53public final class ExpressionFactory {
54
55 /**
56 * Marks functions which should be executed also when one or more arguments are null.
57 */
58 @Target(ElementType.METHOD)
59 @Retention(RetentionPolicy.RUNTIME)
60 static @interface NullableArguments {}
61
62 private static final List<Method> arrayFunctions = new ArrayList<>();
63 private static final List<Method> parameterFunctions = new ArrayList<>();
64 private static final List<Method> parameterFunctionsEnv = new ArrayList<>();
65
66 static {
67 for (Method m : Functions.class.getDeclaredMethods()) {
68 Class<?>[] paramTypes = m.getParameterTypes();
69 if (paramTypes.length == 1 && paramTypes[0].isArray()) {
70 arrayFunctions.add(m);
71 } else if (paramTypes.length >= 1 && paramTypes[0].equals(Environment.class)) {
72 parameterFunctionsEnv.add(m);
73 } else {
74 parameterFunctions.add(m);
75 }
76 }
77 try {
78 parameterFunctions.add(Math.class.getMethod("abs", float.class));
79 parameterFunctions.add(Math.class.getMethod("acos", double.class));
80 parameterFunctions.add(Math.class.getMethod("asin", double.class));
81 parameterFunctions.add(Math.class.getMethod("atan", double.class));
82 parameterFunctions.add(Math.class.getMethod("atan2", double.class, double.class));
83 parameterFunctions.add(Math.class.getMethod("ceil", double.class));
84 parameterFunctions.add(Math.class.getMethod("cos", double.class));
85 parameterFunctions.add(Math.class.getMethod("cosh", double.class));
86 parameterFunctions.add(Math.class.getMethod("exp", double.class));
87 parameterFunctions.add(Math.class.getMethod("floor", double.class));
88 parameterFunctions.add(Math.class.getMethod("log", double.class));
89 parameterFunctions.add(Math.class.getMethod("max", float.class, float.class));
90 parameterFunctions.add(Math.class.getMethod("min", float.class, float.class));
91 parameterFunctions.add(Math.class.getMethod("random"));
92 parameterFunctions.add(Math.class.getMethod("round", float.class));
93 parameterFunctions.add(Math.class.getMethod("signum", double.class));
94 parameterFunctions.add(Math.class.getMethod("sin", double.class));
95 parameterFunctions.add(Math.class.getMethod("sinh", double.class));
96 parameterFunctions.add(Math.class.getMethod("sqrt", double.class));
97 parameterFunctions.add(Math.class.getMethod("tan", double.class));
98 parameterFunctions.add(Math.class.getMethod("tanh", double.class));
99 } catch (NoSuchMethodException | SecurityException ex) {
100 throw new RuntimeException(ex);
101 }
102 }
103
104 private ExpressionFactory() {
105 // Hide default constructor for utils classes
106 }
107
108 /**
109 * List of functions that can be used in MapCSS expressions.
110 *
111 * First parameter can be of type {@link Environment} (if needed). This is
112 * automatically filled in by JOSM and the user only sees the remaining arguments.
113 * When one of the user supplied arguments cannot be converted the
114 * expected type or is null, the function is not called and it returns null
115 * immediately. Add the annotation {@link NullableArguments} to allow null arguments.
116 * Every method must be static.
117 */
118 @SuppressWarnings("UnusedDeclaration")
119 public static final class Functions {
120
121 private Functions() {
122 // Hide implicit public constructor for utility classes
123 }
124
125 /**
126 * Identity function for compatibility with MapCSS specification.
127 * @param o any object
128 * @return {@code o} unchanged
129 */
130 public static Object eval(Object o) { // NO_UCD (unused code)
131 return o;
132 }
133
134 /**
135 * Function associated to the numeric "+" operator.
136 * @param args arguments
137 * @return Sum of arguments
138 */
139 public static float plus(float... args) { // NO_UCD (unused code)
140 float res = 0;
141 for (float f : args) {
142 res += f;
143 }
144 return res;
145 }
146
147 /**
148 * Function associated to the numeric "-" operator.
149 * @param args arguments
150 * @return Substraction of arguments
151 */
152 public static Float minus(float... args) { // NO_UCD (unused code)
153 if (args.length == 0) {
154 return 0.0F;
155 }
156 if (args.length == 1) {
157 return -args[0];
158 }
159 float res = args[0];
160 for (int i = 1; i < args.length; ++i) {
161 res -= args[i];
162 }
163 return res;
164 }
165
166 /**
167 * Function associated to the numeric "*" operator.
168 * @param args arguments
169 * @return Multiplication of arguments
170 */
171 public static float times(float... args) { // NO_UCD (unused code)
172 float res = 1;
173 for (float f : args) {
174 res *= f;
175 }
176 return res;
177 }
178
179 /**
180 * Function associated to the numeric "/" operator.
181 * @param args arguments
182 * @return Division of arguments
183 */
184 public static Float divided_by(float... args) { // NO_UCD (unused code)
185 if (args.length == 0) {
186 return 1.0F;
187 }
188 float res = args[0];
189 for (int i = 1; i < args.length; ++i) {
190 if (args[i] == 0) {
191 return null;
192 }
193 res /= args[i];
194 }
195 return res;
196 }
197
198 /**
199 * Creates a list of values, e.g., for the {@code dashes} property.
200 * @param args The values to put in a list
201 * @return list of values
202 * @see Arrays#asList(Object[])
203 */
204 public static List<Object> list(Object... args) { // NO_UCD (unused code)
205 return Arrays.asList(args);
206 }
207
208 /**
209 * Returns the number of elements in a list.
210 * @param lst the list
211 * @return length of the list
212 */
213 public static Integer count(List<?> lst) { // NO_UCD (unused code)
214 return lst.size();
215 }
216
217 /**
218 * Returns the first non-null object.
219 * The name originates from <a href="http://wiki.openstreetmap.org/wiki/MapCSS/0.2/eval">MapCSS standard</a>.
220 * @param args arguments
221 * @return the first non-null object
222 * @see Utils#firstNonNull(Object[])
223 */
224 @NullableArguments
225 public static Object any(Object... args) { // NO_UCD (unused code)
226 return Utils.firstNonNull(args);
227 }
228
229 /**
230 * Get the {@code n}th element of the list {@code lst} (counting starts at 0).
231 * @param lst list
232 * @param n index
233 * @return {@code n}th element of the list, or {@code null} if index out of range
234 * @since 5699
235 */
236 public static Object get(List<?> lst, float n) { // NO_UCD (unused code)
237 int idx = Math.round(n);
238 if (idx >= 0 && idx < lst.size()) {
239 return lst.get(idx);
240 }
241 return null;
242 }
243
244 /**
245 * Splits string {@code toSplit} at occurrences of the separator string {@code sep} and returns a list of matches.
246 * @param sep separator string
247 * @param toSplit string to split
248 * @return list of matches
249 * @see String#split(String)
250 * @since 5699
251 */
252 public static List<String> split(String sep, String toSplit) { // NO_UCD (unused code)
253 return Arrays.asList(toSplit.split(Pattern.quote(sep), -1));
254 }
255
256 /**
257 * Creates a color value with the specified amounts of {@code r}ed, {@code g}reen, {@code b}lue (arguments from 0.0 to 1.0)
258 * @param r the red component
259 * @param g the green component
260 * @param b the blue component
261 * @return color matching the given components
262 * @see Color#Color(float, float, float)
263 */
264 public static Color rgb(float r, float g, float b) { // NO_UCD (unused code)
265 try {
266 return new Color(r, g, b);
267 } catch (IllegalArgumentException e) {
268 Main.trace(e);
269 return null;
270 }
271 }
272
273 /**
274 * Creates a color value with the specified amounts of {@code r}ed, {@code g}reen, {@code b}lue, {@code alpha}
275 * (arguments from 0.0 to 1.0)
276 * @param r the red component
277 * @param g the green component
278 * @param b the blue component
279 * @param alpha the alpha component
280 * @return color matching the given components
281 * @see Color#Color(float, float, float, float)
282 */
283 public static Color rgba(float r, float g, float b, float alpha) { // NO_UCD (unused code)
284 try {
285 return new Color(r, g, b, alpha);
286 } catch (IllegalArgumentException e) {
287 Main.trace(e);
288 return null;
289 }
290 }
291
292 /**
293 * Create color from hsb color model. (arguments form 0.0 to 1.0)
294 * @param h hue
295 * @param s saturation
296 * @param b brightness
297 * @return the corresponding color
298 */
299 public static Color hsb_color(float h, float s, float b) { // NO_UCD (unused code)
300 try {
301 return Color.getHSBColor(h, s, b);
302 } catch (IllegalArgumentException e) {
303 Main.trace(e);
304 return null;
305 }
306 }
307
308 /**
309 * Creates a color value from an HTML notation, i.e., {@code #rrggbb}.
310 * @param html HTML notation
311 * @return color matching the given notation
312 */
313 public static Color html2color(String html) { // NO_UCD (unused code)
314 return ColorHelper.html2color(html);
315 }
316
317 /**
318 * Computes the HTML notation ({@code #rrggbb}) for a color value).
319 * @param c color
320 * @return HTML notation matching the given color
321 */
322 public static String color2html(Color c) { // NO_UCD (unused code)
323 return ColorHelper.color2html(c);
324 }
325
326 /**
327 * Get the value of the red color channel in the rgb color model
328 * @param c color
329 * @return the red color channel in the range [0;1]
330 * @see java.awt.Color#getRed()
331 */
332 public static float red(Color c) { // NO_UCD (unused code)
333 return Utils.colorInt2float(c.getRed());
334 }
335
336 /**
337 * Get the value of the green color channel in the rgb color model
338 * @param c color
339 * @return the green color channel in the range [0;1]
340 * @see java.awt.Color#getGreen()
341 */
342 public static float green(Color c) { // NO_UCD (unused code)
343 return Utils.colorInt2float(c.getGreen());
344 }
345
346 /**
347 * Get the value of the blue color channel in the rgb color model
348 * @param c color
349 * @return the blue color channel in the range [0;1]
350 * @see java.awt.Color#getBlue()
351 */
352 public static float blue(Color c) { // NO_UCD (unused code)
353 return Utils.colorInt2float(c.getBlue());
354 }
355
356 /**
357 * Get the value of the alpha channel in the rgba color model
358 * @param c color
359 * @return the alpha channel in the range [0;1]
360 * @see java.awt.Color#getAlpha()
361 */
362 public static float alpha(Color c) { // NO_UCD (unused code)
363 return Utils.colorInt2float(c.getAlpha());
364 }
365
366 /**
367 * Assembles the strings to one.
368 * @param args arguments
369 * @return assembled string
370 * @see Utils#join
371 */
372 @NullableArguments
373 public static String concat(Object... args) { // NO_UCD (unused code)
374 return Utils.join("", Arrays.asList(args));
375 }
376
377 /**
378 * Assembles the strings to one, where the first entry is used as separator.
379 * @param args arguments. First one is used as separator
380 * @return assembled string
381 * @see Utils#join
382 */
383 @NullableArguments
384 public static String join(String... args) { // NO_UCD (unused code)
385 return Utils.join(args[0], Arrays.asList(args).subList(1, args.length));
386 }
387
388 /**
389 * Joins a list of {@code values} into a single string with fields separated by {@code separator}.
390 * @param separator the separator
391 * @param values collection of objects
392 * @return assembled string
393 * @see Utils#join
394 */
395 public static String join_list(final String separator, final List<String> values) { // NO_UCD (unused code)
396 return Utils.join(separator, values);
397 }
398
399 /**
400 * Returns the value of the property {@code key}, e.g., {@code prop("width")}.
401 * @param env the environment
402 * @param key the property key
403 * @return the property value
404 */
405 public static Object prop(final Environment env, String key) { // NO_UCD (unused code)
406 return prop(env, key, null);
407 }
408
409 /**
410 * Returns the value of the property {@code key} from layer {@code layer}.
411 * @param env the environment
412 * @param key the property key
413 * @param layer layer
414 * @return the property value
415 */
416 public static Object prop(final Environment env, String key, String layer) {
417 return env.getCascade(layer).get(key);
418 }
419
420 /**
421 * Determines whether property {@code key} is set.
422 * @param env the environment
423 * @param key the property key
424 * @return {@code true} if the property is set, {@code false} otherwise
425 */
426 public static Boolean is_prop_set(final Environment env, String key) { // NO_UCD (unused code)
427 return is_prop_set(env, key, null);
428 }
429
430 /**
431 * Determines whether property {@code key} is set on layer {@code layer}.
432 * @param env the environment
433 * @param key the property key
434 * @param layer layer
435 * @return {@code true} if the property is set, {@code false} otherwise
436 */
437 public static Boolean is_prop_set(final Environment env, String key, String layer) {
438 return env.getCascade(layer).containsKey(key);
439 }
440
441 /**
442 * Gets the value of the key {@code key} from the object in question.
443 * @param env the environment
444 * @param key the OSM key
445 * @return the value for given key
446 */
447 public static String tag(final Environment env, String key) { // NO_UCD (unused code)
448 return env.osm == null ? null : env.osm.get(key);
449 }
450
451 /**
452 * Gets the first non-null value of the key {@code key} from the object's parent(s).
453 * @param env the environment
454 * @param key the OSM key
455 * @return first non-null value of the key {@code key} from the object's parent(s)
456 */
457 public static String parent_tag(final Environment env, String key) { // NO_UCD (unused code)
458 if (env.parent == null) {
459 if (env.osm != null) {
460 // we don't have a matched parent, so just search all referrers
461 for (OsmPrimitive parent : env.osm.getReferrers()) {
462 String value = parent.get(key);
463 if (value != null) {
464 return value;
465 }
466 }
467 }
468 return null;
469 }
470 return env.parent.get(key);
471 }
472
473 /**
474 * Gets a list of all non-null values of the key {@code key} from the object's parent(s).
475 *
476 * The values are sorted according to {@link AlphanumComparator}.
477 * @param env the environment
478 * @param key the OSM key
479 * @return a list of non-null values of the key {@code key} from the object's parent(s)
480 */
481 public static List<String> parent_tags(final Environment env, String key) { // NO_UCD (unused code)
482 if (env.parent == null) {
483 if (env.osm != null) {
484 final Collection<String> tags = new TreeSet<>(AlphanumComparator.getInstance());
485 // we don't have a matched parent, so just search all referrers
486 for (OsmPrimitive parent : env.osm.getReferrers()) {
487 String value = parent.get(key);
488 if (value != null) {
489 tags.add(value);
490 }
491 }
492 return new ArrayList<>(tags);
493 }
494 return Collections.emptyList();
495 }
496 return Collections.singletonList(env.parent.get(key));
497 }
498
499 /**
500 * Gets the value of the key {@code key} from the object's child.
501 * @param env the environment
502 * @param key the OSM key
503 * @return the value of the key {@code key} from the object's child, or {@code null} if there is no child
504 */
505 public static String child_tag(final Environment env, String key) { // NO_UCD (unused code)
506 return env.child == null ? null : env.child.get(key);
507 }
508
509 /**
510 * Determines whether the object has a tag with the given key.
511 * @param env the environment
512 * @param key the OSM key
513 * @return {@code true} if the object has a tag with the given key, {@code false} otherwise
514 */
515 public static boolean has_tag_key(final Environment env, String key) { // NO_UCD (unused code)
516 return env.osm.hasKey(key);
517 }
518
519 /**
520 * Returns the index of node in parent way or member in parent relation.
521 * @param env the environment
522 * @return the index as float. Starts at 1
523 */
524 public static Float index(final Environment env) { // NO_UCD (unused code)
525 if (env.index == null) {
526 return null;
527 }
528 return Float.valueOf(env.index + 1f);
529 }
530
531 /**
532 * Returns the role of current object in parent relation, or role of child if current object is a relation.
533 * @param env the environment
534 * @return role of current object in parent relation, or role of child if current object is a relation
535 * @see Environment#getRole()
536 */
537 public static String role(final Environment env) { // NO_UCD (unused code)
538 return env.getRole();
539 }
540
541 /**
542 * Returns the area of a closed way or multipolygon in square meters or {@code null}.
543 * @param env the environment
544 * @return the area of a closed way or multipolygon in square meters or {@code null}
545 * @see Geometry#computeArea(OsmPrimitive)
546 */
547 public static Float areasize(final Environment env) { // NO_UCD (unused code)
548 final Double area = Geometry.computeArea(env.osm);
549 return area == null ? null : area.floatValue();
550 }
551
552 /**
553 * Returns the length of the way in metres or {@code null}.
554 * @param env the environment
555 * @return the length of the way in metres or {@code null}.
556 * @see Way#getLength()
557 */
558 public static Float waylength(final Environment env) { // NO_UCD (unused code)
559 if (env.osm instanceof Way) {
560 return (float) ((Way) env.osm).getLength();
561 } else {
562 return null;
563 }
564 }
565
566 /**
567 * Function associated to the logical "!" operator.
568 * @param b boolean value
569 * @return {@code true} if {@code !b}
570 */
571 public static boolean not(boolean b) { // NO_UCD (unused code)
572 return !b;
573 }
574
575 /**
576 * Function associated to the logical "&gt;=" operator.
577 * @param a first value
578 * @param b second value
579 * @return {@code true} if {@code a &gt;= b}
580 */
581 public static boolean greater_equal(float a, float b) { // NO_UCD (unused code)
582 return a >= b;
583 }
584
585 /**
586 * Function associated to the logical "&lt;=" operator.
587 * @param a first value
588 * @param b second value
589 * @return {@code true} if {@code a &lt;= b}
590 */
591 public static boolean less_equal(float a, float b) { // NO_UCD (unused code)
592 return a <= b;
593 }
594
595 /**
596 * Function associated to the logical "&gt;" operator.
597 * @param a first value
598 * @param b second value
599 * @return {@code true} if {@code a &gt; b}
600 */
601 public static boolean greater(float a, float b) { // NO_UCD (unused code)
602 return a > b;
603 }
604
605 /**
606 * Function associated to the logical "&lt;" operator.
607 * @param a first value
608 * @param b second value
609 * @return {@code true} if {@code a &lt; b}
610 */
611 public static boolean less(float a, float b) { // NO_UCD (unused code)
612 return a < b;
613 }
614
615 /**
616 * Converts an angle in degrees to radians.
617 * @param degree the angle in degrees
618 * @return the angle in radians
619 * @see Math#toRadians(double)
620 */
621 public static double degree_to_radians(double degree) { // NO_UCD (unused code)
622 return Math.toRadians(degree);
623 }
624
625 /**
626 * Converts an angle diven in cardinal directions to radians.
627 * The following values are supported: {@code n}, {@code north}, {@code ne}, {@code northeast},
628 * {@code e}, {@code east}, {@code se}, {@code southeast}, {@code s}, {@code south},
629 * {@code sw}, {@code southwest}, {@code w}, {@code west}, {@code nw}, {@code northwest}.
630 * @param cardinal the angle in cardinal directions.
631 * @return the angle in radians
632 * @see RotationAngle#parseCardinalRotation(String)
633 */
634 public static Double cardinal_to_radians(String cardinal) { // NO_UCD (unused code)
635 try {
636 return RotationAngle.parseCardinalRotation(cardinal);
637 } catch (IllegalArgumentException ignore) {
638 Main.trace(ignore);
639 return null;
640 }
641 }
642
643 /**
644 * Determines if the objects {@code a} and {@code b} are equal.
645 * @param a First object
646 * @param b Second object
647 * @return {@code true} if objects are equal, {@code false} otherwise
648 * @see Object#equals(Object)
649 */
650 public static boolean equal(Object a, Object b) {
651 if (a.getClass() == b.getClass()) return a.equals(b);
652 if (a.equals(Cascade.convertTo(b, a.getClass()))) return true;
653 return b.equals(Cascade.convertTo(a, b.getClass()));
654 }
655
656 /**
657 * Determines if the objects {@code a} and {@code b} are not equal.
658 * @param a First object
659 * @param b Second object
660 * @return {@code false} if objects are equal, {@code true} otherwise
661 * @see Object#equals(Object)
662 */
663 public static boolean not_equal(Object a, Object b) { // NO_UCD (unused code)
664 return !equal(a, b);
665 }
666
667 /**
668 * Determines whether the JOSM search with {@code searchStr} applies to the object.
669 * @param env the environment
670 * @param searchStr the search string
671 * @return {@code true} if the JOSM search with {@code searchStr} applies to the object
672 * @see SearchCompiler
673 */
674 public static Boolean JOSM_search(final Environment env, String searchStr) { // NO_UCD (unused code)
675 Match m;
676 try {
677 m = SearchCompiler.compile(searchStr);
678 } catch (ParseError ex) {
679 Main.trace(ex);
680 return null;
681 }
682 return m.match(env.osm);
683 }
684
685 /**
686 * Obtains the JOSM'key {@link org.openstreetmap.josm.data.Preferences} string for key {@code key},
687 * and defaults to {@code def} if that is null.
688 * @param env the environment
689 * @param key Key in JOSM preference
690 * @param def Default value
691 * @return value for key, or default value if not found
692 */
693 public static String JOSM_pref(Environment env, String key, String def) { // NO_UCD (unused code)
694 return MapPaintStyles.getStyles().getPreferenceCached(key, def);
695 }
696
697 /**
698 * Tests if string {@code target} matches pattern {@code pattern}
699 * @param pattern The regex expression
700 * @param target The character sequence to be matched
701 * @return {@code true} if, and only if, the entire region sequence matches the pattern
702 * @see Pattern#matches(String, CharSequence)
703 * @since 5699
704 */
705 public static boolean regexp_test(String pattern, String target) { // NO_UCD (unused code)
706 return Pattern.matches(pattern, target);
707 }
708
709 /**
710 * Tests if string {@code target} matches pattern {@code pattern}
711 * @param pattern The regex expression
712 * @param target The character sequence to be matched
713 * @param flags a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all")
714 * @return {@code true} if, and only if, the entire region sequence matches the pattern
715 * @see Pattern#CASE_INSENSITIVE
716 * @see Pattern#DOTALL
717 * @see Pattern#MULTILINE
718 * @since 5699
719 */
720 public static boolean regexp_test(String pattern, String target, String flags) { // NO_UCD (unused code)
721 int f = 0;
722 if (flags.contains("i")) {
723 f |= Pattern.CASE_INSENSITIVE;
724 }
725 if (flags.contains("s")) {
726 f |= Pattern.DOTALL;
727 }
728 if (flags.contains("m")) {
729 f |= Pattern.MULTILINE;
730 }
731 return Pattern.compile(pattern, f).matcher(target).matches();
732 }
733
734 /**
735 * Tries to match string against pattern regexp and returns a list of capture groups in case of success.
736 * The first element (index 0) is the complete match (i.e. string).
737 * Further elements correspond to the bracketed parts of the regular expression.
738 * @param pattern The regex expression
739 * @param target The character sequence to be matched
740 * @param flags a string that may contain "i" (case insensitive), "m" (multiline) and "s" ("dot all")
741 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
742 * @see Pattern#CASE_INSENSITIVE
743 * @see Pattern#DOTALL
744 * @see Pattern#MULTILINE
745 * @since 5701
746 */
747 public static List<String> regexp_match(String pattern, String target, String flags) { // NO_UCD (unused code)
748 int f = 0;
749 if (flags.contains("i")) {
750 f |= Pattern.CASE_INSENSITIVE;
751 }
752 if (flags.contains("s")) {
753 f |= Pattern.DOTALL;
754 }
755 if (flags.contains("m")) {
756 f |= Pattern.MULTILINE;
757 }
758 return Utils.getMatches(Pattern.compile(pattern, f).matcher(target));
759 }
760
761 /**
762 * Tries to match string against pattern regexp and returns a list of capture groups in case of success.
763 * The first element (index 0) is the complete match (i.e. string).
764 * Further elements correspond to the bracketed parts of the regular expression.
765 * @param pattern The regex expression
766 * @param target The character sequence to be matched
767 * @return a list of capture groups if {@link Matcher#matches()}, or {@code null}.
768 * @since 5701
769 */
770 public static List<String> regexp_match(String pattern, String target) { // NO_UCD (unused code)
771 return Utils.getMatches(Pattern.compile(pattern).matcher(target));
772 }
773
774 /**
775 * Returns the OSM id of the current object.
776 * @param env the environment
777 * @return the OSM id of the current object
778 * @see OsmPrimitive#getUniqueId()
779 */
780 public static long osm_id(final Environment env) { // NO_UCD (unused code)
781 return env.osm.getUniqueId();
782 }
783
784 /**
785 * Translates some text for the current locale. The first argument is the text to translate,
786 * and the subsequent arguments are parameters for the string indicated by <code>{0}</code>, <code>{1}</code>, …
787 * @param args arguments
788 * @return the translated string
789 */
790 @NullableArguments
791 public static String tr(String... args) { // NO_UCD (unused code)
792 final String text = args[0];
793 System.arraycopy(args, 1, args, 0, args.length - 1);
794 return org.openstreetmap.josm.tools.I18n.tr(text, (Object[]) args);
795 }
796
797 /**
798 * Returns the substring of {@code s} starting at index {@code begin} (inclusive, 0-indexed).
799 * @param s The base string
800 * @param begin The start index
801 * @return the substring
802 * @see String#substring(int)
803 */
804 public static String substring(String s, /* due to missing Cascade.convertTo for int*/ float begin) { // NO_UCD (unused code)
805 return s == null ? null : s.substring((int) begin);
806 }
807
808 /**
809 * Returns the substring of {@code s} starting at index {@code begin} (inclusive)
810 * and ending at index {@code end}, (exclusive, 0-indexed).
811 * @param s The base string
812 * @param begin The start index
813 * @param end The end index
814 * @return the substring
815 * @see String#substring(int, int)
816 */
817 public static String substring(String s, float begin, float end) { // NO_UCD (unused code)
818 return s == null ? null : s.substring((int) begin, (int) end);
819 }
820
821 /**
822 * Replaces in {@code s} every {@code} target} substring by {@code replacement}.
823 * @param s The source string
824 * @param target The sequence of char values to be replaced
825 * @param replacement The replacement sequence of char values
826 * @return The resulting string
827 * @see String#replace(CharSequence, CharSequence)
828 */
829 public static String replace(String s, String target, String replacement) { // NO_UCD (unused code)
830 return s == null ? null : s.replace(target, replacement);
831 }
832
833 /**
834 * Percent-encode a string. (See https://en.wikipedia.org/wiki/Percent-encoding)
835 * This is especially useful for data urls, e.g.
836 * <code>concat("data:image/svg+xml,", URL_encode("&lt;svg&gt;...&lt;/svg&gt;"));</code>
837 * @param s arbitrary string
838 * @return the encoded string
839 */
840 public static String URL_encode(String s) { // NO_UCD (unused code)
841 return s == null ? null : Utils.encodeUrl(s);
842 }
843
844 /**
845 * XML-encode a string.
846 *
847 * Escapes special characters in xml. Alternative to using &lt;![CDATA[ ... ]]&gt; blocks.
848 * @param s arbitrary string
849 * @return the encoded string
850 */
851 public static String XML_encode(String s) { // NO_UCD (unused code)
852 return s == null ? null : XmlWriter.encode(s);
853 }
854
855 /**
856 * Calculates the CRC32 checksum from a string (based on RFC 1952).
857 * @param s the string
858 * @return long value from 0 to 2^32-1
859 */
860 public static long CRC32_checksum(String s) { // NO_UCD (unused code)
861 CRC32 cs = new CRC32();
862 cs.update(s.getBytes(StandardCharsets.UTF_8));
863 return cs.getValue();
864 }
865
866 /**
867 * check if there is right-hand traffic at the current location
868 * @param env the environment
869 * @return true if there is right-hand traffic
870 * @since 7193
871 */
872 public static boolean is_right_hand_traffic(Environment env) {
873 return RightAndLefthandTraffic.isRightHandTraffic(center(env));
874 }
875
876 /**
877 * Determines whether the way is {@link Geometry#isClockwise closed and oriented clockwise},
878 * or non-closed and the {@link Geometry#angleIsClockwise 1st, 2nd and last node are in clockwise order}.
879 *
880 * @param env the environment
881 * @return true if the way is closed and oriented clockwise
882 */
883 public static boolean is_clockwise(Environment env) {
884 if (!(env.osm instanceof Way)) {
885 return false;
886 }
887 final Way way = (Way) env.osm;
888 return (way.isClosed() && Geometry.isClockwise(way))
889 || (!way.isClosed() && way.getNodesCount() > 2 && Geometry.angleIsClockwise(way.getNode(0), way.getNode(1), way.lastNode()));
890 }
891
892 /**
893 * Determines whether the way is {@link Geometry#isClockwise closed and oriented anticlockwise},
894 * or non-closed and the {@link Geometry#angleIsClockwise 1st, 2nd and last node are in anticlockwise order}.
895 *
896 * @param env the environment
897 * @return true if the way is closed and oriented clockwise
898 */
899 public static boolean is_anticlockwise(Environment env) {
900 if (!(env.osm instanceof Way)) {
901 return false;
902 }
903 final Way way = (Way) env.osm;
904 return (way.isClosed() && !Geometry.isClockwise(way))
905 || (!way.isClosed() && way.getNodesCount() > 2 && !Geometry.angleIsClockwise(way.getNode(0), way.getNode(1), way.lastNode()));
906 }
907
908 /**
909 * Prints the object to the command line (for debugging purpose).
910 * @param o the object
911 * @return the same object, unchanged
912 */
913 @NullableArguments
914 public static Object print(Object o) { // NO_UCD (unused code)
915 System.out.print(o == null ? "none" : o.toString());
916 return o;
917 }
918
919 /**
920 * Prints the object to the command line, with new line at the end
921 * (for debugging purpose).
922 * @param o the object
923 * @return the same object, unchanged
924 */
925 @NullableArguments
926 public static Object println(Object o) { // NO_UCD (unused code)
927 System.out.println(o == null ? "none" : o.toString());
928 return o;
929 }
930
931 /**
932 * Get the number of tags for the current primitive.
933 * @param env the environment
934 * @return number of tags
935 */
936 public static int number_of_tags(Environment env) { // NO_UCD (unused code)
937 return env.osm.getNumKeys();
938 }
939
940 /**
941 * Get value of a setting.
942 * @param env the environment
943 * @param key setting key (given as layer identifier, e.g. setting::mykey {...})
944 * @return the value of the setting (calculated when the style is loaded)
945 */
946 public static Object setting(Environment env, String key) { // NO_UCD (unused code)
947 return env.source.settingValues.get(key);
948 }
949
950 /**
951 * Returns the center of the environment OSM primitive.
952 * @param env the environment
953 * @return the center of the environment OSM primitive
954 * @since 11247
955 */
956 public static LatLon center(Environment env) { // NO_UCD (unused code)
957 return env.osm instanceof Node ? ((Node) env.osm).getCoor() : env.osm.getBBox().getCenter();
958 }
959
960 /**
961 * Determines if the object is inside territories matching given ISO3166 codes.
962 * @param env the environment
963 * @param codes comma-separated list of ISO3166-1-alpha2 or ISO3166-2 country/subdivision codes
964 * @return {@code true} if the object is inside territory matching given ISO3166 codes
965 * @since 11247
966 */
967 public static boolean inside(Environment env, String codes) { // NO_UCD (unused code)
968 Set<String> osmCodes = Territories.getIso3166Codes(center(env));
969 for (String code : codes.toUpperCase(Locale.ENGLISH).split(",")) {
970 if (osmCodes.contains(code.trim())) {
971 return true;
972 }
973 }
974 return false;
975 }
976
977 /**
978 * Determines if the object is outside territories matching given ISO3166 codes.
979 * @param env the environment
980 * @param codes comma-separated list of ISO3166-1-alpha2 or ISO3166-2 country/subdivision codes
981 * @return {@code true} if the object is outside territory matching given ISO3166 codes
982 * @since 11247
983 */
984 public static boolean outside(Environment env, String codes) { // NO_UCD (unused code)
985 return !inside(env, codes);
986 }
987 }
988
989 /**
990 * Main method to create an function-like expression.
991 *
992 * @param name the name of the function or operator
993 * @param args the list of arguments (as expressions)
994 * @return the generated Expression. If no suitable function can be found,
995 * returns {@link NullExpression#INSTANCE}.
996 */
997 public static Expression createFunctionExpression(String name, List<Expression> args) {
998 if ("cond".equals(name) && args.size() == 3)
999 return new CondOperator(args.get(0), args.get(1), args.get(2));
1000 else if ("and".equals(name))
1001 return new AndOperator(args);
1002 else if ("or".equals(name))
1003 return new OrOperator(args);
1004 else if ("length".equals(name) && args.size() == 1)
1005 return new LengthFunction(args.get(0));
1006 else if ("max".equals(name) && !args.isEmpty())
1007 return new MinMaxFunction(args, true);
1008 else if ("min".equals(name) && !args.isEmpty())
1009 return new MinMaxFunction(args, false);
1010
1011 for (Method m : arrayFunctions) {
1012 if (m.getName().equals(name))
1013 return new ArrayFunction(m, args);
1014 }
1015 for (Method m : parameterFunctions) {
1016 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length)
1017 return new ParameterFunction(m, args, false);
1018 }
1019 for (Method m : parameterFunctionsEnv) {
1020 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length-1)
1021 return new ParameterFunction(m, args, true);
1022 }
1023 return NullExpression.INSTANCE;
1024 }
1025
1026 /**
1027 * Expression that always evaluates to null.
1028 */
1029 public static class NullExpression implements Expression {
1030
1031 /**
1032 * The unique instance.
1033 */
1034 public static final NullExpression INSTANCE = new NullExpression();
1035
1036 @Override
1037 public Object evaluate(Environment env) {
1038 return null;
1039 }
1040 }
1041
1042 /**
1043 * Conditional operator.
1044 */
1045 public static class CondOperator implements Expression {
1046
1047 private final Expression condition, firstOption, secondOption;
1048
1049 /**
1050 * Constructs a new {@code CondOperator}.
1051 * @param condition condition
1052 * @param firstOption first option
1053 * @param secondOption second option
1054 */
1055 public CondOperator(Expression condition, Expression firstOption, Expression secondOption) {
1056 this.condition = condition;
1057 this.firstOption = firstOption;
1058 this.secondOption = secondOption;
1059 }
1060
1061 @Override
1062 public Object evaluate(Environment env) {
1063 Boolean b = Cascade.convertTo(condition.evaluate(env), boolean.class);
1064 if (b != null && b)
1065 return firstOption.evaluate(env);
1066 else
1067 return secondOption.evaluate(env);
1068 }
1069 }
1070
1071 /**
1072 * "And" logical operator.
1073 */
1074 public static class AndOperator implements Expression {
1075
1076 private final List<Expression> args;
1077
1078 /**
1079 * Constructs a new {@code AndOperator}.
1080 * @param args arguments
1081 */
1082 public AndOperator(List<Expression> args) {
1083 this.args = args;
1084 }
1085
1086 @Override
1087 public Object evaluate(Environment env) {
1088 for (Expression arg : args) {
1089 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1090 if (b == null || !b) {
1091 return Boolean.FALSE;
1092 }
1093 }
1094 return Boolean.TRUE;
1095 }
1096 }
1097
1098 /**
1099 * "Or" logical operator.
1100 */
1101 public static class OrOperator implements Expression {
1102
1103 private final List<Expression> args;
1104
1105 /**
1106 * Constructs a new {@code OrOperator}.
1107 * @param args arguments
1108 */
1109 public OrOperator(List<Expression> args) {
1110 this.args = args;
1111 }
1112
1113 @Override
1114 public Object evaluate(Environment env) {
1115 for (Expression arg : args) {
1116 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1117 if (b != null && b) {
1118 return Boolean.TRUE;
1119 }
1120 }
1121 return Boolean.FALSE;
1122 }
1123 }
1124
1125 /**
1126 * Function to calculate the length of a string or list in a MapCSS eval expression.
1127 *
1128 * Separate implementation to support overloading for different argument types.
1129 *
1130 * The use for calculating the length of a list is deprecated, use
1131 * {@link Functions#count(java.util.List)} instead (see #10061).
1132 */
1133 public static class LengthFunction implements Expression {
1134
1135 private final Expression arg;
1136
1137 /**
1138 * Constructs a new {@code LengthFunction}.
1139 * @param args arguments
1140 */
1141 public LengthFunction(Expression args) {
1142 this.arg = args;
1143 }
1144
1145 @Override
1146 public Object evaluate(Environment env) {
1147 List<?> l = Cascade.convertTo(arg.evaluate(env), List.class);
1148 if (l != null)
1149 return l.size();
1150 String s = Cascade.convertTo(arg.evaluate(env), String.class);
1151 if (s != null)
1152 return s.length();
1153 return null;
1154 }
1155 }
1156
1157 /**
1158 * Computes the maximum/minimum value an arbitrary number of floats, or a list of floats.
1159 */
1160 public static class MinMaxFunction implements Expression {
1161
1162 private final List<Expression> args;
1163 private final boolean computeMax;
1164
1165 /**
1166 * Constructs a new {@code MinMaxFunction}.
1167 * @param args arguments
1168 * @param computeMax if {@code true}, compute max. If {@code false}, compute min
1169 */
1170 public MinMaxFunction(final List<Expression> args, final boolean computeMax) {
1171 this.args = args;
1172 this.computeMax = computeMax;
1173 }
1174
1175 public Float aggregateList(List<?> lst) {
1176 final List<Float> floats = Utils.transform(lst, (Function<Object, Float>) x -> Cascade.convertTo(x, float.class));
1177 final Collection<Float> nonNullList = SubclassFilteredCollection.filter(floats, Objects::nonNull);
1178 return nonNullList.isEmpty() ? (Float) Float.NaN : computeMax ? Collections.max(nonNullList) : Collections.min(nonNullList);
1179 }
1180
1181 @Override
1182 public Object evaluate(final Environment env) {
1183 List<?> l = Cascade.convertTo(args.get(0).evaluate(env), List.class);
1184 if (args.size() != 1 || l == null)
1185 l = Utils.transform(args, (Function<Expression, Object>) x -> x.evaluate(env));
1186 return aggregateList(l);
1187 }
1188 }
1189
1190 /**
1191 * Function that takes a certain number of argument with specific type.
1192 *
1193 * Implementation is based on a Method object.
1194 * If any of the arguments evaluate to null, the result will also be null.
1195 */
1196 public static class ParameterFunction implements Expression {
1197
1198 private final Method m;
1199 private final boolean nullable;
1200 private final List<Expression> args;
1201 private final Class<?>[] expectedParameterTypes;
1202 private final boolean needsEnvironment;
1203
1204 /**
1205 * Constructs a new {@code ParameterFunction}.
1206 * @param m method
1207 * @param args arguments
1208 * @param needsEnvironment whether function needs environment
1209 */
1210 public ParameterFunction(Method m, List<Expression> args, boolean needsEnvironment) {
1211 this.m = m;
1212 this.nullable = m.getAnnotation(NullableArguments.class) != null;
1213 this.args = args;
1214 this.expectedParameterTypes = m.getParameterTypes();
1215 this.needsEnvironment = needsEnvironment;
1216 }
1217
1218 @Override
1219 public Object evaluate(Environment env) {
1220 Object[] convertedArgs;
1221
1222 if (needsEnvironment) {
1223 convertedArgs = new Object[args.size()+1];
1224 convertedArgs[0] = env;
1225 for (int i = 1; i < convertedArgs.length; ++i) {
1226 convertedArgs[i] = Cascade.convertTo(args.get(i-1).evaluate(env), expectedParameterTypes[i]);
1227 if (convertedArgs[i] == null && !nullable) {
1228 return null;
1229 }
1230 }
1231 } else {
1232 convertedArgs = new Object[args.size()];
1233 for (int i = 0; i < convertedArgs.length; ++i) {
1234 convertedArgs[i] = Cascade.convertTo(args.get(i).evaluate(env), expectedParameterTypes[i]);
1235 if (convertedArgs[i] == null && !nullable) {
1236 return null;
1237 }
1238 }
1239 }
1240 Object result = null;
1241 try {
1242 result = m.invoke(null, convertedArgs);
1243 } catch (IllegalAccessException | IllegalArgumentException ex) {
1244 throw new RuntimeException(ex);
1245 } catch (InvocationTargetException ex) {
1246 Main.error(ex);
1247 return null;
1248 }
1249 return result;
1250 }
1251
1252 @Override
1253 public String toString() {
1254 StringBuilder b = new StringBuilder("ParameterFunction~");
1255 b.append(m.getName()).append('(');
1256 for (int i = 0; i < args.size(); ++i) {
1257 if (i > 0) b.append(',');
1258 b.append(expectedParameterTypes[i]).append(' ').append(args.get(i));
1259 }
1260 b.append(')');
1261 return b.toString();
1262 }
1263 }
1264
1265 /**
1266 * Function that takes an arbitrary number of arguments.
1267 *
1268 * Currently, all array functions are static, so there is no need to
1269 * provide the environment, like it is done in {@link ParameterFunction}.
1270 * If any of the arguments evaluate to null, the result will also be null.
1271 */
1272 public static class ArrayFunction implements Expression {
1273
1274 private final Method m;
1275 private final boolean nullable;
1276 private final List<Expression> args;
1277 private final Class<?>[] expectedParameterTypes;
1278 private final Class<?> arrayComponentType;
1279
1280 /**
1281 * Constructs a new {@code ArrayFunction}.
1282 * @param m method
1283 * @param args arguments
1284 */
1285 public ArrayFunction(Method m, List<Expression> args) {
1286 this.m = m;
1287 this.nullable = m.getAnnotation(NullableArguments.class) != null;
1288 this.args = args;
1289 this.expectedParameterTypes = m.getParameterTypes();
1290 this.arrayComponentType = expectedParameterTypes[0].getComponentType();
1291 }
1292
1293 @Override
1294 public Object evaluate(Environment env) {
1295 Object[] convertedArgs = new Object[expectedParameterTypes.length];
1296 Object arrayArg = Array.newInstance(arrayComponentType, args.size());
1297 for (int i = 0; i < args.size(); ++i) {
1298 Object o = Cascade.convertTo(args.get(i).evaluate(env), arrayComponentType);
1299 if (o == null && !nullable) {
1300 return null;
1301 }
1302 Array.set(arrayArg, i, o);
1303 }
1304 convertedArgs[0] = arrayArg;
1305
1306 Object result = null;
1307 try {
1308 result = m.invoke(null, convertedArgs);
1309 } catch (IllegalAccessException | IllegalArgumentException ex) {
1310 throw new RuntimeException(ex);
1311 } catch (InvocationTargetException ex) {
1312 Main.error(ex);
1313 return null;
1314 }
1315 return result;
1316 }
1317
1318 @Override
1319 public String toString() {
1320 StringBuilder b = new StringBuilder("ArrayFunction~");
1321 b.append(m.getName()).append('(');
1322 for (int i = 0; i < args.size(); ++i) {
1323 if (i > 0) b.append(',');
1324 b.append(arrayComponentType).append(' ').append(args.get(i));
1325 }
1326 b.append(')');
1327 return b.toString();
1328 }
1329 }
1330}
Note: See TracBrowser for help on using the repository browser.