Source code elsie/render/backends/cairo/rcontext.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import io
import math

import cairocffi as cairo
import lxml.etree as et
import pangocairocffi
from PIL import Image

from ....text.textstyle import TextStyle
from ....utils.geom import Rect, find_centroid
from ..rcontext import RenderingContext
from .draw import (
    apply_viewbox,
    ctx_scope,
    fill_shape,
    fill_stroke_shape,
    rounded_rectangle,
    stroke_shape,
    transform,
)
from .shapes import draw_path
from .svg import render_svg
from .text import (
    build_layout,
    compute_subtext_extents,
    from_pango_units,
    get_extents,
    to_pango_units,
)
from .utils import normalize_svg

TARGET_DPI = 96
CAIRO_DPI = 72

# DPI scaling: 72 (cairo) vs 96 (Inkscape)
RESOLUTION_SCALE = CAIRO_DPI / TARGET_DPI


class CairoRenderingContext(RenderingContext):
    def __init__(
        self,
        width: int,
        height: int,
        filename: str = None,
        export_format: str = "pdf",
        viewbox=None,
        step=1,
        debug_boxes=False,
    ):
        super().__init__(step, debug_boxes)

        self.width = width
        self.height = height
        self.device_width = width * RESOLUTION_SCALE
        self.device_height = height * RESOLUTION_SCALE
        self.filename = filename

        if export_format == "pdf":
            self.surface = cairo.PDFSurface(
                self.filename, self.device_width, self.device_height
            )
            self.reference_ctx = self.ctx = cairo.Context(self.surface)
            self.ctx.scale(RESOLUTION_SCALE, RESOLUTION_SCALE)
            self.cairosvg_dpi = TARGET_DPI
        elif export_format == "png":
            self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
            self.ctx = cairo.Context(self.surface)
            self.ctx.set_source_rgba(0, 0, 0, 255)
            reference_surface = cairo.PDFSurface(
                None, self.device_width, self.device_height
            )
            self.reference_ctx = cairo.Context(reference_surface)
            self.reference_ctx.scale(RESOLUTION_SCALE, RESOLUTION_SCALE)
            self.cairosvg_dpi = CAIRO_DPI
        else:
            assert False

        self.line_scaling = 1.0
        if viewbox:
            self.line_scaling = apply_viewbox(self.ctx, width, height, viewbox)

        self.pctx = pangocairocffi.create_context(self.reference_ctx)

    def draw_rect(
        self,
        rect: Rect,
        rx=None,
        ry=None,
        rotation=None,
        **kwargs,
    ):
        if rx is None:
            rx = ry
        if ry is None:
            ry = rx

        with ctx_scope(self.ctx):
            transform(self.ctx, rect.mid_point, rotation)

            def draw():
                self.ctx.rectangle(rect.x, rect.y, rect.width, rect.height)

            def draw_rounded():
                rounded_rectangle(
                    self.ctx, rect.x, rect.y, rect.width, rect.height, rx, ry
                )

            draw_fn = draw_rounded if rx or ry else draw
            fill_stroke_shape(self.ctx, draw_fn, **kwargs)

    def draw_ellipse(
        self, rect: Rect, rotation=None, color=None, bg_color=None, **kwargs
    ):
        dim_larger = rect.width
        dim_smaller = rect.height
        if dim_larger < dim_smaller:
            dim_larger, dim_smaller = dim_smaller, dim_larger
        scale_x = 1.0 if dim_larger == rect.width else dim_smaller / dim_larger
        scale_y = 1.0 if dim_larger == rect.height else dim_smaller / dim_larger
        center = rect.mid_point

        def draw():
            self.ctx.arc(center[0], center[1], dim_larger / 2.0, 0, 2 * math.pi)

        with ctx_scope(self.ctx):
            transform(
                self.ctx, center, rotation=rotation, scale_x=scale_x, scale_y=scale_y
            )
            if bg_color:
                fill_shape(self.ctx, draw, bg_color=bg_color)
            if color:
                draw()
        # Do not apply transform to stroke (https://www.cairographics.org/cookbook/ellipses/)
        if color:
            stroke_shape(self.ctx, lambda: ..., color=color, **kwargs)

    def draw_polygon(self, points, rotation=None, **kwargs):
        with ctx_scope(self.ctx):
            transform(self.ctx, find_centroid(points), rotation=rotation)

            def draw():
                self.ctx.move_to(*points[0])
                for p in points[1:] + [points[0]]:
                    self.ctx.line_to(*p)

            fill_stroke_shape(self.ctx, draw, **kwargs)

    def draw_polyline(self, points, **kwargs):
        with ctx_scope(self.ctx):

            def draw():
                self.ctx.move_to(*points[0])
                for p in points[1:]:
                    self.ctx.line_to(*p)

            stroke_shape(self.ctx, draw, **kwargs)

    def draw_path(self, commands, **kwargs):
        with ctx_scope(self.ctx):

            def draw():
                draw_path(self.ctx, commands)

            fill_stroke_shape(self.ctx, draw, **kwargs)

    def compute_text_extents(self, parsed_text, style: TextStyle, styles) -> Rect:
        layout = build_layout(
            self.ctx, self.pctx, parsed_text, style, styles, RESOLUTION_SCALE
        )
        return get_extents(layout)

    def compute_subtext_extents(
        self, parsed_text, style: TextStyle, styles, id_index: int
    ) -> Rect:
        from ....text.textboxitem import text_x_in_rect

        layout = build_layout(
            self.ctx, self.pctx, parsed_text, style, styles, RESOLUTION_SCALE
        )
        extents = get_extents(layout)
        start_x = text_x_in_rect(Rect(x=0, width=extents.width), style)
        x, width = compute_subtext_extents(layout, parsed_text, id_index)
        return Rect(x=x - start_x, width=width)

    def draw_text(
        self,
        rect,
        x,
        y,
        parsed_text,
        style: TextStyle,
        styles,
        rotation=None,
        scale=None,
        **kwargs,
    ):
        # TODO: try basic Cairo text API
        with ctx_scope(self.ctx):
            layout = build_layout(
                self.reference_ctx,
                self.pctx,
                parsed_text,
                style,
                styles,
                resolution_scale=RESOLUTION_SCALE,
                spacing_scale=self.line_scaling,
                text_scale=scale,
            )
            layout.set_width(to_pango_units(rect.width))
            baseline = from_pango_units(layout.get_baseline())

            if rotation is not None:
                transform(self.ctx, rect.mid_point, rotation=rotation)
            self.ctx.move_to(rect.x, y - baseline)
            pangocairocffi.show_layout(self.ctx, layout)

    def draw_bitmap(self, x, y, width, height, data, rotation=None, **kwargs):
        assert isinstance(data, bytes)
        image = Image.open(io.BytesIO(data))
        if image.mode != "RGBA":
            image = image.convert("RGBA")
        img_width, img_height = image.width, image.height

        data = bytearray(image.tobytes("raw", "BGRa"))
        surface = cairo.ImageSurface(
            cairo.FORMAT_ARGB32, width=img_width, height=img_height, data=data
        )
        surface.set_device_scale(img_width / width, img_height / height)

        center = (x + width / 2, y + height / 2)
        with ctx_scope(self.ctx):
            transform(self.ctx, center, rotation=rotation)
            self.ctx.set_source_surface(surface, x, y)
            self.ctx.move_to(x, y)
            self.ctx.paint()

    def draw_svg(
        self,
        svg,
        x,
        y,
        width,
        height,
        rotation=None,
        **kwargs,
    ):
        root = et.fromstring(svg)
        normalized = normalize_svg(root)
        normalized_svg = et.tostring(normalized, encoding="utf8")
        render_svg(
            self.surface,
            svg=normalized_svg.decode(),
            x=x,
            y=y,
            width=width,
            height=height,
            rotation=rotation,
            dpi=self.cairosvg_dpi,
        )