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