1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4"""
5***************************************************************************
6    dump_babel_formats.py
7    ---------------------
8    Date                 : July 2021
9    Copyright            : (C) 2021 by Nyall Dawson
10    Email                : nyall dot dawson at gmail dot com
11***************************************************************************
12*                                                                         *
13*   This program is free software; you can redistribute it and/or modify  *
14*   it under the terms of the GNU General Public License as published by  *
15*   the Free Software Foundation; either version 2 of the License, or     *
16*   (at your option) any later version.                                   *
17*                                                                         *
18***************************************************************************
19"""
20
21"""
22Dumps a list of babel formats for inclusion in QgsBabelFormatRegistry::QgsBabelFormatRegistry()
23"""
24
25__author__ = 'Nyall Dawson'
26__date__ = 'July 2021'
27__copyright__ = '(C) 2021, Nyall Dawson'
28
29import subprocess
30import re
31
32
33def process_lines(lines):
34    """
35    Processes lines from gpsbabel -^3 output
36    """
37    current_line = 0
38    format_out = {}
39    while current_line < len(lines):
40        line = lines[current_line]
41
42        fields = line.split('\t')
43        assert len(fields) >= 5, fields
44
45        current_line += 1
46        html_pages = []
47        while lines[current_line].startswith('http'):
48            html_pages.append(lines[current_line])
49            current_line += 1
50
51        while current_line < len(lines) and lines[current_line].startswith('option'):
52            options = lines[current_line].split('\t')
53            assert len(options) >= 9, options
54
55            name, description, option_type, option_def, option_min, option_max, option_html = options[:7]
56            # print(name, description, option_type, option_def, option_min, option_max, option_html)
57
58            option_http_pages = []
59            current_line += 1
60            while current_line < len(lines) and lines[current_line].startswith('http'):
61                option_http_pages.append(lines[current_line])
62                current_line += 1
63
64        name = fields[2]
65        description = fields[4]
66
67        # remove odd comment from description!
68        description = description.replace(' [ Get Jonathon Johnson to describe', '')
69
70        read_waypoints = fields[1][0] == 'r'
71        read_tracks = fields[1][2] == 'r'
72        read_routes = fields[1][4] == 'r'
73        write_waypoints = fields[1][1] == 'w'
74        write_tracks = fields[1][3] == 'w'
75        write_routes = fields[1][5] == 'w'
76        is_file_format = fields[0] == 'file'
77        is_device_format = fields[0] == 'serial'
78        extensions = fields[3].split('/')
79
80        if is_file_format and any([read_routes, read_tracks, read_waypoints]):
81            capabilities = []
82            if read_waypoints:
83                capabilities.append('Qgis::BabelFormatCapability::Waypoints')
84            if read_routes:
85                capabilities.append('Qgis::BabelFormatCapability::Routes')
86            if read_tracks:
87                capabilities.append('Qgis::BabelFormatCapability::Tracks')
88            capabilities_string = ' | '.join(capabilities)
89
90            extensions_string = '{' + ', '.join([f'QStringLiteral( "{ext.strip()}" )' for ext in extensions if ext.strip()]) + '}'
91            format_out[
92                name] = f'mImporters[QStringLiteral( "{name}" )] = new QgsBabelSimpleImportFormat( QStringLiteral( "{name}" ), QStringLiteral( "{description}" ), {capabilities_string}, {extensions_string} );'
93
94    for format_name in sorted(format_out.keys(), key=lambda x: x.lower()):
95        print(format_out[format_name])
96
97
98CMD = "gpsbabel -^3"
99START_FORMATS_RX = re.compile("^file|serial")
100
101result = subprocess.Popen(CMD, shell=True, stdout=subprocess.PIPE)
102found_first_line = False
103input_lines = []
104for input_line in result.stdout.readlines():
105    input_str = input_line.decode()
106    if not found_first_line:
107        if START_FORMATS_RX.match(input_str):
108            found_first_line = True
109
110        else:
111            continue
112
113    if input_str.strip():
114        input_lines.append(input_str.strip())
115
116process_lines(input_lines)
117