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

Last change on this file since 7125 was 7125, checked in by simon04, 10 years ago

MapCSS parsing: warn on unknown base selectors (2/2)

  • Property svn:eol-style set to native
File size: 12.2 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.ByteArrayInputStream;
8import java.io.File;
9import java.io.IOException;
10import java.io.InputStream;
11import java.nio.charset.StandardCharsets;
12import java.text.MessageFormat;
13import java.util.ArrayList;
14import java.util.List;
15import java.util.Map.Entry;
16import java.util.zip.ZipEntry;
17import java.util.zip.ZipFile;
18
19import org.openstreetmap.josm.Main;
20import org.openstreetmap.josm.data.Version;
21import org.openstreetmap.josm.data.osm.Node;
22import org.openstreetmap.josm.data.osm.OsmPrimitive;
23import org.openstreetmap.josm.data.osm.Relation;
24import org.openstreetmap.josm.data.osm.Way;
25import org.openstreetmap.josm.gui.mappaint.Cascade;
26import org.openstreetmap.josm.gui.mappaint.Environment;
27import org.openstreetmap.josm.gui.mappaint.MultiCascade;
28import org.openstreetmap.josm.gui.mappaint.Range;
29import org.openstreetmap.josm.gui.mappaint.StyleSource;
30import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.ChildOrParentSelector;
31import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
32import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
33import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
34import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError;
35import org.openstreetmap.josm.gui.preferences.SourceEntry;
36import org.openstreetmap.josm.io.MirroredInputStream;
37import org.openstreetmap.josm.tools.CheckParameterUtil;
38import org.openstreetmap.josm.tools.LanguageInfo;
39import org.openstreetmap.josm.tools.Utils;
40
41public class MapCSSStyleSource extends StyleSource {
42
43 /**
44 * The accepted MIME types sent in the HTTP Accept header.
45 * @since 6867
46 */
47 public static final String MAPCSS_STYLE_MIME_TYPES = "text/x-mapcss, text/mapcss, text/css; q=0.9, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5";
48
49 // all rules
50 public final List<MapCSSRule> rules = new ArrayList<>();
51 // rules filtered by primitive type
52 public final List<MapCSSRule> nodeRules = new ArrayList<>();
53 public final List<MapCSSRule> wayRules = new ArrayList<>();
54 public final List<MapCSSRule> relationRules = new ArrayList<>();
55 public final List<MapCSSRule> multipolygonRules = new ArrayList<>();
56 public final List<MapCSSRule> canvasRules = new ArrayList<>();
57
58 private Color backgroundColorOverride;
59 private String css = null;
60 private ZipFile zipFile;
61
62 public MapCSSStyleSource(String url, String name, String shortdescription) {
63 super(url, name, shortdescription);
64 }
65
66 public MapCSSStyleSource(SourceEntry entry) {
67 super(entry);
68 }
69
70 /**
71 * <p>Creates a new style source from the MapCSS styles supplied in
72 * {@code css}</p>
73 *
74 * @param css the MapCSS style declaration. Must not be null.
75 * @throws IllegalArgumentException thrown if {@code css} is null
76 */
77 public MapCSSStyleSource(String css) throws IllegalArgumentException{
78 super(null, null, null);
79 CheckParameterUtil.ensureParameterNotNull(css);
80 this.css = css;
81 }
82
83 @Override
84 public void loadStyleSource() {
85 init();
86 rules.clear();
87 nodeRules.clear();
88 wayRules.clear();
89 relationRules.clear();
90 multipolygonRules.clear();
91 canvasRules.clear();
92 try (InputStream in = getSourceInputStream()) {
93 try {
94 // evaluate @media { ... } blocks
95 MapCSSParser preprocessor = new MapCSSParser(in, "UTF-8", MapCSSParser.LexicalState.PREPROCESSOR);
96 String mapcss = preprocessor.pp_root(this);
97
98 // do the actual mapcss parsing
99 InputStream in2 = new ByteArrayInputStream(mapcss.getBytes(StandardCharsets.UTF_8));
100 MapCSSParser parser = new MapCSSParser(in2, "UTF-8", MapCSSParser.LexicalState.DEFAULT);
101 parser.sheet(this);
102
103 loadMeta();
104 loadCanvas();
105 } finally {
106 closeSourceInputStream(in);
107 }
108 } catch (IOException e) {
109 Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
110 Main.error(e);
111 logError(e);
112 } catch (TokenMgrError e) {
113 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
114 Main.error(e);
115 logError(e);
116 } catch (ParseException e) {
117 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
118 Main.error(e);
119 logError(new ParseException(e.getMessage())); // allow e to be garbage collected, it links to the entire token stream
120 }
121 // optimization: filter rules for different primitive types
122 for (MapCSSRule r: rules) {
123 // find the rightmost selector, this must be a GeneralSelector
124 Selector selRightmost = r.selector;
125 while (selRightmost instanceof ChildOrParentSelector) {
126 selRightmost = ((ChildOrParentSelector) selRightmost).right;
127 }
128 MapCSSRule optRule = new MapCSSRule(r.selector.optimizedBaseCheck(), r.declaration);
129 final String base = ((GeneralSelector) selRightmost).getBase();
130 switch (base) {
131 case "node":
132 nodeRules.add(optRule);
133 break;
134 case "way":
135 wayRules.add(optRule);
136 break;
137 case "area":
138 wayRules.add(optRule);
139 multipolygonRules.add(optRule);
140 break;
141 case "relation":
142 relationRules.add(optRule);
143 multipolygonRules.add(optRule);
144 break;
145 case "*":
146 nodeRules.add(optRule);
147 wayRules.add(optRule);
148 relationRules.add(optRule);
149 multipolygonRules.add(optRule);
150 break;
151 case "canvas":
152 canvasRules.add(r);
153 break;
154 case "meta":
155 break;
156 default:
157 final RuntimeException e = new RuntimeException(MessageFormat.format("Unknown MapCSS base selector {0}", base));
158 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
159 Main.error(e);
160 logError(e);
161 }
162 }
163 }
164
165 @Override
166 public InputStream getSourceInputStream() throws IOException {
167 if (css != null) {
168 return new ByteArrayInputStream(css.getBytes(StandardCharsets.UTF_8));
169 }
170 MirroredInputStream in = getMirroredInputStream();
171 if (isZip) {
172 File file = in.getFile();
173 Utils.close(in);
174 zipFile = new ZipFile(file, StandardCharsets.UTF_8);
175 zipIcons = file;
176 ZipEntry zipEntry = zipFile.getEntry(zipEntryPath);
177 return zipFile.getInputStream(zipEntry);
178 } else {
179 zipFile = null;
180 zipIcons = null;
181 return in;
182 }
183 }
184
185 @Override
186 public MirroredInputStream getMirroredInputStream() throws IOException {
187 return new MirroredInputStream(url, null, MAPCSS_STYLE_MIME_TYPES);
188 }
189
190 @Override
191 public void closeSourceInputStream(InputStream is) {
192 super.closeSourceInputStream(is);
193 if (isZip) {
194 Utils.close(zipFile);
195 }
196 }
197
198 /**
199 * load meta info from a selector "meta"
200 */
201 private void loadMeta() {
202 Cascade c = constructSpecial("meta");
203 String pTitle = c.get("title", null, String.class);
204 if (title == null) {
205 title = pTitle;
206 }
207 String pIcon = c.get("icon", null, String.class);
208 if (icon == null) {
209 icon = pIcon;
210 }
211 }
212
213 private void loadCanvas() {
214 Cascade c = constructSpecial("canvas");
215 backgroundColorOverride = c.get("fill-color", null, Color.class);
216 if (backgroundColorOverride == null) {
217 backgroundColorOverride = c.get("background-color", null, Color.class);
218 if (backgroundColorOverride != null) {
219 Main.warn(tr("Detected deprecated {0} in {1} which will be removed shortly.", "canvas{background-color}", url));
220 }
221 }
222 }
223
224 private Cascade constructSpecial(String type) {
225
226 MultiCascade mc = new MultiCascade();
227 Node n = new Node();
228 String code = LanguageInfo.getJOSMLocaleCode();
229 n.put("lang", code);
230 // create a fake environment to read the meta data block
231 Environment env = new Environment(n, mc, "default", this);
232
233 for (MapCSSRule r : rules) {
234 if ((r.selector instanceof GeneralSelector)) {
235 GeneralSelector gs = (GeneralSelector) r.selector;
236 if (gs.getBase().equals(type)) {
237 if (!gs.matchesConditions(env)) {
238 continue;
239 }
240 r.execute(env);
241 }
242 }
243 }
244 return mc.getCascade("default");
245 }
246
247 @Override
248 public Color getBackgroundColorOverride() {
249 return backgroundColorOverride;
250 }
251
252 @Override
253 public void apply(MultiCascade mc, OsmPrimitive osm, double scale, OsmPrimitive multipolyOuterWay, boolean pretendWayIsClosed) {
254 Environment env = new Environment(osm, mc, null, this);
255 List<MapCSSRule> matchingRules;
256 if (osm instanceof Node) {
257 matchingRules = nodeRules;
258 } else if (osm instanceof Way) {
259 matchingRules = wayRules;
260 } else {
261 if (((Relation) osm).isMultipolygon()) {
262 matchingRules = multipolygonRules;
263 } else if (osm.hasKey("#canvas")) {
264 matchingRules = canvasRules;
265 } else {
266 matchingRules = relationRules;
267 }
268 }
269
270 // the declaration indices are sorted, so it suffices to save the
271 // last used index
272 int lastDeclUsed = -1;
273
274 for (MapCSSRule r : matchingRules) {
275 env.clearSelectorMatchingInformation();
276 if (r.selector.matches(env)) { // as side effect env.parent will be set (if s is a child selector)
277 Selector s = r.selector;
278 if (s.getRange().contains(scale)) {
279 mc.range = Range.cut(mc.range, s.getRange());
280 } else {
281 mc.range = mc.range.reduceAround(scale, s.getRange());
282 continue;
283 }
284
285 if (r.declaration.idx == lastDeclUsed) continue; // don't apply one declaration more than once
286 lastDeclUsed = r.declaration.idx;
287 String sub = s.getSubpart();
288 if (sub == null) {
289 sub = "default";
290 }
291 else if ("*".equals(sub)) {
292 for (Entry<String, Cascade> entry : mc.getLayers()) {
293 env.layer = entry.getKey();
294 if ("*".equals(env.layer)) {
295 continue;
296 }
297 r.execute(env);
298 }
299 }
300 env.layer = sub;
301 r.execute(env);
302 }
303 }
304 }
305
306 public boolean evalMediaExpression(String feature, Object val) {
307 if ("user-agent".equals(feature)) {
308 String s = Cascade.convertTo(val, String.class);
309 if ("josm".equals(s)) return true;
310 }
311 if ("min-josm-version".equals(feature)) {
312 Float v = Cascade.convertTo(val, Float.class);
313 if (v != null) return Math.round(v) <= Version.getInstance().getVersion();
314 }
315 if ("max-josm-version".equals(feature)) {
316 Float v = Cascade.convertTo(val, Float.class);
317 if (v != null) return Math.round(v) >= Version.getInstance().getVersion();
318 }
319 return false;
320 }
321
322 @Override
323 public String toString() {
324 return Utils.join("\n", rules);
325 }
326}
Note: See TracBrowser for help on using the repository browser.