001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.imagery.vectortile.mapbox.style; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.Image; 007import java.awt.image.BufferedImage; 008import java.io.BufferedReader; 009import java.io.File; 010import java.io.IOException; 011import java.io.InputStream; 012import java.io.OutputStream; 013import java.nio.charset.StandardCharsets; 014import java.nio.file.Files; 015import java.util.Collections; 016import java.util.LinkedHashMap; 017import java.util.List; 018import java.util.Map; 019import java.util.Map.Entry; 020import java.util.Objects; 021import java.util.Optional; 022import java.util.concurrent.ConcurrentHashMap; 023import java.util.stream.Collectors; 024 025import javax.imageio.ImageIO; 026import jakarta.json.Json; 027import jakarta.json.JsonException; 028import jakarta.json.JsonObject; 029import jakarta.json.JsonReader; 030import jakarta.json.JsonValue; 031 032import org.openstreetmap.josm.data.imagery.vectortile.mapbox.InvalidMapboxVectorTileException; 033import org.openstreetmap.josm.data.preferences.JosmBaseDirectories; 034import org.openstreetmap.josm.gui.MainApplication; 035import org.openstreetmap.josm.gui.mappaint.ElemStyles; 036import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource; 037import org.openstreetmap.josm.io.CachedFile; 038import org.openstreetmap.josm.spi.preferences.Config; 039import org.openstreetmap.josm.tools.Logging; 040import org.openstreetmap.josm.tools.Utils; 041 042/** 043 * Create a mapping for a Mapbox Vector Style 044 * 045 * @author Taylor Smock 046 * @see <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/">https://docs.mapbox.com/mapbox-gl-js/style-spec/</a> 047 * @since 17862 048 */ 049public class MapboxVectorStyle { 050 051 private static final ConcurrentHashMap<String, MapboxVectorStyle> STYLE_MAPPING = new ConcurrentHashMap<>(); 052 053 /** 054 * Get a MapboxVector style for a URL 055 * @param url The url to get 056 * @return The Mapbox Vector Style. May be {@code null} if there was an error. 057 */ 058 public static MapboxVectorStyle getMapboxVectorStyle(String url) { 059 return STYLE_MAPPING.computeIfAbsent(url, key -> { 060 try (CachedFile style = new CachedFile(url); 061 BufferedReader reader = style.getContentReader(); 062 JsonReader jsonReader = Json.createReader(reader)) { 063 return new MapboxVectorStyle(jsonReader.read().asJsonObject()); 064 } catch (IOException e) { 065 Logging.error(e); 066 } 067 // Documentation indicates that this will <i>not</i> be entered into the map, which means that this will be 068 // retried if something goes wrong. 069 return null; 070 }); 071 } 072 073 /** The version for the style specification */ 074 private final int version; 075 /** The optional name for the vector style */ 076 private final String name; 077 /** The optional URL for sprites. This mush be absolute (so it must contain the scheme, authority, and path). */ 078 private final String spriteUrl; 079 /** The optional URL for glyphs. This may have replaceable values in it. */ 080 private final String glyphUrl; 081 /** The required collection of sources with a list of layers that are applicable for that source*/ 082 private final Map<Source, ElemStyles> sources; 083 084 /** 085 * Create a new MapboxVector style. You should prefer {@link #getMapboxVectorStyle(String)} 086 * for deduplication purposes. 087 * 088 * @param jsonObject The object to create the style from 089 * @see #getMapboxVectorStyle(String) 090 */ 091 public MapboxVectorStyle(JsonObject jsonObject) { 092 // There should be a version specifier. We currently only support version 8. 093 // This can throw an NPE when there is no version number. 094 this.version = jsonObject.getInt("version"); 095 if (this.version == 8) { 096 this.name = jsonObject.getString("name", null); 097 String id = jsonObject.getString("id", this.name); 098 this.spriteUrl = jsonObject.getString("sprite", null); 099 this.glyphUrl = jsonObject.getString("glyphs", null); 100 final List<Source> sourceList; 101 if (jsonObject.containsKey("sources") && jsonObject.get("sources").getValueType() == JsonValue.ValueType.OBJECT) { 102 sourceList = jsonObject.getJsonObject("sources").entrySet().stream() 103 .filter(entry -> entry.getValue().getValueType() == JsonValue.ValueType.OBJECT) 104 .map(entry -> { 105 try { 106 return new Source(entry.getKey(), entry.getValue().asJsonObject()); 107 } catch (InvalidMapboxVectorTileException e) { 108 Logging.error(e); 109 // Reraise if not a known exception 110 if (!"TileJson not yet supported".equals(e.getMessage())) { 111 throw e; 112 } 113 } 114 return null; 115 }).filter(Objects::nonNull).collect(Collectors.toList()); 116 } else { 117 sourceList = Collections.emptyList(); 118 } 119 final List<Layers> layers; 120 if (jsonObject.containsKey("layers") && jsonObject.get("layers").getValueType() == JsonValue.ValueType.ARRAY) { 121 layers = jsonObject.getJsonArray("layers").stream() 122 .filter(JsonObject.class::isInstance).map(JsonObject.class::cast).map(obj -> new Layers(id, obj)) 123 .collect(Collectors.toList()); 124 } else { 125 layers = Collections.emptyList(); 126 } 127 final Map<Optional<Source>, List<Layers>> sourceLayer = layers.stream().collect( 128 Collectors.groupingBy(layer -> sourceList.stream().filter(source -> source.getName().equals(layer.getSource())) 129 .findFirst(), LinkedHashMap::new, Collectors.toList())); 130 // Abuse HashMap null (null == default) 131 this.sources = new LinkedHashMap<>(); 132 for (Entry<Optional<Source>, List<Layers>> entry : sourceLayer.entrySet()) { 133 final Source source = entry.getKey().orElse(null); 134 final String data = entry.getValue().stream().map(Layers::toString).collect(Collectors.joining()); 135 final String metaData = "meta{title:" + (source == null ? "Generated Style" : 136 source.getName()) + ";version:\"autogenerated\";description:\"auto generated style\";}"; 137 138 // This is the default canvas 139 final String canvas = "canvas{default-points:false;default-lines:false;}"; 140 final MapCSSStyleSource style = new MapCSSStyleSource(metaData + canvas + data); 141 // Save to directory 142 MainApplication.worker.execute(() -> this.save((source == null ? data.hashCode() : source.getName()) + ".mapcss", style)); 143 this.sources.put(source, new ElemStyles(Collections.singleton(style))); 144 } 145 if (!Utils.isStripEmpty(this.spriteUrl)) { 146 MainApplication.worker.execute(this::fetchSprites); 147 } 148 } else { 149 throw new IllegalArgumentException(tr("Vector Tile Style Version not understood: version {0} (json: {1})", 150 this.version, jsonObject)); 151 } 152 } 153 154 /** 155 * Fetch sprites. Please note that this is (literally) only png. Unfortunately. 156 * @see <a href="https://docs.mapbox.com/mapbox-gl-js/style-spec/sprite/">https://docs.mapbox.com/mapbox-gl-js/style-spec/sprite/</a> 157 */ 158 private void fetchSprites() { 159 // HiDPI images first -- if this succeeds, don't bother with the lower resolution (JOSM has no method to switch) 160 try (CachedFile spriteJson = new CachedFile(this.spriteUrl + "@2x.json"); 161 CachedFile spritePng = new CachedFile(this.spriteUrl + "@2x.png")) { 162 if (parseSprites(spriteJson, spritePng)) { 163 return; 164 } 165 } 166 try (CachedFile spriteJson = new CachedFile(this.spriteUrl + ".json"); 167 CachedFile spritePng = new CachedFile(this.spriteUrl + ".png")) { 168 parseSprites(spriteJson, spritePng); 169 } 170 } 171 172 private boolean parseSprites(CachedFile spriteJson, CachedFile spritePng) { 173 /* JSON looks like this: 174 * { "image-name": {"width": width, "height": height, "x": x, "y": y, "pixelRatio": 1 }} 175 * width/height are the dimensions of the image 176 * x -- distance right from top left 177 * y -- distance down from top left 178 * pixelRatio -- this <i>appears</i> to be from the "@2x" (default 1) 179 * content -- [left, top corner, right, bottom corner] 180 * stretchX -- [[from, to], [from, to], ...] 181 * stretchY -- [[from, to], [from, to], ...] 182 */ 183 final JsonObject spriteObject; 184 final BufferedImage spritePngImage; 185 try (BufferedReader spriteJsonBufferedReader = spriteJson.getContentReader(); 186 JsonReader spriteJsonReader = Json.createReader(spriteJsonBufferedReader); 187 InputStream spritePngBufferedReader = spritePng.getInputStream() 188 ) { 189 spriteObject = spriteJsonReader.read().asJsonObject(); 190 spritePngImage = ImageIO.read(spritePngBufferedReader); 191 } catch (IOException | JsonException e) { 192 Logging.error(e); 193 return false; 194 } 195 for (Entry<String, JsonValue> entry : spriteObject.entrySet()) { 196 final JsonObject info = entry.getValue().asJsonObject(); 197 int width = info.getInt("width"); 198 int height = info.getInt("height"); 199 int x = info.getInt("x"); 200 int y = info.getInt("y"); 201 save(entry.getKey() + ".png", spritePngImage.getSubimage(x, y, width, height)); 202 } 203 return true; 204 } 205 206 private void save(String name, Object object) { 207 final File cache; 208 if (object instanceof Image) { 209 // Images have a specific location where they are looked for 210 cache = new File(Config.getDirs().getUserDataDirectory(true), "images"); 211 } else { 212 cache = JosmBaseDirectories.getInstance().getCacheDirectory(true); 213 } 214 final File location = new File(cache, this.name != null ? this.name : Integer.toString(this.hashCode())); 215 if ((!location.exists() && !location.mkdirs()) || (location.exists() && !location.isDirectory())) { 216 // Don't try to save if the file exists and is not a directory or we couldn't create it 217 return; 218 } 219 final File toSave = new File(location, name); 220 Logging.debug("Saving {0} to {1}...", object.getClass().getSimpleName(), toSave); 221 try { 222 if (object instanceof BufferedImage) { 223 // This directory is checked first when getting images 224 if (!ImageIO.write((BufferedImage) object, "png", toSave)) { 225 Logging.warn("No appropriate PNG writer could be found"); 226 } 227 } else { 228 try (OutputStream fileOutputStream = Files.newOutputStream(toSave.toPath())) { 229 if (object instanceof String) { 230 fileOutputStream.write(((String) object).getBytes(StandardCharsets.UTF_8)); 231 } else if (object instanceof MapCSSStyleSource) { 232 MapCSSStyleSource source = (MapCSSStyleSource) object; 233 try (InputStream inputStream = source.getSourceInputStream()) { 234 int byteVal = inputStream.read(); 235 do { 236 fileOutputStream.write(byteVal); 237 byteVal = inputStream.read(); 238 } while (byteVal > -1); 239 source.url = "file:/" + toSave.getAbsolutePath().replace('\\', '/'); 240 if (source.isLoaded()) { 241 source.loadStyleSource(); 242 } 243 } 244 } 245 } 246 } 247 } catch (IOException e) { 248 Logging.warn(e); 249 } 250 } 251 252 /** 253 * Get the generated layer → style mapping 254 * @return The mapping (use to enable/disable a paint style) 255 */ 256 public Map<Source, ElemStyles> getSources() { 257 return this.sources; 258 } 259 260 /** 261 * Get the sprite url for the style 262 * @return The base sprite url 263 */ 264 public String getSpriteUrl() { 265 return this.spriteUrl; 266 } 267 268 @Override 269 public boolean equals(Object other) { 270 if (other != null && other.getClass() == this.getClass()) { 271 MapboxVectorStyle o = (MapboxVectorStyle) other; 272 return this.version == o.version 273 && Objects.equals(this.name, o.name) 274 && Objects.equals(this.glyphUrl, o.glyphUrl) 275 && Objects.equals(this.spriteUrl, o.spriteUrl) 276 && Objects.equals(this.sources, o.sources); 277 } 278 return false; 279 } 280 281 @Override 282 public int hashCode() { 283 return Objects.hash(this.name, this.version, this.glyphUrl, this.spriteUrl, this.sources); 284 } 285 286 @Override 287 public String toString() { 288 return "MapboxVectorStyle [version=" + version + ", " + (name != null ? "name=" + name + ", " : "") 289 + (spriteUrl != null ? "spriteUrl=" + spriteUrl + ", " : "") 290 + (glyphUrl != null ? "glyphUrl=" + glyphUrl + ", " : "") 291 + (sources != null ? "sources=" + sources : "") + "]"; 292 } 293}