source: josm/trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java@ 15986

Last change on this file since 15986 was 15986, checked in by simon04, 4 years ago

see #18802 - Add Selector.getBase

  • Property svn:eol-style set to native
File size: 29.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.mappaint.mapcss;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Color;
7import java.io.BufferedReader;
8import java.io.ByteArrayInputStream;
9import java.io.File;
10import java.io.IOException;
11import java.io.InputStream;
12import java.io.Reader;
13import java.io.StringReader;
14import java.lang.reflect.Field;
15import java.nio.charset.StandardCharsets;
16import java.text.MessageFormat;
17import java.util.ArrayList;
18import java.util.BitSet;
19import java.util.Collection;
20import java.util.Collections;
21import java.util.HashMap;
22import java.util.HashSet;
23import java.util.Iterator;
24import java.util.List;
25import java.util.Locale;
26import java.util.Map;
27import java.util.Map.Entry;
28import java.util.NoSuchElementException;
29import java.util.Optional;
30import java.util.Set;
31import java.util.concurrent.locks.ReadWriteLock;
32import java.util.concurrent.locks.ReentrantReadWriteLock;
33import java.util.stream.Collectors;
34import java.util.zip.ZipEntry;
35import java.util.zip.ZipFile;
36
37import org.openstreetmap.josm.data.Version;
38import org.openstreetmap.josm.data.osm.INode;
39import org.openstreetmap.josm.data.osm.IPrimitive;
40import org.openstreetmap.josm.data.osm.IRelation;
41import org.openstreetmap.josm.data.osm.IWay;
42import org.openstreetmap.josm.data.osm.KeyValueVisitor;
43import org.openstreetmap.josm.data.osm.Node;
44import org.openstreetmap.josm.data.osm.OsmUtils;
45import org.openstreetmap.josm.data.osm.Tagged;
46import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
47import org.openstreetmap.josm.gui.mappaint.Cascade;
48import org.openstreetmap.josm.gui.mappaint.Environment;
49import org.openstreetmap.josm.gui.mappaint.MultiCascade;
50import org.openstreetmap.josm.gui.mappaint.Range;
51import org.openstreetmap.josm.gui.mappaint.StyleKeys;
52import org.openstreetmap.josm.gui.mappaint.StyleSetting;
53import org.openstreetmap.josm.gui.mappaint.StyleSetting.StyleSettingGroup;
54import org.openstreetmap.josm.gui.mappaint.StyleSettingFactory;
55import org.openstreetmap.josm.gui.mappaint.StyleSource;
56import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.KeyCondition;
57import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.KeyMatchType;
58import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.KeyValueCondition;
59import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition;
60import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
61import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
62import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
63import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError;
64import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement;
65import org.openstreetmap.josm.io.CachedFile;
66import org.openstreetmap.josm.io.UTFInputStreamReader;
67import org.openstreetmap.josm.tools.CheckParameterUtil;
68import org.openstreetmap.josm.tools.I18n;
69import org.openstreetmap.josm.tools.JosmRuntimeException;
70import org.openstreetmap.josm.tools.LanguageInfo;
71import org.openstreetmap.josm.tools.Logging;
72import org.openstreetmap.josm.tools.Utils;
73
74/**
75 * This is a mappaint style that is based on MapCSS rules.
76 */
77public class MapCSSStyleSource extends StyleSource {
78
79 /**
80 * The accepted MIME types sent in the HTTP Accept header.
81 * @since 6867
82 */
83 public static final String MAPCSS_STYLE_MIME_TYPES =
84 "text/x-mapcss, text/mapcss, text/css; q=0.9, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5";
85
86 /**
87 * all rules in this style file
88 */
89 public final List<MapCSSRule> rules = new ArrayList<>();
90 /**
91 * Rules for nodes
92 */
93 public final MapCSSRuleIndex nodeRules = new MapCSSRuleIndex();
94 /**
95 * Rules for ways without tag area=no
96 */
97 public final MapCSSRuleIndex wayRules = new MapCSSRuleIndex();
98 /**
99 * Rules for ways with tag area=no
100 */
101 public final MapCSSRuleIndex wayNoAreaRules = new MapCSSRuleIndex();
102 /**
103 * Rules for relations that are not multipolygon relations
104 */
105 public final MapCSSRuleIndex relationRules = new MapCSSRuleIndex();
106 /**
107 * Rules for multipolygon relations
108 */
109 public final MapCSSRuleIndex multipolygonRules = new MapCSSRuleIndex();
110 /**
111 * rules to apply canvas properties
112 */
113 public final MapCSSRuleIndex canvasRules = new MapCSSRuleIndex();
114
115 private Color backgroundColorOverride;
116 private String css;
117 private ZipFile zipFile;
118
119 private boolean removeAreaStylePseudoClass;
120
121 /**
122 * This lock prevents concurrent execution of {@link MapCSSRuleIndex#clear() } /
123 * {@link MapCSSRuleIndex#initIndex()} and {@link MapCSSRuleIndex#getRuleCandidates }.
124 *
125 * For efficiency reasons, these methods are synchronized higher up the
126 * stack trace.
127 */
128 public static final ReadWriteLock STYLE_SOURCE_LOCK = new ReentrantReadWriteLock();
129
130 /**
131 * Set of all supported MapCSS keys.
132 */
133 static final Set<String> SUPPORTED_KEYS = new HashSet<>();
134 static {
135 Field[] declaredFields = StyleKeys.class.getDeclaredFields();
136 for (Field f : declaredFields) {
137 try {
138 SUPPORTED_KEYS.add((String) f.get(null));
139 if (!f.getName().toLowerCase(Locale.ENGLISH).replace('_', '-').equals(f.get(null))) {
140 throw new JosmRuntimeException(f.getName());
141 }
142 } catch (IllegalArgumentException | IllegalAccessException ex) {
143 throw new JosmRuntimeException(ex);
144 }
145 }
146 for (LineElement.LineType lt : LineElement.LineType.values()) {
147 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.COLOR);
148 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES);
149 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_BACKGROUND_COLOR);
150 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_BACKGROUND_OPACITY);
151 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.DASHES_OFFSET);
152 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.LINECAP);
153 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.LINEJOIN);
154 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.MITERLIMIT);
155 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.OFFSET);
156 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.OPACITY);
157 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.REAL_WIDTH);
158 SUPPORTED_KEYS.add(lt.prefix + StyleKeys.WIDTH);
159 }
160 }
161
162 /**
163 * A collection of {@link MapCSSRule}s, that are indexed by tag key and value.
164 *
165 * Speeds up the process of finding all rules that match a certain primitive.
166 *
167 * Rules with a {@link SimpleKeyValueCondition} [key=value] or rules that require a specific key to be set are
168 * indexed. Now you only need to loop the tags of a primitive to retrieve the possibly matching rules.
169 *
170 * To use this index, you need to {@link #add(MapCSSRule)} all rules to it. You then need to call
171 * {@link #initIndex()}. Afterwards, you can use {@link #getRuleCandidates(IPrimitive)} to get an iterator over
172 * all rules that might be applied to that primitive.
173 */
174 public static class MapCSSRuleIndex {
175 /**
176 * This is an iterator over all rules that are marked as possible in the bitset.
177 *
178 * @author Michael Zangl
179 */
180 private final class RuleCandidatesIterator implements Iterator<MapCSSRule>, KeyValueVisitor {
181 private final BitSet ruleCandidates;
182 private int next;
183
184 private RuleCandidatesIterator(BitSet ruleCandidates) {
185 this.ruleCandidates = ruleCandidates;
186 }
187
188 @Override
189 public boolean hasNext() {
190 return next >= 0 && next < rules.size();
191 }
192
193 @Override
194 public MapCSSRule next() {
195 if (!hasNext())
196 throw new NoSuchElementException();
197 MapCSSRule rule = rules.get(next);
198 next = ruleCandidates.nextSetBit(next + 1);
199 return rule;
200 }
201
202 @Override
203 public void remove() {
204 throw new UnsupportedOperationException();
205 }
206
207 @Override
208 public void visitKeyValue(Tagged p, String key, String value) {
209 MapCSSKeyRules v = index.get(key);
210 if (v != null) {
211 BitSet rs = v.get(value);
212 ruleCandidates.or(rs);
213 }
214 }
215
216 /**
217 * Call this before using the iterator.
218 */
219 public void prepare() {
220 next = ruleCandidates.nextSetBit(0);
221 }
222 }
223
224 /**
225 * This is a map of all rules that are only applied if the primitive has a given key (and possibly value)
226 *
227 * @author Michael Zangl
228 */
229 private static final class MapCSSKeyRules {
230 /**
231 * The indexes of rules that might be applied if this tag is present and the value has no special handling.
232 */
233 BitSet generalRules = new BitSet();
234
235 /**
236 * A map that sores the indexes of rules that might be applied if the key=value pair is present on this
237 * primitive. This includes all key=* rules.
238 */
239 Map<String, BitSet> specialRules = new HashMap<>();
240
241 public void addForKey(int ruleIndex) {
242 generalRules.set(ruleIndex);
243 for (BitSet r : specialRules.values()) {
244 r.set(ruleIndex);
245 }
246 }
247
248 public void addForKeyAndValue(String value, int ruleIndex) {
249 BitSet forValue = specialRules.get(value);
250 if (forValue == null) {
251 forValue = new BitSet();
252 forValue.or(generalRules);
253 specialRules.put(value.intern(), forValue);
254 }
255 forValue.set(ruleIndex);
256 }
257
258 public BitSet get(String value) {
259 BitSet forValue = specialRules.get(value);
260 if (forValue != null) return forValue; else return generalRules;
261 }
262 }
263
264 /**
265 * All rules this index is for. Once this index is built, this list is sorted.
266 */
267 private final List<MapCSSRule> rules = new ArrayList<>();
268 /**
269 * All rules that only apply when the given key is present.
270 */
271 private final Map<String, MapCSSKeyRules> index = new HashMap<>();
272 /**
273 * Rules that do not require any key to be present. Only the index in the {@link #rules} array is stored.
274 */
275 private final BitSet remaining = new BitSet();
276
277 /**
278 * Add a rule to this index. This needs to be called before {@link #initIndex()} is called.
279 * @param rule The rule to add.
280 */
281 public void add(MapCSSRule rule) {
282 rules.add(rule);
283 }
284
285 /**
286 * Initialize the index.
287 * <p>
288 * You must own the write lock of STYLE_SOURCE_LOCK when calling this method.
289 */
290 public void initIndex() {
291 Collections.sort(rules);
292 for (int ruleIndex = 0; ruleIndex < rules.size(); ruleIndex++) {
293 MapCSSRule r = rules.get(ruleIndex);
294 final List<Condition> conditions = r.selector.getConditions();
295 if (conditions == null || conditions.isEmpty()) {
296 remaining.set(ruleIndex);
297 continue;
298 }
299 Optional<SimpleKeyValueCondition> lastCondition = Utils.filteredCollection(conditions, SimpleKeyValueCondition.class).stream()
300 .reduce((first, last) -> last);
301 if (lastCondition.isPresent()) {
302 getEntryInIndex(lastCondition.get().k).addForKeyAndValue(lastCondition.get().v, ruleIndex);
303 } else {
304 String key = findAnyRequiredKey(conditions);
305 if (key != null) {
306 getEntryInIndex(key).addForKey(ruleIndex);
307 } else {
308 remaining.set(ruleIndex);
309 }
310 }
311 }
312 }
313
314 /**
315 * Search for any key that condition might depend on.
316 *
317 * @param conds The conditions to search through.
318 * @return An arbitrary key this rule depends on or <code>null</code> if there is no such key.
319 */
320 private static String findAnyRequiredKey(List<Condition> conds) {
321 String key = null;
322 for (Condition c : conds) {
323 if (c instanceof KeyCondition) {
324 KeyCondition keyCondition = (KeyCondition) c;
325 if (!keyCondition.negateResult && conditionRequiresKeyPresence(keyCondition.matchType)) {
326 key = keyCondition.label;
327 }
328 } else if (c instanceof KeyValueCondition) {
329 KeyValueCondition keyValueCondition = (KeyValueCondition) c;
330 if (keyValueCondition.requiresExactKeyMatch()) {
331 key = keyValueCondition.k;
332 }
333 }
334 }
335 return key;
336 }
337
338 private static boolean conditionRequiresKeyPresence(KeyMatchType matchType) {
339 return matchType != KeyMatchType.REGEX;
340 }
341
342 private MapCSSKeyRules getEntryInIndex(String key) {
343 MapCSSKeyRules rulesWithMatchingKey = index.get(key);
344 if (rulesWithMatchingKey == null) {
345 rulesWithMatchingKey = new MapCSSKeyRules();
346 index.put(key.intern(), rulesWithMatchingKey);
347 }
348 return rulesWithMatchingKey;
349 }
350
351 /**
352 * Get a subset of all rules that might match the primitive. Rules not included in the result are guaranteed to
353 * not match this primitive.
354 * <p>
355 * You must have a read lock of STYLE_SOURCE_LOCK when calling this method.
356 *
357 * @param osm the primitive to match
358 * @return An iterator over possible rules in the right order.
359 * @since 13810 (signature)
360 */
361 public Iterator<MapCSSRule> getRuleCandidates(IPrimitive osm) {
362 final BitSet ruleCandidates = new BitSet(rules.size());
363 ruleCandidates.or(remaining);
364
365 final RuleCandidatesIterator candidatesIterator = new RuleCandidatesIterator(ruleCandidates);
366 osm.visitKeys(candidatesIterator);
367 candidatesIterator.prepare();
368 return candidatesIterator;
369 }
370
371 /**
372 * Clear the index.
373 * <p>
374 * You must own the write lock STYLE_SOURCE_LOCK when calling this method.
375 */
376 public void clear() {
377 rules.clear();
378 index.clear();
379 remaining.clear();
380 }
381 }
382
383 /**
384 * Constructs a new, active {@link MapCSSStyleSource}.
385 * @param url URL that {@link org.openstreetmap.josm.io.CachedFile} understands
386 * @param name The name for this StyleSource
387 * @param shortdescription The title for that source.
388 */
389 public MapCSSStyleSource(String url, String name, String shortdescription) {
390 super(url, name, shortdescription);
391 }
392
393 /**
394 * Constructs a new {@link MapCSSStyleSource}
395 * @param entry The entry to copy the data (url, name, ...) from.
396 */
397 public MapCSSStyleSource(SourceEntry entry) {
398 super(entry);
399 }
400
401 /**
402 * <p>Creates a new style source from the MapCSS styles supplied in
403 * {@code css}</p>
404 *
405 * @param css the MapCSS style declaration. Must not be null.
406 * @throws IllegalArgumentException if {@code css} is null
407 */
408 public MapCSSStyleSource(String css) {
409 super(null, null, null);
410 CheckParameterUtil.ensureParameterNotNull(css);
411 this.css = css;
412 }
413
414 @Override
415 public void loadStyleSource(boolean metadataOnly) {
416 STYLE_SOURCE_LOCK.writeLock().lock();
417 try {
418 init();
419 rules.clear();
420 nodeRules.clear();
421 wayRules.clear();
422 wayNoAreaRules.clear();
423 relationRules.clear();
424 multipolygonRules.clear();
425 canvasRules.clear();
426 // remove "areaStyle" pseudo classes intended only for validator (causes StackOverflowError otherwise), see #16183
427 removeAreaStylePseudoClass = url == null || !url.contains("validator"); // resource://data/validator/ or xxx.validator.mapcss
428 try (InputStream in = getSourceInputStream()) {
429 try (Reader reader = new BufferedReader(UTFInputStreamReader.create(in))) {
430 // evaluate @media { ... } blocks
431 MapCSSParser preprocessor = new MapCSSParser(reader, MapCSSParser.LexicalState.PREPROCESSOR);
432
433 // do the actual mapcss parsing
434 try (Reader in2 = new StringReader(preprocessor.pp_root(this))) {
435 new MapCSSParser(in2, MapCSSParser.LexicalState.DEFAULT).sheet(this);
436 }
437
438 loadMeta();
439 if (!metadataOnly) {
440 loadCanvas();
441 loadSettings();
442 }
443 } finally {
444 closeSourceInputStream(in);
445 }
446 } catch (IOException | IllegalArgumentException e) {
447 Logging.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
448 Logging.log(Logging.LEVEL_ERROR, e);
449 logError(e);
450 } catch (TokenMgrError e) {
451 Logging.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
452 Logging.error(e);
453 logError(e);
454 } catch (ParseException e) {
455 Logging.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
456 Logging.error(e);
457 logError(new ParseException(e.getMessage())); // allow e to be garbage collected, it links to the entire token stream
458 }
459 if (metadataOnly) {
460 return;
461 }
462 // optimization: filter rules for different primitive types
463 for (MapCSSRule r: rules) {
464 MapCSSRule optRule = new MapCSSRule(r.selector.optimizedBaseCheck(), r.declaration);
465 final String base = r.selector.getBase();
466 switch (base) {
467 case Selector.BASE_NODE:
468 nodeRules.add(optRule);
469 break;
470 case Selector.BASE_WAY:
471 wayNoAreaRules.add(optRule);
472 wayRules.add(optRule);
473 break;
474 case Selector.BASE_AREA:
475 wayRules.add(optRule);
476 multipolygonRules.add(optRule);
477 break;
478 case Selector.BASE_RELATION:
479 relationRules.add(optRule);
480 multipolygonRules.add(optRule);
481 break;
482 case Selector.BASE_ANY:
483 nodeRules.add(optRule);
484 wayRules.add(optRule);
485 wayNoAreaRules.add(optRule);
486 relationRules.add(optRule);
487 multipolygonRules.add(optRule);
488 break;
489 case Selector.BASE_CANVAS:
490 canvasRules.add(r);
491 break;
492 case Selector.BASE_META:
493 case Selector.BASE_SETTING:
494 case Selector.BASE_SETTINGS:
495 break;
496 default:
497 final RuntimeException e = new JosmRuntimeException(MessageFormat.format("Unknown MapCSS base selector {0}", base));
498 Logging.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
499 Logging.error(e);
500 logError(e);
501 }
502 }
503 nodeRules.initIndex();
504 wayRules.initIndex();
505 wayNoAreaRules.initIndex();
506 relationRules.initIndex();
507 multipolygonRules.initIndex();
508 canvasRules.initIndex();
509 loaded = true;
510 } finally {
511 STYLE_SOURCE_LOCK.writeLock().unlock();
512 }
513 }
514
515 @Override
516 public InputStream getSourceInputStream() throws IOException {
517 if (css != null) {
518 return new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8));
519 }
520 CachedFile cf = getCachedFile();
521 if (isZip) {
522 File file = cf.getFile();
523 zipFile = new ZipFile(file, StandardCharsets.UTF_8);
524 zipIcons = file;
525 I18n.addTexts(zipIcons);
526 ZipEntry zipEntry = zipFile.getEntry(zipEntryPath);
527 return zipFile.getInputStream(zipEntry);
528 } else {
529 zipFile = null;
530 zipIcons = null;
531 return cf.getInputStream();
532 }
533 }
534
535 @Override
536 @SuppressWarnings("resource")
537 public CachedFile getCachedFile() throws IOException {
538 return new CachedFile(url).setHttpAccept(MAPCSS_STYLE_MIME_TYPES); // NOSONAR
539 }
540
541 @Override
542 public void closeSourceInputStream(InputStream is) {
543 super.closeSourceInputStream(is);
544 if (isZip) {
545 Utils.close(zipFile);
546 }
547 }
548
549 /**
550 * load meta info from a selector "meta"
551 */
552 private void loadMeta() {
553 Cascade c = constructSpecial(Selector.BASE_META);
554 String pTitle = c.get("title", null, String.class);
555 if (title == null) {
556 title = pTitle;
557 }
558 String pIcon = c.get("icon", null, String.class);
559 if (icon == null) {
560 icon = pIcon;
561 }
562 }
563
564 private void loadCanvas() {
565 Cascade c = constructSpecial(Selector.BASE_CANVAS);
566 backgroundColorOverride = c.get("fill-color", null, Color.class);
567 }
568
569 private static void loadSettings(MapCSSRule r, GeneralSelector gs, Environment env) {
570 if (gs.matchesConditions(env)) {
571 env.layer = null;
572 env.layer = gs.getSubpart().getId(env);
573 r.execute(env);
574 }
575 }
576
577 private void loadSettings() {
578 settings.clear();
579 settingValues.clear();
580 settingGroups.clear();
581 MultiCascade mc = new MultiCascade();
582 MultiCascade mcGroups = new MultiCascade();
583 Node n = new Node();
584 n.put("lang", LanguageInfo.getJOSMLocaleCode());
585 // create a fake environment to read the meta data block
586 Environment env = new Environment(n, mc, "default", this);
587 Environment envGroups = new Environment(n, mcGroups, "default", this);
588
589 // Parse rules
590 for (MapCSSRule r : rules) {
591 if (r.selector instanceof GeneralSelector) {
592 GeneralSelector gs = (GeneralSelector) r.selector;
593 if (Selector.BASE_SETTING.equals(gs.getBase())) {
594 loadSettings(r, gs, env);
595 } else if (Selector.BASE_SETTINGS.equals(gs.getBase())) {
596 loadSettings(r, gs, envGroups);
597 }
598 }
599 }
600 // Load groups
601 for (Entry<String, Cascade> e : mcGroups.getLayers()) {
602 if ("default".equals(e.getKey())) {
603 Logging.warn("settings requires layer identifier e.g. 'settings::settings_group {...}'");
604 continue;
605 }
606 settingGroups.put(StyleSettingGroup.create(e.getValue(), this, e.getKey()), new ArrayList<>());
607 }
608 // Load settings
609 for (Entry<String, Cascade> e : mc.getLayers()) {
610 if ("default".equals(e.getKey())) {
611 Logging.warn("setting requires layer identifier e.g. 'setting::my_setting {...}'");
612 continue;
613 }
614 Cascade c = e.getValue();
615 StyleSetting set = StyleSettingFactory.create(c, this, e.getKey());
616 if (set != null) {
617 settings.add(set);
618 settingValues.put(e.getKey(), set.getValue());
619 String groupId = c.get("group", null, String.class);
620 if (groupId != null) {
621 final StyleSettingGroup group = settingGroups.keySet().stream()
622 .filter(g -> g.key.equals(groupId))
623 .findAny()
624 .orElseThrow(() -> new IllegalArgumentException("Unknown settings group: " + groupId));
625 settingGroups.get(group).add(set);
626 }
627 }
628 }
629 settings.sort(null);
630 }
631
632 private Cascade constructSpecial(String type) {
633
634 MultiCascade mc = new MultiCascade();
635 Node n = new Node();
636 String code = LanguageInfo.getJOSMLocaleCode();
637 n.put("lang", code);
638 // create a fake environment to read the meta data block
639 Environment env = new Environment(n, mc, "default", this);
640
641 for (MapCSSRule r : rules) {
642 if (r.selector instanceof GeneralSelector) {
643 GeneralSelector gs = (GeneralSelector) r.selector;
644 if (gs.getBase().equals(type)) {
645 if (!gs.matchesConditions(env)) {
646 continue;
647 }
648 r.execute(env);
649 }
650 }
651 }
652 return mc.getCascade("default");
653 }
654
655 @Override
656 public Color getBackgroundColorOverride() {
657 return backgroundColorOverride;
658 }
659
660 @Override
661 public void apply(MultiCascade mc, IPrimitive osm, double scale, boolean pretendWayIsClosed) {
662 MapCSSRuleIndex matchingRuleIndex;
663 if (osm instanceof INode) {
664 matchingRuleIndex = nodeRules;
665 } else if (osm instanceof IWay) {
666 if (OsmUtils.isFalse(osm.get("area"))) {
667 matchingRuleIndex = wayNoAreaRules;
668 } else {
669 matchingRuleIndex = wayRules;
670 }
671 } else if (osm instanceof IRelation) {
672 if (((IRelation<?>) osm).isMultipolygon()) {
673 matchingRuleIndex = multipolygonRules;
674 } else if (osm.hasKey("#canvas")) {
675 matchingRuleIndex = canvasRules;
676 } else {
677 matchingRuleIndex = relationRules;
678 }
679 } else {
680 throw new IllegalArgumentException("Unsupported type: " + osm);
681 }
682
683 Environment env = new Environment(osm, mc, null, this);
684 // the declaration indices are sorted, so it suffices to save the last used index
685 int lastDeclUsed = -1;
686
687 Iterator<MapCSSRule> candidates = matchingRuleIndex.getRuleCandidates(osm);
688 while (candidates.hasNext()) {
689 MapCSSRule r = candidates.next();
690 env.clearSelectorMatchingInformation();
691 env.layer = r.selector.getSubpart().getId(env);
692 String sub = env.layer;
693 if (r.selector.matches(env)) { // as side effect env.parent will be set (if s is a child selector)
694 Selector s = r.selector;
695 if (s.getRange().contains(scale)) {
696 mc.range = Range.cut(mc.range, s.getRange());
697 } else {
698 mc.range = mc.range.reduceAround(scale, s.getRange());
699 continue;
700 }
701
702 if (r.declaration.idx == lastDeclUsed)
703 continue; // don't apply one declaration more than once
704 lastDeclUsed = r.declaration.idx;
705 if ("*".equals(sub)) {
706 for (Entry<String, Cascade> entry : mc.getLayers()) {
707 env.layer = entry.getKey();
708 if ("*".equals(env.layer)) {
709 continue;
710 }
711 r.execute(env);
712 }
713 }
714 env.layer = sub;
715 r.execute(env);
716 }
717 }
718 }
719
720 /**
721 * Evaluate a supports condition
722 * @param feature The feature to evaluate for
723 * @param val The additional parameter passed to evaluate
724 * @return <code>true</code> if JSOM supports that feature
725 */
726 public boolean evalSupportsDeclCondition(String feature, Object val) {
727 if (feature == null) return false;
728 if (SUPPORTED_KEYS.contains(feature)) return true;
729 switch (feature) {
730 case "user-agent":
731 String s = Cascade.convertTo(val, String.class);
732 return "josm".equals(s);
733 case "min-josm-version":
734 Float min = Cascade.convertTo(val, Float.class);
735 return min != null && Math.round(min) <= Version.getInstance().getVersion();
736 case "max-josm-version":
737 Float max = Cascade.convertTo(val, Float.class);
738 return max != null && Math.round(max) >= Version.getInstance().getVersion();
739 default:
740 return false;
741 }
742 }
743
744 /**
745 * Removes "meta" rules. Not needed for validator.
746 * @since 13633
747 */
748 public void removeMetaRules() {
749 rules.removeIf(x -> x.selector instanceof GeneralSelector && Selector.BASE_META.equals(x.selector.getBase()));
750 }
751
752 /**
753 * Whether to remove "areaStyle" pseudo classes. Only for use in MapCSSParser!
754 * @return whether to remove "areaStyle" pseudo classes
755 */
756 public boolean isRemoveAreaStylePseudoClass() {
757 return removeAreaStylePseudoClass;
758 }
759
760 @Override
761 public String toString() {
762 return rules.stream().map(MapCSSRule::toString).collect(Collectors.joining("\n"));
763 }
764}
Note: See TracBrowser for help on using the repository browser.