source: josm/trunk/taginfoextract.groovy@ 7608

Last change on this file since 7608 was 7554, checked in by bastiK, 10 years ago

see #10512 - one more option

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