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