File: util.py

package info (click to toggle)
qgis 2.18.28%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,007,948 kB
  • sloc: cpp: 671,774; python: 158,539; xml: 35,690; ansic: 8,346; sh: 1,766; perl: 1,669; sql: 999; yacc: 836; lex: 461; makefile: 292
file content (186 lines) | stat: -rw-r--r-- 5,587 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2010 NextGIS (http://nextgis.org),
#                    Alexander Bruy (alexander.bruy@gmail.com),
#                    Maxim Dubinin (sim@gis-lab.info)
#
# Copyright (C) 2014 Tom Kralidis (tomkralidis@gmail.com)
# Copyright (C) 2014 Angelos Tzotsos (tzotsos@gmail.com)
#
# This source is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# This code is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
###############################################################################

#avoid PendingDeprecationWarning from PyQt4.uic
import warnings
warnings.filterwarnings("ignore", category=PendingDeprecationWarning)

import ConfigParser
from gettext import gettext, ngettext
import logging
import os
import webbrowser
from xml.dom.minidom import parseString
import xml.etree.ElementTree as etree

from jinja2 import Environment, FileSystemLoader
from pygments import highlight
from pygments.lexers import XmlLexer
from pygments.formatters import HtmlFormatter
from qgis.PyQt.QtCore import QSettings, QUrl
from qgis.PyQt.QtWidgets import QMessageBox
from qgis.PyQt.uic import loadUiType

from qgis.core import QGis


LOGGER = logging.getLogger('MetaSearch')


class StaticContext(object):

    """base configuration / scaffolding"""

    def __init__(self):
        """init"""
        self.ppath = os.path.dirname(os.path.abspath(__file__))
        self.metadata = ConfigParser.ConfigParser()
        self.metadata.readfp(open(os.path.join(self.ppath, 'metadata.txt')))


def get_ui_class(ui_file):
    """return class object of a uifile"""
    ui_file_full = '%s%sui%s%s' % (os.path.dirname(os.path.abspath(__file__)),
                                   os.sep, os.sep, ui_file)
    return loadUiType(ui_file_full)[0]


def render_template(language, context, data, template):
    """Renders HTML display of metadata XML"""

    env = Environment(extensions=['jinja2.ext.i18n'],
                      loader=FileSystemLoader(context.ppath))
    env.install_gettext_callables(gettext, ngettext, newstyle=True)

    template_file = 'resources/templates/%s' % template
    template = env.get_template(template_file)
    return template.render(language=language, obj=data)


def get_connections_from_file(parent, filename):
    """load connections from connection file"""

    error = 0
    try:
        doc = etree.parse(filename).getroot()
        if doc.tag != 'qgsCSWConnections':
            error = 1
            msg = parent.tr('Invalid CSW connections XML.')
    except etree.ParseError as err:
        error = 1
        msg = parent.tr('Cannot parse XML file: %s' % err)
    except IOError as err:
        error = 1
        msg = parent.tr('Cannot open file: %s' % err)

    if error == 1:
        QMessageBox.information(parent, parent.tr('Loading Connections'), msg)
        return
    return doc


def prettify_xml(xml):
    """convenience function to prettify XML"""

    if xml.count('\n') > 5:  # likely already pretty printed
        return xml
    else:
        # check if it's a GET request
        if xml.startswith('http'):
            return xml
        else:
            return parseString(xml).toprettyxml()


def highlight_xml(context, xml):
    """render XML as highlighted HTML"""

    hformat = HtmlFormatter()
    css = hformat.get_style_defs('.highlight')
    body = highlight(prettify_xml(xml), XmlLexer(), hformat)

    env = Environment(loader=FileSystemLoader(context.ppath))

    template_file = 'resources/templates/xml_highlight.html'
    template = env.get_template(template_file)
    return template.render(css=css, body=body)


def get_help_url():
    """return QGIS MetaSearch help documentation link"""

    locale_name = QSettings().value('locale/userLocale')[0:2]
    major, minor = QGis.QGIS_VERSION.split('.')[:2]

    if minor == '99':  # master
        version = 'testing'
    else:
        version = '.'.join([major, minor])

    path = '%s/%s/docs/user_manual/plugins/plugins_metasearch.html' % \
           (version, locale_name)

    return '/'.join(['http://docs.qgis.org', path])


def open_url(url):
    """open URL in web browser"""

    webbrowser.open(url)


def normalize_text(text):
    """tidy up string"""

    return text.replace('\n', '')


def serialize_string(input_string):
    """apply a serial counter to a string"""

    s = input_string.strip().split()

    last_token = s[-1]
    all_other_tokens_as_string = input_string.replace(last_token, '')

    if last_token.isdigit():
        value = '%s%s' % (all_other_tokens_as_string, int(last_token) + 1)
    else:
        value = '%s 1' % input_string

    return value


def clean_ows_url(url):
    """clean an OWS URL of added basic service parameters"""

    url2 = QUrl(url)
    url2.removeEncodedQueryItem('service')
    url2.removeEncodedQueryItem('SERVICE')
    url2.removeEncodedQueryItem('request')
    url2.removeEncodedQueryItem('REQUEST')

    return url2.toString()