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

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

see #15229 - see #15182 - see #13036 - remove more GUI stuff from DeleteCommand

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