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

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

see #18802 - Add Selector.getConditions

File size: 24.2 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.stream.Collectors;
27
28import javax.imageio.ImageIO;
29import javax.json.Json;
30import javax.json.JsonArrayBuilder;
31import javax.json.JsonObjectBuilder;
32import javax.json.JsonWriter;
33import javax.json.stream.JsonGenerator;
34
35import org.openstreetmap.josm.actions.DeleteAction;
36import org.openstreetmap.josm.command.DeleteCommand;
37import org.openstreetmap.josm.data.Preferences;
38import org.openstreetmap.josm.data.Version;
39import org.openstreetmap.josm.data.coor.LatLon;
40import org.openstreetmap.josm.data.osm.Node;
41import org.openstreetmap.josm.data.osm.OsmPrimitive;
42import org.openstreetmap.josm.data.osm.Tag;
43import org.openstreetmap.josm.data.osm.Way;
44import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings;
45import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer;
46import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
47import org.openstreetmap.josm.data.preferences.JosmUrls;
48import org.openstreetmap.josm.data.preferences.sources.ExtendedSourceEntry;
49import org.openstreetmap.josm.data.preferences.sources.SourceEntry;
50import org.openstreetmap.josm.data.projection.ProjectionRegistry;
51import org.openstreetmap.josm.data.projection.Projections;
52import org.openstreetmap.josm.gui.NavigatableComponent;
53import org.openstreetmap.josm.gui.mappaint.Cascade;
54import org.openstreetmap.josm.gui.mappaint.Environment;
55import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
56import org.openstreetmap.josm.gui.mappaint.MultiCascade;
57import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory;
58import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSRule;
59import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource;
60import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser;
61import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.ParseException;
62import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement;
63import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement;
64import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement;
65import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
66import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;
67import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetReader;
68import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;
69import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem;
70import org.openstreetmap.josm.io.CachedFile;
71import org.openstreetmap.josm.io.OsmTransferException;
72import org.openstreetmap.josm.spi.preferences.Config;
73import org.openstreetmap.josm.tools.Http1Client;
74import org.openstreetmap.josm.tools.HttpClient;
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 * @param args Main program arguments
96 * @throws Exception if any error occurs
97 */
98 public static void main(String[] args) throws Exception {
99 HttpClient.setFactory(Http1Client::new);
100 TagInfoExtract script = new TagInfoExtract();
101 script.parseCommandLineArguments(args);
102 script.init();
103 switch (script.options.mode) {
104 case MAPPAINT:
105 script.new StyleSheet().run();
106 break;
107 case PRESETS:
108 script.new Presets().run();
109 break;
110 case EXTERNAL_PRESETS:
111 script.new ExternalPresets().run();
112 break;
113 default:
114 throw new IllegalStateException("Invalid type " + script.options.mode);
115 }
116 if (!script.options.noexit) {
117 System.exit(0);
118 }
119 }
120
121 enum Mode {
122 MAPPAINT, PRESETS, EXTERNAL_PRESETS
123 }
124
125 private final Options options = new Options();
126
127 /**
128 * Parse command line arguments.
129 * @param args command line arguments
130 */
131 private void parseCommandLineArguments(String[] args) {
132 if (args.length == 1 && "--help".equals(args[0])) {
133 this.usage();
134 }
135 final OptionParser parser = new OptionParser(getClass().getName());
136 parser.addArgumentParameter("type", OptionParser.OptionCount.REQUIRED, options::setMode);
137 parser.addArgumentParameter("input", OptionParser.OptionCount.OPTIONAL, options::setInputFile);
138 parser.addArgumentParameter("output", OptionParser.OptionCount.OPTIONAL, options::setOutputFile);
139 parser.addArgumentParameter("imgdir", OptionParser.OptionCount.OPTIONAL, options::setImageDir);
140 parser.addArgumentParameter("imgurlprefix", OptionParser.OptionCount.OPTIONAL, options::setImageUrlPrefix);
141 parser.addFlagParameter("noexit", options::setNoExit);
142 parser.addFlagParameter("help", this::usage);
143 parser.parseOptionsOrExit(Arrays.asList(args));
144 }
145
146 private void usage() {
147 System.out.println("java " + getClass().getName());
148 System.out.println(" --type TYPE\tthe project type to be generated: " + Arrays.toString(Mode.values()));
149 System.out.println(" --input FILE\tthe input file to use (overrides defaults for types mappaint, presets)");
150 System.out.println(" --output FILE\tthe output file to use (defaults to STDOUT)");
151 System.out.println(" --imgdir DIRECTORY\tthe directory to put the generated images in (default: " + options.imageDir + ")");
152 System.out.println(" --imgurlprefix STRING\timage URLs prefix for generated image files (public path on webserver)");
153 System.out.println(" --noexit\tdo not call System.exit(), for use from Ant script");
154 System.out.println(" --help\tshow this help");
155 System.exit(0);
156 }
157
158 private static class Options {
159 Mode mode;
160 int josmSvnRevision = Version.getInstance().getVersion();
161 Path baseDir = Paths.get("");
162 Path imageDir = Paths.get("taginfo-img");
163 String imageUrlPrefix;
164 CachedFile inputFile;
165 Path outputFile;
166 boolean noexit;
167
168 void setMode(String value) {
169 mode = Mode.valueOf(value.toUpperCase(Locale.ENGLISH));
170 switch (mode) {
171 case MAPPAINT:
172 inputFile = new CachedFile("resource://styles/standard/elemstyles.mapcss");
173 break;
174 case PRESETS:
175 inputFile = new CachedFile("resource://data/defaultpresets.xml");
176 break;
177 default:
178 inputFile = null;
179 }
180 }
181
182 void setInputFile(String value) {
183 inputFile = new CachedFile(value);
184 }
185
186 void setOutputFile(String value) {
187 outputFile = Paths.get(value);
188 }
189
190 void setImageDir(String value) {
191 imageDir = Paths.get(value);
192 }
193
194 void setImageUrlPrefix(String value) {
195 imageUrlPrefix = value;
196 }
197
198 void setNoExit() {
199 noexit = true;
200 }
201
202 /**
203 * Determine full image url (can refer to JOSM or OSM repository).
204 * @param path the image path
205 * @return full image url
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 * @throws IOException if any I/O error occurs
327 * @throws ParseException in case of parsing error
328 */
329 private void parseStyleSheet() throws IOException, ParseException {
330 try (BufferedReader reader = options.inputFile.getContentReader()) {
331 MapCSSParser parser = new MapCSSParser(reader, MapCSSParser.LexicalState.DEFAULT);
332 styleSource = new MapCSSStyleSource("");
333 styleSource.url = "";
334 parser.sheet(styleSource);
335 }
336 }
337
338 /**
339 * Collect all the tag from the style sheet.
340 * @return list of taginfo tags
341 */
342 private List<TagInfoTag> convertStyleSheet() {
343 return styleSource.rules.stream()
344 .flatMap(rule -> rule.selector.getConditions().stream())
345 .filter(ConditionFactory.SimpleKeyValueCondition.class::isInstance)
346 .map(ConditionFactory.SimpleKeyValueCondition.class::cast)
347 .map(condition -> condition.asTag(null))
348 .distinct()
349 .map(tag -> {
350 String iconUrl = null;
351 final EnumSet<TagInfoTag.Type> types = EnumSet.noneOf(TagInfoTag.Type.class);
352 Optional<String> nodeUrl = new NodeChecker(tag).findUrl(true);
353 if (nodeUrl.isPresent()) {
354 iconUrl = nodeUrl.get();
355 types.add(TagInfoTag.Type.NODE);
356 }
357 Optional<String> wayUrl = new WayChecker(tag).findUrl(iconUrl == null);
358 if (wayUrl.isPresent()) {
359 if (iconUrl == null) {
360 iconUrl = wayUrl.get();
361 }
362 types.add(TagInfoTag.Type.WAY);
363 }
364 Optional<String> areaUrl = new AreaChecker(tag).findUrl(iconUrl == null);
365 if (areaUrl.isPresent()) {
366 if (iconUrl == null) {
367 iconUrl = areaUrl.get();
368 }
369 types.add(TagInfoTag.Type.AREA);
370 }
371 return new TagInfoTag(null, tag.getKey(), tag.getValue(), types, iconUrl);
372 })
373 .collect(Collectors.toList());
374 }
375
376 /**
377 * Check if a certain tag is supported by the style as node / way / area.
378 */
379 private abstract class Checker {
380 Checker(Tag tag) {
381 this.tag = tag;
382 }
383
384 Environment applyStylesheet(OsmPrimitive osm) {
385 osm.put(tag);
386 MultiCascade mc = new MultiCascade();
387
388 Environment env = new Environment(osm, mc, null, styleSource);
389 for (MapCSSRule r : styleSource.rules) {
390 env.clearSelectorMatchingInformation();
391 if (r.matches(env)) {
392 // ignore selector range
393 if (env.layer == null) {
394 env.layer = "default";
395 }
396 r.execute(env);
397 }
398 }
399 env.layer = "default";
400 return env;
401 }
402
403 /**
404 * Create image file from StyleElement.
405 * @param element style element
406 * @param type object type
407 * @param nc navigatable component
408 *
409 * @return the URL
410 */
411 String createImage(StyleElement element, final String type, NavigatableComponent nc) {
412 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
413 Graphics2D g = img.createGraphics();
414 g.setClip(0, 0, 16, 16);
415 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
416 renderer.getSettings(false);
417 element.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
418 final String imageName = type + "_" + tag + ".png";
419 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
420 ImageIO.write(img, "png", out);
421 } catch (IOException e) {
422 throw new UncheckedIOException(e);
423 }
424 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
425 return baseUrl + "/" + imageName;
426 }
427
428 /**
429 * Checks, if tag is supported and find URL for image icon in this case.
430 *
431 * @param generateImage if true, create or find a suitable image icon and return URL,
432 * if false, just check if tag is supported and return true or false
433 * @return URL for image icon if tag is supported
434 */
435 abstract Optional<String> findUrl(boolean generateImage);
436
437 protected Tag tag;
438 protected OsmPrimitive osm;
439 }
440
441 private class NodeChecker extends Checker {
442 NodeChecker(Tag tag) {
443 super(tag);
444 }
445
446 @Override
447 Optional<String> findUrl(boolean generateImage) {
448 this.osm = new Node(LatLon.ZERO);
449 Environment env = applyStylesheet(osm);
450 Cascade c = env.mc.getCascade("default");
451 Object image = c.get("icon-image");
452 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
453 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
454 }
455 return Optional.empty();
456 }
457
458 }
459
460 private class WayChecker extends Checker {
461 WayChecker(Tag tag) {
462 super(tag);
463 }
464
465 @Override
466 Optional<String> findUrl(boolean generateImage) {
467 this.osm = new Way();
468 NavigatableComponent nc = new NavigatableComponent();
469 Node n1 = new Node(nc.getLatLon(2, 8));
470 Node n2 = new Node(nc.getLatLon(14, 8));
471 ((Way) osm).addNode(n1);
472 ((Way) osm).addNode(n2);
473 Environment env = applyStylesheet(osm);
474 LineElement les = LineElement.createLine(env);
475 if (les != null) {
476 if (!generateImage) return Optional.of("");
477 return Optional.of(createImage(les, "way", nc));
478 }
479 return Optional.empty();
480 }
481
482 }
483
484 private class AreaChecker extends Checker {
485 AreaChecker(Tag tag) {
486 super(tag);
487 }
488
489 @Override
490 Optional<String> findUrl(boolean generateImage) {
491 this.osm = new Way();
492 NavigatableComponent nc = new NavigatableComponent();
493 Node n1 = new Node(nc.getLatLon(2, 2));
494 Node n2 = new Node(nc.getLatLon(14, 2));
495 Node n3 = new Node(nc.getLatLon(14, 14));
496 Node n4 = new Node(nc.getLatLon(2, 14));
497 ((Way) osm).addNode(n1);
498 ((Way) osm).addNode(n2);
499 ((Way) osm).addNode(n3);
500 ((Way) osm).addNode(n4);
501 ((Way) osm).addNode(n1);
502 Environment env = applyStylesheet(osm);
503 AreaElement aes = AreaElement.create(env);
504 if (aes != null) {
505 if (!generateImage) return Optional.of("");
506 return Optional.of(createImage(aes, "area", nc));
507 }
508 return Optional.empty();
509 }
510 }
511 }
512
513 /**
514 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
515 */
516 private static class TagInfoTag {
517 final String description;
518 final String key;
519 final String value;
520 final Set<Type> objectTypes;
521 final String iconURL;
522
523 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
524 this.description = description;
525 this.key = key;
526 this.value = value;
527 this.objectTypes = objectTypes;
528 this.iconURL = iconURL;
529 }
530
531 JsonObjectBuilder toJson() {
532 final JsonObjectBuilder object = Json.createObjectBuilder();
533 if (description != null) {
534 object.add("description", description);
535 }
536 object.add("key", key);
537 object.add("value", value);
538 if ((!objectTypes.isEmpty())) {
539 final JsonArrayBuilder types = Json.createArrayBuilder();
540 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
541 object.add("object_types", types);
542 }
543 if (iconURL != null) {
544 object.add("icon_url", iconURL);
545 }
546 return object;
547 }
548
549 enum Type {
550 NODE, WAY, AREA, RELATION
551 }
552 }
553
554 /**
555 * Initialize the script.
556 * @throws IOException if any I/O error occurs
557 */
558 private void init() throws IOException {
559 Logging.setLogLevel(Logging.LEVEL_INFO);
560 Preferences.main().enableSaveOnPut(false);
561 Config.setPreferencesInstance(Preferences.main());
562 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
563 Config.setUrlsProvider(JosmUrls.getInstance());
564 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
565 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
566 tmpdir.toFile().deleteOnExit();
567 System.setProperty("josm.home", tmpdir.toString());
568 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
569 Territories.initialize();
570 RightAndLefthandTraffic.initialize();
571 Files.createDirectories(options.imageDir);
572 }
573}
Note: See TracBrowser for help on using the repository browser.