Skip to content

Commit

Permalink
Cache font key instead of whole font content
Browse files Browse the repository at this point in the history
  • Loading branch information
liZe authored and okkays committed May 1, 2024
1 parent 365960c commit 4693087
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
12 changes: 2 additions & 10 deletions weasyprint/pdf/stream.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""PDF stream."""

import io
from functools import lru_cache
from hashlib import md5

import pydyf
Expand All @@ -13,7 +12,7 @@
from ..matrix import Matrix
from ..text.constants import PANGO_STRETCH_PERCENT
from ..text.ffi import ffi, harfbuzz, pango, units_to_double
from ..text.fonts import get_hb_face_data, get_pango_font_hb_face
from ..text.fonts import get_hb_face_data, get_pango_font_hb_face, get_pango_font_key


class Font:
Expand Down Expand Up @@ -323,15 +322,8 @@ def set_blend_mode(self, mode):
'BM': f'/{mode}',
}))

@lru_cache()
def add_font(self, pango_font):
description = pango.pango_font_describe(pango_font)
mask = (
pango.PANGO_FONT_MASK_SIZE +
pango.PANGO_FONT_MASK_GRAVITY)
pango.pango_font_description_unset_fields(description, mask)
key = pango.pango_font_description_hash(description)
pango.pango_font_description_free(description)
key = get_pango_font_key(pango_font)
if key not in self._fonts:
self._fonts[key] = Font(pango_font)
return self._fonts[key]
Expand Down
16 changes: 15 additions & 1 deletion weasyprint/text/fonts.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Interface with external libraries managing fonts installed on the system."""

from functools import lru_cache
from hashlib import md5
from io import BytesIO
from pathlib import Path
Expand Down Expand Up @@ -364,7 +365,7 @@ def get_pango_font_hb_face(pango_font):
return pangoft2.pango_fc_font_map_get_hb_face(fontmap, fc_font)


def get_hb_face_blob_data(hb_face, ot_color=None):
def get_hb_face_data(hb_face, ot_color=None):
"""Get binary data out of given Harfbuzz face.
If ``ot_color`` is 'svg', return the SVG color glyph reference. If it’s 'png',
Expand All @@ -382,3 +383,16 @@ def get_hb_face_blob_data(hb_face, ot_color=None):
hb_data = harfbuzz.hb_blob_get_data(hb_blob, length)
if hb_data != ffi.NULL:
return ffi.unpack(hb_data, int(length[0]))


@lru_cache()
def get_pango_font_key(pango_font):
"""Get key corresponding to given Pango font."""
description = ffi.gc(
pango.pango_font_describe(pango_font),
pango.pango_font_description_free)
mask = (
pango.PANGO_FONT_MASK_SIZE +
pango.PANGO_FONT_MASK_GRAVITY)
pango.pango_font_description_unset_fields(description, mask)
return pango.pango_font_description_hash(description)

0 comments on commit 4693087

Please sign in to comment.