source: josm/trunk/scripts/TagInfoExtract.java@ 14651

Last change on this file since 14651 was 14651, checked in by simon04, 7 years ago

see #17170 - TagInfoExtract: create imageDir

File size: 23.8 KB
Line 
1// License: GPL. For details, see LICENSE file.
2
3import java.awt.Graphics2D;
4import java.awt.image.BufferedImage;
5import java.io.BufferedReader;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.io.StringWriter;
10import java.io.UncheckedIOException;
11import java.io.Writer;
12import java.nio.file.Files;
13import java.nio.file.Path;
14import java.nio.file.Paths;
15import java.time.Instant;
16import java.time.ZoneId;
17import java.time.format.DateTimeFormatter;
18import java.util.ArrayList;
19import java.util.Arrays;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.EnumSet;
23import java.util.List;
24import java.util.Locale;
25import java.util.Optional;
26import java.util.Set;
27import java.util.stream.Collectors;
28
29import javax.imageio.ImageIO;
30import javax.json.Json;
31import javax.json.JsonArrayBuilder;
32import javax.json.JsonObjectBuilder;
33import javax.json.JsonWriter;
34import javax.json.stream.JsonGenerator;
35
36import org.openstreetmap.josm.actions.DeleteAction;
37import org.openstreetmap.josm.command.DeleteCommand;
38import org.openstreetmap.josm.data.Preferences;
39import org.openstreetmap.josm.data.Version;
40import org.openstreetmap.josm.data.coor.LatLon;
41import org.openstreetmap.josm.data.osm.Node;
42import org.openstreetmap.josm.data.osm.OsmPrimitive;
43import org.openstreetmap.josm.data.osm.Tag;
44import org.openstreetmap.josm.data.osm.Way;
45import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings;
46import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
47import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
48import org.openstreetmap.josm.data.preferences.JosmUrls;
49import org.openstreetmap.josm.data.preferences.sources.ExtendedSourceEntry;
50import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
51import org.openstreetmap.josm.data.projection.ProjectionRegistry;
52import org.openstreetmap.josm.data.projection.Projections;
53import org.openstreetmap.josm.gui.NavigatableComponent;
54import org.openstreetmap.josm.gui.mappaint.Cascade;
55import org.openstreetmap.josm.gui.mappaint.Environment;
56import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
57import org.openstreetmap.josm.gui.mappaint.MultiCascade;
58import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory;
59import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
60import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
61import org.openstreetmap.josm.gui.mappaint.mapcss.Selector;
62import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
63import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
64import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement;
65import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement;
66import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
67import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
68import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
69import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetReader;
70import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;
71import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
72import org.openstreetmap.josm.io.CachedFile;
73import org.openstreetmap.josm.io.OsmTransferException;
74import org.openstreetmap.josm.spi.preferences.Config;
75import org.openstreetmap.josm.tools.Logging;
76import org.openstreetmap.josm.tools.OptionParser;
77import org.openstreetmap.josm.tools.RightAndLefthandTraffic;
78import org.openstreetmap.josm.tools.Territories;
79import org.openstreetmap.josm.tools.Utils;
80import org.xml.sax.SAXException;
81
82/**
83 * Extracts tag information for the taginfo project.
84 * <p>
85 * Run from the base directory of a JOSM checkout:
86 * <p>
87 * java -cp dist/josm-custom.jar TagInfoExtract --type mappaint
88 * java -cp dist/josm-custom.jar TagInfoExtract --type presets
89 * java -cp dist/josm-custom.jar TagInfoExtract --type external_presets
90 */
91public class TagInfoExtract {
92
93 /**
94 * Main method.
95 */
96 public static void main(String[] args) throws Exception {
97 TagInfoExtract script = new TagInfoExtract();
98 script.parseCommandLineArguments(args);
99 script.init();
100 switch (script.options.mode) {
101 case MAPPAINT:
102 script.new StyleSheet().run();
103 break;
104 case PRESETS:
105 script.new Presets().run();
106 break;
107 case EXTERNAL_PRESETS:
108 script.new ExternalPresets().run();
109 break;
110 default:
111 throw new IllegalStateException("Invalid type " + script.options.mode);
112 }
113 if (!script.options.noexit) {
114 System.exit(0);
115 }
116 }
117
118 enum Mode {
119 MAPPAINT, PRESETS, EXTERNAL_PRESETS
120 }
121
122 private final Options options = new Options();
123
124 /**
125 * Parse command line arguments.
126 */
127 private void parseCommandLineArguments(String[] args) {
128 if (args.length == 1 && "--help".equals(args[0])) {
129 this.usage();
130 }
131 final OptionParser parser = new OptionParser(getClass().getName());
132 parser.addArgumentParameter("type", OptionParser.OptionCount.REQUIRED, options::setMode);
133 parser.addArgumentParameter("input", OptionParser.OptionCount.OPTIONAL, options::setInputFile);
134 parser.addArgumentParameter("output", OptionParser.OptionCount.OPTIONAL, options::setOutputFile);
135 parser.addArgumentParameter("imgdir", OptionParser.OptionCount.OPTIONAL, options::setImageDir);
136 parser.addArgumentParameter("imgurlprefix", OptionParser.OptionCount.OPTIONAL, options::setImageUrlPrefix);
137 parser.addFlagParameter("noexit", options::setNoExit);
138 parser.addFlagParameter("help", this::usage);
139 parser.parseOptionsOrExit(Arrays.asList(args));
140 }
141
142 private void usage() {
143 System.out.println("java " + getClass().getName());
144 System.out.println(" --type TYPE\tthe project type to be generated: " + Arrays.toString(Mode.values()));
145 System.out.println(" --input FILE\tthe input file to use (overrides defaults for types mappaint, presets)");
146 System.out.println(" --output FILE\tthe output file to use (defaults to STDOUT)");
147 System.out.println(" --imgdir DIRECTORY\tthe directory to put the generated images in (default: " + options.imageDir + ")");
148 System.out.println(" --imgurlprefix STRING\timage URLs prefix for generated image files (public path on webserver)");
149 System.out.println(" --noexit\tdo not call System.exit(), for use from Ant script");
150 System.out.println(" --help\tshow this help");
151 System.exit(0);
152 }
153
154 private static class Options {
155 Mode mode;
156 int josmSvnRevision = Version.getInstance().getVersion();
157 Path baseDir = Paths.get("");
158 Path imageDir = Paths.get("taginfo-img");
159 String imageUrlPrefix;
160 CachedFile inputFile;
161 Path outputFile;
162 boolean noexit;
163
164 void setMode(String value) {
165 mode = Mode.valueOf(value.toUpperCase(Locale.ENGLISH));
166 switch (mode) {
167 case MAPPAINT:
168 inputFile = new CachedFile("resource://styles/standard/elemstyles.mapcss");
169 break;
170 case PRESETS:
171 inputFile = new CachedFile("resource://data/defaultpresets.xml");
172 break;
173 default:
174 inputFile = null;
175 }
176 }
177
178 void setInputFile(String value) {
179 inputFile = new CachedFile(value);
180 }
181
182 void setOutputFile(String value) {
183 outputFile = Paths.get(value);
184 }
185
186 void setImageDir(String value) {
187 imageDir = Paths.get(value);
188 }
189
190 void setImageUrlPrefix(String value) {
191 imageUrlPrefix = value;
192 }
193
194 void setNoExit() {
195 noexit = true;
196 }
197
198 /**
199 * Determine full image url (can refer to JOSM or OSM repository).
200 * @param path the image path
201 */
202 private String findImageUrl(String path) {
203 final Path f = baseDir.resolve("images").resolve(path);
204 if (Files.exists(f)) {
205 return "https://josm.openstreetmap.de/export/" + josmSvnRevision + "/josm/trunk/images/" + path;
206 }
207 throw new IllegalStateException("Cannot find image url for " + path);
208 }
209 }
210
211 private abstract class Extractor {
212 abstract void run() throws Exception;
213
214 void writeJson(String name, String description, Iterable<TagInfoTag> tags) throws IOException {
215 try (Writer writer = options.outputFile != null ? Files.newBufferedWriter(options.outputFile) : new StringWriter();
216 JsonWriter json = Json
217 .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
218 .createWriter(writer)) {
219 JsonObjectBuilder project = Json.createObjectBuilder()
220 .add("name", name)
221 .add("description", description)
222 .add("project_url", "https://josm.openstreetmap.de/")
223 .add("icon_url", "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png")
224 .add("contact_name", "JOSM developer team")
225 .add("contact_email", "josm-dev@openstreetmap.org");
226 final JsonArrayBuilder jsonTags = Json.createArrayBuilder();
227 for (TagInfoTag t : tags) {
228 jsonTags.add(t.toJson());
229 }
230 json.writeObject(Json.createObjectBuilder()
231 .add("data_format", 1)
232 .add("data_updated", DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmmss'Z'").withZone(ZoneId.of("Z")).format(Instant.now()))
233 .add("project", project)
234 .add("tags", jsonTags)
235 .build());
236 if (options.outputFile == null) {
237 System.out.println(writer.toString());
238 }
239 }
240 }
241
242 }
243
244 private class Presets extends Extractor {
245
246 @Override
247 void run() throws IOException, OsmTransferException, SAXException {
248 try (BufferedReader reader = options.inputFile.getContentReader()) {
249 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(reader, true);
250 List<TagInfoTag> tags = convertPresets(presets, "", true);
251 writeJson("JOSM main presets", "Tags supported by the default presets in the OSM editor JOSM", tags);
252 }
253 }
254
255 List<TagInfoTag> convertPresets(Iterable<TaggingPreset> presets, String descriptionPrefix, boolean addImages) {
256 final List<TagInfoTag> tags = new ArrayList<>();
257 for (TaggingPreset preset : presets) {
258 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
259 final Iterable<String> values = item.isKeyRequired()
260 ? item.getValues()
261 : Collections.emptyList();
262 for (String value : values) {
263 final Set<TagInfoTag.Type> types = preset.types == null ? Collections.emptySet() : preset.types.stream()
264 .map(it -> TaggingPresetType.CLOSEDWAY.equals(it)
265 ? TagInfoTag.Type.AREA
266 : TaggingPresetType.MULTIPOLYGON.equals(it)
267 ? TagInfoTag.Type.RELATION
268 : TagInfoTag.Type.valueOf(it.toString()))
269 .collect(Collectors.toCollection(() -> EnumSet.noneOf(TagInfoTag.Type.class)));
270 tags.add(new TagInfoTag(descriptionPrefix + preset.getName(), item.key, value, types,
271 addImages && preset.iconName != null ? options.findImageUrl(preset.iconName) : null));
272 }
273 }
274 }
275 return tags;
276 }
277
278 }
279
280 private class ExternalPresets extends Presets {
281
282 @Override
283 void run() throws IOException, OsmTransferException, SAXException {
284 TaggingPresetReader.setLoadIcons(false);
285 final Collection<ExtendedSourceEntry> sources = new TaggingPresetPreference.TaggingPresetSourceEditor().loadAndGetAvailableSources();
286 final List<TagInfoTag> tags = new ArrayList<>();
287 for (SourceEntry source : sources) {
288 if (source.url.startsWith("resource")) {
289 // default presets
290 continue;
291 }
292 try {
293 System.out.println("Loading " + source.url);
294 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(source.url, false);
295 final List<TagInfoTag> t = convertPresets(presets, source.title + " ", false);
296 System.out.println("Converting " + t.size() + " presets of " + source.title);
297 tags.addAll(t);
298 } catch (Exception ex) {
299 System.err.println("Skipping " + source.url + " due to error");
300 ex.printStackTrace();
301 }
302
303 }
304 writeJson("JOSM user presets", "Tags supported by the user contributed presets in the OSM editor JOSM", tags);
305 }
306 }
307
308 private class StyleSheet extends Extractor {
309 private MapCSSStyleSource styleSource;
310
311 @Override
312 void run() throws IOException, ParseException {
313 init();
314 parseStyleSheet();
315 final List<TagInfoTag> tags = convertStyleSheet();
316 writeJson("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags);
317 }
318
319 /**
320 * Read the style sheet file and parse the MapCSS code.
321 */
322 private void parseStyleSheet() throws IOException, ParseException {
323 try (InputStream stream = options.inputFile.getInputStream()) {
324 MapCSSParser parser = new MapCSSParser(stream, "UTF-8", MapCSSParser.LexicalState.DEFAULT);
325 styleSource = new MapCSSStyleSource("");
326 styleSource.url = "";
327 parser.sheet(styleSource);
328 }
329 }
330
331 /**
332 * Collect all the tag from the style sheet.
333 */
334 private List<TagInfoTag> convertStyleSheet() {
335 return styleSource.rules.stream()
336 .map(rule -> rule.selector)
337 .filter(Selector.GeneralSelector.class::isInstance)
338 .map(Selector.GeneralSelector.class::cast)
339 .map(Selector.AbstractSelector::getConditions)
340 .flatMap(Collection::stream)
341 .filter(ConditionFactory.SimpleKeyValueCondition.class::isInstance)
342 .map(ConditionFactory.SimpleKeyValueCondition.class::cast)
343 .map(condition -> condition.asTag(null))
344 .distinct()
345 .map(tag -> {
346 String iconUrl = null;
347 final EnumSet<TagInfoTag.Type> types = EnumSet.noneOf(TagInfoTag.Type.class);
348 Optional<String> nodeUrl = new NodeChecker(tag).findUrl(true);
349 if (nodeUrl.isPresent()) {
350 iconUrl = nodeUrl.get();
351 types.add(TagInfoTag.Type.NODE);
352 }
353 Optional<String> wayUrl = new WayChecker(tag).findUrl(iconUrl == null);
354 if (wayUrl.isPresent()) {
355 if (iconUrl == null) {
356 iconUrl = wayUrl.get();
357 }
358 types.add(TagInfoTag.Type.WAY);
359 }
360 Optional<String> areaUrl = new AreaChecker(tag).findUrl(iconUrl == null);
361 if (areaUrl.isPresent()) {
362 if (iconUrl == null) {
363 iconUrl = areaUrl.get();
364 }
365 types.add(TagInfoTag.Type.AREA);
366 }
367 return new TagInfoTag(null, tag.getKey(), tag.getValue(), types, iconUrl);
368 })
369 .collect(Collectors.toList());
370 }
371
372 /**
373 * Check if a certain tag is supported by the style as node / way / area.
374 */
375 private abstract class Checker {
376 Checker(Tag tag) {
377 this.tag = tag;
378 }
379
380 Environment applyStylesheet(OsmPrimitive osm) {
381 osm.put(tag);
382 MultiCascade mc = new MultiCascade();
383
384 Environment env = new Environment(osm, mc, null, styleSource);
385 for (MapCSSRule r : styleSource.rules) {
386 env.clearSelectorMatchingInformation();
387 if (r.selector.matches(env)) {
388 // ignore selector range
389 if (env.layer == null) {
390 env.layer = "default";
391 }
392 r.execute(env);
393 }
394 }
395 env.layer = "default";
396 return env;
397 }
398
399 /**
400 * Create image file from StyleElement.
401 *
402 * @return the URL
403 */
404 String createImage(StyleElement element, final String type, NavigatableComponent nc) {
405 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
406 Graphics2D g = img.createGraphics();
407 g.setClip(0, 0, 16, 16);
408 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
409 renderer.getSettings(false);
410 element.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
411 final String imageName = type + "_" + tag + ".png";
412 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
413 ImageIO.write(img, "png", out);
414 } catch (IOException e) {
415 throw new UncheckedIOException(e);
416 }
417 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
418 return baseUrl + "/" + imageName;
419 }
420
421 /**
422 * Checks, if tag is supported and find URL for image icon in this case.
423 *
424 * @param generateImage if true, create or find a suitable image icon and return URL,
425 * if false, just check if tag is supported and return true or false
426 */
427 abstract Optional<String> findUrl(boolean generateImage);
428
429 protected Tag tag;
430 protected OsmPrimitive osm;
431 }
432
433 private class NodeChecker extends Checker {
434 NodeChecker(Tag tag) {
435 super(tag);
436 }
437
438 @Override
439 Optional<String> findUrl(boolean generateImage) {
440 this.osm = new Node(LatLon.ZERO);
441 Environment env = applyStylesheet(osm);
442 Cascade c = env.mc.getCascade("default");
443 Object image = c.get("icon-image");
444 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
445 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
446 }
447 return Optional.empty();
448 }
449
450 }
451
452 private class WayChecker extends Checker {
453 WayChecker(Tag tag) {
454 super(tag);
455 }
456
457 @Override
458 Optional<String> findUrl(boolean generateImage) {
459 this.osm = new Way();
460 NavigatableComponent nc = new NavigatableComponent();
461 Node n1 = new Node(nc.getLatLon(2, 8));
462 Node n2 = new Node(nc.getLatLon(14, 8));
463 ((Way) osm).addNode(n1);
464 ((Way) osm).addNode(n2);
465 Environment env = applyStylesheet(osm);
466 LineElement les = LineElement.createLine(env);
467 if (les != null) {
468 if (!generateImage) return Optional.of("");
469 return Optional.of(createImage(les, "way", nc));
470 }
471 return Optional.empty();
472 }
473
474 }
475
476 private class AreaChecker extends Checker {
477 AreaChecker(Tag tag) {
478 super(tag);
479 }
480
481 @Override
482 Optional<String> findUrl(boolean generateImage) {
483 this.osm = new Way();
484 NavigatableComponent nc = new NavigatableComponent();
485 Node n1 = new Node(nc.getLatLon(2, 2));
486 Node n2 = new Node(nc.getLatLon(14, 2));
487 Node n3 = new Node(nc.getLatLon(14, 14));
488 Node n4 = new Node(nc.getLatLon(2, 14));
489 ((Way) osm).addNode(n1);
490 ((Way) osm).addNode(n2);
491 ((Way) osm).addNode(n3);
492 ((Way) osm).addNode(n4);
493 ((Way) osm).addNode(n1);
494 Environment env = applyStylesheet(osm);
495 AreaElement aes = AreaElement.create(env);
496 if (aes != null) {
497 if (!generateImage) return Optional.of("");
498 return Optional.of(createImage(aes, "area", nc));
499 }
500 return Optional.empty();
501 }
502 }
503 }
504
505 /**
506 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
507 */
508 private static class TagInfoTag {
509 final String description;
510 final String key;
511 final String value;
512 final Set<Type> objectTypes;
513 final String iconURL;
514
515 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
516 this.description = description;
517 this.key = key;
518 this.value = value;
519 this.objectTypes = objectTypes;
520 this.iconURL = iconURL;
521 }
522
523 JsonObjectBuilder toJson() {
524 final JsonObjectBuilder object = Json.createObjectBuilder();
525 if (description != null) {
526 object.add("description", description);
527 }
528 object.add("key", key);
529 object.add("value", value);
530 if ((!objectTypes.isEmpty())) {
531 final JsonArrayBuilder types = Json.createArrayBuilder();
532 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
533 object.add("object_types", types);
534 }
535 if (iconURL != null) {
536 object.add("icon_url", iconURL);
537 }
538 return object;
539 }
540
541 enum Type {
542 NODE, WAY, AREA, RELATION
543 }
544 }
545
546 /**
547 * Initialize the script.
548 */
549 private void init() throws IOException {
550 Logging.setLogLevel(Logging.LEVEL_INFO);
551 Preferences.main().enableSaveOnPut(false);
552 Config.setPreferencesInstance(Preferences.main());
553 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
554 Config.setUrlsProvider(JosmUrls.getInstance());
555 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
556 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
557 tmpdir.toFile().deleteOnExit();
558 System.setProperty("josm.home", tmpdir.toString());
559 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
560 Territories.initialize();
561 RightAndLefthandTraffic.initialize();
562 Files.createDirectories(options.imageDir);
563 }
564}
Note: See TracBrowser for help on using the repository browser.