1# Copyright (c) 2017-2021 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
2# This program is free software: you can redistribute it and/or modify
3# it under the terms of the GNU General Public License as published by
4# the Free Software Foundation, either version 3 of the License, or
5# (at your option) any later version.
6# This program is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9# GNU General Public License for more details.
10# You should have received a copy of the GNU General Public License
11# along with this program. If not, see <http://www.gnu.org/licenses/>.
12
13from urllib.parse import urlparse
14import re
15from os.path import dirname
16
17from eolie.logger import Logger
18
19
20class CSSImportRule:
21    """
22        Represent an import rule
23    """
24
25    def __init__(self, css, uri, cancellable):
26        """
27            Init rule
28            @param css as str
29            @param uri as str
30            @param cancellable as Gio.Cancellable
31        """
32        self.__stylesheet = None
33        try:
34            parsed = urlparse(uri)
35            search = re.search('@import url\(["\']?([^"\')]*)', css)
36            css = search.group(1)
37            if css.startswith(".."):
38                path_split = parsed.path.split("/")
39                css_uri = "%s://%s%s/%s" % (parsed.scheme, parsed.netloc,
40                                            "/".join(path_split[:-1]), css)
41            elif css.startswith("//"):
42                css_uri = "%s:%s" % (parsed.scheme, css)
43            elif not css.startswith("http"):
44                parent = dirname(parsed.path)
45                css_uri = "%s://%s%s/%s" % (
46                    parsed.scheme, parsed.netloc, parent, css)
47            from eolie.css_stylesheet import StyleSheet
48            self.__stylesheet = StyleSheet(uri=css_uri,
49                                           cancellable=cancellable)
50            self.__stylesheet.populate()
51        except Exception as e:
52            Logger.error("CSSImportRule::__init__: %s -> %s", e, css)
53
54    @property
55    def css_text(self):
56        """
57            Get css text for rules
58            @return str
59        """
60        if self.__stylesheet is None:
61            return ""
62        else:
63            return self.__stylesheet.css_text
64
65    @property
66    def populated(self):
67        """
68            True if rule is populated
69            @return bool
70        """
71        return self.__stylesheet is not None and self.__stylesheet.populated
72
73#######################
74# PRIVATE             #
75#######################
76