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