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

Last change on this file since 8687 was 8687, checked in by Don-vip, 9 years ago

see #11795 - add taginfo target to Ant build

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