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

Last change on this file since 12019 was 11982, checked in by stoecker, 8 years ago

silence TagInfo outputs

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