001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.io.session; 003 004import java.io.BufferedOutputStream; 005import java.io.File; 006import java.io.IOException; 007import java.io.OutputStream; 008import java.io.OutputStreamWriter; 009import java.nio.charset.StandardCharsets; 010import java.nio.file.Files; 011import java.util.Collection; 012import java.util.HashMap; 013import java.util.List; 014import java.util.Locale; 015import java.util.Map; 016import java.util.Objects; 017import java.util.Set; 018import java.util.stream.Collectors; 019import java.util.zip.ZipEntry; 020import java.util.zip.ZipOutputStream; 021 022import javax.xml.parsers.DocumentBuilder; 023import javax.xml.parsers.ParserConfigurationException; 024import javax.xml.transform.OutputKeys; 025import javax.xml.transform.Transformer; 026import javax.xml.transform.TransformerException; 027import javax.xml.transform.dom.DOMSource; 028import javax.xml.transform.stream.StreamResult; 029 030import org.openstreetmap.josm.data.coor.EastNorth; 031import org.openstreetmap.josm.data.coor.LatLon; 032import org.openstreetmap.josm.data.projection.ProjectionRegistry; 033import org.openstreetmap.josm.gui.MainApplication; 034import org.openstreetmap.josm.gui.MapView; 035import org.openstreetmap.josm.gui.layer.GpxLayer; 036import org.openstreetmap.josm.gui.layer.GpxRouteLayer; 037import org.openstreetmap.josm.gui.layer.Layer; 038import org.openstreetmap.josm.gui.layer.NoteLayer; 039import org.openstreetmap.josm.gui.layer.OsmDataLayer; 040import org.openstreetmap.josm.gui.layer.TMSLayer; 041import org.openstreetmap.josm.gui.layer.WMSLayer; 042import org.openstreetmap.josm.gui.layer.WMTSLayer; 043import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer; 044import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer; 045import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference; 046import org.openstreetmap.josm.tools.JosmRuntimeException; 047import org.openstreetmap.josm.tools.Logging; 048import org.openstreetmap.josm.tools.MultiMap; 049import org.openstreetmap.josm.tools.Utils; 050import org.openstreetmap.josm.tools.XmlUtils; 051import org.w3c.dom.Document; 052import org.w3c.dom.Element; 053import org.w3c.dom.Text; 054 055/** 056 * Writes a .jos session file from current supported layers. 057 * @since 4685 058 */ 059public class SessionWriter { 060 061 private static final Map<Class<? extends Layer>, Class<? extends SessionLayerExporter>> sessionLayerExporters = new HashMap<>(); 062 063 private final List<Layer> layers; 064 private final int active; 065 private final Map<Layer, SessionLayerExporter> exporters; 066 private final MultiMap<Layer, Layer> dependencies; 067 private final boolean zip; 068 069 private ZipOutputStream zipOut; 070 071 static { 072 registerSessionLayerExporter(OsmDataLayer.class, OsmDataSessionExporter.class); 073 registerSessionLayerExporter(TMSLayer.class, ImagerySessionExporter.class); 074 registerSessionLayerExporter(WMSLayer.class, ImagerySessionExporter.class); 075 registerSessionLayerExporter(WMTSLayer.class, ImagerySessionExporter.class); 076 registerSessionLayerExporter(GpxLayer.class, GpxTracksSessionExporter.class); 077 registerSessionLayerExporter(GpxRouteLayer.class, GpxRoutesSessionExporter.class); 078 registerSessionLayerExporter(GeoImageLayer.class, GeoImageSessionExporter.class); 079 registerSessionLayerExporter(MarkerLayer.class, MarkerSessionExporter.class); 080 registerSessionLayerExporter(NoteLayer.class, NoteSessionExporter.class); 081 } 082 083 /** 084 * Register a session layer exporter. 085 * 086 * The exporter class must have a one-argument constructor with layerClass as formal parameter type. 087 * @param layerClass layer class 088 * @param exporter exporter for this layer class 089 */ 090 public static void registerSessionLayerExporter(Class<? extends Layer> layerClass, Class<? extends SessionLayerExporter> exporter) { 091 sessionLayerExporters.put(layerClass, exporter); 092 } 093 094 /** 095 * Returns the session layer exporter for the given layer. 096 * @param layer layer to export 097 * @return session layer exporter for the given layer 098 * @throws IllegalArgumentException if layer cannot be exported 099 */ 100 public static SessionLayerExporter getSessionLayerExporter(Layer layer) { 101 Class<? extends Layer> layerClass = layer.getClass(); 102 Class<? extends SessionLayerExporter> exporterClass = sessionLayerExporters.get(layerClass); 103 if (exporterClass == null) 104 return null; 105 try { 106 return exporterClass.getConstructor(layerClass).newInstance(layer); 107 } catch (ReflectiveOperationException e) { 108 throw new JosmRuntimeException(e); 109 } 110 } 111 112 /** 113 * Constructs a new {@code SessionWriter}. 114 * @param layers The ordered list of layers to save 115 * @param active The index of active layer in {@code layers} (starts at 0). Ignored if set to -1 116 * @param exporters The exporters to use to save layers 117 * @param dependencies layer dependencies 118 * @param zip {@code true} if a joz archive has to be created, {@code false otherwise} 119 * @since 6271 120 */ 121 public SessionWriter(List<Layer> layers, int active, Map<Layer, SessionLayerExporter> exporters, 122 MultiMap<Layer, Layer> dependencies, boolean zip) { 123 this.layers = layers; 124 this.active = active; 125 this.exporters = exporters; 126 this.dependencies = dependencies; 127 this.zip = zip; 128 } 129 130 /** 131 * A class that provides some context for the individual {@link SessionLayerExporter} 132 * when doing the export. 133 */ 134 public class ExportSupport { 135 private final Document doc; 136 private final int layerIndex; 137 138 /** 139 * Constructs a new {@code ExportSupport}. 140 * @param doc XML document 141 * @param layerIndex layer index 142 */ 143 public ExportSupport(Document doc, int layerIndex) { 144 this.doc = doc; 145 this.layerIndex = layerIndex; 146 } 147 148 /** 149 * Creates an element of the type specified. 150 * @param name The name of the element type to instantiate 151 * @return A new {@code Element} object 152 * @see Document#createElement 153 */ 154 public Element createElement(String name) { 155 return doc.createElement(name); 156 } 157 158 /** 159 * Creates a text node given the specified string. 160 * @param text The data for the node. 161 * @return The new {@code Text} object. 162 * @see Document#createTextNode 163 */ 164 public Text createTextNode(String text) { 165 return doc.createTextNode(text); 166 } 167 168 /** 169 * Get the index of the layer that is currently exported. 170 * @return the index of the layer that is currently exported 171 */ 172 public int getLayerIndex() { 173 return layerIndex; 174 } 175 176 /** 177 * Create a file inside the zip archive. 178 * 179 * @param zipPath the path inside the zip archive, e.g. "layers/03/data.xml" 180 * @return the OutputStream you can write to. Never close the returned 181 * output stream, but make sure to flush buffers. 182 * @throws IOException if any I/O error occurs 183 */ 184 public OutputStream getOutputStreamZip(String zipPath) throws IOException { 185 if (!isZip()) throw new JosmRuntimeException("not zip"); 186 ZipEntry entry = new ZipEntry(zipPath); 187 zipOut.putNextEntry(entry); 188 return zipOut; 189 } 190 191 /** 192 * Check, if the session is exported as a zip archive. 193 * 194 * @return true, if the session is exported as a zip archive (.joz file 195 * extension). It will always return true, if one of the 196 * {@link SessionLayerExporter} returns true for the 197 * {@link SessionLayerExporter#requiresZip()} method. Otherwise, the 198 * user can decide in the file chooser dialog. 199 */ 200 public boolean isZip() { 201 return zip; 202 } 203 } 204 205 /** 206 * Creates XML (.jos) session document. 207 * @return new document 208 * @throws IOException if any I/O error occurs 209 */ 210 public Document createJosDocument() throws IOException { 211 DocumentBuilder builder = null; 212 try { 213 builder = XmlUtils.newSafeDOMBuilder(); 214 } catch (ParserConfigurationException e) { 215 throw new IOException(e); 216 } 217 Document doc = builder.newDocument(); 218 219 Element root = doc.createElement("josm-session"); 220 root.setAttribute("version", "0.1"); 221 doc.appendChild(root); 222 223 writeViewPort(root); 224 writeProjection(root); 225 226 Element layersEl = doc.createElement("layers"); 227 if (active >= 0) { 228 layersEl.setAttribute("active", Integer.toString(active+1)); 229 } 230 root.appendChild(layersEl); 231 232 for (int index = 0; index < layers.size(); ++index) { 233 Layer layer = layers.get(index); 234 SessionLayerExporter exporter = exporters.get(layer); 235 ExportSupport support = new ExportSupport(doc, index+1); 236 Element el = exporter.export(support); 237 el.setAttribute("index", Integer.toString(index+1)); 238 el.setAttribute("name", layer.getName()); 239 el.setAttribute("visible", Boolean.toString(layer.isVisible())); 240 if (!Utils.equalsEpsilon(layer.getOpacity(), 1.0)) { 241 el.setAttribute("opacity", Double.toString(layer.getOpacity())); 242 } 243 Set<Layer> deps = dependencies.get(layer); 244 final String depends = deps == null ? "" : deps.stream().map(depLayer -> { 245 int depIndex = layers.indexOf(depLayer); 246 if (depIndex == -1) { 247 Logging.warn("Unable to find " + depLayer); 248 return null; 249 } else { 250 return Integer.toString(depIndex+1); 251 } 252 }).filter(Objects::nonNull).collect(Collectors.joining(",")); 253 if (!depends.isEmpty()) { 254 el.setAttribute("depends", depends); 255 } 256 layersEl.appendChild(el); 257 } 258 return doc; 259 } 260 261 private static void writeViewPort(Element root) { 262 Document doc = root.getOwnerDocument(); 263 Element viewportEl = doc.createElement("viewport"); 264 root.appendChild(viewportEl); 265 Element centerEl = doc.createElement("center"); 266 viewportEl.appendChild(centerEl); 267 MapView mapView = MainApplication.getMap().mapView; 268 EastNorth center = mapView.getCenter(); 269 LatLon centerLL = ProjectionRegistry.getProjection().eastNorth2latlon(center); 270 centerEl.setAttribute("lat", Double.toString(centerLL.lat())); 271 centerEl.setAttribute("lon", Double.toString(centerLL.lon())); 272 Element scale = doc.createElement("scale"); 273 viewportEl.appendChild(scale); 274 double dist100px = mapView.getDist100Pixel(); 275 scale.setAttribute("meter-per-pixel", String.format(Locale.ROOT, "%6f", dist100px / 100)); 276 } 277 278 private static void writeProjection(Element root) { 279 Document doc = root.getOwnerDocument(); 280 Element projectionEl = doc.createElement("projection"); 281 root.appendChild(projectionEl); 282 String pcId = ProjectionPreference.getCurrentProjectionChoiceId(); 283 Element projectionChoiceEl = doc.createElement("projection-choice"); 284 projectionEl.appendChild(projectionChoiceEl); 285 Element idEl = doc.createElement("id"); 286 projectionChoiceEl.appendChild(idEl); 287 idEl.setTextContent(pcId); 288 Collection<String> parameters = ProjectionPreference.getSubprojectionPreference(pcId); 289 Element parametersEl = doc.createElement("parameters"); 290 projectionChoiceEl.appendChild(parametersEl); 291 if (parameters != null) { 292 for (String param : parameters) { 293 Element paramEl = doc.createElement("param"); 294 parametersEl.appendChild(paramEl); 295 paramEl.setTextContent(param); 296 } 297 } 298 String code = ProjectionRegistry.getProjection().toCode(); 299 if (code != null) { 300 Element codeEl = doc.createElement("code"); 301 projectionEl.appendChild(codeEl); 302 codeEl.setTextContent(code); 303 } 304 } 305 306 /** 307 * Writes given .jos document to an output stream. 308 * @param doc session document 309 * @param out output stream 310 * @throws IOException if any I/O error occurs 311 */ 312 public void writeJos(Document doc, OutputStream out) throws IOException { 313 try { 314 OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); 315 writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); 316 Transformer trans = XmlUtils.newSafeTransformerFactory().newTransformer(); 317 trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 318 trans.setOutputProperty(OutputKeys.INDENT, "yes"); 319 trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 320 StreamResult result = new StreamResult(writer); 321 DOMSource source = new DOMSource(doc); 322 trans.transform(source, result); 323 } catch (TransformerException e) { 324 throw new JosmRuntimeException(e); 325 } 326 } 327 328 /** 329 * Writes session to given file. 330 * @param f output file 331 * @throws IOException if any I/O error occurs 332 */ 333 public void write(File f) throws IOException { 334 try (OutputStream out = Files.newOutputStream(f.toPath())) { 335 write(out); 336 } 337 } 338 339 /** 340 * Writes session to given output stream. 341 * @param out output stream 342 * @throws IOException if any I/O error occurs 343 */ 344 public void write(OutputStream out) throws IOException { 345 if (zip) { 346 zipOut = new ZipOutputStream(new BufferedOutputStream(out), StandardCharsets.UTF_8); 347 } 348 Document doc = createJosDocument(); // as side effect, files may be added to zipOut 349 if (zip) { 350 ZipEntry entry = new ZipEntry("session.jos"); 351 zipOut.putNextEntry(entry); 352 writeJos(doc, zipOut); 353 Utils.close(zipOut); 354 } else { 355 writeJos(doc, new BufferedOutputStream(out)); 356 } 357 } 358}