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

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

major code cleanup/refactoring of tagging presets: slay the monster TaggingPresetItems (60 Kb, 1600 lines) and extract all its internal classes to a new package gui.tagging.presets.items

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