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

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

findbugs

  • Property svn:eol-style set to native
File size: 18.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 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
18import org.openstreetmap.josm.Main
19import org.openstreetmap.josm.data.Version
20import org.openstreetmap.josm.data.coor.LatLon
21import org.openstreetmap.josm.data.osm.Node
22import org.openstreetmap.josm.data.osm.OsmPrimitive
23import org.openstreetmap.josm.data.osm.Way
24import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings
25import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer
26import org.openstreetmap.josm.data.projection.Projections
27import org.openstreetmap.josm.gui.NavigatableComponent
28import org.openstreetmap.josm.gui.mappaint.Environment
29import org.openstreetmap.josm.gui.mappaint.MultiCascade
30import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference
31import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource
32import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition
33import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector
34import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser
35import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement
36import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement
37import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement
38import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference
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
44import org.openstreetmap.josm.io.CachedFile
45import org.openstreetmap.josm.tools.RightAndLefthandTraffic
46import org.openstreetmap.josm.tools.Territories
47import org.openstreetmap.josm.tools.Utils
48
49import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
50import groovy.json.JsonBuilder
51
52class TagInfoExtract {
53
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
60 String base_dir = "."
61 Set tags = []
62
63 private def cached_svnrev
64
65 /**
66 * Check if a certain tag is supported by the style as node / way / area.
67 */
68 abstract class Checker {
69
70 def tag
71 OsmPrimitive osm
72
73 Checker(tag) {
74 this.tag = tag
75 }
76
77 Environment apply_stylesheet(OsmPrimitive osm) {
78 osm.put(tag[0], tag[1])
79 MultiCascade mc = new MultiCascade()
80
81 Environment env = new Environment(osm, mc, null, style_source)
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 }
95
96 /**
97 * Create image file from StyleElement.
98 * @return the URL
99 */
100 def create_image(StyleElement elem_style, type, nc) {
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)
106 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
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}"
111 }
112
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 }
120
121 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
122 class NodeChecker extends Checker {
123 NodeChecker(tag) {
124 super(tag)
125 }
126
127 @Override
128 def find_url(boolean generate_image) {
129 osm = new Node(LatLon.ZERO)
130 def env = apply_stylesheet(osm)
131 def c = env.mc.getCascade("default")
132 def image = c.get("icon-image")
133 if (image) {
134 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
135 return find_image_url(image.iconName)
136 }
137 }
138 }
139 }
140
141 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
142 class WayChecker extends Checker {
143 WayChecker(tag) {
144 super(tag)
145 }
146
147 @Override
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))
153 ((Way)osm).addNode(n1)
154 ((Way)osm).addNode(n2)
155 def env = apply_stylesheet(osm)
156 def les = LineElement.createLine(env)
157 if (les != null) {
158 if (!generate_image) return true
159 return create_image(les, 'way', nc)
160 }
161 }
162 }
163
164 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
165 class AreaChecker extends Checker {
166 AreaChecker(tag) {
167 super(tag)
168 }
169
170 @Override
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))
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)
183 def env = apply_stylesheet(osm)
184 def aes = AreaElement.create(env)
185 if (aes != null) {
186 if (!generate_image) return true
187 return create_image(aes, 'area', nc)
188 }
189 }
190 }
191
192 /**
193 * Main method.
194 */
195 static main(def args) {
196 parse_command_line_arguments(args)
197 def script = new TagInfoExtract()
198 if (!options.t || options.t == 'mappaint') {
199 script.run()
200 } else if (options.t == 'presets') {
201 script.run_presets()
202 } else if (options.t == 'external_presets') {
203 script.run_external_presets()
204 } else {
205 System.err.println 'Invalid type ' + options.t
206 if (!options.noexit) {
207 System.exit(1)
208 }
209 }
210
211 if (!options.noexit) {
212 System.exit(0)
213 }
214 }
215
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:",
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: -)")
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)")
226 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
227 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
228 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
229 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
230 cli.h(longOpt:'help', "show this help")
231 options = cli.parse(args)
232
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 }
254
255 void run_presets() {
256 init()
257 def presets = TaggingPresetReader.readAll(input_file, true)
258 def tags = convert_presets(presets, "", true)
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) {
263 def tags = []
264 for (TaggingPreset preset : presets) {
265 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
266 def values
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;
270 default: values = [];
271 }
272 for (String value : values) {
273 def tag = [
274 description: descriptionPrefix + preset.name,
275 key: item.key,
276 value: value,
277 ]
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]
283 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
284 tags += tag
285 }
286 }
287 }
288 return tags
289 }
290
291 void run_external_presets() {
292 init()
293 TaggingPresetReader.setLoadIcons(false)
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)
313 }
314
315 void run() {
316 init()
317 parse_style_sheet()
318 collect_tags()
319
320 def tags = tags.collect {
321 def tag = it
322 def types = []
323 def final_url = null
324
325 def node_url = new NodeChecker(tag).find_url(true)
326 if (node_url) {
327 types += 'node'
328 final_url = node_url
329 }
330 def way_url = new WayChecker(tag).find_url(final_url == null)
331 if (way_url) {
332 types += 'way'
333 if (!final_url) {
334 final_url = way_url
335 }
336 }
337 def area_url = new AreaChecker(tag).find_url(final_url == null)
338 if (area_url) {
339 types += 'area'
340 if (!final_url) {
341 final_url = area_url
342 }
343 }
344
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
349 }
350
351 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
352 }
353
354 void write_json(name, description, tags) {
355 def json = new JsonBuilder()
356 def project = [
357 name: name,
358 description: description,
359 project_url: "https://josm.openstreetmap.de/",
360 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
361 contact_name: "JOSM developer team",
362 contact_email: "josm-dev@openstreetmap.org",
363 ]
364 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
365
366 if (output_file != null) {
367 json.writeTo(output_file)
368 output_file.close()
369 } else {
370 print json.toPrettyString()
371 }
372 }
373
374 /**
375 * Initialize the script.
376 */
377 def init() {
378 Main.determinePlatformHook()
379 Main.pref.enableSaveOnPut(false)
380 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
381 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
382 tmpdir.toFile().deleteOnExit()
383 System.setProperty("josm.home", tmpdir.toString())
384 Territories.initialize()
385 RightAndLefthandTraffic.initialize()
386
387 josm_svn_revision = Version.getInstance().getVersion()
388 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
389
390 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
391 input_file = "resource://styles/standard/elemstyles.mapcss"
392 } else if (options.arguments().size() == 0 && options.t == 'presets') {
393 input_file = "resource://data/defaultpresets.xml"
394 } else {
395 input_file = options.arguments()[0]
396 }
397
398 output_file = null
399 if (options.o && options.o != "-") {
400 output_file = new FileWriter(options.o)
401 }
402 }
403
404 /**
405 * Determine full image url (can refer to JOSM or OSM repository).
406 */
407 def find_image_url(String path) {
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()) {
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}"
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}"
423 } else {
424 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
425 }
426 }
427 assert false, "Cannot find image url for ${path}"
428 }
429
430 /**
431 * Get revision for the repository https://svn.openstreetmap.org.
432 */
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) {
441 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
442 } else {
443 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
444 }
445
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 }
452
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 }
464
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 }
478 }
479 }
480 }
481}
Note: See TracBrowser for help on using the repository browser.