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

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

checkstyle: various checks

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