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