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

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

see #18140 - reorganization of data(_nodist), images(_nodist), styles(_nodist), IDE and native files in a more practical file tree.

  • Everything belonging to the jar is now in resources (data, images, styles)
  • Everything not belonging to the jar is now in nodist (data, images, styles)
  • Everything related to OS native functions is now in native (linux, macosx, windows)
  • Everything related to an IDE is now in ide (eclipse, netbeans)
File size: 24.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.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/resources/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/resources/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.selectors.stream())
345 .flatMap(selector -> selector.getConditions().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.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 * @param element style element
407 * @param type object type
408 * @param nc navigatable component
409 *
410 * @return the URL
411 */
412 String createImage(StyleElement element, final String type, NavigatableComponent nc) {
413 BufferedImage img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
414 Graphics2D g = img.createGraphics();
415 g.setClip(0, 0, 16, 16);
416 StyledMapRenderer renderer = new StyledMapRenderer(g, nc, false);
417 renderer.getSettings(false);
418 element.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false);
419 final String imageName = type + "_" + tag + ".png";
420 try (OutputStream out = Files.newOutputStream(options.imageDir.resolve(imageName))) {
421 ImageIO.write(img, "png", out);
422 } catch (IOException e) {
423 throw new UncheckedIOException(e);
424 }
425 final String baseUrl = options.imageUrlPrefix != null ? options.imageUrlPrefix : options.imageDir.toString();
426 return baseUrl + "/" + imageName;
427 }
428
429 /**
430 * Checks, if tag is supported and find URL for image icon in this case.
431 *
432 * @param generateImage if true, create or find a suitable image icon and return URL,
433 * if false, just check if tag is supported and return true or false
434 * @return URL for image icon if tag is supported
435 */
436 abstract Optional<String> findUrl(boolean generateImage);
437
438 protected Tag tag;
439 protected OsmPrimitive osm;
440 }
441
442 private class NodeChecker extends Checker {
443 NodeChecker(Tag tag) {
444 super(tag);
445 }
446
447 @Override
448 Optional<String> findUrl(boolean generateImage) {
449 this.osm = new Node(LatLon.ZERO);
450 Environment env = applyStylesheet(osm);
451 Cascade c = env.mc.getCascade("default");
452 Object image = c.get("icon-image");
453 if (image instanceof MapPaintStyles.IconReference && !((MapPaintStyles.IconReference) image).isDeprecatedIcon()) {
454 return Optional.of(options.findImageUrl(((MapPaintStyles.IconReference) image).iconName));
455 }
456 return Optional.empty();
457 }
458
459 }
460
461 private class WayChecker extends Checker {
462 WayChecker(Tag tag) {
463 super(tag);
464 }
465
466 @Override
467 Optional<String> findUrl(boolean generateImage) {
468 this.osm = new Way();
469 NavigatableComponent nc = new NavigatableComponent();
470 Node n1 = new Node(nc.getLatLon(2, 8));
471 Node n2 = new Node(nc.getLatLon(14, 8));
472 ((Way) osm).addNode(n1);
473 ((Way) osm).addNode(n2);
474 Environment env = applyStylesheet(osm);
475 LineElement les = LineElement.createLine(env);
476 if (les != null) {
477 if (!generateImage) return Optional.of("");
478 return Optional.of(createImage(les, "way", nc));
479 }
480 return Optional.empty();
481 }
482
483 }
484
485 private class AreaChecker extends Checker {
486 AreaChecker(Tag tag) {
487 super(tag);
488 }
489
490 @Override
491 Optional<String> findUrl(boolean generateImage) {
492 this.osm = new Way();
493 NavigatableComponent nc = new NavigatableComponent();
494 Node n1 = new Node(nc.getLatLon(2, 2));
495 Node n2 = new Node(nc.getLatLon(14, 2));
496 Node n3 = new Node(nc.getLatLon(14, 14));
497 Node n4 = new Node(nc.getLatLon(2, 14));
498 ((Way) osm).addNode(n1);
499 ((Way) osm).addNode(n2);
500 ((Way) osm).addNode(n3);
501 ((Way) osm).addNode(n4);
502 ((Way) osm).addNode(n1);
503 Environment env = applyStylesheet(osm);
504 AreaElement aes = AreaElement.create(env);
505 if (aes != null) {
506 if (!generateImage) return Optional.of("");
507 return Optional.of(createImage(aes, "area", nc));
508 }
509 return Optional.empty();
510 }
511 }
512 }
513
514 /**
515 * POJO representing a <a href="https://wiki.openstreetmap.org/wiki/Taginfo/Projects">Taginfo tag</a>.
516 */
517 private static class TagInfoTag {
518 final String description;
519 final String key;
520 final String value;
521 final Set<Type> objectTypes;
522 final String iconURL;
523
524 TagInfoTag(String description, String key, String value, Set<Type> objectTypes, String iconURL) {
525 this.description = description;
526 this.key = key;
527 this.value = value;
528 this.objectTypes = objectTypes;
529 this.iconURL = iconURL;
530 }
531
532 JsonObjectBuilder toJson() {
533 final JsonObjectBuilder object = Json.createObjectBuilder();
534 if (description != null) {
535 object.add("description", description);
536 }
537 object.add("key", key);
538 object.add("value", value);
539 if ((!objectTypes.isEmpty())) {
540 final JsonArrayBuilder types = Json.createArrayBuilder();
541 objectTypes.stream().map(Enum::name).map(String::toLowerCase).forEach(types::add);
542 object.add("object_types", types);
543 }
544 if (iconURL != null) {
545 object.add("icon_url", iconURL);
546 }
547 return object;
548 }
549
550 enum Type {
551 NODE, WAY, AREA, RELATION
552 }
553 }
554
555 /**
556 * Initialize the script.
557 * @throws IOException if any I/O error occurs
558 */
559 private void init() throws IOException {
560 Logging.setLogLevel(Logging.LEVEL_INFO);
561 Preferences.main().enableSaveOnPut(false);
562 Config.setPreferencesInstance(Preferences.main());
563 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
564 Config.setUrlsProvider(JosmUrls.getInstance());
565 ProjectionRegistry.setProjection(Projections.getProjectionByCode("EPSG:3857"));
566 Path tmpdir = Files.createTempDirectory(options.baseDir, "pref");
567 tmpdir.toFile().deleteOnExit();
568 System.setProperty("josm.home", tmpdir.toString());
569 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
570 Territories.initialize();
571 RightAndLefthandTraffic.initialize();
572 Files.createDirectories(options.imageDir);
573 }
574}
Note: See TracBrowser for help on using the repository browser.