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