2
# vim:fileencoding=utf-8
3
from __future__ import (unicode_literals, division, absolute_import,
7
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
10
from bisect import bisect
12
from calibre import guess_type as _guess_type
15
return _guess_type(x)[0] or 'application/octet-stream'
17
def setup_cssutils_serialization(tab_width=2):
19
prefs = cssutils.ser.prefs
20
prefs.indent = tab_width * ' '
21
prefs.indentClosingBrace = False
22
prefs.omitLastSemicolon = False
24
class PositionFinder(object):
26
def __init__(self, raw):
27
pat = br'\n' if isinstance(raw, bytes) else r'\n'
28
self.new_lines = tuple(m.start() + 1 for m in re.finditer(pat, raw))
30
def __call__(self, pos):
31
lnum = bisect(self.new_lines, pos)
33
offset = abs(pos - self.new_lines[lnum - 1])
36
return (lnum + 1, offset)
38
class CommentFinder(object):
40
def __init__(self, raw, pat=r'(?s)/\*.*?\*/'):
41
self.starts, self.ends = [], []
42
for m in re.finditer(pat, raw):
44
self.starts.append(start), self.ends.append(end)
46
def __call__(self, offset):
49
q = bisect(self.starts, offset) - 1
50
return q >= 0 and self.starts[q] <= offset <= self.ends[q]
52
def link_stylesheets(container, names, sheets, remove=False, mtype='text/css'):
53
from calibre.ebooks.oeb.base import XPath, XHTML
56
lp = XPath('//h:link[@href]')
57
hp = XPath('//h:head')
59
root = container.parsed(name)
62
if (link.get('type', mtype) or mtype) == mtype:
63
container.remove_from_xml(link)
64
changed_names.add(name)
66
existing = {container.href_to_name(l.get('href'), name) for l in lp(root) if (l.get('type', mtype) or mtype) == mtype}
67
extra = snames - existing
69
changed_names.add(name)
72
except (TypeError, IndexError):
73
parent = root.makeelement(XHTML('head'))
74
container.insert_into_xml(root, parent, index=0)
77
container.insert_into_xml(
78
parent, parent.makeelement(XHTML('link'), rel='stylesheet', type=mtype,
79
href=container.name_to_href(sheet, name)))