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

Last change on this file since 11295 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
RevLine 
[7544]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 *
[8306]7 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t mappaint
8 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t presets
[8681]9 * groovy -cp dist/josm-custom.jar scripts/taginfoextract.groovy -t external_presets
[7544]10 */
[8439]11import groovy.json.JsonBuilder
[8687]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
[7544]20import org.openstreetmap.josm.Main
[7625]21import org.openstreetmap.josm.data.Version
[7544]22import org.openstreetmap.josm.data.coor.LatLon
23import org.openstreetmap.josm.data.osm.Node
[9289]24import org.openstreetmap.josm.data.osm.OsmPrimitive
[7553]25import org.openstreetmap.josm.data.osm.Way
[7625]26import org.openstreetmap.josm.data.osm.visitor.paint.MapPaintSettings
27import org.openstreetmap.josm.data.osm.visitor.paint.StyledMapRenderer
[7544]28import org.openstreetmap.josm.data.projection.Projections
[7625]29import org.openstreetmap.josm.gui.NavigatableComponent
[7544]30import org.openstreetmap.josm.gui.mappaint.Environment
[8687]31import org.openstreetmap.josm.gui.mappaint.MultiCascade
[8681]32import org.openstreetmap.josm.gui.mappaint.MapPaintStyles.IconReference
[8687]33import org.openstreetmap.josm.gui.mappaint.mapcss.MapCSSStyleSource
[10837]34import org.openstreetmap.josm.gui.mappaint.mapcss.ConditionFactory.SimpleKeyValueCondition
[7625]35import org.openstreetmap.josm.gui.mappaint.mapcss.Selector.GeneralSelector
[7544]36import org.openstreetmap.josm.gui.mappaint.mapcss.parsergen.MapCSSParser
[9289]37import org.openstreetmap.josm.gui.mappaint.styleelement.AreaElement
[9283]38import org.openstreetmap.josm.gui.mappaint.styleelement.LineElement
[9289]39import org.openstreetmap.josm.gui.mappaint.styleelement.StyleElement
[8681]40import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference
[8863]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
[7544]46import org.openstreetmap.josm.io.CachedFile
[11252]47import org.openstreetmap.josm.tools.RightAndLefthandTraffic
48import org.openstreetmap.josm.tools.Territories
[8274]49import org.openstreetmap.josm.tools.Utils
[7544]50
[9880]51class TagInfoExtract {
[7544]52
[7553]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
[9289]59 String base_dir = "."
60 Set tags = []
[7625]61
[7553]62 private def cached_svnrev
[7544]63
[7553]64 /**
65 * Check if a certain tag is supported by the style as node / way / area.
66 */
67 abstract class Checker {
[7625]68
[7553]69 def tag
[9289]70 OsmPrimitive osm
[7625]71
[7553]72 Checker(tag) {
73 this.tag = tag
74 }
[7625]75
[9289]76 Environment apply_stylesheet(OsmPrimitive osm) {
[7553]77 osm.put(tag[0], tag[1])
[9289]78 MultiCascade mc = new MultiCascade()
[7625]79
[9289]80 Environment env = new Environment(osm, mc, null, style_source)
[7553]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 }
[7625]94
[7553]95 /**
[9289]96 * Create image file from StyleElement.
[7553]97 * @return the URL
[7625]98 */
[9289]99 def create_image(StyleElement elem_style, type, nc) {
[7553]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)
[7625]105 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
[7554]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}"
[7553]110 }
[7544]111
[7553]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 }
[7544]119
[7553]120 class NodeChecker extends Checker {
121 NodeChecker(tag) {
122 super(tag)
123 }
124
[9953]125 @Override
[7553]126 def find_url(boolean generate_image) {
[9214]127 osm = new Node(LatLon.ZERO)
[7553]128 def env = apply_stylesheet(osm)
129 def c = env.mc.getCascade("default")
130 def image = c.get("icon-image")
131 if (image) {
[10927]132 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
133 return find_image_url(image.iconName)
[7553]134 }
135 }
136 }
[7544]137 }
138
[7553]139 class WayChecker extends Checker {
140 WayChecker(tag) {
141 super(tag)
142 }
143
[9953]144 @Override
[7553]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))
[9289]150 ((Way)osm).addNode(n1)
151 ((Way)osm).addNode(n2)
[7553]152 def env = apply_stylesheet(osm)
[9283]153 def les = LineElement.createLine(env)
[7553]154 if (les != null) {
155 if (!generate_image) return true
156 return create_image(les, 'way', nc)
157 }
158 }
[7544]159 }
[7553]160
161 class AreaChecker extends Checker {
162 AreaChecker(tag) {
163 super(tag)
164 }
165
[9953]166 @Override
[7553]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))
[9289]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)
[7553]179 def env = apply_stylesheet(osm)
[9289]180 def aes = AreaElement.create(env)
[7553]181 if (aes != null) {
182 if (!generate_image) return true
183 return create_image(aes, 'area', nc)
184 }
185 }
[7544]186 }
187
[7553]188 /**
189 * Main method.
190 */
191 static main(def args) {
192 parse_command_line_arguments(args)
[9880]193 def script = new TagInfoExtract()
[8274]194 if (!options.t || options.t == 'mappaint') {
195 script.run()
196 } else if (options.t == 'presets') {
197 script.run_presets()
[8681]198 } else if (options.t == 'external_presets') {
199 script.run_external_presets()
[8274]200 } else {
201 System.err.println 'Invalid type ' + options.t
[8687]202 if (!options.noexit) {
203 System.exit(1)
204 }
[8274]205 }
206
[8687]207 if (!options.noexit) {
208 System.exit(0)
209 }
[7553]210 }
[7544]211
[7553]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:",
[7936]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: -)")
[8274]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)")
[7553]222 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
[8687]223 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
[8274]224 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
[7554]225 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
[7553]226 cli.h(longOpt:'help', "show this help")
227 options = cli.parse(args)
[7544]228
[7553]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 }
[7625]250
[8274]251 void run_presets() {
252 init()
[8681]253 def presets = TaggingPresetReader.readAll(input_file, true)
[8690]254 def tags = convert_presets(presets, "", true)
[8681]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) {
[8274]259 def tags = []
260 for (TaggingPreset preset : presets) {
[8863]261 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
[8274]262 def values
[8863]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;
[8274]266 default: values = [];
267 }
268 for (String value : values) {
269 def tag = [
[8681]270 description: descriptionPrefix + preset.name,
[8274]271 key: item.key,
272 value: value,
273 ]
[10769]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]
[8681]279 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
[8274]280 tags += tag
281 }
282 }
283 }
[8681]284 return tags
285 }
[8274]286
[8681]287 void run_external_presets() {
288 init()
[8710]289 TaggingPresetReader.setLoadIcons(false)
[8681]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)
[8274]309 }
310
[7553]311 void run() {
312 init()
313 parse_style_sheet()
314 collect_tags()
[7544]315
[8272]316 def tags = tags.collect {
317 def tag = it
[7553]318 def types = []
319 def final_url = null
320
321 def node_url = new NodeChecker(tag).find_url(true)
322 if (node_url) {
[8272]323 types += 'node'
[7553]324 final_url = node_url
325 }
326 def way_url = new WayChecker(tag).find_url(final_url == null)
327 if (way_url) {
[8272]328 types += 'way'
[7553]329 if (!final_url) {
330 final_url = way_url
[7544]331 }
332 }
[7553]333 def area_url = new AreaChecker(tag).find_url(final_url == null)
334 if (area_url) {
[8272]335 types += 'area'
[7553]336 if (!final_url) {
337 final_url = area_url
338 }
339 }
[7625]340
[8272]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
[7625]345 }
[7553]346
[8274]347 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
[7544]348 }
349
[8274]350 void write_json(name, description, tags) {
[8272]351 def json = new JsonBuilder()
352 def project = [
353 name: name,
354 description: description,
[8274]355 project_url: "https://josm.openstreetmap.de/",
356 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
[8272]357 contact_name: "JOSM developer team",
358 contact_email: "josm-dev@openstreetmap.org",
359 ]
[10769]360 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
[8274]361
362 if (output_file != null) {
363 json.writeTo(output_file)
364 output_file.close()
365 } else {
366 print json.toPrettyString()
367 }
[8272]368 }
369
[7553]370 /**
371 * Initialize the script.
372 */
373 def init() {
[8681]374 Main.determinePlatformHook()
[7553]375 Main.pref.enableSaveOnPut(false)
376 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
[8275]377 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
[8717]378 tmpdir.toFile().deleteOnExit()
[8275]379 System.setProperty("josm.home", tmpdir.toString())
[11252]380 Territories.initialize()
381 RightAndLefthandTraffic.initialize()
[7544]382
[7553]383 josm_svn_revision = Version.getInstance().getVersion()
384 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
[7544]385
[8274]386 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
[7553]387 input_file = "resource://styles/standard/elemstyles.mapcss"
[8274]388 } else if (options.arguments().size() == 0 && options.t == 'presets') {
389 input_file = "resource://data/defaultpresets.xml"
[7553]390 } else {
391 input_file = options.arguments()[0]
392 }
[7544]393
[7553]394 output_file = null
395 if (options.o && options.o != "-") {
396 output_file = new FileWriter(options.o)
397 }
398 }
[7544]399
[7553]400 /**
[8274]401 * Determine full image url (can refer to JOSM or OSM repository).
[7553]402 */
[9289]403 def find_image_url(String path) {
[8274]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()) {
[8439]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}"
[8671]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}"
[8439]419 } else {
420 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
421 }
[8274]422 }
423 assert false, "Cannot find image url for ${path}"
424 }
425
426 /**
427 * Get revision for the repository https://svn.openstreetmap.org.
428 */
[7553]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) {
[8274]437 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
[7553]438 } else {
439 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
440 }
[7625]441
[7553]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 }
[7625]448
[7553]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 }
[7625]460
[7553]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 }
[7544]474 }
475 }
476 }
477}
Note: See TracBrowser for help on using the repository browser.