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