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

Last change on this file since 8687 was 8687, checked in by Don-vip, 8 years ago

see #11795 - add taginfo target to Ant build

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