source: josm/trunk/taginfoextract.groovy@ 8273

Last change on this file since 8273 was 8273, checked in by simon04, 10 years ago

see #10512 - taginfoextract: fix problem wrt layer name

Before, no object_types and icon_url have been extracted.

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