pax_global_header00006660000000000000000000000064137466316760014535gustar00rootroot0000000000000052 comment=8ffa678b221e8327a84e049651926d8a4138d31e cairocffi-1.2.0/000077500000000000000000000000001374663167600134625ustar00rootroot00000000000000cairocffi-1.2.0/.github/000077500000000000000000000000001374663167600150225ustar00rootroot00000000000000cairocffi-1.2.0/.github/FUNDING.yml000066400000000000000000000001161374663167600166350ustar00rootroot00000000000000# These are supported funding model platforms open_collective: courtbouillon cairocffi-1.2.0/.github/workflows/000077500000000000000000000000001374663167600170575ustar00rootroot00000000000000cairocffi-1.2.0/.github/workflows/tests.yml000066400000000000000000000036431374663167600207520ustar00rootroot00000000000000name: cairocffi's tests on: [push] jobs: tests: name: ${{ matrix.os }} - ${{ matrix.python-version }} runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: os: [ubuntu-latest, macos-latest, windows-latest] python-version: [3.6, 3.7, 3.8, pypy3] exclude: # No wheel for numpy - os: macos-latest python-version: pypy3 - os: windows-latest python-version: pypy3 steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: xvfb daemon (Ubuntu) if: matrix.os == 'ubuntu-latest' run: sudo /sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1024x16 - name: Pip installs (Ubuntu) if: matrix.os == 'ubuntu-latest' run: | python -m pip install -e .[test,xcb] python -m pip install -e .[test] - name: Install cairo gdk-pixbuf (MacOS) if: matrix.os == 'macos-latest' run: | brew update brew pin numpy gdal postgis brew install cairo gdk-pixbuf - name: Install msys2 and DejaVu (Windows) if: matrix.os == 'windows-latest' run: | choco install -y --no-progress msys2 powershell "C:\tools\msys64\usr\bin\bash -lc 'pacman -S mingw-w64-x86_64-ttf-dejavu mingw-w64-x86_64-gtk3 --noconfirm'" xcopy "C:\tools\msys64\mingw64\share\fonts\TTF" "C:\Users\runneradmin\.fonts" /e /i $env:PATH += ";C:\tools\msys64\mingw64\bin" echo "::set-env name=PATH::$env:PATH" - name: Force numpy install binary (Pypy3) if: matrix.python-version == 'pypy3' run: python -m pip install --only-binary ":all:" numpy - name: Launch tests run: python setup.py test cairocffi-1.2.0/.gitignore000066400000000000000000000001621374663167600154510ustar00rootroot00000000000000*.pyc __pycache__ cairocffi/_ffi*.py *.egg *.egg-info /.eggs /dist /.cache /.coverage /.pytest_cache /docs/_build cairocffi-1.2.0/LICENSE000066400000000000000000000027761374663167600145030ustar00rootroot00000000000000BSD 3-Clause License Copyright (c) 2013-2019, Simon Sapin and contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cairocffi-1.2.0/NEWS.rst000066400000000000000000000154521374663167600147770ustar00rootroot00000000000000cairocffi changelog ------------------- Version 1.2.0 ............. Released on 2020-10-29 * `#152 `_: Add NumPy support * `#143 `_: Make write_to_png function work on hardened systems * `#156 `_: Use major version name to open shared libraries * `#165 `_: Don’t list setuptools as required for installation Version 1.1.0 ............. Released on 2019-09-05 * `#135 `_, `#127 `_, `#119 `_: Clean the way external libraries are found * `#126 `_: Remove const char* elements from cdef * Support Cairo features up to 1.17.2 * Fix documentation generation Version 1.0.2 ............. Released on 2019-02-15 * `#123 `_: Rely on a recent version of setuptools to handle VERSION Version 1.0.1 ............. Released on 2019-02-12 * `#120 `_: Don't delete _generated modules on ffi_build import Version 1.0.0 ............. Released on 2019-02-08 6 years after its first release, cairocffi can now be considered as stable. * Drop Python 2.6, 2.7 and 3.4 support * Test with Python 3.7 * Clean code, tests and packaging Version 0.9.0 ............. Released on 2018-08-06 * Drop Python 3.2 and 3.3 support * Test with PyPy and PyPy3 * `#114 `_: Fix test compatibility with Cairo 1.15.12 * `#112 `_: Add cairo library name from PyGObject for Windows * Fix ``pango_example.py`` * `#85 `_: Fix crash with xbc tests * Clean documentation * Support Cairo features up to 1.15.12 Version 0.8.1 ............. Released on 2018-05-30 * `#98 `_: Add width and height options to pixbuf.decode_to_image_surface * `#112 `_: Add cairo library name from PyGObject for Windows Version 0.8.0 ............. Released on 2017-02-03 * Follow semver * `#76 `_: Avoid implicit relative import * `#74 `_: Use utf-8 instead of utf8 in headers * `#73 `_: Keep cairo library loaded until all relevant objects are freed * `#86 `_: Add cairo_quartz_* functions for MacOS * Use the default ReadTheDocs theme * Fix implicit casts Version 0.7.2 ............. Released on 2015-08-04 * Use ctypes.util.find_library with dlopen. Version 0.7.1 ............. Released on 2015-06-22 * Allow installing cairocffi when cffi<1.0 is installed. Version 0.7 ........... Released on 2015-06-05 * `#47 `_: Fix PyPy support. * `#60 `_: Use CFFI-1.0 methods. * `#61 `_: Allow ffi import when package is pip installed. Version 0.6 ........... Released on 2014-09-23. * `#39 `_: Add :class:`xcb.XCBSurface`. * `#42 `_: Add :class:`Win32PrintingSurface`. Version 0.5.4 ............. Released on 2014-05-23. * Stop testing with tox on Python 3.1, start on 3.4 * Start testing pushes and pull requests `on Travis-CI `_ * Add more variants of the library names to try with `dlopen()`. This seems to be necessary on OpenBSD. Version 0.5.3 ............. Released on 2014-03-11. Fix `#28 `_: Add another dynamic library name to try to load, for OS X. Version 0.5.2 ............. Released on 2014-02-27. Fix `#21 `_: ``UnicodeDecodeError`` when installing with a non-UTF-8 locale. Version 0.5.1 ............. Released on 2013-07-16. Fix `#15 `_: Work around `CFFI bug #92 `_ that caused memory leaks when file-like :obj:`target` objects are passed to :meth:`Surface.write_to_png`, :class:`PDFSurface`, :class:`PSSurface` and :class:`SVGSurface`. Version 0.5 ........... Released on 2013-06-20. Change :func:`~cairocffi.pixbuf.decode_to_image_surface` to raise a specific :exc:`~cairocffi.pixbuf.ImageLoadingError` exception instead of a generic :exc:`~exceptions.ValueError`. This new exception type inherits from :exc:`~exceptions.ValueError`. Version 0.4.3 ............. Released on 2013-05-27. * Fix `#10 `_: Pretend to be pycairo 1.10.0, for compatibility with matplotlib which does version detection. * Fix `WeasyPrint#94 `_: Make (again??) GTK acutally optional for PixBuf support. Version 0.4.2 ............. Released on 2013-05-03. * Fix `#9 `_: Make GTK acutally optional for PixBuf support. Version 0.4.1 ............. Released on 2013-04-30. * Various documentation improvements * Bug fixes: * Fix error handling in :meth:`ImageSurface.create_from_png`. * Fix :meth:`ScaledFont.text_to_glyphs` and :meth:`Context.show_text_glyphs` with new-style enums. Version 0.4 ........... Released on 2013-04-06. No change since 0.3.1, but depend on CFFI < 0.6 because of backward-incompatible changes. cairocffi 0.4 will require CFFI 0.6 or more. .. code-block:: python # Before cairocffi 0.4: surface = cairocffi.ImageSurface('ARGB32', 300, 400) # All cairocffi versions: surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) * Compatibility with CFFI 0.6 Version 0.3.2 ............. Released on 2013-03-29. No change since 0.3.1, but depend on CFFI < 0.6 because of backward-incompatible changes. cairocffi 0.4 will require CFFI 0.6 or more. Version 0.3.1 ............. Released on 2013-03-18. Fix handling of GDK-PixBuf errors. Version 0.3 ........... Released on 2013-02-26. * Add :mod:`cairocffi.pixbuf`, for loading images with GDK-PixBuf. * Add iteration and item access on :class:`Matrix`. * Better `Windows support`_ by trying to load ``libcairo-2.dll`` .. _Windows support: http://packages.python.org/cairocffi/overview.html#installing-cairo-on-windows Version 0.2 ........... Released on 2013-01-08. Added :class:`RecordingSurface`. Version 0.1 ........... Released on 2013-01-07. First PyPI release. cairocffi-1.2.0/README.rst000066400000000000000000000030761374663167600151570ustar00rootroot00000000000000cairocffi is a `CFFI`_-based drop-in replacement for Pycairo_, a set of Python bindings and object-oriented API for cairo_. Cairo is a 2D vector graphics library with support for multiple backends including image buffers, PNG, PostScript, PDF, and SVG file output. Additionally, the ``cairocffi.pixbuf`` module uses GDK-PixBuf_ to decode various image formats for use in cairo. .. _CFFI: https://cffi.readthedocs.org/ .. _Pycairo: https://pycairo.readthedocs.io/ .. _cairo: http://cairographics.org/ .. _GDK-PixBuf: https://gitlab.gnome.org/GNOME/gdk-pixbuf * Free software: BSD license * For Python 3.6+, tested on CPython and PyPy * Documentation: https://cairocffi.readthedocs.io * Changelog: https://github.com/Kozea/cairocffi/releases * Code, issues, tests: https://github.com/Kozea/cairocffi * Code of conduct: https://www.courtbouillon.org/code-of-conduct * Professional support: https://www.courtbouillon.org * Donation: https://opencollective.com/courtbouillon * API partially compatible with Pycairo. * Works with any version of cairo. cairocffi has been created and developed by Kozea (https://kozea.fr). Professional support, maintenance and community management is provided by CourtBouillon (https://www.courtbouillon.org). Copyrights are retained by their contributors, no copyright assignment is required to contribute to cairocffi. Unless explicitly stated otherwise, any contribution intentionally submitted for inclusion is licensed under the BSD 3-clause license, without any additional terms or conditions. For full authorship information, see the version control history. cairocffi-1.2.0/cairocffi/000077500000000000000000000000001374663167600154075ustar00rootroot00000000000000cairocffi-1.2.0/cairocffi/VERSION000066400000000000000000000000051374663167600164520ustar00rootroot000000000000001.2.0cairocffi-1.2.0/cairocffi/__init__.py000066400000000000000000000100001374663167600175070ustar00rootroot00000000000000""" cairocffi ~~~~~~~~~ CFFI-based cairo bindings for Python. See README for details. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import sys from ctypes.util import find_library from pathlib import Path from . import constants from ._generated.ffi import ffi VERSION = __version__ = (Path(__file__).parent / 'VERSION').read_text().strip() # supported version of cairo, used to be pycairo version too: version = '1.17.2' version_info = (1, 17, 2) def dlopen(ffi, library_names, filenames): """Try various names for the same library, for different platforms.""" exceptions = [] for library_name in library_names: library_filename = find_library(library_name) if library_filename: filenames = (library_filename,) + filenames else: exceptions.append( 'no library called "{}" was found'.format(library_name)) for filename in filenames: try: return ffi.dlopen(filename) except OSError as exception: # pragma: no cover exceptions.append(exception) error_message = '\n'.join( # pragma: no cover str(exception) for exception in exceptions) raise OSError(error_message) # pragma: no cover cairo = dlopen( ffi, ('cairo', 'libcairo-2'), ('libcairo.so.2', 'libcairo.2.dylib', 'libcairo-2.dll')) class _keepref(object): """Function wrapper that keeps a reference to another object.""" def __init__(self, ref, func): self.ref = ref self.func = func def __call__(self, *args, **kwargs): self.func(*args, **kwargs) class CairoError(Exception): """Raised when cairo returns an error status.""" def __init__(self, message, status): super(CairoError, self).__init__(message) self.status = status Error = CairoError # pycairo compat STATUS_TO_EXCEPTION = { constants.STATUS_NO_MEMORY: MemoryError, constants.STATUS_READ_ERROR: IOError, constants.STATUS_WRITE_ERROR: IOError, constants.STATUS_TEMP_FILE_ERROR: IOError, constants.STATUS_FILE_NOT_FOUND: FileNotFoundError, } def _check_status(status): """Take a cairo status code and raise an exception if/as appropriate.""" if status != constants.STATUS_SUCCESS: exception = STATUS_TO_EXCEPTION.get(status, CairoError) status_name = ffi.string(ffi.cast("cairo_status_t", status)) message = 'cairo returned %s: %s' % ( status_name, ffi.string(cairo.cairo_status_to_string(status))) raise exception(message, status) def cairo_version(): """Return the cairo version number as a single integer, such as 11208 for ``1.12.8``. Major, minor and micro versions are "worth" 10000, 100 and 1 respectively. Can be useful as a guard for method not available in older cairo versions:: if cairo_version() >= 11000: surface.set_mime_data('image/jpeg', jpeg_bytes) """ return cairo.cairo_version() def cairo_version_string(): """Return the cairo version number as a string, such as ``1.12.8``.""" return ffi.string(cairo.cairo_version_string()).decode('ascii') def install_as_pycairo(): """Install cairocffi so that ``import cairo`` imports it. cairoffi’s API is compatible with pycairo as much as possible. """ sys.modules['cairo'] = sys.modules[__name__] # Implementation is in submodules, but public API is all here. from .surfaces import ( # noqa isort:skip Surface, ImageSurface, PDFSurface, PSSurface, SVGSurface, RecordingSurface, Win32Surface, Win32PrintingSurface) try: from .xcb import XCBSurface # noqa isort:skip except ImportError: pass from .patterns import ( # noqa isort:skip Pattern, SolidPattern, SurfacePattern, Gradient, LinearGradient, RadialGradient) from .fonts import ( # noqa isort:skip FontFace, ToyFontFace, ScaledFont, FontOptions) from .context import Context # noqa isort:skip from .matrix import Matrix # noqa isort:skip from .constants import * # noqa isort:skip cairocffi-1.2.0/cairocffi/constants.py000066400000000000000000001551041374663167600200030ustar00rootroot00000000000000# *** Do not edit this file *** # Generated by utils/mkconstants.py TAG_DEST = b"cairo.dest" TAG_LINK = b"Link" STATUS_SUCCESS = 0 STATUS_NO_MEMORY = 1 STATUS_INVALID_RESTORE = 2 STATUS_INVALID_POP_GROUP = 3 STATUS_NO_CURRENT_POINT = 4 STATUS_INVALID_MATRIX = 5 STATUS_INVALID_STATUS = 6 STATUS_NULL_POINTER = 7 STATUS_INVALID_STRING = 8 STATUS_INVALID_PATH_DATA = 9 STATUS_READ_ERROR = 10 STATUS_WRITE_ERROR = 11 STATUS_SURFACE_FINISHED = 12 STATUS_SURFACE_TYPE_MISMATCH = 13 STATUS_PATTERN_TYPE_MISMATCH = 14 STATUS_INVALID_CONTENT = 15 STATUS_INVALID_FORMAT = 16 STATUS_INVALID_VISUAL = 17 STATUS_FILE_NOT_FOUND = 18 STATUS_INVALID_DASH = 19 STATUS_INVALID_DSC_COMMENT = 20 STATUS_INVALID_INDEX = 21 STATUS_CLIP_NOT_REPRESENTABLE = 22 STATUS_TEMP_FILE_ERROR = 23 STATUS_INVALID_STRIDE = 24 STATUS_FONT_TYPE_MISMATCH = 25 STATUS_USER_FONT_IMMUTABLE = 26 STATUS_USER_FONT_ERROR = 27 STATUS_NEGATIVE_COUNT = 28 STATUS_INVALID_CLUSTERS = 29 STATUS_INVALID_SLANT = 30 STATUS_INVALID_WEIGHT = 31 STATUS_INVALID_SIZE = 32 STATUS_USER_FONT_NOT_IMPLEMENTED = 33 STATUS_DEVICE_TYPE_MISMATCH = 34 STATUS_DEVICE_ERROR = 35 STATUS_INVALID_MESH_CONSTRUCTION = 36 STATUS_DEVICE_FINISHED = 37 STATUS_JBIG2_GLOBAL_MISSING = 38 STATUS_PNG_ERROR = 39 STATUS_FREETYPE_ERROR = 40 STATUS_WIN32_GDI_ERROR = 41 STATUS_TAG_ERROR = 42 STATUS_LAST_STATUS = 43 CONTENT_COLOR = 0x1000 CONTENT_ALPHA = 0x2000 CONTENT_COLOR_ALPHA = 0x3000 FORMAT_INVALID = -1 FORMAT_ARGB32 = 0 FORMAT_RGB24 = 1 FORMAT_A8 = 2 FORMAT_A1 = 3 FORMAT_RGB16_565 = 4 FORMAT_RGB30 = 5 FORMAT_RGB96F = 6 FORMAT_RGBA128F = 7 OPERATOR_CLEAR = 0 OPERATOR_SOURCE = 1 OPERATOR_OVER = 2 OPERATOR_IN = 3 OPERATOR_OUT = 4 OPERATOR_ATOP = 5 OPERATOR_DEST = 6 OPERATOR_DEST_OVER = 7 OPERATOR_DEST_IN = 8 OPERATOR_DEST_OUT = 9 OPERATOR_DEST_ATOP = 10 OPERATOR_XOR = 11 OPERATOR_ADD = 12 OPERATOR_SATURATE = 13 OPERATOR_MULTIPLY = 14 OPERATOR_SCREEN = 15 OPERATOR_OVERLAY = 16 OPERATOR_DARKEN = 17 OPERATOR_LIGHTEN = 18 OPERATOR_COLOR_DODGE = 19 OPERATOR_COLOR_BURN = 20 OPERATOR_HARD_LIGHT = 21 OPERATOR_SOFT_LIGHT = 22 OPERATOR_DIFFERENCE = 23 OPERATOR_EXCLUSION = 24 OPERATOR_HSL_HUE = 25 OPERATOR_HSL_SATURATION = 26 OPERATOR_HSL_COLOR = 27 OPERATOR_HSL_LUMINOSITY = 28 ANTIALIAS_DEFAULT = 0 ANTIALIAS_NONE = 1 ANTIALIAS_GRAY = 2 ANTIALIAS_SUBPIXEL = 3 ANTIALIAS_FAST = 4 ANTIALIAS_GOOD = 5 ANTIALIAS_BEST = 6 FILL_RULE_WINDING = 0 FILL_RULE_EVEN_ODD = 1 LINE_CAP_BUTT = 0 LINE_CAP_ROUND = 1 LINE_CAP_SQUARE = 2 LINE_JOIN_MITER = 0 LINE_JOIN_ROUND = 1 LINE_JOIN_BEVEL = 2 TEXT_CLUSTER_FLAG_BACKWARD = 0x00000001 FONT_SLANT_NORMAL = 0 FONT_SLANT_ITALIC = 1 FONT_SLANT_OBLIQUE = 2 FONT_WEIGHT_NORMAL = 0 FONT_WEIGHT_BOLD = 1 SUBPIXEL_ORDER_DEFAULT = 0 SUBPIXEL_ORDER_RGB = 1 SUBPIXEL_ORDER_BGR = 2 SUBPIXEL_ORDER_VRGB = 3 SUBPIXEL_ORDER_VBGR = 4 HINT_STYLE_DEFAULT = 0 HINT_STYLE_NONE = 1 HINT_STYLE_SLIGHT = 2 HINT_STYLE_MEDIUM = 3 HINT_STYLE_FULL = 4 HINT_METRICS_DEFAULT = 0 HINT_METRICS_OFF = 1 HINT_METRICS_ON = 2 FONT_TYPE_TOY = 0 FONT_TYPE_FT = 1 FONT_TYPE_WIN32 = 2 FONT_TYPE_QUARTZ = 3 FONT_TYPE_USER = 4 PATH_MOVE_TO = 0 PATH_LINE_TO = 1 PATH_CURVE_TO = 2 PATH_CLOSE_PATH = 3 DEVICE_TYPE_DRM = 0 DEVICE_TYPE_GL = 1 DEVICE_TYPE_SCRIPT = 2 DEVICE_TYPE_XCB = 3 DEVICE_TYPE_XLIB = 4 DEVICE_TYPE_XML = 5 DEVICE_TYPE_COGL = 6 DEVICE_TYPE_WIN32 = 7 DEVICE_TYPE_INVALID = -1 SURFACE_OBSERVER_NORMAL = 0 SURFACE_OBSERVER_RECORD_OPERATIONS = 0x1 SURFACE_TYPE_IMAGE = 0 SURFACE_TYPE_PDF = 1 SURFACE_TYPE_PS = 2 SURFACE_TYPE_XLIB = 3 SURFACE_TYPE_XCB = 4 SURFACE_TYPE_GLITZ = 5 SURFACE_TYPE_QUARTZ = 6 SURFACE_TYPE_WIN32 = 7 SURFACE_TYPE_BEOS = 8 SURFACE_TYPE_DIRECTFB = 9 SURFACE_TYPE_SVG = 10 SURFACE_TYPE_OS2 = 11 SURFACE_TYPE_WIN32_PRINTING = 12 SURFACE_TYPE_QUARTZ_IMAGE = 13 SURFACE_TYPE_SCRIPT = 14 SURFACE_TYPE_QT = 15 SURFACE_TYPE_RECORDING = 16 SURFACE_TYPE_VG = 17 SURFACE_TYPE_GL = 18 SURFACE_TYPE_DRM = 19 SURFACE_TYPE_TEE = 20 SURFACE_TYPE_XML = 21 SURFACE_TYPE_SKIA = 22 SURFACE_TYPE_SUBSURFACE = 23 SURFACE_TYPE_COGL = 24 PATTERN_TYPE_SOLID = 0 PATTERN_TYPE_SURFACE = 1 PATTERN_TYPE_LINEAR = 2 PATTERN_TYPE_RADIAL = 3 PATTERN_TYPE_MESH = 4 PATTERN_TYPE_RASTER_SOURCE = 5 EXTEND_NONE = 0 EXTEND_REPEAT = 1 EXTEND_REFLECT = 2 EXTEND_PAD = 3 FILTER_FAST = 0 FILTER_GOOD = 1 FILTER_BEST = 2 FILTER_NEAREST = 3 FILTER_BILINEAR = 4 FILTER_GAUSSIAN = 5 REGION_OVERLAP_IN = 0 REGION_OVERLAP_OUT = 1 REGION_OVERLAP_PART = 2 PDF_OUTLINE_ROOT = 0 PDF_VERSION_1_4 = 0 PDF_VERSION_1_5 = 1 PDF_OUTLINE_FLAG_OPEN = 0x1 PDF_OUTLINE_FLAG_BOLD = 0x2 PDF_OUTLINE_FLAG_ITALIC = 0x4 PDF_METADATA_TITLE = 0 PDF_METADATA_AUTHOR = 1 PDF_METADATA_SUBJECT = 2 PDF_METADATA_KEYWORDS = 3 PDF_METADATA_CREATOR = 4 PDF_METADATA_CREATE_DATE = 5 PDF_METADATA_MOD_DATE = 6 PS_LEVEL_2 = 0 PS_LEVEL_3 = 1 SVG_VERSION_1_1 = 0 SVG_VERSION_1_2 = 1 SVG_UNIT_USER = 0 SVG_UNIT_EM = 1 SVG_UNIT_EX = 2 SVG_UNIT_PX = 3 SVG_UNIT_IN = 4 SVG_UNIT_CM = 5 SVG_UNIT_MM = 6 SVG_UNIT_PT = 7 SVG_UNIT_PC = 8 SVG_UNIT_PERCENT = 9 _CAIRO_HEADERS = r""" int cairo_version (void); const char* cairo_version_string (void); typedef int cairo_bool_t; typedef struct _cairo cairo_t; typedef struct _cairo_surface cairo_surface_t; typedef struct _cairo_device cairo_device_t; typedef struct _cairo_matrix { double xx; double yx; double xy; double yy; double x0; double y0; } cairo_matrix_t; typedef struct _cairo_pattern cairo_pattern_t; typedef void (*cairo_destroy_func_t) (void *data); typedef struct _cairo_user_data_key { int unused; } cairo_user_data_key_t; typedef enum _cairo_status { CAIRO_STATUS_SUCCESS = 0, CAIRO_STATUS_NO_MEMORY, CAIRO_STATUS_INVALID_RESTORE, CAIRO_STATUS_INVALID_POP_GROUP, CAIRO_STATUS_NO_CURRENT_POINT, CAIRO_STATUS_INVALID_MATRIX, CAIRO_STATUS_INVALID_STATUS, CAIRO_STATUS_NULL_POINTER, CAIRO_STATUS_INVALID_STRING, CAIRO_STATUS_INVALID_PATH_DATA, CAIRO_STATUS_READ_ERROR, CAIRO_STATUS_WRITE_ERROR, CAIRO_STATUS_SURFACE_FINISHED, CAIRO_STATUS_SURFACE_TYPE_MISMATCH, CAIRO_STATUS_PATTERN_TYPE_MISMATCH, CAIRO_STATUS_INVALID_CONTENT, CAIRO_STATUS_INVALID_FORMAT, CAIRO_STATUS_INVALID_VISUAL, CAIRO_STATUS_FILE_NOT_FOUND, CAIRO_STATUS_INVALID_DASH, CAIRO_STATUS_INVALID_DSC_COMMENT, CAIRO_STATUS_INVALID_INDEX, CAIRO_STATUS_CLIP_NOT_REPRESENTABLE, CAIRO_STATUS_TEMP_FILE_ERROR, CAIRO_STATUS_INVALID_STRIDE, CAIRO_STATUS_FONT_TYPE_MISMATCH, CAIRO_STATUS_USER_FONT_IMMUTABLE, CAIRO_STATUS_USER_FONT_ERROR, CAIRO_STATUS_NEGATIVE_COUNT, CAIRO_STATUS_INVALID_CLUSTERS, CAIRO_STATUS_INVALID_SLANT, CAIRO_STATUS_INVALID_WEIGHT, CAIRO_STATUS_INVALID_SIZE, CAIRO_STATUS_USER_FONT_NOT_IMPLEMENTED, CAIRO_STATUS_DEVICE_TYPE_MISMATCH, CAIRO_STATUS_DEVICE_ERROR, CAIRO_STATUS_INVALID_MESH_CONSTRUCTION, CAIRO_STATUS_DEVICE_FINISHED, CAIRO_STATUS_JBIG2_GLOBAL_MISSING, CAIRO_STATUS_PNG_ERROR, CAIRO_STATUS_FREETYPE_ERROR, CAIRO_STATUS_WIN32_GDI_ERROR, CAIRO_STATUS_TAG_ERROR, CAIRO_STATUS_LAST_STATUS } cairo_status_t; typedef enum _cairo_content { CAIRO_CONTENT_COLOR = 0x1000, CAIRO_CONTENT_ALPHA = 0x2000, CAIRO_CONTENT_COLOR_ALPHA = 0x3000 } cairo_content_t; typedef enum _cairo_format { CAIRO_FORMAT_INVALID = -1, CAIRO_FORMAT_ARGB32 = 0, CAIRO_FORMAT_RGB24 = 1, CAIRO_FORMAT_A8 = 2, CAIRO_FORMAT_A1 = 3, CAIRO_FORMAT_RGB16_565 = 4, CAIRO_FORMAT_RGB30 = 5, CAIRO_FORMAT_RGB96F = 6, CAIRO_FORMAT_RGBA128F = 7 } cairo_format_t; typedef cairo_status_t (*cairo_write_func_t) (void *closure, const unsigned char *data, unsigned int length); typedef cairo_status_t (*cairo_read_func_t) (void *closure, unsigned char *data, unsigned int length); typedef struct _cairo_rectangle_int { int x, y; int width, height; } cairo_rectangle_int_t; cairo_t * cairo_create (cairo_surface_t *target); cairo_t * cairo_reference (cairo_t *cr); void cairo_destroy (cairo_t *cr); unsigned int cairo_get_reference_count (cairo_t *cr); void * cairo_get_user_data (cairo_t *cr, const cairo_user_data_key_t *key); cairo_status_t cairo_set_user_data (cairo_t *cr, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); void cairo_save (cairo_t *cr); void cairo_restore (cairo_t *cr); void cairo_push_group (cairo_t *cr); void cairo_push_group_with_content (cairo_t *cr, cairo_content_t content); cairo_pattern_t * cairo_pop_group (cairo_t *cr); void cairo_pop_group_to_source (cairo_t *cr); typedef enum _cairo_operator { CAIRO_OPERATOR_CLEAR, CAIRO_OPERATOR_SOURCE, CAIRO_OPERATOR_OVER, CAIRO_OPERATOR_IN, CAIRO_OPERATOR_OUT, CAIRO_OPERATOR_ATOP, CAIRO_OPERATOR_DEST, CAIRO_OPERATOR_DEST_OVER, CAIRO_OPERATOR_DEST_IN, CAIRO_OPERATOR_DEST_OUT, CAIRO_OPERATOR_DEST_ATOP, CAIRO_OPERATOR_XOR, CAIRO_OPERATOR_ADD, CAIRO_OPERATOR_SATURATE, CAIRO_OPERATOR_MULTIPLY, CAIRO_OPERATOR_SCREEN, CAIRO_OPERATOR_OVERLAY, CAIRO_OPERATOR_DARKEN, CAIRO_OPERATOR_LIGHTEN, CAIRO_OPERATOR_COLOR_DODGE, CAIRO_OPERATOR_COLOR_BURN, CAIRO_OPERATOR_HARD_LIGHT, CAIRO_OPERATOR_SOFT_LIGHT, CAIRO_OPERATOR_DIFFERENCE, CAIRO_OPERATOR_EXCLUSION, CAIRO_OPERATOR_HSL_HUE, CAIRO_OPERATOR_HSL_SATURATION, CAIRO_OPERATOR_HSL_COLOR, CAIRO_OPERATOR_HSL_LUMINOSITY } cairo_operator_t; void cairo_set_operator (cairo_t *cr, cairo_operator_t op); void cairo_set_source (cairo_t *cr, cairo_pattern_t *source); void cairo_set_source_rgb (cairo_t *cr, double red, double green, double blue); void cairo_set_source_rgba (cairo_t *cr, double red, double green, double blue, double alpha); void cairo_set_source_surface (cairo_t *cr, cairo_surface_t *surface, double x, double y); void cairo_set_tolerance (cairo_t *cr, double tolerance); typedef enum _cairo_antialias { CAIRO_ANTIALIAS_DEFAULT, CAIRO_ANTIALIAS_NONE, CAIRO_ANTIALIAS_GRAY, CAIRO_ANTIALIAS_SUBPIXEL, CAIRO_ANTIALIAS_FAST, CAIRO_ANTIALIAS_GOOD, CAIRO_ANTIALIAS_BEST } cairo_antialias_t; void cairo_set_antialias (cairo_t *cr, cairo_antialias_t antialias); typedef enum _cairo_fill_rule { CAIRO_FILL_RULE_WINDING, CAIRO_FILL_RULE_EVEN_ODD } cairo_fill_rule_t; void cairo_set_fill_rule (cairo_t *cr, cairo_fill_rule_t fill_rule); void cairo_set_line_width (cairo_t *cr, double width); typedef enum _cairo_line_cap { CAIRO_LINE_CAP_BUTT, CAIRO_LINE_CAP_ROUND, CAIRO_LINE_CAP_SQUARE } cairo_line_cap_t; void cairo_set_line_cap (cairo_t *cr, cairo_line_cap_t line_cap); typedef enum _cairo_line_join { CAIRO_LINE_JOIN_MITER, CAIRO_LINE_JOIN_ROUND, CAIRO_LINE_JOIN_BEVEL } cairo_line_join_t; void cairo_set_line_join (cairo_t *cr, cairo_line_join_t line_join); void cairo_set_dash (cairo_t *cr, const double *dashes, int num_dashes, double offset); void cairo_set_miter_limit (cairo_t *cr, double limit); void cairo_translate (cairo_t *cr, double tx, double ty); void cairo_scale (cairo_t *cr, double sx, double sy); void cairo_rotate (cairo_t *cr, double angle); void cairo_transform (cairo_t *cr, const cairo_matrix_t *matrix); void cairo_set_matrix (cairo_t *cr, const cairo_matrix_t *matrix); void cairo_identity_matrix (cairo_t *cr); void cairo_user_to_device (cairo_t *cr, double *x, double *y); void cairo_user_to_device_distance (cairo_t *cr, double *dx, double *dy); void cairo_device_to_user (cairo_t *cr, double *x, double *y); void cairo_device_to_user_distance (cairo_t *cr, double *dx, double *dy); void cairo_new_path (cairo_t *cr); void cairo_move_to (cairo_t *cr, double x, double y); void cairo_new_sub_path (cairo_t *cr); void cairo_line_to (cairo_t *cr, double x, double y); void cairo_curve_to (cairo_t *cr, double x1, double y1, double x2, double y2, double x3, double y3); void cairo_arc (cairo_t *cr, double xc, double yc, double radius, double angle1, double angle2); void cairo_arc_negative (cairo_t *cr, double xc, double yc, double radius, double angle1, double angle2); void cairo_rel_move_to (cairo_t *cr, double dx, double dy); void cairo_rel_line_to (cairo_t *cr, double dx, double dy); void cairo_rel_curve_to (cairo_t *cr, double dx1, double dy1, double dx2, double dy2, double dx3, double dy3); void cairo_rectangle (cairo_t *cr, double x, double y, double width, double height); void cairo_close_path (cairo_t *cr); void cairo_path_extents (cairo_t *cr, double *x1, double *y1, double *x2, double *y2); void cairo_paint (cairo_t *cr); void cairo_paint_with_alpha (cairo_t *cr, double alpha); void cairo_mask (cairo_t *cr, cairo_pattern_t *pattern); void cairo_mask_surface (cairo_t *cr, cairo_surface_t *surface, double surface_x, double surface_y); void cairo_stroke (cairo_t *cr); void cairo_stroke_preserve (cairo_t *cr); void cairo_fill (cairo_t *cr); void cairo_fill_preserve (cairo_t *cr); void cairo_copy_page (cairo_t *cr); void cairo_show_page (cairo_t *cr); cairo_bool_t cairo_in_stroke (cairo_t *cr, double x, double y); cairo_bool_t cairo_in_fill (cairo_t *cr, double x, double y); cairo_bool_t cairo_in_clip (cairo_t *cr, double x, double y); void cairo_stroke_extents (cairo_t *cr, double *x1, double *y1, double *x2, double *y2); void cairo_fill_extents (cairo_t *cr, double *x1, double *y1, double *x2, double *y2); void cairo_reset_clip (cairo_t *cr); void cairo_clip (cairo_t *cr); void cairo_clip_preserve (cairo_t *cr); void cairo_clip_extents (cairo_t *cr, double *x1, double *y1, double *x2, double *y2); typedef struct _cairo_rectangle { double x, y, width, height; } cairo_rectangle_t; typedef struct _cairo_rectangle_list { cairo_status_t status; cairo_rectangle_t *rectangles; int num_rectangles; } cairo_rectangle_list_t; cairo_rectangle_list_t * cairo_copy_clip_rectangle_list (cairo_t *cr); void cairo_rectangle_list_destroy (cairo_rectangle_list_t *rectangle_list); void cairo_tag_begin (cairo_t *cr, const char *tag_name, const char *attributes); void cairo_tag_end (cairo_t *cr, const char *tag_name); typedef struct _cairo_scaled_font cairo_scaled_font_t; typedef struct _cairo_font_face cairo_font_face_t; typedef struct { unsigned long index; double x; double y; } cairo_glyph_t; cairo_glyph_t * cairo_glyph_allocate (int num_glyphs); void cairo_glyph_free (cairo_glyph_t *glyphs); typedef struct { int num_bytes; int num_glyphs; } cairo_text_cluster_t; cairo_text_cluster_t * cairo_text_cluster_allocate (int num_clusters); void cairo_text_cluster_free (cairo_text_cluster_t *clusters); typedef enum _cairo_text_cluster_flags { CAIRO_TEXT_CLUSTER_FLAG_BACKWARD = 0x00000001 } cairo_text_cluster_flags_t; typedef struct { double x_bearing; double y_bearing; double width; double height; double x_advance; double y_advance; } cairo_text_extents_t; typedef struct { double ascent; double descent; double height; double max_x_advance; double max_y_advance; } cairo_font_extents_t; typedef enum _cairo_font_slant { CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_SLANT_ITALIC, CAIRO_FONT_SLANT_OBLIQUE } cairo_font_slant_t; typedef enum _cairo_font_weight { CAIRO_FONT_WEIGHT_NORMAL, CAIRO_FONT_WEIGHT_BOLD } cairo_font_weight_t; typedef enum _cairo_subpixel_order { CAIRO_SUBPIXEL_ORDER_DEFAULT, CAIRO_SUBPIXEL_ORDER_RGB, CAIRO_SUBPIXEL_ORDER_BGR, CAIRO_SUBPIXEL_ORDER_VRGB, CAIRO_SUBPIXEL_ORDER_VBGR } cairo_subpixel_order_t; typedef enum _cairo_hint_style { CAIRO_HINT_STYLE_DEFAULT, CAIRO_HINT_STYLE_NONE, CAIRO_HINT_STYLE_SLIGHT, CAIRO_HINT_STYLE_MEDIUM, CAIRO_HINT_STYLE_FULL } cairo_hint_style_t; typedef enum _cairo_hint_metrics { CAIRO_HINT_METRICS_DEFAULT, CAIRO_HINT_METRICS_OFF, CAIRO_HINT_METRICS_ON } cairo_hint_metrics_t; typedef struct _cairo_font_options cairo_font_options_t; cairo_font_options_t * cairo_font_options_create (void); cairo_font_options_t * cairo_font_options_copy (const cairo_font_options_t *original); void cairo_font_options_destroy (cairo_font_options_t *options); cairo_status_t cairo_font_options_status (cairo_font_options_t *options); void cairo_font_options_merge (cairo_font_options_t *options, const cairo_font_options_t *other); cairo_bool_t cairo_font_options_equal (const cairo_font_options_t *options, const cairo_font_options_t *other); unsigned long cairo_font_options_hash (const cairo_font_options_t *options); void cairo_font_options_set_antialias (cairo_font_options_t *options, cairo_antialias_t antialias); cairo_antialias_t cairo_font_options_get_antialias (const cairo_font_options_t *options); void cairo_font_options_set_subpixel_order (cairo_font_options_t *options, cairo_subpixel_order_t subpixel_order); cairo_subpixel_order_t cairo_font_options_get_subpixel_order (const cairo_font_options_t *options); void cairo_font_options_set_hint_style (cairo_font_options_t *options, cairo_hint_style_t hint_style); cairo_hint_style_t cairo_font_options_get_hint_style (const cairo_font_options_t *options); void cairo_font_options_set_hint_metrics (cairo_font_options_t *options, cairo_hint_metrics_t hint_metrics); cairo_hint_metrics_t cairo_font_options_get_hint_metrics (const cairo_font_options_t *options); const char * cairo_font_options_get_variations (cairo_font_options_t *options); void cairo_font_options_set_variations (cairo_font_options_t *options, const char *variations); void cairo_select_font_face (cairo_t *cr, const char *family, cairo_font_slant_t slant, cairo_font_weight_t weight); void cairo_set_font_size (cairo_t *cr, double size); void cairo_set_font_matrix (cairo_t *cr, const cairo_matrix_t *matrix); void cairo_get_font_matrix (cairo_t *cr, cairo_matrix_t *matrix); void cairo_set_font_options (cairo_t *cr, const cairo_font_options_t *options); void cairo_get_font_options (cairo_t *cr, cairo_font_options_t *options); void cairo_set_font_face (cairo_t *cr, cairo_font_face_t *font_face); cairo_font_face_t * cairo_get_font_face (cairo_t *cr); void cairo_set_scaled_font (cairo_t *cr, const cairo_scaled_font_t *scaled_font); cairo_scaled_font_t * cairo_get_scaled_font (cairo_t *cr); void cairo_show_text (cairo_t *cr, const char *utf8); void cairo_show_glyphs (cairo_t *cr, const cairo_glyph_t *glyphs, int num_glyphs); void cairo_show_text_glyphs (cairo_t *cr, const char *utf8, int utf8_len, const cairo_glyph_t *glyphs, int num_glyphs, const cairo_text_cluster_t *clusters, int num_clusters, cairo_text_cluster_flags_t cluster_flags); void cairo_text_path (cairo_t *cr, const char *utf8); void cairo_glyph_path (cairo_t *cr, const cairo_glyph_t *glyphs, int num_glyphs); void cairo_text_extents (cairo_t *cr, const char *utf8, cairo_text_extents_t *extents); void cairo_glyph_extents (cairo_t *cr, const cairo_glyph_t *glyphs, int num_glyphs, cairo_text_extents_t *extents); void cairo_font_extents (cairo_t *cr, cairo_font_extents_t *extents); cairo_font_face_t * cairo_font_face_reference (cairo_font_face_t *font_face); void cairo_font_face_destroy (cairo_font_face_t *font_face); unsigned int cairo_font_face_get_reference_count (cairo_font_face_t *font_face); cairo_status_t cairo_font_face_status (cairo_font_face_t *font_face); typedef enum _cairo_font_type { CAIRO_FONT_TYPE_TOY, CAIRO_FONT_TYPE_FT, CAIRO_FONT_TYPE_WIN32, CAIRO_FONT_TYPE_QUARTZ, CAIRO_FONT_TYPE_USER } cairo_font_type_t; cairo_font_type_t cairo_font_face_get_type (cairo_font_face_t *font_face); void * cairo_font_face_get_user_data (cairo_font_face_t *font_face, const cairo_user_data_key_t *key); cairo_status_t cairo_font_face_set_user_data (cairo_font_face_t *font_face, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); cairo_scaled_font_t * cairo_scaled_font_create (cairo_font_face_t *font_face, const cairo_matrix_t *font_matrix, const cairo_matrix_t *ctm, const cairo_font_options_t *options); cairo_scaled_font_t * cairo_scaled_font_reference (cairo_scaled_font_t *scaled_font); void cairo_scaled_font_destroy (cairo_scaled_font_t *scaled_font); unsigned int cairo_scaled_font_get_reference_count (cairo_scaled_font_t *scaled_font); cairo_status_t cairo_scaled_font_status (cairo_scaled_font_t *scaled_font); cairo_font_type_t cairo_scaled_font_get_type (cairo_scaled_font_t *scaled_font); void * cairo_scaled_font_get_user_data (cairo_scaled_font_t *scaled_font, const cairo_user_data_key_t *key); cairo_status_t cairo_scaled_font_set_user_data (cairo_scaled_font_t *scaled_font, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); void cairo_scaled_font_extents (cairo_scaled_font_t *scaled_font, cairo_font_extents_t *extents); void cairo_scaled_font_text_extents (cairo_scaled_font_t *scaled_font, const char *utf8, cairo_text_extents_t *extents); void cairo_scaled_font_glyph_extents (cairo_scaled_font_t *scaled_font, const cairo_glyph_t *glyphs, int num_glyphs, cairo_text_extents_t *extents); cairo_status_t cairo_scaled_font_text_to_glyphs (cairo_scaled_font_t *scaled_font, double x, double y, const char *utf8, int utf8_len, cairo_glyph_t **glyphs, int *num_glyphs, cairo_text_cluster_t **clusters, int *num_clusters, cairo_text_cluster_flags_t *cluster_flags); cairo_font_face_t * cairo_scaled_font_get_font_face (cairo_scaled_font_t *scaled_font); void cairo_scaled_font_get_font_matrix (cairo_scaled_font_t *scaled_font, cairo_matrix_t *font_matrix); void cairo_scaled_font_get_ctm (cairo_scaled_font_t *scaled_font, cairo_matrix_t *ctm); void cairo_scaled_font_get_scale_matrix (cairo_scaled_font_t *scaled_font, cairo_matrix_t *scale_matrix); void cairo_scaled_font_get_font_options (cairo_scaled_font_t *scaled_font, cairo_font_options_t *options); cairo_font_face_t * cairo_toy_font_face_create (const char *family, cairo_font_slant_t slant, cairo_font_weight_t weight); const char * cairo_toy_font_face_get_family (cairo_font_face_t *font_face); cairo_font_slant_t cairo_toy_font_face_get_slant (cairo_font_face_t *font_face); cairo_font_weight_t cairo_toy_font_face_get_weight (cairo_font_face_t *font_face); cairo_font_face_t * cairo_user_font_face_create (void); typedef cairo_status_t (*cairo_user_scaled_font_init_func_t) (cairo_scaled_font_t *scaled_font, cairo_t *cr, cairo_font_extents_t *extents); typedef cairo_status_t (*cairo_user_scaled_font_render_glyph_func_t) (cairo_scaled_font_t *scaled_font, unsigned long glyph, cairo_t *cr, cairo_text_extents_t *extents); typedef cairo_status_t (*cairo_user_scaled_font_text_to_glyphs_func_t) (cairo_scaled_font_t *scaled_font, const char *utf8, int utf8_len, cairo_glyph_t **glyphs, int *num_glyphs, cairo_text_cluster_t **clusters, int *num_clusters, cairo_text_cluster_flags_t *cluster_flags); typedef cairo_status_t (*cairo_user_scaled_font_unicode_to_glyph_func_t) (cairo_scaled_font_t *scaled_font, unsigned long unicode, unsigned long *glyph_index); void cairo_user_font_face_set_init_func (cairo_font_face_t *font_face, cairo_user_scaled_font_init_func_t init_func); void cairo_user_font_face_set_render_glyph_func (cairo_font_face_t *font_face, cairo_user_scaled_font_render_glyph_func_t render_glyph_func); void cairo_user_font_face_set_text_to_glyphs_func (cairo_font_face_t *font_face, cairo_user_scaled_font_text_to_glyphs_func_t text_to_glyphs_func); void cairo_user_font_face_set_unicode_to_glyph_func (cairo_font_face_t *font_face, cairo_user_scaled_font_unicode_to_glyph_func_t unicode_to_glyph_func); cairo_user_scaled_font_init_func_t cairo_user_font_face_get_init_func (cairo_font_face_t *font_face); cairo_user_scaled_font_render_glyph_func_t cairo_user_font_face_get_render_glyph_func (cairo_font_face_t *font_face); cairo_user_scaled_font_text_to_glyphs_func_t cairo_user_font_face_get_text_to_glyphs_func (cairo_font_face_t *font_face); cairo_user_scaled_font_unicode_to_glyph_func_t cairo_user_font_face_get_unicode_to_glyph_func (cairo_font_face_t *font_face); cairo_operator_t cairo_get_operator (cairo_t *cr); cairo_pattern_t * cairo_get_source (cairo_t *cr); double cairo_get_tolerance (cairo_t *cr); cairo_antialias_t cairo_get_antialias (cairo_t *cr); cairo_bool_t cairo_has_current_point (cairo_t *cr); void cairo_get_current_point (cairo_t *cr, double *x, double *y); cairo_fill_rule_t cairo_get_fill_rule (cairo_t *cr); double cairo_get_line_width (cairo_t *cr); cairo_line_cap_t cairo_get_line_cap (cairo_t *cr); cairo_line_join_t cairo_get_line_join (cairo_t *cr); double cairo_get_miter_limit (cairo_t *cr); int cairo_get_dash_count (cairo_t *cr); void cairo_get_dash (cairo_t *cr, double *dashes, double *offset); void cairo_get_matrix (cairo_t *cr, cairo_matrix_t *matrix); cairo_surface_t * cairo_get_target (cairo_t *cr); cairo_surface_t * cairo_get_group_target (cairo_t *cr); typedef enum _cairo_path_data_type { CAIRO_PATH_MOVE_TO, CAIRO_PATH_LINE_TO, CAIRO_PATH_CURVE_TO, CAIRO_PATH_CLOSE_PATH } cairo_path_data_type_t; typedef union _cairo_path_data_t cairo_path_data_t; union _cairo_path_data_t { struct { cairo_path_data_type_t type; int length; } header; struct { double x, y; } point; }; typedef struct cairo_path { cairo_status_t status; cairo_path_data_t *data; int num_data; } cairo_path_t; cairo_path_t * cairo_copy_path (cairo_t *cr); cairo_path_t * cairo_copy_path_flat (cairo_t *cr); void cairo_append_path (cairo_t *cr, const cairo_path_t *path); void cairo_path_destroy (cairo_path_t *path); cairo_status_t cairo_status (cairo_t *cr); const char * cairo_status_to_string (cairo_status_t status); cairo_device_t * cairo_device_reference (cairo_device_t *device); typedef enum _cairo_device_type { CAIRO_DEVICE_TYPE_DRM, CAIRO_DEVICE_TYPE_GL, CAIRO_DEVICE_TYPE_SCRIPT, CAIRO_DEVICE_TYPE_XCB, CAIRO_DEVICE_TYPE_XLIB, CAIRO_DEVICE_TYPE_XML, CAIRO_DEVICE_TYPE_COGL, CAIRO_DEVICE_TYPE_WIN32, CAIRO_DEVICE_TYPE_INVALID = -1 } cairo_device_type_t; cairo_device_type_t cairo_device_get_type (cairo_device_t *device); cairo_status_t cairo_device_status (cairo_device_t *device); cairo_status_t cairo_device_acquire (cairo_device_t *device); void cairo_device_release (cairo_device_t *device); void cairo_device_flush (cairo_device_t *device); void cairo_device_finish (cairo_device_t *device); void cairo_device_destroy (cairo_device_t *device); unsigned int cairo_device_get_reference_count (cairo_device_t *device); void * cairo_device_get_user_data (cairo_device_t *device, const cairo_user_data_key_t *key); cairo_status_t cairo_device_set_user_data (cairo_device_t *device, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); cairo_surface_t * cairo_surface_create_similar (cairo_surface_t *other, cairo_content_t content, int width, int height); cairo_surface_t * cairo_surface_create_similar_image (cairo_surface_t *other, cairo_format_t format, int width, int height); cairo_surface_t * cairo_surface_map_to_image (cairo_surface_t *surface, const cairo_rectangle_int_t *extents); void cairo_surface_unmap_image (cairo_surface_t *surface, cairo_surface_t *image); cairo_surface_t * cairo_surface_create_for_rectangle (cairo_surface_t *target, double x, double y, double width, double height); typedef enum { CAIRO_SURFACE_OBSERVER_NORMAL = 0, CAIRO_SURFACE_OBSERVER_RECORD_OPERATIONS = 0x1 } cairo_surface_observer_mode_t; cairo_surface_t * cairo_surface_create_observer (cairo_surface_t *target, cairo_surface_observer_mode_t mode); typedef void (*cairo_surface_observer_callback_t) (cairo_surface_t *observer, cairo_surface_t *target, void *data); cairo_status_t cairo_surface_observer_add_paint_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_mask_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_fill_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_stroke_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_glyphs_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_flush_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_add_finish_callback (cairo_surface_t *abstract_surface, cairo_surface_observer_callback_t func, void *data); cairo_status_t cairo_surface_observer_print (cairo_surface_t *surface, cairo_write_func_t write_func, void *closure); double cairo_surface_observer_elapsed (cairo_surface_t *surface); cairo_status_t cairo_device_observer_print (cairo_device_t *device, cairo_write_func_t write_func, void *closure); double cairo_device_observer_elapsed (cairo_device_t *device); double cairo_device_observer_paint_elapsed (cairo_device_t *device); double cairo_device_observer_mask_elapsed (cairo_device_t *device); double cairo_device_observer_fill_elapsed (cairo_device_t *device); double cairo_device_observer_stroke_elapsed (cairo_device_t *device); double cairo_device_observer_glyphs_elapsed (cairo_device_t *device); cairo_surface_t * cairo_surface_reference (cairo_surface_t *surface); void cairo_surface_finish (cairo_surface_t *surface); void cairo_surface_destroy (cairo_surface_t *surface); cairo_device_t * cairo_surface_get_device (cairo_surface_t *surface); unsigned int cairo_surface_get_reference_count (cairo_surface_t *surface); cairo_status_t cairo_surface_status (cairo_surface_t *surface); typedef enum _cairo_surface_type { CAIRO_SURFACE_TYPE_IMAGE, CAIRO_SURFACE_TYPE_PDF, CAIRO_SURFACE_TYPE_PS, CAIRO_SURFACE_TYPE_XLIB, CAIRO_SURFACE_TYPE_XCB, CAIRO_SURFACE_TYPE_GLITZ, CAIRO_SURFACE_TYPE_QUARTZ, CAIRO_SURFACE_TYPE_WIN32, CAIRO_SURFACE_TYPE_BEOS, CAIRO_SURFACE_TYPE_DIRECTFB, CAIRO_SURFACE_TYPE_SVG, CAIRO_SURFACE_TYPE_OS2, CAIRO_SURFACE_TYPE_WIN32_PRINTING, CAIRO_SURFACE_TYPE_QUARTZ_IMAGE, CAIRO_SURFACE_TYPE_SCRIPT, CAIRO_SURFACE_TYPE_QT, CAIRO_SURFACE_TYPE_RECORDING, CAIRO_SURFACE_TYPE_VG, CAIRO_SURFACE_TYPE_GL, CAIRO_SURFACE_TYPE_DRM, CAIRO_SURFACE_TYPE_TEE, CAIRO_SURFACE_TYPE_XML, CAIRO_SURFACE_TYPE_SKIA, CAIRO_SURFACE_TYPE_SUBSURFACE, CAIRO_SURFACE_TYPE_COGL } cairo_surface_type_t; cairo_surface_type_t cairo_surface_get_type (cairo_surface_t *surface); cairo_content_t cairo_surface_get_content (cairo_surface_t *surface); cairo_status_t cairo_surface_write_to_png (cairo_surface_t *surface, const char *filename); cairo_status_t cairo_surface_write_to_png_stream (cairo_surface_t *surface, cairo_write_func_t write_func, void *closure); void * cairo_surface_get_user_data (cairo_surface_t *surface, const cairo_user_data_key_t *key); cairo_status_t cairo_surface_set_user_data (cairo_surface_t *surface, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); void cairo_surface_get_mime_data (cairo_surface_t *surface, const char *mime_type, const unsigned char **data, unsigned long *length); cairo_status_t cairo_surface_set_mime_data (cairo_surface_t *surface, const char *mime_type, const unsigned char *data, unsigned long length, cairo_destroy_func_t destroy, void *closure); cairo_bool_t cairo_surface_supports_mime_type (cairo_surface_t *surface, const char *mime_type); void cairo_surface_get_font_options (cairo_surface_t *surface, cairo_font_options_t *options); void cairo_surface_flush (cairo_surface_t *surface); void cairo_surface_mark_dirty (cairo_surface_t *surface); void cairo_surface_mark_dirty_rectangle (cairo_surface_t *surface, int x, int y, int width, int height); void cairo_surface_set_device_scale (cairo_surface_t *surface, double x_scale, double y_scale); void cairo_surface_get_device_scale (cairo_surface_t *surface, double *x_scale, double *y_scale); void cairo_surface_set_device_offset (cairo_surface_t *surface, double x_offset, double y_offset); void cairo_surface_get_device_offset (cairo_surface_t *surface, double *x_offset, double *y_offset); void cairo_surface_set_fallback_resolution (cairo_surface_t *surface, double x_pixels_per_inch, double y_pixels_per_inch); void cairo_surface_get_fallback_resolution (cairo_surface_t *surface, double *x_pixels_per_inch, double *y_pixels_per_inch); void cairo_surface_copy_page (cairo_surface_t *surface); void cairo_surface_show_page (cairo_surface_t *surface); cairo_bool_t cairo_surface_has_show_text_glyphs (cairo_surface_t *surface); cairo_surface_t * cairo_image_surface_create (cairo_format_t format, int width, int height); int cairo_format_stride_for_width (cairo_format_t format, int width); cairo_surface_t * cairo_image_surface_create_for_data (unsigned char *data, cairo_format_t format, int width, int height, int stride); unsigned char * cairo_image_surface_get_data (cairo_surface_t *surface); cairo_format_t cairo_image_surface_get_format (cairo_surface_t *surface); int cairo_image_surface_get_width (cairo_surface_t *surface); int cairo_image_surface_get_height (cairo_surface_t *surface); int cairo_image_surface_get_stride (cairo_surface_t *surface); cairo_surface_t * cairo_image_surface_create_from_png (const char *filename); cairo_surface_t * cairo_image_surface_create_from_png_stream (cairo_read_func_t read_func, void *closure); cairo_surface_t * cairo_recording_surface_create (cairo_content_t content, const cairo_rectangle_t *extents); void cairo_recording_surface_ink_extents (cairo_surface_t *surface, double *x0, double *y0, double *width, double *height); cairo_bool_t cairo_recording_surface_get_extents (cairo_surface_t *surface, cairo_rectangle_t *extents); typedef cairo_surface_t * (*cairo_raster_source_acquire_func_t) (cairo_pattern_t *pattern, void *callback_data, cairo_surface_t *target, const cairo_rectangle_int_t *extents); typedef void (*cairo_raster_source_release_func_t) (cairo_pattern_t *pattern, void *callback_data, cairo_surface_t *surface); typedef cairo_status_t (*cairo_raster_source_snapshot_func_t) (cairo_pattern_t *pattern, void *callback_data); typedef cairo_status_t (*cairo_raster_source_copy_func_t) (cairo_pattern_t *pattern, void *callback_data, const cairo_pattern_t *other); typedef void (*cairo_raster_source_finish_func_t) (cairo_pattern_t *pattern, void *callback_data); cairo_pattern_t * cairo_pattern_create_raster_source (void *user_data, cairo_content_t content, int width, int height); void cairo_raster_source_pattern_set_callback_data (cairo_pattern_t *pattern, void *data); void * cairo_raster_source_pattern_get_callback_data (cairo_pattern_t *pattern); void cairo_raster_source_pattern_set_acquire (cairo_pattern_t *pattern, cairo_raster_source_acquire_func_t acquire, cairo_raster_source_release_func_t release); void cairo_raster_source_pattern_get_acquire (cairo_pattern_t *pattern, cairo_raster_source_acquire_func_t *acquire, cairo_raster_source_release_func_t *release); void cairo_raster_source_pattern_set_snapshot (cairo_pattern_t *pattern, cairo_raster_source_snapshot_func_t snapshot); cairo_raster_source_snapshot_func_t cairo_raster_source_pattern_get_snapshot (cairo_pattern_t *pattern); void cairo_raster_source_pattern_set_copy (cairo_pattern_t *pattern, cairo_raster_source_copy_func_t copy); cairo_raster_source_copy_func_t cairo_raster_source_pattern_get_copy (cairo_pattern_t *pattern); void cairo_raster_source_pattern_set_finish (cairo_pattern_t *pattern, cairo_raster_source_finish_func_t finish); cairo_raster_source_finish_func_t cairo_raster_source_pattern_get_finish (cairo_pattern_t *pattern); cairo_pattern_t * cairo_pattern_create_rgb (double red, double green, double blue); cairo_pattern_t * cairo_pattern_create_rgba (double red, double green, double blue, double alpha); cairo_pattern_t * cairo_pattern_create_for_surface (cairo_surface_t *surface); cairo_pattern_t * cairo_pattern_create_linear (double x0, double y0, double x1, double y1); cairo_pattern_t * cairo_pattern_create_radial (double cx0, double cy0, double radius0, double cx1, double cy1, double radius1); cairo_pattern_t * cairo_pattern_create_mesh (void); cairo_pattern_t * cairo_pattern_reference (cairo_pattern_t *pattern); void cairo_pattern_destroy (cairo_pattern_t *pattern); unsigned int cairo_pattern_get_reference_count (cairo_pattern_t *pattern); cairo_status_t cairo_pattern_status (cairo_pattern_t *pattern); void * cairo_pattern_get_user_data (cairo_pattern_t *pattern, const cairo_user_data_key_t *key); cairo_status_t cairo_pattern_set_user_data (cairo_pattern_t *pattern, const cairo_user_data_key_t *key, void *user_data, cairo_destroy_func_t destroy); typedef enum _cairo_pattern_type { CAIRO_PATTERN_TYPE_SOLID, CAIRO_PATTERN_TYPE_SURFACE, CAIRO_PATTERN_TYPE_LINEAR, CAIRO_PATTERN_TYPE_RADIAL, CAIRO_PATTERN_TYPE_MESH, CAIRO_PATTERN_TYPE_RASTER_SOURCE } cairo_pattern_type_t; cairo_pattern_type_t cairo_pattern_get_type (cairo_pattern_t *pattern); void cairo_pattern_add_color_stop_rgb (cairo_pattern_t *pattern, double offset, double red, double green, double blue); void cairo_pattern_add_color_stop_rgba (cairo_pattern_t *pattern, double offset, double red, double green, double blue, double alpha); void cairo_mesh_pattern_begin_patch (cairo_pattern_t *pattern); void cairo_mesh_pattern_end_patch (cairo_pattern_t *pattern); void cairo_mesh_pattern_curve_to (cairo_pattern_t *pattern, double x1, double y1, double x2, double y2, double x3, double y3); void cairo_mesh_pattern_line_to (cairo_pattern_t *pattern, double x, double y); void cairo_mesh_pattern_move_to (cairo_pattern_t *pattern, double x, double y); void cairo_mesh_pattern_set_control_point (cairo_pattern_t *pattern, unsigned int point_num, double x, double y); void cairo_mesh_pattern_set_corner_color_rgb (cairo_pattern_t *pattern, unsigned int corner_num, double red, double green, double blue); void cairo_mesh_pattern_set_corner_color_rgba (cairo_pattern_t *pattern, unsigned int corner_num, double red, double green, double blue, double alpha); void cairo_pattern_set_matrix (cairo_pattern_t *pattern, const cairo_matrix_t *matrix); void cairo_pattern_get_matrix (cairo_pattern_t *pattern, cairo_matrix_t *matrix); typedef enum _cairo_extend { CAIRO_EXTEND_NONE, CAIRO_EXTEND_REPEAT, CAIRO_EXTEND_REFLECT, CAIRO_EXTEND_PAD } cairo_extend_t; void cairo_pattern_set_extend (cairo_pattern_t *pattern, cairo_extend_t extend); cairo_extend_t cairo_pattern_get_extend (cairo_pattern_t *pattern); typedef enum _cairo_filter { CAIRO_FILTER_FAST, CAIRO_FILTER_GOOD, CAIRO_FILTER_BEST, CAIRO_FILTER_NEAREST, CAIRO_FILTER_BILINEAR, CAIRO_FILTER_GAUSSIAN } cairo_filter_t; void cairo_pattern_set_filter (cairo_pattern_t *pattern, cairo_filter_t filter); cairo_filter_t cairo_pattern_get_filter (cairo_pattern_t *pattern); cairo_status_t cairo_pattern_get_rgba (cairo_pattern_t *pattern, double *red, double *green, double *blue, double *alpha); cairo_status_t cairo_pattern_get_surface (cairo_pattern_t *pattern, cairo_surface_t **surface); cairo_status_t cairo_pattern_get_color_stop_rgba (cairo_pattern_t *pattern, int index, double *offset, double *red, double *green, double *blue, double *alpha); cairo_status_t cairo_pattern_get_color_stop_count (cairo_pattern_t *pattern, int *count); cairo_status_t cairo_pattern_get_linear_points (cairo_pattern_t *pattern, double *x0, double *y0, double *x1, double *y1); cairo_status_t cairo_pattern_get_radial_circles (cairo_pattern_t *pattern, double *x0, double *y0, double *r0, double *x1, double *y1, double *r1); cairo_status_t cairo_mesh_pattern_get_patch_count (cairo_pattern_t *pattern, unsigned int *count); cairo_path_t * cairo_mesh_pattern_get_path (cairo_pattern_t *pattern, unsigned int patch_num); cairo_status_t cairo_mesh_pattern_get_corner_color_rgba (cairo_pattern_t *pattern, unsigned int patch_num, unsigned int corner_num, double *red, double *green, double *blue, double *alpha); cairo_status_t cairo_mesh_pattern_get_control_point (cairo_pattern_t *pattern, unsigned int patch_num, unsigned int point_num, double *x, double *y); void cairo_matrix_init (cairo_matrix_t *matrix, double xx, double yx, double xy, double yy, double x0, double y0); void cairo_matrix_init_identity (cairo_matrix_t *matrix); void cairo_matrix_init_translate (cairo_matrix_t *matrix, double tx, double ty); void cairo_matrix_init_scale (cairo_matrix_t *matrix, double sx, double sy); void cairo_matrix_init_rotate (cairo_matrix_t *matrix, double radians); void cairo_matrix_translate (cairo_matrix_t *matrix, double tx, double ty); void cairo_matrix_scale (cairo_matrix_t *matrix, double sx, double sy); void cairo_matrix_rotate (cairo_matrix_t *matrix, double radians); cairo_status_t cairo_matrix_invert (cairo_matrix_t *matrix); void cairo_matrix_multiply (cairo_matrix_t *result, const cairo_matrix_t *a, const cairo_matrix_t *b); void cairo_matrix_transform_distance (const cairo_matrix_t *matrix, double *dx, double *dy); void cairo_matrix_transform_point (const cairo_matrix_t *matrix, double *x, double *y); typedef struct _cairo_region cairo_region_t; typedef enum _cairo_region_overlap { CAIRO_REGION_OVERLAP_IN, CAIRO_REGION_OVERLAP_OUT, CAIRO_REGION_OVERLAP_PART } cairo_region_overlap_t; cairo_region_t * cairo_region_create (void); cairo_region_t * cairo_region_create_rectangle (const cairo_rectangle_int_t *rectangle); cairo_region_t * cairo_region_create_rectangles (const cairo_rectangle_int_t *rects, int count); cairo_region_t * cairo_region_copy (const cairo_region_t *original); cairo_region_t * cairo_region_reference (cairo_region_t *region); void cairo_region_destroy (cairo_region_t *region); cairo_bool_t cairo_region_equal (const cairo_region_t *a, const cairo_region_t *b); cairo_status_t cairo_region_status (const cairo_region_t *region); void cairo_region_get_extents (const cairo_region_t *region, cairo_rectangle_int_t *extents); int cairo_region_num_rectangles (const cairo_region_t *region); void cairo_region_get_rectangle (const cairo_region_t *region, int nth, cairo_rectangle_int_t *rectangle); cairo_bool_t cairo_region_is_empty (const cairo_region_t *region); cairo_region_overlap_t cairo_region_contains_rectangle (const cairo_region_t *region, const cairo_rectangle_int_t *rectangle); cairo_bool_t cairo_region_contains_point (const cairo_region_t *region, int x, int y); void cairo_region_translate (cairo_region_t *region, int dx, int dy); cairo_status_t cairo_region_subtract (cairo_region_t *dst, const cairo_region_t *other); cairo_status_t cairo_region_subtract_rectangle (cairo_region_t *dst, const cairo_rectangle_int_t *rectangle); cairo_status_t cairo_region_intersect (cairo_region_t *dst, const cairo_region_t *other); cairo_status_t cairo_region_intersect_rectangle (cairo_region_t *dst, const cairo_rectangle_int_t *rectangle); cairo_status_t cairo_region_union (cairo_region_t *dst, const cairo_region_t *other); cairo_status_t cairo_region_union_rectangle (cairo_region_t *dst, const cairo_rectangle_int_t *rectangle); cairo_status_t cairo_region_xor (cairo_region_t *dst, const cairo_region_t *other); cairo_status_t cairo_region_xor_rectangle (cairo_region_t *dst, const cairo_rectangle_int_t *rectangle); void cairo_debug_reset_static_data (void); const int CAIRO_PDF_OUTLINE_ROOT = 0; typedef enum _cairo_pdf_version { CAIRO_PDF_VERSION_1_4, CAIRO_PDF_VERSION_1_5 } cairo_pdf_version_t; cairo_surface_t * cairo_pdf_surface_create (const char *filename, double width_in_points, double height_in_points); cairo_surface_t * cairo_pdf_surface_create_for_stream (cairo_write_func_t write_func, void *closure, double width_in_points, double height_in_points); void cairo_pdf_surface_restrict_to_version (cairo_surface_t *surface, cairo_pdf_version_t version); void cairo_pdf_get_versions (cairo_pdf_version_t const **versions, int *num_versions); const char * cairo_pdf_version_to_string (cairo_pdf_version_t version); void cairo_pdf_surface_set_size (cairo_surface_t *surface, double width_in_points, double height_in_points); typedef enum _cairo_pdf_outline_flags { CAIRO_PDF_OUTLINE_FLAG_OPEN = 0x1, CAIRO_PDF_OUTLINE_FLAG_BOLD = 0x2, CAIRO_PDF_OUTLINE_FLAG_ITALIC = 0x4, } cairo_pdf_outline_flags_t; int cairo_pdf_surface_add_outline (cairo_surface_t *surface, int parent_id, const char *utf8, const char *link_attribs, cairo_pdf_outline_flags_t flags); typedef enum _cairo_pdf_metadata { CAIRO_PDF_METADATA_TITLE, CAIRO_PDF_METADATA_AUTHOR, CAIRO_PDF_METADATA_SUBJECT, CAIRO_PDF_METADATA_KEYWORDS, CAIRO_PDF_METADATA_CREATOR, CAIRO_PDF_METADATA_CREATE_DATE, CAIRO_PDF_METADATA_MOD_DATE, } cairo_pdf_metadata_t; void cairo_pdf_surface_set_metadata (cairo_surface_t *surface, cairo_pdf_metadata_t metadata, const char *utf8); void cairo_pdf_surface_set_page_label (cairo_surface_t *surface, const char *utf8); void cairo_pdf_surface_set_thumbnail_size (cairo_surface_t *surface, int width, int height); typedef enum _cairo_ps_level { CAIRO_PS_LEVEL_2, CAIRO_PS_LEVEL_3 } cairo_ps_level_t; cairo_surface_t * cairo_ps_surface_create (const char *filename, double width_in_points, double height_in_points); cairo_surface_t * cairo_ps_surface_create_for_stream (cairo_write_func_t write_func, void *closure, double width_in_points, double height_in_points); void cairo_ps_surface_restrict_to_level (cairo_surface_t *surface, cairo_ps_level_t level); void cairo_ps_get_levels (cairo_ps_level_t const **levels, int *num_levels); const char * cairo_ps_level_to_string (cairo_ps_level_t level); void cairo_ps_surface_set_eps (cairo_surface_t *surface, cairo_bool_t eps); cairo_bool_t cairo_ps_surface_get_eps (cairo_surface_t *surface); void cairo_ps_surface_set_size (cairo_surface_t *surface, double width_in_points, double height_in_points); void cairo_ps_surface_dsc_comment (cairo_surface_t *surface, const char *comment); void cairo_ps_surface_dsc_begin_setup (cairo_surface_t *surface); void cairo_ps_surface_dsc_begin_page_setup (cairo_surface_t *surface); typedef enum _cairo_svg_version { CAIRO_SVG_VERSION_1_1, CAIRO_SVG_VERSION_1_2 } cairo_svg_version_t; typedef enum _cairo_svg_unit { CAIRO_SVG_UNIT_USER = 0, CAIRO_SVG_UNIT_EM, CAIRO_SVG_UNIT_EX, CAIRO_SVG_UNIT_PX, CAIRO_SVG_UNIT_IN, CAIRO_SVG_UNIT_CM, CAIRO_SVG_UNIT_MM, CAIRO_SVG_UNIT_PT, CAIRO_SVG_UNIT_PC, CAIRO_SVG_UNIT_PERCENT } cairo_svg_unit_t; cairo_surface_t * cairo_svg_surface_create (const char *filename, double width_in_points, double height_in_points); cairo_surface_t * cairo_svg_surface_create_for_stream (cairo_write_func_t write_func, void *closure, double width_in_points, double height_in_points); void cairo_svg_surface_restrict_to_version (cairo_surface_t *surface, cairo_svg_version_t version); void cairo_svg_get_versions (cairo_svg_version_t const **versions, int *num_versions); const char * cairo_svg_version_to_string (cairo_svg_version_t version); void cairo_svg_surface_set_document_unit (cairo_surface_t *surface, cairo_svg_unit_t unit); cairo_svg_unit_t cairo_svg_surface_get_document_unit (cairo_surface_t *surface); typedef void* HDC; typedef void* HFONT; typedef void LOGFONTW; cairo_surface_t * cairo_win32_surface_create (HDC hdc); cairo_surface_t * cairo_win32_surface_create_with_format (HDC hdc, cairo_format_t format); cairo_surface_t * cairo_win32_printing_surface_create (HDC hdc); cairo_surface_t * cairo_win32_surface_create_with_ddb (HDC hdc, cairo_format_t format, int width, int height); cairo_surface_t * cairo_win32_surface_create_with_dib (cairo_format_t format, int width, int height); HDC cairo_win32_surface_get_dc (cairo_surface_t *surface); cairo_surface_t * cairo_win32_surface_get_image (cairo_surface_t *surface); cairo_font_face_t * cairo_win32_font_face_create_for_logfontw (LOGFONTW *logfont); cairo_font_face_t * cairo_win32_font_face_create_for_hfont (HFONT font); cairo_font_face_t * cairo_win32_font_face_create_for_logfontw_hfont (LOGFONTW *logfont, HFONT font); cairo_status_t cairo_win32_scaled_font_select_font (cairo_scaled_font_t *scaled_font, HDC hdc); void cairo_win32_scaled_font_done_font (cairo_scaled_font_t *scaled_font); double cairo_win32_scaled_font_get_metrics_factor (cairo_scaled_font_t *scaled_font); void cairo_win32_scaled_font_get_logical_to_device (cairo_scaled_font_t *scaled_font, cairo_matrix_t *logical_to_device); void cairo_win32_scaled_font_get_device_to_logical (cairo_scaled_font_t *scaled_font, cairo_matrix_t *device_to_logical); typedef void* CGContextRef; typedef void* CGFontRef; typedef void* ATSUFontID; cairo_surface_t * cairo_quartz_surface_create (cairo_format_t format, unsigned int width, unsigned int height); cairo_surface_t * cairo_quartz_surface_create_for_cg_context (CGContextRef cgContext, unsigned int width, unsigned int height); CGContextRef cairo_quartz_surface_get_cg_context (cairo_surface_t *surface); cairo_font_face_t * cairo_quartz_font_face_create_for_cgfont (CGFontRef font); cairo_font_face_t * cairo_quartz_font_face_create_for_atsu_font_id (ATSUFontID font_id); """ _CAIRO_XCB_HEADERS = r""" cairo_surface_t * cairo_xcb_surface_create (xcb_connection_t *connection, xcb_drawable_t drawable, xcb_visualtype_t *visual, int width, int height); cairo_surface_t * cairo_xcb_surface_create_for_bitmap (xcb_connection_t *connection, xcb_screen_t *screen, xcb_pixmap_t bitmap, int width, int height); cairo_surface_t * cairo_xcb_surface_create_with_xrender_format (xcb_connection_t *connection, xcb_screen_t *screen, xcb_drawable_t drawable, xcb_render_pictforminfo_t *format, int width, int height); void cairo_xcb_surface_set_size (cairo_surface_t *surface, int width, int height); void cairo_xcb_surface_set_drawable (cairo_surface_t *surface, xcb_drawable_t drawable, int width, int height); xcb_connection_t * cairo_xcb_device_get_connection (cairo_device_t *device); void cairo_xcb_device_debug_cap_xshm_version (cairo_device_t *device, int major_version, int minor_version); void cairo_xcb_device_debug_cap_xrender_version (cairo_device_t *device, int major_version, int minor_version); void cairo_xcb_device_debug_set_precision (cairo_device_t *device, int precision); int cairo_xcb_device_debug_get_precision (cairo_device_t *device); """ cairocffi-1.2.0/cairocffi/context.py000066400000000000000000002454671374663167600174670ustar00rootroot00000000000000""" cairocffi.context ~~~~~~~~~~~~~~~~~ Bindings for Context objects. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ from . import _check_status, _keepref, cairo, constants, ffi from .fonts import FontFace, FontOptions, ScaledFont, _encode_string from .matrix import Matrix from .patterns import Pattern from .surfaces import Surface PATH_POINTS_PER_TYPE = { constants.PATH_MOVE_TO: 1, constants.PATH_LINE_TO: 1, constants.PATH_CURVE_TO: 3, constants.PATH_CLOSE_PATH: 0 } def _encode_path(path_items): """Take an iterable of ``(path_operation, coordinates)`` tuples in the same format as from :meth:`Context.copy_path` and return a ``(path, data)`` tuple of cdata object. The first cdata object is a ``cairo_path_t *`` pointer that can be used as long as both objects live. """ points_per_type = PATH_POINTS_PER_TYPE path_items = list(path_items) length = 0 for path_type, coordinates in path_items: num_points = points_per_type[path_type] length += 1 + num_points # 1 header + N points if len(coordinates) != 2 * num_points: raise ValueError('Expected %d coordinates, got %d.' % ( 2 * num_points, len(coordinates))) data = ffi.new('cairo_path_data_t[]', length) position = 0 for path_type, coordinates in path_items: header = data[position].header header.type = path_type header.length = 1 + len(coordinates) // 2 position += 1 for i in range(0, len(coordinates), 2): point = data[position].point point.x = coordinates[i] point.y = coordinates[i + 1] position += 1 path = ffi.new( 'cairo_path_t *', {'status': constants.STATUS_SUCCESS, 'data': data, 'num_data': length}) return path, data def _iter_path(pointer): """Take a cairo_path_t * pointer and yield ``(path_operation, coordinates)`` tuples. See :meth:`Context.copy_path` for the data structure. """ _check_status(pointer.status) data = pointer.data num_data = pointer.num_data points_per_type = PATH_POINTS_PER_TYPE position = 0 while position < num_data: path_data = data[position] path_type = path_data.header.type points = () for i in range(points_per_type[path_type]): point = data[position + i + 1].point points += (point.x, point.y) yield (path_type, points) position += path_data.header.length class Context(object): """A :class:`Context` contains the current state of the rendering device, including coordinates of yet to be drawn shapes. Cairo contexts are central to cairo and all drawing with cairo is always done to a :class:`Context` object. :param target: The target :class:`Surface` object. Cairo contexts can be used as Python :ref:`context managers `. See :meth:`save`. """ def __init__(self, target): self._init_pointer(cairo.cairo_create(target._pointer)) def _init_pointer(self, pointer): self._pointer = ffi.gc(pointer, _keepref(cairo, cairo.cairo_destroy)) self._check_status() def _check_status(self): _check_status(cairo.cairo_status(self._pointer)) @classmethod def _from_pointer(cls, pointer, incref): """Wrap an existing :c:type:`cairo_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count ` now. :return: A new :class:`Context` instance. """ if pointer == ffi.NULL: raise ValueError('Null pointer') if incref: cairo.cairo_reference(pointer) self = object.__new__(cls) cls._init_pointer(self, pointer) return self def get_target(self): """Return this context’s target surface. :returns: An instance of :class:`Surface` or one of its sub-classes, a new Python object referencing the existing cairo surface. """ return Surface._from_pointer( cairo.cairo_get_target(self._pointer), incref=True) # # Save / restore # def save(self): """Makes a copy of the current state of this context and saves it on an internal stack of saved states. When :meth:`restore` is called, the context will be restored to the saved state. Multiple calls to :meth:`save` and :meth:`restore` can be nested; each call to :meth:`restore` restores the state from the matching paired :meth:`save`. Instead of using :meth:`save` and :meth:`restore` directly, it is recommended to use a :ref:`with statement `:: with context: do_something(context) … which is equivalent to:: context.save() try: do_something(context) finally: context.restore() """ cairo.cairo_save(self._pointer) self._check_status() def restore(self): """Restores the context to the state saved by a preceding call to :meth:`save` and removes that state from the stack of saved states. """ cairo.cairo_restore(self._pointer) self._check_status() def __enter__(self): self.save() return self def __exit__(self, exc_type, exc_val, exc_tb): self.restore() # # Groups # def push_group(self): """Temporarily redirects drawing to an intermediate surface known as a group. The redirection lasts until the group is completed by a call to :meth:`pop_group` or :meth:`pop_group_to_source`. These calls provide the result of any drawing to the group as a pattern, (either as an explicit object, or set as the source pattern). This group functionality can be convenient for performing intermediate compositing. One common use of a group is to render objects as opaque within the group, (so that they occlude each other), and then blend the result with translucence onto the destination. Groups can be nested arbitrarily deep by making balanced calls to :meth:`push_group` / :meth:`pop_group`. Each call pushes / pops the new target group onto / from a stack. The :meth:`group` method calls :meth:`save` so that any changes to the graphics state will not be visible outside the group, (the pop_group methods call :meth:`restore`). By default the intermediate group will have a content type of :obj:`COLOR_ALPHA `. Other content types can be chosen for the group by using :meth:`push_group_with_content` instead. As an example, here is how one might fill and stroke a path with translucence, but without any portion of the fill being visible under the stroke:: context.push_group() context.set_source(fill_pattern) context.fill_preserve() context.set_source(stroke_pattern) context.stroke() context.pop_group_to_source() context.paint_with_alpha(alpha) """ cairo.cairo_push_group(self._pointer) self._check_status() def push_group_with_content(self, content): """Temporarily redirects drawing to an intermediate surface known as a group. The redirection lasts until the group is completed by a call to :meth:`pop_group` or :meth:`pop_group_to_source`. These calls provide the result of any drawing to the group as a pattern, (either as an explicit object, or set as the source pattern). The group will have a content type of :obj:`content`. The ability to control this content type is the only distinction between this method and :meth:`push_group` which you should see for a more detailed description of group rendering. :param content: A :ref:`CONTENT` string. """ cairo.cairo_push_group_with_content(self._pointer, content) self._check_status() def pop_group(self): """Terminates the redirection begun by a call to :meth:`push_group` or :meth:`push_group_with_content` and returns a new pattern containing the results of all drawing operations performed to the group. The :meth:`pop_group` method calls :meth:`restore`, (balancing a call to :meth:`save` by the push_group method), so that any changes to the graphics state will not be visible outside the group. :returns: A newly created :class:`SurfacePattern` containing the results of all drawing operations performed to the group. """ return Pattern._from_pointer( cairo.cairo_pop_group(self._pointer), incref=False) def pop_group_to_source(self): """Terminates the redirection begun by a call to :meth:`push_group` or :meth:`push_group_with_content` and installs the resulting pattern as the source pattern in the given cairo context. The behavior of this method is equivalent to:: context.set_source(context.pop_group()) """ cairo.cairo_pop_group_to_source(self._pointer) self._check_status() def get_group_target(self): """Returns the current destination surface for the context. This is either the original target surface as passed to :class:`Context` or the target surface for the current group as started by the most recent call to :meth:`push_group` or :meth:`push_group_with_content`. """ return Surface._from_pointer( cairo.cairo_get_group_target(self._pointer), incref=True) # # Sources # def set_source_rgba(self, red, green, blue, alpha=1): """Sets the source pattern within this context to a solid color. This color will then be used for any subsequent drawing operation until a new source pattern is set. The color and alpha components are floating point numbers in the range 0 to 1. If the values passed in are outside that range, they will be clamped. The default source pattern is opaque black, (that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``). :param red: Red component of the color. :param green: Green component of the color. :param blue: Blue component of the color. :param alpha: Alpha component of the color. 1 (the default) is opaque, 0 fully transparent. :type red: float :type green: float :type blue: float :type alpha: float """ cairo.cairo_set_source_rgba(self._pointer, red, green, blue, alpha) self._check_status() def set_source_rgb(self, red, green, blue): """Same as :meth:`set_source_rgba` with alpha always 1. Exists for compatibility with pycairo. """ cairo.cairo_set_source_rgb(self._pointer, red, green, blue) self._check_status() def set_source_surface(self, surface, x=0, y=0): """This is a convenience method for creating a pattern from surface and setting it as the source in this context with :meth:`set_source`. The :obj:`x` and :obj:`y` parameters give the user-space coordinate at which the surface origin should appear. (The surface origin is its upper-left corner before any transformation has been applied.) The :obj:`x` and :obj:`y` parameters are negated and then set as translation values in the pattern matrix. Other than the initial translation pattern matrix, as described above, all other pattern attributes, (such as its extend mode), are set to the default values as in :class:`SurfacePattern`. The resulting pattern can be queried with :meth:`get_source` so that these attributes can be modified if desired, (eg. to create a repeating pattern with :meth:`Pattern.set_extend`). :param surface: A :class:`Surface` to be used to set the source pattern. :param x: User-space X coordinate for surface origin. :param y: User-space Y coordinate for surface origin. :type x: float :type y: float """ cairo.cairo_set_source_surface(self._pointer, surface._pointer, x, y) self._check_status() def set_source(self, source): """Sets the source pattern within this context to :obj:`source`. This pattern will then be used for any subsequent drawing operation until a new source pattern is set. .. note:: The pattern's transformation matrix will be locked to the user space in effect at the time of :meth:`set_source`. This means that further modifications of the current transformation matrix will not affect the source pattern. See :meth:`Pattern.set_matrix`. The default source pattern is opaque black, (that is, it is equivalent to ``context.set_source_rgba(0, 0, 0)``). :param source: A :class:`Pattern` to be used as the source for subsequent drawing operations. """ cairo.cairo_set_source(self._pointer, source._pointer) self._check_status() def get_source(self): """Return this context’s source. :returns: An instance of :class:`Pattern` or one of its sub-classes, a new Python object referencing the existing cairo pattern. """ return Pattern._from_pointer( cairo.cairo_get_source(self._pointer), incref=True) # # Context parameters # def set_antialias(self, antialias): """Set the :ref:`ANTIALIAS` of the rasterizer used for drawing shapes. This value is a hint, and a particular backend may or may not support a particular value. At the current time, no backend supports :obj:`SUBPIXEL ` when drawing shapes. Note that this option does not affect text rendering, instead see :meth:`FontOptions.set_antialias`. :param antialias: An :ref:`ANTIALIAS` string. """ cairo.cairo_set_antialias(self._pointer, antialias) self._check_status() def get_antialias(self): """Return the :ref:`ANTIALIAS` string.""" return cairo.cairo_get_antialias(self._pointer) def set_dash(self, dashes, offset=0): """Sets the dash pattern to be used by :meth:`stroke`. A dash pattern is specified by dashes, a list of positive values. Each value provides the length of alternate "on" and "off" portions of the stroke. :obj:`offset` specifies an offset into the pattern at which the stroke begins. Each "on" segment will have caps applied as if the segment were a separate sub-path. In particular, it is valid to use an "on" length of 0 with :obj:`LINE_CAP_ROUND` or :obj:`LINE_CAP_SQUARE` in order to distributed dots or squares along a path. Note: The length values are in user-space units as evaluated at the time of stroking. This is not necessarily the same as the user space at the time of :meth:`set_dash`. If :obj:`dashes` is empty dashing is disabled. If it is of length 1 a symmetric pattern is assumed with alternating on and off portions of the size specified by the single value. :param dashes: A list of floats specifying alternate lengths of on and off stroke portions. :type offset: float :param offset: An offset into the dash pattern at which the stroke should start. :raises: :exc:`CairoError` if any value in dashes is negative, or if all values are 0. The context will be put into an error state. """ cairo.cairo_set_dash( self._pointer, ffi.new('double[]', dashes), len(dashes), offset) self._check_status() def get_dash(self): """Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect. """ dashes = ffi.new('double[]', cairo.cairo_get_dash_count(self._pointer)) offset = ffi.new('double *') cairo.cairo_get_dash(self._pointer, dashes, offset) self._check_status() return list(dashes), offset[0] def get_dash_count(self): """Same as ``len(context.get_dash()[0])``.""" # Not really useful with get_dash() returning a list, # but retained for compatibility with pycairo. return cairo.cairo_get_dash_count(self._pointer) def set_fill_rule(self, fill_rule): """Set the current :ref:`FILL_RULE` within the cairo context. The fill rule is used to determine which regions are inside or outside a complex (potentially self-intersecting) path. The current fill rule affects both :meth:`fill` and :meth:`clip`. The default fill rule is :obj:`WINDING `. :param fill_rule: A :ref:`FILL_RULE` string. """ cairo.cairo_set_fill_rule(self._pointer, fill_rule) self._check_status() def get_fill_rule(self): """Return the current :ref:`FILL_RULE` string.""" return cairo.cairo_get_fill_rule(self._pointer) def set_line_cap(self, line_cap): """Set the current :ref:`LINE_CAP` within the cairo context. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default line cap is :obj:`BUTT `. :param line_cap: A :ref:`LINE_CAP` string. """ cairo.cairo_set_line_cap(self._pointer, line_cap) self._check_status() def get_line_cap(self): """Return the current :ref:`LINE_CAP` string.""" return cairo.cairo_get_line_cap(self._pointer) def set_line_join(self, line_join): """Set the current :ref:`LINE_JOIN` within the cairo context. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default line cap is :obj:`MITER `. :param line_join: A :ref:`LINE_JOIN` string. """ cairo.cairo_set_line_join(self._pointer, line_join) self._check_status() def get_line_join(self): """Return the current :ref:`LINE_JOIN` string.""" return cairo.cairo_get_line_join(self._pointer) def set_line_width(self, width): """Sets the current line width within the cairo context. The line width value specifies the diameter of a pen that is circular in user space, (though device-space pen may be an ellipse in general due to scaling / shear / rotation of the CTM). .. note:: When the description above refers to user space and CTM it refers to the user space and CTM in effect at the time of the stroking operation, not the user space and CTM in effect at the time of the call to :meth:`set_line_width`. The simplest usage makes both of these spaces identical. That is, if there is no change to the CTM between a call to :meth:`set_line_width` and the stroking operation, then one can just pass user-space values to :meth:`set_line_width` and ignore this note. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default line width value is 2.0. :type width: float :param width: The new line width. """ cairo.cairo_set_line_width(self._pointer, width) self._check_status() def get_line_width(self): """Return the current line width as a float.""" return cairo.cairo_get_line_width(self._pointer) def set_miter_limit(self, limit): """Sets the current miter limit within the cairo context. If the current line join style is set to :obj:`MITER ` (see :meth:`set_line_join`), the miter limit is used to determine whether the lines should be joined with a bevel instead of a miter. Cairo divides the length of the miter by the line width. If the result is greater than the miter limit, the style is converted to a bevel. As with the other stroke parameters, the current line cap style is examined by :meth:`stroke`, :meth:`stroke_extents`, and :meth:`stroke_to_path`, but does not have any effect during path construction. The default miter limit value is 10.0, which will convert joins with interior angles less than 11 degrees to bevels instead of miters. For reference, a miter limit of 2.0 makes the miter cutoff at 60 degrees, and a miter limit of 1.414 makes the cutoff at 90 degrees. A miter limit for a desired angle can be computed as: ``miter_limit = 1. / sin(angle / 2.)`` :param limit: The miter limit to set. :type limit: float """ cairo.cairo_set_miter_limit(self._pointer, limit) self._check_status() def get_miter_limit(self): """Return the current miter limit as a float.""" return cairo.cairo_get_miter_limit(self._pointer) def set_operator(self, operator): """Set the current :ref:`OPERATOR` to be used for all drawing operations. The default operator is :obj:`OVER `. :param operator: A :ref:`OPERATOR` string. """ cairo.cairo_set_operator(self._pointer, operator) self._check_status() def get_operator(self): """Return the current :ref:`OPERATOR` string.""" return cairo.cairo_get_operator(self._pointer) def set_tolerance(self, tolerance): """Sets the tolerance used when converting paths into trapezoids. Curved segments of the path will be subdivided until the maximum deviation between the original path and the polygonal approximation is less than tolerance. The default value is 0.1. A larger value will give better performance, a smaller value, better appearance. (Reducing the value from the default value of 0.1 is unlikely to improve appearance significantly.) The accuracy of paths within Cairo is limited by the precision of its internal arithmetic, and the prescribed tolerance is restricted to the smallest representable internal value. :type tolerance: float :param tolerance: The tolerance, in device units (typically pixels) """ cairo.cairo_set_tolerance(self._pointer, tolerance) self._check_status() def get_tolerance(self): """Return the current tolerance as a float.""" return cairo.cairo_get_tolerance(self._pointer) # # CTM: Current transformation matrix # def translate(self, tx, ty): """Modifies the current transformation matrix (CTM) by translating the user-space origin by ``(tx, ty)``. This offset is interpreted as a user-space coordinate according to the CTM in place before the new call to :meth:`translate`. In other words, the translation of the user-space origin takes place after any existing transformation. :param tx: Amount to translate in the X direction :param ty: Amount to translate in the Y direction :type tx: float :type ty: float """ cairo.cairo_translate(self._pointer, tx, ty) self._check_status() def scale(self, sx, sy=None): """Modifies the current transformation matrix (CTM) by scaling the X and Y user-space axes by :obj:`sx` and :obj:`sy` respectively. The scaling of the axes takes place after any existing transformation of user space. If :obj:`sy` is omitted, it is the same as :obj:`sx` so that scaling preserves aspect ratios. :param sx: Scale factor in the X direction. :param sy: Scale factor in the Y direction. :type sx: float :type sy: float """ if sy is None: sy = sx cairo.cairo_scale(self._pointer, sx, sy) self._check_status() def rotate(self, radians): """Modifies the current transformation matrix (CTM) by rotating the user-space axes by angle :obj:`radians`. The rotation of the axes takes places after any existing transformation of user space. :type radians: float :param radians: Angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction. """ cairo.cairo_rotate(self._pointer, radians) self._check_status() def transform(self, matrix): """Modifies the current transformation matrix (CTM) by applying :obj:`matrix` as an additional transformation. The new transformation of user space takes place after any existing transformation. :param matrix: A transformation :class:`Matrix` to be applied to the user-space axes. """ cairo.cairo_transform(self._pointer, matrix._pointer) self._check_status() def set_matrix(self, matrix): """Modifies the current transformation matrix (CTM) by setting it equal to :obj:`matrix`. :param matrix: A transformation :class:`Matrix` from user space to device space. """ cairo.cairo_set_matrix(self._pointer, matrix._pointer) self._check_status() def get_matrix(self): """Return a copy of the current transformation matrix (CTM).""" matrix = Matrix() cairo.cairo_get_matrix(self._pointer, matrix._pointer) self._check_status() return matrix def identity_matrix(self): """Resets the current transformation matrix (CTM) by setting it equal to the identity matrix. That is, the user-space and device-space axes will be aligned and one user-space unit will transform to one device-space unit. """ cairo.cairo_identity_matrix(self._pointer) self._check_status() def user_to_device(self, x, y): """Transform a coordinate from user space to device space by multiplying the given point by the current transformation matrix (CTM). :param x: X position. :param y: Y position. :type x: float :type y: float :returns: A ``(device_x, device_y)`` tuple of floats. """ xy = ffi.new('double[2]', [x, y]) cairo.cairo_user_to_device(self._pointer, xy + 0, xy + 1) self._check_status() return tuple(xy) def user_to_device_distance(self, dx, dy): """Transform a distance vector from user space to device space. This method is similar to :meth:`Context.user_to_device` except that the translation components of the CTM will be ignored when transforming ``(dx, dy)``. :param dx: X component of a distance vector. :param dy: Y component of a distance vector. :type x: float :type y: float :returns: A ``(device_dx, device_dy)`` tuple of floats. """ xy = ffi.new('double[2]', [dx, dy]) cairo.cairo_user_to_device_distance(self._pointer, xy + 0, xy + 1) self._check_status() return tuple(xy) def device_to_user(self, x, y): """Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM). :param x: X position. :param y: Y position. :type x: float :type y: float :returns: A ``(user_x, user_y)`` tuple of floats. """ xy = ffi.new('double[2]', [x, y]) cairo.cairo_device_to_user(self._pointer, xy + 0, xy + 1) self._check_status() return tuple(xy) def device_to_user_distance(self, dx, dy): """Transform a distance vector from device space to user space. This method is similar to :meth:`Context.device_to_user` except that the translation components of the inverse CTM will be ignored when transforming ``(dx, dy)``. :param dx: X component of a distance vector. :param dy: Y component of a distance vector. :type x: float :type y: float :returns: A ``(user_dx, user_dy)`` tuple of floats. """ xy = ffi.new('double[2]', [dx, dy]) cairo.cairo_device_to_user_distance(self._pointer, xy + 0, xy + 1) self._check_status() return tuple(xy) # # Path # def has_current_point(self): """Returns whether a current point is defined on the current path. See :meth:`get_current_point`. """ return bool(cairo.cairo_has_current_point(self._pointer)) def get_current_point(self): """Return the current point of the current path, which is conceptually the final point reached by the path so far. The current point is returned in the user-space coordinate system. If there is no defined current point or if the context is in an error status, ``(0, 0)`` is returned. It is possible to check this in advance with :meth:`has_current_point`. Most path construction methods alter the current point. See the following for details on how they affect the current point: :meth:`new_path`, :meth:`new_sub_path`, :meth:`append_path`, :meth:`close_path`, :meth:`move_to`, :meth:`line_to`, :meth:`curve_to`, :meth:`rel_move_to`, :meth:`rel_line_to`, :meth:`rel_curve_to`, :meth:`arc`, :meth:`arc_negative`, :meth:`rectangle`, :meth:`text_path`, :meth:`glyph_path`, :meth:`stroke_to_path`. Some methods use and alter the current point but do not otherwise change current path: :meth:`show_text`, :meth:`show_glyphs`, :meth:`show_text_glyphs`. Some methods unset the current path and as a result, current point: :meth:`fill`, :meth:`stroke`. :returns: A ``(x, y)`` tuple of floats, the coordinates of the current point. """ # I’d prefer returning None if self.has_current_point() is False # But keep (0, 0) for compat with pycairo. xy = ffi.new('double[2]') cairo.cairo_get_current_point(self._pointer, xy + 0, xy + 1) self._check_status() return tuple(xy) def new_path(self): """ Clears the current path. After this call there will be no path and no current point. """ cairo.cairo_new_path(self._pointer) self._check_status() def new_sub_path(self): """Begin a new sub-path. Note that the existing path is not affected. After this call there will be no current point. In many cases, this call is not needed since new sub-paths are frequently started with :meth:`move_to`. A call to :meth:`new_sub_path` is particularly useful when beginning a new sub-path with one of the :meth:`arc` calls. This makes things easier as it is no longer necessary to manually compute the arc's initial coordinates for a call to :meth:`move_to`. """ cairo.cairo_new_sub_path(self._pointer) self._check_status() def move_to(self, x, y): """Begin a new sub-path. After this call the current point will be ``(x, y)``. :param x: X position of the new point. :param y: Y position of the new point. :type float: x :type float: y """ cairo.cairo_move_to(self._pointer, x, y) self._check_status() def rel_move_to(self, dx, dy): """Begin a new sub-path. After this call the current point will be offset by ``(dx, dy)``. Given a current point of ``(x, y)``, ``context.rel_move_to(dx, dy)`` is logically equivalent to ``context.move_to(x + dx, y + dy)``. :param dx: The X offset. :param dy: The Y offset. :type float: dx :type float: dy :raises: :exc:`CairoError` if there is no current point. Doing so will cause leave the context in an error state. """ cairo.cairo_rel_move_to(self._pointer, dx, dy) self._check_status() def line_to(self, x, y): """Adds a line to the path from the current point to position ``(x, y)`` in user-space coordinates. After this call the current point will be ``(x, y)``. If there is no current point before the call to :meth:`line_to` this method will behave as ``context.move_to(x, y)``. :param x: X coordinate of the end of the new line. :param y: Y coordinate of the end of the new line. :type float: x :type float: y """ cairo.cairo_line_to(self._pointer, x, y) self._check_status() def rel_line_to(self, dx, dy): """ Relative-coordinate version of :meth:`line_to`. Adds a line to the path from the current point to a point that is offset from the current point by ``(dx, dy)`` in user space. After this call the current point will be offset by ``(dx, dy)``. Given a current point of ``(x, y)``, ``context.rel_line_to(dx, dy)`` is logically equivalent to ``context.line_to(x + dx, y + dy)``. :param dx: The X offset to the end of the new line. :param dy: The Y offset to the end of the new line. :type float: dx :type float: dy :raises: :exc:`CairoError` if there is no current point. Doing so will cause leave the context in an error state. """ cairo.cairo_rel_line_to(self._pointer, dx, dy) self._check_status() def rectangle(self, x, y, width, height): """Adds a closed sub-path rectangle of the given size to the current path at position ``(x, y)`` in user-space coordinates. This method is logically equivalent to:: context.move_to(x, y) context.rel_line_to(width, 0) context.rel_line_to(0, height) context.rel_line_to(-width, 0) context.close_path() :param x: The X coordinate of the top left corner of the rectangle. :param y: The Y coordinate of the top left corner of the rectangle. :param width: Width of the rectangle. :param height: Height of the rectangle. :type float: x :type float: y :type float: width :type float: heigth """ cairo.cairo_rectangle(self._pointer, x, y, width, height) self._check_status() def arc(self, xc, yc, radius, angle1, angle2): """Adds a circular arc of the given radius to the current path. The arc is centered at ``(xc, yc)``, begins at :obj:`angle1` and proceeds in the direction of increasing angles to end at :obj:`angle2`. If :obj:`angle2` is less than :obj:`angle1` it will be progressively increased by ``2 * pi`` until it is greater than :obj:`angle1`. If there is a current point, an initial line segment will be added to the path to connect the current point to the beginning of the arc. If this initial line is undesired, it can be avoided by calling :meth:`new_sub_path` before calling :meth:`arc`. Angles are measured in radians. An angle of 0 is in the direction of the positive X axis (in user space). An angle of ``pi / 2`` radians (90 degrees) is in the direction of the positive Y axis (in user space). Angles increase in the direction from the positive X axis toward the positive Y axis. So with the default transformation matrix, angles increase in a clockwise direction. (To convert from degrees to radians, use ``degrees * pi / 180``.) This method gives the arc in the direction of increasing angles; see :meth:`arc_negative` to get the arc in the direction of decreasing angles. The arc is circular in user space. To achieve an elliptical arc, you can scale the current transformation matrix by different amounts in the X and Y directions. For example, to draw an ellipse in the box given by x, y, width, height:: from math import pi with context: context.translate(x + width / 2., y + height / 2.) context.scale(width / 2., height / 2.) context.arc(0, 0, 1, 0, 2 * pi) :param xc: X position of the center of the arc. :param yc: Y position of the center of the arc. :param radius: The radius of the arc. :param angle1: The start angle, in radians. :param angle2: The end angle, in radians. :type xc: float :type yc: float :type radius: float :type angle1: float :type angle2: float """ cairo.cairo_arc(self._pointer, xc, yc, radius, angle1, angle2) self._check_status() def arc_negative(self, xc, yc, radius, angle1, angle2): """Adds a circular arc of the given radius to the current path. The arc is centered at ``(xc, yc)``, begins at :obj:`angle1` and proceeds in the direction of decreasing angles to end at :obj:`angle2`. If :obj:`angle2` is greater than :obj:`angle1` it will be progressively decreased by ``2 * pi`` until it is greater than :obj:`angle1`. See :meth:`arc` for more details. This method differs only in the direction of the arc between the two angles. :param xc: X position of the center of the arc. :param yc: Y position of the center of the arc. :param radius: The radius of the arc. :param angle1: The start angle, in radians. :param angle2: The end angle, in radians. :type xc: float :type yc: float :type radius: float :type angle1: float :type angle2: float """ cairo.cairo_arc_negative(self._pointer, xc, yc, radius, angle1, angle2) self._check_status() def curve_to(self, x1, y1, x2, y2, x3, y3): """Adds a cubic Bézier spline to the path from the current point to position ``(x3, y3)`` in user-space coordinates, using ``(x1, y1)`` and ``(x2, y2)`` as the control points. After this call the current point will be ``(x3, y3)``. If there is no current point before the call to :meth:`curve_to` this method will behave as if preceded by a call to ``context.move_to(x1, y1)``. :param x1: The X coordinate of the first control point. :param y1: The Y coordinate of the first control point. :param x2: The X coordinate of the second control point. :param y2: The Y coordinate of the second control point. :param x3: The X coordinate of the end of the curve. :param y3: The Y coordinate of the end of the curve. :type x1: float :type y1: float :type x2: float :type y2: float :type x3: float :type y3: float """ cairo.cairo_curve_to(self._pointer, x1, y1, x2, y2, x3, y3) self._check_status() def rel_curve_to(self, dx1, dy1, dx2, dy2, dx3, dy3): """ Relative-coordinate version of :meth:`curve_to`. All offsets are relative to the current point. Adds a cubic Bézier spline to the path from the current point to a point offset from the current point by ``(dx3, dy3)``, using points offset by ``(dx1, dy1)`` and ``(dx2, dy2)`` as the control points. After this call the current point will be offset by ``(dx3, dy3)``. Given a current point of ``(x, y)``, ``context.rel_curve_to(dx1, dy1, dx2, dy2, dx3, dy3)`` is logically equivalent to ``context.curve_to(x+dx1, y+dy1, x+dx2, y+dy2, x+dx3, y+dy3)``. :param dx1: The X offset to the first control point. :param dy1: The Y offset to the first control point. :param dx2: The X offset to the second control point. :param dy2: The Y offset to the second control point. :param dx3: The X offset to the end of the curve. :param dy3: The Y offset to the end of the curve. :type dx1: float :type dy1: float :type dx2: float :type dy2: float :type dx3: float :type dy3: float :raises: :exc:`CairoError` if there is no current point. Doing so will cause leave the context in an error state. """ cairo.cairo_rel_curve_to(self._pointer, dx1, dy1, dx2, dy2, dx3, dy3) self._check_status() def text_path(self, text): """Adds closed paths for text to the current path. The generated path if filled, achieves an effect similar to that of :meth:`show_text`. Text conversion and positioning is done similar to :meth:`show_text`. Like :meth:`show_text`, after this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for chaining multiple calls to to :meth:`text_path` without having to set current point in between. :param text: The text to show, as an Unicode or UTF-8 string. .. note:: The :meth:`text_path` method is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See :ref:`fonts` for details, and :meth:`glyph_path` for the "real" text path API in cairo. """ cairo.cairo_text_path(self._pointer, _encode_string(text)) self._check_status() def glyph_path(self, glyphs): """Adds closed paths for the glyphs to the current path. The generated path if filled, achieves an effect similar to that of :meth:`show_glyphs`. :param glyphs: The glyphs to show. See :meth:`show_text_glyphs` for the data structure. """ glyphs = ffi.new('cairo_glyph_t[]', glyphs) cairo.cairo_glyph_path(self._pointer, glyphs, len(glyphs)) self._check_status() def close_path(self): """Adds a line segment to the path from the current point to the beginning of the current sub-path, (the most recent point passed to cairo_move_to()), and closes this sub-path. After this call the current point will be at the joined endpoint of the sub-path. The behavior of :meth:`close_path` is distinct from simply calling :meth:`line_to` with the equivalent coordinate in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, there is a line join connecting the final and initial segments of the sub-path. If there is no current point before the call to :meth:`close_path`, this method will have no effect. """ cairo.cairo_close_path(self._pointer) self._check_status() def copy_path(self): """Return a copy of the current path. :returns: A list of ``(path_operation, coordinates)`` tuples of a :ref:`PATH_OPERATION` string and a tuple of floats coordinates whose content depends on the operation type: * :obj:`MOVE_TO `: 1 point ``(x, y)`` * :obj:`LINE_TO `: 1 point ``(x, y)`` * :obj:`CURVE_TO `: 3 points ``(x1, y1, x2, y2, x3, y3)`` * :obj:`CLOSE_PATH ` 0 points ``()`` (empty tuple) """ path = cairo.cairo_copy_path(self._pointer) result = list(_iter_path(path)) cairo.cairo_path_destroy(path) return result def copy_path_flat(self): """Return a flattened copy of the current path This method is like :meth:`copy_path` except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value, see :meth:`set_tolerance`). That is, the result is guaranteed to not have any elements of type :obj:`CURVE_TO ` which will instead be replaced by a series of :obj:`LINE_TO ` elements. :returns: A list of ``(path_operation, coordinates)`` tuples. See :meth:`copy_path` for the data structure. """ path = cairo.cairo_copy_path_flat(self._pointer) result = list(_iter_path(path)) cairo.cairo_path_destroy(path) return result def append_path(self, path): """Append :obj:`path` onto the current path. The path may be either the return value from one of :meth:`copy_path` or :meth:`copy_path_flat` or it may be constructed manually. :param path: An iterable of tuples in the same format as returned by :meth:`copy_path`. """ # Both objects need to stay alive # until after cairo.cairo_append_path() is finished, but not after. path, _ = _encode_path(path) cairo.cairo_append_path(self._pointer, path) self._check_status() def path_extents(self): """Computes a bounding box in user-space coordinates covering the points on the current path. If the current path is empty, returns an empty rectangle ``(0, 0, 0, 0)``. Stroke parameters, fill rule, surface dimensions and clipping are not taken into account. Contrast with :meth:`fill_extents` and :meth:`stroke_extents` which return the extents of only the area that would be "inked" by the corresponding drawing operations. The result of :meth:`path_extents` is defined as equivalent to the limit of :meth:`stroke_extents` with :obj:`LINE_CAP_ROUND` as the line width approaches 0, (but never reaching the empty-rectangle returned by :meth:`stroke_extents` for a line width of 0). Specifically, this means that zero-area sub-paths such as :meth:`move_to`; :meth:`line_to()` segments, (even degenerate cases where the coordinates to both calls are identical), will be considered as contributing to the extents. However, a lone :meth:`move_to` will not contribute to the results of :meth:`path_extents`. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ extents = ffi.new('double[4]') cairo.cairo_path_extents( self._pointer, extents + 0, extents + 1, extents + 2, extents + 3) self._check_status() return tuple(extents) # # Drawing operators # def paint(self): """A drawing operator that paints the current source everywhere within the current clip region. """ cairo.cairo_paint(self._pointer) self._check_status() def paint_with_alpha(self, alpha): """A drawing operator that paints the current source everywhere within the current clip region using a mask of constant alpha value alpha. The effect is similar to :meth:`paint`, but the drawing is faded out using the :obj:`alpha` value. :type alpha: float :param alpha: Alpha value, between 0 (transparent) and 1 (opaque). """ cairo.cairo_paint_with_alpha(self._pointer, alpha) self._check_status() def mask(self, pattern): """A drawing operator that paints the current source using the alpha channel of :obj:`pattern` as a mask. (Opaque areas of :obj:`pattern` are painted with the source, transparent areas are not painted.) :param pattern: A :class:`Pattern` object. """ cairo.cairo_mask(self._pointer, pattern._pointer) self._check_status() def mask_surface(self, surface, surface_x=0, surface_y=0): """A drawing operator that paints the current source using the alpha channel of :obj:`surface` as a mask. (Opaque areas of :obj:`surface` are painted with the source, transparent areas are not painted.) :param pattern: A :class:`Surface` object. :param surface_x: X coordinate at which to place the origin of surface. :param surface_y: Y coordinate at which to place the origin of surface. :type surface_x: float :type surface_y: float """ cairo.cairo_mask_surface( self._pointer, surface._pointer, surface_x, surface_y) self._check_status() def fill(self): """A drawing operator that fills the current path according to the current fill rule, (each sub-path is implicitly closed before being filled). After :meth:`fill`, the current path will be cleared from the cairo context. See :meth:`set_fill_rule` and :meth:`fill_preserve`. """ cairo.cairo_fill(self._pointer) self._check_status() def fill_preserve(self): """A drawing operator that fills the current path according to the current fill rule, (each sub-path is implicitly closed before being filled). Unlike :meth:`fill`, :meth:`fill_preserve` preserves the path within the cairo context. See :meth:`set_fill_rule` and :meth:`fill`. """ cairo.cairo_fill_preserve(self._pointer) self._check_status() def fill_extents(self): """Computes a bounding box in user-space coordinates covering the area that would be affected, (the "inked" area), by a :meth:`fill` operation given the current path and fill parameters. If the current path is empty, returns an empty rectangle ``(0, 0, 0, 0)``. Surface dimensions and clipping are not taken into account. Contrast with :meth:`path_extents` which is similar, but returns non-zero extents for some paths with no inked area, (such as a simple line segment). Note that :meth:`fill_extents` must necessarily do more work to compute the precise inked areas in light of the fill rule, so :meth:`path_extents` may be more desirable for sake of performance if the non-inked path extents are desired. See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ extents = ffi.new('double[4]') cairo.cairo_fill_extents( self._pointer, extents + 0, extents + 1, extents + 2, extents + 3) self._check_status() return tuple(extents) def in_fill(self, x, y): """Tests whether the given point is inside the area that would be affected by a :meth:`fill` operation given the current path and filling parameters. Surface dimensions and clipping are not taken into account. See :meth:`fill`, :meth:`set_fill_rule` and :meth:`fill_preserve`. :param x: X coordinate of the point to test :param y: Y coordinate of the point to test :type x: float :type y: float :returns: A boolean. """ return bool(cairo.cairo_in_fill(self._pointer, x, y)) def stroke(self): """A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. After :meth:`stroke`, the current path will be cleared from the cairo context. See :meth:`set_line_width`, :meth:`set_line_join`, :meth:`set_line_cap`, :meth:`set_dash`, and :meth:`stroke_preserve`. Note: Degenerate segments and sub-paths are treated specially and provide a useful result. These can result in two different situations: 1. Zero-length "on" segments set in :meth:`set_dash`. If the cap style is :obj:`ROUND ` or :obj:`SQUARE ` then these segments will be drawn as circular dots or squares respectively. In the case of :obj:`SQUARE `, the orientation of the squares is determined by the direction of the underlying path. 2. A sub-path created by :meth:`move_to` followed by either a :meth:`close_path` or one or more calls to :meth:`line_to` to the same coordinate as the :meth:`move_to`. If the cap style is :obj:`ROUND ` then these sub-paths will be drawn as circular dots. Note that in the case of :obj:`SQUARE ` a degenerate sub-path will not be drawn at all, (since the correct orientation is indeterminate). In no case will a cap style of :obj:`BUTT ` cause anything to be drawn in the case of either degenerate segments or sub-paths. """ cairo.cairo_stroke(self._pointer) self._check_status() def stroke_preserve(self): """A drawing operator that strokes the current path according to the current line width, line join, line cap, and dash settings. Unlike :meth:`stroke`, :meth:`stroke_preserve` preserves the path within the cairo context. See :meth:`set_line_width`, :meth:`set_line_join`, :meth:`set_line_cap`, :meth:`set_dash`, and :meth:`stroke`. """ cairo.cairo_stroke_preserve(self._pointer) self._check_status() def stroke_extents(self): """Computes a bounding box in user-space coordinates covering the area that would be affected, (the "inked" area), by a :meth:`stroke` operation given the current path and stroke parameters. If the current path is empty, returns an empty rectangle ``(0, 0, 0, 0)``. Surface dimensions and clipping are not taken into account. Note that if the line width is set to exactly zero, then :meth:`stroke_extents` will return an empty rectangle. Contrast with :meth:`path_extents` which can be used to compute the non-empty bounds as the line width approaches zero. Note that :meth:`stroke_extents` must necessarily do more work to compute the precise inked areas in light of the stroke parameters, so :meth:`path_extents` may be more desirable for sake of performance if the non-inked path extents are desired. See :meth:`stroke`, :meth:`set_line_width`, :meth:`set_line_join`, :meth:`set_line_cap`, :meth:`set_dash`, and :meth:`stroke_preserve`. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ extents = ffi.new('double[4]') cairo.cairo_stroke_extents( self._pointer, extents + 0, extents + 1, extents + 2, extents + 3) self._check_status() return tuple(extents) def in_stroke(self, x, y): """Tests whether the given point is inside the area that would be affected by a :meth:`stroke` operation given the current path and stroking parameters. Surface dimensions and clipping are not taken into account. See :meth:`stroke`, :meth:`set_line_width`, :meth:`set_line_join`, :meth:`set_line_cap`, :meth:`set_dash`, and :meth:`stroke_preserve`. :param x: X coordinate of the point to test :param y: Y coordinate of the point to test :type x: float :type y: float :returns: A boolean. """ return bool(cairo.cairo_in_stroke(self._pointer, x, y)) def clip(self): """Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by :meth:`fill` and according to the current fill rule (see :meth:`set_fill_rule`). After :meth:`clip`, the current path will be cleared from the cairo context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region. Calling :meth:`clip` can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling :meth:`clip` within a :meth:`save` / :meth:`restore` pair. The only other means of increasing the size of the clip region is :meth:`reset_clip`. """ cairo.cairo_clip(self._pointer) self._check_status() def clip_preserve(self): """Establishes a new clip region by intersecting the current clip region with the current path as it would be filled by :meth:`fill` and according to the current fill rule (see :meth:`set_fill_rule`). Unlike :meth:`clip`, :meth:`clip_preserve` preserves the path within the cairo context. The current clip region affects all drawing operations by effectively masking out any changes to the surface that are outside the current clip region. Calling :meth:`clip_preserve` can only make the clip region smaller, never larger. But the current clip is part of the graphics state, so a temporary restriction of the clip region can be achieved by calling :meth:`clip_preserve` within a :meth:`save` / :meth:`restore` pair. The only other means of increasing the size of the clip region is :meth:`reset_clip`. """ cairo.cairo_clip_preserve(self._pointer) self._check_status() def clip_extents(self): """Computes a bounding box in user coordinates covering the area inside the current clip. :return: A ``(x1, y1, x2, y2)`` tuple of floats: the left, top, right and bottom of the resulting extents, respectively. """ extents = ffi.new('double[4]') cairo.cairo_clip_extents( self._pointer, extents + 0, extents + 1, extents + 2, extents + 3) self._check_status() return tuple(extents) def copy_clip_rectangle_list(self): """Return the current clip region as a list of rectangles in user coordinates. :return: A list of rectangles, as ``(x, y, width, height)`` tuples of floats. :raises: :exc:`CairoError` if the clip region cannot be represented as a list of user-space rectangles. """ rectangle_list = cairo.cairo_copy_clip_rectangle_list(self._pointer) _check_status(rectangle_list.status) rectangles = rectangle_list.rectangles result = [] for i in range(rectangle_list.num_rectangles): rect = rectangles[i] result.append((rect.x, rect.y, rect.width, rect.height)) cairo.cairo_rectangle_list_destroy(rectangle_list) return result def in_clip(self, x, y): """Tests whether the given point is inside the area that would be visible through the current clip, i.e. the area that would be filled by a :meth:`paint` operation. See :meth:`clip`, and :meth:`clip_preserve`. :param x: X coordinate of the point to test :param y: Y coordinate of the point to test :type x: float :type y: float :returns: A boolean. *New in cairo 1.10.* """ return bool(cairo.cairo_in_clip(self._pointer, x, y)) def reset_clip(self): """Reset the current clip region to its original, unrestricted state. That is, set the clip region to an infinitely large shape containing the target surface. Equivalently, if infinity is too hard to grasp, one can imagine the clip region being reset to the exact bounds of the target surface. Note that code meant to be reusable should not call :meth:`reset_clip` as it will cause results unexpected by higher-level code which calls :meth:`clip`. Consider using :meth:`cairo` and :meth:`restore` around :meth:`clip` as a more robust means of temporarily restricting the clip region. """ cairo.cairo_reset_clip(self._pointer) self._check_status() # # Fonts # def select_font_face(self, family='', slant=constants.FONT_SLANT_NORMAL, weight=constants.FONT_WEIGHT_NORMAL): """Selects a family and style of font from a simplified description as a family name, slant and weight. .. note:: The :meth:`select_font_face` method is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See :ref:`fonts` for details. Cairo provides no operation to list available family names on the system (this is a "toy", remember), but the standard CSS2 generic family names, (``"serif"``, ``"sans-serif"``, ``"cursive"``, ``"fantasy"``, ``"monospace"``), are likely to work as expected. If family starts with the string ``"cairo:"``, or if no native font backends are compiled in, cairo will use an internal font family. The internal font family recognizes many modifiers in the family string, most notably, it recognizes the string ``"monospace"``. That is, the family name ``"cairo:monospace"`` will use the monospace version of the internal font family. If text is drawn without a call to :meth:`select_font_face`, (nor :meth:`set_font_face` nor :meth:`set_scaled_font`), the default family is platform-specific, but is essentially ``"sans-serif"``. Default slant is :obj:`NORMAL `, and default weight is :obj:`NORMAL `. This method is equivalent to a call to :class:`ToyFontFace` followed by :meth:`set_font_face`. """ cairo.cairo_select_font_face( self._pointer, _encode_string(family), slant, weight) self._check_status() def set_font_face(self, font_face): """Replaces the current font face with :obj:`font_face`. :param font_face: A :class:`FontFace` object, or :obj:`None` to restore the default font. """ font_face = font_face._pointer if font_face is not None else ffi.NULL cairo.cairo_set_font_face(self._pointer, font_face) self._check_status() def get_font_face(self): """Return the current font face. :param font_face: A new :class:`FontFace` object wrapping an existing cairo object. """ return FontFace._from_pointer( cairo.cairo_get_font_face(self._pointer), incref=True) def set_font_size(self, size): """Sets the current font matrix to a scale by a factor of :obj:`size`, replacing any font matrix previously set with :meth:`set_font_size` or :meth:`set_font_matrix`. This results in a font size of size user space units. (More precisely, this matrix will result in the font's em-square being a size by size square in user space.) If text is drawn without a call to :meth:`set_font_size`, (nor :meth:`set_font_matrix` nor :meth:`set_scaled_font`), the default font size is 10.0. :param size: The new font size, in user space units :type size: float """ cairo.cairo_set_font_size(self._pointer, size) self._check_status() def set_font_matrix(self, matrix): """Sets the current font matrix to :obj:`matrix`. The font matrix gives a transformation from the design space of the font (in this space, the em-square is 1 unit by 1 unit) to user space. Normally, a simple scale is used (see :meth:`set_font_size`), but a more complex font matrix can be used to shear the font or stretch it unequally along the two axes :param matrix: A :class:`Matrix` describing a transform to be applied to the current font. """ cairo.cairo_set_font_matrix(self._pointer, matrix._pointer) self._check_status() def get_font_matrix(self): """Copies the current font matrix. See :meth:`set_font_matrix`. :returns: A new :class:`Matrix`. """ matrix = Matrix() cairo.cairo_get_font_matrix(self._pointer, matrix._pointer) self._check_status() return matrix def set_font_options(self, font_options): """Sets a set of custom font rendering options. Rendering options are derived by merging these options with the options derived from underlying surface; if the value in options has a default value (like :obj:`ANTIALIAS_DEFAULT`), then the value from the surface is used. :param font_options: A :class:`FontOptions` object. """ cairo.cairo_set_font_options(self._pointer, font_options._pointer) self._check_status() def get_font_options(self): """Retrieves font rendering options set via :meth:`set_font_options`. Note that the returned options do not include any options derived from the underlying surface; they are literally the options passed to :meth:`set_font_options`. :return: A new :class:`FontOptions` object. """ font_options = FontOptions() cairo.cairo_get_font_options(self._pointer, font_options._pointer) return font_options def set_scaled_font(self, scaled_font): """Replaces the current font face, font matrix, and font options with those of :obj:`scaled_font`. Except for some translation, the current CTM of the context should be the same as that of the :obj:`scaled_font`, which can be accessed using :meth:`ScaledFont.get_ctm`. :param scaled_font: A :class:`ScaledFont` object. """ cairo.cairo_set_scaled_font(self._pointer, scaled_font._pointer) self._check_status() def get_scaled_font(self): """Return the current scaled font. :return: A new :class:`ScaledFont` object, wrapping an existing cairo object. """ return ScaledFont._from_pointer( cairo.cairo_get_scaled_font(self._pointer), incref=True) def font_extents(self): """Return the extents of the currently selected font. Values are given in the current user-space coordinate system. Because font metrics are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call :meth:`context.scale(2) `, text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged. :returns: A ``(ascent, descent, height, max_x_advance, max_y_advance)`` tuple of floats. :obj:`ascent` The distance that the font extends above the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements above it. :obj:`descent` The distance that the font extends below the baseline. This value is positive for typical fonts that include portions below the baseline. Note that this is not always exactly equal to the maximum of the extents of all the glyphs in the font, but rather is picked to express the font designer's intent as to how the font should align with elements below it. :obj:`height` The recommended vertical distance between baselines when setting consecutive lines of text with the font. This is greater than ``ascent + descent`` by a quantity known as the line spacing or external leading. When space is at a premium, most fonts can be set with only a distance of ``ascent + descent`` between lines. :obj:`max_x_advance` The maximum distance in the X direction that the origin is advanced for any glyph in the font. :obj:`max_y_advance` The maximum distance in the Y direction that the origin is advanced for any glyph in the font. This will be zero for normal fonts used for horizontal writing. (The scripts of East Asia are sometimes written vertically.) """ extents = ffi.new('cairo_font_extents_t *') cairo.cairo_font_extents(self._pointer, extents) self._check_status() # returning extents as is would be a nice API, # but return a tuple for compat with pycairo. return ( extents.ascent, extents.descent, extents.height, extents.max_x_advance, extents.max_y_advance) # # Text # def text_extents(self, text): """Returns the extents for a string of text. The extents describe a user-space rectangle that encloses the "inked" portion of the text, (as it would be drawn by :meth:`show_text`). Additionally, the :obj:`x_advance` and :obj:`y_advance` values indicate the amount by which the current point would be advanced by :meth:`show_text`. Note that whitespace characters do not directly contribute to the size of the rectangle (:obj:`width` and :obj:`height`). They do contribute indirectly by changing the position of non-whitespace characters. In particular, trailing whitespace characters are likely to not affect the size of the rectangle, though they will affect the x_advance and y_advance values. Because text extents are in user-space coordinates, they are mostly, but not entirely, independent of the current transformation matrix. If you call :meth:`context.scale(2) `, text will be drawn twice as big, but the reported text extents will not be doubled. They will change slightly due to hinting (so you can't assume that metrics are independent of the transformation matrix), but otherwise will remain unchanged. :param text: The text to measure, as an Unicode or UTF-8 string. :returns: A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)`` tuple of floats. :obj:`x_bearing` The horizontal distance from the origin to the leftmost part of the glyphs as drawn. Positive if the glyphs lie entirely to the right of the origin. :obj:`y_bearing` The vertical distance from the origin to the topmost part of the glyphs as drawn. Positive only if the glyphs lie completely below the origin; will usually be negative. :obj:`width` Width of the glyphs as drawn. :obj:`height` Height of the glyphs as drawn. :obj:`x_advance` Distance to advance in the X direction after drawing these glyphs. :obj:`y_advance` Distance to advance in the Y direction after drawing these glyphs. Will typically be zero except for vertical text layout as found in East-Asian languages. """ extents = ffi.new('cairo_text_extents_t *') cairo.cairo_text_extents(self._pointer, _encode_string(text), extents) self._check_status() # returning extents as is would be a nice API, # but return a tuple for compat with pycairo. return ( extents.x_bearing, extents.y_bearing, extents.width, extents.height, extents.x_advance, extents.y_advance) def glyph_extents(self, glyphs): """Returns the extents for a list of glyphs. The extents describe a user-space rectangle that encloses the "inked" portion of the glyphs, (as it would be drawn by :meth:`show_glyphs`). Additionally, the :obj:`x_advance` and :obj:`y_advance` values indicate the amount by which the current point would be advanced by :meth:`show_glyphs`. :param glyphs: A list of glyphs. See :meth:`show_text_glyphs` for the data structure. :returns: A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)`` tuple of floats. See :meth:`text_extents` for details. """ glyphs = ffi.new('cairo_glyph_t[]', glyphs) extents = ffi.new('cairo_text_extents_t *') cairo.cairo_glyph_extents( self._pointer, glyphs, len(glyphs), extents) self._check_status() return ( extents.x_bearing, extents.y_bearing, extents.width, extents.height, extents.x_advance, extents.y_advance) def show_text(self, text): """A drawing operator that generates the shape from a string text, rendered according to the current font :meth:`face `, font :meth:`size ` (font :meth:`matrix `), and font :meth:`options `. This method first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph. After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for easy display of a single logical string with multiple calls to :meth:`show_text`. :param text: The text to show, as an Unicode or UTF-8 string. .. note:: This method is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See :ref:`fonts` for details and :meth:`show_glyphs` for the "real" text display API in cairo. """ cairo.cairo_show_text(self._pointer, _encode_string(text)) self._check_status() def show_glyphs(self, glyphs): """A drawing operator that generates the shape from a list of glyphs, rendered according to the current font :meth:`face `, font :meth:`size ` (font :meth:`matrix `), and font :meth:`options `. :param glyphs: The glyphs to show. See :meth:`show_text_glyphs` for the data structure. """ glyphs = ffi.new('cairo_glyph_t[]', glyphs) cairo.cairo_show_glyphs(self._pointer, glyphs, len(glyphs)) self._check_status() def show_text_glyphs(self, text, glyphs, clusters, cluster_flags=0): """This operation has rendering effects similar to :meth:`show_glyphs` but, if the target surface supports it (see :meth:`Surface.has_show_text_glyphs`), uses the provided text and cluster mapping to embed the text for the glyphs shown in the output. If the target does not support the extended attributes, this method acts like the basic :meth:`show_glyphs` as if it had been passed :obj:`glyphs`. The mapping between :obj:`text` and :obj:`glyphs` is provided by an list of clusters. Each cluster covers a number of UTF-8 text bytes and glyphs, and neighboring clusters cover neighboring areas of :obj:`text` and :obj:`glyphs`. The clusters should collectively cover :obj:`text` and :obj:`glyphs` in entirety. :param text: The text to show, as an Unicode or UTF-8 string. Because of how :obj:`clusters` work, using UTF-8 bytes might be more convenient. :param glyphs: A list of glyphs. Each glyph is a ``(glyph_id, x, y)`` tuple. :obj:`glyph_id` is an opaque integer. Its exact interpretation depends on the font technology being used. :obj:`x` and :obj:`y` are the float offsets in the X and Y direction between the origin used for drawing or measuring the string and the origin of this glyph. Note that the offsets are not cumulative. When drawing or measuring text, each glyph is individually positioned with respect to the overall origin. :param clusters: A list of clusters. A text cluster is a minimal mapping of some glyphs corresponding to some UTF-8 text, represented as a ``(num_bytes, num_glyphs)`` tuple of integers, the number of UTF-8 bytes and glyphs covered by the cluster. For a cluster to be valid, both :obj:`num_bytes` and :obj:`num_glyphs` should be non-negative, and at least one should be non-zero. Note that clusters with zero glyphs are not as well supported as normal clusters. For example, PDF rendering applications typically ignore those clusters when PDF text is being selected. :type cluster_flags: int :param cluster_flags: Flags (as a bit field) for the cluster mapping. The first cluster always covers bytes from the beginning of :obj:`text`. If :obj:`cluster_flags` does not have the :obj:`TEXT_CLUSTER_FLAG_BACKWARD` flag set, the first cluster also covers the beginning of :obj:`glyphs`, otherwise it covers the end of the :obj:`glyphs` list and following clusters move backward. """ glyphs = ffi.new('cairo_glyph_t[]', glyphs) clusters = ffi.new('cairo_text_cluster_t[]', clusters) cairo.cairo_show_text_glyphs( self._pointer, _encode_string(text), -1, glyphs, len(glyphs), clusters, len(clusters), cluster_flags) self._check_status() # # Pages # def show_page(self): """Emits and clears the current page for backends that support multiple pages. Use :meth:`copy_page` if you don't want to clear the page. This is a convenience method that simply calls :meth:`Surface.show_page` on the context’s target. """ cairo.cairo_show_page(self._pointer) self._check_status() def copy_page(self): """Emits the current page for backends that support multiple pages, but doesn't clear it, so the contents of the current page will be retained for the next page too. Use :meth:`show_page` if you want to clear the page. This is a convenience method that simply calls :meth:`Surface.copy_page` on the context’s target. """ cairo.cairo_copy_page(self._pointer) self._check_status() # # Tags # def tag_begin(self, tag_name, attributes=None): """Marks the beginning of the ``tag_name`` structure. Call :meth:`tag_end` with the same ``tag_name`` to mark the end of the structure. The attributes string is of the form "key1=value2 key2=value2 ...". Values may be boolean (true/false or 1/0), integer, float, string, or an array. String values are enclosed in single quotes ('). Single quotes and backslashes inside the string should be escaped with a backslash. Boolean values may be set to true by only specifying the key. eg the attribute string "key" is the equivalent to "key=true". Arrays are enclosed in '[]'. eg "rect=[1.2 4.3 2.0 3.0]". If no attributes are required, ``attributes`` can be omitted, an empty string or None. See cairo's Tags and Links Description for the list of tags and attributes. Invalid nesting of tags or invalid attributes will cause the context to shutdown with a status of ``CAIRO_STATUS_TAG_ERROR``. See :meth:`tag_end`. :param tag_name: tag name :param attributes: tag attributes *New in cairo 1.16.* *New in cairocffi 0.9.* """ if attributes is None: attributes = '' cairo.cairo_tag_begin( self._pointer, _encode_string(tag_name), _encode_string(attributes)) self._check_status() def tag_end(self, tag_name): """Marks the end of the ``tag_name`` structure. Invalid nesting of tags will cause @cr to shutdown with a status of ``CAIRO_STATUS_TAG_ERROR``. See :meth:`tag_begin`. :param tag_name: tag name *New in cairo 1.16.* *New in cairocffi 0.9.* """ cairo.cairo_tag_end(self._pointer, _encode_string(tag_name)) self._check_status() cairocffi-1.2.0/cairocffi/ffi_build.py000066400000000000000000000071631374663167600177130ustar00rootroot00000000000000""" cairocffi.ffi_build ~~~~~~~~~~~~~~~~~~~ Build the cffi bindings :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import sys from pathlib import Path from cffi import FFI # Path hack to import constants when this file is exec'd by setuptools sys.path.append(str(Path(__file__).parent)) import constants # noqa isort:skip # Create an empty _generated folder if needed (Path(__file__).parent / '_generated').mkdir(exist_ok=True) # Primary cffi definitions ffi = FFI() ffi.set_source('cairocffi._generated.ffi', None) ffi.cdef(constants._CAIRO_HEADERS) # include xcffib cffi definitions for cairo xcb support try: from xcffib.ffi_build import ffi as xcb_ffi ffi.include(xcb_ffi) ffi.cdef(constants._CAIRO_XCB_HEADERS) except ImportError: pass # gdk pixbuf cffi definitions ffi_pixbuf = FFI() ffi_pixbuf.set_source('cairocffi._generated.ffi_pixbuf', None) ffi_pixbuf.include(ffi) ffi_pixbuf.cdef(''' typedef unsigned long gsize; typedef unsigned int guint32; typedef unsigned int guint; typedef unsigned char guchar; typedef char gchar; typedef int gint; typedef gint gboolean; typedef guint32 GQuark; typedef void* gpointer; typedef ... GdkPixbufLoader; typedef ... GdkPixbufFormat; typedef ... GdkPixbuf; typedef struct { GQuark domain; gint code; gchar *message; } GError; typedef enum { GDK_COLORSPACE_RGB } GdkColorspace; GdkPixbufLoader * gdk_pixbuf_loader_new (void); GdkPixbufFormat * gdk_pixbuf_loader_get_format (GdkPixbufLoader *loader); GdkPixbuf * gdk_pixbuf_loader_get_pixbuf (GdkPixbufLoader *loader); gboolean gdk_pixbuf_loader_write ( GdkPixbufLoader *loader, const guchar *buf, gsize count, GError **error); void gdk_pixbuf_loader_set_size ( GdkPixbufLoader *loader, int width, int height); gboolean gdk_pixbuf_loader_close ( GdkPixbufLoader *loader, GError **error); gchar * gdk_pixbuf_format_get_name (GdkPixbufFormat *format); GdkColorspace gdk_pixbuf_get_colorspace (const GdkPixbuf *pixbuf); int gdk_pixbuf_get_n_channels (const GdkPixbuf *pixbuf); gboolean gdk_pixbuf_get_has_alpha (const GdkPixbuf *pixbuf); int gdk_pixbuf_get_bits_per_sample (const GdkPixbuf *pixbuf); int gdk_pixbuf_get_width (const GdkPixbuf *pixbuf); int gdk_pixbuf_get_height (const GdkPixbuf *pixbuf); int gdk_pixbuf_get_rowstride (const GdkPixbuf *pixbuf); guchar * gdk_pixbuf_get_pixels (const GdkPixbuf *pixbuf); gsize gdk_pixbuf_get_byte_length (const GdkPixbuf *pixbuf); gboolean gdk_pixbuf_save_to_buffer ( GdkPixbuf *pixbuf, gchar **buffer, gsize *buffer_size, const char *type, GError **error, ...); void gdk_cairo_set_source_pixbuf ( cairo_t *cr, const GdkPixbuf *pixbuf, double pixbuf_x, double pixbuf_y); void g_object_ref (gpointer object); void g_object_unref (gpointer object); void g_error_free (GError *error); void g_type_init (void); ''') if __name__ == '__main__': ffi.compile() ffi_pixbuf.compile() cairocffi-1.2.0/cairocffi/fonts.py000066400000000000000000000460451374663167600171230ustar00rootroot00000000000000""" cairocffi.fonts ~~~~~~~~~~~~~~~ Bindings for font-related objects. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ from . import _check_status, _keepref, cairo, constants, ffi from .matrix import Matrix def _encode_string(string): """Return a byte string, encoding Unicode with UTF-8.""" if not isinstance(string, bytes): string = string.encode('utf8') return ffi.new('char[]', string) class FontFace(object): """The base class for all font face types. Should not be instantiated directly, but see :doc:`cffi_api`. An instance may be returned for cairo font face types that are not (yet) defined in cairocffi. """ def __init__(self, pointer): self._pointer = ffi.gc( pointer, _keepref(cairo, cairo.cairo_font_face_destroy)) self._check_status() def _check_status(self): _check_status(cairo.cairo_font_face_status(self._pointer)) @staticmethod def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_font_face_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count ` now. :return: A new instance of :class:`FontFace` or one of its sub-classes, depending on the face’s type. """ if pointer == ffi.NULL: raise ValueError('Null pointer') if incref: cairo.cairo_font_face_reference(pointer) self = object.__new__(FONT_TYPE_TO_CLASS.get( cairo.cairo_font_face_get_type(pointer), FontFace)) FontFace.__init__(self, pointer) # Skip the subclass’s __init__ return self class ToyFontFace(FontFace): """Creates a font face from a triplet of family, slant, and weight. These font faces are used in implementation of cairo’s "toy" font API. If family is the zero-length string ``""``, the platform-specific default family is assumed. The default family then can be queried using :meth:`get_family`. The :meth:`Context.select_font_face` method uses this to create font faces. See that method for limitations and other details of toy font faces. :param family: a font family name, as an Unicode or UTF-8 string. :param slant: The :ref:`FONT_SLANT` string for the font face. :param weight: The :ref:`FONT_WEIGHT` string for the font face. """ def __init__(self, family='', slant=constants.FONT_SLANT_NORMAL, weight=constants.FONT_WEIGHT_NORMAL): FontFace.__init__(self, cairo.cairo_toy_font_face_create( _encode_string(family), slant, weight)) def get_family(self): """Return this font face’s family name.""" return ffi.string(cairo.cairo_toy_font_face_get_family( self._pointer)).decode('utf8', 'replace') def get_slant(self): """Return this font face’s :ref:`FONT_SLANT` string.""" return cairo.cairo_toy_font_face_get_slant(self._pointer) def get_weight(self): """Return this font face’s :ref:`FONT_WEIGHT` string.""" return cairo.cairo_toy_font_face_get_weight(self._pointer) FONT_TYPE_TO_CLASS = { constants.FONT_TYPE_TOY: ToyFontFace, } class ScaledFont(object): """Creates a :class:`ScaledFont` object from a font face and matrices that describe the size of the font and the environment in which it will be used. :param font_face: A :class:`FontFace` object. :type font_matrix: Matrix :param font_matrix: Font space to user space transformation matrix for the font. In the simplest case of a N point font, this matrix is just a scale by N, but it can also be used to shear the font or stretch it unequally along the two axes. If omitted, a scale by 10 matrix is assumed (ie. a 10 point font size). See :class:`Context.set_font_matrix`. :type ctm: Matrix :param ctm: User to device transformation matrix with which the font will be used. If omitted, an identity matrix is assumed. :param options: The :class:`FontOptions` object to use when getting metrics for the font and rendering with it. If omitted, the default options are assumed. """ def __init__(self, font_face, font_matrix=None, ctm=None, options=None): if font_matrix is None: font_matrix = Matrix() font_matrix.scale(10) # Default font size if ctm is None: ctm = Matrix() if options is None: options = FontOptions() self._init_pointer(cairo.cairo_scaled_font_create( font_face._pointer, font_matrix._pointer, ctm._pointer, options._pointer)) def _init_pointer(self, pointer): self._pointer = ffi.gc( pointer, _keepref(cairo, cairo.cairo_scaled_font_destroy)) self._check_status() def _check_status(self): _check_status(cairo.cairo_scaled_font_status(self._pointer)) @staticmethod def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_scaled_font_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count ` now. :return: A new :class:`ScaledFont` instance. """ if pointer == ffi.NULL: raise ValueError('Null pointer') if incref: cairo.cairo_scaled_font_reference(pointer) self = object.__new__(ScaledFont) ScaledFont._init_pointer(self, pointer) return self def get_font_face(self): """Return the font face that this scaled font uses. :returns: A new instance of :class:`FontFace` (or one of its sub-classes). Might wrap be the same font face passed to :class:`ScaledFont`, but this does not hold true for all possible cases. """ return FontFace._from_pointer( cairo.cairo_scaled_font_get_font_face(self._pointer), incref=True) def get_font_options(self): """Copies the scaled font’s options. :returns: A new :class:`FontOptions` object. """ font_options = FontOptions() cairo.cairo_scaled_font_get_font_options( self._pointer, font_options._pointer) return font_options def get_font_matrix(self): """Copies the scaled font’s font matrix. :returns: A new :class:`Matrix` object. """ matrix = Matrix() cairo.cairo_scaled_font_get_font_matrix(self._pointer, matrix._pointer) self._check_status() return matrix def get_ctm(self): """Copies the scaled font’s font current transform matrix. Note that the translation offsets ``(x0, y0)`` of the CTM are ignored by :class:`ScaledFont`. So, the matrix this method returns always has 0 as ``x0`` and ``y0``. :returns: A new :class:`Matrix` object. """ matrix = Matrix() cairo.cairo_scaled_font_get_ctm(self._pointer, matrix._pointer) self._check_status() return matrix def get_scale_matrix(self): """Copies the scaled font’s scaled matrix. The scale matrix is product of the font matrix and the ctm associated with the scaled font, and hence is the matrix mapping from font space to device space. :returns: A new :class:`Matrix` object. """ matrix = Matrix() cairo.cairo_scaled_font_get_scale_matrix( self._pointer, matrix._pointer) self._check_status() return matrix def extents(self): """Return the scaled font’s extents. See :meth:`Context.font_extents`. :returns: A ``(ascent, descent, height, max_x_advance, max_y_advance)`` tuple of floats. """ extents = ffi.new('cairo_font_extents_t *') cairo.cairo_scaled_font_extents(self._pointer, extents) self._check_status() return ( extents.ascent, extents.descent, extents.height, extents.max_x_advance, extents.max_y_advance) def text_extents(self, text): """Returns the extents for a string of text. The extents describe a user-space rectangle that encloses the "inked" portion of the text, (as it would be drawn by :meth:`show_text`). Additionally, the :obj:`x_advance` and :obj:`y_advance` values indicate the amount by which the current point would be advanced by :meth:`show_text`. :param text: The text to measure, as an Unicode or UTF-8 string. :returns: A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)`` tuple of floats. See :meth:`Context.text_extents` for details. """ extents = ffi.new('cairo_text_extents_t *') cairo.cairo_scaled_font_text_extents( self._pointer, _encode_string(text), extents) self._check_status() return ( extents.x_bearing, extents.y_bearing, extents.width, extents.height, extents.x_advance, extents.y_advance) def glyph_extents(self, glyphs): """Returns the extents for a list of glyphs. The extents describe a user-space rectangle that encloses the "inked" portion of the glyphs, (as it would be drawn by :meth:`show_glyphs`). Additionally, the :obj:`x_advance` and :obj:`y_advance` values indicate the amount by which the current point would be advanced by :meth:`show_glyphs`. :param glyphs: A list of glyphs, as returned by :meth:`text_to_glyphs`. Each glyph is a ``(glyph_id, x, y)`` tuple of an integer and two floats. :returns: A ``(x_bearing, y_bearing, width, height, x_advance, y_advance)`` tuple of floats. See :meth:`Context.text_extents` for details. """ glyphs = ffi.new('cairo_glyph_t[]', glyphs) extents = ffi.new('cairo_text_extents_t *') cairo.cairo_scaled_font_glyph_extents( self._pointer, glyphs, len(glyphs), extents) self._check_status() return ( extents.x_bearing, extents.y_bearing, extents.width, extents.height, extents.x_advance, extents.y_advance) def text_to_glyphs(self, x, y, text, with_clusters): """Converts a string of text to a list of glyphs, optionally with cluster mapping, that can be used to render later using this scaled font. The output values can be readily passed to :meth:`Context.show_text_glyphs`, :meth:`Context.show_glyphs` or related methods, assuming that the exact same :class:`ScaledFont` is used for the operation. :type x: float :type y: float :type with_clusters: bool :param x: X position to place first glyph. :param y: Y position to place first glyph. :param text: The text to convert, as an Unicode or UTF-8 string. :param with_clusters: Whether to compute the cluster mapping. :returns: A ``(glyphs, clusters, clusters_flags)`` tuple if :obj:`with_clusters` is true, otherwise just :obj:`glyphs`. See :meth:`Context.show_text_glyphs` for the data structure. .. note:: This method is part of what the cairo designers call the "toy" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See :ref:`fonts` for details and :meth:`Context.show_glyphs` for the "real" text display API in cairo. """ glyphs = ffi.new('cairo_glyph_t **', ffi.NULL) num_glyphs = ffi.new('int *') if with_clusters: clusters = ffi.new('cairo_text_cluster_t **', ffi.NULL) num_clusters = ffi.new('int *') cluster_flags = ffi.new('cairo_text_cluster_flags_t *') else: clusters = ffi.NULL num_clusters = ffi.NULL cluster_flags = ffi.NULL # TODO: Pass len_utf8 explicitly to support NULL bytes? status = cairo.cairo_scaled_font_text_to_glyphs( self._pointer, x, y, _encode_string(text), -1, glyphs, num_glyphs, clusters, num_clusters, cluster_flags) glyphs = ffi.gc(glyphs[0], _keepref(cairo, cairo.cairo_glyph_free)) if with_clusters: clusters = ffi.gc( clusters[0], _keepref(cairo, cairo.cairo_text_cluster_free)) _check_status(status) glyphs = [ (glyph.index, glyph.x, glyph.y) for i in range(num_glyphs[0]) for glyph in [glyphs[i]]] if with_clusters: clusters = [ (cluster.num_bytes, cluster.num_glyphs) for i in range(num_clusters[0]) for cluster in [clusters[i]]] return glyphs, clusters, cluster_flags[0] else: return glyphs class FontOptions(object): """An opaque object holding all options that are used when rendering fonts. Individual features of a :class:`FontOptions` can be set or accessed using method named :meth:`set_FEATURE_NAME` and :meth:`get_FEATURE_NAME`, like :meth:`set_antialias` and :meth:`get_antialias`. New features may be added to :class:`FontOptions` in the future. For this reason, ``==``, :meth:`copy`, :meth:`merge`, and :func:`hash` should be used to check for equality copy,, merge, or compute a hash value of :class:`FontOptions` objects. :param values: Call the corresponding :meth:`set_FEATURE_NAME` methods after creating a new :class:`FontOptions`:: options = FontOptions() options.set_antialias(cairocffi.ANTIALIAS_BEST) assert FontOptions(antialias=cairocffi.ANTIALIAS_BEST) == options """ def __init__(self, **values): self._init_pointer(cairo.cairo_font_options_create()) for name, value in values.items(): getattr(self, 'set_' + name)(value) def _init_pointer(self, pointer): self._pointer = ffi.gc( pointer, _keepref(cairo, cairo.cairo_font_options_destroy)) self._check_status() def _check_status(self): _check_status(cairo.cairo_font_options_status(self._pointer)) def copy(self): """Return a new :class:`FontOptions` with the same values.""" cls = type(self) other = object.__new__(cls) cls._init_pointer(other, cairo.cairo_font_options_copy(self._pointer)) return other def merge(self, other): """Merges non-default options from :obj:`other`, replacing existing values. This operation can be thought of as somewhat similar to compositing other onto options with the operation of :obj:`OVER `. """ cairo.cairo_font_options_merge(self._pointer, other._pointer) _check_status(cairo.cairo_font_options_status(self._pointer)) def __hash__(self): return cairo.cairo_font_options_hash(self._pointer) def __eq__(self, other): return cairo.cairo_font_options_equal(self._pointer, other._pointer) def __ne__(self, other): return not self == other equal = __eq__ hash = __hash__ def set_antialias(self, antialias): """Changes the :ref:`ANTIALIAS` for the font options object. This specifies the type of antialiasing to do when rendering text. """ cairo.cairo_font_options_set_antialias(self._pointer, antialias) self._check_status() def get_antialias(self): """Return the :ref:`ANTIALIAS` string for the font options object.""" return cairo.cairo_font_options_get_antialias(self._pointer) def set_subpixel_order(self, subpixel_order): """Changes the :ref:`SUBPIXEL_ORDER` for the font options object. The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of :obj:`SUBPIXEL `. """ cairo.cairo_font_options_set_subpixel_order( self._pointer, subpixel_order) self._check_status() def get_subpixel_order(self): """Return the :ref:`SUBPIXEL_ORDER` string for the font options object. """ return cairo.cairo_font_options_get_subpixel_order(self._pointer) def set_hint_style(self, hint_style): """Changes the :ref:`HINT_STYLE` for the font options object. This controls whether to fit font outlines to the pixel grid, and if so, whether to optimize for fidelity or contrast. """ cairo.cairo_font_options_set_hint_style(self._pointer, hint_style) self._check_status() def get_hint_style(self): """Return the :ref:`HINT_STYLE` string for the font options object.""" return cairo.cairo_font_options_get_hint_style(self._pointer) def set_hint_metrics(self, hint_metrics): """Changes the :ref:`HINT_METRICS` for the font options object. This controls whether metrics are quantized to integer values in device units. """ cairo.cairo_font_options_set_hint_metrics(self._pointer, hint_metrics) self._check_status() def get_hint_metrics(self): """Return the :ref:`HINT_METRICS` string for the font options object. """ return cairo.cairo_font_options_get_hint_metrics(self._pointer) def set_variations(self, variations): """Sets the OpenType font variations for the font options object. Font variations are specified as a string with a format that is similar to the CSS font-variation-settings. The string contains a comma-separated list of axis assignments, which each assignment consists of a 4-character axis name and a value, separated by whitespace and optional equals sign. :param variations: the new font variations, or ``None``. *New in cairo 1.16.* *New in cairocffi 0.9.* """ if variations is None: variations = ffi.NULL else: variations = _encode_string(variations) cairo.cairo_font_options_set_variations(self._pointer, variations) self._check_status() def get_variations(self): """Gets the OpenType font variations for the font options object. See :meth:`set_variations` for details about the string format. :return: the font variations for the font options object. The returned string belongs to the ``options`` and must not be modified. It is valid until either the font options object is destroyed or the font variations in this object is modified with :meth:`set_variations`. *New in cairo 1.16.* *New in cairocffi 0.9.* """ variations = cairo.cairo_font_options_get_variations(self._pointer) if variations != ffi.NULL: return ffi.string(variations).decode('utf8', 'replace') cairocffi-1.2.0/cairocffi/matrix.py000066400000000000000000000176001374663167600172710ustar00rootroot00000000000000""" cairocffi.matrix ~~~~~~~~~~~~~~~~ Transformation matrices. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ from . import _check_status, cairo, ffi class Matrix(object): """A 2D transformation matrix. Matrices are used throughout cairo to convert between different coordinate spaces. A :class:`Matrix` holds an affine transformation, such as a scale, rotation, shear, or a combination of these. The transformation of a point (x,y) is given by:: x_new = xx * x + xy * y + x0 y_new = yx * x + yy * y + y0 The current transformation matrix of a :class:`Context`, represented as a :class:`Matrix`, defines the transformation from user-space coordinates to device-space coordinates. See :meth:`Context.get_matrix` and :meth:`Context.set_matrix`. The default values produce an identity matrix. Matrices can be compared with ``m1 == m2`` and ``m2 != m2`` as well as multiplied with ``m3 = m1 * m2``. """ def __init__(self, xx=1, yx=0, xy=0, yy=1, x0=0, y0=0): self._pointer = ffi.new('cairo_matrix_t *') cairo.cairo_matrix_init(self._pointer, xx, yx, xy, yy, x0, y0) @classmethod def init_rotate(cls, radians): """Return a new :class:`Matrix` for a transformation that rotates by :obj:`radians`. :type radians: float :param radians: Angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction. """ result = cls() cairo.cairo_matrix_init_rotate(result._pointer, radians) return result def as_tuple(self): """Return all of the matrix’s components. :returns: A ``(xx, yx, xy, yy, x0, y0)`` tuple of floats. """ ptr = self._pointer return (ptr.xx, ptr.yx, ptr.xy, ptr.yy, ptr.x0, ptr.y0) def copy(self): """Return a new copy of this matrix.""" return type(self)(*self.as_tuple()) def __getitem__(self, index): return getattr( self._pointer, ('xx', 'yx', 'xy', 'yy', 'x0', 'y0')[index]) def __iter__(self): return iter(self.as_tuple()) def __eq__(self, other): return self.as_tuple() == other.as_tuple() def __ne__(self, other): return self.as_tuple() != other.as_tuple() def __repr__(self): class_ = type(self) return '%s(%g, %g, %g, %g, %g, %g)' % ( (class_.__name__,) + self.as_tuple()) def multiply(self, other): """Multiply with another matrix and return the result as a new :class:`Matrix` object. Same as ``self * other``. """ res = Matrix() cairo.cairo_matrix_multiply( res._pointer, self._pointer, other._pointer) return res __mul__ = multiply def translate(self, tx, ty): """Applies a translation by :obj:`tx`, :obj:`ty` to the transformation in this matrix. The effect of the new transformation is to first translate the coordinates by :obj:`tx` and :obj:`ty`, then apply the original transformation to the coordinates. .. note:: This changes the matrix in-place. :param tx: Amount to translate in the X direction. :param ty: Amount to translate in the Y direction. :type tx: float :type ty: float """ cairo.cairo_matrix_translate(self._pointer, tx, ty) def scale(self, sx, sy=None): """Applies scaling by :obj:`sx`, :obj:`sy` to the transformation in this matrix. The effect of the new transformation is to first scale the coordinates by :obj:`sx` and :obj:`sy`, then apply the original transformation to the coordinates. If :obj:`sy` is omitted, it is the same as :obj:`sx` so that scaling preserves aspect ratios. .. note:: This changes the matrix in-place. :param sx: Scale factor in the X direction. :param sy: Scale factor in the Y direction. :type sx: float :type sy: float """ if sy is None: sy = sx cairo.cairo_matrix_scale(self._pointer, sx, sy) def rotate(self, radians): """Applies a rotation by :obj:`radians` to the transformation in this matrix. The effect of the new transformation is to first rotate the coordinates by :obj:`radians`, then apply the original transformation to the coordinates. .. note:: This changes the matrix in-place. :type radians: float :param radians: Angle of rotation, in radians. The direction of rotation is defined such that positive angles rotate in the direction from the positive X axis toward the positive Y axis. With the default axis orientation of cairo, positive angles rotate in a clockwise direction. """ cairo.cairo_matrix_rotate(self._pointer, radians) def invert(self): """Changes matrix to be the inverse of its original value. Not all transformation matrices have inverses; if the matrix collapses points together (it is degenerate), then it has no inverse and this function will fail. .. note:: This changes the matrix in-place. :raises: :exc:`CairoError` on degenerate matrices. """ _check_status(cairo.cairo_matrix_invert(self._pointer)) def inverted(self): """Return the inverse of this matrix. See :meth:`invert`. :raises: :exc:`CairoError` on degenerate matrices. :returns: A new :class:`Matrix` object. """ matrix = self.copy() matrix.invert() return matrix def transform_point(self, x, y): """Transforms the point ``(x, y)`` by this matrix. :param x: X position. :param y: Y position. :type x: float :type y: float :returns: A ``(new_x, new_y)`` tuple of floats. """ xy = ffi.new('double[2]', [x, y]) cairo.cairo_matrix_transform_point(self._pointer, xy + 0, xy + 1) return tuple(xy) def transform_distance(self, dx, dy): """Transforms the distance vector ``(dx, dy)`` by this matrix. This is similar to :meth:`transform_point` except that the translation components of the transformation are ignored. The calculation of the returned vector is as follows:: dx2 = dx1 * xx + dy1 * xy dy2 = dx1 * yx + dy1 * yy Affine transformations are position invariant, so the same vector always transforms to the same vector. If ``(x1, y1)`` transforms to ``(x2, y2)`` then ``(x1 + dx1, y1 + dy1)`` will transform to ``(x1 + dx2, y1 + dy2)`` for all values of ``x1`` and ``x2``. :param dx: X component of a distance vector. :param dy: Y component of a distance vector. :type dx: float :type dy: float :returns: A ``(new_dx, new_dy)`` tuple of floats. """ xy = ffi.new('double[2]', [dx, dy]) cairo.cairo_matrix_transform_distance(self._pointer, xy + 0, xy + 1) return tuple(xy) def _component_property(name): return property( lambda self: getattr(self._pointer, name), lambda self, value: setattr(self._pointer, name, value), doc='Read-write attribute access to a single float component.') xx = _component_property('xx') yx = _component_property('yx') xy = _component_property('xy') yy = _component_property('yy') x0 = _component_property('x0') y0 = _component_property('y0') del _component_property cairocffi-1.2.0/cairocffi/patterns.py000066400000000000000000000312621374663167600176250ustar00rootroot00000000000000""" cairocffi.patterns ~~~~~~~~~~~~~~~~~~ Bindings for the various types of pattern objects. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ from . import _check_status, _keepref, cairo, constants, ffi from .matrix import Matrix from .surfaces import Surface class Pattern(object): """The base class for all pattern types. Should not be instantiated directly, but see :doc:`cffi_api`. An instance may be returned for cairo pattern types that are not (yet) defined in cairocffi. A :class:`Pattern` represents a source when drawing onto a surface. There are different sub-classes of :class:`Pattern`, for different types of sources; for example, :class:`SolidPattern` is a pattern for a solid color. Other than instantiating the various :class:`Pattern` sub-classes, some of the pattern types can be implicitly created using various :class:`Context`; for example :meth:`Context.set_source_rgb`. """ def __init__(self, pointer): self._pointer = ffi.gc( pointer, _keepref(cairo, cairo.cairo_pattern_destroy)) self._check_status() def _check_status(self): _check_status(cairo.cairo_pattern_status(self._pointer)) @staticmethod def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_pattern_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count ` now. :return: A new instance of :class:`Pattern` or one of its sub-classes, depending on the pattern’s type. """ if pointer == ffi.NULL: raise ValueError('Null pointer') if incref: cairo.cairo_pattern_reference(pointer) self = object.__new__(PATTERN_TYPE_TO_CLASS.get( cairo.cairo_pattern_get_type(pointer), Pattern)) Pattern.__init__(self, pointer) # Skip the subclass’s __init__ return self def set_extend(self, extend): """ Sets the mode to be used for drawing outside the area of this pattern. See :ref:`EXTEND` for details on the semantics of each extend strategy. The default extend mode is :obj:`NONE ` for :class:`SurfacePattern` and :obj:`PAD ` for :class:`Gradient` patterns. """ cairo.cairo_pattern_set_extend(self._pointer, extend) self._check_status() def get_extend(self): """Gets the current extend mode for this pattern. :returns: A :ref:`EXTEND` string. """ return cairo.cairo_pattern_get_extend(self._pointer) # pycairo only has filters on SurfacePattern, # but cairo seems to accept it on any pattern. def set_filter(self, filter): """Sets the filter to be used for resizing when using this pattern. See :ref:`FILTER` for details on each filter. Note that you might want to control filtering even when you do not have an explicit :class:`Pattern`, (for example when using :meth:`Context.set_source_surface`). In these cases, it is convenient to use :meth:`Context.get_source` to get access to the pattern that cairo creates implicitly. For example:: context.get_source().set_filter(cairocffi.FILTER_NEAREST) """ cairo.cairo_pattern_set_filter(self._pointer, filter) self._check_status() def get_filter(self): """Return the current filter string for this pattern. See :ref:`FILTER` for details on each filter. """ return cairo.cairo_pattern_get_filter(self._pointer) def set_matrix(self, matrix): """Sets the pattern’s transformation matrix to :obj:`matrix`. This matrix is a transformation from user space to pattern space. When a pattern is first created it always has the identity matrix for its transformation matrix, which means that pattern space is initially identical to user space. **Important:** Please note that the direction of this transformation matrix is from user space to pattern space. This means that if you imagine the flow from a pattern to user space (and on to device space), then coordinates in that flow will be transformed by the inverse of the pattern matrix. For example, if you want to make a pattern appear twice as large as it does by default the correct code to use is:: pattern.set_matrix(Matrix(xx=0.5, yy=0.5)) Meanwhile, using values of 2 rather than 0.5 in the code above would cause the pattern to appear at half of its default size. Also, please note the discussion of the user-space locking semantics of :meth:`Context.set_source`. :param matrix: A :class:`Matrix` to be copied into the pattern. """ cairo.cairo_pattern_set_matrix(self._pointer, matrix._pointer) self._check_status() def get_matrix(self): """Copies the pattern’s transformation matrix. :retuns: A new :class:`Matrix` object. """ matrix = Matrix() cairo.cairo_pattern_get_matrix(self._pointer, matrix._pointer) self._check_status() return matrix class SolidPattern(Pattern): """Creates a new pattern corresponding to a solid color. The color and alpha components are in the range 0 to 1. If the values passed in are outside that range, they will be clamped. :param red: Red component of the color. :param green: Green component of the color. :param blue: Blue component of the color. :param alpha: Alpha component of the color. 1 (the default) is opaque, 0 fully transparent. :type red: float :type green: float :type blue: float :type alpha: float """ def __init__(self, red, green, blue, alpha=1): Pattern.__init__( self, cairo.cairo_pattern_create_rgba(red, green, blue, alpha)) def get_rgba(self): """Returns the solid pattern’s color. :returns: a ``(red, green, blue, alpha)`` tuple of floats. """ rgba = ffi.new('double[4]') _check_status(cairo.cairo_pattern_get_rgba( self._pointer, rgba + 0, rgba + 1, rgba + 2, rgba + 3)) return tuple(rgba) class SurfacePattern(Pattern): """Create a new pattern for the given surface. :param surface: A :class:`Surface` object. """ def __init__(self, surface): Pattern.__init__( self, cairo.cairo_pattern_create_for_surface(surface._pointer)) def get_surface(self): """Return this :class:`SurfacePattern`’s surface. :returns: An instance of :class:`Surface` or one of its sub-classes, a new Python object referencing the existing cairo surface. """ surface_p = ffi.new('cairo_surface_t **') _check_status(cairo.cairo_pattern_get_surface( self._pointer, surface_p)) return Surface._from_pointer(surface_p[0], incref=True) class Gradient(Pattern): """ The common parent of :class:`LinearGradient` and :class:`RadialGradient`. Should not be instantiated directly. """ def add_color_stop_rgba(self, offset, red, green, blue, alpha=1): """Adds a translucent color stop to a gradient pattern. The offset specifies the location along the gradient's control vector. For example, a linear gradient's control vector is from (x0,y0) to (x1,y1) while a radial gradient's control vector is from any point on the start circle to the corresponding point on the end circle. If two (or more) stops are specified with identical offset values, they will be sorted according to the order in which the stops are added (stops added earlier before stops added later). This can be useful for reliably making sharp color transitions instead of the typical blend. The color components and offset are in the range 0 to 1. If the values passed in are outside that range, they will be clamped. :param offset: Location along the gradient's control vector :param red: Red component of the color. :param green: Green component of the color. :param blue: Blue component of the color. :param alpha: Alpha component of the color. 1 (the default) is opaque, 0 fully transparent. :type offset: float :type red: float :type green: float :type blue: float :type alpha: float """ cairo.cairo_pattern_add_color_stop_rgba( self._pointer, offset, red, green, blue, alpha) self._check_status() def add_color_stop_rgb(self, offset, red, green, blue): """Same as :meth:`add_color_stop_rgba` with ``alpha=1``. Kept for compatibility with pycairo. """ cairo.cairo_pattern_add_color_stop_rgb( self._pointer, offset, red, green, blue) self._check_status() def get_color_stops(self): """Return this gradient’s color stops so far. :returns: A list of ``(offset, red, green, blue, alpha)`` tuples of floats. """ count = ffi.new('int *') _check_status(cairo.cairo_pattern_get_color_stop_count( self._pointer, count)) stops = [] stop = ffi.new('double[5]') for i in range(count[0]): _check_status(cairo.cairo_pattern_get_color_stop_rgba( self._pointer, i, stop + 0, stop + 1, stop + 2, stop + 3, stop + 4)) stops.append(tuple(stop)) return stops class LinearGradient(Gradient): """Create a new linear gradient along the line defined by (x0, y0) and (x1, y1). Before using the gradient pattern, a number of color stops should be defined using :meth:`~Gradient.add_color_stop_rgba`. Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with :meth:`~Pattern.set_matrix`. :param x0: X coordinate of the start point. :param y0: Y coordinate of the start point. :param x1: X coordinate of the end point. :param y1: Y coordinate of the end point. :type x0: float :type y0: float :type x1: float :type y1: float """ def __init__(self, x0, y0, x1, y1): Pattern.__init__( self, cairo.cairo_pattern_create_linear(x0, y0, x1, y1)) def get_linear_points(self): """Return this linear gradient’s endpoints. :returns: A ``(x0, y0, x1, y1)`` tuple of floats. """ points = ffi.new('double[4]') _check_status(cairo.cairo_pattern_get_linear_points( self._pointer, points + 0, points + 1, points + 2, points + 3)) return tuple(points) class RadialGradient(Gradient): """Creates a new radial gradient pattern between the two circles defined by (cx0, cy0, radius0) and (cx1, cy1, radius1). Before using the gradient pattern, a number of color stops should be defined using :meth:`~Gradient.add_color_stop_rgba`. Note: The coordinates here are in pattern space. For a new pattern, pattern space is identical to user space, but the relationship between the spaces can be changed with :meth:`~Pattern.set_matrix`. :param cx0: X coordinate of the start circle. :param cy0: Y coordinate of the start circle. :param radius0: Radius of the start circle. :param cx1: X coordinate of the end circle. :param cy1: Y coordinate of the end circle. :param radius1: Y coordinate of the end circle. :type cx0: float :type cy0: float :type radius0: float :type cx1: float :type cy1: float :type radius1: float """ def __init__(self, cx0, cy0, radius0, cx1, cy1, radius1): Pattern.__init__(self, cairo.cairo_pattern_create_radial( cx0, cy0, radius0, cx1, cy1, radius1)) def get_radial_circles(self): """Return this radial gradient’s endpoint circles, each specified as a center coordinate and a radius. :returns: A ``(cx0, cy0, radius0, cx1, cy1, radius1)`` tuple of floats. """ circles = ffi.new('double[6]') _check_status(cairo.cairo_pattern_get_radial_circles( self._pointer, circles + 0, circles + 1, circles + 2, circles + 3, circles + 4, circles + 5)) return tuple(circles) PATTERN_TYPE_TO_CLASS = { constants.PATTERN_TYPE_SOLID: SolidPattern, constants.PATTERN_TYPE_SURFACE: SurfacePattern, constants.PATTERN_TYPE_LINEAR: LinearGradient, constants.PATTERN_TYPE_RADIAL: RadialGradient, } cairocffi-1.2.0/cairocffi/pixbuf.py000066400000000000000000000161341374663167600172630ustar00rootroot00000000000000""" cairocffi.pixbuf ~~~~~~~~~~~~~~~~ Loading various image formats with GDK-PixBuf :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import sys from array import array from functools import partial from io import BytesIO from . import Context, ImageSurface, constants, dlopen from ._generated.ffi_pixbuf import ffi __all__ = ['decode_to_image_surface'] gdk_pixbuf = dlopen( ffi, ('gdk_pixbuf-2.0', 'libgdk_pixbuf-2.0-0'), ('libgdk_pixbuf-2.0.so.0', 'libgdk_pixbuf-2.0.0.dylib', 'libgdk_pixbuf-2.0-0.dll')) gobject = dlopen( ffi, ('gobject-2.0', 'libgobject-2.0-0'), ('libgobject-2.0.so.0', 'libgobject-2.0.dylib', 'libgobject-2.0-0.dll')) glib = dlopen( ffi, ('glib-2.0', 'libglib-2.0-0'), ('libglib-2.0.so.0', 'libglib-2.0.dylib', 'libglib-2.0-0.dll')) try: gdk = dlopen( ffi, ('gdk-3', 'libgdk-3-0'), ('libgdk-3.so.0', 'libgdk-3.0.dylib', 'libgdk-3-0.dll')) except OSError: gdk = None gobject.g_type_init() class ImageLoadingError(ValueError): """PixBuf returned an error when loading an image. The image data is probably corrupted. """ def handle_g_error(error, return_value): """Convert a :c:type:`GError**` to a Python :exception:`ImageLoadingError`, and raise it. """ error = error[0] assert bool(return_value) == (error == ffi.NULL) if error != ffi.NULL: if error.message != ffi.NULL: message = ('Pixbuf error: ' + ffi.string(error.message).decode('utf8', 'replace')) else: # pragma: no cover message = 'Pixbuf error' glib.g_error_free(error) raise ImageLoadingError(message) class Pixbuf(object): """Wrap a :c:type:`GdkPixbuf` pointer and simulate methods.""" def __init__(self, pointer): gobject.g_object_ref(pointer) self._pointer = ffi.gc(pointer, gobject.g_object_unref) def __getattr__(self, name): function = getattr(gdk_pixbuf, 'gdk_pixbuf_' + name) return partial(function, self._pointer) def decode_to_pixbuf(image_data, width=None, height=None): """Decode an image from memory with GDK-PixBuf. The file format is detected automatically. :param image_data: A byte string :param width: Integer width in pixels or None :param height: Integer height in pixels or None :returns: A tuple of a new :class:`PixBuf` object and the name of the detected image format. :raises: :exc:`ImageLoadingError` if the image data is invalid or in an unsupported format. """ loader = ffi.gc( gdk_pixbuf.gdk_pixbuf_loader_new(), gobject.g_object_unref) error = ffi.new('GError **') if width and height: gdk_pixbuf.gdk_pixbuf_loader_set_size(loader, width, height) handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_write( loader, image_data, len(image_data), error)) handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_close(loader, error)) format_ = gdk_pixbuf.gdk_pixbuf_loader_get_format(loader) format_name = ( ffi.string(gdk_pixbuf.gdk_pixbuf_format_get_name(format_)) .decode('ascii') if format_ != ffi.NULL else None) pixbuf = gdk_pixbuf.gdk_pixbuf_loader_get_pixbuf(loader) if pixbuf == ffi.NULL: # pragma: no cover raise ImageLoadingError('Not enough image data (got a NULL pixbuf.)') return Pixbuf(pixbuf), format_name def decode_to_image_surface(image_data, width=None, height=None): """Decode an image from memory into a cairo surface. The file format is detected automatically. :param image_data: A byte string :param width: Integer width in pixels or None :param height: Integer height in pixels or None :returns: A tuple of a new :class:`~cairocffi.ImageSurface` object and the name of the detected image format. :raises: :exc:`ImageLoadingError` if the image data is invalid or in an unsupported format. """ pixbuf, format_name = decode_to_pixbuf(image_data, width, height) surface = ( pixbuf_to_cairo_gdk(pixbuf) if gdk is not None else pixbuf_to_cairo_slices(pixbuf) if not pixbuf.get_has_alpha() else pixbuf_to_cairo_png(pixbuf)) return surface, format_name def pixbuf_to_cairo_gdk(pixbuf): """Convert from PixBuf to ImageSurface, using GDK. This method is fastest but GDK is not always available. """ dummy_context = Context(ImageSurface(constants.FORMAT_ARGB32, 1, 1)) gdk.gdk_cairo_set_source_pixbuf( dummy_context._pointer, pixbuf._pointer, 0, 0) return dummy_context.get_source().get_surface() def pixbuf_to_cairo_slices(pixbuf): """Convert from PixBuf to ImageSurface, using slice-based byte swapping. This method is 2~5x slower than GDK but does not support an alpha channel. (cairo uses pre-multiplied alpha, but not Pixbuf.) """ assert pixbuf.get_colorspace() == gdk_pixbuf.GDK_COLORSPACE_RGB assert pixbuf.get_n_channels() == 3 assert pixbuf.get_bits_per_sample() == 8 width = pixbuf.get_width() height = pixbuf.get_height() rowstride = pixbuf.get_rowstride() pixels = ffi.buffer(pixbuf.get_pixels(), pixbuf.get_byte_length()) # TODO: remove this when cffi buffers support slicing with a stride. pixels = pixels[:] # Convert GdkPixbuf’s big-endian RGBA to cairo’s native-endian ARGB cairo_stride = ImageSurface.format_stride_for_width( constants.FORMAT_RGB24, width) data = bytearray(cairo_stride * height) big_endian = sys.byteorder == 'big' pixbuf_row_length = width * 3 # stride == row_length + padding cairo_row_length = width * 4 # stride == row_length + padding alpha = b'\xff' * width # opaque for y in range(height): offset = rowstride * y end = offset + pixbuf_row_length red = pixels[offset:end:3] green = pixels[offset + 1:end:3] blue = pixels[offset + 2:end:3] offset = cairo_stride * y end = offset + cairo_row_length if big_endian: # pragma: no cover data[offset:end:4] = alpha data[offset + 1:end:4] = red data[offset + 2:end:4] = green data[offset + 3:end:4] = blue else: data[offset + 3:end:4] = alpha data[offset + 2:end:4] = red data[offset + 1:end:4] = green data[offset:end:4] = blue data = array('B', data) return ImageSurface(constants.FORMAT_RGB24, width, height, data, cairo_stride) def pixbuf_to_cairo_png(pixbuf): """Convert from PixBuf to ImageSurface, by going through the PNG format. This method is 10~30x slower than GDK but always works. """ buffer_pointer = ffi.new('gchar **') buffer_size = ffi.new('gsize *') error = ffi.new('GError **') handle_g_error(error, pixbuf.save_to_buffer( buffer_pointer, buffer_size, ffi.new('char[]', b'png'), error, ffi.new('char[]', b'compression'), ffi.new('char[]', b'0'), ffi.NULL)) png_bytes = ffi.buffer(buffer_pointer[0], buffer_size[0]) return ImageSurface.create_from_png(BytesIO(png_bytes)) cairocffi-1.2.0/cairocffi/surfaces.py000066400000000000000000001612001374663167600175740ustar00rootroot00000000000000""" 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.""" self.instances.add(self) class Surface(object): """The base class for all surface types. Should not be instantiated directly, but see :doc:`cffi_api`. An instance may be returned for cairo surface types that are not (yet) defined in cairocffi. A :class:`Surface` represents an image, either as the destination of a drawing operation or as source when drawing onto another surface. To draw to a :class:`Surface`, create a cairo :class:`Context` with the surface as the target. There are different sub-classes of :class:`Surface` for different drawing backends; for example, :class:`ImageSurface` is a bitmap image in memory. The initial contents of a surface after creation depend upon the manner of its creation. If cairo creates the surface and backing storage for the user, it will be initially cleared; for example, :class:`ImageSurface` and :meth:`create_similar`. Alternatively, if the user passes in a reference to some backing storage and asks cairo to wrap that in a :class:`Surface`, then the contents are not modified; for example, :class:`ImageSurface` with a :obj:`data` argument. """ def __init__(self, pointer, target_keep_alive=None): self._pointer = ffi.gc( pointer, _keepref(cairo, cairo.cairo_surface_destroy)) self._check_status() if hasattr(target_keep_alive, '__array_interface__'): is_empty = target_keep_alive.size == 0 else: is_empty = target_keep_alive in (None, ffi.NULL) if not is_empty: keep_alive = KeepAlive(target_keep_alive) _check_status(cairo.cairo_surface_set_user_data( self._pointer, SURFACE_TARGET_KEY, *keep_alive.closure)) keep_alive.save() def _check_status(self): _check_status(cairo.cairo_surface_status(self._pointer)) @staticmethod def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_surface_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count ` now. :return: A new instance of :class:`Surface` or one of its sub-classes, depending on the surface’s type. """ if pointer == ffi.NULL: raise ValueError('Null pointer') if incref: cairo.cairo_surface_reference(pointer) self = object.__new__(SURFACE_TYPE_TO_CLASS.get( cairo.cairo_surface_get_type(pointer), Surface)) Surface.__init__(self, pointer) # Skip the subclass’s __init__ return self def create_similar(self, content, width, height): """Create a new surface that is as compatible as possible for uploading to and the use in conjunction with this surface. For example the new surface will have the same fallback resolution and :class:`FontOptions`. Generally, the new surface will also use the same backend as other, unless that is not possible for some reason. Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.) Use :meth:`create_similar_image` if you need an image surface which can be painted quickly to the target surface. :param content: the :ref:`CONTENT` string for the new surface. :param width: width of the new surface (in device-space units) :param height: height of the new surface (in device-space units) :type content: str :type width: int :type height: int :returns: A new instance of :class:`Surface` or one of its subclasses. """ return Surface._from_pointer( cairo.cairo_surface_create_similar( self._pointer, content, width, height), incref=False) def create_similar_image(self, content, width, height): """ Create a new image surface that is as compatible as possible for uploading to and the use in conjunction with this surface. However, this surface can still be used like any normal image surface. Initially the surface contents are all 0 (transparent if contents have transparency, black otherwise.) Use :meth:`create_similar` if you don't need an image surface. :param format: the :ref:`FORMAT` string for the new surface :param width: width of the new surface, (in device-space units) :param height: height of the new surface (in device-space units) :type format: str :type width: int :type height: int :returns: A new :class:`ImageSurface` instance. """ return Surface._from_pointer( cairo.cairo_surface_create_similar_image( self._pointer, content, width, height), incref=False) def create_for_rectangle(self, x, y, width, height): """ Create a new surface that is a rectangle within this surface. All operations drawn to this surface are then clipped and translated onto the target surface. Nothing drawn via this sub-surface outside of its bounds is drawn onto the target surface, making this a useful method for passing constrained child surfaces to library routines that draw directly onto the parent surface, i.e. with no further backend allocations, double buffering or copies. .. note:: As of cairo 1.12, the semantics of subsurfaces have not been finalized yet unless the rectangle is in full device units, is contained within the extents of the target surface, and the target or subsurface's device transforms are not changed. :param x: The x-origin of the sub-surface from the top-left of the target surface (in device-space units) :param y: The y-origin of the sub-surface from the top-left of the target surface (in device-space units) :param width: Width of the sub-surface (in device-space units) :param height: Height of the sub-surface (in device-space units) :type x: float :type y: float :type width: float :type height: float :returns: A new :class:`Surface` object. *New in cairo 1.10.* """ return Surface._from_pointer( cairo.cairo_surface_create_for_rectangle( self._pointer, x, y, width, height), incref=False) def get_content(self): """Returns the :ref:`CONTENT` string of this surface, which indicates whether the surface contains color and/or alpha information. """ return cairo.cairo_surface_get_content(self._pointer) def has_show_text_glyphs(self): """Returns whether the surface supports sophisticated :meth:`Context.show_text_glyphs` operations. That is, whether it actually uses the text and cluster data provided to a :meth:`Context.show_text_glyphs` call. .. note:: Even if this method returns :obj:`False`, :meth:`Context.show_text_glyphs` operation targeted at surface will still succeed. It just will act like a :meth:`Context.show_glyphs` operation. Users can use this method to avoid computing UTF-8 text and cluster mapping if the target surface does not use it. """ return bool(cairo.cairo_surface_has_show_text_glyphs(self._pointer)) def set_device_offset(self, x_offset, y_offset): """ Sets an offset that is added to the device coordinates determined by the CTM when drawing to surface. One use case for this method is when we want to create a :class:`Surface` that redirects drawing for a portion of an onscreen surface to an offscreen surface in a way that is completely invisible to the user of the cairo API. Setting a transformation via :meth:`Context.translate` isn't sufficient to do this, since methods like :meth:`Context.device_to_user` will expose the hidden offset. Note that the offset affects drawing to the surface as well as using the surface in a source pattern. :param x_offset: The offset in the X direction, in device units :param y_offset: The offset in the Y direction, in device units """ cairo.cairo_surface_set_device_offset( self._pointer, x_offset, y_offset) self._check_status() def get_device_offset(self): """Returns the previous device offset set by :meth:`set_device_offset`. :returns: ``(x_offset, y_offset)`` """ offsets = ffi.new('double[2]') cairo.cairo_surface_get_device_offset( self._pointer, offsets + 0, offsets + 1) return tuple(offsets) def set_fallback_resolution(self, x_pixels_per_inch, y_pixels_per_inch): """ Set the horizontal and vertical resolution for image fallbacks. When certain operations aren't supported natively by a backend, cairo will fallback by rendering operations to an image and then overlaying that image onto the output. For backends that are natively vector-oriented, this method can be used to set the resolution used for these image fallbacks, (larger values will result in more detailed images, but also larger file sizes). Some examples of natively vector-oriented backends are the ps, pdf, and svg backends. For backends that are natively raster-oriented, image fallbacks are still possible, but they are always performed at the native device resolution. So this method has no effect on those backends. .. note:: The fallback resolution only takes effect at the time of completing a page (with :meth:`show_page` or :meth:`copy_page`) so there is currently no way to have more than one fallback resolution in effect on a single page. The default fallback resoultion is 300 pixels per inch in both dimensions. :param x_pixels_per_inch: horizontal resolution in pixels per inch :type x_pixels_per_inch: float :param y_pixels_per_inch: vertical resolution in pixels per inch :type y_pixels_per_inch: float """ cairo.cairo_surface_set_fallback_resolution( self._pointer, x_pixels_per_inch, y_pixels_per_inch) self._check_status() def get_fallback_resolution(self): """Returns the previous fallback resolution set by :meth:`set_fallback_resolution`, or default fallback resolution if never set. :returns: ``(x_pixels_per_inch, y_pixels_per_inch)`` """ ppi = ffi.new('double[2]') cairo.cairo_surface_get_fallback_resolution( self._pointer, ppi + 0, ppi + 1) return tuple(ppi) def get_font_options(self): """Retrieves the default font rendering options for the surface. This allows display surfaces to report the correct subpixel order for rendering on them, print surfaces to disable hinting of metrics and so forth. The result can then be used with :class:`ScaledFont`. :returns: A new :class:`FontOptions` object. """ font_options = FontOptions() cairo.cairo_surface_get_font_options( self._pointer, font_options._pointer) return font_options def set_device_scale(self, x_scale, y_scale): """Sets a scale that is multiplied to the device coordinates determined by the CTM when drawing to surface. One common use for this is to render to very high resolution display devices at a scale factor, so that code that assumes 1 pixel will be a certain size will still work. Setting a transformation via cairo_translate() isn't sufficient to do this, since functions like cairo_device_to_user() will expose the hidden scale. Note that the scale affects drawing to the surface as well as using the surface in a source pattern. :param x_scale: the scale in the X direction, in device units. :param y_scale: the scale in the Y direction, in device units. *New in cairo 1.14.* *New in cairocffi 0.9.* """ cairo.cairo_surface_set_device_scale(self._pointer, x_scale, y_scale) self._check_status() def get_device_scale(self): """Returns the previous device offset set by :meth:`set_device_scale`. *New in cairo 1.14.* *New in cairocffi 0.9.* """ size = ffi.new('double[2]') cairo.cairo_surface_get_device_scale(self._pointer, size + 0, size + 1) return tuple(size) def set_mime_data(self, mime_type, data): """ Attach an image in the format :obj:`mime_type` to this surface. To remove the data from a surface, call this method with same mime type and :obj:`None` for data. The attached image (or filename) data can later be used by backends which support it (currently: PDF, PS, SVG and Win32 Printing surfaces) to emit this data instead of making a snapshot of the surface. This approach tends to be faster and requires less memory and disk space. The recognized MIME types are the following: ``"image/png"`` The Portable Network Graphics image file format (ISO/IEC 15948). ``"image/jpeg"`` The Joint Photographic Experts Group (JPEG) image coding standard (ISO/IEC 10918-1). ``"image/jp2"`` The Joint Photographic Experts Group (JPEG) 2000 image coding standard (ISO/IEC 15444-1). ``"text/x-uri"`` URL for an image file (unofficial MIME type). See corresponding backend surface docs for details about which MIME types it can handle. Caution: the associated MIME data will be discarded if you draw on the surface afterwards. Use this method with care. :param mime_type: The MIME type of the image data. :type mime_type: ASCII string :param data: The image data to attach to the surface. :type data: bytes *New in cairo 1.10.* """ mime_type = ffi.new('char[]', mime_type.encode('utf8')) if data is None: _check_status(cairo.cairo_surface_set_mime_data( self._pointer, mime_type, ffi.NULL, 0, ffi.NULL, ffi.NULL)) else: # TODO: avoid making a copy here if possible. length = len(data) data = ffi.new('unsigned char[]', data) keep_alive = KeepAlive(data, mime_type) _check_status(cairo.cairo_surface_set_mime_data( self._pointer, mime_type, data, length, *keep_alive.closure)) keep_alive.save() # Only on success def get_mime_data(self, mime_type): """Return mime data previously attached to surface using the specified mime type. :param mime_type: The MIME type of the image data. :type mime_type: ASCII string :returns: A CFFI buffer object, or :obj:`None` if no data has been attached with the given mime type. *New in cairo 1.10.* """ buffer_address = ffi.new('unsigned char **') buffer_length = ffi.new('unsigned long *') mime_type = ffi.new('char[]', mime_type.encode('utf8')) cairo.cairo_surface_get_mime_data( self._pointer, mime_type, buffer_address, buffer_length) return (ffi.buffer(buffer_address[0], buffer_length[0]) if buffer_address[0] != ffi.NULL else None) def supports_mime_type(self, mime_type): """ Return whether surface supports :obj:`mime_type`. :param mime_type: The MIME type of the image data. :type mime_type: ASCII string *New in cairo 1.12.* """ mime_type = ffi.new('char[]', mime_type.encode('utf8')) return bool(cairo.cairo_surface_supports_mime_type( self._pointer, mime_type)) def mark_dirty(self): """Tells cairo that drawing has been done to surface using means other than cairo, and that cairo should reread any cached areas. Note that you must call :meth:`flush` before doing such drawing. """ cairo.cairo_surface_mark_dirty(self._pointer) self._check_status() def mark_dirty_rectangle(self, x, y, width, height): """ Like :meth:`mark_dirty`, but drawing has been done only to the specified rectangle, so that cairo can retain cached contents for other parts of the surface. Any cached clip set on the surface will be reset by this method, to make sure that future cairo calls have the clip set that they expect. :param x: X coordinate of dirty rectangle. :param y: Y coordinate of dirty rectangle. :param width: Width of dirty rectangle. :param height: Height of dirty rectangle. :type x: float :type y: float :type width: float :type height: float """ cairo.cairo_surface_mark_dirty_rectangle( self._pointer, x, y, width, height) self._check_status() def show_page(self): """Emits and clears the current page for backends that support multiple pages. Use :meth:`copy_page` if you don't want to clear the page. :meth:`Context.show_page` is a convenience method for this. """ cairo.cairo_surface_show_page(self._pointer) self._check_status() def copy_page(self): """Emits the current page for backends that support multiple pages, but doesn't clear it, so that the contents of the current page will be retained for the next page. Use :meth:`show_page` if you want to get an empty page after the emission. """ cairo.cairo_surface_copy_page(self._pointer) self._check_status() def flush(self): """Do any pending drawing for the surface and also restore any temporary modifications cairo has made to the surface's state. This method must be called before switching from drawing on the surface with cairo to drawing on it directly with native APIs. If the surface doesn't support direct access, then this method does nothing. """ cairo.cairo_surface_flush(self._pointer) self._check_status() def finish(self): """This method finishes the surface and drops all references to external resources. For example, for the Xlib backend it means that cairo will no longer access the drawable, which can be freed. After calling :meth:`finish` the only valid operations on a surface are getting and setting user data, flushing and finishing it. Further drawing to the surface will not affect the surface but will instead trigger a :class:`CairoError` with a ``SURFACE_FINISHED`` status. When the surface is garbage-collected, cairo will call :meth:`finish()` if it hasn't been called already, before freeing the resources associated with the surface. """ cairo.cairo_surface_finish(self._pointer) self._check_status() def write_to_png(self, target=None): """Writes the contents of surface as a PNG image. :param target: A filename, a binary mode file-like object with a :meth:`~file.write` method, or :obj:`None`. :returns: If :obj:`target` is :obj:`None`, return the PNG contents as a byte string. """ return_bytes = target is None if return_bytes: target = io.BytesIO() if hasattr(target, 'write'): try: write_func = _make_write_func(target) _check_status(cairo.cairo_surface_write_to_png_stream( self._pointer, write_func, ffi.NULL)) except SystemError: # noqa # Callback creation has failed if hasattr(target, 'name'): # File-like object has a name, write here _check_status(cairo.cairo_surface_write_to_png( self._pointer, _encode_filename(target.name))) else: # Use a fallback temporary file with NamedTemporaryFile('wb', delete=False) as fd: filename = fd.name _check_status(cairo.cairo_surface_write_to_png( self._pointer, _encode_filename(filename))) png_file = Path(filename) target.write(png_file.read_bytes()) png_file.unlink() else: _check_status(cairo.cairo_surface_write_to_png( self._pointer, _encode_filename(target))) if return_bytes: return target.getvalue() class ImageSurface(Surface): """Creates an image surface of the specified format and dimensions. If :obj:`data` is not :obj:`None` its initial contents will be used as the initial image contents; you must explicitly clear the buffer, using, for example, :meth:`Context.rectangle` and :meth:`Context.fill` if you want it cleared. .. note:: Currently only :class:`array.array` buffers are supported on PyPy. Otherwise, the surface contents are all initially 0. (Specifically, within each pixel, each color or alpha channel belonging to format will be 0. The contents of bits within a pixel, but not belonging to the given format are undefined). :param format: :ref:`FORMAT` string for the surface to create. :param width: Width of the surface, in pixels. :param height: Height of the surface, in pixels. :param data: Buffer supplied in which to write contents, or :obj:`None` to create a new buffer. :param stride: The number of bytes between the start of rows in the buffer as allocated. This value should always be computed by :meth:`format_stride_for_width` before allocating the data buffer. If omitted but :obj:`data` is given, :meth:`format_stride_for_width` is used. :type format: str :type width: int :type height: int :type stride: int """ def __init__(self, format, width, height, data=None, stride=None): if data is None: pointer = cairo.cairo_image_surface_create(format, width, height) else: if stride is None: stride = self.format_stride_for_width(format, width) address, length = from_buffer(data) if length < stride * height: raise ValueError('Got a %d bytes buffer, needs at least %d.' % (length, stride * height)) pointer = cairo.cairo_image_surface_create_for_data( ffi.cast('unsigned char*', address), format, width, height, stride) Surface.__init__(self, pointer, target_keep_alive=data) @classmethod def create_for_data(cls, data, format, width, height, stride=None): """Same as ``ImageSurface(format, width, height, data, stride)``. Exists for compatibility with pycairo. """ return cls(format, width, height, data, stride) @staticmethod def format_stride_for_width(format, width): """ This method provides a stride value (byte offset between rows) that will respect all alignment requirements of the accelerated image-rendering code within cairo. Typical usage will be of the form:: from cairocffi import ImageSurface stride = ImageSurface.format_stride_for_width(format, width) data = bytearray(stride * height) surface = ImageSurface(format, width, height, data, stride) :param format: A :ref:`FORMAT` string. :param width: The desired width of the surface, in pixels. :type format: str :type width: int :returns: The appropriate stride to use given the desired format and width, or -1 if either the format is invalid or the width too large. """ return cairo.cairo_format_stride_for_width(format, width) @classmethod def create_from_png(cls, source): """Decode a PNG file into a new image surface. :param source: A filename or a binary mode file-like object with a :meth:`~file.read` method. If you already have a byte string in memory, use :class:`io.BytesIO`. :returns: A new :class:`ImageSurface` instance. """ if hasattr(source, 'read'): read_func = _make_read_func(source) pointer = cairo.cairo_image_surface_create_from_png_stream( read_func, ffi.NULL) else: pointer = cairo.cairo_image_surface_create_from_png( _encode_filename(source)) self = object.__new__(cls) Surface.__init__(self, pointer) # Skip ImageSurface.__init__ return self def get_data(self): """Return the buffer pointing to the image’s pixel data, encoded according to the surface’s :ref:`FORMAT` string. A call to :meth:`flush` is required before accessing the pixel data to ensure that all pending drawing operations are finished. A call to :meth:`~Surface.mark_dirty` is required after the data is modified. :returns: A read-write CFFI buffer object. """ return ffi.buffer( cairo.cairo_image_surface_get_data(self._pointer), self.get_stride() * self.get_height()) def get_format(self): """Return the :ref:`FORMAT` string of the surface.""" return cairo.cairo_image_surface_get_format(self._pointer) def get_width(self): """Return the width of the surface, in pixels.""" return cairo.cairo_image_surface_get_width(self._pointer) def get_height(self): """Return the width of the surface, in pixels.""" return cairo.cairo_image_surface_get_height(self._pointer) def get_stride(self): """Return the stride of the image surface in bytes (or 0 if surface is not an image surface). The stride is the distance in bytes from the beginning of one row of the image data to the beginning of the next row. """ return cairo.cairo_image_surface_get_stride(self._pointer) class PDFSurface(Surface): """Creates a PDF surface of the specified size in PostScript points to be written to :obj:`target`. Note that the size of individual pages of the PDF output can vary. See :meth:`set_size`. The PDF surface backend recognizes the following MIME types for the data attached to a surface (see :meth:`~Surface.set_mime_data`) when it is used as a source pattern for drawing on this surface: ``image/jpeg`` and ``image/jp2``. If any of them is specified, the PDF backend emits an image with the content of MIME data (with the ``/DCTDecode`` or ``/JPXDecode`` filter, respectively) instead of a surface snapshot (with the ``/FlateDecode`` filter), which typically produces PDF with a smaller file size. :obj:`target` can be :obj:`None` to specify no output. This will generate a surface that may be queried and used as a source, without generating a temporary file. :param target: A filename, a binary mode file-like object with a :meth:`~file.write` method, or :obj:`None`. :param width_in_points: Width of the surface, in points (1 point == 1/72.0 inch) :param height_in_points: Height of the surface, in points (1 point == 1/72.0 inch) :type width_in_points: float :type height_in_points: float """ def __init__(self, target, width_in_points, height_in_points): if hasattr(target, 'write') or target is None: write_func = _make_write_func(target) pointer = cairo.cairo_pdf_surface_create_for_stream( write_func, ffi.NULL, width_in_points, height_in_points) else: write_func = None pointer = cairo.cairo_pdf_surface_create( _encode_filename(target), width_in_points, height_in_points) Surface.__init__(self, pointer, target_keep_alive=write_func) def set_size(self, width_in_points, height_in_points): """Changes the size of a PDF surface for the current (and subsequent) pages. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this method immediately after creating the surface or immediately after completing a page with either :meth:`~Surface.show_page` or :meth:`~Surface.copy_page`. :param width_in_points: New width of the page, in points (1 point = 1/72.0 inch) :param height_in_points: New height of the page, in points (1 point = 1/72.0 inch) :type width_in_points: float :type height_in_points: float """ cairo.cairo_pdf_surface_set_size( self._pointer, width_in_points, height_in_points) self._check_status() def add_outline(self, parent_id, utf8, link_attribs, flags=None): """Add an item to the document outline hierarchy. The outline has the ``utf8`` name and links to the location specified by ``link_attribs``. Link attributes have the same keys and values as the Link Tag, excluding the ``rect`` attribute. The item will be a child of the item with id ``parent_id``. Use ``PDF_OUTLINE_ROOT`` as the parent id of top level items. :param parent_id: the id of the parent item or ``PDF_OUTLINE_ROOT`` if this is a top level item. :param utf8: the name of the outline. :param link_attribs: the link attributes specifying where this outline links to. :param flags: outline item flags. :return: the id for the added item. *New in cairo 1.16.* *New in cairocffi 0.9.* """ if flags is None: flags = 0 value = cairo.cairo_pdf_surface_add_outline( self._pointer, parent_id, _encode_string(utf8), _encode_string(link_attribs), flags) self._check_status() return value def set_metadata(self, metadata, utf8): """Sets document metadata. The ``PDF_METADATA_CREATE_DATE`` and ``PDF_METADATA_MOD_DATE`` values must be in ISO-8601 format: YYYY-MM-DDThh:mm:ss. An optional timezone of the form "[+/-]hh:mm" or "Z" for UTC time can be appended. All other metadata values can be any UTF-8 string. :param metadata: the metadata item to set. :param utf8: metadata value. *New in cairo 1.16.* *New in cairocffi 0.9.* """ cairo.cairo_pdf_surface_set_metadata( self._pointer, metadata, _encode_string(utf8)) self._check_status() def set_page_label(self, utf8): """Set page label for the current page. :param utf8: the page label. *New in cairo 1.16.* *New in cairocffi 0.9.* """ cairo.cairo_pdf_surface_set_page_label( self._pointer, _encode_string(utf8)) def set_thumbnail_size(self, width, height): """Set thumbnail image size for the current and all subsequent pages. Setting a width or height of 0 disables thumbnails for the current and subsequent pages. :param width: thumbnail width. :param height: thumbnail height. *New in cairo 1.16.* *New in cairocffi 0.9.* """ cairo.cairo_pdf_surface_set_thumbnail_size( self._pointer, width, height) def restrict_to_version(self, version): """Restricts the generated PDF file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this method immediately after creating the surface. :param version: A :ref:`PDF_VERSION` string. *New in cairo 1.10.* """ cairo.cairo_pdf_surface_restrict_to_version(self._pointer, version) self._check_status() @staticmethod def get_versions(): """Return the list of supported PDF versions. See :meth:`restrict_to_version`. :return: A list of :ref:`PDF_VERSION` strings. *New in cairo 1.10.* """ versions = ffi.new('cairo_pdf_version_t const **') num_versions = ffi.new('int *') cairo.cairo_pdf_get_versions(versions, num_versions) versions = versions[0] return [versions[i] for i in range(num_versions[0])] @staticmethod def version_to_string(version): """Return the string representation of the given :ref:`PDF_VERSION`. See :meth:`get_versions` for a way to get the list of valid version ids. *New in cairo 1.10.* """ c_string = cairo.cairo_pdf_version_to_string(version) if c_string == ffi.NULL: raise ValueError(version) return ffi.string(c_string).decode('ascii') class PSSurface(Surface): """Creates a PostScript surface of the specified size in PostScript points to be written to :obj:`target`. Note that the size of individual pages of the PostScript output can vary. See :meth:`set_size`. :obj:`target` can be :obj:`None` to specify no output. This will generate a surface that may be queried and used as a source, without generating a temporary file. The PostScript surface backend recognizes the ``image/jpeg`` MIME type for the data attached to a surface (see :meth:`~Surface.set_mime_data`) when it is used as a source pattern for drawing on this surface. If it is specified, the PostScript backend emits an image with the content of MIME data (with the ``/DCTDecode`` filter) instead of a surface snapshot (with the ``/FlateDecode`` filter), which typically produces PostScript with a smaller file size. :param target: A filename, a binary mode file-like object with a :meth:`~file.write` method, or :obj:`None`. :param width_in_points: Width of the surface, in points (1 point == 1/72.0 inch) :param height_in_points: Height of the surface, in points (1 point == 1/72.0 inch) :type width_in_points: float :type height_in_points: float """ def __init__(self, target, width_in_points, height_in_points): if hasattr(target, 'write') or target is None: write_func = _make_write_func(target) pointer = cairo.cairo_ps_surface_create_for_stream( write_func, ffi.NULL, width_in_points, height_in_points) else: write_func = None pointer = cairo.cairo_ps_surface_create( _encode_filename(target), width_in_points, height_in_points) Surface.__init__(self, pointer, target_keep_alive=write_func) def dsc_comment(self, comment): """ Emit a comment into the PostScript output for the given surface. The comment is expected to conform to the PostScript Language Document Structuring Conventions (DSC). Please see that manual for details on the available comments and their meanings. In particular, the ``%%IncludeFeature`` comment allows a device-independent means of controlling printer device features. So the PostScript Printer Description Files Specification will also be a useful reference. The comment string must begin with a percent character (%) and the total length of the string (including any initial percent characters) must not exceed 255 bytes. Violating either of these conditions will place surface into an error state. But beyond these two conditions, this method will not enforce conformance of the comment with any particular specification. The comment string should not have a trailing newline. The DSC specifies different sections in which particular comments can appear. This method provides for comments to be emitted within three sections: the header, the Setup section, and the PageSetup section. Comments appearing in the first two sections apply to the entire document while comments in the BeginPageSetup section apply only to a single page. For comments to appear in the header section, this method should be called after the surface is created, but before a call to :meth:`dsc_begin_setup`. For comments to appear in the Setup section, this method should be called after a call to :meth:`dsc_begin_setup` but before a call to :meth:`dsc_begin_page_setup`. For comments to appear in the PageSetup section, this method should be called after a call to :meth:`dsc_begin_page_setup`. Note that it is only necessary to call :meth:`dsc_begin_page_setup` for the first page of any surface. After a call to :meth:`~Surface.show_page` or :meth:`~Surface.copy_page` comments are unambiguously directed to the PageSetup section of the current page. But it doesn't hurt to call this method at the beginning of every page as that consistency may make the calling code simpler. As a final note, cairo automatically generates several comments on its own. As such, applications must not manually generate any of the following comments: Header section: ``%!PS-Adobe-3.0``, ``%%Creator``, ``%%CreationDate``, ``%%Pages``, ``%%BoundingBox``, ``%%DocumentData``, ``%%LanguageLevel``, ``%%EndComments``. Setup section: ``%%BeginSetup``, ``%%EndSetup``. PageSetup section: ``%%BeginPageSetup``, ``%%PageBoundingBox``, ``%%EndPageSetup``. Other sections: ``%%BeginProlog``, ``%%EndProlog``, ``%%Page``, ``%%Trailer``, ``%%EOF``. """ cairo.cairo_ps_surface_dsc_comment( self._pointer, _encode_string(comment)) self._check_status() def dsc_begin_setup(self): """Indicate that subsequent calls to :meth:`dsc_comment` should direct comments to the Setup section of the PostScript output. This method should be called at most once per surface, and must be called before any call to :meth:`dsc_begin_page_setup` and before any drawing is performed to the surface. See :meth:`dsc_comment` for more details. """ cairo.cairo_ps_surface_dsc_begin_setup(self._pointer) self._check_status() def dsc_begin_page_setup(self): """Indicate that subsequent calls to :meth:`dsc_comment` should direct comments to the PageSetup section of the PostScript output. This method is only needed for the first page of a surface. It must be called after any call to :meth:`dsc_begin_setup` and before any drawing is performed to the surface. See :meth:`dsc_comment` for more details. """ cairo.cairo_ps_surface_dsc_begin_page_setup(self._pointer) self._check_status() def set_eps(self, eps): """ If :obj:`eps` is True, the PostScript surface will output Encapsulated PostScript. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this method immediately after creating the surface. An Encapsulated PostScript file should never contain more than one page. """ cairo.cairo_ps_surface_set_eps(self._pointer, bool(eps)) self._check_status() def get_eps(self): """Check whether the PostScript surface will output Encapsulated PostScript. """ return bool(cairo.cairo_ps_surface_get_eps(self._pointer)) def set_size(self, width_in_points, height_in_points): """Changes the size of a PostScript surface for the current (and subsequent) pages. This method should only be called before any drawing operations have been performed on the current page. The simplest way to do this is to call this method immediately after creating the surface or immediately after completing a page with either :meth:`~Surface.show_page` or :meth:`~Surface.copy_page`. :param width_in_points: New width of the page, in points (1 point == 1/72.0 inch) :param height_in_points: New height of the page, in points (1 point == 1/72.0 inch) :type width_in_points: float :type height_in_points: float """ cairo.cairo_ps_surface_set_size( self._pointer, width_in_points, height_in_points) self._check_status() def restrict_to_level(self, level): """Restricts the generated PostScript file to :obj:`level`. See :meth:`get_levels` for a list of available level values that can be used here. This method should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this method immediately after creating the surface. :param version: A :ref:`PS_LEVEL` string. """ cairo.cairo_ps_surface_restrict_to_level(self._pointer, level) self._check_status() @staticmethod def get_levels(): """Return the list of supported PostScript levels. See :meth:`restrict_to_level`. :return: A list of :ref:`PS_LEVEL` strings. """ levels = ffi.new('cairo_ps_level_t const **') num_levels = ffi.new('int *') cairo.cairo_ps_get_levels(levels, num_levels) levels = levels[0] return [levels[i] for i in range(num_levels[0])] @staticmethod def ps_level_to_string(level): """Return the string representation of the given :ref:`PS_LEVEL`. See :meth:`get_levels` for a way to get the list of valid level ids. """ c_string = cairo.cairo_ps_level_to_string(level) if c_string == ffi.NULL: raise ValueError(level) return ffi.string(c_string).decode('ascii') class SVGSurface(Surface): """Creates a SVG surface of the specified size in points to be written to :obj:`target`. :obj:`target` can be :obj:`None` to specify no output. This will generate a surface that may be queried and used as a source, without generating a temporary file. The SVG surface backend recognizes the following MIME types for the data attached to a surface (see :meth:`~Surface.set_mime_data`) when it is used as a source pattern for drawing on this surface: ``image/png``, ``image/jpeg`` and ``text/x-uri``. If any of them is specified, the SVG backend emits a href with the content of MIME data instead of a surface snapshot (PNG, Base64-encoded) in the corresponding image tag. The unofficial MIME type ``text/x-uri`` is examined first. If present, the URL is emitted as is: assuring the correctness of URL is left to the client code. If ``text/x-uri`` is not present, but ``image/jpeg`` or ``image/png`` is specified, the corresponding data is Base64-encoded and emitted. :param target: A filename, a binary mode file-like object with a :meth:`~file.write` method, or :obj:`None`. :param width_in_points: Width of the surface, in points (1 point == 1/72.0 inch) :param height_in_points: Height of the surface, in points (1 point == 1/72.0 inch) :type width_in_points: float :type height_in_points: float """ def __init__(self, target, width_in_points, height_in_points): if hasattr(target, 'write') or target is None: write_func = _make_write_func(target) pointer = cairo.cairo_svg_surface_create_for_stream( write_func, ffi.NULL, width_in_points, height_in_points) else: write_func = None pointer = cairo.cairo_svg_surface_create( _encode_filename(target), width_in_points, height_in_points) Surface.__init__(self, pointer, target_keep_alive=write_func) def restrict_to_version(self, version): """Restricts the generated SVG file to :obj:`version`. See :meth:`get_versions` for a list of available version values that can be used here. This method should only be called before any drawing operations have been performed on the given surface. The simplest way to do this is to call this method immediately after creating the surface. :param version: A :ref:`SVG_VERSION` string. """ cairo.cairo_svg_surface_restrict_to_version(self._pointer, version) self._check_status() def set_document_unit(self, unit): """Use specified unit for width and height of generated SVG file. See ``SVG_UNIT_*`` enumerated values for a list of available unit values that can be used here. This function can be called at any time before generating the SVG file. However to minimize the risk of ambiguities it's recommended to call it before any drawing operations have been performed on the given surface, to make it clearer what the unit used in the drawing operations is. The simplest way to do this is to call this function immediately after creating the SVG surface. Note if this function is never called, the default unit for SVG documents generated by cairo will be "pt". This is for historical reasons. :param unit: SVG unit. *New in cairo 1.16.* *New in cairocffi 0.9.* """ cairo.cairo_svg_surface_set_document_unit(self._pointer, unit) self._check_status() def get_document_unit(self): """Get the unit of the SVG surface. If the surface passed as an argument is not a SVG surface, the function sets the error status to ``STATUS_SURFACE_TYPE_MISMATCH`` and returns :ref:`SVG_UNIT_USER`. :return: The SVG unit of the SVG surface. *New in cairo 1.16.* *New in cairocffi 0.9.* """ unit = cairo.cairo_svg_surface_get_document_unit(self._pointer) self._check_status() return unit @staticmethod def get_versions(): """Return the list of supported SVG versions. See :meth:`restrict_to_version`. :return: A list of :ref:`SVG_VERSION` strings. """ versions = ffi.new('cairo_svg_version_t const **') num_versions = ffi.new('int *') cairo.cairo_svg_get_versions(versions, num_versions) versions = versions[0] return [versions[i] for i in range(num_versions[0])] @staticmethod def version_to_string(version): """Return the string representation of the given :ref:`SVG_VERSION`. See :meth:`get_versions` for a way to get the list of valid version ids. """ c_string = cairo.cairo_svg_version_to_string(version) if c_string == ffi.NULL: raise ValueError(version) return ffi.string(c_string).decode('ascii') class RecordingSurface(Surface): """A recording surface is a surface that records all drawing operations at the highest level of the surface backend interface, (that is, the level of paint, mask, stroke, fill, and show_text_glyphs). The recording surface can then be "replayed" against any target surface by using it as a source surface. If you want to replay a surface so that the results in :obj:`target` will be identical to the results that would have been obtained if the original operations applied to the recording surface had instead been applied to the target surface, you can use code like this:: context = Context(target) context.set_source_surface(recording_surface, 0, 0) context.paint() A recording surface is logically unbounded, i.e. it has no implicit constraint on the size of the drawing surface. However, in practice this is rarely useful as you wish to replay against a particular target surface with known bounds. For this case, it is more efficient to specify the target extents to the recording surface upon creation. The recording phase of the recording surface is careful to snapshot all necessary objects (paths, patterns, etc.), in order to achieve accurate replay. :param content: The :ref:`CONTENT` string of the recording surface :param extents: The extents to record as a ``(x, y, width, height)`` tuple of floats in device units, or :obj:`None` to record unbounded operations. ``(x, y)`` are the coordinates of the top-left corner of the rectangle, ``(width, height)`` its dimensions. *New in cairo 1.10* *New in cairocffi 0.2* """ def __init__(self, content, extents): extents = (ffi.new('cairo_rectangle_t *', extents) if extents is not None else ffi.NULL) Surface.__init__( self, cairo.cairo_recording_surface_create(content, extents)) def get_extents(self): """Return the extents of the recording-surface. :returns: A ``(x, y, width, height)`` tuple of floats, or :obj:`None` if the surface is unbounded. *New in cairo 1.12* """ extents = ffi.new('cairo_rectangle_t *') if cairo.cairo_recording_surface_get_extents(self._pointer, extents): return (extents.x, extents.y, extents.width, extents.height) def ink_extents(self): """Measures the extents of the operations stored within the recording-surface. This is useful to compute the required size of an image surface (or equivalent) into which to replay the full sequence of drawing operations. :return: A ``(x, y, width, height)`` tuple of floats. """ extents = ffi.new('double[4]') cairo.cairo_recording_surface_ink_extents( self._pointer, extents + 0, extents + 1, extents + 2, extents + 3) self._check_status() return tuple(extents) class Win32Surface(Surface): # pragma: no cover """Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. The resulting surface will always be of format CAIRO_FORMAT_RGB24; should you need another surface format, you will need to create one through cairo_win32_surface_create_with_dib(). :param hdc : The DC to create a surface for, as obtained from :func:`win32gui.CreateDC`. **Note**: this unsafely inteprets an integer as a pointer. Make sure it actually points to a valid DC! :type hdc: int *New in cairocffi 0.8* """ def __init__(self, hdc): pointer = cairo.cairo_win32_surface_create(ffi.cast('void*', hdc)) Surface.__init__(self, pointer) class Win32PrintingSurface(Surface): # pragma: no cover """Creates a cairo surface that targets the given DC. The DC will be queried for its initial clip extents, and this will be used as the size of the cairo surface. The DC should be a printing DC; antialiasing will be ignored, and GDI will be used as much as possible to draw to the surface. The returned surface will be wrapped using the paginated surface to provide correct complex rendering behaviour; cairo_surface_show_page() and associated methods must be used for correct output. :param hdc: The DC to create a surface for, as obtained from :func:`win32gui.CreateDC`. **Note**: this unsafely inteprets an integer as a pointer. Make sure it actually points to a valid DC! :type hdc: int *New in cairocffi 0.6* """ def __init__(self, hdc): pointer = cairo.cairo_win32_printing_surface_create( ffi.cast('void*', hdc)) Surface.__init__(self, pointer) SURFACE_TYPE_TO_CLASS = { constants.SURFACE_TYPE_IMAGE: ImageSurface, constants.SURFACE_TYPE_PDF: PDFSurface, constants.SURFACE_TYPE_SVG: SVGSurface, constants.SURFACE_TYPE_RECORDING: RecordingSurface, constants.SURFACE_TYPE_WIN32: Win32Surface, constants.SURFACE_TYPE_WIN32_PRINTING: Win32PrintingSurface } cairocffi-1.2.0/cairocffi/test_cairo.py000066400000000000000000001332301374663167600201170ustar00rootroot00000000000000""" cairocffi.tests ~~~~~~~~~~~~~~~ Test suite for cairocffi. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import array import base64 import contextlib import gc import io import math import os import shutil import sys import tempfile import cairocffi import pytest from . import ( PDF_METADATA_AUTHOR, PDF_METADATA_CREATE_DATE, PDF_METADATA_CREATOR, PDF_METADATA_KEYWORDS, PDF_METADATA_MOD_DATE, PDF_METADATA_SUBJECT, PDF_METADATA_TITLE, PDF_OUTLINE_FLAG_BOLD, PDF_OUTLINE_FLAG_OPEN, PDF_OUTLINE_ROOT, SVG_UNIT_PC, SVG_UNIT_PT, SVG_UNIT_PX, TAG_LINK, Context, FontFace, FontOptions, ImageSurface, LinearGradient, Matrix, Pattern, PDFSurface, PSSurface, RadialGradient, RecordingSurface, ScaledFont, SolidPattern, Surface, SurfacePattern, SVGSurface, ToyFontFace, cairo_version, cairo_version_string) if sys.byteorder == 'little': def pixel(argb): # pragma: no cover """Convert a 4-byte ARGB string to native-endian.""" return argb[::-1] else: def pixel(argb): # pragma: no cover """Convert a 4-byte ARGB string to native-endian.""" return argb @contextlib.contextmanager def temp_directory(): tempdir = tempfile.mkdtemp('é') assert 'é' in tempdir # Test non-ASCII filenames try: yield tempdir finally: shutil.rmtree(tempdir) def round_tuple(values): return tuple(round(v, 6) for v in values) def assert_raise_finished(func, *args, **kwargs): with pytest.raises(cairocffi.CairoError) as exc: func(*args, **kwargs) assert 'SURFACE_FINISHED' in str(exc) or 'ExceptionInfo' in str(exc) def test_cairo_version(): major, minor, micro = map(int, cairo_version_string().split('.')) assert cairo_version() == major * 10000 + minor * 100 + micro def test_install_as_pycairo(): cairocffi.install_as_pycairo() import cairo assert cairo is cairocffi def test_image_surface(): assert ImageSurface.format_stride_for_width( cairocffi.FORMAT_ARGB32, 100) == 400 assert ImageSurface.format_stride_for_width( cairocffi.FORMAT_A8, 100) == 100 surface = ImageSurface(cairocffi.FORMAT_ARGB32, 20, 30) assert surface.get_format() == cairocffi.FORMAT_ARGB32 assert surface.get_width() == 20 assert surface.get_height() == 30 assert surface.get_stride() == 20 * 4 with pytest.raises(ValueError): # buffer too small data = array.array('B', b'\x00' * 799) ImageSurface.create_for_data(data, cairocffi.FORMAT_ARGB32, 10, 20) data = array.array('B', b'\x00' * 800) surface = ImageSurface.create_for_data(data, cairocffi.FORMAT_ARGB32, 10, 20, stride=40) context = Context(surface) # The default source is opaque black: assert context.get_source().get_rgba() == (0, 0, 0, 1) context.paint_with_alpha(0.5) assert data.tobytes() == pixel(b'\x80\x00\x00\x00') * 200 def test_image_bytearray_buffer(): if '__pypy__' in sys.modules: pytest.xfail() # Also test buffers through ctypes.c_char.from_buffer, # not available on PyPy data = bytearray(800) surface = ImageSurface.create_for_data(data, cairocffi.FORMAT_ARGB32, 10, 20, stride=40) Context(surface).paint_with_alpha(0.5) assert data == pixel(b'\x80\x00\x00\x00') * 200 @pytest.mark.xfail(cairo_version() < 11200, reason='Cairo version too low') def test_surface_create_similar_image(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 20, 30) similar = surface.create_similar_image(cairocffi.FORMAT_A8, 4, 100) assert isinstance(similar, ImageSurface) assert similar.get_content() == cairocffi.CONTENT_ALPHA assert similar.get_format() == cairocffi.FORMAT_A8 assert similar.get_width() == 4 assert similar.get_height() == 100 @pytest.mark.xfail(cairo_version() < 11000, reason='Cairo version too low') def test_surface_create_for_rectangle(): surface = ImageSurface(cairocffi.FORMAT_A8, 4, 4) data = surface.get_data() assert data[:] == b'\x00' * 16 Context(surface.create_for_rectangle(1, 1, 2, 2)).paint() assert data[:] == ( b'\x00\x00\x00\x00' b'\x00\xFF\xFF\x00' b'\x00\xFF\xFF\x00' b'\x00\x00\x00\x00') def test_surface(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 20, 30) similar = surface.create_similar(cairocffi.CONTENT_ALPHA, 4, 100) assert isinstance(similar, ImageSurface) assert similar.get_content() == cairocffi.CONTENT_ALPHA assert similar.get_format() == cairocffi.FORMAT_A8 assert similar.get_width() == 4 assert similar.get_height() == 100 assert similar.has_show_text_glyphs() is False assert PDFSurface(None, 1, 1).has_show_text_glyphs() is True surface.copy_page() surface.show_page() surface.mark_dirty() surface.mark_dirty_rectangle(1, 2, 300, 12000) surface.flush() surface.set_device_offset(14, 3) assert surface.get_device_offset() == (14, 3) surface.set_fallback_resolution(15, 6) assert surface.get_fallback_resolution() == (15, 6) context = Context(surface) assert isinstance(context.get_target(), ImageSurface) surface_map = cairocffi.surfaces.SURFACE_TYPE_TO_CLASS try: del surface_map[cairocffi.SURFACE_TYPE_IMAGE] target = context.get_target() assert target._pointer == surface._pointer assert isinstance(target, Surface) assert not isinstance(target, ImageSurface) finally: surface_map[cairocffi.SURFACE_TYPE_IMAGE] = ImageSurface surface.finish() assert_raise_finished(surface.copy_page) assert_raise_finished(surface.show_page) assert_raise_finished(surface.set_device_offset, 1, 2) assert_raise_finished(surface.set_fallback_resolution, 3, 4) def test_target_lifetime(): # Test our work around for # Related CFFI bug: https://bitbucket.org/cffi/cffi/issue/92/ if not hasattr(sys, 'getrefcount'): pytest.xfail() # PyPy gc.collect() # Clean up stuff from other tests target = io.BytesIO() initial_refcount = sys.getrefcount(target) assert len(cairocffi.surfaces.KeepAlive.instances) == 0 surface = PDFSurface(target, 100, 100) # The target is in a KeepAlive object assert len(cairocffi.surfaces.KeepAlive.instances) == 1 assert sys.getrefcount(target) == initial_refcount + 1 del surface gc.collect() # Make sure surface is collected assert len(cairocffi.surfaces.KeepAlive.instances) == 0 assert sys.getrefcount(target) == initial_refcount @pytest.mark.xfail(cairo_version() < 11000, reason='Cairo version too low') def test_mime_data(): surface = PDFSurface(None, 1, 1) assert surface.get_mime_data('image/jpeg') is None gc.collect() # Clean up KeepAlive stuff from other tests assert len(cairocffi.surfaces.KeepAlive.instances) == 0 surface.set_mime_data('image/jpeg', b'lol') assert len(cairocffi.surfaces.KeepAlive.instances) == 1 assert surface.get_mime_data('image/jpeg')[:] == b'lol' surface.set_mime_data('image/jpeg', None) assert len(cairocffi.surfaces.KeepAlive.instances) == 0 if cairo_version() >= 11200: # This actually segfauts on cairo 1.10.x assert surface.get_mime_data('image/jpeg') is None surface.finish() assert_raise_finished(surface.set_mime_data, 'image/jpeg', None) @pytest.mark.xfail(cairo_version() < 11200, reason='Cairo version too low') def test_supports_mime_type(): # Also test we get actual booleans: assert PDFSurface(None, 1, 1).supports_mime_type('image/jpeg') is True surface = ImageSurface(cairocffi.FORMAT_A8, 1, 1) assert surface.supports_mime_type('image/jpeg') is False @pytest.mark.xfail(cairo_version() < 11400, reason='Cairo version too low') def test_device_scale(): surface = PDFSurface(None, 1, 1) assert surface.get_device_scale() == (1, 1) surface.set_device_scale(2, 3) assert surface.get_device_scale() == (2, 3) @pytest.mark.xfail(cairo_version() < 11504, reason='Cairo version too low') def test_metadata(): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) surface.set_metadata(PDF_METADATA_TITLE, 'title') surface.set_metadata(PDF_METADATA_SUBJECT, 'subject') surface.set_metadata(PDF_METADATA_CREATOR, 'creator') surface.set_metadata(PDF_METADATA_AUTHOR, 'author') surface.set_metadata(PDF_METADATA_KEYWORDS, 'keywords') surface.set_metadata(PDF_METADATA_CREATE_DATE, '2013-07-21T23:46:00+01:00') surface.set_metadata(PDF_METADATA_MOD_DATE, '2013-07-21T23:46:00Z') surface.finish() pdf_bytes = file_obj.getvalue() assert b'/Title (title)' in pdf_bytes assert b'/Subject (subject)' in pdf_bytes assert b'/Creator (creator)' in pdf_bytes assert b'/Author (author)' in pdf_bytes assert b'/Keywords (keywords)' in pdf_bytes assert b"/CreationDate (20130721234600+01'00)" in pdf_bytes assert b'/ModDate (20130721234600Z)' in pdf_bytes @pytest.mark.xfail(cairo_version() < 11504, reason='Cairo version too low') def test_outline(): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) outline = surface.add_outline( PDF_OUTLINE_ROOT, 'title 1', 'page=1 pos=[1 1]', PDF_OUTLINE_FLAG_OPEN & PDF_OUTLINE_FLAG_BOLD) surface.add_outline(outline, 'title 2', 'page=1 pos=[1 1]') surface.finish() pdf_bytes = file_obj.getvalue() assert b'/Title (title 1)' in pdf_bytes assert b'/Title (title 2)' in pdf_bytes @pytest.mark.xfail(cairo_version() < 11504, reason='Cairo version too low') def test_page_label(): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) surface.set_page_label('abc') surface.finish() pdf_bytes = file_obj.getvalue() assert b'/P (abc)' in pdf_bytes @pytest.mark.xfail(cairo_version() < 11504, reason='Cairo version too low') def test_tag(): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 10, 10) context = Context(surface) context.tag_begin('Document') context.tag_begin( TAG_LINK, attributes='rect=[1 2 4 5] uri=\'https://cairocffi.readthedocs.io/\'') context.set_source_rgba(1, 0, .5, 1) context.rectangle(2, 3, 4, 5) context.fill() context.tag_end(TAG_LINK) context.tag_end('Document') context.show_page() surface.finish() pdf_bytes = file_obj.getvalue() assert b'/URI (https://cairocffi.readthedocs.io/)' in pdf_bytes assert b'/S /Document' in pdf_bytes @pytest.mark.xfail(cairo_version() < 11504, reason='Cairo version too low') def test_thumbnail_size(): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) surface.set_thumbnail_size(1, 1) surface.finish() pdf_bytes1 = file_obj.getvalue() file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) surface.set_thumbnail_size(9, 9) surface.finish() pdf_bytes2 = file_obj.getvalue() assert len(pdf_bytes1) < len(pdf_bytes2) @pytest.mark.xfail(cairo_version() < 11510, reason='Cairo version too low') def test_document_unit(): surface = SVGSurface(None, 1, 2) assert surface.get_document_unit() == SVG_UNIT_PT file_obj = io.BytesIO() surface = SVGSurface(file_obj, 1, 2) surface.set_document_unit(SVG_UNIT_PX) assert surface.get_document_unit() == SVG_UNIT_PX surface.finish() pdf_bytes = file_obj.getvalue() assert b'width="1px"' in pdf_bytes assert b'height="2px"' in pdf_bytes file_obj = io.BytesIO() surface = SVGSurface(file_obj, 1, 2) surface.set_document_unit(SVG_UNIT_PC) assert surface.get_document_unit() == SVG_UNIT_PC surface.finish() pdf_bytes = file_obj.getvalue() assert b'width="1pc"' in pdf_bytes assert b'height="2pc"' in pdf_bytes def test_png(): png_bytes = base64.b64decode( b'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQI12O' b'w69x7BgAE3gJRgNit0AAAAABJRU5ErkJggg==') png_magic_number = png_bytes[:8] with temp_directory() as tempdir: filename = os.path.join(tempdir, 'foo.png') filename_bytes = filename.encode(sys.getfilesystemencoding()) surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) surface.write_to_png(filename) with open(filename, 'rb') as fd: written_png_bytes = fd.read() assert written_png_bytes.startswith(png_magic_number) open(filename, 'wb').close() with open(filename, 'rb') as fd: assert fd.read() == b'' surface.write_to_png(filename_bytes) with open(filename, 'rb') as fd: assert fd.read() == written_png_bytes file_obj = io.BytesIO() surface.write_to_png(file_obj) assert file_obj.getvalue() == written_png_bytes assert surface.write_to_png() == written_png_bytes with open(filename, 'wb') as fd: fd.write(png_bytes) for source in [io.BytesIO(png_bytes), filename, filename_bytes]: surface = ImageSurface.create_from_png(source) assert surface.get_format() == cairocffi.FORMAT_ARGB32 assert surface.get_width() == 1 assert surface.get_height() == 1 assert surface.get_stride() == 4 assert surface.get_data()[:] == pixel(b'\xcc\x32\x6e\x97') with pytest.raises(IOError): # Truncated input surface = ImageSurface.create_from_png(io.BytesIO(png_bytes[:30])) with pytest.raises(IOError): surface = ImageSurface.create_from_png(io.BytesIO(b'')) @pytest.mark.xfail(cairo_version() < 11000, reason='Cairo version too low') def test_pdf_versions(): assert set(PDFSurface.get_versions()) >= set([ cairocffi.PDF_VERSION_1_4, cairocffi.PDF_VERSION_1_5]) assert PDFSurface.version_to_string(cairocffi.PDF_VERSION_1_4) == 'PDF 1.4' with pytest.raises(TypeError): PDFSurface.version_to_string('PDF_VERSION_42') with pytest.raises(ValueError): PDFSurface.version_to_string(42) file_obj = io.BytesIO() PDFSurface(file_obj, 1, 1).finish() assert file_obj.getvalue().startswith(b'%PDF-1.5') file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) surface.restrict_to_version(cairocffi.PDF_VERSION_1_4) surface.finish() assert file_obj.getvalue().startswith(b'%PDF-1.4') def test_pdf_surface(): with temp_directory() as tempdir: filename = os.path.join(tempdir, 'foo.pdf') filename_bytes = filename.encode(sys.getfilesystemencoding()) file_obj = io.BytesIO() for target in [filename, filename_bytes, file_obj, None]: surface = PDFSurface(target, 123, 432) surface.finish() with open(filename, 'rb') as fd: assert fd.read().startswith(b'%PDF') with open(filename_bytes, 'rb') as fd: assert fd.read().startswith(b'%PDF') pdf_bytes = file_obj.getvalue() assert pdf_bytes.startswith(b'%PDF') assert b'/MediaBox [ 0 0 123 432 ]' in pdf_bytes assert pdf_bytes.count(b'/Type /Pages') == 1 assert pdf_bytes.count(b'/Type /Page') == 2 file_obj = io.BytesIO() surface = PDFSurface(file_obj, 1, 1) context = Context(surface) surface.set_size(12, 100) context.show_page() surface.set_size(42, 700) context.copy_page() surface.finish() pdf_bytes = file_obj.getvalue() assert b'/MediaBox [ 0 0 1 1 ]' not in pdf_bytes assert b'/MediaBox [ 0 0 12 100 ]' in pdf_bytes assert b'/MediaBox [ 0 0 42 700 ]' in pdf_bytes assert pdf_bytes.count(b'/Type /Pages') == 1 assert pdf_bytes.count(b'/Type /Page') == 3 def test_svg_surface(): assert set(SVGSurface.get_versions()) >= set([ cairocffi.SVG_VERSION_1_1, cairocffi.SVG_VERSION_1_2]) assert SVGSurface.version_to_string(cairocffi.SVG_VERSION_1_1) == 'SVG 1.1' with pytest.raises(TypeError): SVGSurface.version_to_string('SVG_VERSION_42') with pytest.raises(ValueError): SVGSurface.version_to_string(42) with temp_directory() as tempdir: filename = os.path.join(tempdir, 'foo.svg') filename_bytes = filename.encode(sys.getfilesystemencoding()) file_obj = io.BytesIO() for target in [filename, filename_bytes, file_obj, None]: SVGSurface(target, 123, 432).finish() with open(filename, 'rb') as fd: assert fd.read().startswith(b'= set([ cairocffi.PS_LEVEL_2, cairocffi.PS_LEVEL_3]) assert PSSurface.ps_level_to_string(cairocffi.PS_LEVEL_3) == 'PS Level 3' with pytest.raises(TypeError): PSSurface.ps_level_to_string('PS_LEVEL_42') with pytest.raises(ValueError): PSSurface.ps_level_to_string(42) with temp_directory() as tempdir: filename = os.path.join(tempdir, 'foo.ps') filename_bytes = filename.encode(sys.getfilesystemencoding()) file_obj = io.BytesIO() for target in [filename, filename_bytes, file_obj, None]: PSSurface(target, 123, 432).finish() with open(filename, 'rb') as fd: assert fd.read().startswith(b'%!PS') with open(filename_bytes, 'rb') as fd: assert fd.read().startswith(b'%!PS') assert file_obj.getvalue().startswith(b'%!PS') file_obj = io.BytesIO() surface = PSSurface(file_obj, 1, 1) surface.restrict_to_level(cairocffi.PS_LEVEL_2) # Not obvious to test assert surface.get_eps() is False surface.set_eps('lol') assert surface.get_eps() is True surface.set_eps('') assert surface.get_eps() is False surface.set_size(10, 12) surface.dsc_comment('%%Lorem') surface.dsc_begin_setup() surface.dsc_comment('%%ipsum') surface.dsc_begin_page_setup() surface.dsc_comment('%%dolor') surface.finish() ps_bytes = file_obj.getvalue() assert b'%%Lorem' in ps_bytes assert b'%%ipsum' in ps_bytes assert b'%%dolor' in ps_bytes @pytest.mark.xfail(cairo_version() < 11000, reason='Cairo version too low') def _recording_surface_common(extents): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 100) empty_pixels = surface.get_data()[:] assert empty_pixels == b'\x00' * 40000 surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 100) context = Context(surface) context.move_to(20, 50) context.show_text('Something about us.') text_pixels = surface.get_data()[:] assert text_pixels != empty_pixels recording_surface = RecordingSurface(cairocffi.CONTENT_COLOR_ALPHA, extents) context = Context(recording_surface) context.move_to(20, 50) assert recording_surface.ink_extents() == (0, 0, 0, 0) context.show_text('Something about us.') recording_surface.flush() assert recording_surface.ink_extents() != (0, 0, 0, 0) surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 100) context = Context(surface) context.set_source_surface(recording_surface) context.paint() recorded_pixels = surface.get_data()[:] return text_pixels, recorded_pixels def test_recording_surface(): text_pixels, recorded_pixels = _recording_surface_common((0, 0, 140, 80)) assert recorded_pixels == text_pixels @pytest.mark.xfail(cairo_version() < 11200, reason='Cairo version too low') def test_unbounded_recording_surface(): text_pixels, recorded_pixels = _recording_surface_common(None) assert recorded_pixels == text_pixels @pytest.mark.xfail(cairo_version() < 11200, reason='Cairo version too low') def test_recording_surface_get_extents(): for extents in [None, (0, 0, 140, 80)]: surface = RecordingSurface(cairocffi.CONTENT_COLOR_ALPHA, extents) assert surface.get_extents() == extents def test_matrix(): m = Matrix() with pytest.raises(AttributeError): m.some_inexistent_attribute assert m.as_tuple() == (1, 0, 0, 1, 0, 0) m.translate(12, 4) assert m.as_tuple() == (1, 0, 0, 1, 12, 4) m.scale(2, 7) assert m.as_tuple() == (2, 0, 0, 7, 12, 4) assert m[3] == 7 assert m.yy == 7 m.yy = 3 assert m.as_tuple() == (2, 0, 0, 3, 12, 4) assert repr(m) == 'Matrix(2, 0, 0, 3, 12, 4)' assert str(m) == 'Matrix(2, 0, 0, 3, 12, 4)' assert m.transform_distance(1, 2) == (2, 6) assert m.transform_point(1, 2) == (14, 10) m2 = m.copy() assert m2 == m m2.invert() assert m2.as_tuple() == (0.5, 0, 0, 1./3, -12 / 2, -4. / 3) assert m.inverted() == m2 assert m.as_tuple() == (2, 0, 0, 3, 12, 4) # Unchanged m2 = Matrix(*m) assert m2 == m m2.invert() assert m2.as_tuple() == (0.5, 0, 0, 1./3, -12 / 2, -4. / 3) assert m.inverted() == m2 assert m.as_tuple() == (2, 0, 0, 3, 12, 4) # Still unchanged m.rotate(math.pi / 2) assert round_tuple(m.as_tuple()) == (0, 3, -2, 0, 12, 4) m *= Matrix.init_rotate(math.pi) assert round_tuple(m.as_tuple()) == (0, -3, 2, 0, -12, -4) def test_surface_pattern(): surface = ImageSurface(cairocffi.FORMAT_A1, 1, 1) pattern = SurfacePattern(surface) surface_again = pattern.get_surface() assert surface_again is not surface assert surface_again._pointer == surface._pointer assert pattern.get_extend() == cairocffi.EXTEND_NONE pattern.set_extend(cairocffi.EXTEND_REPEAT) assert pattern.get_extend() == cairocffi.EXTEND_REPEAT assert pattern.get_filter() == cairocffi.FILTER_GOOD pattern.set_filter(cairocffi.FILTER_BEST) assert pattern.get_filter() == cairocffi.FILTER_BEST assert pattern.get_matrix() == Matrix() # identity matrix = Matrix.init_rotate(0.5) pattern.set_matrix(matrix) assert pattern.get_matrix() == matrix assert pattern.get_matrix() != Matrix() def test_solid_pattern(): assert SolidPattern(1, .5, .25).get_rgba() == (1, .5, .25, 1) assert SolidPattern(1, .5, .25, .75).get_rgba() == (1, .5, .25, .75) surface = PDFSurface(None, 1, 1) context = Context(surface) pattern = SolidPattern(1, .5, .25) context.set_source(pattern) assert isinstance(context.get_source(), SolidPattern) pattern_map = cairocffi.patterns.PATTERN_TYPE_TO_CLASS try: del pattern_map[cairocffi.PATTERN_TYPE_SOLID] re_pattern = context.get_source() assert re_pattern._pointer == pattern._pointer assert isinstance(re_pattern, Pattern) assert not isinstance(re_pattern, SolidPattern) finally: pattern_map[cairocffi.PATTERN_TYPE_SOLID] = SolidPattern def pdf_with_pattern(pattern=None): file_obj = io.BytesIO() surface = PDFSurface(file_obj, 100, 100) context = Context(surface) if pattern is not None: context.set_source(pattern) context.paint() surface.finish() return file_obj.getvalue() def test_linear_gradient(): gradient = LinearGradient(1, 2, 10, 20) assert gradient.get_linear_points() == (1, 2, 10, 20) gradient.add_color_stop_rgb(1, 1, .5, .25) gradient.add_color_stop_rgb(offset=.5, red=1, green=.5, blue=.25) gradient.add_color_stop_rgba(.5, 1, .5, .75, .25) assert gradient.get_color_stops() == [ (.5, 1, .5, .25, 1), (.5, 1, .5, .75, .25), (1, 1, .5, .25, 1)] # Values chosen so that we can test get_data() bellow with an exact # byte string that (hopefully) does not depend on rounding behavior: # 255 / 5. == 51.0 == 0x33 surface = ImageSurface(cairocffi.FORMAT_A8, 8, 4) assert surface.get_data()[:] == b'\x00' * 32 gradient = LinearGradient(1.5, 0, 6.5, 0) gradient.add_color_stop_rgba(0, 0, 0, 0, 0) gradient.add_color_stop_rgba(1, 0, 0, 0, 1) context = Context(surface) context.set_source(gradient) context.paint() assert surface.get_data()[:] == b'\x00\x00\x33\x66\x99\xCC\xFF\xFF' * 4 assert b'/ShadingType 2' not in pdf_with_pattern() assert b'/ShadingType 2' in pdf_with_pattern(gradient) def test_radial_gradient(): gradient = RadialGradient(42, 420, 10, 43, 430, 100) assert gradient.get_radial_circles() == (42, 420, 10, 43, 430, 100) gradient.add_color_stop_rgb(1, 1, .5, .25) gradient.add_color_stop_rgb(offset=.5, red=1, green=.5, blue=.25) gradient.add_color_stop_rgba(.5, 1, .5, .75, .25) assert gradient.get_color_stops() == [ (.5, 1, .5, .25, 1), (.5, 1, .5, .75, .25), (1, 1, .5, .25, 1)] assert b'/ShadingType 3' not in pdf_with_pattern() assert b'/ShadingType 3' in pdf_with_pattern(gradient) def test_context_as_context_manager(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) context = Context(surface) # The default source is opaque black: assert context.get_source().get_rgba() == (0, 0, 0, 1) with context: context.set_source_rgb(1, .25, .5) assert context.get_source().get_rgba() == (1, .25, .5, 1) # Context restored at the end of with statement. assert context.get_source().get_rgba() == (0, 0, 0, 1) try: with context: context.set_source_rgba(1, .25, .75, .5) assert context.get_source().get_rgba() == (1, .25, .75, .5) raise ValueError except ValueError: pass # Context also restored on exceptions. assert context.get_source().get_rgba() == (0, 0, 0, 1) def test_context_groups(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) context = Context(surface) assert isinstance(context.get_target(), ImageSurface) assert context.get_target()._pointer == surface._pointer assert context.get_group_target()._pointer == surface._pointer assert (context.get_group_target().get_content() == cairocffi.CONTENT_COLOR_ALPHA) assert surface.get_data()[:] == pixel(b'\x00\x00\x00\x00') with context: context.push_group_with_content(cairocffi.CONTENT_ALPHA) assert (context.get_group_target().get_content() == cairocffi.CONTENT_ALPHA) context.set_source_rgba(1, .2, .4, .8) # Only A is actually used assert isinstance(context.get_source(), SolidPattern) context.paint() context.pop_group_to_source() assert isinstance(context.get_source(), SurfacePattern) # Still nothing on the original surface assert surface.get_data()[:] == pixel(b'\x00\x00\x00\x00') context.paint() assert surface.get_data()[:] == pixel(b'\xCC\x00\x00\x00') with context: context.push_group() context.set_source_rgba(1, .2, .4) context.paint() group = context.pop_group() assert isinstance(context.get_source(), SolidPattern) assert isinstance(group, SurfacePattern) context.set_source_surface(group.get_surface()) assert surface.get_data()[:] == pixel(b'\xCC\x00\x00\x00') context.paint() assert surface.get_data()[:] == pixel(b'\xFF\xFF\x33\x66') def test_context_current_transform_matrix(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) context = Context(surface) assert isinstance(context.get_matrix(), Matrix) assert context.get_matrix().as_tuple() == (1, 0, 0, 1, 0, 0) context.translate(6, 5) assert context.get_matrix().as_tuple() == (1, 0, 0, 1, 6, 5) context.scale(1, 6) assert context.get_matrix().as_tuple() == (1, 0, 0, 6, 6, 5) context.scale(.5) assert context.get_matrix().as_tuple() == (.5, 0, 0, 3, 6, 5) context.rotate(math.pi / 2) assert round_tuple(context.get_matrix().as_tuple()) == (0, 3, -.5, 0, 6, 5) context.identity_matrix() assert context.get_matrix().as_tuple() == (1, 0, 0, 1, 0, 0) context.set_matrix(Matrix(2, 1, 3, 7, 8, 2)) assert context.get_matrix().as_tuple() == (2, 1, 3, 7, 8, 2) context.transform(Matrix(2, 0, 0, .5, 0, 0)) assert context.get_matrix().as_tuple() == (4, 2, 1.5, 3.5, 8, 2) context.set_matrix(Matrix(2, 0, 0, 3, 12, 4)) assert context.user_to_device_distance(1, 2) == (2, 6) assert context.user_to_device(1, 2) == (14, 10) assert context.device_to_user_distance(2, 6) == (1, 2) assert round_tuple(context.device_to_user(14, 10)) == (1, 2) def test_context_path(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) context = Context(surface) assert context.copy_path() == [] assert context.has_current_point() is False assert context.get_current_point() == (0, 0) context.arc(100, 200, 20, math.pi/2, 0) path_1 = context.copy_path() assert path_1[0] == (cairocffi.PATH_MOVE_TO, (100, 220)) assert len(path_1) > 1 assert all(part[0] == cairocffi.PATH_CURVE_TO for part in path_1[1:]) assert context.has_current_point() is True assert context.get_current_point() == (120, 200) context.new_sub_path() assert context.copy_path() == path_1 assert context.has_current_point() is False assert context.get_current_point() == (0, 0) context.new_path() assert context.copy_path() == [] assert context.has_current_point() is False assert context.get_current_point() == (0, 0) context.arc_negative(100, 200, 20, math.pi/2, 0) path_2 = context.copy_path() assert path_2[0] == (cairocffi.PATH_MOVE_TO, (100, 220)) assert len(path_2) > 1 assert all(part[0] == cairocffi.PATH_CURVE_TO for part in path_2[1:]) assert path_2 != path_1 context.new_path() context.rectangle(10, 20, 100, 200) path = context.copy_path() # Some cairo versions add a MOVE_TO after a CLOSE_PATH if path[-1] == (cairocffi.PATH_MOVE_TO, (10, 20)): # pragma: no cover path = path[:-1] assert path == [ (cairocffi.PATH_MOVE_TO, (10, 20)), (cairocffi.PATH_LINE_TO, (110, 20)), (cairocffi.PATH_LINE_TO, (110, 220)), (cairocffi.PATH_LINE_TO, (10, 220)), (cairocffi.PATH_CLOSE_PATH, ())] assert context.path_extents() == (10, 20, 110, 220) context.new_path() context.move_to(10, 20) context.line_to(10, 30) context.rel_move_to(2, 5) context.rel_line_to(2, 5) context.curve_to(20, 30, 70, 50, 100, 120) context.rel_curve_to(20, 30, 70, 50, 100, 120) context.close_path() path = context.copy_path() if path[-1] == (cairocffi.PATH_MOVE_TO, (12, 35)): # pragma: no cover path = path[:-1] assert path == [ (cairocffi.PATH_MOVE_TO, (10, 20)), (cairocffi.PATH_LINE_TO, (10, 30)), (cairocffi.PATH_MOVE_TO, (12, 35)), (cairocffi.PATH_LINE_TO, (14, 40)), (cairocffi.PATH_CURVE_TO, (20, 30, 70, 50, 100, 120)), (cairocffi.PATH_CURVE_TO, (120, 150, 170, 170, 200, 240)), (cairocffi.PATH_CLOSE_PATH, ())] context.new_path() context.move_to(10, 15) context.curve_to(20, 30, 70, 50, 100, 120) assert context.copy_path() == [ (cairocffi.PATH_MOVE_TO, (10, 15)), (cairocffi.PATH_CURVE_TO, (20, 30, 70, 50, 100, 120))] path = context.copy_path_flat() assert len(path) > 2 assert path[0] == (cairocffi.PATH_MOVE_TO, (10, 15)) assert all(part[0] == cairocffi.PATH_LINE_TO for part in path[1:]) assert path[-1] == (cairocffi.PATH_LINE_TO, (100, 120)) context.new_path() context.move_to(10, 20) context.line_to(10, 30) path = context.copy_path() assert path == [ (cairocffi.PATH_MOVE_TO, (10, 20)), (cairocffi.PATH_LINE_TO, (10, 30))] additional_path = [(cairocffi.PATH_LINE_TO, (30, 150))] context.append_path(additional_path) assert context.copy_path() == path + additional_path # Incorrect number of points: with pytest.raises(ValueError): context.append_path([(cairocffi.PATH_LINE_TO, (30, 150, 1))]) with pytest.raises(ValueError): context.append_path([(cairocffi.PATH_LINE_TO, (30, 150, 1, 4))]) def test_context_properties(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 1, 1) context = Context(surface) assert context.get_antialias() == cairocffi.ANTIALIAS_DEFAULT context.set_antialias(cairocffi.ANTIALIAS_BEST) assert context.get_antialias() == cairocffi.ANTIALIAS_BEST assert context.get_dash() == ([], 0) context.set_dash([4, 1, 3, 2], 1.5) assert context.get_dash() == ([4, 1, 3, 2], 1.5) assert context.get_dash_count() == 4 assert context.get_fill_rule() == cairocffi.FILL_RULE_WINDING context.set_fill_rule(cairocffi.FILL_RULE_EVEN_ODD) assert context.get_fill_rule() == cairocffi.FILL_RULE_EVEN_ODD assert context.get_line_cap() == cairocffi.LINE_CAP_BUTT context.set_line_cap(cairocffi.LINE_CAP_SQUARE) assert context.get_line_cap() == cairocffi.LINE_CAP_SQUARE assert context.get_line_join() == cairocffi.LINE_JOIN_MITER context.set_line_join(cairocffi.LINE_JOIN_ROUND) assert context.get_line_join() == cairocffi.LINE_JOIN_ROUND assert context.get_line_width() == 2 context.set_line_width(13) assert context.get_line_width() == 13 assert context.get_miter_limit() == 10 context.set_miter_limit(4) assert context.get_miter_limit() == 4 assert context.get_operator() == cairocffi.OPERATOR_OVER context.set_operator(cairocffi.OPERATOR_XOR) assert context.get_operator() == cairocffi.OPERATOR_XOR assert context.get_tolerance() == 0.1 context.set_tolerance(0.25) assert context.get_tolerance() == 0.25 def test_context_fill(): surface = ImageSurface(cairocffi.FORMAT_A8, 4, 4) assert surface.get_data()[:] == b'\x00' * 16 context = Context(surface) context.set_source_rgba(0, 0, 0, .5) context.set_line_width(.5) context.rectangle(1, 1, 2, 2) assert context.fill_extents() == (1, 1, 3, 3) assert context.stroke_extents() == (.75, .75, 3.25, 3.25) assert context.in_fill(2, 2) is True assert context.in_fill(.8, 2) is False assert context.in_stroke(2, 2) is False assert context.in_stroke(.8, 2) is True path = list(context.copy_path()) assert path context.fill_preserve() assert list(context.copy_path()) == path assert surface.get_data()[:] == ( b'\x00\x00\x00\x00' b'\x00\x80\x80\x00' b'\x00\x80\x80\x00' b'\x00\x00\x00\x00' ) context.fill() assert list(context.copy_path()) == [] assert surface.get_data()[:] == ( b'\x00\x00\x00\x00' b'\x00\xC0\xC0\x00' b'\x00\xC0\xC0\x00' b'\x00\x00\x00\x00' ) def test_context_stroke(): for preserve in [True, False]: surface = ImageSurface(cairocffi.FORMAT_A8, 4, 4) assert surface.get_data()[:] == b'\x00' * 16 context = Context(surface) context.set_source_rgba(0, 0, 0, 1) context.set_line_width(1) context.rectangle(.5, .5, 2, 2) path = list(context.copy_path()) assert path context.stroke_preserve() if preserve else context.stroke() assert list(context.copy_path()) == (path if preserve else []) assert surface.get_data()[:] == ( b'\xFF\xFF\xFF\x00' b'\xFF\x00\xFF\x00' b'\xFF\xFF\xFF\x00' b'\x00\x00\x00\x00') def test_context_clip(): surface = ImageSurface(cairocffi.FORMAT_A8, 4, 4) assert surface.get_data()[:] == b'\x00' * 16 context = Context(surface) context.rectangle(1, 1, 2, 2) assert context.clip_extents() == (0, 0, 4, 4) path = list(context.copy_path()) assert path context.clip_preserve() assert list(context.copy_path()) == path assert context.clip_extents() == (1, 1, 3, 3) context.clip() assert list(context.copy_path()) == [] assert context.clip_extents() == (1, 1, 3, 3) context.reset_clip() assert context.clip_extents() == (0, 0, 4, 4) context.rectangle(1, 1, 2, 2) context.rectangle(1, 2, 1, 2) context.clip() assert context.copy_clip_rectangle_list() == [(1, 1, 2, 2), (1, 3, 1, 1)] assert context.clip_extents() == (1, 1, 3, 4) @pytest.mark.xfail(cairo_version() < 11000, reason='Cairo version too low') def test_context_in_clip(): surface = ImageSurface(cairocffi.FORMAT_A8, 4, 4) context = Context(surface) context.rectangle(1, 1, 2, 2) assert context.in_clip(.5, 2) is True assert context.in_clip(1.5, 2) is True context.clip() assert context.in_clip(.5, 2) is False assert context.in_clip(1.5, 2) is True def test_context_mask(): mask_surface = ImageSurface(cairocffi.FORMAT_ARGB32, 2, 2) context = Context(mask_surface) context.set_source_rgba(1, 0, .5, 1) context.rectangle(0, 0, 1, 1) context.fill() context.set_source_rgba(1, .5, 1, .5) context.rectangle(1, 1, 1, 1) context.fill() surface = ImageSurface(cairocffi.FORMAT_ARGB32, 4, 4) context = Context(surface) context.mask(SurfacePattern(mask_surface)) o = pixel(b'\x00\x00\x00\x00') b = pixel(b'\x80\x00\x00\x00') B = pixel(b'\xFF\x00\x00\x00') assert surface.get_data()[:] == ( B + o + o + o + o + b + o + o + o + o + o + o + o + o + o + o ) surface = ImageSurface(cairocffi.FORMAT_ARGB32, 4, 4) context = Context(surface) context.mask_surface(mask_surface, surface_x=1, surface_y=2) o = pixel(b'\x00\x00\x00\x00') b = pixel(b'\x80\x00\x00\x00') B = pixel(b'\xFF\x00\x00\x00') assert surface.get_data()[:] == ( o + o + o + o + o + o + o + o + o + B + o + o + o + o + b + o ) def test_context_font(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 10, 10) context = Context._from_pointer(Context(surface)._pointer, incref=True) assert context.get_font_matrix().as_tuple() == (10, 0, 0, 10, 0, 0) context.set_font_matrix(Matrix(2, 0, 0, 3, 12, 4)) assert context.get_font_matrix().as_tuple() == (2, 0, 0, 3, 12, 4) context.set_font_size(14) assert context.get_font_matrix().as_tuple() == (14, 0, 0, 14, 0, 0) context.set_font_size(10) context.select_font_face(b'@cairo:serif', cairocffi.FONT_SLANT_ITALIC) font_face = context.get_font_face() assert isinstance(font_face, ToyFontFace) assert font_face.get_family() == '@cairo:serif' assert font_face.get_slant() == cairocffi.FONT_SLANT_ITALIC assert font_face.get_weight() == cairocffi.FONT_WEIGHT_NORMAL try: del cairocffi.fonts.FONT_TYPE_TO_CLASS[cairocffi.FONT_TYPE_TOY] re_font_face = context.get_font_face() assert re_font_face._pointer == font_face._pointer assert isinstance(re_font_face, FontFace) assert not isinstance(re_font_face, ToyFontFace) finally: cairocffi.fonts.FONT_TYPE_TO_CLASS[cairocffi.FONT_TYPE_TOY] = \ ToyFontFace ascent, descent, height, max_x_advance, max_y_advance = ( context.font_extents()) # That’s about all we can assume for a default font. assert max_x_advance > 0 assert max_y_advance == 0 _, _, _, _, x_advance, y_advance = context.text_extents('i' * 10) assert x_advance > 0 assert y_advance == 0 context.set_font_face( ToyFontFace('@cairo:monospace', weight=cairocffi.FONT_WEIGHT_BOLD)) _, _, _, _, x_advance_mono, y_advance = context.text_extents('i' * 10) assert x_advance_mono > x_advance assert y_advance == 0 assert list(context.copy_path()) == [] context.text_path('a') assert list(context.copy_path()) assert surface.get_data()[:] == b'\x00' * 400 context.move_to(1, 9) context.show_text('a') assert surface.get_data()[:] != b'\x00' * 400 assert (context.get_font_options().get_hint_metrics() == cairocffi.HINT_METRICS_DEFAULT) context.set_font_options( FontOptions(hint_metrics=cairocffi.HINT_METRICS_ON)) assert (context.get_font_options().get_hint_metrics() == cairocffi.HINT_METRICS_ON) assert (surface.get_font_options().get_hint_metrics() == cairocffi.HINT_METRICS_ON) context.set_font_matrix(Matrix(2, 0, 0, 3, 12, 4)) assert context.get_scaled_font().get_font_matrix().as_tuple() == ( 2, 0, 0, 3, 12, 4) context.set_scaled_font(ScaledFont(ToyFontFace(), font_matrix=Matrix( 0, 1, 4, 0, 12, 4))) assert context.get_font_matrix().as_tuple() == (0, 1, 4, 0, 12, 4) # Reset the default context.set_font_face(None) # TODO: test this somehow. def test_scaled_font(): font = ScaledFont(ToyFontFace()) font_extents = font.extents() ascent, descent, height, max_x_advance, max_y_advance = font_extents assert max_x_advance > 0 assert max_y_advance == 0 _, _, _, _, x_advance, y_advance = font.text_extents('i' * 10) assert x_advance > 0 assert y_advance == 0 font = ScaledFont(ToyFontFace('@cairo:serif')) _, _, _, _, x_advance, y_advance = font.text_extents('i' * 10) font = ScaledFont(ToyFontFace('@cairo:monospace')) _, _, _, _, x_advance_mono, y_advance = font.text_extents('i' * 10) assert x_advance_mono > x_advance assert y_advance == 0 # Not much we can test: # The toy font face was "materialized" into a specific backend. assert isinstance(font.get_font_face(), FontFace) font = ScaledFont( ToyFontFace('@cairo:monospace'), Matrix(xx=20, yy=20), Matrix(xx=3, yy=.5), FontOptions(antialias=cairocffi.ANTIALIAS_BEST)) assert font.get_font_options().get_antialias() == cairocffi.ANTIALIAS_BEST assert font.get_font_matrix().as_tuple() == (20, 0, 0, 20, 0, 0) assert font.get_ctm().as_tuple() == (3, 0, 0, .5, 0, 0) assert font.get_scale_matrix().as_tuple() == (60, 0, 0, 10, 0, 0) _, _, _, _, x_advance_mono_2, y_advance_2 = font.text_extents('i' * 10) # Same yy as before: assert y_advance == y_advance_2 # Bigger xx: assert x_advance_mono_2 > x_advance_mono def test_font_options(): options = FontOptions() assert options.get_antialias() == cairocffi.ANTIALIAS_DEFAULT options.set_antialias(cairocffi.ANTIALIAS_FAST) assert options.get_antialias() == cairocffi.ANTIALIAS_FAST assert options.get_subpixel_order() == cairocffi.SUBPIXEL_ORDER_DEFAULT options.set_subpixel_order(cairocffi.SUBPIXEL_ORDER_BGR) assert options.get_subpixel_order() == cairocffi.SUBPIXEL_ORDER_BGR assert options.get_hint_style() == cairocffi.HINT_STYLE_DEFAULT options.set_hint_style(cairocffi.HINT_STYLE_SLIGHT) assert options.get_hint_style() == cairocffi.HINT_STYLE_SLIGHT assert options.get_hint_metrics() == cairocffi.HINT_METRICS_DEFAULT options.set_hint_metrics(cairocffi.HINT_METRICS_OFF) assert options.get_hint_metrics() == cairocffi.HINT_METRICS_OFF options_1 = FontOptions(hint_metrics=cairocffi.HINT_METRICS_ON) assert options_1.get_hint_metrics() == cairocffi.HINT_METRICS_ON assert options_1.get_antialias() == cairocffi.HINT_METRICS_DEFAULT options_2 = options_1.copy() assert options_2 == options_1 assert len(set([options_1, options_2])) == 1 # test __hash__ options_2.set_antialias(cairocffi.ANTIALIAS_BEST) assert options_2 != options_1 assert len(set([options_1, options_2])) == 2 options_1.merge(options_2) assert options_2 == options_1 @pytest.mark.xfail(cairo_version() < 11512, reason='Cairo version too low') def test_font_options_variations(): options = FontOptions() assert options.get_variations() is None options.set_variations('wght 400, wdth 300') assert options.get_variations() == 'wght 400, wdth 300' options.set_variations(None) assert options.get_variations() is None def test_glyphs(): surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 20) context = Context(surface) font = context.get_scaled_font() text = 'Étt' glyphs, clusters, is_backwards = font.text_to_glyphs( 5, 15, text, with_clusters=True) assert font.text_to_glyphs(5, 15, text, with_clusters=False) == glyphs (idx1, x1, y1), (idx2, x2, y2), (idx3, x3, y3) = glyphs assert idx1 != idx2 == idx3 assert y1 == y2 == y3 == 15 assert 5 == x1 < x2 < x3 assert clusters == [(2, 1), (1, 1), (1, 1)] assert is_backwards == 0 assert round_tuple(font.glyph_extents(glyphs)) == ( round_tuple(font.text_extents(text))) assert round_tuple(font.glyph_extents(glyphs)) == ( round_tuple(context.glyph_extents(glyphs))) assert context.copy_path() == [] context.glyph_path(glyphs) glyph_path = context.copy_path() assert glyph_path context.new_path() assert context.copy_path() == [] context.move_to(10, 20) # Not the same coordinates as text_to_glyphs context.text_path(text) assert context.copy_path() != [] assert context.copy_path() != glyph_path context.new_path() assert context.copy_path() == [] context.move_to(5, 15) context.text_path(text) text_path = context.copy_path() # For some reason, paths end with a different on old cairo. assert text_path[:-1] == glyph_path[:-1] empty = b'\x00' * 100 * 20 * 4 assert surface.get_data()[:] == empty context.show_glyphs(glyphs) glyph_pixels = surface.get_data()[:] assert glyph_pixels != empty surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 20) context = Context(surface) context.move_to(5, 15) context.show_text_glyphs(text, glyphs, clusters, is_backwards) text_glyphs_pixels = surface.get_data()[:] assert glyph_pixels == text_glyphs_pixels surface = ImageSurface(cairocffi.FORMAT_ARGB32, 100, 20) context = Context(surface) context.move_to(5, 15) context.show_text(text) text_pixels = surface.get_data()[:] assert glyph_pixels == text_pixels def test_from_null_pointer(): for class_ in [Surface, Context, Pattern, FontFace, ScaledFont]: with pytest.raises(ValueError): class_._from_pointer(cairocffi.ffi.NULL, 'unused') cairocffi-1.2.0/cairocffi/test_numpy.py000066400000000000000000000006251374663167600201730ustar00rootroot00000000000000import math import cairocffi as cairo import numpy def test_numpy(): data = numpy.zeros((200, 200, 4), dtype=numpy.uint8) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200, data=data) cr = cairo.Context(surface) cr.set_source_rgb(1.0, 1.0, 1.0) cr.paint() cr.arc(100, 100, 80, 0, 2*math.pi) cr.set_line_width(3) cr.set_source_rgb(1.0, 0.0, 0.0) cr.stroke() cairocffi-1.2.0/cairocffi/test_pixbuf.py000066400000000000000000000045361374663167600203250ustar00rootroot00000000000000""" cairocffi.test_pixbuf ~~~~~~~~~~~~~~~~~~~~~ Test suite for cairocffi.pixbuf. :copyright: Copyright 2013-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import base64 import sys import zlib import pytest from . import constants, pixbuf PNG_BYTES = base64.b64decode( b'iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAAAE0lEQV' b'QI12NkaPjfwAAFTAxIAAAuNwIDqJbDRgAAAABJRU5ErkJggg==') JPEG_BYTES = zlib.decompress(base64.b64decode( b'eJylzb0JgFAMBOA704hYvIC9oygIou7nPFq4g3+Nm0RT+iy9VPkIF9vsQhjavgVJdM/ATjS' b'+/YqX/O2gzdAUCUSoSJSitAUFiHdS1xArXBlr5qrf2wO58HkiigrlWK+T7TezChqU')) def test_api(): with pytest.raises(pixbuf.ImageLoadingError): pixbuf.decode_to_image_surface(b'') with pytest.raises(pixbuf.ImageLoadingError): pixbuf.decode_to_image_surface(b'Not a valid image.') with pytest.raises(pixbuf.ImageLoadingError): pixbuf.decode_to_image_surface(PNG_BYTES[:10]) surface, format_name = pixbuf.decode_to_image_surface(PNG_BYTES) assert format_name == 'png' assert_decoded(surface) def test_gdk(): if pixbuf.gdk is None: pytest.xfail() pixbuf_obj, format_name = pixbuf.decode_to_pixbuf(PNG_BYTES) assert format_name == 'png' assert_decoded(pixbuf.pixbuf_to_cairo_gdk(pixbuf_obj)) def test_slices(): pixbuf_obj, format_name = pixbuf.decode_to_pixbuf(PNG_BYTES) assert format_name == 'png' assert_decoded(pixbuf.pixbuf_to_cairo_png(pixbuf_obj)) def test_size(): pixbuf_obj, format_name = pixbuf.decode_to_pixbuf(PNG_BYTES, 10, 10) assert format_name == 'png' surface = pixbuf.pixbuf_to_cairo_png(pixbuf_obj) assert surface.get_width() == 10 assert surface.get_height() == 10 assert surface.get_format() == constants.FORMAT_ARGB32 def test_png(): pixbuf_obj, format_name = pixbuf.decode_to_pixbuf(JPEG_BYTES) assert format_name == 'jpeg' assert_decoded(pixbuf.pixbuf_to_cairo_slices(pixbuf_obj), constants.FORMAT_RGB24, b'\xff\x00\x80\xff') def assert_decoded(surface, format_=constants.FORMAT_ARGB32, rgba=b'\x80\x00\x40\x80'): assert surface.get_width() == 3 assert surface.get_height() == 2 assert surface.get_format() == format_ if sys.byteorder == 'little': # pragma: no cover rgba = rgba[::-1] assert surface.get_data()[:] == rgba * 6 cairocffi-1.2.0/cairocffi/test_xcb.py000066400000000000000000000143021374663167600175740ustar00rootroot00000000000000""" cairocffi.test_xcb ~~~~~~~~~~~~~~~~~~ Test suite for cairocffi.xcb. :copyright: Copyright 2014-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ import os import time import pytest xcffib = pytest.importorskip('xcffib') # noqa import xcffib.xproto # noqa isort:skip from xcffib.xproto import ConfigWindow, CW, EventMask, GC # noqa isort:skip from . import Context, XCBSurface, cairo_version # noqa isort:skip @pytest.fixture def xcb_conn(): """ Fixture that will setup and take down a xcffib.Connection object running on a display spawned by xvfb """ display = os.environ.get('DISPLAY') if display is None: # pragma: no cover pytest.skip('DISPLAY environment variable not set') conn = xcffib.connect(display) yield conn conn.disconnect() def find_root_visual(conn): """Find the xcffib.xproto.VISUALTYPE corresponding to the root visual""" default_screen = conn.setup.roots[conn.pref_screen] for i in default_screen.allowed_depths: for v in i.visuals: if v.visual_id == default_screen.root_visual: return v def create_window(conn, width, height): """Creates a window of the given dimensions and returns the XID""" wid = conn.generate_id() default_screen = conn.setup.roots[conn.pref_screen] conn.core.CreateWindow( default_screen.root_depth, # depth wid, # id default_screen.root, # parent 0, 0, width, height, 0, # x, y, w, h, border width xcffib.xproto.WindowClass.InputOutput, # window class default_screen.root_visual, # visual CW.BackPixel | CW.EventMask, # value mask [ # value list default_screen.black_pixel, EventMask.Exposure | EventMask.StructureNotify ] ) return wid def create_pixmap(conn, wid, width, height): """Creates a window of the given dimensions and returns the XID""" pixmap = conn.generate_id() default_screen = conn.setup.roots[conn.pref_screen] conn.core.CreatePixmap( default_screen.root_depth, # depth pixmap, wid, # pixmap id, drawable id (window) width, height ) return pixmap def create_gc(conn): """Creates a simple graphics context""" gc = conn.generate_id() default_screen = conn.setup.roots[conn.pref_screen] conn.core.CreateGC( gc, default_screen.root, # gc id, drawable GC.Foreground | GC.Background, # value mask [ # value list default_screen.black_pixel, default_screen.white_pixel ] ) return gc @pytest.mark.xfail(cairo_version() < 11200, reason="Cairo version too low") def test_xcb_pixmap(xcb_conn): width = 10 height = 10 # create a new window wid = create_window(xcb_conn, width, height) # create the pixmap used to draw with cairo pixmap = create_pixmap(xcb_conn, wid, width, height) # create graphics context to copy pixmap on window gc = create_gc(xcb_conn) # create XCB surface on pixmap root_visual = find_root_visual(xcb_conn) surface = XCBSurface(xcb_conn, pixmap, root_visual, width, height) assert surface # use xcb surface to create context, draw white ctx = Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() # map the window and wait for it to appear xcb_conn.core.MapWindow(wid) xcb_conn.flush() start = time.time() while time.time() < start + 10: event = xcb_conn.wait_for_event() if isinstance(event, xcffib.xproto.ExposeEvent): break else: pytest.fail("Never received ExposeEvent") # copy the pixmap to the window xcb_conn.core.CopyArea( pixmap, # source wid, # dest gc, # gc 0, 0, # source x, source y 0, 0, # dest x, dest y width, height ) ctx = None surface = None xcb_conn.core.FreeGC(gc) xcb_conn.core.FreePixmap(pixmap) # flush the connection, make sure no errors were thrown xcb_conn.flush() while event: event = xcb_conn.poll_for_event() @pytest.mark.xfail(cairo_version() < 11200, reason="Cairo version too low") def test_xcb_window(xcb_conn): width = 10 height = 10 # create a new window used to draw with cairo wid = create_window(xcb_conn, width, height) # map the window and wait for it to appear xcb_conn.core.MapWindow(wid) xcb_conn.flush() start = time.time() while time.time() < start + 10: event = xcb_conn.wait_for_event() if isinstance(event, xcffib.xproto.ExposeEvent): break else: pytest.fail("Never received ExposeEvent") # create XCB surface on window root_visual = find_root_visual(xcb_conn) surface = XCBSurface(xcb_conn, wid, root_visual, width, height) assert surface # use xcb surface to create context, draw white ctx = Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() xcb_conn.flush() # now move the window and change its size xcb_conn.core.ConfigureWindow( wid, (ConfigWindow.X | ConfigWindow.Y | ConfigWindow.Width | ConfigWindow.Height), [ 5, 5, # x, y width * 2, height * 2 # width, height ] ) xcb_conn.flush() # wait for the notification of the size change start = time.time() while time.time() < start + 10: event = xcb_conn.wait_for_event() if isinstance(event, xcffib.xproto.ConfigureNotifyEvent): assert event.width == 2*width assert event.height == 2*height width = event.width height = event.height break else: pytest.fail("Never received ConfigureNotifyEvent") # re-size and re-draw the surface surface.set_size(width, height) ctx = Context(surface) ctx.set_source_rgb(1, 1, 1) ctx.paint() # flush the connection, make sure no errors were thrown xcb_conn.flush() while event: event = xcb_conn.poll_for_event() cairocffi-1.2.0/cairocffi/xcb.py000066400000000000000000000037471374663167600165500ustar00rootroot00000000000000""" cairocffi.xcb ~~~~~~~~~~~~~ Bindings for XCB surface objects using xcffib. :copyright: Copyright 2014-2019 by Simon Sapin :license: BSD, see LICENSE for details. """ from xcffib import visualtype_to_c_struct from . import cairo, constants from .surfaces import SURFACE_TYPE_TO_CLASS, Surface class XCBSurface(Surface): """The XCB surface is used to render cairo graphics to X Window System windows and pixmaps using the XCB library. Creates a cairo surface that targets the given drawable (pixmap or window). .. note:: This class works using objects and libraries in :mod:`xcffib` :param conn: The :class:`xcffib.Connection` for an open XCB connection :param drawable: An XID corresponding to an XCB drawable (a pixmap or a window) :param visual: An :class:`xcffib.xproto.VISUALTYPE` object. :param width: integer :param height: integer """ def __init__(self, conn, drawable, visual, width, height): c_visual = visualtype_to_c_struct(visual) p = cairo.cairo_xcb_surface_create( conn._conn, drawable, c_visual, width, height) Surface.__init__(self, p) def set_size(self, width, height): """ Informs cairo of the new size of the X Drawable underlying the surface. For a surface created for a Window (rather than a Pixmap), this function must be called each time the size of the window changes (for a subwindow, you are normally resizing the window yourself, but for a toplevel window, it is necessary to listen for :class:`xcffib.xproto.ConfigureNotifyEvent`'s). A Pixmap can never change size, so it is never necessary to call this function on a surface created for a Pixmap. :param width: integer :param height: integer """ cairo.cairo_xcb_surface_set_size(self._pointer, width, height) self._check_status() SURFACE_TYPE_TO_CLASS[constants.SURFACE_TYPE_XCB] = XCBSurface cairocffi-1.2.0/docs/000077500000000000000000000000001374663167600144125ustar00rootroot00000000000000cairocffi-1.2.0/docs/api.rst000066400000000000000000000513371374663167600157260ustar00rootroot00000000000000Python API reference #################### .. module:: cairocffi Meta ==== .. autofunction:: install_as_pycairo .. autofunction:: cairo_version .. autofunction:: cairo_version_string .. autoexception:: CairoError .. data:: Error An alias for :exc:`CairoError`, for compatibility with pycairo. Surfaces ======== .. autoclass:: Surface ImageSurface ------------ .. autoclass:: ImageSurface PDFSurface ---------- .. autoclass:: PDFSurface PSSurface --------- .. autoclass:: PSSurface SVGSurface ---------- .. autoclass:: SVGSurface RecordingSurface ---------------- .. autoclass:: RecordingSurface Win32PrintingSurface -------------------- .. autoclass:: Win32PrintingSurface Context ======= .. autoclass:: Context Matrix ====== .. autoclass:: Matrix Patterns ======== .. autoclass:: Pattern() SolidPattern ------------ .. autoclass:: SolidPattern SurfacePattern -------------- .. autoclass:: SurfacePattern Gradient -------- .. autoclass:: Gradient() LinearGradient .............. .. autoclass:: LinearGradient RadialGradient .............. .. autoclass:: RadialGradient .. _fonts: Fonts & text ============ A font is (in simple terms) a collection of shapes used to draw text. A *glyph* is one of these shapes. There can be multiple glyphs for the same character (alternates to be used in different contexts, for example), or a glyph can be a ligature of multiple characters. Converting text to positioned glyphs is *shaping*. Cairo itself provides a "toy" text API that only does simple shaping: no ligature or kerning; one glyph per character, positioned by moving the cursor by the X and Y *advance* of each glyph. It is expected that most applications will need to :ref:`use Pango ` or a similar library in conjunction with cairo for more comprehensive font handling and text layout. Font faces ---------- .. note:: At the moment cairocffi only supports cairo’s "toy" font selection API. :class:`FontFace` objects of other types could be obtained eg. from :meth:`Context.get_font_face`, but they can not be instantiated directly. .. autoclass:: FontFace() ToyFontFace ........... .. autoclass:: ToyFontFace ScaledFont ---------- .. autoclass:: ScaledFont FontOptions ----------- .. autoclass:: FontOptions(**values) .. _enumerated values: Enumerated values ================= Some parameters or return values in the cairo API only have a fixed, finite set of valid values. These are represented as *enumerated types* in C, and as integers in CFFI. Users are encouraged to use the constants defined here in the :mod:`cairocffi` module rather than literal integers. For example:: surface = cairocffi.ImageSurface(cairocffi.FORMAT_ARGB32, 300, 400) .. _CONTENT: Content ------- Used to describe the content that a :class:`Surface` will contain, whether color information, alpha information (translucence vs. opacity), or both. .. data:: CONTENT_COLOR The surface will hold color content only. .. data:: CONTENT_ALPHA The surface will hold alpha content only. .. data:: CONTENT_COLOR_ALPHA The surface will hold color and alpha content. .. _FORMAT: Pixel format ------------ Used to identify the memory format of image data. .. data:: FORMAT_ARGB32 Each pixel is a 32-bit quantity, with alpha in the upper 8 bits, then red, then green, then blue. The 32-bit quantities are stored native-endian. Pre-multiplied alpha is used. (That is, 50% transparent red is 0x80800000, not 0x80ff0000.) .. data:: FORMAT_RGB24 Each pixel is a 32-bit quantity, with the upper 8 bits unused. Red, Green, and Blue are stored in the remaining 24 bits in that order. .. data:: FORMAT_A8 Each pixel is a 8-bit quantity holding an alpha value. .. data:: FORMAT_A1 Each pixel is a 1-bit quantity holding an alpha value. Pixels are packed together into 32-bit quantities. The ordering of the bits matches the endianess of the platform. On a big-endian machine, the first pixel is in the uppermost bit, on a little-endian machine the first pixel is in the least-significant bit. .. data:: FORMAT_RGB16_565 Each pixel is a 16-bit quantity with red in the upper 5 bits, then green in the middle 6 bits, and blue in the lower 5 bits. .. data:: FORMAT_RGB30 Like :obj:`FORMAT_RGB24`, but with the upper 2 bits unused and 10 bits per components. .. _OPERATOR: Compositiong operator --------------------- Used to set the compositing operator for all cairo drawing operations. The default operator is :obj:`OPERATOR_OVER`. The operators marked as **unbounded** modify their destination even outside of the mask layer (that is, their effect is not bound by the mask layer). However, their effect can still be limited by way of clipping. To keep things simple, the operator descriptions here document the behavior for when both source and destination are either fully transparent or fully opaque. The actual implementation works for translucent layers too. For a more detailed explanation of the effects of each operator, including the mathematical definitions, see `http://cairographics.org/operators/ `_. .. data:: OPERATOR_CLEAR Clear destination layer. (bounded) .. data:: OPERATOR_SOURCE Replace destination layer. (bounded) .. data:: OPERATOR_OVER Draw source layer on top of destination layer. (bounded) .. data:: OPERATOR_IN Draw source where there was destination content. (unbounded) .. data:: OPERATOR_OUT Draw source where there was no destination content. (unbounded) .. data:: OPERATOR_ATOP Draw source on top of destination content and only there. .. data:: OPERATOR_DEST Ignore the source. .. data:: OPERATOR_DEST_OVER Draw destination on top of source. .. data:: OPERATOR_DEST_IN Leave destination only where there was source content. (unbounded) .. data:: OPERATOR_DEST_OUT Leave destination only where there was no source content. .. data:: OPERATOR_DEST_ATOP Leave destination on top of source content and only there. (unbounded) .. data:: OPERATOR_XOR Source and destination are shown where there is only one of them. .. data:: OPERATOR_ADD Source and destination layers are accumulated. .. data:: OPERATOR_SATURATE Like :obj:`OPERATOR_OVER`, but assuming source and destination are disjoint geometries. .. data:: OPERATOR_MULTIPLY Source and destination layers are multiplied. This causes the result to be at least as dark as the darker inputs. (Since 1.10) .. data:: OPERATOR_SCREEN Source and destination are complemented and multiplied. This causes the result to be at least as light as the lighter inputs. (Since cairo 1.10) .. data:: OPERATOR_OVERLAY Multiplies or screens, depending on the lightness of the destination color. (Since cairo 1.10) .. data:: OPERATOR_DARKEN Replaces the destination with the source if it is darker, otherwise keeps the source. (Since cairo 1.10) .. data:: OPERATOR_LIGHTEN Replaces the destination with the source if it is lighter, otherwise keeps the source. (Since cairo 1.10) .. data:: OPERATOR_COLOR_DODGE Brightens the destination color to reflect the source color. (Since cairo 1.10) .. data:: OPERATOR_COLOR_BURN Darkens the destination color to reflect the source color. (Since cairo 1.10) .. data:: OPERATOR_HARD_LIGHT Multiplies or screens, dependent on source color. (Since cairo 1.10) .. data:: OPERATOR_SOFT_LIGHT Darkens or lightens, dependent on source color. (Since cairo 1.10) .. data:: OPERATOR_DIFFERENCE Takes the difference of the source and destination color. (Since cairo 1.10) .. data:: OPERATOR_EXCLUSION Produces an effect similar to difference, but with lower contrast. (Since cairo 1.10) .. data:: OPERATOR_HSL_HUE Creates a color with the hue of the source and the saturation and luminosity of the target. (Since cairo 1.10) .. data:: OPERATOR_HSL_SATURATION Creates a color with the saturation of the source and the hue and luminosity of the target. Painting with this mode onto a gray area produces no change. (Since cairo 1.10) .. data:: OPERATOR_HSL_COLOR Creates a color with the hue and saturation of the source and the luminosity of the target. This preserves the gray levels of the target and is useful for coloring monochrome images or tinting color images. (Since cairo 1.10) .. data:: OPERATOR_HSL_LUMINOSITY Creates a color with the luminosity of the source and the hue and saturation of the target. This produces an inverse effect to :obj:`OPERATOR_HSL_COLOR`. (Since cairo 1.10) .. _ANTIALIAS: Antialiasing mode ----------------- Specifies the type of antialiasing to do when rendering text or shapes. .. data:: ANTIALIAS_DEFAULT Use the default antialiasing for the subsystem and target device. .. data:: ANTIALIAS_NONE Use a bilevel alpha mask. .. data:: ANTIALIAS_GRAY Perform single-color antialiasing. .. data:: ANTIALIAS_SUBPIXEL Perform antialiasing by taking advantage of the order of subpixel elements on devices such as LCD panels. As it is not necessarily clear from the above what advantages a particular antialias method provides, since cairo 1.12, there is also a set of hints: .. data:: ANTIALIAS_FAST Allow the backend to degrade raster quality for speed. .. data:: ANTIALIAS_GOOD A balance between speed and quality. .. data:: ANTIALIAS_BEST A high-fidelity, but potentially slow, raster mode. These make no guarantee on how the backend will perform its rasterisation (if it even rasterises!), nor that they have any differing effect other than to enable some form of antialiasing. In the case of glyph rendering, :obj:`ANTIALIAS_FAST` and :obj:`ANTIALIAS_GOOD` will be mapped to :obj:`ANTIALIAS_GRAY`, with :obj:`ANTIALIAS_BEST` being equivalent to :obj:`ANTIALIAS_SUBPIXEL`. The interpretation of :obj:`ANTIALIAS_DEFAULT` is left entirely up to the backend, typically this will be similar to :obj:`ANTIALIAS_GOOD`. .. _FILL_RULE: Fill rule --------- Used to select how paths are filled. For both fill rules, whether or not a point is included in the fill is determined by taking a ray from that point to infinity and looking at intersections with the path. The ray can be in any direction, as long as it doesn't pass through the end point of a segment or have a tricky intersection such as intersecting tangent to the path. (Note that filling is not actually implemented in this way. This is just a description of the rule that is applied.) The default fill rule is :obj:`FILL_RULE_WINDING`. New entries may be added in future versions. .. data:: FILL_RULE_WINDING If the path crosses the ray fromleft-to-right, counts +1. If the path crosses the rayfrom right to left, counts -1. (Left and right are determined from the perspective of looking along the ray from the starting point.) If the total count is non-zero, the point will be filled. .. data:: FILL_RULE_EVEN_ODD Counts the total number of intersections, without regard to the orientation of the contour. If the total number of intersections is odd, the point will be filled. .. _LINE_CAP: Line cap style -------------- Specifies how to render the endpoints of the path when stroking. The default line cap style is :obj:`LINE_CAP_BUTT`. .. data:: LINE_CAP_BUTT Start (stop) the line exactly at the start (end) point. .. data:: LINE_CAP_ROUND Use a round ending, the center of the circle is the end point. .. data:: LINE_CAP_SQUARE Use squared ending, the center of the square is the end point. .. _LINE_JOIN: Line join style --------------- Specifies how to render the junction of two lines when stroking. The default line join style is :obj:`LINE_JOIN_MITER`. .. data:: LINE_JOIN_MITER Use a sharp (angled) corner, see :meth:`Context.set_miter_limit`. .. data:: LINE_JOIN_ROUND Use a rounded join, the center of the circle is the joint point. .. data:: LINE_JOIN_BEVEL Use a cut-off join, the join is cut off at half the line width from the joint point. .. _FONT_SLANT: Font slant ---------- Specifies variants of a font face based on their slant. .. data:: FONT_SLANT_NORMAL Upright font style. .. data:: FONT_SLANT_ITALIC Italic font style. .. data:: FONT_SLANT_OBLIQUE Oblique font style. .. _FONT_WEIGHT: Font weight ----------- Specifies variants of a font face based on their weight. .. data:: FONT_WEIGHT_NORMAL Normal font weight. .. data:: FONT_WEIGHT_BOLD Bold font weight. .. _SUBPIXEL_ORDER: Subpixel order -------------- The subpixel order specifies the order of color elements within each pixel on the display device when rendering with an antialiasing mode of :obj:`ANTIALIAS_SUBPIXEL`. .. data:: SUBPIXEL_ORDER_DEFAULT Use the default subpixel order for for the target device. .. data:: SUBPIXEL_ORDER_RGB Subpixel elements are arranged horizontally with red at the left. .. data:: SUBPIXEL_ORDER_BGR Subpixel elements are arranged horizontally with blue at the left. .. data:: SUBPIXEL_ORDER_VRGB Subpixel elements are arranged vertically with red at the top. .. data:: SUBPIXEL_ORDER_VBGR Subpixel elements are arranged vertically with blue at the top. .. _HINT_STYLE: Hint style ---------- Specifies the type of hinting to do on font outlines. Hinting is the process of fitting outlines to the pixel grid in order to improve the appearance of the result. Since hinting outlines involves distorting them, it also reduces the faithfulness to the original outline shapes. Not all of the outline hinting styles are supported by all font backends. New entries may be added in future versions. .. data:: HINT_STYLE_DEFAULT Use the default hint style for font backend and target device. .. data:: HINT_STYLE_NONE Do not hint outlines. .. data:: HINT_STYLE_SLIGHT Hint outlines slightly to improve contrast while retaining good fidelity to the original shapes. .. data:: HINT_STYLE_MEDIUM Hint outlines with medium strength giving a compromise between fidelity to the original shapes and contrast. .. data:: HINT_STYLE_FULL Hint outlines to maximize contrast. .. _HINT_METRICS: Metrics hinting mode -------------------- Specifies whether to hint font metrics; hinting font metrics means quantizing them so that they are integer values in device space. Doing this improves the consistency of letter and line spacing, however it also means that text will be laid out differently at different zoom factors. .. data:: HINT_METRICS_DEFAULT Hint metrics in the default manner for the font backend and target device. .. data:: HINT_METRICS_OFF Do not hint font metrics. .. data:: HINT_METRICS_ON Hint font metrics. .. .. _FONT_TYPE: Font type --------- Used to describe the type of a given font face or scaled font. The font types are also known as "font backends" within cairo. The type of a font face is determined by the function used to create it. The type of a scaled font is determined by the type of the font face passed to :class:`ScaledFont`. New entries may be added in future versions. .. data:: FONT_TYPE_TOY The font was created using cairo's toy font api. .. data:: FONT_TYPE_FT The font is of type FreeType. .. data:: FONT_TYPE_WIN32 The font is of type Win32. .. data:: FONT_TYPE_QUARTZ The font is of type Quartz. .. data:: FONT_TYPE_USER The font was create using cairo's user font api. (Since cairo 1.8) .. _PATH_OPERATION: Path operation -------------- Used to describe the type of one portion of a path when represented as a list. See :meth:`Context.copy_path` for details. .. data:: PATH_MOVE_TO .. data:: PATH_LINE_TO .. data:: PATH_CURVE_TO .. data:: PATH_CLOSE_PATH .. _EXTEND: Pattern extend -------------- Used to describe how pattern color/alpha will be determined for areas "outside" the pattern's natural area, (for example, outside the surface bounds or outside the gradient geometry). Mesh patterns are not affected by the extend mode. The default extend mode is :obj:`EXTEND_NONE` for :class:`SurfacePattern` and :obj:`EXTEND_PAD` for :class:`Gradient` patterns. New entries may be added in future versions. .. data:: EXTEND_NONE Pixels outside of the source pattern are fully transparent. .. data:: EXTEND_REPEAT The pattern is tiled by repeating. .. data:: EXTEND_REFLECT The pattern is tiled by reflecting at the edges. .. data:: EXTEND_PAD Pixels outside of the pattern copy the closest pixel from the source. .. _FILTER: Pixel filter ------------ Used to indicate what filtering should be applied when reading pixel values from patterns. See :meth:`Pattern.set_filter` for indicating the desired filter to be used with a particular pattern. .. data:: FILTER_FAST A high-performance filter, with quality similar to :obj:`FILTER_NEAREST`. .. data:: FILTER_GOOD A reasonable-performance filter, with quality similar to :obj:`FILTER_BILINEAR`. .. data:: FILTER_BEST The highest-quality available, performance may not be suitable for interactive use. .. data:: FILTER_NEAREST Nearest-neighbor filtering. .. data:: FILTER_BILINEAR Linear interpolation in two dimensions. .. data:: FILTER_GAUSSIAN This filter value is currently unimplemented, and should not be used in current code. .. _PDF_VERSION: PDF version ----------- Used to describe the version number of the PDF specification that a generated PDF file will conform to. .. data:: PDF_VERSION_1_4 The version 1.4 of the PDF specification. .. data:: PDF_VERSION_1_5 The version 1.5 of the PDF specification. .. _PDF_OUTLINE: PDF outline ----------- Used to specify the attributes of an outline item. These flags may be bitwise-or'd to produce any combination of flags. *New in cairo 1.16.* *New in cairocffi 0.9.* .. data:: PDF_OUTLINE_FLAG_OPEN The outline item defaults to open in the PDF viewer. .. data:: PDF_OUTLINE_FLAG_BOLD The outline item is displayed by the viewer in bold text. .. data:: PDF_OUTLINE_FLAG_ITALIC The outline item is displayed by the viewer in italic text. There's also a constant used to specify the root level for outlines. .. data:: PDF_OUTLINE_ROOT Root level for outlines. .. _PDF_METADATA: PDF metadata ------------ Used to specify the metadata to set. *New in cairo 1.16.* *New in cairocffi 0.9.* .. data:: PDF_METADATA_TITLE The document title. .. data:: PDF_METADATA_AUTHOR The document author. .. data:: PDF_METADATA_SUBJECT The document subject. .. data:: PDF_METADATA_KEYWORDS The document keywords. .. data:: PDF_METADATA_CREATOR The document creator. .. data:: PDF_METADATA_CREATE_DATE The document creation date. .. data:: PDF_METADATA_MOD_DATE The document modification date. .. _PS_LEVEL: PostScript level ---------------- Used to describe the language level of the PostScript Language Reference that a generated PostScript file will conform to. .. data:: PS_LEVEL_2 The language level 2 of the PostScript specification. .. data:: PS_LEVEL_3 The language level 3 of the PostScript specification. .. _SVG_VERSION: SVG version ----------- Used to describe the version number of the SVG specification that a generated SVG file will conform to. .. data:: SVG_VERSION_1_1 The version 1.1 of the SVG specification. .. data:: SVG_VERSION_1_2 The version 1.2 of the SVG specification. .. _SVG_UNIT: SVG unit -------- Used to describe the units valid for coordinates and lengths in the SVG specification. See also: - https://www.w3.org/TR/SVG/coords.html#Units - https://www.w3.org/TR/SVG/types.html#DataTypeLength - https://www.w3.org/TR/css-values-3/#lengths *New in cairo 1.16.* *New in cairocffi 0.9.* .. data:: SVG_UNIT_USER User unit, a value in the current coordinate system. If used in the root element for the initial coordinate systems it corresponds to pixels. .. data:: SVG_UNIT_EM The size of the element's font. .. data:: SVG_UNIT_EX The x-height of the element’s font. .. data:: SVG_UNIT_PX Pixels (1px = 1/96th of 1in). .. data:: SVG_UNIT_IN Inches (1in = 2.54cm = 96px). .. data:: SVG_UNIT_CM Centimeters (1cm = 96px/2.54). .. data:: SVG_UNIT_MM Millimeters (1mm = 1/10th of 1cm). .. data:: SVG_UNIT_PT Points (1pt = 1/72th of 1in). .. data:: SVG_UNIT_PC Picas (1pc = 1/6th of 1in). .. data:: SVG_UNIT_PERCENT Percent, a value that is some fraction of another reference value. .. _cluster-flags: Cluster flags ------------- Specifies properties of a text cluster mapping. Flags are integer values representing a bit field. .. data:: TEXT_CLUSTER_FLAG_BACKWARD :annotation: = 0x00000001 The clusters in the cluster array map to glyphs in the glyph array from end to start. (Since 1.8) cairocffi-1.2.0/docs/cffi_api.rst000066400000000000000000000103571374663167600167120ustar00rootroot00000000000000CFFI API ======== .. currentmodule:: cairocffi cairocffi’s :doc:`API ` is made of a number of :ref:`wrapper ` classes that provide a more Pythonic interface for various cairo objects. Functions that take a pointer as their first argument become methods, error statuses become exceptions, and :ref:`reference counting ` is hidden away. In order to use other C libraries that use integrate with cairo, or if cairocffi’s API is not sufficient (Consider making a `pull request`_!) you can access cairo’s lower level C pointers and API through CFFI_. .. _pull request: https://github.com/SimonSapin/cairocffi .. _CFFI: https://cffi.readthedocs.org/ Module-level objects -------------------- .. data:: ffi A :class:`cffi.FFI` instance with all of the cairo C API declared. .. data:: cairo The libcairo library, pre-loaded with :meth:`ffi.dlopen`. All cairo functions are accessible as attributes of this object:: import cairocffi from cairocffi import cairo as cairo_c, SURFACE_TYPE_XLIB if cairo_c.cairo_surface_get_type(surface._pointer) == SURFACE_TYPE_XLIB: ... See the `cairo manual`_ for details. .. _cairo manual: http://cairographics.org/manual/ .. _refcounting: Reference counting in cairo --------------------------- Most cairo objects are reference-counted, and freed when the count reaches zero. cairocffi’s Python wrapper will automatically decrease the reference count when they are garbage-collected. Therefore, care must be taken when creating a wrapper as to the reference count should be increased (for existing cairo objects) or not (for cairo objects that were just created with a refcount of 1.) .. _wrappers: Wrappers -------- .. automethod:: Surface._from_pointer .. automethod:: Pattern._from_pointer .. automethod:: FontFace._from_pointer .. automethod:: ScaledFont._from_pointer .. automethod:: Context._from_pointer .. attribute:: Surface._pointer The underlying :c:type:`cairo_surface_t *` cdata pointer. .. attribute:: Pattern._pointer The underlying :c:type:`cairo_pattern_t *` cdata pointer. .. attribute:: FontFace._pointer The underlying :c:type:`cairo_font_face_t *` cdata pointer. .. attribute:: ScaledFont._pointer The underlying :c:type:`cairo_scaled_font_t *` cdata pointer. .. attribute:: FontOptions._pointer The underlying :c:type:`cairo_scaled_font_t *` cdata pointer. .. attribute:: Matrix._pointer The underlying :c:type:`cairo_matrix_t *` cdata pointer. .. attribute:: Context._pointer The underlying :c:type:`cairo_t *` cdata pointer. .. _converting_pycairo: Converting pycairo wrappers to cairocffi ---------------------------------------- Some libraries such as PyGTK or PyGObject provide a pycairo :class:`~cairo.Context` object for you to draw on. It is possible to extract the underlying :c:type:`cairo_t *` pointer and create a cairocffi wrapper for the same cairo context. The follwing function does that with unsafe pointer manipulation. It only works on CPython. .. literalinclude:: ../utils/pycairo_to_cairocffi.py Converting other types of objects like surfaces is very similar, but left as an exercise to the reader. Converting cairocffi wrappers to pycairo ---------------------------------------- The reverse conversion is also possible. Here we use ctypes rather than CFFI because Python’s C API is sensitive to the GIL. .. literalinclude:: ../utils/cairocffi_to_pycairo.py .. _using_pango: Example: using Pango through CFFI with cairocffi ------------------------------------------------ The program below shows a fairly standard usage of CFFI to access Pango’s C API. The :attr:`Context._pointer` pointer can be used directly as an argument to CFFI functions that expect ``cairo_t *``. The C definitions are copied from `Pango’s`_ and `GLib’s`_ documentation. .. _Pango’s: http://developer.gnome.org/pango/stable/ .. _GLib’s: http://developer.gnome.org/glib/stable/ Using CFFI for accessing Pango (rather than the traditional bindings in PyGTK or PyGObject with introspection) is not only easiest for using together with cairocffi, but also means that all of Pango’s API is within reach, whereas bindings often only expose the high level API. .. literalinclude:: ../utils/pango_example.py cairocffi-1.2.0/docs/changelog.rst000066400000000000000000000000651374663167600170740ustar00rootroot00000000000000.. currentmodule:: cairocffi .. include:: ../CHANGES cairocffi-1.2.0/docs/conf.py000066400000000000000000000010531374663167600157100ustar00rootroot00000000000000from pathlib import Path extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage'] master_doc = 'index' project = 'cairocffi' copyright = '2013-2019, Simon Sapin' release = ( Path(__file__).parent.parent / 'cairocffi' / 'VERSION').read_text().strip() version = '.'.join(release.split('.')[:2]) exclude_patterns = ['_build'] autodoc_member_order = 'bysource' autodoc_default_flags = ['members'] intersphinx_mapping = { 'http://docs.python.org/': None, 'http://cairographics.org/documentation/pycairo/2/': None} cairocffi-1.2.0/docs/index.rst000066400000000000000000000002131374663167600162470ustar00rootroot00000000000000.. include:: ../README.rst Documentation ------------- .. toctree:: overview api pixbuf xcb cffi_api changelog cairocffi-1.2.0/docs/overview.rst000066400000000000000000000125061374663167600170160ustar00rootroot00000000000000Overview ======== .. currentmodule:: cairocffi Installing CFFI --------------- cairocffi requires CFFI, which can be installed with pip_ but has its own dependencies that can be tricky to install. * On Linux, install ``python-dev`` and ``libffi-dev`` from your system’s package manager. * On OS X, install ``pkg-config`` and ``libffi``, for example with `Homebrew`_. You may need to `set the PKG_CONFIG_PATH environment variable`_. * On Windows, consider using `Christoph Gohlke’s unofficial binary builds`_. See `CFFI’s own documentation`_ for details. .. _Homebrew: http://brew.sh/ .. _set the PKG_CONFIG_PATH environment variable: http://cffi.readthedocs.org/#macos-x .. _Christoph Gohlke’s unofficial binary builds: http://www.lfd.uci.edu/~gohlke/pythonlibs/#cffi .. _CFFI’s own documentation: http://cffi.readthedocs.org/ Installing cairocffi -------------------- Install with pip_:: pip install cairocffi This will automatically install CFFI. cairocffi can also be setup to utizile XCB support via xcffib_, that has to be installed before cairocffi:: pip install xcffib pip install cairocffi In addition to other dependencies, this will install xcffib. .. _pip: http://pip-installer.org/ .. _xcffib: https://github.com/tych0/xcffib/ Importing --------- The module to import is named ``cairocffi`` in order to co-exist peacefully with Pycairo_ which uses ``cairo``, but ``cairo`` is shorter and nicer to use:: import cairocffi as cairo cairocffi will dynamically load cairo as a shared library at this point. If it fails to find it, you will see an exception like this:: OSError: library not found: 'cairo' Make sure cairo is correctly installed and available through your system’s usual mechanisms. On Linux, the ``LD_LIBRARY_PATH`` environment variable can be used to indicate where to find shared libraries. .. _Pycairo: http://cairographics.org/pycairo/ Installing cairo on Windows ........................... cairocffi needs a ``libcairo-2.dll`` file in a directory that is listed in the ``PATH`` environment variable. `Alexander Shaduri’s GTK+ installer `_ works. (Make sure to leave the *Set up PATH environment variable* checkbox checked.) Pycairo on Windows is sometimes compiled statically against cairo and may not provide a ``.dll`` file that cairocffi can use. cairo versions -------------- Cairo, pycairo, and cairocffi each have version numbers. The same cairocffi version can be used with a variety of cairo versions. For example, the :meth:`Surface.set_mime_data` method is based on the :c:func:`cairo_surface_set_mime_data` C function, which is only available since cairo 1.10. You will get a runtime exception if you try to use it with an older cairo. You can however still use the rest of the API. There is no need for cairocffi’s versions to be tied to cairo’s versions. Use :func:`cairo_version` to test the version number for cairo:: if cairocffi.cairo_version() > 11000: surface.set_mime_data('image/jpeg', jpeg_bytes) Here are all the version numbers:: >>> print("The cairo version is %s, meaning %s." ... % (cairocffi.cairo_version(), cairocffi.cairo_version_string()) The cairo version is 11402, meaning 1.14.02. >>> print("The latest pycairo version this cairocffi version is compatible with is %s." ... % cairo.version) The latest pycairo version this cairocffi version is compatible with is 1.10.0. >>> print("The cairocffi version is %s." % cairo.VERSION) The cairocffi version is 0.7.2 cairocffi is automatically tested with both cairo 1.13.0 (Ubuntu Trusty's default version) and manually tested with the latest (1.15.12 as of this writing.) Compatibility with Pycairo -------------------------- cairocffi’s Python API is compatible with Pycairo. Please `file a bug `_ if you find incompatibilities. In your own code that uses Pycairo, you should be able to just change the imports from ``import cairo`` to ``import cairocffi as cairo`` as above. If it’s not your own code that imports Pycairo, the :func:`install_as_pycairo` function can help:: import cairocffi cairocffi.install_as_pycairo() import cairo assert cairo is cairocffi Alternatively, add a ``cairo.py`` file somewhere in your ``sys.path``, so that it’s imported instead of pycairo:: from cairocffi import * It is also possible to :ref:`convert pycairo contexts to cairocffi `. Basic usage ----------- For doing something useful with cairo, you need at least a surface and a context:: import cairocffi as cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 300, 200) context = cairo.Context(surface) with context: context.set_source_rgb(1, 1, 1) # White context.paint() # Restore the default source which is black. context.move_to(90, 140) context.rotate(-0.5) context.set_font_size(20) context.show_text('Hi from cairo!') surface.write_to_png('example.png') The :class:`Surface` represents the target. There are various types of surface for various output backends. The :class:`Context` holds internal state and is use for drawing. We’re only using solid colors here, but more complex :class:`Pattern` types are also available. All the details are in :doc:`api`. cairocffi-1.2.0/docs/pixbuf.rst000066400000000000000000000023221374663167600164400ustar00rootroot00000000000000.. module:: cairocffi.pixbuf Decoding images with GDK-PixBuf =============================== The :meth:`ImageSurface.create_from_png() ` method can decode PNG images and provide a cairo surface, but what about other image formats? The :mod:`cairocffi.pixbuf` module uses GDK-PixBuf_ to decode JPEG, GIF, and various other formats (depending on what is installed.) If you don’t import this module, it is possible to use the rest of cairocffi without having GDK-PixBuf installed. GDK-PixBuf is an independent package since version 2.22, but before that was part of `GTK+`_. .. _GDK-PixBuf: https://live.gnome.org/GdkPixbuf .. _GTK+: http://www.gtk.org/ This module also converts pixel data since the internal format in GDK-PixBuf (big-endian RGBA) is not the same as in cairo (native-endian ARGB). For this reason, although it is a "toy" API, :meth:`ImageSurface.create_from_png() ` can be faster than :func:`decode_to_image_surface` if the format is known to be PNG. The pixel conversion is done by GTK+ if available, but a (slower) fallback method is used otherwise. .. autoexception:: ImageLoadingError .. autofunction:: decode_to_image_surface cairocffi-1.2.0/docs/xcb.rst000066400000000000000000000004211374663167600157150ustar00rootroot00000000000000.. module:: cairocffi.xcb Using XCB surfaces with xcffib ============================== The :mod:`cairocffi.xcb` module uses xcffib_ as the XCB library to create graphics for X windows and pixmaps. .. autoclass:: XCBSurface .. _xcffib: https://github.com/tych0/xcffib/ cairocffi-1.2.0/setup.cfg000066400000000000000000000037401374663167600153070ustar00rootroot00000000000000[metadata] name = cairocffi url = https://github.com/Kozea/cairocffi version = file: cairocffi/VERSION license = BSD license_file = LICENSE description = cffi-based cairo bindings for Python long_description = file: README.rst long_description_content_type = text/x-rst author = Simon Sapin author_email = contact@courtbouillon.org platforms = Linux macOS Windows keywords = cairo cffi binding classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: BSD License Programming Language :: Python :: 3 :: Only Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Topic :: Multimedia :: Graphics project_urls = Documentation = https://cairocffi.readthedocs.io/ Code = https://github.com/Kozea/cairocffi/ Issue tracker = https://github.com/Kozea/cairocffi/issues Donation = https://opencollective.com/courtbouillon [options] packages = find: setup_requires = cffi >= 1.1.0 pytest-runner setuptools install_requires = cffi >= 1.1.0 tests_require = pytest-cov pytest-flake8 pytest-isort pytest-runner numpy python_requires = >= 3.6 [options.package_data] cairocffi = VERSION [options.packages.find] exclude = cairocffi._generated [options.extras_require] doc = sphinx sphinx_rtd_theme test = pytest-runner pytest-cov pytest-flake8 pytest-isort xcb = xcffib >= 0.3.2 [build_sphinx] source-dir = docs build-dir = docs/_build [aliases] test = pytest [tool:pytest] addopts = --flake8 --isort norecursedirs = build dist .cache .eggs .git [flake8] exclude = cairocffi/constants.py cairocffi/_generated/*.py [isort] default_section = FIRSTPARTY multi_line_output = 4 [coverage:report] exclude_lines = pragma: no cover pytest.xfail() pytest.fail() except OSError: except ImportError: raise OSError omit = .* [coverage:run] branch = True include = cairocffi/* cairocffi-1.2.0/setup.py000066400000000000000000000005241374663167600151750ustar00rootroot00000000000000import sys from setuptools import setup if sys.version_info.major < 3: raise RuntimeError( 'cairocffi does not support Python 2.x anymore. ' 'Please use Python 3 or install an older version of cairocffi.') setup( cffi_modules=[ 'cairocffi/ffi_build.py:ffi', 'cairocffi/ffi_build.py:ffi_pixbuf'] ) cairocffi-1.2.0/utils/000077500000000000000000000000001374663167600146225ustar00rootroot00000000000000cairocffi-1.2.0/utils/cairo_coverage.py000066400000000000000000000014111374663167600201410ustar00rootroot00000000000000import inspect import cairocffi import pycparser ALL_THE_CODE = ''.join( line for module in [ cairocffi, cairocffi.surfaces, cairocffi.patterns, cairocffi.fonts, cairocffi.context, cairocffi.matrix] for line in inspect.getsourcelines(module)[0]) class Visitor(pycparser.c_ast.NodeVisitor): def visit_Decl(self, node): for _, child in node.children(): if isinstance(child, pycparser.c_ast.FuncDecl): if ('cairo.' + node.name) not in ALL_THE_CODE and not ( node.name.endswith('user_data')): print(node.name) break print('cairo functions never used in cairocffi:\n') Visitor().visit(pycparser.CParser().parse(cairocffi.constants._CAIRO_HEADERS)) cairocffi-1.2.0/utils/cairocffi_to_pycairo.py000066400000000000000000000025561374663167600213610ustar00rootroot00000000000000import ctypes import cairo # pycairo import cairocffi pycairo = ctypes.PyDLL(cairo._cairo.__file__) pycairo.PycairoContext_FromContext.restype = ctypes.c_void_p pycairo.PycairoContext_FromContext.argtypes = 3 * [ctypes.c_void_p] ctypes.pythonapi.PyList_Append.argtypes = 2 * [ctypes.c_void_p] def _UNSAFE_cairocffi_context_to_pycairo(cairocffi_context): # Sanity check. Continuing with another type would probably segfault. if not isinstance(cairocffi_context, cairocffi.Context): raise TypeError('Expected a cairocffi.Context, got %r' % cairocffi_context) # Create a reference for PycairoContext_FromContext to take ownership of. cairocffi.cairo.cairo_reference(cairocffi_context._pointer) # Casting the pointer to uintptr_t (the integer type as wide as a pointer) # gets the context’s integer address. # On CPython id(cairo.Context) gives the address to the Context type, # as expected by PycairoContext_FromContext. address = pycairo.PycairoContext_FromContext( int(cairocffi.ffi.cast('uintptr_t', cairocffi_context._pointer)), id(cairo.Context), None) assert address # This trick uses Python’s C API # to get a reference to a Python object from its address. temp_list = [] assert ctypes.pythonapi.PyList_Append(id(temp_list), address) == 0 return temp_list[0] cairocffi-1.2.0/utils/compare_pycairo.py000066400000000000000000000013641374663167600203540ustar00rootroot00000000000000import cairo as pycairo import cairocffi # We want the real pycairo assert pycairo is not cairocffi print('Missing pycairo API:\n') for name in dir(pycairo): pycairo_obj = getattr(pycairo, name) cairocffi_obj = getattr(cairocffi, name, None) if name.startswith(('_', 'version', 'CAPI')): continue if cairocffi_obj is None: print(name) elif isinstance(pycairo_obj, type): for method_name in dir(pycairo_obj): if method_name.startswith('__'): continue pycairo_method = getattr(pycairo_obj, method_name) cairocffi_method = getattr(cairocffi_obj, method_name, None) if cairocffi_method is None: print('%s.%s' % (name, method_name)) cairocffi-1.2.0/utils/mkconstants.py000066400000000000000000000056421374663167600175470ustar00rootroot00000000000000import os import re import sys import textwrap import pycparser.c_generator def parse_constant(node): if isinstance(node, pycparser.c_ast.Constant): return node.value elif isinstance(node, pycparser.c_ast.UnaryOp) and node.op == '-': return '-' + parse_constant(node.expr) else: raise TypeError(node) class PrintEnumsVisitor(pycparser.c_ast.NodeVisitor): def visit_Decl(self, node): if node.name and node.name.startswith('CAIRO_'): # len('CAIRO_') == 6 if node.init.type == 'string': print('%s = b%s' % (node.name[6:], node.init.value)) else: print('%s = %s' % (node.name[6:], node.init.value)) print('') def visit_Enum(self, node): value = 0 for enumerator in node.values.enumerators: if enumerator.value is not None: value_string = parse_constant(enumerator.value) value = int(value_string, 0) else: value_string = str(value) assert enumerator.name.startswith('CAIRO_') # len('CAIRO_') == 6 print('%s = %s' % (enumerator.name[6:], value_string)) value += 1 print('') def read_cairo_header(cairo_git_dir, suffix): filename = os.path.join(cairo_git_dir, 'src', 'cairo%s.h' % suffix) source = open(filename, encoding='iso-8859-1').read() source = re.sub( '/\\*.*?\\*/' '|CAIRO_(BEGIN|END)_DECLS' '|cairo_public ' r'|^\s*#.*?[^\\]\n', '', source, flags=re.DOTALL | re.MULTILINE) source = re.sub('\n{3,}', '\n\n', source) return source def generate(cairo_git_dir): # Remove comments, preprocessor instructions and macros. source = read_cairo_header(cairo_git_dir, '') source += 'const int CAIRO_PDF_OUTLINE_ROOT = 0;\n' source += read_cairo_header(cairo_git_dir, '-pdf') source += read_cairo_header(cairo_git_dir, '-ps') source += read_cairo_header(cairo_git_dir, '-svg') source += ''' typedef void* HDC; typedef void* HFONT; typedef void LOGFONTW; ''' source += read_cairo_header(cairo_git_dir, '-win32') source += ''' typedef void* CGContextRef; typedef void* CGFontRef; typedef void* ATSUFontID; ''' source += read_cairo_header(cairo_git_dir, '-quartz') ast = pycparser.CParser().parse(source) print(textwrap.dedent('''\ # *** Do not edit this file *** # Generated by utils/mkconstants.py TAG_DEST = b"cairo.dest" TAG_LINK = b"Link"\n''')) PrintEnumsVisitor().visit(ast) print('_CAIRO_HEADERS = r"""%s"""' % source) source = read_cairo_header(cairo_git_dir, '-xcb') print('_CAIRO_XCB_HEADERS = r"""%s"""' % source) if __name__ == '__main__': if len(sys.argv) >= 2: generate(sys.argv[1]) else: print('Usage: %s path/to/cairo_source.git' % sys.argv[0]) cairocffi-1.2.0/utils/pango_example.py000066400000000000000000000034751374663167600200240ustar00rootroot00000000000000import cairocffi import cffi ffi = cffi.FFI() ffi.cdef(''' /* GLib */ typedef void cairo_t; typedef void* gpointer; void g_object_unref (gpointer object); /* Pango and PangoCairo */ typedef ... PangoLayout; typedef enum { PANGO_ALIGN_LEFT, PANGO_ALIGN_CENTER, PANGO_ALIGN_RIGHT } PangoAlignment; int pango_units_from_double (double d); PangoLayout * pango_cairo_create_layout (cairo_t *cr); void pango_cairo_show_layout (cairo_t *cr, PangoLayout *layout); void pango_layout_set_width (PangoLayout *layout, int width); void pango_layout_set_alignment ( PangoLayout *layout, PangoAlignment alignment); void pango_layout_set_markup ( PangoLayout *layout, const char *text, int length); ''') gobject = ffi.dlopen('gobject-2.0') pango = ffi.dlopen('pango-1.0') pangocairo = ffi.dlopen('pangocairo-1.0') def gobject_ref(pointer): return ffi.gc(pointer, gobject.g_object_unref) units_from_double = pango.pango_units_from_double def write_example_pdf(target): pt_per_mm = 72 / 25.4 width, height = 210 * pt_per_mm, 297 * pt_per_mm # A4 portrait surface = cairocffi.PDFSurface(target, width, height) context = cairocffi.Context(surface) context.translate(0, 300) context.rotate(-0.2) layout = gobject_ref( pangocairo.pango_cairo_create_layout(context._pointer)) pango.pango_layout_set_width(layout, units_from_double(width)) pango.pango_layout_set_alignment(layout, pango.PANGO_ALIGN_CENTER) markup = 'Hi from Παν語!' markup = ffi.new('char[]', markup.encode('utf8')) pango.pango_layout_set_markup(layout, markup, -1) pangocairo.pango_cairo_show_layout(context._pointer, layout) if __name__ == '__main__': write_example_pdf(target='pango_example.pdf') cairocffi-1.2.0/utils/pycairo_to_cairocffi.py000066400000000000000000000020401374663167600213450ustar00rootroot00000000000000import cairo # pycairo import cairocffi def _UNSAFE_pycairo_context_to_cairocffi(pycairo_context): # Sanity check. Continuing with another type would probably segfault. if not isinstance(pycairo_context, cairo.Context): raise TypeError('Expected a cairo.Context, got %r' % pycairo_context) # On CPython, id() gives the memory address of a Python object. # pycairo implements Context as a C struct: # typedef struct { # PyObject_HEAD # cairo_t *ctx; # PyObject *base; # } PycairoContext; # Still on CPython, object.__basicsize__ is the size of PyObject_HEAD, # ie. the offset to the ctx field. # ffi.cast() converts the integer address to a cairo_t** pointer. # [0] dereferences that pointer, ie. read the ctx field. # The result is a cairo_t* pointer that cairocffi can use. return cairocffi.Context._from_pointer( cairocffi.ffi.cast('cairo_t **', id(pycairo_context) + object.__basicsize__)[0], incref=True) cairocffi-1.2.0/utils/tests.py000066400000000000000000000017471374663167600163470ustar00rootroot00000000000000import io import cairo # noqa, pycairo import cairocffi import pango_example from cairocffi_to_pycairo import _UNSAFE_cairocffi_context_to_pycairo from pycairo_to_cairocffi import _UNSAFE_pycairo_context_to_cairocffi def test(): cairocffi_context = cairocffi.Context(cairocffi.PDFSurface(None, 10, 20)) cairocffi_context.scale(2, 3) pycairo_context = _UNSAFE_cairocffi_context_to_pycairo(cairocffi_context) cairocffi_context2 = _UNSAFE_pycairo_context_to_cairocffi(pycairo_context) assert tuple(cairocffi_context.get_matrix()) == (2, 0, 0, 3, 0, 0) assert tuple(cairocffi_context2.get_matrix()) == (2, 0, 0, 3, 0, 0) assert tuple(pycairo_context.get_matrix()) == (2, 0, 0, 3, 0, 0) assert cairocffi_context2._pointer == cairocffi_context._pointer file_obj = io.BytesIO() # Mostly test that this runs without raising. pango_example.write_example_pdf(file_obj) assert file_obj.getvalue().startswith(b'%PDF') if __name__ == '__main__': test()