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

Last change on this file since 7033 was 7033, checked in by Don-vip, 10 years ago

see #8465 - global use of try-with-resources, according to

  • Property svn:eol-style set to native
File size: 8.7 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.util.ArrayList;
12import java.util.List;
13import java.util.Map.Entry;
14import java.util.zip.ZipEntry;
15import java.util.zip.ZipFile;
16
17import org.openstreetmap.josm.Main;
18import org.openstreetmap.josm.data.Version;
19import org.openstreetmap.josm.data.osm.Node;
20import org.openstreetmap.josm.data.osm.OsmPrimitive;
21import org.openstreetmap.josm.gui.mappaint.Cascade;
22import org.openstreetmap.josm.gui.mappaint.Environment;
23import org.openstreetmap.josm.gui.mappaint.MultiCascade;
24import org.openstreetmap.josm.gui.mappaint.Range;
25import org.openstreetmap.josm.gui.mappaint.StyleSource;
26import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector;
27import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
28import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
29import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.TokenMgrError;
30import org.openstreetmap.josm.gui.preferences.SourceEntry;
31import org.openstreetmap.josm.io.MirroredInputStream;
32import org.openstreetmap.josm.tools.CheckParameterUtil;
33import org.openstreetmap.josm.tools.LanguageInfo;
34import org.openstreetmap.josm.tools.Utils;
35
36public class MapCSSStyleSource extends StyleSource {
37
38 /**
39 * The accepted MIME types sent in the HTTP Accept header.
40 * @since 6867
41 */
42 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";
43
44 public final List<MapCSSRule> rules;
45 private Color backgroundColorOverride;
46 private String css = null;
47 private ZipFile zipFile;
48
49 public MapCSSStyleSource(String url, String name, String shortdescription) {
50 super(url, name, shortdescription);
51 rules = new ArrayList<>();
52 }
53
54 public MapCSSStyleSource(SourceEntry entry) {
55 super(entry);
56 rules = new ArrayList<>();
57 }
58
59 /**
60 * <p>Creates a new style source from the MapCSS styles supplied in
61 * {@code css}</p>
62 *
63 * @param css the MapCSS style declaration. Must not be null.
64 * @throws IllegalArgumentException thrown if {@code css} is null
65 */
66 public MapCSSStyleSource(String css) throws IllegalArgumentException{
67 super(null, null, null);
68 CheckParameterUtil.ensureParameterNotNull(css);
69 this.css = css;
70 rules = new ArrayList<>();
71 }
72
73 @Override
74 public void loadStyleSource() {
75 init();
76 rules.clear();
77 try (InputStream in = getSourceInputStream()) {
78 try {
79 // evaluate @media { ... } blocks
80 MapCSSParser preprocessor = new MapCSSParser(in, "UTF-8", MapCSSParser.LexicalState.PREPROCESSOR);
81 String mapcss = preprocessor.pp_root(this);
82
83 // do the actual mapcss parsing
84 InputStream in2 = new ByteArrayInputStream(mapcss.getBytes(Utils.UTF_8));
85 MapCSSParser parser = new MapCSSParser(in2, "UTF-8", MapCSSParser.LexicalState.DEFAULT);
86 parser.sheet(this);
87
88 loadMeta();
89 loadCanvas();
90 } finally {
91 closeSourceInputStream(in);
92 }
93 } catch (IOException e) {
94 Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
95 Main.error(e);
96 logError(e);
97 } catch (TokenMgrError e) {
98 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
99 Main.error(e);
100 logError(e);
101 } catch (ParseException e) {
102 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
103 Main.error(e);
104 logError(new ParseException(e.getMessage())); // allow e to be garbage collected, it links to the entire token stream
105 }
106 }
107
108 @Override
109 public InputStream getSourceInputStream() throws IOException {
110 if (css != null) {
111 return new ByteArrayInputStream(css.getBytes(Utils.UTF_8));
112 }
113 MirroredInputStream in = new MirroredInputStream(url, null, MAPCSS_STYLE_MIME_TYPES);
114 if (isZip) {
115 File file = in.getFile();
116 Utils.close(in);
117 zipFile = new ZipFile(file);
118 zipIcons = file;
119 ZipEntry zipEntry = zipFile.getEntry(zipEntryPath);
120 return zipFile.getInputStream(zipEntry);
121 } else {
122 zipFile = null;
123 zipIcons = null;
124 return in;
125 }
126 }
127
128 @Override
129 public void closeSourceInputStream(InputStream is) {
130 super.closeSourceInputStream(is);
131 if (isZip) {
132 Utils.close(zipFile);
133 }
134 }
135
136 /**
137 * load meta info from a selector "meta"
138 */
139 private void loadMeta() {
140 Cascade c = constructSpecial("meta");
141 String pTitle = c.get("title", null, String.class);
142 if (title == null) {
143 title = pTitle;
144 }
145 String pIcon = c.get("icon", null, String.class);
146 if (icon == null) {
147 icon = pIcon;
148 }
149 }
150
151 private void loadCanvas() {
152 Cascade c = constructSpecial("canvas");
153 backgroundColorOverride = c.get("background-color", null, Color.class);
154 }
155
156 private Cascade constructSpecial(String type) {
157
158 MultiCascade mc = new MultiCascade();
159 Node n = new Node();
160 String code = LanguageInfo.getJOSMLocaleCode();
161 n.put("lang", code);
162 // create a fake environment to read the meta data block
163 Environment env = new Environment(n, mc, "default", this);
164
165 NEXT_RULE:
166 for (MapCSSRule r : rules) {
167 for (Selector s : r.selectors) {
168 if ((s instanceof GeneralSelector)) {
169 GeneralSelector gs = (GeneralSelector) s;
170 if (gs.getBase().equals(type)) {
171 if (!gs.matchesConditions(env)) {
172 continue NEXT_RULE;
173 }
174 r.execute(env);
175 }
176 }
177 }
178 }
179 return mc.getCascade("default");
180 }
181
182 @Override
183 public Color getBackgroundColorOverride() {
184 return backgroundColorOverride;
185 }
186
187 @Override
188 public void apply(MultiCascade mc, OsmPrimitive osm, double scale, OsmPrimitive multipolyOuterWay, boolean pretendWayIsClosed) {
189 Environment env = new Environment(osm, mc, null, this);
190 RULE: for (MapCSSRule r : rules) {
191 for (Selector s : r.selectors) {
192 env.clearSelectorMatchingInformation();
193 if (s.matches(env)) { // as side effect env.parent will be set (if s is a child selector)
194 if (s.getRange().contains(scale)) {
195 mc.range = Range.cut(mc.range, s.getRange());
196 } else {
197 mc.range = mc.range.reduceAround(scale, s.getRange());
198 continue;
199 }
200
201 String sub = s.getSubpart();
202 if (sub == null) {
203 sub = "default";
204 }
205 else if ("*".equals(sub)) {
206 for (Entry<String, Cascade> entry : mc.getLayers()) {
207 env.layer = entry.getKey();
208 if (Utils.equal(env.layer, "*")) {
209 continue;
210 }
211 r.execute(env);
212 }
213 }
214 env.layer = sub;
215 r.execute(env);
216 continue RULE;
217 }
218 }
219 }
220 }
221
222 public boolean evalMediaExpression(String feature, Object val) {
223 if ("user-agent".equals(feature)) {
224 String s = Cascade.convertTo(val, String.class);
225 if ("josm".equals(s)) return true;
226 }
227 if ("min-josm-version".equals(feature)) {
228 Float v = Cascade.convertTo(val, Float.class);
229 if (v != null) return Math.round(v) <= Version.getInstance().getVersion();
230 }
231 if ("max-josm-version".equals(feature)) {
232 Float v = Cascade.convertTo(val, Float.class);
233 if (v != null) return Math.round(v) >= Version.getInstance().getVersion();
234 }
235 return false;
236 }
237
238 @Override
239 public String toString() {
240 return Utils.join("\n", rules);
241 }
242}
Note: See TracBrowser for help on using the repository browser.