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