1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io.session;
|
---|
3 |
|
---|
4 | import java.io.BufferedOutputStream;
|
---|
5 | import java.io.File;
|
---|
6 | import java.io.IOException;
|
---|
7 | import java.io.OutputStream;
|
---|
8 | import java.io.OutputStreamWriter;
|
---|
9 | import java.nio.charset.StandardCharsets;
|
---|
10 | import java.nio.file.Files;
|
---|
11 | import java.util.Collection;
|
---|
12 | import java.util.HashMap;
|
---|
13 | import java.util.List;
|
---|
14 | import java.util.Locale;
|
---|
15 | import java.util.Map;
|
---|
16 | import java.util.Objects;
|
---|
17 | import java.util.Set;
|
---|
18 | import java.util.stream.Collectors;
|
---|
19 | import java.util.zip.ZipEntry;
|
---|
20 | import java.util.zip.ZipOutputStream;
|
---|
21 |
|
---|
22 | import javax.xml.parsers.DocumentBuilder;
|
---|
23 | import javax.xml.parsers.ParserConfigurationException;
|
---|
24 | import javax.xml.transform.OutputKeys;
|
---|
25 | import javax.xml.transform.Transformer;
|
---|
26 | import javax.xml.transform.TransformerException;
|
---|
27 | import javax.xml.transform.dom.DOMSource;
|
---|
28 | import javax.xml.transform.stream.StreamResult;
|
---|
29 |
|
---|
30 | import org.openstreetmap.josm.data.coor.EastNorth;
|
---|
31 | import org.openstreetmap.josm.data.coor.LatLon;
|
---|
32 | import org.openstreetmap.josm.data.projection.ProjectionRegistry;
|
---|
33 | import org.openstreetmap.josm.gui.MainApplication;
|
---|
34 | import org.openstreetmap.josm.gui.MapView;
|
---|
35 | import org.openstreetmap.josm.gui.layer.GpxLayer;
|
---|
36 | import org.openstreetmap.josm.gui.layer.GpxRouteLayer;
|
---|
37 | import org.openstreetmap.josm.gui.layer.Layer;
|
---|
38 | import org.openstreetmap.josm.gui.layer.NoteLayer;
|
---|
39 | import org.openstreetmap.josm.gui.layer.OsmDataLayer;
|
---|
40 | import org.openstreetmap.josm.gui.layer.TMSLayer;
|
---|
41 | import org.openstreetmap.josm.gui.layer.WMSLayer;
|
---|
42 | import org.openstreetmap.josm.gui.layer.WMTSLayer;
|
---|
43 | import org.openstreetmap.josm.gui.layer.geoimage.GeoImageLayer;
|
---|
44 | import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
|
---|
45 | import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
|
---|
46 | import org.openstreetmap.josm.tools.JosmRuntimeException;
|
---|
47 | import org.openstreetmap.josm.tools.Logging;
|
---|
48 | import org.openstreetmap.josm.tools.MultiMap;
|
---|
49 | import org.openstreetmap.josm.tools.Utils;
|
---|
50 | import org.openstreetmap.josm.tools.XmlUtils;
|
---|
51 | import org.w3c.dom.Document;
|
---|
52 | import org.w3c.dom.Element;
|
---|
53 | import org.w3c.dom.Text;
|
---|
54 |
|
---|
55 | /**
|
---|
56 | * Writes a .jos session file from current supported layers.
|
---|
57 | * @since 4685
|
---|
58 | */
|
---|
59 | public class SessionWriter {
|
---|
60 |
|
---|
61 | private static final Map<Class<? extends Layer>, Class<? extends SessionLayerExporter>> sessionLayerExporters = new HashMap<>();
|
---|
62 |
|
---|
63 | private final List<Layer> layers;
|
---|
64 | private final int active;
|
---|
65 | private final Map<Layer, SessionLayerExporter> exporters;
|
---|
66 | private final MultiMap<Layer, Layer> dependencies;
|
---|
67 | private final boolean zip;
|
---|
68 |
|
---|
69 | private ZipOutputStream zipOut;
|
---|
70 |
|
---|
71 | static {
|
---|
72 | registerSessionLayerExporter(OsmDataLayer.class, OsmDataSessionExporter.class);
|
---|
73 | registerSessionLayerExporter(TMSLayer.class, ImagerySessionExporter.class);
|
---|
74 | registerSessionLayerExporter(WMSLayer.class, ImagerySessionExporter.class);
|
---|
75 | registerSessionLayerExporter(WMTSLayer.class, ImagerySessionExporter.class);
|
---|
76 | registerSessionLayerExporter(GpxLayer.class, GpxTracksSessionExporter.class);
|
---|
77 | registerSessionLayerExporter(GpxRouteLayer.class, GpxRoutesSessionExporter.class);
|
---|
78 | registerSessionLayerExporter(GeoImageLayer.class, GeoImageSessionExporter.class);
|
---|
79 | registerSessionLayerExporter(MarkerLayer.class, MarkerSessionExporter.class);
|
---|
80 | registerSessionLayerExporter(NoteLayer.class, NoteSessionExporter.class);
|
---|
81 | }
|
---|
82 |
|
---|
83 | /**
|
---|
84 | * Register a session layer exporter.
|
---|
85 | *
|
---|
86 | * The exporter class must have a one-argument constructor with layerClass as formal parameter type.
|
---|
87 | * @param layerClass layer class
|
---|
88 | * @param exporter exporter for this layer class
|
---|
89 | */
|
---|
90 | public static void registerSessionLayerExporter(Class<? extends Layer> layerClass, Class<? extends SessionLayerExporter> exporter) {
|
---|
91 | sessionLayerExporters.put(layerClass, exporter);
|
---|
92 | }
|
---|
93 |
|
---|
94 | /**
|
---|
95 | * Returns the session layer exporter for the given layer.
|
---|
96 | * @param layer layer to export
|
---|
97 | * @return session layer exporter for the given layer
|
---|
98 | * @throws IllegalArgumentException if layer cannot be exported
|
---|
99 | */
|
---|
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 | * Get the index of the specified layer
|
---|
178 | * @param layer the layer
|
---|
179 | * @return the index of the specified layer
|
---|
180 | * @since 18466
|
---|
181 | */
|
---|
182 | public int getLayerIndexOf(Layer layer) {
|
---|
183 | return layers.indexOf(layer) + 1;
|
---|
184 | }
|
---|
185 |
|
---|
186 | /**
|
---|
187 | * Create a file inside the zip archive.
|
---|
188 | *
|
---|
189 | * @param zipPath the path inside the zip archive, e.g. "layers/03/data.xml"
|
---|
190 | * @return the OutputStream you can write to. Never close the returned
|
---|
191 | * output stream, but make sure to flush buffers.
|
---|
192 | * @throws IOException if any I/O error occurs
|
---|
193 | */
|
---|
194 | public OutputStream getOutputStreamZip(String zipPath) throws IOException {
|
---|
195 | if (!isZip()) throw new JosmRuntimeException("not zip");
|
---|
196 | ZipEntry entry = new ZipEntry(zipPath);
|
---|
197 | zipOut.putNextEntry(entry);
|
---|
198 | return zipOut;
|
---|
199 | }
|
---|
200 |
|
---|
201 | /**
|
---|
202 | * Check, if the session is exported as a zip archive.
|
---|
203 | *
|
---|
204 | * @return true, if the session is exported as a zip archive (.joz file
|
---|
205 | * extension). It will always return true, if one of the
|
---|
206 | * {@link SessionLayerExporter} returns true for the
|
---|
207 | * {@link SessionLayerExporter#requiresZip()} method. Otherwise, the
|
---|
208 | * user can decide in the file chooser dialog.
|
---|
209 | */
|
---|
210 | public boolean isZip() {
|
---|
211 | return zip;
|
---|
212 | }
|
---|
213 | }
|
---|
214 |
|
---|
215 | /**
|
---|
216 | * Creates XML (.jos) session document.
|
---|
217 | * @return new document
|
---|
218 | * @throws IOException if any I/O error occurs
|
---|
219 | */
|
---|
220 | public Document createJosDocument() throws IOException {
|
---|
221 | DocumentBuilder builder = null;
|
---|
222 | try {
|
---|
223 | builder = XmlUtils.newSafeDOMBuilder();
|
---|
224 | } catch (ParserConfigurationException e) {
|
---|
225 | throw new IOException(e);
|
---|
226 | }
|
---|
227 | Document doc = builder.newDocument();
|
---|
228 |
|
---|
229 | Element root = doc.createElement("josm-session");
|
---|
230 | root.setAttribute("version", "0.1");
|
---|
231 | doc.appendChild(root);
|
---|
232 |
|
---|
233 | writeViewPort(root);
|
---|
234 | writeProjection(root);
|
---|
235 |
|
---|
236 | Element layersEl = doc.createElement("layers");
|
---|
237 | if (active >= 0) {
|
---|
238 | layersEl.setAttribute("active", Integer.toString(active+1));
|
---|
239 | }
|
---|
240 | root.appendChild(layersEl);
|
---|
241 |
|
---|
242 | for (int index = 0; index < layers.size(); ++index) {
|
---|
243 | Layer layer = layers.get(index);
|
---|
244 | SessionLayerExporter exporter = exporters.get(layer);
|
---|
245 | ExportSupport support = new ExportSupport(doc, index+1);
|
---|
246 | Element el = exporter.export(support);
|
---|
247 | if (el == null) continue;
|
---|
248 | el.setAttribute("index", Integer.toString(index+1));
|
---|
249 | el.setAttribute("name", layer.getName());
|
---|
250 | el.setAttribute("visible", Boolean.toString(layer.isVisible()));
|
---|
251 | if (!Utils.equalsEpsilon(layer.getOpacity(), 1.0)) {
|
---|
252 | el.setAttribute("opacity", Double.toString(layer.getOpacity()));
|
---|
253 | }
|
---|
254 | Set<Layer> deps = dependencies.get(layer);
|
---|
255 | final String depends = deps == null ? "" : deps.stream().map(depLayer -> {
|
---|
256 | int depIndex = layers.indexOf(depLayer);
|
---|
257 | if (depIndex == -1) {
|
---|
258 | Logging.warn("Unable to find " + depLayer);
|
---|
259 | return null;
|
---|
260 | } else {
|
---|
261 | return Integer.toString(depIndex+1);
|
---|
262 | }
|
---|
263 | }).filter(Objects::nonNull).collect(Collectors.joining(","));
|
---|
264 | if (!depends.isEmpty()) {
|
---|
265 | el.setAttribute("depends", depends);
|
---|
266 | }
|
---|
267 | layersEl.appendChild(el);
|
---|
268 | }
|
---|
269 | return doc;
|
---|
270 | }
|
---|
271 |
|
---|
272 | private static void writeViewPort(Element root) {
|
---|
273 | Document doc = root.getOwnerDocument();
|
---|
274 | Element viewportEl = doc.createElement("viewport");
|
---|
275 | root.appendChild(viewportEl);
|
---|
276 | Element centerEl = doc.createElement("center");
|
---|
277 | viewportEl.appendChild(centerEl);
|
---|
278 | MapView mapView = MainApplication.getMap().mapView;
|
---|
279 | EastNorth center = mapView.getCenter();
|
---|
280 | LatLon centerLL = ProjectionRegistry.getProjection().eastNorth2latlon(center);
|
---|
281 | centerEl.setAttribute("lat", Double.toString(centerLL.lat()));
|
---|
282 | centerEl.setAttribute("lon", Double.toString(centerLL.lon()));
|
---|
283 | Element scale = doc.createElement("scale");
|
---|
284 | viewportEl.appendChild(scale);
|
---|
285 | double dist100px = mapView.getDist100Pixel();
|
---|
286 | scale.setAttribute("meter-per-pixel", String.format(Locale.ROOT, "%6f", dist100px / 100));
|
---|
287 | }
|
---|
288 |
|
---|
289 | private static void writeProjection(Element root) {
|
---|
290 | Document doc = root.getOwnerDocument();
|
---|
291 | Element projectionEl = doc.createElement("projection");
|
---|
292 | root.appendChild(projectionEl);
|
---|
293 | String pcId = ProjectionPreference.getCurrentProjectionChoiceId();
|
---|
294 | Element projectionChoiceEl = doc.createElement("projection-choice");
|
---|
295 | projectionEl.appendChild(projectionChoiceEl);
|
---|
296 | Element idEl = doc.createElement("id");
|
---|
297 | projectionChoiceEl.appendChild(idEl);
|
---|
298 | idEl.setTextContent(pcId);
|
---|
299 | Collection<String> parameters = ProjectionPreference.getSubprojectionPreference(pcId);
|
---|
300 | Element parametersEl = doc.createElement("parameters");
|
---|
301 | projectionChoiceEl.appendChild(parametersEl);
|
---|
302 | if (parameters != null) {
|
---|
303 | for (String param : parameters) {
|
---|
304 | Element paramEl = doc.createElement("param");
|
---|
305 | parametersEl.appendChild(paramEl);
|
---|
306 | paramEl.setTextContent(param);
|
---|
307 | }
|
---|
308 | }
|
---|
309 | String code = ProjectionRegistry.getProjection().toCode();
|
---|
310 | if (code != null) {
|
---|
311 | Element codeEl = doc.createElement("code");
|
---|
312 | projectionEl.appendChild(codeEl);
|
---|
313 | codeEl.setTextContent(code);
|
---|
314 | }
|
---|
315 | }
|
---|
316 |
|
---|
317 | /**
|
---|
318 | * Writes given .jos document to an output stream.
|
---|
319 | * @param doc session document
|
---|
320 | * @param out output stream
|
---|
321 | * @throws IOException if any I/O error occurs
|
---|
322 | */
|
---|
323 | public void writeJos(Document doc, OutputStream out) throws IOException {
|
---|
324 | try {
|
---|
325 | OutputStreamWriter writer = new OutputStreamWriter(out, StandardCharsets.UTF_8);
|
---|
326 | writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
|
---|
327 | Transformer trans = XmlUtils.newSafeTransformerFactory().newTransformer();
|
---|
328 | trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
|
---|
329 | trans.setOutputProperty(OutputKeys.INDENT, "yes");
|
---|
330 | trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
|
---|
331 | StreamResult result = new StreamResult(writer);
|
---|
332 | DOMSource source = new DOMSource(doc);
|
---|
333 | trans.transform(source, result);
|
---|
334 | } catch (TransformerException e) {
|
---|
335 | throw new JosmRuntimeException(e);
|
---|
336 | }
|
---|
337 | }
|
---|
338 |
|
---|
339 | /**
|
---|
340 | * Writes session to given file.
|
---|
341 | * @param f output file
|
---|
342 | * @throws IOException if any I/O error occurs
|
---|
343 | */
|
---|
344 | public void write(File f) throws IOException {
|
---|
345 | try (OutputStream out = Files.newOutputStream(f.toPath())) {
|
---|
346 | write(out);
|
---|
347 | }
|
---|
348 | }
|
---|
349 |
|
---|
350 | /**
|
---|
351 | * Writes session to given output stream.
|
---|
352 | * @param out output stream
|
---|
353 | * @throws IOException if any I/O error occurs
|
---|
354 | */
|
---|
355 | public void write(OutputStream out) throws IOException {
|
---|
356 | if (zip) {
|
---|
357 | zipOut = new ZipOutputStream(new BufferedOutputStream(out), StandardCharsets.UTF_8);
|
---|
358 | }
|
---|
359 | Document doc = createJosDocument(); // as side effect, files may be added to zipOut
|
---|
360 | if (zip) {
|
---|
361 | ZipEntry entry = new ZipEntry("session.jos");
|
---|
362 | zipOut.putNextEntry(entry);
|
---|
363 | writeJos(doc, zipOut);
|
---|
364 | Utils.close(zipOut);
|
---|
365 | } else {
|
---|
366 | writeJos(doc, new BufferedOutputStream(out));
|
---|
367 | }
|
---|
368 | }
|
---|
369 | }
|
---|