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

Last change on this file since 14635 was 14635, checked in by simon04, 5 years ago

see #17170 - Refactoring of TagInfoExtract

File size: 23.9 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 try {
189 Files.createDirectories(imageDir);
190 } catch (IOException e) {
191 throw new UncheckedIOException(e);
192 }
193 }
194
195 void setImageUrlPrefix(String value) {
196 imageUrlPrefix = value;
197 }
198
199 void setNoExit() {
200 noexit = true;
201 }
202
203 /**
204 * Determine full image url (can refer to JOSM or OSM repository).
205 * @param path the image path
206 */
207 private String findImageUrl(String path) {
208 final Path f = baseDir.resolve("images").resolve(path);
209 if (Files.exists(f)) {
210 return "https://josm.openstreetmap.de/export/" + josmSvnRevision + "/josm/trunk/images/" + path;
211 }
212 throw new IllegalStateException("Cannot find image url for " + path);
213 }
214 }
215
216 private abstract class Extractor {
217 abstract void run() throws Exception;
218
219 void writeJson(String name, String description, Iterable<TagInfoTag> tags) throws IOException {
220 try (Writer writer = options.outputFile != null ? Files.newBufferedWriter(options.outputFile) : new StringWriter();
221 JsonWriter json = Json
222 .createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
223 .createWriter(writer)) {
224 JsonObjectBuilder project = Json.createObjectBuilder()
225 .add("name", name)
226 .add("description", description)
227 .add("project_url", "https://josm.openstreetmap.de/")
228 .add("icon_url", "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png")
229 .add("contact_name", "JOSM developer team")
230 .add("contact_email", "josm-dev@openstreetmap.org");
231 final JsonArrayBuilder jsonTags = Json.createArrayBuilder();
232 for (TagInfoTag t : tags) {
233 jsonTags.add(t.toJson());
234 }
235 json.writeObject(Json.createObjectBuilder()
236 .add("data_format", 1)
237 .add("data_updated", DateTimeFormatter.ofPattern("yyyyMMdd'T'hhmmss'Z'").withZone(ZoneId.of("Z")).format(Instant.now()))
238 .add("project", project)
239 .add("tags", jsonTags)
240 .build());
241 if (options.outputFile == null) {
242 System.out.println(writer.toString());
243 }
244 }
245 }
246
247 }
248
249 private class Presets extends Extractor {
250
251 @Override
252 void run() throws IOException, OsmTransferException, SAXException {
253 try (BufferedReader reader = options.inputFile.getContentReader()) {
254 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(reader, true);
255 List<TagInfoTag> tags = convertPresets(presets, "", true);
256 writeJson("JOSM main presets", "Tags supported by the default presets in the OSM editor JOSM", tags);
257 }
258 }
259
260 List<TagInfoTag> convertPresets(Iterable<TaggingPreset> presets, String descriptionPrefix, boolean addImages) {
261 final List<TagInfoTag> tags = new ArrayList<>();
262 for (TaggingPreset preset : presets) {
263 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
264 final Iterable<String> values = item.isKeyRequired()
265 ? item.getValues()
266 : Collections.emptyList();
267 for (String value : values) {
268 final Set<TagInfoTag.Type> types = preset.types == null ? Collections.emptySet() : preset.types.stream()
269 .map(it -> TaggingPresetType.CLOSEDWAY.equals(it)
270 ? TagInfoTag.Type.AREA
271 : TaggingPresetType.MULTIPOLYGON.equals(it)
272 ? TagInfoTag.Type.RELATION
273 : TagInfoTag.Type.valueOf(it.toString()))
274 .collect(Collectors.toCollection(() -> EnumSet.noneOf(TagInfoTag.Type.class)));
275 tags.add(new TagInfoTag(descriptionPrefix + preset.getName(), item.key, value, types,
276 addImages && preset.iconName != null ? options.findImageUrl(preset.iconName) : null));
277 }
278 }
279 }
280 return tags;
281 }
282
283 }
284
285 private class ExternalPresets extends Presets {
286
287 @Override
288 void run() throws IOException, OsmTransferException, SAXException {
289 TaggingPresetReader.setLoadIcons(false);
290 final Collection<ExtendedSourceEntry> sources = new TaggingPresetPreference.TaggingPresetSourceEditor().loadAndGetAvailableSources();
291 final List<TagInfoTag> tags = new ArrayList<>();
292 for (SourceEntry source : sources) {
293 if (source.url.startsWith("resource")) {
294 // default presets
295 continue;
296 }
297 try {
298 System.out.println("Loading " + source.url);
299 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(source.url, false);
300 final List<TagInfoTag> t = convertPresets(presets, source.title + " ", false);
301 System.out.println("Converting " + t.size() + " presets of " + source.title);
302 tags.addAll(t);
303 } catch (Exception ex) {
304 System.err.println("Skipping " + source.url + " due to error");
305 ex.printStackTrace();
306 }
307
308 }
309 writeJson("JOSM user presets", "Tags supported by the user contributed presets in the OSM editor JOSM", tags);
310 }
311 }
312
313 private class StyleSheet extends Extractor {
314 private MapCSSStyleSource styleSource;
315
316 @Override
317 void run() throws IOException, ParseException {
318 init();
319 parseStyleSheet();
320 final List<TagInfoTag> tags = convertStyleSheet();
321 writeJson("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags);
322 }
323
324 /**
325 * Read the style sheet file and parse the MapCSS code.
326 */
327 private void parseStyleSheet() throws IOException, ParseException {
328 try (InputStream stream = options.inputFile.getInputStream()) {
329 MapCSSParser parser = new MapCSSParser(stream, "UTF-8", MapCSSParser.LexicalState.DEFAULT);
330 styleSource = new MapCSSStyleSource("");
331 styleSource.url = "";
332 parser.sheet(styleSource);
333 }
334 }
335
336 /**
337 * Collect all the tag from the style sheet.
338 */
339 private List<TagInfoTag> convertStyleSheet() {
340 return styleSource.rules.stream()
341 .map(rule -> rule.selector)
342 .filter(Selector.GeneralSelector.class::isInstance)
343 .map(Selector.GeneralSelector.class::cast)
344 .map(Selector.AbstractSelector::getConditions)
345 .flatMap(Collection::stream)
346 .filter(ConditionFactory.SimpleKeyValueCondition.class::isInstance)
347 .map(ConditionFactory.SimpleKeyValueCondition.class::cast)
348 .map(condition -> condition.asTag(null))
349 .distinct()
350 .map(tag -> {
351 String iconUrl = null;
352 final EnumSet<TagInfoTag.Type> types = EnumSet.noneOf(TagInfoTag.Type.class);
353 Optional<String> nodeUrl = new NodeChecker(tag).findUrl(true);
354 if (nodeUrl.isPresent()) {
355 iconUrl = nodeUrl.get();
356 types.add(TagInfoTag.Type.NODE);
357 }
358 Optional<String> wayUrl = new WayChecker(tag).findUrl(iconUrl == null);
359 if (wayUrl.isPresent()) {
360 if (iconUrl == null) {
361 iconUrl = wayUrl.get();
362 }
363 types.add(TagInfoTag.Type.WAY);
364 }
365 Optional<String> areaUrl = new AreaChecker(tag).findUrl(iconUrl == null);
366 if (areaUrl.isPresent()) {
367 if (iconUrl == null) {
368 iconUrl = areaUrl.get();
369 }
370 types.add(TagInfoTag.Type.AREA);
371 }
372 return new TagInfoTag(null, tag.getKey(), tag.getValue(), types, iconUrl);
373 })
374 .collect(Collectors.toList());
375 }
376
377 /**
378 * Check if a certain tag is supported by the style as node / way / area.
379 */
380 private abstract class Checker {
381 Checker(Tag tag) {
382 this.tag = tag;
383 }
384
385 Environment applyStylesheet(OsmPrimitive osm) {
386 osm.put(tag);
387 MultiCascade mc = new MultiCascade();
388
389 Environment env = new Environment(osm, mc, null, styleSource);
390 for (MapCSSRule r : styleSource.rules) {
391 env.clearSelectorMatchingInformation();
392 if (r.selector.matches(env)) {
393 // ignore selector range
394 if (env.layer == null) {
395 env.layer = "default";
396 }
397 r.execute(env);
398 }
399 }
400 env.layer = "default";
401 return env;
402 }
403
404 /**
405 * Create image file from StyleElement.
406 *
407 * @return the URL
408 */
409 String createImage(StyleElement elem_style, final String type, NavigatableComponent nc) {
410 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
411 Graphics2D g = img.createGraphics();
412 g.setClip(0, 0, 16, 16);
413 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
414 renderer.getSettings(false);
415 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
416 final String imageName = type + "_" + tag + ".png";
417 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
418 ImageIO.write(img, "png", out);
419 } catch (IOException e) {
420 throw new UncheckedIOException(e);
421 }
422 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
423 return baseUrl + "/" + imageName;
424 }
425
426 /**
427 * Checks, if tag is supported and find URL for image icon in this case.
428 *
429 * @param generateImage if true, create or find a suitable image icon and return URL,
430 * if false, just check if tag is supported and return true or false
431 */
432 abstract Optional<String> findUrl(boolean generateImage);
433
434 protected Tag tag;
435 protected OsmPrimitive osm;
436 }
437
438 private class NodeChecker extends Checker {
439 NodeChecker(Tag tag) {
440 super(tag);
441 }
442
443 @Override
444 Optional<String> findUrl(boolean generateImage) {
445 this.osm = new Node(LatLon.ZERO);
446 Environment env = applyStylesheet(osm);
447 Cascade c = env.mc.getCascade("default");
448 Object image = c.get("icon-image");
449 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
450 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
451 }
452 return Optional.empty();
453 }
454
455 }
456
457 private class WayChecker extends Checker {
458 WayChecker(Tag tag) {
459 super(tag);
460 }
461
462 @Override
463 Optional<String> findUrl(boolean generateImage) {
464 this.osm = new Way();
465 NavigatableComponent nc = new NavigatableComponent();
466 Node n1 = new Node(nc.getLatLon(2, 8));
467 Node n2 = new Node(nc.getLatLon(14, 8));
468 ((Way) osm).addNode(n1);
469 ((Way) osm).addNode(n2);
470 Environment env = applyStylesheet(osm);
471 LineElement les = LineElement.createLine(env);
472 if (les != null) {
473 if (!generateImage) return Optional.of("");
474 return Optional.of(createImage(les, "way", nc));
475 }
476 return Optional.empty();
477 }
478
479 }
480
481 private class AreaChecker extends Checker {
482 AreaChecker(Tag tag) {
483 super(tag);
484 }
485
486 @Override
487 Optional<String> findUrl(boolean generateImage) {
488 this.osm = new Way();
489 NavigatableComponent nc = new NavigatableComponent();
490 Node n1 = new Node(nc.getLatLon(2, 2));
491 Node n2 = new Node(nc.getLatLon(14, 2));
492 Node n3 = new Node(nc.getLatLon(14, 14));
493 Node n4 = new Node(nc.getLatLon(2, 14));
494 ((Way) osm).addNode(n1);
495 ((Way) osm).addNode(n2);
496 ((Way) osm).addNode(n3);
497 ((Way) osm).addNode(n4);
498 ((Way) osm).addNode(n1);
499 Environment env = applyStylesheet(osm);
500 AreaElement aes = AreaElement.create(env);
501 if (aes != null) {
502 if (!generateImage) return Optional.of("");
503 return Optional.of(createImage(aes, "area", nc));
504 }
505 return Optional.empty();
506 }
507 }
508 }
509
510 /**
511 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
512 */
513 private static class TagInfoTag {
514 final String description;
515 final String key;
516 final String value;
517 final Set<Type> objectTypes;
518 final String iconURL;
519
520 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
521 this.description = description;
522 this.key = key;
523 this.value = value;
524 this.objectTypes = objectTypes;
525 this.iconURL = iconURL;
526 }
527
528 JsonObjectBuilder toJson() {
529 final JsonObjectBuilder object = Json.createObjectBuilder();
530 if (description != null) {
531 object.add("description", description);
532 }
533 object.add("key", key);
534 object.add("value", value);
535 if ((!objectTypes.isEmpty())) {
536 final JsonArrayBuilder types = Json.createArrayBuilder();
537 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
538 object.add("object_types", types);
539 }
540 if (iconURL != null) {
541 object.add("icon_url", iconURL);
542 }
543 return object;
544 }
545
546 enum Type {
547 NODE, WAY, AREA, RELATION
548 }
549 }
550
551 /**
552 * Initialize the script.
553 */
554 private void init() throws IOException {
555 Logging.setLogLevel(Logging.LEVEL_INFO);
556 Preferences.main().enableSaveOnPut(false);
557 Config.setPreferencesInstance(Preferences.main());
558 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
559 Config.setUrlsProvider(JosmUrls.getInstance());
560 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
561 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
562 tmpdir.toFile().deleteOnExit();
563 System.setProperty("josm.home", tmpdir.toString());
564 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
565 Territories.initialize();
566 RightAndLefthandTraffic.initialize();
567 }
568}
Note: See TracBrowser for help on using the repository browser.