001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.gui.mappaint.xml;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.IOException;
007import java.io.InputStream;
008import java.io.InputStreamReader;
009import java.nio.charset.StandardCharsets;
010import java.util.Collection;
011import java.util.Collections;
012import java.util.HashMap;
013import java.util.LinkedList;
014import java.util.List;
015import java.util.Map;
016import java.util.Objects;
017
018import org.openstreetmap.josm.Main;
019import org.openstreetmap.josm.data.osm.Node;
020import org.openstreetmap.josm.data.osm.OsmPrimitive;
021import org.openstreetmap.josm.data.osm.OsmUtils;
022import org.openstreetmap.josm.data.osm.Relation;
023import org.openstreetmap.josm.data.osm.Way;
024import org.openstreetmap.josm.gui.mappaint.Cascade;
025import org.openstreetmap.josm.gui.mappaint.Keyword;
026import org.openstreetmap.josm.gui.mappaint.MultiCascade;
027import org.openstreetmap.josm.gui.mappaint.Range;
028import org.openstreetmap.josm.gui.mappaint.StyleKeys;
029import org.openstreetmap.josm.gui.mappaint.StyleSource;
030import org.openstreetmap.josm.gui.preferences.SourceEntry;
031import org.openstreetmap.josm.io.CachedFile;
032import org.openstreetmap.josm.tools.Utils;
033import org.openstreetmap.josm.tools.XmlObjectParser;
034import org.xml.sax.SAXException;
035import org.xml.sax.SAXParseException;
036
037public class XmlStyleSource extends StyleSource implements StyleKeys {
038
039    /**
040     * The accepted MIME types sent in the HTTP Accept header.
041     * @since 6867
042     */
043    public static final String XML_STYLE_MIME_TYPES = "application/xml, text/xml, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5";
044
045    protected final Map<String, IconPrototype> icons = new HashMap<>();
046    protected final Map<String, LinePrototype> lines = new HashMap<>();
047    protected final Map<String, LinemodPrototype> modifiers = new HashMap<>();
048    protected final Map<String, AreaPrototype> areas = new HashMap<>();
049    protected final List<IconPrototype> iconsList = new LinkedList<>();
050    protected final List<LinePrototype> linesList = new LinkedList<>();
051    protected final List<LinemodPrototype> modifiersList = new LinkedList<>();
052    protected final List<AreaPrototype> areasList = new LinkedList<>();
053
054    public XmlStyleSource(String url, String name, String shortdescription) {
055        super(url, name, shortdescription);
056    }
057
058    public XmlStyleSource(SourceEntry entry) {
059        super(entry);
060    }
061
062    @Override
063    protected void init() {
064        super.init();
065        icons.clear();
066        lines.clear();
067        modifiers.clear();
068        areas.clear();
069        iconsList.clear();
070        linesList.clear();
071        modifiersList.clear();
072        areasList.clear();
073    }
074
075    @Override
076    public void loadStyleSource() {
077        init();
078        try {
079            try (
080                InputStream in = getSourceInputStream();
081                InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8)
082            ) {
083                XmlObjectParser parser = new XmlObjectParser(new XmlStyleSourceHandler(this));
084                parser.startWithValidation(reader,
085                        Main.getXMLBase()+"/mappaint-style-1.0",
086                        "resource://data/mappaint-style.xsd");
087                while (parser.hasNext());
088            }
089        } catch (IOException e) {
090            Main.warn(tr("Failed to load Mappaint styles from ''{0}''. Exception was: {1}", url, e.toString()));
091            Main.error(e);
092            logError(e);
093        } catch (SAXParseException e) {
094            Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: [{1}:{2}] {3}", url, e.getLineNumber(), e.getColumnNumber(), e.getMessage()));
095            Main.error(e);
096            logError(e);
097        } catch (SAXException e) {
098            Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: {1}", url, e.getMessage()));
099            Main.error(e);
100            logError(e);
101        }
102    }
103
104    @Override
105    public InputStream getSourceInputStream() throws IOException {
106        CachedFile cf = getCachedFile();
107        InputStream zip = cf.findZipEntryInputStream("xml", "style");
108        if (zip != null) {
109            zipIcons = cf.getFile();
110            return zip;
111        } else {
112            zipIcons = null;
113            return cf.getInputStream();
114        }
115    }
116
117    @Override
118    public CachedFile getCachedFile() throws IOException {
119        return new CachedFile(url).setHttpAccept(XML_STYLE_MIME_TYPES);
120    }
121
122    private static class WayPrototypesRecord {
123        public LinePrototype line;
124        public List<LinemodPrototype> linemods;
125        public AreaPrototype area;
126    }
127
128    private <T extends Prototype> T update(T current, T candidate, Double scale, MultiCascade mc) {
129        if (requiresUpdate(current, candidate, scale, mc))
130            return candidate;
131        else
132            return current;
133    }
134
135    /**
136     * checks whether a certain match is better than the current match
137     * @param current can be null
138     * @param candidate the new Prototype that could be used instead
139     * @param scale ignored if null, otherwise checks if scale is within the range of candidate
140     * @param mc side effect: update the valid region for the current MultiCascade
141     */
142    private boolean requiresUpdate(Prototype current, Prototype candidate, Double scale, MultiCascade mc) {
143        if (current == null || candidate.priority >= current.priority) {
144            if (scale == null)
145                return true;
146
147            if (candidate.range.contains(scale)) {
148                mc.range = Range.cut(mc.range, candidate.range);
149                return true;
150            } else {
151                mc.range = mc.range.reduceAround(scale, candidate.range);
152                return false;
153            }
154        }
155        return false;
156    }
157
158    private IconPrototype getNode(OsmPrimitive primitive, Double scale, MultiCascade mc) {
159        IconPrototype icon = null;
160        for (String key : primitive.keySet()) {
161            String val = primitive.get(key);
162            IconPrototype p;
163            if ((p = icons.get("n" + key + "=" + val)) != null) {
164                icon = update(icon, p, scale, mc);
165            }
166            if ((p = icons.get("b" + key + "=" + OsmUtils.getNamedOsmBoolean(val))) != null) {
167                icon = update(icon, p, scale, mc);
168            }
169            if ((p = icons.get("x" + key)) != null) {
170                icon = update(icon, p, scale, mc);
171            }
172        }
173        for (IconPrototype s : iconsList) {
174            if (s.check(primitive))
175            {
176                icon = update(icon, s, scale, mc);
177            }
178        }
179        return icon;
180    }
181
182    /**
183     * @param closed The primitive is a closed way or we pretend it is closed.
184     *  This is useful for multipolygon relations and outer ways of untagged
185     *  multipolygon relations.
186     */
187    private void get(OsmPrimitive primitive, boolean closed, WayPrototypesRecord p, Double scale, MultiCascade mc) {
188        String lineIdx = null;
189        HashMap<String, LinemodPrototype> overlayMap = new HashMap<>();
190        boolean isNotArea = primitive.isKeyFalse("area");
191        for (String key : primitive.keySet()) {
192            String val = primitive.get(key);
193            AreaPrototype styleArea;
194            LinePrototype styleLine;
195            LinemodPrototype styleLinemod;
196            String idx = "n" + key + "=" + val;
197            if ((styleArea = areas.get(idx)) != null && (closed || !styleArea.closed) && !isNotArea) {
198                p.area = update(p.area, styleArea, scale, mc);
199            }
200            if ((styleLine = lines.get(idx)) != null) {
201                if (requiresUpdate(p.line, styleLine, scale, mc)) {
202                    p.line = styleLine;
203                    lineIdx = idx;
204                }
205            }
206            if ((styleLinemod = modifiers.get(idx)) != null) {
207                if (requiresUpdate(null, styleLinemod, scale, mc)) {
208                    overlayMap.put(idx, styleLinemod);
209                }
210            }
211            idx = "b" + key + "=" + OsmUtils.getNamedOsmBoolean(val);
212            if ((styleArea = areas.get(idx)) != null && (closed || !styleArea.closed) && !isNotArea) {
213                p.area = update(p.area, styleArea, scale, mc);
214            }
215            if ((styleLine = lines.get(idx)) != null) {
216                if (requiresUpdate(p.line, styleLine, scale, mc)) {
217                    p.line = styleLine;
218                    lineIdx = idx;
219                }
220            }
221            if ((styleLinemod = modifiers.get(idx)) != null) {
222                if (requiresUpdate(null, styleLinemod, scale, mc)) {
223                    overlayMap.put(idx, styleLinemod);
224                }
225            }
226            idx = "x" + key;
227            if ((styleArea = areas.get(idx)) != null && (closed || !styleArea.closed) && !isNotArea) {
228                p.area = update(p.area, styleArea, scale, mc);
229            }
230            if ((styleLine = lines.get(idx)) != null) {
231                if (requiresUpdate(p.line, styleLine, scale, mc)) {
232                    p.line = styleLine;
233                    lineIdx = idx;
234                }
235            }
236            if ((styleLinemod = modifiers.get(idx)) != null) {
237                if (requiresUpdate(null, styleLinemod, scale, mc)) {
238                    overlayMap.put(idx, styleLinemod);
239                }
240            }
241        }
242        for (AreaPrototype s : areasList) {
243            if ((closed || !s.closed) && !isNotArea && s.check(primitive)) {
244                p.area = update(p.area, s, scale, mc);
245            }
246        }
247        for (LinePrototype s : linesList) {
248            if (s.check(primitive)) {
249                p.line = update(p.line, s, scale, mc);
250            }
251        }
252        for (LinemodPrototype s : modifiersList) {
253            if (s.check(primitive)) {
254                if (requiresUpdate(null, s, scale, mc)) {
255                    overlayMap.put(s.getCode(), s);
256                }
257            }
258        }
259        overlayMap.remove(lineIdx); // do not use overlay if linestyle is from the same rule (example: railway=tram)
260        if (!overlayMap.isEmpty()) {
261            List<LinemodPrototype> tmp = new LinkedList<>();
262            if (p.linemods != null) {
263                tmp.addAll(p.linemods);
264            }
265            tmp.addAll(overlayMap.values());
266            Collections.sort(tmp);
267            p.linemods = tmp;
268        }
269    }
270
271    public void add(XmlCondition c, Collection<XmlCondition> conditions, Prototype prot) {
272         if(conditions != null)
273         {
274            prot.conditions = conditions;
275            if (prot instanceof IconPrototype) {
276                iconsList.add((IconPrototype) prot);
277            } else if (prot instanceof LinemodPrototype) {
278                modifiersList.add((LinemodPrototype) prot);
279            } else if (prot instanceof LinePrototype) {
280                linesList.add((LinePrototype) prot);
281            } else if (prot instanceof AreaPrototype) {
282                areasList.add((AreaPrototype) prot);
283            } else
284                throw new RuntimeException();
285         }
286         else {
287             String key = c.getKey();
288            prot.code = key;
289            if (prot instanceof IconPrototype) {
290                icons.put(key, (IconPrototype) prot);
291            } else if (prot instanceof LinemodPrototype) {
292               modifiers.put(key, (LinemodPrototype) prot);
293            } else if (prot instanceof LinePrototype) {
294                lines.put(key, (LinePrototype) prot);
295            } else if (prot instanceof AreaPrototype) {
296                areas.put(key, (AreaPrototype) prot);
297            } else
298                throw new RuntimeException();
299         }
300     }
301
302    @Override
303    public void apply(MultiCascade mc, OsmPrimitive osm, double scale, OsmPrimitive multipolyOuterWay, boolean pretendWayIsClosed) {
304        Cascade def = mc.getOrCreateCascade("default");
305        boolean useMinMaxScale = Main.pref.getBoolean("mappaint.zoomLevelDisplay", false);
306
307        if (osm instanceof Node || (osm instanceof Relation && "restriction".equals(osm.get("type")))) {
308            IconPrototype icon = getNode(osm, (useMinMaxScale ? scale : null), mc);
309            if (icon != null) {
310                def.put(ICON_IMAGE, icon.icon);
311                if (osm instanceof Node) {
312                    if (icon.annotate != null) {
313                        if (icon.annotate) {
314                            def.put(TEXT, Keyword.AUTO);
315                        } else {
316                            def.remove(TEXT);
317                        }
318                    }
319                }
320            }
321        } else if (osm instanceof Way || (osm instanceof Relation && ((Relation)osm).isMultipolygon())) {
322            WayPrototypesRecord p = new WayPrototypesRecord();
323            get(osm, pretendWayIsClosed || !(osm instanceof Way) || ((Way) osm).isClosed(), p, (useMinMaxScale ? scale : null), mc);
324            if (p.line != null) {
325                def.put(WIDTH, new Float(p.line.getWidth()));
326                def.putOrClear(REAL_WIDTH, p.line.realWidth != null ? new Float(p.line.realWidth) : null);
327                def.putOrClear(COLOR, p.line.color);
328                if (p.line.color != null) {
329                    int alpha = p.line.color.getAlpha();
330                    if (alpha != 255) {
331                        def.put(OPACITY, Utils.color_int2float(alpha));
332                    }
333                }
334                def.putOrClear(DASHES, p.line.getDashed());
335                def.putOrClear(DASHES_BACKGROUND_COLOR, p.line.dashedColor);
336            }
337            Float refWidth = def.get(WIDTH, null, Float.class);
338            if (refWidth != null && p.linemods != null) {
339                int numOver = 0, numUnder = 0;
340
341                while (mc.hasLayer(String.format("over_%d", ++numOver)));
342                while (mc.hasLayer(String.format("under_%d", ++numUnder)));
343
344                for (LinemodPrototype mod : p.linemods) {
345                    Cascade c;
346                    if (mod.over) {
347                        String layer = String.format("over_%d", numOver);
348                        c = mc.getOrCreateCascade(layer);
349                        c.put(OBJECT_Z_INDEX, new Float(numOver));
350                        ++numOver;
351                    } else {
352                        String layer = String.format("under_%d", numUnder);
353                        c = mc.getOrCreateCascade(layer);
354                        c.put(OBJECT_Z_INDEX, new Float(-numUnder));
355                        ++numUnder;
356                    }
357                    c.put(WIDTH, new Float(mod.getWidth(refWidth)));
358                    c.putOrClear(COLOR, mod.color);
359                    if (mod.color != null) {
360                        int alpha = mod.color.getAlpha();
361                        if (alpha != 255) {
362                            c.put(OPACITY, Utils.color_int2float(alpha));
363                        }
364                    }
365                    c.putOrClear(DASHES, mod.getDashed());
366                    c.putOrClear(DASHES_BACKGROUND_COLOR, mod.dashedColor);
367                }
368            }
369            if (multipolyOuterWay != null) {
370                WayPrototypesRecord p2 = new WayPrototypesRecord();
371                get(multipolyOuterWay, true, p2, (useMinMaxScale ? scale : null), mc);
372                if (Objects.equals(p.area, p2.area)) {
373                    p.area = null;
374                }
375            }
376            if (p.area != null) {
377                def.putOrClear(FILL_COLOR, p.area.color);
378                def.putOrClear(TEXT_POSITION, Keyword.CENTER);
379                def.putOrClear(TEXT, Keyword.AUTO);
380                def.remove(FILL_IMAGE);
381            }
382        }
383    }
384}