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

Last change on this file since 12855 was 12855, checked in by bastiK, 7 years ago

see #15229 - add separate interface IBaseDirectories to look up pref, user data and cache dir

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