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

Last change on this file since 12227 was 11982, checked in by stoecker, 7 years ago

silence TagInfo outputs

  • Property svn:eol-style set to native
File size: 18.1 KB
RevLine 
[7544]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 *
[8306]7 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t mappaint
8 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t presets
[8681]9 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t external_presets
[7544]10 */
[8687]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
[7544]18import org.openstreetmap.josm.Main
[7625]19import org.openstreetmap.josm.data.Version
[7544]20import org.openstreetmap.josm.data.coor.LatLon
21import org.openstreetmap.josm.data.osm.Node
[9289]22import org.openstreetmap.josm.data.osm.OsmPrimitive
[7553]23import org.openstreetmap.josm.data.osm.Way
[7625]24import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings
25import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer
[7544]26import org.openstreetmap.josm.data.projection.Projections
[7625]27import org.openstreetmap.josm.gui.NavigatableComponent
[7544]28import org.openstreetmap.josm.gui.mappaint.Environment
[8687]29import org.openstreetmap.josm.gui.mappaint.MultiCascade
[8681]30import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference
[8687]31import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource
[10837]32import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition
[7625]33import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector
[7544]34import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser
[9289]35import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement
[9283]36import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement
[9289]37import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement
[8681]38import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference
[8863]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
[7544]44import org.openstreetmap.josm.io.CachedFile
[11982]45import org.openstreetmap.josm.tools.Logging
[11252]46import org.openstreetmap.josm.tools.RightAndLefthandTraffic
47import org.openstreetmap.josm.tools.Territories
[8274]48import org.openstreetmap.josm.tools.Utils
[7544]49
[11324]50import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
51import groovy.json.JsonBuilder
52
[9880]53class TagInfoExtract {
[7544]54
[7553]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
[9289]61 String base_dir = "."
62 Set tags = []
[7625]63
[7553]64 private def cached_svnrev
[7544]65
[7553]66 /**
67 * Check if a certain tag is supported by the style as node / way / area.
68 */
69 abstract class Checker {
[7625]70
[7553]71 def tag
[9289]72 OsmPrimitive osm
[7625]73
[7553]74 Checker(tag) {
75 this.tag = tag
76 }
[7625]77
[9289]78 Environment apply_stylesheet(OsmPrimitive osm) {
[7553]79 osm.put(tag[0], tag[1])
[9289]80 MultiCascade mc = new MultiCascade()
[7625]81
[9289]82 Environment env = new Environment(osm, mc, null, style_source)
[7553]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 }
[7625]96
[7553]97 /**
[9289]98 * Create image file from StyleElement.
[7553]99 * @return the URL
[7625]100 */
[9289]101 def create_image(StyleElement elem_style, type, nc) {
[7553]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)
[7625]107 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
[7554]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}"
[7553]112 }
[7544]113
[7553]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 }
[7544]121
[11324]122 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]123 class NodeChecker extends Checker {
124 NodeChecker(tag) {
125 super(tag)
126 }
127
[9953]128 @Override
[7553]129 def find_url(boolean generate_image) {
[9214]130 osm = new Node(LatLon.ZERO)
[7553]131 def env = apply_stylesheet(osm)
132 def c = env.mc.getCascade("default")
133 def image = c.get("icon-image")
134 if (image) {
[10927]135 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
136 return find_image_url(image.iconName)
[7553]137 }
138 }
139 }
[7544]140 }
141
[11324]142 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]143 class WayChecker extends Checker {
144 WayChecker(tag) {
145 super(tag)
146 }
147
[9953]148 @Override
[7553]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))
[9289]154 ((Way)osm).addNode(n1)
155 ((Way)osm).addNode(n2)
[7553]156 def env = apply_stylesheet(osm)
[9283]157 def les = LineElement.createLine(env)
[7553]158 if (les != null) {
159 if (!generate_image) return true
160 return create_image(les, 'way', nc)
161 }
162 }
[7544]163 }
[7553]164
[11324]165 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]166 class AreaChecker extends Checker {
167 AreaChecker(tag) {
168 super(tag)
169 }
170
[9953]171 @Override
[7553]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))
[9289]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)
[7553]184 def env = apply_stylesheet(osm)
[9289]185 def aes = AreaElement.create(env)
[7553]186 if (aes != null) {
187 if (!generate_image) return true
188 return create_image(aes, 'area', nc)
189 }
190 }
[7544]191 }
192
[7553]193 /**
194 * Main method.
195 */
196 static main(def args) {
197 parse_command_line_arguments(args)
[9880]198 def script = new TagInfoExtract()
[8274]199 if (!options.t || options.t == 'mappaint') {
200 script.run()
201 } else if (options.t == 'presets') {
202 script.run_presets()
[8681]203 } else if (options.t == 'external_presets') {
204 script.run_external_presets()
[8274]205 } else {
206 System.err.println 'Invalid type ' + options.t
[8687]207 if (!options.noexit) {
208 System.exit(1)
209 }
[8274]210 }
211
[8687]212 if (!options.noexit) {
213 System.exit(0)
214 }
[7553]215 }
[7544]216
[7553]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:",
[7936]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: -)")
[8274]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)")
[7553]227 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
[8687]228 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
[8274]229 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
[7554]230 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
[7553]231 cli.h(longOpt:'help', "show this help")
232 options = cli.parse(args)
[7544]233
[7553]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 }
[7625]255
[8274]256 void run_presets() {
257 init()
[8681]258 def presets = TaggingPresetReader.readAll(input_file, true)
[8690]259 def tags = convert_presets(presets, "", true)
[8681]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) {
[8274]264 def tags = []
265 for (TaggingPreset preset : presets) {
[8863]266 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
[8274]267 def values
[8863]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;
[8274]271 default: values = [];
272 }
273 for (String value : values) {
274 def tag = [
[8681]275 description: descriptionPrefix + preset.name,
[8274]276 key: item.key,
277 value: value,
278 ]
[10769]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]
[8681]284 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
[8274]285 tags += tag
286 }
287 }
288 }
[8681]289 return tags
290 }
[8274]291
[8681]292 void run_external_presets() {
293 init()
[8710]294 TaggingPresetReader.setLoadIcons(false)
[8681]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)
[8274]314 }
315
[7553]316 void run() {
317 init()
318 parse_style_sheet()
319 collect_tags()
[7544]320
[8272]321 def tags = tags.collect {
322 def tag = it
[7553]323 def types = []
324 def final_url = null
325
326 def node_url = new NodeChecker(tag).find_url(true)
327 if (node_url) {
[8272]328 types += 'node'
[7553]329 final_url = node_url
330 }
331 def way_url = new WayChecker(tag).find_url(final_url == null)
332 if (way_url) {
[8272]333 types += 'way'
[7553]334 if (!final_url) {
335 final_url = way_url
[7544]336 }
337 }
[7553]338 def area_url = new AreaChecker(tag).find_url(final_url == null)
339 if (area_url) {
[8272]340 types += 'area'
[7553]341 if (!final_url) {
342 final_url = area_url
343 }
344 }
[7625]345
[8272]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
[7625]350 }
[7553]351
[8274]352 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
[7544]353 }
354
[8274]355 void write_json(name, description, tags) {
[8272]356 def json = new JsonBuilder()
357 def project = [
358 name: name,
359 description: description,
[8274]360 project_url: "https://josm.openstreetmap.de/",
361 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
[8272]362 contact_name: "JOSM developer team",
363 contact_email: "josm-dev@openstreetmap.org",
364 ]
[10769]365 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
[8274]366
367 if (output_file != null) {
368 json.writeTo(output_file)
369 output_file.close()
370 } else {
371 print json.toPrettyString()
372 }
[8272]373 }
374
[7553]375 /**
376 * Initialize the script.
377 */
378 def init() {
[8681]379 Main.determinePlatformHook()
[11982]380 Logging.setLogLevel(Logging.LEVEL_INFO)
[7553]381 Main.pref.enableSaveOnPut(false)
382 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
[8275]383 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
[8717]384 tmpdir.toFile().deleteOnExit()
[8275]385 System.setProperty("josm.home", tmpdir.toString())
[11252]386 Territories.initialize()
387 RightAndLefthandTraffic.initialize()
[7544]388
[7553]389 josm_svn_revision = Version.getInstance().getVersion()
390 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
[7544]391
[8274]392 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
[7553]393 input_file = "resource://styles/standard/elemstyles.mapcss"
[8274]394 } else if (options.arguments().size() == 0 && options.t == 'presets') {
395 input_file = "resource://data/defaultpresets.xml"
[7553]396 } else {
397 input_file = options.arguments()[0]
398 }
[7544]399
[7553]400 output_file = null
401 if (options.o && options.o != "-") {
402 output_file = new FileWriter(options.o)
403 }
404 }
[7544]405
[7553]406 /**
[8274]407 * Determine full image url (can refer to JOSM or OSM repository).
[7553]408 */
[9289]409 def find_image_url(String path) {
[8274]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()) {
[8439]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}"
[8671]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}"
[8439]425 } else {
426 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
427 }
[8274]428 }
429 assert false, "Cannot find image url for ${path}"
430 }
431
432 /**
433 * Get revision for the repository https://svn.openstreetmap.org.
434 */
[7553]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) {
[8274]443 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
[7553]444 } else {
445 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
446 }
[7625]447
[7553]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 }
[7625]454
[7553]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 }
[7625]466
[7553]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 }
[7544]480 }
481 }
482 }
483}
Note: See TracBrowser for help on using the repository browser.