From e878b52c99de94f3af17a7cd1c6aaf47d18b4432 Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Sun, 28 Sep 2014 11:28:22 +0530 Subject: [PATCH] MOBI Output: Handle input documents that use CSS 3 syntax for colors by converting the color to the #RRGGBB format required for MOBI --- src/calibre/ebooks/mobi/mobiml.py | 7 ++++--- src/calibre/ebooks/mobi/utils.py | 9 +++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/calibre/ebooks/mobi/mobiml.py b/src/calibre/ebooks/mobi/mobiml.py index 97d2ce3e77..966a3c2ee8 100644 --- a/src/calibre/ebooks/mobi/mobiml.py +++ b/src/calibre/ebooks/mobi/mobiml.py @@ -13,6 +13,7 @@ from calibre.ebooks.oeb.base import namespace, barename from calibre.ebooks.oeb.base import XHTML, XHTML_NS, urlnormalize from calibre.ebooks.oeb.stylizer import Stylizer from calibre.ebooks.oeb.transforms.flatcss import KeyMapper +from calibre.ebooks.mobi.utils import convert_color_for_font_tag from calibre.utils.magick.draw import identify_data MBP_NS = 'http://mobipocket.com/ns/mbp' @@ -125,7 +126,7 @@ class MobiMLizer(object): self.mobimlize_elem(body, stylizer, BlockState(nbody), [FormatState()]) item.data = nroot - #print etree.tostring(nroot) + # print etree.tostring(nroot) def mobimlize_font(self, ptsize): return self.fnums[self.fmap[ptsize]] @@ -280,10 +281,10 @@ class MobiMLizer(object): inline = etree.SubElement(inline, XHTML('b')) if istate.bgcolor is not None and istate.bgcolor != 'transparent' : inline = etree.SubElement(inline, XHTML('span'), - bgcolor=istate.bgcolor) + bgcolor=convert_color_for_font_tag(istate.bgcolor)) if istate.fgcolor != 'black': inline = etree.SubElement(inline, XHTML('font'), - color=unicode(istate.fgcolor)) + color=convert_color_for_font_tag(istate.fgcolor)) if istate.strikethrough: inline = etree.SubElement(inline, XHTML('s')) if istate.underline: diff --git a/src/calibre/ebooks/mobi/utils.py b/src/calibre/ebooks/mobi/utils.py index d20fc5bcba..b01e057dbb 100644 --- a/src/calibre/ebooks/mobi/utils.py +++ b/src/calibre/ebooks/mobi/utils.py @@ -14,6 +14,7 @@ from io import BytesIO from calibre.utils.magick.draw import Image, save_cover_data_to, thumbnail from calibre.utils.imghdr import what from calibre.ebooks import normalize +from tinycss.color3 import parse_color_string IMAGE_MAX_SIZE = 10 * 1024 * 1024 RECORD_SIZE = 0x1000 # 4096 (Text record size (uncompressed)) @@ -604,3 +605,11 @@ def is_guide_ref_start(ref): (ref.type and ref.type.lower() in {'start', 'other.start', 'text'})) + +def convert_color_for_font_tag(val): + rgba = parse_color_string(unicode(val or '')) + if rgba is None or rgba == 'currentColor': + return val + clamp = lambda x: min(x, max(0, x), 1) + rgb = map(clamp, rgba[:3]) + return '#' + ''.join(map(lambda x:'%02x' % int(x * 255), rgb))