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

Last change on this file since 8681 was 8681, checked in by simon04, 8 years ago

see #11795 - taginfo-extract also external presets

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