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     */
143    private static boolean requiresUpdate(Prototype current, Prototype candidate, Double scale, MultiCascade mc) {
144        if (current == null || candidate.priority >= current.priority) {
145            if (scale == null)
146                return true;
147
148            if (candidate.range.contains(scale)) {
149                mc.range = Range.cut(mc.range, candidate.range);
150                return true;
151            } else {
152                mc.range = mc.range.reduceAround(scale, candidate.range);
153                return false;
154            }
155        }
156        return false;
157    }
158
159    private IconPrototype getNode(OsmPrimitive primitive, Double scale, MultiCascade mc) {
160        IconPrototype icon = null;
161        for (String key : primitive.keySet()) {
162            String val = primitive.get(key);
163            IconPrototype p;
164            if ((p = icons.get('n' + key + '=' + val)) != null) {
165                icon = update(icon, p, scale, mc);
166            }
167            if ((p = icons.get('b' + key + '=' + OsmUtils.getNamedOsmBoolean(val))) != null) {
168                icon = update(icon, p, scale, mc);
169            }
170            if ((p = icons.get('x' + key)) != null) {
171                icon = update(icon, p, scale, mc);
172            }
173        }
174        for (IconPrototype s : iconsList) {
175            if (s.check(primitive)) {
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        Map<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            prot.conditions = conditions;
274            if (prot instanceof IconPrototype) {
275                iconsList.add((IconPrototype) prot);
276            } else if (prot instanceof LinemodPrototype) {
277                modifiersList.add((LinemodPrototype) prot);
278            } else if (prot instanceof LinePrototype) {
279                linesList.add((LinePrototype) prot);
280            } else if (prot instanceof AreaPrototype) {
281                areasList.add((AreaPrototype) prot);
282            } else
283                throw new RuntimeException();
284         } else {
285             String key = c.getKey();
286            prot.code = key;
287            if (prot instanceof IconPrototype) {
288                icons.put(key, (IconPrototype) prot);
289            } else if (prot instanceof LinemodPrototype) {
290               modifiers.put(key, (LinemodPrototype) prot);
291            } else if (prot instanceof LinePrototype) {
292                lines.put(key, (LinePrototype) prot);
293            } else if (prot instanceof AreaPrototype) {
294                areas.put(key, (AreaPrototype) prot);
295            } else
296                throw new RuntimeException();
297         }
298     }
299
300    @Override
301    public void apply(MultiCascade mc, OsmPrimitive osm, double scale, boolean pretendWayIsClosed) {
302        Cascade def = mc.getOrCreateCascade("default");
303        boolean useMinMaxScale = Main.pref.getBoolean("mappaint.zoomLevelDisplay", false);
304
305        if (osm instanceof Node || (osm instanceof Relation && "restriction".equals(osm.get("type")))) {
306            IconPrototype icon = getNode(osm, useMinMaxScale ? scale : null, mc);
307            if (icon != null) {
308                def.put(ICON_IMAGE, icon.icon);
309                if (osm instanceof Node) {
310                    if (icon.annotate != null) {
311                        if (icon.annotate) {
312                            def.put(TEXT, Keyword.AUTO);
313                        } else {
314                            def.remove(TEXT);
315                        }
316                    }
317                }
318            }
319        } else if (osm instanceof Way || (osm instanceof Relation && ((Relation) osm).isMultipolygon())) {
320            WayPrototypesRecord p = new WayPrototypesRecord();
321            get(osm, pretendWayIsClosed || !(osm instanceof Way) || ((Way) osm).isClosed(), p, useMinMaxScale ? scale : null, mc);
322            if (p.line != null) {
323                def.put(WIDTH, new Float(p.line.getWidth()));
324                def.putOrClear(REAL_WIDTH, p.line.realWidth != null ? new Float(p.line.realWidth) : null);
325                def.putOrClear(COLOR, p.line.color);
326                if (p.line.color != null) {
327                    int alpha = p.line.color.getAlpha();
328                    if (alpha != 255) {
329                        def.put(OPACITY, Utils.color_int2float(alpha));
330                    }
331                }
332                def.putOrClear(DASHES, p.line.getDashed());
333                def.putOrClear(DASHES_BACKGROUND_COLOR, p.line.dashedColor);
334            }
335            Float refWidth = def.get(WIDTH, null, Float.class);
336            if (refWidth != null && p.linemods != null) {
337                int numOver = 0, numUnder = 0;
338
339                while (mc.hasLayer(String.format("over_%d", ++numOver)));
340                while (mc.hasLayer(String.format("under_%d", ++numUnder)));
341
342                for (LinemodPrototype mod : p.linemods) {
343                    Cascade c;
344                    if (mod.over) {
345                        String layer = String.format("over_%d", numOver);
346                        c = mc.getOrCreateCascade(layer);
347                        c.put(OBJECT_Z_INDEX, new Float(numOver));
348                        ++numOver;
349                    } else {
350                        String layer = String.format("under_%d", numUnder);
351                        c = mc.getOrCreateCascade(layer);
352                        c.put(OBJECT_Z_INDEX, new Float(-numUnder));
353                        ++numUnder;
354                    }
355                    c.put(WIDTH, new Float(mod.getWidth(refWidth)));
356                    c.putOrClear(COLOR, mod.color);
357                    if (mod.color != null) {
358                        int alpha = mod.color.getAlpha();
359                        if (alpha != 255) {
360                            c.put(OPACITY, Utils.color_int2float(alpha));
361                        }
362                    }
363                    c.putOrClear(DASHES, mod.getDashed());
364                    c.putOrClear(DASHES_BACKGROUND_COLOR, mod.dashedColor);
365                }
366            }
367            if (p.area != null) {
368                def.putOrClear(FILL_COLOR, p.area.color);
369                def.putOrClear(TEXT_POSITION, Keyword.CENTER);
370                def.putOrClear(TEXT, Keyword.AUTO);
371                def.remove(FILL_IMAGE);
372            }
373        }
374    }
375}