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

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

fix #17170 - Migrate TagInfoExtract.groovy to Java

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