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

Last change on this file since 11593 was 11324, checked in by Don-vip, 7 years ago

findbugs

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