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

Last change on this file since 13142 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
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
[12751]19import org.openstreetmap.josm.actions.DeleteAction
20import org.openstreetmap.josm.command.DeleteCommand
[7625]21import org.openstreetmap.josm.data.Version
[7544]22import org.openstreetmap.josm.data.coor.LatLon
23import org.openstreetmap.josm.data.osm.Node
[9289]24import org.openstreetmap.josm.data.osm.OsmPrimitive
[7553]25import org.openstreetmap.josm.data.osm.Way
[7625]26import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings
27import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer
[13022]28import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
[7544]29import org.openstreetmap.josm.data.projection.Projections
[7625]30import org.openstreetmap.josm.gui.NavigatableComponent
[7544]31import org.openstreetmap.josm.gui.mappaint.Environment
[8687]32import org.openstreetmap.josm.gui.mappaint.MultiCascade
[8681]33import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference
[8687]34import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource
[10837]35import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition
[7625]36import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector
[7544]37import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser
[9289]38import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement
[9283]39import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement
[9289]40import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement
[8681]41import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference
[8863]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
[7544]47import org.openstreetmap.josm.io.CachedFile
[12852]48import org.openstreetmap.josm.spi.preferences.Config
[11982]49import org.openstreetmap.josm.tools.Logging
[11252]50import org.openstreetmap.josm.tools.RightAndLefthandTraffic
51import org.openstreetmap.josm.tools.Territories
[8274]52import org.openstreetmap.josm.tools.Utils
[7544]53
[11324]54import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
55import groovy.json.JsonBuilder
56
[9880]57class TagInfoExtract {
[7544]58
[7553]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
[9289]65 String base_dir = "."
66 Set tags = []
[7625]67
[7553]68 private def cached_svnrev
[7544]69
[7553]70 /**
71 * Check if a certain tag is supported by the style as node / way / area.
72 */
73 abstract class Checker {
[7625]74
[7553]75 def tag
[9289]76 OsmPrimitive osm
[7625]77
[7553]78 Checker(tag) {
79 this.tag = tag
80 }
[7625]81
[9289]82 Environment apply_stylesheet(OsmPrimitive osm) {
[7553]83 osm.put(tag[0], tag[1])
[9289]84 MultiCascade mc = new MultiCascade()
[7625]85
[9289]86 Environment env = new Environment(osm, mc, null, style_source)
[7553]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 }
[7625]100
[7553]101 /**
[9289]102 * Create image file from StyleElement.
[7553]103 * @return the URL
[7625]104 */
[9289]105 def create_image(StyleElement elem_style, type, nc) {
[7553]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)
[7625]111 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
[7554]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}"
[7553]116 }
[7544]117
[7553]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 }
[7544]125
[11324]126 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]127 class NodeChecker extends Checker {
128 NodeChecker(tag) {
129 super(tag)
130 }
131
[9953]132 @Override
[7553]133 def find_url(boolean generate_image) {
[9214]134 osm = new Node(LatLon.ZERO)
[7553]135 def env = apply_stylesheet(osm)
136 def c = env.mc.getCascade("default")
137 def image = c.get("icon-image")
138 if (image) {
[10927]139 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
140 return find_image_url(image.iconName)
[7553]141 }
142 }
143 }
[7544]144 }
145
[11324]146 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]147 class WayChecker extends Checker {
148 WayChecker(tag) {
149 super(tag)
150 }
151
[9953]152 @Override
[7553]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))
[9289]158 ((Way)osm).addNode(n1)
159 ((Way)osm).addNode(n2)
[7553]160 def env = apply_stylesheet(osm)
[9283]161 def les = LineElement.createLine(env)
[7553]162 if (les != null) {
163 if (!generate_image) return true
164 return create_image(les, 'way', nc)
165 }
166 }
[7544]167 }
[7553]168
[11324]169 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]170 class AreaChecker extends Checker {
171 AreaChecker(tag) {
172 super(tag)
173 }
174
[9953]175 @Override
[7553]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))
[9289]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)
[7553]188 def env = apply_stylesheet(osm)
[9289]189 def aes = AreaElement.create(env)
[7553]190 if (aes != null) {
191 if (!generate_image) return true
192 return create_image(aes, 'area', nc)
193 }
194 }
[7544]195 }
196
[7553]197 /**
198 * Main method.
199 */
200 static main(def args) {
201 parse_command_line_arguments(args)
[9880]202 def script = new TagInfoExtract()
[8274]203 if (!options.t || options.t == 'mappaint') {
204 script.run()
205 } else if (options.t == 'presets') {
206 script.run_presets()
[8681]207 } else if (options.t == 'external_presets') {
208 script.run_external_presets()
[8274]209 } else {
210 System.err.println 'Invalid type ' + options.t
[8687]211 if (!options.noexit) {
212 System.exit(1)
213 }
[8274]214 }
215
[8687]216 if (!options.noexit) {
217 System.exit(0)
218 }
[7553]219 }
[7544]220
[7553]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:",
[7936]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: -)")
[8274]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)")
[7553]231 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
[8687]232 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
[8274]233 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
[7554]234 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
[7553]235 cli.h(longOpt:'help', "show this help")
236 options = cli.parse(args)
[7544]237
[7553]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 }
[7625]259
[8274]260 void run_presets() {
261 init()
[8681]262 def presets = TaggingPresetReader.readAll(input_file, true)
[8690]263 def tags = convert_presets(presets, "", true)
[8681]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) {
[8274]268 def tags = []
269 for (TaggingPreset preset : presets) {
[8863]270 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
[8274]271 def values
[8863]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;
[8274]275 default: values = [];
276 }
277 for (String value : values) {
278 def tag = [
[8681]279 description: descriptionPrefix + preset.name,
[8274]280 key: item.key,
281 value: value,
282 ]
[10769]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]
[8681]288 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
[8274]289 tags += tag
290 }
291 }
292 }
[8681]293 return tags
294 }
[8274]295
[8681]296 void run_external_presets() {
297 init()
[8710]298 TaggingPresetReader.setLoadIcons(false)
[8681]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)
[8274]318 }
319
[7553]320 void run() {
321 init()
322 parse_style_sheet()
323 collect_tags()
[7544]324
[8272]325 def tags = tags.collect {
326 def tag = it
[7553]327 def types = []
328 def final_url = null
329
330 def node_url = new NodeChecker(tag).find_url(true)
331 if (node_url) {
[8272]332 types += 'node'
[7553]333 final_url = node_url
334 }
335 def way_url = new WayChecker(tag).find_url(final_url == null)
336 if (way_url) {
[8272]337 types += 'way'
[7553]338 if (!final_url) {
339 final_url = way_url
[7544]340 }
341 }
[7553]342 def area_url = new AreaChecker(tag).find_url(final_url == null)
343 if (area_url) {
[8272]344 types += 'area'
[7553]345 if (!final_url) {
346 final_url = area_url
347 }
348 }
[7625]349
[8272]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
[7625]354 }
[7553]355
[8274]356 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
[7544]357 }
358
[8274]359 void write_json(name, description, tags) {
[8272]360 def json = new JsonBuilder()
361 def project = [
362 name: name,
363 description: description,
[8274]364 project_url: "https://josm.openstreetmap.de/",
365 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
[8272]366 contact_name: "JOSM developer team",
367 contact_email: "josm-dev@openstreetmap.org",
368 ]
[10769]369 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
[8274]370
371 if (output_file != null) {
372 json.writeTo(output_file)
373 output_file.close()
374 } else {
375 print json.toPrettyString()
376 }
[8272]377 }
378
[7553]379 /**
380 * Initialize the script.
381 */
382 def init() {
[8681]383 Main.determinePlatformHook()
[11982]384 Logging.setLogLevel(Logging.LEVEL_INFO)
[7553]385 Main.pref.enableSaveOnPut(false)
[12852]386 Config.setPreferencesInstance(Main.pref)
[13022]387 Config.setBaseDirectoriesProvider(JosmBaseDirectories.getInstance());
[7553]388 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
[8275]389 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
[8717]390 tmpdir.toFile().deleteOnExit()
[8275]391 System.setProperty("josm.home", tmpdir.toString())
[12760]392 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback)
[11252]393 Territories.initialize()
394 RightAndLefthandTraffic.initialize()
[7544]395
[7553]396 josm_svn_revision = Version.getInstance().getVersion()
397 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
[7544]398
[8274]399 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
[7553]400 input_file = "resource://styles/standard/elemstyles.mapcss"
[8274]401 } else if (options.arguments().size() == 0 && options.t == 'presets') {
402 input_file = "resource://data/defaultpresets.xml"
[7553]403 } else {
404 input_file = options.arguments()[0]
405 }
[7544]406
[7553]407 output_file = null
408 if (options.o && options.o != "-") {
409 output_file = new FileWriter(options.o)
410 }
411 }
[7544]412
[7553]413 /**
[8274]414 * Determine full image url (can refer to JOSM or OSM repository).
[7553]415 */
[9289]416 def find_image_url(String path) {
[8274]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()) {
[8439]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}"
[8671]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}"
[8439]432 } else {
433 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
434 }
[8274]435 }
436 assert false, "Cannot find image url for ${path}"
437 }
438
439 /**
440 * Get revision for the repository https://svn.openstreetmap.org.
441 */
[7553]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) {
[8274]450 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
[7553]451 } else {
452 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
453 }
[7625]454
[7553]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 }
[7625]461
[7553]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 }
[7625]473
[7553]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 }
[7544]487 }
488 }
489 }
490}
Note: See TracBrowser for help on using the repository browser.