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

Last change on this file since 16059 was 16018, checked in by Don-vip, 4 years ago

see #18845 - fix epsg and taginfo goals

File size: 24.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.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", "https://josm.openstreetmap.de/")
230 .add("icon_url", "https://josm.openstreetmap.de/export/7770/josm/trunk/resources/images/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 = preset.types == null ? Collections.emptySet() : preset.types.stream()
271 .map(it -> TaggingPresetType.CLOSEDWAY.equals(it)
272 ? TagInfoTag.Type.AREA
273 : TaggingPresetType.MULTIPOLYGON.equals(it)
274 ? TagInfoTag.Type.RELATION
275 : TagInfoTag.Type.valueOf(it.toString()))
276 .collect(Collectors.toCollection(() -> EnumSet.noneOf(TagInfoTag.Type.class)));
277 tags.add(new TagInfoTag(descriptionPrefix + preset.getName(), item.key, value, types,
278 addImages && preset.iconName != null ? options.findImageUrl(preset.iconName) : null));
279 }
280 }
281 }
282 return tags;
283 }
284
285 }
286
287 private class ExternalPresets extends Presets {
288
289 @Override
290 void run() throws IOException, OsmTransferException, SAXException {
291 TaggingPresetReader.setLoadIcons(false);
292 final Collection<ExtendedSourceEntry> sources = new TaggingPresetPreference.TaggingPresetSourceEditor().loadAndGetAvailableSources();
293 final List<TagInfoTag> tags = new ArrayList<>();
294 for (SourceEntry source : sources) {
295 if (source.url.startsWith("resource")) {
296 // default presets
297 continue;
298 }
299 try {
300 System.out.println("Loading " + source.url);
301 Collection<TaggingPreset> presets = TaggingPresetReader.readAll(source.url, false);
302 final List<TagInfoTag> t = convertPresets(presets, source.title + " ", false);
303 System.out.println("Converting " + t.size() + " presets of " + source.title);
304 tags.addAll(t);
305 } catch (Exception ex) {
306 System.err.println("Skipping " + source.url + " due to error");
307 ex.printStackTrace();
308 }
309
310 }
311 writeJson("JOSM user presets", "Tags supported by the user contributed presets in the OSM editor JOSM", tags);
312 }
313 }
314
315 private class StyleSheet extends Extractor {
316 private MapCSSStyleSource styleSource;
317
318 @Override
319 void run() throws IOException, ParseException {
320 init();
321 parseStyleSheet();
322 final List<TagInfoTag> tags = convertStyleSheet();
323 writeJson("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags);
324 }
325
326 /**
327 * Read the style sheet file and parse the MapCSS code.
328 * @throws IOException if any I/O error occurs
329 * @throws ParseException in case of parsing error
330 */
331 private void parseStyleSheet() throws IOException, ParseException {
332 try (BufferedReader reader = options.inputFile.getContentReader()) {
333 MapCSSParser parser = new MapCSSParser(reader, MapCSSParser.LexicalState.DEFAULT);
334 styleSource = new MapCSSStyleSource("");
335 styleSource.url = "";
336 parser.sheet(styleSource);
337 }
338 }
339
340 /**
341 * Collect all the tag from the style sheet.
342 * @return list of taginfo tags
343 */
344 private List<TagInfoTag> convertStyleSheet() {
345 return styleSource.rules.stream()
346 .flatMap(rule -> rule.selectors.stream())
347 .flatMap(selector -> selector.getConditions().stream())
348 .filter(ConditionFactory.SimpleKeyValueCondition.class::isInstance)
349 .map(ConditionFactory.SimpleKeyValueCondition.class::cast)
350 .map(condition -> condition.asTag(null))
351 .distinct()
352 .map(tag -> {
353 String iconUrl = null;
354 final EnumSet<TagInfoTag.Type> types = EnumSet.noneOf(TagInfoTag.Type.class);
355 Optional<String> nodeUrl = new NodeChecker(tag).findUrl(true);
356 if (nodeUrl.isPresent()) {
357 iconUrl = nodeUrl.get();
358 types.add(TagInfoTag.Type.NODE);
359 }
360 Optional<String> wayUrl = new WayChecker(tag).findUrl(iconUrl == null);
361 if (wayUrl.isPresent()) {
362 if (iconUrl == null) {
363 iconUrl = wayUrl.get();
364 }
365 types.add(TagInfoTag.Type.WAY);
366 }
367 Optional<String> areaUrl = new AreaChecker(tag).findUrl(iconUrl == null);
368 if (areaUrl.isPresent()) {
369 if (iconUrl == null) {
370 iconUrl = areaUrl.get();
371 }
372 types.add(TagInfoTag.Type.AREA);
373 }
374 return new TagInfoTag(null, tag.getKey(), tag.getValue(), types, iconUrl);
375 })
376 .collect(Collectors.toList());
377 }
378
379 /**
380 * Check if a certain tag is supported by the style as node / way / area.
381 */
382 private abstract class Checker {
383 private final Pattern reservedChars = Pattern.compile("[<>:\"|\\?\\*]");
384
385 Checker(Tag tag) {
386 this.tag = tag;
387 }
388
389 Environment applyStylesheet(OsmPrimitive osm) {
390 osm.put(tag);
391 MultiCascade mc = new MultiCascade();
392
393 Environment env = new Environment(osm, mc, null, styleSource);
394 for (MapCSSRule r : styleSource.rules) {
395 env.clearSelectorMatchingInformation();
396 if (r.matches(env)) {
397 // ignore selector range
398 if (env.layer == null) {
399 env.layer = "default";
400 }
401 r.execute(env);
402 }
403 }
404 env.layer = "default";
405 return env;
406 }
407
408 /**
409 * Create image file from StyleElement.
410 * @param element style element
411 * @param type object type
412 * @param nc navigatable component
413 *
414 * @return the URL
415 */
416 String createImage(StyleElement element, final String type, NavigatableComponent nc) {
417 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
418 Graphics2D g = img.createGraphics();
419 g.setClip(0, 0, 16, 16);
420 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
421 renderer.getSettings(false);
422 element.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
423 final String imageName = type + "_" + normalize(tag.toString()) + ".png";
424 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
425 ImageIO.write(img, "png", out);
426 } catch (IOException e) {
427 throw new UncheckedIOException(e);
428 }
429 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
430 return baseUrl + "/" + imageName;
431 }
432
433 /**
434 * Normalizes tag so that it can used as a filename on all platforms, including Windows.
435 * @param tag OSM tag, that can contain illegal path characters
436 * @return OSM tag with all illegal path characters replaced by underscore ('_')
437 */
438 String normalize(String tag) {
439 Matcher m = reservedChars.matcher(tag);
440 return m.find() ? m.replaceAll("_") : tag;
441 }
442
443 /**
444 * Checks, if tag is supported and find URL for image icon in this case.
445 *
446 * @param generateImage if true, create or find a suitable image icon and return URL,
447 * if false, just check if tag is supported and return true or false
448 * @return URL for image icon if tag is supported
449 */
450 abstract Optional<String> findUrl(boolean generateImage);
451
452 protected Tag tag;
453 protected OsmPrimitive osm;
454 }
455
456 private class NodeChecker extends Checker {
457 NodeChecker(Tag tag) {
458 super(tag);
459 }
460
461 @Override
462 Optional<String> findUrl(boolean generateImage) {
463 this.osm = new Node(LatLon.ZERO);
464 Environment env = applyStylesheet(osm);
465 Cascade c = env.mc.getCascade("default");
466 Object image = c.get("icon-image");
467 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
468 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
469 }
470 return Optional.empty();
471 }
472
473 }
474
475 private class WayChecker extends Checker {
476 WayChecker(Tag tag) {
477 super(tag);
478 }
479
480 @Override
481 Optional<String> findUrl(boolean generateImage) {
482 this.osm = new Way();
483 NavigatableComponent nc = new NavigatableComponent();
484 Node n1 = new Node(nc.getLatLon(2, 8));
485 Node n2 = new Node(nc.getLatLon(14, 8));
486 ((Way) osm).addNode(n1);
487 ((Way) osm).addNode(n2);
488 Environment env = applyStylesheet(osm);
489 LineElement les = LineElement.createLine(env);
490 if (les != null) {
491 if (!generateImage) return Optional.of("");
492 return Optional.of(createImage(les, "way", nc));
493 }
494 return Optional.empty();
495 }
496
497 }
498
499 private class AreaChecker extends Checker {
500 AreaChecker(Tag tag) {
501 super(tag);
502 }
503
504 @Override
505 Optional<String> findUrl(boolean generateImage) {
506 this.osm = new Way();
507 NavigatableComponent nc = new NavigatableComponent();
508 Node n1 = new Node(nc.getLatLon(2, 2));
509 Node n2 = new Node(nc.getLatLon(14, 2));
510 Node n3 = new Node(nc.getLatLon(14, 14));
511 Node n4 = new Node(nc.getLatLon(2, 14));
512 ((Way) osm).addNode(n1);
513 ((Way) osm).addNode(n2);
514 ((Way) osm).addNode(n3);
515 ((Way) osm).addNode(n4);
516 ((Way) osm).addNode(n1);
517 Environment env = applyStylesheet(osm);
518 AreaElement aes = AreaElement.create(env);
519 if (aes != null) {
520 if (!generateImage) return Optional.of("");
521 return Optional.of(createImage(aes, "area", nc));
522 }
523 return Optional.empty();
524 }
525 }
526 }
527
528 /**
529 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
530 */
531 private static class TagInfoTag {
532 final String description;
533 final String key;
534 final String value;
535 final Set<Type> objectTypes;
536 final String iconURL;
537
538 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
539 this.description = description;
540 this.key = key;
541 this.value = value;
542 this.objectTypes = objectTypes;
543 this.iconURL = iconURL;
544 }
545
546 JsonObjectBuilder toJson() {
547 final JsonObjectBuilder object = Json.createObjectBuilder();
548 if (description != null) {
549 object.add("description", description);
550 }
551 object.add("key", key);
552 object.add("value", value);
553 if ((!objectTypes.isEmpty())) {
554 final JsonArrayBuilder types = Json.createArrayBuilder();
555 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
556 object.add("object_types", types);
557 }
558 if (iconURL != null) {
559 object.add("icon_url", iconURL);
560 }
561 return object;
562 }
563
564 enum Type {
565 NODE, WAY, AREA, RELATION
566 }
567 }
568
569 /**
570 * Initialize the script.
571 * @throws IOException if any I/O error occurs
572 */
573 private void init() throws IOException {
574 Logging.setLogLevel(Logging.LEVEL_INFO);
575 Preferences.main().enableSaveOnPut(false);
576 Config.setPreferencesInstance(Preferences.main());
577 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
578 Config.setUrlsProvider(JosmUrls.getInstance());
579 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
580 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
581 tmpdir.toFile().deleteOnExit();
582 System.setProperty("josm.home", tmpdir.toString());
583 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
584 Territories.initialize();
585 RightAndLefthandTraffic.initialize();
586 Files.createDirectories(options.imageDir);
587 }
588}
Note: See TracBrowser for help on using the repository browser.