source: josm/trunk/scripts/taginfoextract.groovy@ 8710

Last change on this file since 8710 was 8710, checked in by simon04, 9 years ago

see #11795 - taginfoextract: avoid "Could not get presets icon" by not loading icons

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