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

Last change on this file since 11313 was 11252, checked in by Don-vip, 7 years ago

see #10387 - refactor actions to fix taginfo script

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