source: josm/trunk/taginfoextract.groovy@ 8274

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

see #10512 - taginfoextract: add initial presets extration, switch all links to HTTPS

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