# coding: utf-8
"""
weasyprint.html
---------------
Specific handling for some HTML elements, especially replaced elements.
Replaced elements (eg. elements) are rendered externally and
behave as an atomic opaque box in CSS. In general, they may or may not
have intrinsic dimensions. But the only replaced elements currently
supported in WeasyPrint are images with intrinsic dimensions.
:copyright: Copyright 2011-2014 Simon Sapin and contributors, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import division, unicode_literals
import logging
import os.path
import re
import sys
from . import CSS
from .compat import urljoin, xrange
from .css import get_child_text
from .formatting_structure import boxes
from .logger import LOGGER
from .urls import get_url_attribute
# XXX temporarily disable logging for user-agent stylesheet
level = LOGGER.level
LOGGER.setLevel(logging.ERROR)
if hasattr(sys, "frozen"):
root = os.path.dirname(sys.executable)
else:
root = os.path.dirname(__file__)
HTML5_UA_STYLESHEET = CSS(filename=os.path.join(root, 'css', 'html5_ua.css'))
HTML5_PH_STYLESHEET = CSS(filename=os.path.join(root, 'css', 'html5_ph.css'))
LOGGER.setLevel(level)
# http://whatwg.org/C#space-character
HTML_WHITESPACE = ' \t\n\f\r'
HTML_SPACE_SEPARATED_TOKENS_RE = re.compile('[^%s]+' % HTML_WHITESPACE)
def ascii_lower(string):
r"""Transform (only) ASCII letters to lower case: A-Z is mapped to a-z.
:param string: An Unicode string.
:returns: A new Unicode string.
This is used for `ASCII case-insensitive
`_ matching.
This is different from the :meth:`~py:str.lower` method of Unicode strings
which also affect non-ASCII characters,
sometimes mapping them into the ASCII range:
>>> keyword = u'Bac\N{KELVIN SIGN}ground'
>>> assert keyword.lower() == u'background'
>>> assert ascii_lower(keyword) != keyword.lower()
>>> assert ascii_lower(keyword) == u'bac\N{KELVIN SIGN}ground'
"""
# This turns out to be faster than unicode.translate()
return string.encode('utf8').lower().decode('utf8')
def element_has_link_type(element, link_type):
"""
Return whether the given element has a ``rel`` attribute with the
given link type.
:param link_type: Must be a lower-case string.
"""
return any(ascii_lower(token) == link_type for token in
HTML_SPACE_SEPARATED_TOKENS_RE.findall(element.get('rel', '')))
# Maps HTML tag names to function taking an HTML element and returning a Box.
HTML_HANDLERS = {}
def handle_element(element, box, get_image_from_uri, base_url):
"""Handle HTML elements that need special care.
:returns: a (possibly empty) list of boxes.
"""
if box.element_tag in HTML_HANDLERS:
return HTML_HANDLERS[element.tag](
element, box, get_image_from_uri, base_url)
else:
return [box]
def handler(tag):
"""Return a decorator registering a function handling ``tag`` elements."""
def decorator(function):
"""Decorator registering a function handling ``tag`` elements."""
HTML_HANDLERS[tag] = function
return function
return decorator
def make_replaced_box(element, box, image):
"""Wrap an image in a replaced box.
That box is either block-level or inline-level, depending on what the
element should be.
"""
if box.style.display in ('block', 'list-item', 'table'):
type_ = boxes.BlockReplacedBox
else:
# TODO: support images with 'display: table-cell'?
type_ = boxes.InlineReplacedBox
return type_(element.tag, box.style, image)
@handler('img')
def handle_img(element, box, get_image_from_uri, base_url):
"""Handle ```` elements, return either an image or the alt-text.
See: http://www.w3.org/TR/html5/embedded-content-1.html#the-img-element
"""
src = get_url_attribute(element, 'src', base_url)
alt = element.get('alt')
if src:
image = get_image_from_uri(src)
if image is not None:
return [make_replaced_box(element, box, image)]
else:
# Invalid image, use the alt-text.
if alt:
box.children = [boxes.TextBox.anonymous_from(box, alt)]
return [box]
elif alt == '':
# The element represents nothing
return []
else:
assert alt is None
# TODO: find some indicator that an image is missing.
# For now, just remove the image.
return []
else:
if alt:
box.children = [boxes.TextBox.anonymous_from(box, alt)]
return [box]
else:
return []
@handler('embed')
def handle_embed(element, box, get_image_from_uri, base_url):
"""Handle ``