1 #!/usr/bin/env python 2 3 """ 4 Common HTML theme functionality. 5 6 Copyright (C) 2018, 2019 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from moinformat.themes.common import Theme 23 from os import listdir 24 from os.path import splitext 25 26 class HTMLTheme(Theme): 27 28 "A common HTML theme abstraction." 29 30 # Support a collection of links to stylesheets provided by each theme. 31 32 link = '<link rel="stylesheet" type="text/css" charset="utf-8"' \ 33 ' media="%(media)s" href="%(root)s/_css/%(filename)s" />\n' 34 35 bundled_link = '<style type="text/css" media="%(media)s">\n%(data)s' \ 36 '</style>\n' 37 38 def get_links(self, subs, bundle=False): 39 40 """ 41 Using 'subs', return a string containing markup linking to resources if 42 'bundle' is a false value or omitted. If 'bundle' is a true value, 43 incorporate resources within the document. 44 """ 45 46 d = {} 47 d.update(subs) 48 49 css = self.get_resource("css") 50 links = [] 51 52 for filename in listdir(css): 53 54 # Only link to CSS files. 55 56 basename, ext = splitext(filename) 57 if ext != ".css": 58 continue 59 60 # Filenames can have the form <media>.css or <media>-<name>.css to 61 # set the media type. 62 63 t = basename.split("-", 1) 64 65 d["media"] = t[0] or "all" 66 d["filename"] = filename 67 68 if bundle: 69 d["data"] = self.load_resource(filename, css) 70 71 template = bundle and self.bundled_link or self.link 72 links.append(template % d) 73 74 return "".join(links) 75 76 # Public methods. 77 78 def apply(self, text): 79 80 "Apply this theme to the given 'text', returning a themed version." 81 82 template = self.load_resource("template.html") 83 subs = { 84 "encoding" : self.output.encoding, 85 "root" : self.linker.get_top_level() or ".", 86 "text" : text, 87 "title" : self.metadata.get("title") or self.metadata.get("pagename"), 88 } 89 subs["links"] = self.get_links(subs, self.bundle) 90 return template % subs 91 92 def install_resources(self): 93 94 "Install resources for this theme." 95 96 if not self.bundle: 97 self.install_resource("css", "_css") 98 99 # vim: tabstop=4 expandtab shiftwidth=4