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

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

sonar - fix recent minor code style issues

  • Property svn:eol-style set to native
File size: 53.0 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.TreeSet;
21import java.util.function.Function;
22import java.util.regex.Matcher;
23import java.util.regex.Pattern;
24import java.util.zip.CRC32;
25
26import org.openstreetmap.josm.Main;
27import org.openstreetmap.josm.actions.search.SearchCompiler;
28import org.openstreetmap.josm.actions.search.SearchCompiler.Match;
29import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError;
30import org.openstreetmap.josm.data.coor.LatLon;
31import org.openstreetmap.josm.data.osm.Node;
32import org.openstreetmap.josm.data.osm.OsmPrimitive;
33import org.openstreetmap.josm.data.osm.Way;
34import org.openstreetmap.josm.gui.mappaint.Cascade;
35import org.openstreetmap.josm.gui.mappaint.Environment;
36import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
37import org.openstreetmap.josm.gui.util.RotationAngle;
38import org.openstreetmap.josm.io.XmlWriter;
39import org.openstreetmap.josm.tools.AlphanumComparator;
40import org.openstreetmap.josm.tools.ColorHelper;
41import org.openstreetmap.josm.tools.Geometry;
42import org.openstreetmap.josm.tools.JosmRuntimeException;
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 @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 JosmRuntimeException(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 Utils.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 * Converts string {@code s} to uppercase.
835 * @param s The source string
836 * @return The resulting string
837 * @see String#toUpperCase(Locale)
838 * @since 11756
839 */
840 public static String upper(String s) {
841 return s == null ? null : s.toUpperCase(Locale.ENGLISH);
842 }
843
844 /**
845 * Converts string {@code s} to lowercase.
846 * @param s The source string
847 * @return The resulting string
848 * @see String#toLowerCase(Locale)
849 * @since 11756
850 */
851 public static String lower(String s) {
852 return s == null ? null : s.toLowerCase(Locale.ENGLISH);
853 }
854
855 /**
856 * Trim whitespaces from the string {@code s}.
857 * @param s The source string
858 * @return The resulting string
859 * @see Utils#strip
860 * @since 11756
861 */
862 public static String trim(String s) {
863 return Utils.strip(s);
864 }
865
866 /**
867 * Percent-decode a string. (See https://en.wikipedia.org/wiki/Percent-encoding)
868 * This is especially useful for wikipedia titles
869 * @param s url-encoded string
870 * @return the decoded string, or original in case of an error
871 * @since 11756
872 */
873 public static String URL_decode(String s) {
874 if (s == null) return null;
875 try {
876 return Utils.decodeUrl(s);
877 } catch (IllegalStateException e) {
878 Main.debug(e);
879 return s;
880 }
881 }
882
883 /**
884 * Percent-encode a string. (See https://en.wikipedia.org/wiki/Percent-encoding)
885 * This is especially useful for data urls, e.g.
886 * <code>concat("data:image/svg+xml,", URL_encode("&lt;svg&gt;...&lt;/svg&gt;"));</code>
887 * @param s arbitrary string
888 * @return the encoded string
889 */
890 public static String URL_encode(String s) { // NO_UCD (unused code)
891 return s == null ? null : Utils.encodeUrl(s);
892 }
893
894 /**
895 * XML-encode a string.
896 *
897 * Escapes special characters in xml. Alternative to using &lt;![CDATA[ ... ]]&gt; blocks.
898 * @param s arbitrary string
899 * @return the encoded string
900 */
901 public static String XML_encode(String s) { // NO_UCD (unused code)
902 return s == null ? null : XmlWriter.encode(s);
903 }
904
905 /**
906 * Calculates the CRC32 checksum from a string (based on RFC 1952).
907 * @param s the string
908 * @return long value from 0 to 2^32-1
909 */
910 public static long CRC32_checksum(String s) { // NO_UCD (unused code)
911 CRC32 cs = new CRC32();
912 cs.update(s.getBytes(StandardCharsets.UTF_8));
913 return cs.getValue();
914 }
915
916 /**
917 * check if there is right-hand traffic at the current location
918 * @param env the environment
919 * @return true if there is right-hand traffic
920 * @since 7193
921 */
922 public static boolean is_right_hand_traffic(Environment env) {
923 return RightAndLefthandTraffic.isRightHandTraffic(center(env));
924 }
925
926 /**
927 * Determines whether the way is {@link Geometry#isClockwise closed and oriented clockwise},
928 * or non-closed and the {@link Geometry#angleIsClockwise 1st, 2nd and last node are in clockwise order}.
929 *
930 * @param env the environment
931 * @return true if the way is closed and oriented clockwise
932 */
933 public static boolean is_clockwise(Environment env) {
934 if (!(env.osm instanceof Way)) {
935 return false;
936 }
937 final Way way = (Way) env.osm;
938 return (way.isClosed() && Geometry.isClockwise(way))
939 || (!way.isClosed() && way.getNodesCount() > 2 && Geometry.angleIsClockwise(way.getNode(0), way.getNode(1), way.lastNode()));
940 }
941
942 /**
943 * Determines whether the way is {@link Geometry#isClockwise closed and oriented anticlockwise},
944 * or non-closed and the {@link Geometry#angleIsClockwise 1st, 2nd and last node are in anticlockwise order}.
945 *
946 * @param env the environment
947 * @return true if the way is closed and oriented clockwise
948 */
949 public static boolean is_anticlockwise(Environment env) {
950 if (!(env.osm instanceof Way)) {
951 return false;
952 }
953 final Way way = (Way) env.osm;
954 return (way.isClosed() && !Geometry.isClockwise(way))
955 || (!way.isClosed() && way.getNodesCount() > 2 && !Geometry.angleIsClockwise(way.getNode(0), way.getNode(1), way.lastNode()));
956 }
957
958 /**
959 * Prints the object to the command line (for debugging purpose).
960 * @param o the object
961 * @return the same object, unchanged
962 */
963 @NullableArguments
964 public static Object print(Object o) { // NO_UCD (unused code)
965 System.out.print(o == null ? "none" : o.toString());
966 return o;
967 }
968
969 /**
970 * Prints the object to the command line, with new line at the end
971 * (for debugging purpose).
972 * @param o the object
973 * @return the same object, unchanged
974 */
975 @NullableArguments
976 public static Object println(Object o) { // NO_UCD (unused code)
977 System.out.println(o == null ? "none" : o.toString());
978 return o;
979 }
980
981 /**
982 * Get the number of tags for the current primitive.
983 * @param env the environment
984 * @return number of tags
985 */
986 public static int number_of_tags(Environment env) { // NO_UCD (unused code)
987 return env.osm.getNumKeys();
988 }
989
990 /**
991 * Get value of a setting.
992 * @param env the environment
993 * @param key setting key (given as layer identifier, e.g. setting::mykey {...})
994 * @return the value of the setting (calculated when the style is loaded)
995 */
996 public static Object setting(Environment env, String key) { // NO_UCD (unused code)
997 return env.source.settingValues.get(key);
998 }
999
1000 /**
1001 * Returns the center of the environment OSM primitive.
1002 * @param env the environment
1003 * @return the center of the environment OSM primitive
1004 * @since 11247
1005 */
1006 public static LatLon center(Environment env) { // NO_UCD (unused code)
1007 return env.osm instanceof Node ? ((Node) env.osm).getCoor() : env.osm.getBBox().getCenter();
1008 }
1009
1010 /**
1011 * Determines if the object is inside territories matching given ISO3166 codes.
1012 * @param env the environment
1013 * @param codes comma-separated list of ISO3166-1-alpha2 or ISO3166-2 country/subdivision codes
1014 * @return {@code true} if the object is inside territory matching given ISO3166 codes
1015 * @since 11247
1016 */
1017 public static boolean inside(Environment env, String codes) { // NO_UCD (unused code)
1018 for (String code : codes.toUpperCase(Locale.ENGLISH).split(",")) {
1019 if (Territories.isIso3166Code(code.trim(), center(env))) {
1020 return true;
1021 }
1022 }
1023 return false;
1024 }
1025
1026 /**
1027 * Determines if the object is outside territories matching given ISO3166 codes.
1028 * @param env the environment
1029 * @param codes comma-separated list of ISO3166-1-alpha2 or ISO3166-2 country/subdivision codes
1030 * @return {@code true} if the object is outside territory matching given ISO3166 codes
1031 * @since 11247
1032 */
1033 public static boolean outside(Environment env, String codes) { // NO_UCD (unused code)
1034 return !inside(env, codes);
1035 }
1036
1037 /**
1038 * Determines if the object centroid lies at given lat/lon coordinates.
1039 * @param env the environment
1040 * @param lat latitude, i.e., the north-south position in degrees
1041 * @param lon longitude, i.e., the east-west position in degrees
1042 * @return {@code true} if the object centroid lies at given lat/lon coordinates
1043 * @since 12514
1044 */
1045 public static boolean at(Environment env, double lat, double lon) { // NO_UCD (unused code)
1046 return new LatLon(lat, lon).equalsEpsilon(center(env));
1047 }
1048 }
1049
1050 /**
1051 * Main method to create an function-like expression.
1052 *
1053 * @param name the name of the function or operator
1054 * @param args the list of arguments (as expressions)
1055 * @return the generated Expression. If no suitable function can be found,
1056 * returns {@link NullExpression#INSTANCE}.
1057 */
1058 public static Expression createFunctionExpression(String name, List<Expression> args) {
1059 if ("cond".equals(name) && args.size() == 3)
1060 return new CondOperator(args.get(0), args.get(1), args.get(2));
1061 else if ("and".equals(name))
1062 return new AndOperator(args);
1063 else if ("or".equals(name))
1064 return new OrOperator(args);
1065 else if ("length".equals(name) && args.size() == 1)
1066 return new LengthFunction(args.get(0));
1067 else if ("max".equals(name) && !args.isEmpty())
1068 return new MinMaxFunction(args, true);
1069 else if ("min".equals(name) && !args.isEmpty())
1070 return new MinMaxFunction(args, false);
1071
1072 for (Method m : arrayFunctions) {
1073 if (m.getName().equals(name))
1074 return new ArrayFunction(m, args);
1075 }
1076 for (Method m : parameterFunctions) {
1077 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length)
1078 return new ParameterFunction(m, args, false);
1079 }
1080 for (Method m : parameterFunctionsEnv) {
1081 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length-1)
1082 return new ParameterFunction(m, args, true);
1083 }
1084 return NullExpression.INSTANCE;
1085 }
1086
1087 /**
1088 * Expression that always evaluates to null.
1089 */
1090 public static class NullExpression implements Expression {
1091
1092 /**
1093 * The unique instance.
1094 */
1095 public static final NullExpression INSTANCE = new NullExpression();
1096
1097 @Override
1098 public Object evaluate(Environment env) {
1099 return null;
1100 }
1101 }
1102
1103 /**
1104 * Conditional operator.
1105 */
1106 public static class CondOperator implements Expression {
1107
1108 private final Expression condition, firstOption, secondOption;
1109
1110 /**
1111 * Constructs a new {@code CondOperator}.
1112 * @param condition condition
1113 * @param firstOption first option
1114 * @param secondOption second option
1115 */
1116 public CondOperator(Expression condition, Expression firstOption, Expression secondOption) {
1117 this.condition = condition;
1118 this.firstOption = firstOption;
1119 this.secondOption = secondOption;
1120 }
1121
1122 @Override
1123 public Object evaluate(Environment env) {
1124 Boolean b = Cascade.convertTo(condition.evaluate(env), boolean.class);
1125 if (b != null && b)
1126 return firstOption.evaluate(env);
1127 else
1128 return secondOption.evaluate(env);
1129 }
1130 }
1131
1132 /**
1133 * "And" logical operator.
1134 */
1135 public static class AndOperator implements Expression {
1136
1137 private final List<Expression> args;
1138
1139 /**
1140 * Constructs a new {@code AndOperator}.
1141 * @param args arguments
1142 */
1143 public AndOperator(List<Expression> args) {
1144 this.args = args;
1145 }
1146
1147 @Override
1148 public Object evaluate(Environment env) {
1149 for (Expression arg : args) {
1150 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1151 if (b == null || !b) {
1152 return Boolean.FALSE;
1153 }
1154 }
1155 return Boolean.TRUE;
1156 }
1157 }
1158
1159 /**
1160 * "Or" logical operator.
1161 */
1162 public static class OrOperator implements Expression {
1163
1164 private final List<Expression> args;
1165
1166 /**
1167 * Constructs a new {@code OrOperator}.
1168 * @param args arguments
1169 */
1170 public OrOperator(List<Expression> args) {
1171 this.args = args;
1172 }
1173
1174 @Override
1175 public Object evaluate(Environment env) {
1176 for (Expression arg : args) {
1177 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class);
1178 if (b != null && b) {
1179 return Boolean.TRUE;
1180 }
1181 }
1182 return Boolean.FALSE;
1183 }
1184 }
1185
1186 /**
1187 * Function to calculate the length of a string or list in a MapCSS eval expression.
1188 *
1189 * Separate implementation to support overloading for different argument types.
1190 *
1191 * The use for calculating the length of a list is deprecated, use
1192 * {@link Functions#count(java.util.List)} instead (see #10061).
1193 */
1194 public static class LengthFunction implements Expression {
1195
1196 private final Expression arg;
1197
1198 /**
1199 * Constructs a new {@code LengthFunction}.
1200 * @param args arguments
1201 */
1202 public LengthFunction(Expression args) {
1203 this.arg = args;
1204 }
1205
1206 @Override
1207 public Object evaluate(Environment env) {
1208 List<?> l = Cascade.convertTo(arg.evaluate(env), List.class);
1209 if (l != null)
1210 return l.size();
1211 String s = Cascade.convertTo(arg.evaluate(env), String.class);
1212 if (s != null)
1213 return s.length();
1214 return null;
1215 }
1216 }
1217
1218 /**
1219 * Computes the maximum/minimum value an arbitrary number of floats, or a list of floats.
1220 */
1221 public static class MinMaxFunction implements Expression {
1222
1223 private final List<Expression> args;
1224 private final boolean computeMax;
1225
1226 /**
1227 * Constructs a new {@code MinMaxFunction}.
1228 * @param args arguments
1229 * @param computeMax if {@code true}, compute max. If {@code false}, compute min
1230 */
1231 public MinMaxFunction(final List<Expression> args, final boolean computeMax) {
1232 this.args = args;
1233 this.computeMax = computeMax;
1234 }
1235
1236 /**
1237 * Compute the minimum / maximum over the list
1238 * @param lst The list
1239 * @return The minimum or maximum depending on {@link #computeMax}
1240 */
1241 public Float aggregateList(List<?> lst) {
1242 final List<Float> floats = Utils.transform(lst, (Function<Object, Float>) x -> Cascade.convertTo(x, float.class));
1243 final Collection<Float> nonNullList = SubclassFilteredCollection.filter(floats, Objects::nonNull);
1244 return nonNullList.isEmpty() ? (Float) Float.NaN : computeMax ? Collections.max(nonNullList) : Collections.min(nonNullList);
1245 }
1246
1247 @Override
1248 public Object evaluate(final Environment env) {
1249 List<?> l = Cascade.convertTo(args.get(0).evaluate(env), List.class);
1250 if (args.size() != 1 || l == null)
1251 l = Utils.transform(args, (Function<Expression, Object>) x -> x.evaluate(env));
1252 return aggregateList(l);
1253 }
1254 }
1255
1256 /**
1257 * Function that takes a certain number of argument with specific type.
1258 *
1259 * Implementation is based on a Method object.
1260 * If any of the arguments evaluate to null, the result will also be null.
1261 */
1262 public static class ParameterFunction implements Expression {
1263
1264 private final Method m;
1265 private final boolean nullable;
1266 private final List<Expression> args;
1267 private final Class<?>[] expectedParameterTypes;
1268 private final boolean needsEnvironment;
1269
1270 /**
1271 * Constructs a new {@code ParameterFunction}.
1272 * @param m method
1273 * @param args arguments
1274 * @param needsEnvironment whether function needs environment
1275 */
1276 public ParameterFunction(Method m, List<Expression> args, boolean needsEnvironment) {
1277 this.m = m;
1278 this.nullable = m.getAnnotation(NullableArguments.class) != null;
1279 this.args = args;
1280 this.expectedParameterTypes = m.getParameterTypes();
1281 this.needsEnvironment = needsEnvironment;
1282 }
1283
1284 @Override
1285 public Object evaluate(Environment env) {
1286 Object[] convertedArgs;
1287
1288 if (needsEnvironment) {
1289 convertedArgs = new Object[args.size()+1];
1290 convertedArgs[0] = env;
1291 for (int i = 1; i < convertedArgs.length; ++i) {
1292 convertedArgs[i] = Cascade.convertTo(args.get(i-1).evaluate(env), expectedParameterTypes[i]);
1293 if (convertedArgs[i] == null && !nullable) {
1294 return null;
1295 }
1296 }
1297 } else {
1298 convertedArgs = new Object[args.size()];
1299 for (int i = 0; i < convertedArgs.length; ++i) {
1300 convertedArgs[i] = Cascade.convertTo(args.get(i).evaluate(env), expectedParameterTypes[i]);
1301 if (convertedArgs[i] == null && !nullable) {
1302 return null;
1303 }
1304 }
1305 }
1306 Object result = null;
1307 try {
1308 result = m.invoke(null, convertedArgs);
1309 } catch (IllegalAccessException | IllegalArgumentException ex) {
1310 throw new JosmRuntimeException(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("ParameterFunction~");
1321 b.append(m.getName()).append('(');
1322 for (int i = 0; i < expectedParameterTypes.length; ++i) {
1323 if (i > 0) b.append(',');
1324 b.append(expectedParameterTypes[i]);
1325 if (!needsEnvironment) {
1326 b.append(' ').append(args.get(i));
1327 } else if (i > 0) {
1328 b.append(' ').append(args.get(i-1));
1329 }
1330 }
1331 b.append(')');
1332 return b.toString();
1333 }
1334 }
1335
1336 /**
1337 * Function that takes an arbitrary number of arguments.
1338 *
1339 * Currently, all array functions are static, so there is no need to
1340 * provide the environment, like it is done in {@link ParameterFunction}.
1341 * If any of the arguments evaluate to null, the result will also be null.
1342 */
1343 public static class ArrayFunction implements Expression {
1344
1345 private final Method m;
1346 private final boolean nullable;
1347 private final List<Expression> args;
1348 private final Class<?>[] expectedParameterTypes;
1349 private final Class<?> arrayComponentType;
1350
1351 /**
1352 * Constructs a new {@code ArrayFunction}.
1353 * @param m method
1354 * @param args arguments
1355 */
1356 public ArrayFunction(Method m, List<Expression> args) {
1357 this.m = m;
1358 this.nullable = m.getAnnotation(NullableArguments.class) != null;
1359 this.args = args;
1360 this.expectedParameterTypes = m.getParameterTypes();
1361 this.arrayComponentType = expectedParameterTypes[0].getComponentType();
1362 }
1363
1364 @Override
1365 public Object evaluate(Environment env) {
1366 Object[] convertedArgs = new Object[expectedParameterTypes.length];
1367 Object arrayArg = Array.newInstance(arrayComponentType, args.size());
1368 for (int i = 0; i < args.size(); ++i) {
1369 Object o = Cascade.convertTo(args.get(i).evaluate(env), arrayComponentType);
1370 if (o == null && !nullable) {
1371 return null;
1372 }
1373 Array.set(arrayArg, i, o);
1374 }
1375 convertedArgs[0] = arrayArg;
1376
1377 Object result = null;
1378 try {
1379 result = m.invoke(null, convertedArgs);
1380 } catch (IllegalAccessException | IllegalArgumentException ex) {
1381 throw new JosmRuntimeException(ex);
1382 } catch (InvocationTargetException ex) {
1383 Main.error(ex);
1384 return null;
1385 }
1386 return result;
1387 }
1388
1389 @Override
1390 public String toString() {
1391 StringBuilder b = new StringBuilder("ArrayFunction~");
1392 b.append(m.getName()).append('(');
1393 for (int i = 0; i < args.size(); ++i) {
1394 if (i > 0) b.append(',');
1395 b.append(arrayComponentType).append(' ').append(args.get(i));
1396 }
1397 b.append(')');
1398 return b.toString();
1399 }
1400 }
1401}
Note: See TracBrowser for help on using the repository browser.