001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.mappaint.mapcss; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Color; 007import java.io.BufferedReader; 008import java.io.ByteArrayInputStream; 009import java.io.File; 010import java.io.IOException; 011import java.io.InputStream; 012import java.io.Reader; 013import java.io.StringReader; 014import java.lang.reflect.Field; 015import java.nio.charset.StandardCharsets; 016import java.util.ArrayList; 017import java.util.HashSet; 018import java.util.Iterator; 019import java.util.List; 020import java.util.Locale; 021import java.util.Map.Entry; 022import java.util.Set; 023import java.util.concurrent.locks.ReadWriteLock; 024import java.util.concurrent.locks.ReentrantReadWriteLock; 025import java.util.stream.Collectors; 026import java.util.zip.ZipEntry; 027import java.util.zip.ZipFile; 028 029import org.openstreetmap.josm.data.Version; 030import org.openstreetmap.josm.data.osm.IPrimitive; 031import org.openstreetmap.josm.data.osm.Node; 032import org.openstreetmap.josm.data.preferences.sources.SourceEntry; 033import org.openstreetmap.josm.gui.mappaint.Cascade; 034import org.openstreetmap.josm.gui.mappaint.Environment; 035import org.openstreetmap.josm.gui.mappaint.MultiCascade; 036import org.openstreetmap.josm.gui.mappaint.Range; 037import org.openstreetmap.josm.gui.mappaint.StyleKeys; 038import org.openstreetmap.josm.gui.mappaint.StyleSetting; 039import org.openstreetmap.josm.gui.mappaint.StyleSetting.StyleSettingGroup; 040import org.openstreetmap.josm.gui.mappaint.StyleSettingFactory; 041import org.openstreetmap.josm.gui.mappaint.StyleSource; 042import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector; 043import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser; 044import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException; 045import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError; 046import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement; 047import org.openstreetmap.josm.io.CachedFile; 048import org.openstreetmap.josm.io.UTFInputStreamReader; 049import org.openstreetmap.josm.tools.CheckParameterUtil; 050import org.openstreetmap.josm.tools.I18n; 051import org.openstreetmap.josm.tools.JosmRuntimeException; 052import org.openstreetmap.josm.tools.LanguageInfo; 053import org.openstreetmap.josm.tools.Logging; 054import org.openstreetmap.josm.tools.Utils; 055 056/** 057 * This is a mappaint style that is based on MapCSS rules. 058 */ 059public class MapCSSStyleSource extends StyleSource { 060 061 /** 062 * The accepted MIME types sent in the HTTP Accept header. 063 * @since 6867 064 */ 065 public static final String MAPCSS_STYLE_MIME_TYPES = 066 "text/x-mapcss, text/mapcss, text/css; q=0.9, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5"; 067 068 /** 069 * all rules in this style file 070 */ 071 public final List<MapCSSRule> rules = new ArrayList<>(); 072 /** 073 * Index of rules in this style file 074 */ 075 private final MapCSSStyleIndex ruleIndex = new MapCSSStyleIndex(); 076 077 private Color backgroundColorOverride; 078 private String css; 079 private ZipFile zipFile; 080 081 private boolean removeAreaStylePseudoClass; 082 083 /** 084 * This lock prevents concurrent execution of {@link MapCSSRuleIndex#clear() } / 085 * {@link MapCSSRuleIndex#initIndex()} and {@link MapCSSRuleIndex#getRuleCandidates }. 086 * 087 * For efficiency reasons, these methods are synchronized higher up the 088 * stack trace. 089 */ 090 public static final ReadWriteLock STYLE_SOURCE_LOCK = new ReentrantReadWriteLock(); 091 092 /** 093 * Set of all supported MapCSS keys. 094 */ 095 static final Set<String> SUPPORTED_KEYS = new HashSet<>(); 096 static { 097 for (Field f : StyleKeys.class.getDeclaredFields()) { 098 try { 099 SUPPORTED_KEYS.add((String) f.get(null)); 100 if (!f.getName().toLowerCase(Locale.ENGLISH).replace('_', '-').equals(f.get(null))) { 101 throw new JosmRuntimeException(f.getName()); 102 } 103 } catch (IllegalArgumentException | IllegalAccessException ex) { 104 throw new JosmRuntimeException(ex); 105 } 106 } 107 for (LineElement.LineType lt : LineElement.LineType.values()) { 108 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.COLOR); 109 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES); 110 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_BACKGROUND_COLOR); 111 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_BACKGROUND_OPACITY); 112 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_OFFSET); 113 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.LINECAP); 114 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.LINEJOIN); 115 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.MITERLIMIT); 116 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.OFFSET); 117 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.OPACITY); 118 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.REAL_WIDTH); 119 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.WIDTH); 120 } 121 } 122 123 /** 124 * Constructs a new, active {@link MapCSSStyleSource}. 125 * @param url URL that {@link org.openstreetmap.josm.io.CachedFile} understands 126 * @param name The name for this StyleSource 127 * @param shortdescription The title for that source. 128 */ 129 public MapCSSStyleSource(String url, String name, String shortdescription) { 130 super(url, name, shortdescription); 131 } 132 133 /** 134 * Constructs a new {@link MapCSSStyleSource} 135 * @param entry The entry to copy the data (url, name, ...) from. 136 */ 137 public MapCSSStyleSource(SourceEntry entry) { 138 super(entry); 139 } 140 141 /** 142 * <p>Creates a new style source from the MapCSS styles supplied in 143 * {@code css}</p> 144 * 145 * @param css the MapCSS style declaration. Must not be null. 146 * @throws IllegalArgumentException if {@code css} is null 147 */ 148 public MapCSSStyleSource(String css) { 149 super(null, null, null); 150 CheckParameterUtil.ensureParameterNotNull(css); 151 this.css = css; 152 } 153 154 @Override 155 public void loadStyleSource(boolean metadataOnly) { 156 STYLE_SOURCE_LOCK.writeLock().lock(); 157 try { 158 init(); 159 rules.clear(); 160 ruleIndex.clear(); 161 // remove "areaStyle" pseudo classes intended only for validator (causes StackOverflowError otherwise), see #16183 162 removeAreaStylePseudoClass = url == null || !url.contains("validator"); // resource://data/validator/ or xxx.validator.mapcss 163 try (InputStream in = getSourceInputStream()) { 164 try (Reader reader = new BufferedReader(UTFInputStreamReader.create(in))) { 165 // evaluate @media { ... } blocks 166 MapCSSParser preprocessor = new MapCSSParser(reader, MapCSSParser.LexicalState.PREPROCESSOR); 167 168 // do the actual mapcss parsing 169 try (Reader in2 = new StringReader(preprocessor.pp_root(this))) { 170 new MapCSSParser(in2, MapCSSParser.LexicalState.DEFAULT).sheet(this); 171 } 172 173 loadMeta(); 174 if (!metadataOnly) { 175 loadCanvas(); 176 loadSettings(); 177 } else { 178 rules.clear(); 179 } 180 } finally { 181 closeSourceInputStream(in); 182 } 183 } catch (IOException | IllegalArgumentException e) { 184 Logging.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString())); 185 Logging.log(Logging.LEVEL_ERROR, e); 186 logError(e); 187 } catch (TokenMgrError e) { 188 Logging.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage())); 189 Logging.error(e); 190 logError(e); 191 } catch (ParseException e) { 192 Logging.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage())); 193 Logging.error(e); 194 logError(new ParseException(e.getMessage())); // allow e to be garbage collected, it links to the entire token stream 195 } 196 if (metadataOnly) { 197 return; 198 } 199 // optimization: filter rules for different primitive types 200 ruleIndex.buildIndex(rules.stream()); 201 loaded = true; 202 } finally { 203 STYLE_SOURCE_LOCK.writeLock().unlock(); 204 } 205 } 206 207 @Override 208 public InputStream getSourceInputStream() throws IOException { 209 if (css != null) { 210 return new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8)); 211 } 212 // This just closes any open http connections. It does not (with the current CachedFile implementation) close 213 // streams that it provides via getInputStream. 214 try (CachedFile cf = getCachedFile()) { 215 if (isZip) { 216 File file = cf.getFile(); 217 zipFile = new ZipFile(file, StandardCharsets.UTF_8); 218 zipIcons = file; 219 I18n.addTexts(zipIcons); 220 ZipEntry zipEntry = zipFile.getEntry(zipEntryPath); 221 return zipFile.getInputStream(zipEntry); 222 } else { 223 zipFile = null; 224 zipIcons = null; 225 return cf.getInputStream(); 226 } 227 } 228 } 229 230 @Override 231 @SuppressWarnings("resource") 232 public CachedFile getCachedFile() throws IOException { 233 return new CachedFile(url).setHttpAccept(MAPCSS_STYLE_MIME_TYPES); // NOSONAR 234 } 235 236 @Override 237 public void closeSourceInputStream(InputStream is) { 238 super.closeSourceInputStream(is); 239 if (isZip) { 240 Utils.close(zipFile); 241 } 242 } 243 244 /** 245 * load meta info from a selector "meta" 246 */ 247 private void loadMeta() { 248 Cascade c = constructSpecial(Selector.BASE_META); 249 String pTitle = c.get("title", null, String.class); 250 if (title == null) { 251 title = pTitle; 252 } 253 String pIcon = c.get("icon", null, String.class); 254 if (icon == null) { 255 icon = pIcon; 256 } 257 } 258 259 private void loadCanvas() { 260 Cascade c = constructSpecial(Selector.BASE_CANVAS); 261 backgroundColorOverride = c.get("fill-color", null, Color.class); 262 } 263 264 private static void loadSettings(MapCSSRule r, GeneralSelector gs, Environment env) { 265 if (gs.matchesConditions(env)) { 266 env.layer = null; 267 env.layer = gs.getSubpart().getId(env); 268 r.execute(env); 269 } 270 } 271 272 private void loadSettings() { 273 settings.clear(); 274 settingValues.clear(); 275 settingGroups.clear(); 276 MultiCascade mc = new MultiCascade(); 277 MultiCascade mcGroups = new MultiCascade(); 278 Node n = new Node(); 279 n.put("lang", LanguageInfo.getJOSMLocaleCode()); 280 // create a fake environment to read the meta data block 281 Environment env = new Environment(n, mc, "default", this); 282 Environment envGroups = new Environment(n, mcGroups, "default", this); 283 284 // Parse rules 285 for (MapCSSRule r : rules) { 286 final Selector gs = r.selectors.get(0); 287 if (gs instanceof GeneralSelector) { 288 if (Selector.BASE_SETTING.equals(gs.getBase())) { 289 loadSettings(r, ((GeneralSelector) gs), env); 290 } else if (Selector.BASE_SETTINGS.equals(gs.getBase())) { 291 loadSettings(r, ((GeneralSelector) gs), envGroups); 292 } 293 } 294 } 295 // Load groups 296 for (Entry<String, Cascade> e : mcGroups.getLayers()) { 297 if ("default".equals(e.getKey())) { 298 Logging.warn("settings requires layer identifier e.g. 'settings::settings_group {...}'"); 299 continue; 300 } 301 settingGroups.put(StyleSettingGroup.create(e.getValue(), this, e.getKey()), new ArrayList<>()); 302 } 303 // Load settings 304 for (Entry<String, Cascade> e : mc.getLayers()) { 305 if ("default".equals(e.getKey())) { 306 Logging.warn("setting requires layer identifier e.g. 'setting::my_setting {...}'"); 307 continue; 308 } 309 Cascade c = e.getValue(); 310 StyleSetting set = StyleSettingFactory.create(c, this, e.getKey()); 311 if (set != null) { 312 settings.add(set); 313 settingValues.put(e.getKey(), set.getValue()); 314 String groupId = c.get("group", null, String.class); 315 if (groupId != null) { 316 final StyleSettingGroup group = settingGroups.keySet().stream() 317 .filter(g -> g.key.equals(groupId)) 318 .findAny() 319 .orElseThrow(() -> new IllegalArgumentException("Unknown settings group: " + groupId)); 320 settingGroups.get(group).add(set); 321 } 322 } 323 } 324 settings.sort(null); 325 } 326 327 private Cascade constructSpecial(String type) { 328 329 MultiCascade mc = new MultiCascade(); 330 Node n = new Node(); 331 String code = LanguageInfo.getJOSMLocaleCode(); 332 n.put("lang", code); 333 // create a fake environment to read the meta data block 334 Environment env = new Environment(n, mc, "default", this); 335 336 for (MapCSSRule r : rules) { 337 final boolean matches = r.selectors.stream().anyMatch(gs -> gs instanceof GeneralSelector 338 && gs.getBase().equals(type) 339 && ((GeneralSelector) gs).matchesConditions(env)); 340 if (matches) { 341 r.execute(env); 342 } 343 } 344 return mc.getCascade("default"); 345 } 346 347 @Override 348 public Color getBackgroundColorOverride() { 349 return backgroundColorOverride; 350 } 351 352 @Override 353 public void apply(MultiCascade mc, IPrimitive osm, double scale, boolean pretendWayIsClosed) { 354 355 Environment env = new Environment(osm, mc, null, this); 356 // the declaration indices are sorted, so it suffices to save the last used index 357 int lastDeclUsed = -1; 358 359 Iterator<MapCSSRule> candidates = ruleIndex.getRuleCandidates(osm); 360 while (candidates.hasNext()) { 361 MapCSSRule r = candidates.next(); 362 for (Selector s : r.selectors) { 363 env.clearSelectorMatchingInformation(); 364 env.layer = s.getSubpart().getId(env); 365 String sub = env.layer; 366 if (!s.matches(env)) { // as side effect env.parent will be set (if s is a child selector) 367 continue; 368 } 369 if (s.getRange().contains(scale)) { 370 mc.range = Range.cut(mc.range, s.getRange()); 371 } else { 372 mc.range = mc.range.reduceAround(scale, s.getRange()); 373 continue; 374 } 375 376 if (r.declaration.idx == lastDeclUsed) 377 continue; // don't apply one declaration more than once 378 lastDeclUsed = r.declaration.idx; 379 if ("*".equals(sub)) { 380 for (Entry<String, Cascade> entry : mc.getLayers()) { 381 env.layer = entry.getKey(); 382 if ("*".equals(env.layer)) { 383 continue; 384 } 385 r.execute(env); 386 } 387 } 388 env.layer = sub; 389 r.execute(env); 390 } 391 } 392 } 393 394 /** 395 * Evaluate a supports condition 396 * @param feature The feature to evaluate for 397 * @param val The additional parameter passed to evaluate 398 * @return <code>true</code> if JSOM supports that feature 399 */ 400 public boolean evalSupportsDeclCondition(String feature, Object val) { 401 if (feature == null) return false; 402 if (SUPPORTED_KEYS.contains(feature)) return true; 403 switch (feature) { 404 case "user-agent": 405 String s = Cascade.convertTo(val, String.class); 406 return "josm".equals(s); 407 case "min-josm-version": 408 Float min = Cascade.convertTo(val, Float.class); 409 return min != null && Math.round(min) <= Version.getInstance().getVersion(); 410 case "max-josm-version": 411 Float max = Cascade.convertTo(val, Float.class); 412 return max != null && Math.round(max) >= Version.getInstance().getVersion(); 413 default: 414 return false; 415 } 416 } 417 418 /** 419 * Removes "meta" rules. Not needed for validator. 420 * @since 13633 421 */ 422 public void removeMetaRules() { 423 rules.removeIf(x -> x.selectors.get(0) instanceof GeneralSelector && Selector.BASE_META.equals(x.selectors.get(0).getBase())); 424 } 425 426 /** 427 * Whether to remove "areaStyle" pseudo classes. Only for use in MapCSSParser! 428 * @return whether to remove "areaStyle" pseudo classes 429 */ 430 public boolean isRemoveAreaStylePseudoClass() { 431 return removeAreaStylePseudoClass; 432 } 433 434 @Override 435 public String toString() { 436 // Avoids ConcurrentModificationException 437 return new ArrayList<>(rules).stream().map(MapCSSRule::toString).collect(Collectors.joining("\n")); 438 } 439}