001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.mappaint.mapcss; 003 004import java.awt.Color; 005import java.lang.annotation.ElementType; 006import java.lang.annotation.Retention; 007import java.lang.annotation.RetentionPolicy; 008import java.lang.annotation.Target; 009import java.lang.reflect.Array; 010import java.lang.reflect.InvocationTargetException; 011import java.lang.reflect.Method; 012import java.nio.charset.StandardCharsets; 013import java.util.ArrayList; 014import java.util.Arrays; 015import java.util.Collection; 016import java.util.Collections; 017import java.util.List; 018import java.util.Locale; 019import java.util.Objects; 020import java.util.TreeSet; 021import java.util.function.Function; 022import java.util.regex.Matcher; 023import java.util.regex.Pattern; 024import java.util.zip.CRC32; 025 026import org.openstreetmap.josm.Main; 027import org.openstreetmap.josm.actions.search.SearchCompiler; 028import org.openstreetmap.josm.actions.search.SearchCompiler.Match; 029import org.openstreetmap.josm.actions.search.SearchCompiler.ParseError; 030import org.openstreetmap.josm.data.coor.LatLon; 031import org.openstreetmap.josm.data.osm.Node; 032import org.openstreetmap.josm.data.osm.OsmPrimitive; 033import org.openstreetmap.josm.data.osm.Way; 034import org.openstreetmap.josm.gui.mappaint.Cascade; 035import org.openstreetmap.josm.gui.mappaint.Environment; 036import org.openstreetmap.josm.gui.mappaint.MapPaintStyles; 037import org.openstreetmap.josm.gui.util.RotationAngle; 038import org.openstreetmap.josm.io.XmlWriter; 039import org.openstreetmap.josm.tools.AlphanumComparator; 040import org.openstreetmap.josm.tools.ColorHelper; 041import org.openstreetmap.josm.tools.Geometry; 042import org.openstreetmap.josm.tools.JosmRuntimeException; 043import org.openstreetmap.josm.tools.RightAndLefthandTraffic; 044import org.openstreetmap.josm.tools.SubclassFilteredCollection; 045import org.openstreetmap.josm.tools.Territories; 046import org.openstreetmap.josm.tools.Utils; 047 048/** 049 * Factory to generate {@link Expression}s. 050 * <p> 051 * See {@link #createFunctionExpression}. 052 */ 053public final class ExpressionFactory { 054 055 /** 056 * Marks functions which should be executed also when one or more arguments are null. 057 */ 058 @Target(ElementType.METHOD) 059 @Retention(RetentionPolicy.RUNTIME) 060 static @interface NullableArguments {} 061 062 private static final List<Method> arrayFunctions = new ArrayList<>(); 063 private static final List<Method> parameterFunctions = new ArrayList<>(); 064 private static final List<Method> parameterFunctionsEnv = new ArrayList<>(); 065 066 static { 067 for (Method m : Functions.class.getDeclaredMethods()) { 068 Class<?>[] paramTypes = m.getParameterTypes(); 069 if (paramTypes.length == 1 && paramTypes[0].isArray()) { 070 arrayFunctions.add(m); 071 } else if (paramTypes.length >= 1 && paramTypes[0].equals(Environment.class)) { 072 parameterFunctionsEnv.add(m); 073 } else { 074 parameterFunctions.add(m); 075 } 076 } 077 try { 078 parameterFunctions.add(Math.class.getMethod("abs", float.class)); 079 parameterFunctions.add(Math.class.getMethod("acos", double.class)); 080 parameterFunctions.add(Math.class.getMethod("asin", double.class)); 081 parameterFunctions.add(Math.class.getMethod("atan", double.class)); 082 parameterFunctions.add(Math.class.getMethod("atan2", double.class, double.class)); 083 parameterFunctions.add(Math.class.getMethod("ceil", double.class)); 084 parameterFunctions.add(Math.class.getMethod("cos", double.class)); 085 parameterFunctions.add(Math.class.getMethod("cosh", double.class)); 086 parameterFunctions.add(Math.class.getMethod("exp", double.class)); 087 parameterFunctions.add(Math.class.getMethod("floor", double.class)); 088 parameterFunctions.add(Math.class.getMethod("log", double.class)); 089 parameterFunctions.add(Math.class.getMethod("max", float.class, float.class)); 090 parameterFunctions.add(Math.class.getMethod("min", float.class, float.class)); 091 parameterFunctions.add(Math.class.getMethod("random")); 092 parameterFunctions.add(Math.class.getMethod("round", float.class)); 093 parameterFunctions.add(Math.class.getMethod("signum", double.class)); 094 parameterFunctions.add(Math.class.getMethod("sin", double.class)); 095 parameterFunctions.add(Math.class.getMethod("sinh", double.class)); 096 parameterFunctions.add(Math.class.getMethod("sqrt", double.class)); 097 parameterFunctions.add(Math.class.getMethod("tan", double.class)); 098 parameterFunctions.add(Math.class.getMethod("tanh", double.class)); 099 } 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 ">=" operator. 577 * @param a first value 578 * @param b second value 579 * @return {@code true} if {@code a >= 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 "<=" operator. 587 * @param a first value 588 * @param b second value 589 * @return {@code true} if {@code a <= 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 ">" operator. 597 * @param a first value 598 * @param b second value 599 * @return {@code true} if {@code a > 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 "<" operator. 607 * @param a first value 608 * @param b second value 609 * @return {@code true} if {@code a < 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("<svg>...</svg>"));</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 <![CDATA[ ... ]]> 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 for (String code : codes.toUpperCase(Locale.ENGLISH).split(",")) { 969 if (Territories.isIso3166Code(code.trim(), center(env))) { 970 return true; 971 } 972 } 973 return false; 974 } 975 976 /** 977 * Determines if the object is outside territories matching given ISO3166 codes. 978 * @param env the environment 979 * @param codes comma-separated list of ISO3166-1-alpha2 or ISO3166-2 country/subdivision codes 980 * @return {@code true} if the object is outside territory matching given ISO3166 codes 981 * @since 11247 982 */ 983 public static boolean outside(Environment env, String codes) { // NO_UCD (unused code) 984 return !inside(env, codes); 985 } 986 } 987 988 /** 989 * Main method to create an function-like expression. 990 * 991 * @param name the name of the function or operator 992 * @param args the list of arguments (as expressions) 993 * @return the generated Expression. If no suitable function can be found, 994 * returns {@link NullExpression#INSTANCE}. 995 */ 996 public static Expression createFunctionExpression(String name, List<Expression> args) { 997 if ("cond".equals(name) && args.size() == 3) 998 return new CondOperator(args.get(0), args.get(1), args.get(2)); 999 else if ("and".equals(name)) 1000 return new AndOperator(args); 1001 else if ("or".equals(name)) 1002 return new OrOperator(args); 1003 else if ("length".equals(name) && args.size() == 1) 1004 return new LengthFunction(args.get(0)); 1005 else if ("max".equals(name) && !args.isEmpty()) 1006 return new MinMaxFunction(args, true); 1007 else if ("min".equals(name) && !args.isEmpty()) 1008 return new MinMaxFunction(args, false); 1009 1010 for (Method m : arrayFunctions) { 1011 if (m.getName().equals(name)) 1012 return new ArrayFunction(m, args); 1013 } 1014 for (Method m : parameterFunctions) { 1015 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length) 1016 return new ParameterFunction(m, args, false); 1017 } 1018 for (Method m : parameterFunctionsEnv) { 1019 if (m.getName().equals(name) && args.size() == m.getParameterTypes().length-1) 1020 return new ParameterFunction(m, args, true); 1021 } 1022 return NullExpression.INSTANCE; 1023 } 1024 1025 /** 1026 * Expression that always evaluates to null. 1027 */ 1028 public static class NullExpression implements Expression { 1029 1030 /** 1031 * The unique instance. 1032 */ 1033 public static final NullExpression INSTANCE = new NullExpression(); 1034 1035 @Override 1036 public Object evaluate(Environment env) { 1037 return null; 1038 } 1039 } 1040 1041 /** 1042 * Conditional operator. 1043 */ 1044 public static class CondOperator implements Expression { 1045 1046 private final Expression condition, firstOption, secondOption; 1047 1048 /** 1049 * Constructs a new {@code CondOperator}. 1050 * @param condition condition 1051 * @param firstOption first option 1052 * @param secondOption second option 1053 */ 1054 public CondOperator(Expression condition, Expression firstOption, Expression secondOption) { 1055 this.condition = condition; 1056 this.firstOption = firstOption; 1057 this.secondOption = secondOption; 1058 } 1059 1060 @Override 1061 public Object evaluate(Environment env) { 1062 Boolean b = Cascade.convertTo(condition.evaluate(env), boolean.class); 1063 if (b != null && b) 1064 return firstOption.evaluate(env); 1065 else 1066 return secondOption.evaluate(env); 1067 } 1068 } 1069 1070 /** 1071 * "And" logical operator. 1072 */ 1073 public static class AndOperator implements Expression { 1074 1075 private final List<Expression> args; 1076 1077 /** 1078 * Constructs a new {@code AndOperator}. 1079 * @param args arguments 1080 */ 1081 public AndOperator(List<Expression> args) { 1082 this.args = args; 1083 } 1084 1085 @Override 1086 public Object evaluate(Environment env) { 1087 for (Expression arg : args) { 1088 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class); 1089 if (b == null || !b) { 1090 return Boolean.FALSE; 1091 } 1092 } 1093 return Boolean.TRUE; 1094 } 1095 } 1096 1097 /** 1098 * "Or" logical operator. 1099 */ 1100 public static class OrOperator implements Expression { 1101 1102 private final List<Expression> args; 1103 1104 /** 1105 * Constructs a new {@code OrOperator}. 1106 * @param args arguments 1107 */ 1108 public OrOperator(List<Expression> args) { 1109 this.args = args; 1110 } 1111 1112 @Override 1113 public Object evaluate(Environment env) { 1114 for (Expression arg : args) { 1115 Boolean b = Cascade.convertTo(arg.evaluate(env), boolean.class); 1116 if (b != null && b) { 1117 return Boolean.TRUE; 1118 } 1119 } 1120 return Boolean.FALSE; 1121 } 1122 } 1123 1124 /** 1125 * Function to calculate the length of a string or list in a MapCSS eval expression. 1126 * 1127 * Separate implementation to support overloading for different argument types. 1128 * 1129 * The use for calculating the length of a list is deprecated, use 1130 * {@link Functions#count(java.util.List)} instead (see #10061). 1131 */ 1132 public static class LengthFunction implements Expression { 1133 1134 private final Expression arg; 1135 1136 /** 1137 * Constructs a new {@code LengthFunction}. 1138 * @param args arguments 1139 */ 1140 public LengthFunction(Expression args) { 1141 this.arg = args; 1142 } 1143 1144 @Override 1145 public Object evaluate(Environment env) { 1146 List<?> l = Cascade.convertTo(arg.evaluate(env), List.class); 1147 if (l != null) 1148 return l.size(); 1149 String s = Cascade.convertTo(arg.evaluate(env), String.class); 1150 if (s != null) 1151 return s.length(); 1152 return null; 1153 } 1154 } 1155 1156 /** 1157 * Computes the maximum/minimum value an arbitrary number of floats, or a list of floats. 1158 */ 1159 public static class MinMaxFunction implements Expression { 1160 1161 private final List<Expression> args; 1162 private final boolean computeMax; 1163 1164 /** 1165 * Constructs a new {@code MinMaxFunction}. 1166 * @param args arguments 1167 * @param computeMax if {@code true}, compute max. If {@code false}, compute min 1168 */ 1169 public MinMaxFunction(final List<Expression> args, final boolean computeMax) { 1170 this.args = args; 1171 this.computeMax = computeMax; 1172 } 1173 1174 public Float aggregateList(List<?> lst) { 1175 final List<Float> floats = Utils.transform(lst, (Function<Object, Float>) x -> Cascade.convertTo(x, float.class)); 1176 final Collection<Float> nonNullList = SubclassFilteredCollection.filter(floats, Objects::nonNull); 1177 return nonNullList.isEmpty() ? (Float) Float.NaN : computeMax ? Collections.max(nonNullList) : Collections.min(nonNullList); 1178 } 1179 1180 @Override 1181 public Object evaluate(final Environment env) { 1182 List<?> l = Cascade.convertTo(args.get(0).evaluate(env), List.class); 1183 if (args.size() != 1 || l == null) 1184 l = Utils.transform(args, (Function<Expression, Object>) x -> x.evaluate(env)); 1185 return aggregateList(l); 1186 } 1187 } 1188 1189 /** 1190 * Function that takes a certain number of argument with specific type. 1191 * 1192 * Implementation is based on a Method object. 1193 * If any of the arguments evaluate to null, the result will also be null. 1194 */ 1195 public static class ParameterFunction implements Expression { 1196 1197 private final Method m; 1198 private final boolean nullable; 1199 private final List<Expression> args; 1200 private final Class<?>[] expectedParameterTypes; 1201 private final boolean needsEnvironment; 1202 1203 /** 1204 * Constructs a new {@code ParameterFunction}. 1205 * @param m method 1206 * @param args arguments 1207 * @param needsEnvironment whether function needs environment 1208 */ 1209 public ParameterFunction(Method m, List<Expression> args, boolean needsEnvironment) { 1210 this.m = m; 1211 this.nullable = m.getAnnotation(NullableArguments.class) != null; 1212 this.args = args; 1213 this.expectedParameterTypes = m.getParameterTypes(); 1214 this.needsEnvironment = needsEnvironment; 1215 } 1216 1217 @Override 1218 public Object evaluate(Environment env) { 1219 Object[] convertedArgs; 1220 1221 if (needsEnvironment) { 1222 convertedArgs = new Object[args.size()+1]; 1223 convertedArgs[0] = env; 1224 for (int i = 1; i < convertedArgs.length; ++i) { 1225 convertedArgs[i] = Cascade.convertTo(args.get(i-1).evaluate(env), expectedParameterTypes[i]); 1226 if (convertedArgs[i] == null && !nullable) { 1227 return null; 1228 } 1229 } 1230 } else { 1231 convertedArgs = new Object[args.size()]; 1232 for (int i = 0; i < convertedArgs.length; ++i) { 1233 convertedArgs[i] = Cascade.convertTo(args.get(i).evaluate(env), expectedParameterTypes[i]); 1234 if (convertedArgs[i] == null && !nullable) { 1235 return null; 1236 } 1237 } 1238 } 1239 Object result = null; 1240 try { 1241 result = m.invoke(null, convertedArgs); 1242 } catch (IllegalAccessException | IllegalArgumentException ex) { 1243 throw new JosmRuntimeException(ex); 1244 } catch (InvocationTargetException ex) { 1245 Main.error(ex); 1246 return null; 1247 } 1248 return result; 1249 } 1250 1251 @Override 1252 public String toString() { 1253 StringBuilder b = new StringBuilder("ParameterFunction~"); 1254 b.append(m.getName()).append('('); 1255 for (int i = 0; i < args.size(); ++i) { 1256 if (i > 0) b.append(','); 1257 b.append(expectedParameterTypes[i]).append(' ').append(args.get(i)); 1258 } 1259 b.append(')'); 1260 return b.toString(); 1261 } 1262 } 1263 1264 /** 1265 * Function that takes an arbitrary number of arguments. 1266 * 1267 * Currently, all array functions are static, so there is no need to 1268 * provide the environment, like it is done in {@link ParameterFunction}. 1269 * If any of the arguments evaluate to null, the result will also be null. 1270 */ 1271 public static class ArrayFunction implements Expression { 1272 1273 private final Method m; 1274 private final boolean nullable; 1275 private final List<Expression> args; 1276 private final Class<?>[] expectedParameterTypes; 1277 private final Class<?> arrayComponentType; 1278 1279 /** 1280 * Constructs a new {@code ArrayFunction}. 1281 * @param m method 1282 * @param args arguments 1283 */ 1284 public ArrayFunction(Method m, List<Expression> args) { 1285 this.m = m; 1286 this.nullable = m.getAnnotation(NullableArguments.class) != null; 1287 this.args = args; 1288 this.expectedParameterTypes = m.getParameterTypes(); 1289 this.arrayComponentType = expectedParameterTypes[0].getComponentType(); 1290 } 1291 1292 @Override 1293 public Object evaluate(Environment env) { 1294 Object[] convertedArgs = new Object[expectedParameterTypes.length]; 1295 Object arrayArg = Array.newInstance(arrayComponentType, args.size()); 1296 for (int i = 0; i < args.size(); ++i) { 1297 Object o = Cascade.convertTo(args.get(i).evaluate(env), arrayComponentType); 1298 if (o == null && !nullable) { 1299 return null; 1300 } 1301 Array.set(arrayArg, i, o); 1302 } 1303 convertedArgs[0] = arrayArg; 1304 1305 Object result = null; 1306 try { 1307 result = m.invoke(null, convertedArgs); 1308 } catch (IllegalAccessException | IllegalArgumentException ex) { 1309 throw new JosmRuntimeException(ex); 1310 } catch (InvocationTargetException ex) { 1311 Main.error(ex); 1312 return null; 1313 } 1314 return result; 1315 } 1316 1317 @Override 1318 public String toString() { 1319 StringBuilder b = new StringBuilder("ArrayFunction~"); 1320 b.append(m.getName()).append('('); 1321 for (int i = 0; i < args.size(); ++i) { 1322 if (i > 0) b.append(','); 1323 b.append(arrayComponentType).append(' ').append(args.get(i)); 1324 } 1325 b.append(')'); 1326 return b.toString(); 1327 } 1328 } 1329}