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

Last change on this file since 14020 was 14019, checked in by Don-vip, 6 years ago

update to Groovy 2.5.0 and Eclipse Photon (4.8.0)

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