source: josm/trunk/scripts/TagInfoExtract.groovy@ 13589

Last change on this file since 13589 was 13022, checked in by bastiK, 7 years ago

see #15451 - fix taginfo script

  • Property svn:eol-style set to native
File size: 18.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2/**
3 * Extracts tag information for the taginfo project.
4 *
5 * Run from the base directory of a JOSM checkout:
6 *
7 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t mappaint
8 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t presets
9 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t external_presets
10 */
11import java.awt.image.BufferedImage
12import java.nio.file.FileSystems
13import java.nio.file.Files
14import java.nio.file.Path
15
16import javax.imageio.ImageIO
17
18import org.openstreetmap.josm.Main
19import org.openstreetmap.josm.actions.DeleteAction
20import org.openstreetmap.josm.command.DeleteCommand
21import org.openstreetmap.josm.data.Version
22import org.openstreetmap.josm.data.coor.LatLon
23import org.openstreetmap.josm.data.osm.Node
24import org.openstreetmap.josm.data.osm.OsmPrimitive
25import org.openstreetmap.josm.data.osm.Way
26import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings
27import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer
28import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
29import org.openstreetmap.josm.data.projection.Projections
30import org.openstreetmap.josm.gui.NavigatableComponent
31import org.openstreetmap.josm.gui.mappaint.Environment
32import org.openstreetmap.josm.gui.mappaint.MultiCascade
33import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference
34import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource
35import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition
36import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector
37import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser
38import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement
39import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement
40import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement
41import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference
42import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset
43import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetReader
44import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType
45import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem
46import org.openstreetmap.josm.gui.tagging.presets.items.KeyedItem.MatchType
47import org.openstreetmap.josm.io.CachedFile
48import org.openstreetmap.josm.spi.preferences.Config
49import org.openstreetmap.josm.tools.Logging
50import org.openstreetmap.josm.tools.RightAndLefthandTraffic
51import org.openstreetmap.josm.tools.Territories
52import org.openstreetmap.josm.tools.Utils
53
54import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
55import groovy.json.JsonBuilder
56
57class TagInfoExtract {
58
59 static def options
60 static String image_dir
61 int josm_svn_revision
62 String input_file
63 MapCSSStyleSource style_source
64 FileWriter output_file
65 String base_dir = "."
66 Set tags = []
67
68 private def cached_svnrev
69
70 /**
71 * Check if a certain tag is supported by the style as node / way / area.
72 */
73 abstract class Checker {
74
75 def tag
76 OsmPrimitive osm
77
78 Checker(tag) {
79 this.tag = tag
80 }
81
82 Environment apply_stylesheet(OsmPrimitive osm) {
83 osm.put(tag[0], tag[1])
84 MultiCascade mc = new MultiCascade()
85
86 Environment env = new Environment(osm, mc, null, style_source)
87 for (def r in style_source.rules) {
88 env.clearSelectorMatchingInformation()
89 if (r.selector.matches(env)) {
90 // ignore selector range
91 if (env.layer == null) {
92 env.layer = "default"
93 }
94 r.execute(env)
95 }
96 }
97 env.layer = "default"
98 return env
99 }
100
101 /**
102 * Create image file from StyleElement.
103 * @return the URL
104 */
105 def create_image(StyleElement elem_style, type, nc) {
106 def img = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)
107 def g = img.createGraphics()
108 g.setClip(0, 0, 16, 16)
109 def renderer = new StyledMapRenderer(g, nc, false)
110 renderer.getSettings(false)
111 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
112 def base_url = options.imgurlprefix ? options.imgurlprefix : image_dir
113 def image_name = "${type}_${tag[0]}=${tag[1]}.png"
114 ImageIO.write(img, "png", new File("${image_dir}/${image_name}"))
115 return "${base_url}/${image_name}"
116 }
117
118 /**
119 * Checks, if tag is supported and find URL for image icon in this case.
120 * @param generate_image if true, create or find a suitable image icon and return URL,
121 * if false, just check if tag is supported and return true or false
122 */
123 abstract def find_url(boolean generate_image)
124 }
125
126 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
127 class NodeChecker extends Checker {
128 NodeChecker(tag) {
129 super(tag)
130 }
131
132 @Override
133 def find_url(boolean generate_image) {
134 osm = new Node(LatLon.ZERO)
135 def env = apply_stylesheet(osm)
136 def c = env.mc.getCascade("default")
137 def image = c.get("icon-image")
138 if (image) {
139 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
140 return find_image_url(image.iconName)
141 }
142 }
143 }
144 }
145
146 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
147 class WayChecker extends Checker {
148 WayChecker(tag) {
149 super(tag)
150 }
151
152 @Override
153 def find_url(boolean generate_image) {
154 osm = new Way()
155 def nc = new NavigatableComponent()
156 def n1 = new Node(nc.getLatLon(2,8))
157 def n2 = new Node(nc.getLatLon(14,8))
158 ((Way)osm).addNode(n1)
159 ((Way)osm).addNode(n2)
160 def env = apply_stylesheet(osm)
161 def les = LineElement.createLine(env)
162 if (les != null) {
163 if (!generate_image) return true
164 return create_image(les, 'way', nc)
165 }
166 }
167 }
168
169 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
170 class AreaChecker extends Checker {
171 AreaChecker(tag) {
172 super(tag)
173 }
174
175 @Override
176 def find_url(boolean generate_image) {
177 osm = new Way()
178 def nc = new NavigatableComponent()
179 def n1 = new Node(nc.getLatLon(2,2))
180 def n2 = new Node(nc.getLatLon(14,2))
181 def n3 = new Node(nc.getLatLon(14,14))
182 def n4 = new Node(nc.getLatLon(2,14))
183 ((Way)osm).addNode(n1)
184 ((Way)osm).addNode(n2)
185 ((Way)osm).addNode(n3)
186 ((Way)osm).addNode(n4)
187 ((Way)osm).addNode(n1)
188 def env = apply_stylesheet(osm)
189 def aes = AreaElement.create(env)
190 if (aes != null) {
191 if (!generate_image) return true
192 return create_image(aes, 'area', nc)
193 }
194 }
195 }
196
197 /**
198 * Main method.
199 */
200 static main(def args) {
201 parse_command_line_arguments(args)
202 def script = new TagInfoExtract()
203 if (!options.t || options.t == 'mappaint') {
204 script.run()
205 } else if (options.t == 'presets') {
206 script.run_presets()
207 } else if (options.t == 'external_presets') {
208 script.run_external_presets()
209 } else {
210 System.err.println 'Invalid type ' + options.t
211 if (!options.noexit) {
212 System.exit(1)
213 }
214 }
215
216 if (!options.noexit) {
217 System.exit(0)
218 }
219 }
220
221 /**
222 * Parse command line arguments.
223 */
224 static void parse_command_line_arguments(args) {
225 def cli = new CliBuilder(usage:'taginfoextract.groovy [options] [inputfile]',
226 header:"Options:",
227 footer:"[inputfile] the file to process (optional, default is 'resource://styles/standard/elemstyles.mapcss')")
228 cli.o(args:1, argName: "file", "output file (json), - prints to stdout (default: -)")
229 cli.t(args:1, argName: "type", "the project type to be generated")
230 cli._(longOpt:'svnrev', args:1, argName:"revision", "corresponding revision of the repository https://svn.openstreetmap.org/ (optional, current revision is read from the local checkout or from the web if not given, see --svnweb)")
231 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
232 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
233 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
234 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
235 cli.h(longOpt:'help', "show this help")
236 options = cli.parse(args)
237
238 if (options.h) {
239 cli.usage()
240 System.exit(0)
241 }
242 if (options.arguments().size() > 1) {
243 System.err.println "Error: More than one input file given!"
244 cli.usage()
245 System.exit(-1)
246 }
247 if (options.svnrev) {
248 assert Integer.parseInt(options.svnrev) > 0
249 }
250 image_dir = 'taginfo-img'
251 if (options.imgdir) {
252 image_dir = options.imgdir
253 }
254 def image_dir_file = new File(image_dir)
255 if (!image_dir_file.exists()) {
256 image_dir_file.mkdirs()
257 }
258 }
259
260 void run_presets() {
261 init()
262 def presets = TaggingPresetReader.readAll(input_file, true)
263 def tags = convert_presets(presets, "", true)
264 write_json("JOSM main presets", "Tags supported by the default presets in the OSM editor JOSM", tags)
265 }
266
267 def convert_presets(Iterable<TaggingPreset> presets, String descriptionPrefix, boolean addImages) {
268 def tags = []
269 for (TaggingPreset preset : presets) {
270 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
271 def values
272 switch (MatchType.ofString(item.match)) {
273 case MatchType.KEY_REQUIRED: values = item.getValues(); break;
274 case MatchType.KEY_VALUE_REQUIRED: values = item.getValues(); break;
275 default: values = [];
276 }
277 for (String value : values) {
278 def tag = [
279 description: descriptionPrefix + preset.name,
280 key: item.key,
281 value: value,
282 ]
283 def otypes = preset.types.collect {
284 it == TaggingPresetType.CLOSEDWAY ? "area" :
285 (it == TaggingPresetType.MULTIPOLYGON ? "relation" : it.toString().toLowerCase(Locale.ENGLISH))
286 }
287 if (!otypes.isEmpty()) tag += [object_types: otypes]
288 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
289 tags += tag
290 }
291 }
292 }
293 return tags
294 }
295
296 void run_external_presets() {
297 init()
298 TaggingPresetReader.setLoadIcons(false)
299 def sources = new TaggingPresetPreference.TaggingPresetSourceEditor().loadAndGetAvailableSources()
300 def tags = []
301 for (def source : sources) {
302 if (source.url.startsWith("resource")) {
303 // default presets
304 continue;
305 }
306 try {
307 println "Loading ${source.url}"
308 def presets = TaggingPresetReader.readAll(source.url, false)
309 def t = convert_presets(presets, source.title + " ", false)
310 println "Converting ${t.size()} presets of ${source.title}"
311 tags += t
312 } catch (Exception ex) {
313 System.err.println("Skipping ${source.url} due to error")
314 ex.printStackTrace()
315 }
316 }
317 write_json("JOSM user presets", "Tags supported by the user contributed presets in the OSM editor JOSM", tags)
318 }
319
320 void run() {
321 init()
322 parse_style_sheet()
323 collect_tags()
324
325 def tags = tags.collect {
326 def tag = it
327 def types = []
328 def final_url = null
329
330 def node_url = new NodeChecker(tag).find_url(true)
331 if (node_url) {
332 types += 'node'
333 final_url = node_url
334 }
335 def way_url = new WayChecker(tag).find_url(final_url == null)
336 if (way_url) {
337 types += 'way'
338 if (!final_url) {
339 final_url = way_url
340 }
341 }
342 def area_url = new AreaChecker(tag).find_url(final_url == null)
343 if (area_url) {
344 types += 'area'
345 if (!final_url) {
346 final_url = area_url
347 }
348 }
349
350 def obj = [key: tag[0], value: tag[1]]
351 if (types) obj += [object_types: types]
352 if (final_url) obj += [icon_url: final_url]
353 obj
354 }
355
356 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
357 }
358
359 void write_json(name, description, tags) {
360 def json = new JsonBuilder()
361 def project = [
362 name: name,
363 description: description,
364 project_url: "https://josm.openstreetmap.de/",
365 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
366 contact_name: "JOSM developer team",
367 contact_email: "josm-dev@openstreetmap.org",
368 ]
369 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
370
371 if (output_file != null) {
372 json.writeTo(output_file)
373 output_file.close()
374 } else {
375 print json.toPrettyString()
376 }
377 }
378
379 /**
380 * Initialize the script.
381 */
382 def init() {
383 Main.determinePlatformHook()
384 Logging.setLogLevel(Logging.LEVEL_INFO)
385 Main.pref.enableSaveOnPut(false)
386 Config.setPreferencesInstance(Main.pref)
387 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
388 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
389 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
390 tmpdir.toFile().deleteOnExit()
391 System.setProperty("josm.home", tmpdir.toString())
392 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback)
393 Territories.initialize()
394 RightAndLefthandTraffic.initialize()
395
396 josm_svn_revision = Version.getInstance().getVersion()
397 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
398
399 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
400 input_file = "resource://styles/standard/elemstyles.mapcss"
401 } else if (options.arguments().size() == 0 && options.t == 'presets') {
402 input_file = "resource://data/defaultpresets.xml"
403 } else {
404 input_file = options.arguments()[0]
405 }
406
407 output_file = null
408 if (options.o && options.o != "-") {
409 output_file = new FileWriter(options.o)
410 }
411 }
412
413 /**
414 * Determine full image url (can refer to JOSM or OSM repository).
415 */
416 def find_image_url(String path) {
417 def f = new File("${base_dir}/images/styles/standard/${path}")
418 if (f.exists()) {
419 def rev = osm_svn_revision()
420 return "https://trac.openstreetmap.org/export/${rev}/subversion/applications/share/map-icons/classic.small/${path}"
421 }
422 f = new File("${base_dir}/images/${path}")
423 if (f.exists()) {
424 if (path.startsWith("images/styles/standard/")) {
425 path = path.substring("images/styles/standard/".length())
426 def rev = osm_svn_revision()
427 return "https://trac.openstreetmap.org/export/${rev}/subversion/applications/share/map-icons/classic.small/${path}"
428 } else if (path.startsWith("styles/standard/")) {
429 path = path.substring("styles/standard/".length())
430 def rev = osm_svn_revision()
431 return "https://trac.openstreetmap.org/export/${rev}/subversion/applications/share/map-icons/classic.small/${path}"
432 } else {
433 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
434 }
435 }
436 assert false, "Cannot find image url for ${path}"
437 }
438
439 /**
440 * Get revision for the repository https://svn.openstreetmap.org.
441 */
442 def osm_svn_revision() {
443 if (cached_svnrev != null) return cached_svnrev
444 if (options.svnrev) {
445 cached_svnrev = Integer.parseInt(options.svnrev)
446 return cached_svnrev
447 }
448 def xml
449 if (options.svnweb) {
450 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
451 } else {
452 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
453 }
454
455 def svninfo = new XmlParser().parseText(xml)
456 def rev = svninfo.entry.'@revision'[0]
457 cached_svnrev = Integer.parseInt(rev)
458 assert cached_svnrev > 0
459 return cached_svnrev
460 }
461
462 /**
463 * Read the style sheet file and parse the MapCSS code.
464 */
465 def parse_style_sheet() {
466 def file = new CachedFile(input_file)
467 def stream = file.getInputStream()
468 def parser = new MapCSSParser(stream, "UTF-8", MapCSSParser.LexicalState.DEFAULT)
469 style_source = new MapCSSStyleSource("")
470 style_source.url = ""
471 parser.sheet(style_source)
472 }
473
474 /**
475 * Collect all the tag from the style sheet.
476 */
477 def collect_tags() {
478 for (rule in style_source.rules) {
479 def selector = rule.selector
480 if (selector instanceof GeneralSelector) {
481 def conditions = selector.getConditions()
482 for (cond in conditions) {
483 if (cond instanceof SimpleKeyValueCondition) {
484 tags.add([cond.k, cond.v])
485 }
486 }
487 }
488 }
489 }
490}
Note: See TracBrowser for help on using the repository browser.