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

Last change on this file since 16269 was 16269, checked in by simon04, 6 years ago

Extract TagInfoExtract.TagInfoTag.Type#forPresetType

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