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