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

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

see #15229 - see #15182 - see #13036 - fix groovy script

  • Property svn:eol-style set to native
File size: 18.3 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 */
[8687]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
[7544]18import org.openstreetmap.josm.Main
[12751]19import org.openstreetmap.josm.actions.DeleteAction
20import org.openstreetmap.josm.command.DeleteCommand
[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
[11982]47import org.openstreetmap.josm.tools.Logging
[11252]48import org.openstreetmap.josm.tools.RightAndLefthandTraffic
49import org.openstreetmap.josm.tools.Territories
[8274]50import org.openstreetmap.josm.tools.Utils
[7544]51
[11324]52import edu.umd.cs.findbugs.annotations.SuppressFBWarnings
53import groovy.json.JsonBuilder
54
[9880]55class TagInfoExtract {
[7544]56
[7553]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
[9289]63 String base_dir = "."
64 Set tags = []
[7625]65
[7553]66 private def cached_svnrev
[7544]67
[7553]68 /**
69 * Check if a certain tag is supported by the style as node / way / area.
70 */
71 abstract class Checker {
[7625]72
[7553]73 def tag
[9289]74 OsmPrimitive osm
[7625]75
[7553]76 Checker(tag) {
77 this.tag = tag
78 }
[7625]79
[9289]80 Environment apply_stylesheet(OsmPrimitive osm) {
[7553]81 osm.put(tag[0], tag[1])
[9289]82 MultiCascade mc = new MultiCascade()
[7625]83
[9289]84 Environment env = new Environment(osm, mc, null, style_source)
[7553]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 }
[7625]98
[7553]99 /**
[9289]100 * Create image file from StyleElement.
[7553]101 * @return the URL
[7625]102 */
[9289]103 def create_image(StyleElement elem_style, type, nc) {
[7553]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)
[7625]109 elem_style.paintPrimitive(osm, MapPaintSettings.INSTANCE, renderer, false, false, false)
[7554]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}"
[7553]114 }
[7544]115
[7553]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 }
[7544]123
[11324]124 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]125 class NodeChecker extends Checker {
126 NodeChecker(tag) {
127 super(tag)
128 }
129
[9953]130 @Override
[7553]131 def find_url(boolean generate_image) {
[9214]132 osm = new Node(LatLon.ZERO)
[7553]133 def env = apply_stylesheet(osm)
134 def c = env.mc.getCascade("default")
135 def image = c.get("icon-image")
136 if (image) {
[10927]137 if (image instanceof IconReference && !image.isDeprecatedIcon()) {
138 return find_image_url(image.iconName)
[7553]139 }
140 }
141 }
[7544]142 }
143
[11324]144 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]145 class WayChecker extends Checker {
146 WayChecker(tag) {
147 super(tag)
148 }
149
[9953]150 @Override
[7553]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))
[9289]156 ((Way)osm).addNode(n1)
157 ((Way)osm).addNode(n2)
[7553]158 def env = apply_stylesheet(osm)
[9283]159 def les = LineElement.createLine(env)
[7553]160 if (les != null) {
161 if (!generate_image) return true
162 return create_image(les, 'way', nc)
163 }
164 }
[7544]165 }
[7553]166
[11324]167 @SuppressFBWarnings(value = "MF_CLASS_MASKS_FIELD")
[7553]168 class AreaChecker extends Checker {
169 AreaChecker(tag) {
170 super(tag)
171 }
172
[9953]173 @Override
[7553]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))
[9289]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)
[7553]186 def env = apply_stylesheet(osm)
[9289]187 def aes = AreaElement.create(env)
[7553]188 if (aes != null) {
189 if (!generate_image) return true
190 return create_image(aes, 'area', nc)
191 }
192 }
[7544]193 }
194
[7553]195 /**
196 * Main method.
197 */
198 static main(def args) {
199 parse_command_line_arguments(args)
[9880]200 def script = new TagInfoExtract()
[8274]201 if (!options.t || options.t == 'mappaint') {
202 script.run()
203 } else if (options.t == 'presets') {
204 script.run_presets()
[8681]205 } else if (options.t == 'external_presets') {
206 script.run_external_presets()
[8274]207 } else {
208 System.err.println 'Invalid type ' + options.t
[8687]209 if (!options.noexit) {
210 System.exit(1)
211 }
[8274]212 }
213
[8687]214 if (!options.noexit) {
215 System.exit(0)
216 }
[7553]217 }
[7544]218
[7553]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:",
[7936]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: -)")
[8274]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)")
[7553]229 cli._(longOpt:'imgdir', args:1, argName:"directory", "directory to put the generated images in (default: ./taginfo-img)")
[8687]230 cli._(longOpt:'noexit', "don't call System.exit(), for use from Ant script")
[8274]231 cli._(longOpt:'svnweb', 'fetch revision of the repository https://svn.openstreetmap.org/ from web and not from the local repository')
[7554]232 cli._(longOpt:'imgurlprefix', args:1, argName:'prefix', 'image URLs prefix for generated image files')
[7553]233 cli.h(longOpt:'help', "show this help")
234 options = cli.parse(args)
[7544]235
[7553]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 }
[7625]257
[8274]258 void run_presets() {
259 init()
[8681]260 def presets = TaggingPresetReader.readAll(input_file, true)
[8690]261 def tags = convert_presets(presets, "", true)
[8681]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) {
[8274]266 def tags = []
267 for (TaggingPreset preset : presets) {
[8863]268 for (KeyedItem item : Utils.filteredCollection(preset.data, KeyedItem.class)) {
[8274]269 def values
[8863]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;
[8274]273 default: values = [];
274 }
275 for (String value : values) {
276 def tag = [
[8681]277 description: descriptionPrefix + preset.name,
[8274]278 key: item.key,
279 value: value,
280 ]
[10769]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]
[8681]286 if (addImages && preset.iconName) tag += [icon_url: find_image_url(preset.iconName)]
[8274]287 tags += tag
288 }
289 }
290 }
[8681]291 return tags
292 }
[8274]293
[8681]294 void run_external_presets() {
295 init()
[8710]296 TaggingPresetReader.setLoadIcons(false)
[8681]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)
[8274]316 }
317
[7553]318 void run() {
319 init()
320 parse_style_sheet()
321 collect_tags()
[7544]322
[8272]323 def tags = tags.collect {
324 def tag = it
[7553]325 def types = []
326 def final_url = null
327
328 def node_url = new NodeChecker(tag).find_url(true)
329 if (node_url) {
[8272]330 types += 'node'
[7553]331 final_url = node_url
332 }
333 def way_url = new WayChecker(tag).find_url(final_url == null)
334 if (way_url) {
[8272]335 types += 'way'
[7553]336 if (!final_url) {
337 final_url = way_url
[7544]338 }
339 }
[7553]340 def area_url = new AreaChecker(tag).find_url(final_url == null)
341 if (area_url) {
[8272]342 types += 'area'
[7553]343 if (!final_url) {
344 final_url = area_url
345 }
346 }
[7625]347
[8272]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
[7625]352 }
[7553]353
[8274]354 write_json("JOSM main mappaint style", "Tags supported by the main mappaint style in the OSM editor JOSM", tags)
[7544]355 }
356
[8274]357 void write_json(name, description, tags) {
[8272]358 def json = new JsonBuilder()
359 def project = [
360 name: name,
361 description: description,
[8274]362 project_url: "https://josm.openstreetmap.de/",
363 icon_url: "https://josm.openstreetmap.de/export/7770/josm/trunk/images/logo_16x16x8.png",
[8272]364 contact_name: "JOSM developer team",
365 contact_email: "josm-dev@openstreetmap.org",
366 ]
[10769]367 json data_format: 1, data_updated: new Date().format("yyyyMMdd'T'hhmmss'Z'", TimeZone.getTimeZone('UTC')), project: project, tags: tags
[8274]368
369 if (output_file != null) {
370 json.writeTo(output_file)
371 output_file.close()
372 } else {
373 print json.toPrettyString()
374 }
[8272]375 }
376
[7553]377 /**
378 * Initialize the script.
379 */
380 def init() {
[8681]381 Main.determinePlatformHook()
[11982]382 Logging.setLogLevel(Logging.LEVEL_INFO)
[7553]383 Main.pref.enableSaveOnPut(false)
384 Main.setProjection(Projections.getProjectionByCode("EPSG:3857"))
[8275]385 Path tmpdir = Files.createTempDirectory(FileSystems.getDefault().getPath(base_dir), "pref")
[8717]386 tmpdir.toFile().deleteOnExit()
[8275]387 System.setProperty("josm.home", tmpdir.toString())
[12752]388 DeleteCommand.setDeletionCallback(DeleteAction.&checkAndConfirmOutlyingDelete)
[11252]389 Territories.initialize()
390 RightAndLefthandTraffic.initialize()
[7544]391
[7553]392 josm_svn_revision = Version.getInstance().getVersion()
393 assert josm_svn_revision != Version.JOSM_UNKNOWN_VERSION
[7544]394
[8274]395 if (options.arguments().size() == 0 && (!options.t || options.t == 'mappaint')) {
[7553]396 input_file = "resource://styles/standard/elemstyles.mapcss"
[8274]397 } else if (options.arguments().size() == 0 && options.t == 'presets') {
398 input_file = "resource://data/defaultpresets.xml"
[7553]399 } else {
400 input_file = options.arguments()[0]
401 }
[7544]402
[7553]403 output_file = null
404 if (options.o && options.o != "-") {
405 output_file = new FileWriter(options.o)
406 }
407 }
[7544]408
[7553]409 /**
[8274]410 * Determine full image url (can refer to JOSM or OSM repository).
[7553]411 */
[9289]412 def find_image_url(String path) {
[8274]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()) {
[8439]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}"
[8671]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}"
[8439]428 } else {
429 return "https://josm.openstreetmap.de/export/${josm_svn_revision}/josm/trunk/images/${path}"
430 }
[8274]431 }
432 assert false, "Cannot find image url for ${path}"
433 }
434
435 /**
436 * Get revision for the repository https://svn.openstreetmap.org.
437 */
[7553]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) {
[8274]446 xml = "svn info --xml https://svn.openstreetmap.org/applications/share/map-icons/classic.small".execute().text
[7553]447 } else {
448 xml = "svn info --xml ${base_dir}/images/styles/standard/".execute().text
449 }
[7625]450
[7553]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 }
[7625]457
[7553]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 }
[7625]469
[7553]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 }
[7544]483 }
484 }
485 }
486}
Note: See TracBrowser for help on using the repository browser.