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

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

fix groovy scripts broken by r9278

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