1
1
mirror of https://github.com/Kozea/WeasyPrint.git synced 2024-09-11 20:47:56 +03:00

Minor changes

Improvements provided by refurb.
This commit is contained in:
Guillaume Ayoub 2022-10-05 18:22:35 +02:00
parent 863b3d677f
commit c9c9b3da9d
15 changed files with 43 additions and 52 deletions

View File

@ -123,13 +123,13 @@ class StyleFor:
if ('table' in style['display'] and if ('table' in style['display'] and
style['border_collapse'] == 'collapse'): style['border_collapse'] == 'collapse'):
# Padding do not apply # Padding do not apply
for side in ['top', 'bottom', 'left', 'right']: for side in ('top', 'bottom', 'left', 'right'):
style[f'padding_{side}'] = computed_values.ZERO_PIXELS style[f'padding_{side}'] = computed_values.ZERO_PIXELS
if (len(style['display']) == 1 and if (len(style['display']) == 1 and
style['display'][0].startswith('table-') and style['display'][0].startswith('table-') and
style['display'][0] != 'table-caption'): style['display'][0] != 'table-caption'):
# Margins do not apply # Margins do not apply
for side in ['top', 'bottom', 'left', 'right']: for side in ('top', 'bottom', 'left', 'right'):
style[f'margin_{side}'] = computed_values.ZERO_PIXELS style[f'margin_{side}'] = computed_values.ZERO_PIXELS
return style return style

View File

@ -1,6 +1,7 @@
"""Convert specified property values into computed values.""" """Convert specified property values into computed values."""
from collections import OrderedDict from collections import OrderedDict
from contextlib import suppress
from math import pi from math import pi
from urllib.parse import unquote from urllib.parse import unquote
@ -228,11 +229,9 @@ def compute_variable(value, name, computed, base_url, parent_style):
# See https://drafts.csswg.org/css-variables/#invalid-variables # See https://drafts.csswg.org/css-variables/#invalid-variables
if new_value is None: if new_value is None:
try: with suppress(BaseException):
computed_value = ''.join( computed_value = ''.join(
token.serialize() for token in computed_value) token.serialize() for token in computed_value)
except BaseException:
pass
LOGGER.warning( LOGGER.warning(
'Unsupported computed value "%s" set in variable %r ' 'Unsupported computed value "%s" set in variable %r '
'for property %r.', computed_value, 'for property %r.', computed_value,

View File

@ -167,7 +167,7 @@ def font_weight(token):
if keyword in ('normal', 'bold'): if keyword in ('normal', 'bold'):
return keyword return keyword
if token.type == 'number' and token.int_value is not None: if token.type == 'number' and token.int_value is not None:
if token.int_value in [100, 200, 300, 400, 500, 600, 700, 800, 900]: if token.int_value in (100, 200, 300, 400, 500, 600, 700, 800, 900):
return token.int_value return token.int_value

View File

@ -122,7 +122,7 @@ class Box:
""" """
# Overridden in ParentBox to also translate children, if any. # Overridden in ParentBox to also translate children, if any.
if dx == 0 and dy == 0: if dx == dy == 0:
return return
self.position_x += dx self.position_x += dx
self.position_y += dy self.position_y += dy
@ -224,12 +224,12 @@ class Box:
# See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap # See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap
ratio = min([1] + [ ratio = min([1] + [
extent / sum_radii extent / sum_radii
for extent, sum_radii in [ for extent, sum_radii in (
(width, tlrx + trrx), (width, tlrx + trrx),
(width, blrx + brrx), (width, blrx + brrx),
(height, tlry + blry), (height, tlry + blry),
(height, trry + brry), (height, trry + brry),
] )
if sum_radii > 0 if sum_radii > 0
]) ])
return ( return (

View File

@ -21,7 +21,7 @@ class AbsolutePlaceholder:
object.__setattr__(self, '_layout_done', True) object.__setattr__(self, '_layout_done', True)
def translate(self, dx=0, dy=0, ignore_floats=False): def translate(self, dx=0, dy=0, ignore_floats=False):
if dx == 0 and dy == 0: if dx == dy == 0:
return return
if self._layout_done: if self._layout_done:
self._box.translate(dx, dy, ignore_floats) self._box.translate(dx, dy, ignore_floats)

View File

@ -185,7 +185,7 @@ def block_level_width(box, containing_block):
width = box.width = cb_width - ( width = box.width = cb_width - (
paddings_plus_borders + margin_l + margin_r) paddings_plus_borders + margin_l + margin_r)
margin_sum = cb_width - paddings_plus_borders - width margin_sum = cb_width - paddings_plus_borders - width
if margin_l == 'auto' and margin_r == 'auto': if margin_l == margin_r == 'auto':
box.margin_left = margin_sum / 2 box.margin_left = margin_sum / 2
box.margin_right = margin_sum / 2 box.margin_right = margin_sum / 2
elif margin_l == 'auto' and margin_r != 'auto': elif margin_l == 'auto' and margin_r != 'auto':
@ -750,9 +750,9 @@ def block_container_layout(context, box, bottom_space, skip_stack,
# Top and bottom margins of this box # Top and bottom margins of this box
if (box.height in ('auto', 0) and if (box.height in ('auto', 0) and
get_clearance(context, box, collapsed_margin) is None and get_clearance(context, box, collapsed_margin) is None and
all(value == 0 for value in [ all(value == 0 for value in (
box.min_height, box.border_top_width, box.padding_top, box.min_height, box.border_top_width, box.padding_top,
box.border_bottom_width, box.padding_bottom])): box.border_bottom_width, box.padding_bottom))):
collapsing_through = True collapsing_through = True
else: else:
position_y += collapsed_margin position_y += collapsed_margin

View File

@ -506,7 +506,7 @@ def split_inline_level(context, box, position_x, max_x, bottom_space,
elif isinstance(box, boxes.InlineFlexBox): elif isinstance(box, boxes.InlineFlexBox):
box.position_x = position_x box.position_x = position_x
box.position_y = 0 box.position_y = 0
for side in ['top', 'right', 'bottom', 'left']: for side in ('top', 'right', 'bottom', 'left'):
if getattr(box, f'margin_{side}') == 'auto': if getattr(box, f'margin_{side}') == 'auto':
setattr(box, f'margin_{side}', 0) setattr(box, f'margin_{side}', 0)
new_box, resume_at, _, _, _ = flex_layout( new_box, resume_at, _, _, _ = flex_layout(

View File

@ -123,7 +123,7 @@ def compute_fixed_dimension(context, box, outer, vertical, top_or_left):
# Rule 2 # Rule 2
total = box.padding_plus_border + sum( total = box.padding_plus_border + sum(
value for value in [box.margin_a, box.margin_b, box.inner] value for value in (box.margin_a, box.margin_b, box.inner)
if value != 'auto') if value != 'auto')
if total > outer: if total > outer:
if box.margin_a == 'auto': if box.margin_a == 'auto':
@ -163,7 +163,7 @@ def compute_fixed_dimension(context, box, outer, vertical, top_or_left):
box.inner = (outer - box.padding_plus_border - box.inner = (outer - box.padding_plus_border -
box.margin_a - box.margin_b) box.margin_a - box.margin_b)
# Rule 6 # Rule 6
if box.margin_a == 'auto' and box.margin_b == 'auto': if box.margin_a == box.margin_b == 'auto':
box.margin_a = box.margin_b = ( box.margin_a = box.margin_b = (
outer - box.padding_plus_border - box.inner) / 2 outer - box.padding_plus_border - box.inner) / 2
@ -362,7 +362,7 @@ def make_margin_boxes(context, page, state):
# https://drafts.csswg.org/css-page-3/#margin-box-dimensions # https://drafts.csswg.org/css-page-3/#margin-box-dimensions
generated_boxes = [] generated_boxes = []
for prefix, vertical, containing_block, position_x, position_y in [ for prefix, vertical, containing_block, position_x, position_y in (
('top', False, (max_box_width, margin_top), ('top', False, (max_box_width, margin_top),
margin_left, 0), margin_left, 0),
('bottom', False, (max_box_width, margin_bottom), ('bottom', False, (max_box_width, margin_bottom),
@ -371,7 +371,7 @@ def make_margin_boxes(context, page, state):
0, margin_top), 0, margin_top),
('right', True, (margin_right, max_box_height), ('right', True, (margin_right, max_box_height),
page_end_x, margin_top), page_end_x, margin_top),
]: ):
if vertical: if vertical:
suffixes = ['top', 'middle', 'bottom'] suffixes = ['top', 'middle', 'bottom']
fixed_outer, variable_outer = containing_block fixed_outer, variable_outer = containing_block
@ -399,18 +399,18 @@ def make_margin_boxes(context, page, state):
variable_outer - box.margin_width()) variable_outer - box.margin_width())
compute_fixed_dimension( compute_fixed_dimension(
context, box, fixed_outer, not vertical, context, box, fixed_outer, not vertical,
prefix in ['top', 'left']) prefix in ('top', 'left'))
generated_boxes.append(box) generated_boxes.append(box)
# Corner boxes # Corner boxes
for at_keyword, cb_width, cb_height, position_x, position_y in [ for at_keyword, cb_width, cb_height, position_x, position_y in (
('@top-left-corner', margin_left, margin_top, 0, 0), ('@top-left-corner', margin_left, margin_top, 0, 0),
('@top-right-corner', margin_right, margin_top, page_end_x, 0), ('@top-right-corner', margin_right, margin_top, page_end_x, 0),
('@bottom-left-corner', margin_left, margin_bottom, 0, page_end_y), ('@bottom-left-corner', margin_left, margin_bottom, 0, page_end_y),
('@bottom-right-corner', margin_right, margin_bottom, ('@bottom-right-corner', margin_right, margin_bottom,
page_end_x, page_end_y), page_end_x, page_end_y),
]: ):
box = make_box(at_keyword, (cb_width, cb_height)) box = make_box(at_keyword, (cb_width, cb_height))
if not box.is_generated: if not box.is_generated:
continue continue

View File

@ -93,7 +93,7 @@ def resolve_percentages(box, containing_block, main_flex_direction=None):
box, 'max_height', cb_height, main_flex_direction) box, 'max_height', cb_height, main_flex_direction)
# Used value == computed value # Used value == computed value
for side in ['top', 'right', 'bottom', 'left']: for side in ('top', 'right', 'bottom', 'left'):
prop = f'border_{side}_width' prop = f'border_{side}_width'
setattr(box, prop, box.style[prop]) setattr(box, prop, box.style[prop])

View File

@ -226,8 +226,7 @@ def column_group_content_width(context, box):
def table_cell_min_content_width(context, box, outer): def table_cell_min_content_width(context, box, outer):
"""Return the min-content width for a ``TableCellBox``.""" """Return the min-content width for a ``TableCellBox``."""
children_widths = [ children_widths = [
min_content_width(context, child, outer=True) min_content_width(context, child) for child in box.children
for child in box.children
if not child.is_absolutely_positioned()] if not child.is_absolutely_positioned()]
children_min_width = margin_width( children_min_width = margin_width(
box, max(children_widths) if children_widths else 0) box, max(children_widths) if children_widths else 0)
@ -408,11 +407,9 @@ def table_and_columns_preferred_widths(context, box, outer=True):
min_width = block_min_content_width(context, table, outer=False) min_width = block_min_content_width(context, table, outer=False)
max_width = block_max_content_width(context, table, outer=False) max_width = block_max_content_width(context, table, outer=False)
outer_min_width = adjust( outer_min_width = adjust(
box, outer=True, width=block_min_content_width( box, outer=True, width=block_min_content_width(context, table))
context, table, outer=True))
outer_max_width = adjust( outer_max_width = adjust(
box, outer=True, width=block_max_content_width( box, outer=True, width=block_max_content_width(context, table))
context, table, outer=True))
result = ([], [], [], [], total_horizontal_border_spacing, []) result = ([], [], [], [], total_horizontal_border_spacing, [])
context.tables[table] = result = { context.tables[table] = result = {
False: (min_width, max_width) + result, False: (min_width, max_width) + result,
@ -698,7 +695,7 @@ def flex_min_content_width(context, box, outer=True):
# TODO: use real values, see # TODO: use real values, see
# https://www.w3.org/TR/css-flexbox-1/#intrinsic-sizes # https://www.w3.org/TR/css-flexbox-1/#intrinsic-sizes
min_contents = [ min_contents = [
min_content_width(context, child, outer=True) min_content_width(context, child)
for child in box.children if child.is_flex_item] for child in box.children if child.is_flex_item]
if not min_contents: if not min_contents:
return adjust(box, outer, 0) return adjust(box, outer, 0)
@ -714,7 +711,7 @@ def flex_max_content_width(context, box, outer=True):
# TODO: use real values, see # TODO: use real values, see
# https://www.w3.org/TR/css-flexbox-1/#intrinsic-sizes # https://www.w3.org/TR/css-flexbox-1/#intrinsic-sizes
max_contents = [ max_contents = [
max_content_width(context, child, outer=True) max_content_width(context, child)
for child in box.children if child.is_flex_item] for child in box.children if child.is_flex_item]
if not max_contents: if not max_contents:
return adjust(box, outer, 0) return adjust(box, outer, 0)

View File

@ -99,7 +99,7 @@ def replacedbox_layout(box):
if object_fit == 'fill': if object_fit == 'fill':
draw_width, draw_height = box.width, box.height draw_width, draw_height = box.width, box.height
else: else:
if object_fit == 'contain' or object_fit == 'scale-down': if object_fit in ('contain', 'scale-down'):
draw_width, draw_height = contain_constraint_image_sizing( draw_width, draw_height = contain_constraint_image_sizing(
box.width, box.height, intrinsic_ratio) box.width, box.height, intrinsic_ratio)
elif object_fit == 'cover': elif object_fit == 'cover':
@ -140,7 +140,7 @@ def replaced_box_width(box, containing_block):
# This algorithm simply follows the different points of the specification: # This algorithm simply follows the different points of the specification:
# https://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width # https://www.w3.org/TR/CSS21/visudet.html#inline-replaced-width
if box.height == 'auto' and box.width == 'auto': if box.height == box.width == 'auto':
if width is not None: if width is not None:
# Point #1 # Point #1
box.width = width box.width = width
@ -173,12 +173,12 @@ def replaced_box_height(box):
box.style['image_resolution'], box.style['font_size']) box.style['image_resolution'], box.style['font_size'])
# Test 'auto' on the computed width, not the used width # Test 'auto' on the computed width, not the used width
if box.height == 'auto' and box.width == 'auto': if box.height == box.width == 'auto':
box.height = height box.height = height
elif box.height == 'auto' and ratio: elif box.height == 'auto' and ratio:
box.height = box.width / ratio box.height = box.width / ratio
if box.height == 'auto' and box.width == 'auto' and height is not None: if box.height == box.width == 'auto' and height is not None:
box.height = height box.height = height
elif ratio is not None and box.height == 'auto': elif ratio is not None and box.height == 'auto':
box.height = box.width / ratio box.height = box.width / ratio
@ -191,14 +191,14 @@ def replaced_box_height(box):
def inline_replaced_box_layout(box, containing_block): def inline_replaced_box_layout(box, containing_block):
"""Lay out an inline :class:`boxes.ReplacedBox` ``box``.""" """Lay out an inline :class:`boxes.ReplacedBox` ``box``."""
for side in ['top', 'right', 'bottom', 'left']: for side in ('top', 'right', 'bottom', 'left'):
if getattr(box, f'margin_{side}') == 'auto': if getattr(box, f'margin_{side}') == 'auto':
setattr(box, f'margin_{side}', 0) setattr(box, f'margin_{side}', 0)
inline_replaced_box_width_height(box, containing_block) inline_replaced_box_width_height(box, containing_block)
def inline_replaced_box_width_height(box, containing_block): def inline_replaced_box_width_height(box, containing_block):
if box.style['width'] == 'auto' and box.style['height'] == 'auto': if box.style['width'] == box.style['height'] == 'auto':
replaced_box_width.without_min_max(box, containing_block) replaced_box_width.without_min_max(box, containing_block)
replaced_box_height.without_min_max(box) replaced_box_height.without_min_max(box)
min_max_auto_replaced(box) min_max_auto_replaced(box)
@ -269,7 +269,7 @@ def block_replaced_box_layout(context, box, containing_block):
from .float import avoid_collisions from .float import avoid_collisions
box = box.copy() box = box.copy()
if box.style['width'] == 'auto' and box.style['height'] == 'auto': if box.style['width'] == box.style['height'] == 'auto':
computed_margins = box.margin_left, box.margin_right computed_margins = box.margin_left, box.margin_right
block_replaced_width.without_min_max( block_replaced_width.without_min_max(
box, containing_block) box, containing_block)

View File

@ -1,6 +1,7 @@
"""Render SVG images.""" """Render SVG images."""
import re import re
from contextlib import suppress
from math import cos, hypot, pi, radians, sin, sqrt from math import cos, hypot, pi, radians, sin, sqrt
from xml.etree import ElementTree from xml.etree import ElementTree
@ -415,10 +416,8 @@ class SVG:
# Draw node # Draw node
if visible and node.tag in TAGS: if visible and node.tag in TAGS:
try: with suppress(PointError):
TAGS[node.tag](self, node, font_size) TAGS[node.tag](self, node, font_size)
except PointError:
pass
# Draw node children # Draw node children
if display and node.tag not in DEF_TYPES: if display and node.tag not in DEF_TYPES:

View File

@ -252,7 +252,7 @@ def _bounding_box_elliptical_arc(x1, y1, rx, ry, phi, large, sweep, x, y):
cx = cxprime * cos(phi) - cyprime * sin(phi) + (x1 + x) / 2 cx = cxprime * cos(phi) - cyprime * sin(phi) + (x1 + x) / 2
cy = cxprime * sin(phi) + cyprime * cos(phi) + (y1 + y) / 2 cy = cxprime * sin(phi) + cyprime * cos(phi) + (y1 + y) / 2
if phi == 0 or phi == pi: if phi in (0, pi):
minx = cx - rx minx = cx - rx
tminx = atan2(0, -rx) tminx = atan2(0, -rx)
maxx = cx + rx maxx = cx + rx
@ -261,7 +261,7 @@ def _bounding_box_elliptical_arc(x1, y1, rx, ry, phi, large, sweep, x, y):
tminy = atan2(-ry, 0) tminy = atan2(-ry, 0)
maxy = cy + ry maxy = cy + ry
tmaxy = atan2(ry, 0) tmaxy = atan2(ry, 0)
elif phi == pi / 2 or phi == 3 * pi / 2: elif phi in (pi / 2, 3 * pi / 2):
minx = cx - ry minx = cx - ry
tminx = atan2(0, -ry) tminx = atan2(0, -ry)
maxx = cx + ry maxx = cx + ry

View File

@ -1,6 +1,7 @@
"""Util functions for SVG rendering.""" """Util functions for SVG rendering."""
import re import re
from contextlib import suppress
from math import cos, radians, sin, tan from math import cos, radians, sin, tan
from urllib.parse import urlparse from urllib.parse import urlparse
@ -29,12 +30,10 @@ def size(string, font_size=None, percentage_reference=None):
if not string: if not string:
return 0 return 0
try: with suppress(ValueError):
return float(string) return float(string)
except ValueError:
# Not a float, try something else
pass
# Not a float, try something else
string = normalize(string).split(' ', 1)[0] string = normalize(string).split(' ', 1)[0]
if string.endswith('%'): if string.endswith('%'):
assert percentage_reference is not None assert percentage_reference is not None

View File

@ -1,6 +1,7 @@
"""Imports of dynamic libraries used for text layout.""" """Imports of dynamic libraries used for text layout."""
import os import os
from contextlib import suppress
import cffi import cffi
@ -391,10 +392,8 @@ ffi.cdef('''
def _dlopen(ffi, *names): def _dlopen(ffi, *names):
"""Try various names for the same library, for different platforms.""" """Try various names for the same library, for different platforms."""
for name in names: for name in names:
try: with suppress(OSError):
return ffi.dlopen(name) return ffi.dlopen(name)
except OSError:
pass
# Re-raise the exception. # Re-raise the exception.
print( print(
'\n-----\n\n' '\n-----\n\n'
@ -413,10 +412,8 @@ if hasattr(os, 'add_dll_directory'): # pragma: no cover
'WEASYPRINT_DLL_DIRECTORIES', 'WEASYPRINT_DLL_DIRECTORIES',
'C:\\Program Files\\GTK3-Runtime Win64\\bin').split(';') 'C:\\Program Files\\GTK3-Runtime Win64\\bin').split(';')
for dll_directory in dll_directories: for dll_directory in dll_directories:
try: with suppress((OSError, FileNotFoundError)):
os.add_dll_directory(dll_directory) os.add_dll_directory(dll_directory)
except (OSError, FileNotFoundError):
pass
gobject = _dlopen( gobject = _dlopen(
ffi, 'gobject-2.0-0', 'gobject-2.0', 'libgobject-2.0-0', ffi, 'gobject-2.0-0', 'gobject-2.0', 'libgobject-2.0-0',