source: josm/trunk/taginfoextract.groovy@ 8272

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

see #10512 - Use Groovy's JsonBuilder

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