Normal
  B   ˆl–Ãa¾”*n-j�jã.\ŠbÑ¿�þJ'€³e}·Â6†á^óÈ„m×ÞkÅ_ŠI|¥�+Wé3ž¯ÄÃ ?÷     """
    cairocffi.surface
    ~~~~~~~~~~~~~~~~~

    Bindings for the various types of surface objects.

    :copyright: Copyright 2013-2019 by Simon Sapin
    :license: BSD, see LICENSE for details.

"""

import ctypes
import io
import operator
import os
import sys
import weakref
from functools import reduce
from pathlib import Path
from tempfile import NamedTemporaryFile

from . import _check_status, _keepref, cairo, constants, ffi
from .fonts import FontOptions, _encode_string

SURFACE_TARGET_KEY = ffi.new('cairo_user_data_key_t *')


def _make_read_func(file_obj):
    """Return a CFFI callback that reads from a file-like object."""
    @ffi.callback("cairo_read_func_t", error=constants.STATUS_READ_ERROR)
    def read_func(_closure, data, length):
        string = file_obj.read(length)
        if len(string) < length:  # EOF too early
            return constants.STATUS_READ_ERROR
        ffi.buffer(data, length)[:len(string)] = string
        return constants.STATUS_SUCCESS
    return read_func


def _make_write_func(file_obj):
    """Return a CFFI callback that writes to a file-like object."""
    if file_obj is None:
        return ffi.NULL

    @ffi.callback("cairo_write_func_t", error=constants.STATUS_WRITE_ERROR)
    def write_func(_closure, data, length):
        file_obj.write(ffi.buffer(data, length))
        return constants.STATUS_SUCCESS
    return write_func


def _encode_filename(filename):  # pragma: no cover
    """Return a byte string suitable for a filename.

    Unicode is encoded using an encoding adapted to what both cairo and the
    filesystem want.

    """
    # Don't replace unknown characters as '?' is forbidden in Windows filenames
    errors = 'ignore' if os.name == 'nt' else 'replace'

    if not isinstance(filename, bytes):
        if os.name == 'nt' and cairo.cairo_version() >= 11510:
            # Since 1.15.10, cairo uses utf-8 filenames on Windows
            filename = filename.encode('utf-8', errors=errors)
        else:
            try:
                filename = filename.encode(sys.getfilesystemencoding())
            except UnicodeEncodeError:
                # Use plain ASCII filenames as fallback
                filename = filename.encode('ascii', errors=errors)

    # TODO: avoid characters forbidden in filenames?
    return ffi.new('char[]', filename)


def from_buffer(obj):
    """Return ``(pointer_address, length_in_bytes)`` for a buffer object."""
    if hasattr(obj, 'buffer_info'):
        # Looks like a array.array object.
        address, length = obj.buffer_info()
        return address, length * obj.itemsize
    elif hasattr(obj, '__array_interface__'):
        # Looks like a numpy.ndarray object
        length = reduce(operator.mul, obj.shape)
        return ctypes.addressof(ctypes.c_char.from_buffer(obj)), length
    else:
        # Other buffers.
        # XXX Unfortunately ctypes.c_char.from_buffer
        # does not have length information,
        # and weâ€™re not sure that len(obj) is measured in bytes.
        # (Itâ€™s not for array.array, though that is taken care of.)
        return ctypes.addressof(ctypes.c_char.from_buffer(obj)), len(obj)


class KeepAlive(object):
    """
    Keep some objects alive until a callback is called.
    :attr:`closure` is a tuple of cairo_destroy_func_t and void* cdata objects,
    as expected by cairo_surface_set_mime_data().

    Either :meth:`save` must be called before the callback,
    or none of them must be called.

    """
    instances = set()

    def __init__(self, *objects):
        self.objects = objects
        weakself = weakref.ref(self)

        def closure(_):
            value = weakself()
            if value is not None:
                value.instances.remove(value)

        callback = ffi.callback(
            'cairo_destroy_func_t', closure)
        # cairo wants a non-NULL closure pointer.
        self.closure = (callback, callback)

    def save(self):
        """Start keeping a reference to the passed objects.