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