source: josm/trunk/scripts/taginfoextract.groovy@ 9552

Last change on this file since 9552 was 9289, checked in by Don-vip, 8 years ago

fix taginfo groovy script broken by r9278

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