Giter Site home page Giter Site logo

cairocffi's Introduction

cairocffi 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.

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's People

Contributors

ade-sculpteo avatar alexef avatar avnik avatar bnavigator avatar danxmoran avatar felixonmars avatar felixschwarz avatar flacjacket avatar frostidaho avatar funkybob avatar grewn0uille avatar gutard avatar jsmolic avatar kalekseev avatar lazka avatar li-xiang-ideal avatar lize avatar merriam avatar naveen521kk avatar orivej avatar pmakowski avatar redbug312 avatar robind42 avatar sde1000 avatar simonsapin avatar thrasibule avatar tych0 avatar vladimir-smirnov-sociomantic avatar vrusinov avatar xrmx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cairocffi's Issues

Pypy: type object 'c_char' has no attribute 'from_buffer'

Launching WeasyPrint tests with pypy 2.0.2 gives this error:

weasyprint/tests/testing_utils.py:77: in wrapper
>               function(*args, **kwargs)
weasyprint/tests/test_draw.py:2714: in test_radial_gradients
>           save_pixels_to_png(pixels, 10, 16, '/tmp/a.png')
weasyprint/tests/test_draw.py:50: in save_pixels_to_png
>           data=bytearray(pixels), stride=width * 4
/usr/lib64/pypy2.0/site-packages/cairocffi/surfaces.py:646: in __init__
>           address, length = from_buffer(data)
/usr/lib64/pypy2.0/site-packages/cairocffi/surfaces.py:68: in from_buffer
>           return ctypes.addressof(ctypes.c_char.from_buffer(obj)), len(obj)
E           AttributeError: type object 'c_char' has no attribute 'from_buffer'

"No package 'libffi' found" error during pip install

When I tried to pip install cairocffi into a fresh virtualenv, I got an error saying "Package libffi was not found..."

$ mkvirtualenv tmp
New python executable in tmp/bin/python
Installing setuptools............done.
Installing pip...............done.

(tmp)$ pip install cairocffi
Downloading/unpacking cairocffi
  Downloading cairocffi-0.5.tar.gz (70kB): 70kB downloaded
  Running setup.py egg_info for package cairocffi

    no previously-included directories found matching 'docs/_build'
Downloading/unpacking cffi>=0.6 (from cairocffi)
  Downloading cffi-0.6.tar.gz (169kB): 169kB downloaded
  Running setup.py egg_info for package cffi
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found

Downloading/unpacking pycparser (from cffi>=0.6->cairocffi)
  Downloading pycparser-2.09.1.tar.gz (201kB): 201kB downloaded
  Running setup.py egg_info for package pycparser

Installing collected packages: cairocffi, cffi, pycparser
  Running setup.py install for cairocffi

    no previously-included directories found matching 'docs/_build'
  Running setup.py install for cffi
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    building '_cffi_backend' extension
    /usr/bin/gcc-4.2 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -pipe -no-cpp-precomp -pipe -arch x86_64 -I/usr/include/ffi -I/usr/include/libffi -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c c/_cffi_backend.c -o build/temp.macosx-10.7-x86_64-2.7/c/_cffi_backend.o
    llvm-gcc-4.2 -Wl,-F. -bundle -undefined dynamic_lookup -Wl,-F. -bind_at_load -pipe -no-cpp-precomp -arch x86_64 build/temp.macosx-10.7-x86_64-2.7/c/_cffi_backend.o -lffi -o build/lib.macosx-10.7-x86_64-2.7/_cffi_backend.so

  Running setup.py install for pycparser

Successfully installed cairocffi cffi pycparser
Cleaning up...

(tmp) $ python --version
Python 2.7.1

Add way of using map-to-image

I might be wrong, but it looks like there is no cairocffi way of using cairo-map-to-image, (unless this is the same as passing data to ImageSurface constructor?) - map-to-image and set-dirty and flush seem to be a way to get cairo to act on some existing data.

pip install fails

I am trying to install in a clean virtualenv. I tried pip install cairocffi.

I get the following error (copied from the tail of the pip.log)

Exception information:
Traceback (most recent call last):
  File "/home/creation/.virtualenvs/proto/local/lib/python2.7/site-packages/pip/basecommand.py", line 134, in main
    status = self.run(options, args)
  File "/home/creation/.virtualenvs/proto/local/lib/python2.7/site-packages/pip/commands/install.py", line 241, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/home/creation/.virtualenvs/proto/local/lib/python2.7/site-packages/pip/req.py", line 1298, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/home/creation/.virtualenvs/proto/local/lib/python2.7/site-packages/pip/req.py", line 625, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
  File "/home/creation/.virtualenvs/proto/local/lib/python2.7/site-packages/pip/util.py", line 670, in call_subprocess
    % (command_desc, proc.returncode, cwd))
InstallationError: Command /home/creation/.virtualenvs/proto/bin/python -c "import setuptools;__file__='/home/creation/.virtualenvs/proto/build/cffi/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-vYXHD_-record/install-record.txt --single-version-externally-managed --install-headers /home/creation/.virtualenvs/proto/include/site/python2.7 failed with error code 1 in /home/creation/.virtualenvs/proto/build/cffi

If its at all useful, the last few line of the install output were:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -DUSE__THREAD -I/usr/include/ffi -I/usr/include/libffi -I/usr/include/python2.7 -c c/_cffi_backend.c -o build/temp.linux-i686-2.7/c/_cffi_backend.o

c/_cffi_backend.c:13:17: fatal error: ffi.h: No such file or directory

compilation terminated.

error: command 'gcc' failed with exit status 1

Support cairo Regions

cairocffi does not yet support cairo Regions: http://cairographics.org/manual/cairo-Regions.html

Originally reported as:


Support for cairo_region_t doesn't seem to be there (segfault)

The problem described here for pycairo doesn't seem to be resolved when using cairocffi: https://bugzilla.gnome.org/show_bug.cgi?id=667959

Just try (same with Python 3)

Python 2.7.5 (default, Aug 22 2013, 09:31:58) 
[GCC 4.8.1 20130603 (Red Hat 4.8.1-1)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from gi.repository import Gdk
>>> import cairocffi as cairo
>>> surface = cairo.ImageSurface(0,100,100)
>>> Gdk.cairo_region_create_from_surface(surface)
Segmentation fault (core dumped)

Would be great to have cairo_region_t support, e.g. for input_shape_combine_region.

Dead-lock in text_path function

After switching from pycairo to cairoffi, we encountered a problem with a web app served with uwsgi with 16 processes, and each 5 threads. Sometimes all 5 threads of a worker stuck in a same stack-trace, and worker terminates all threads after a timeout. The last lines from stack is:

File: "/path/to/file.py", line 125, in _generate_image
  context.text_path(text)
File: "python/lib/python3.4/site-packages/cairocffi/context.py", line 1205, in text_path
  cairo.cairo_text_path(self._pointer, _encode_string(text))

The problem only occurs in multi-threaded environment, and it's ok when each process run only 1 thread. It's seems it's a kind of concurrency problem in cairocffi (that doesn't exist in pycairo)

Environment is cairocffi 0.6 / python 3.4.1 / CentOS 7

Document installation for OSX (cannot import name constants)

I am trying to install Graphite. I am stuck upon cairo installation.
I came across "http://stackoverflow.com/questions/11491268/install-pycairo-in-virtualenv".
I have installed cairocffi in my virtual environment.

My environment is:
"OS X: 10.8.5
Python: 2.7.2
Virtual Env:
pip list
cairocffi (0.5.1)
ceres (0.10.0)
cffi (0.8.1)
Django (1.5.5)
django-tagging (0.3.1)
pip (1.5)
pycparser (2.10)
setuptools (2.0.2)
Twisted (11.1.0)
txAMQP (0.6.2)
whisper (0.9.12)
wsgiref (0.1.2)
zope.interface (4.0.5)"

Cairo:
I have installed cairo using macports.
"cairo @1.12.16_2+x11 (active)"

I started graphite with following sequence of commands:

  1. source /opt/graphite/bin/activate
  2. sudo /opt/graphite/bin/carbon-cache.py start
  3. sudo ./bin/run-graphite-devel-server.py /opt/graphite

http://0.0.0.0:8080/ is displaying Graphite home page.
But http://0.0.0.0:8080/render produces following traceback:

Traceback (most recent call last):
  File "/opt/graphite/lib/python2.7/site-packages/django/core/handlers/base.py", line 103, in get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/opt/graphite/lib/python2.7/site-packages/django/core/urlresolvers.py", line 321, in resolve
    sub_match = pattern.resolve(new_path)
  File "/opt/graphite/lib/python2.7/site-packages/django/core/urlresolvers.py", line 321, in resolve
    sub_match = pattern.resolve(new_path)
  File "/opt/graphite/lib/python2.7/site-packages/django/core/urlresolvers.py", line 223, in resolve
    return ResolverMatch(self.callback, args, kwargs, self.name)
  File "/opt/graphite/lib/python2.7/site-packages/django/core/urlresolvers.py", line 230, in callback
    self._callback = get_callable(self._callback_str)
  File "/opt/graphite/lib/python2.7/site-packages/django/utils/functional.py", line 31, in wrapper
    result = func(*args)
  File "/opt/graphite/lib/python2.7/site-packages/django/core/urlresolvers.py", line 97, in get_callable
    mod = import_module(mod_name)
  File "/opt/graphite/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
  File "/opt/graphite/webapp/graphite/render/views.py", line 36, in <module>
    from graphite.render.evaluator import evaluateTarget
  File "/opt/graphite/webapp/graphite/render/evaluator.py", line 47, in <module>
    from graphite.render.functions import SeriesFunctions
  File "/opt/graphite/webapp/graphite/render/functions.py", line 33, in <module>
    from graphite.render.glyph import format_units
  File "/opt/graphite/webapp/graphite/render/glyph.py", line 15, in <module>
    import cairocffi as cairo
  File "/opt/graphite/lib/python2.7/site-packages/cairocffi/__init__.py", line 16, in <module>
    from . import constants
ImportError: cannot import name constants

Make GTK actually optional.

GDK itself (part of GTK) should be optional for Pixbuf support but it’s not. Thanks @Surfoo for the bug report.

python -c 'import cairocffi.pixbuf'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/cairocffi/pixbuf.py", line 92, in <module>
    gdk = dlopen(ffi, 'gdk-3', 'gdk-x11-2.0', 'libgdk-win32-2.0-0')
  File "/usr/local/lib/python2.7/dist-packages/cairocffi/__init__.py", line 31, in dlopen
    return ffi.dlopen(names[0])  # pragma: no cover
  File "/usr/local/lib/python2.7/dist-packages/cffi/api.py", line 111, in dlopen
    lib, function_cache = _make_ffi_library(self, name, flags)
  File "/usr/local/lib/python2.7/dist-packages/cffi/api.py", line 364, in _make_ffi_library
    raise OSError("library not found: %r" % (name,))
OSError: library not found: 'gdk-3'

`import cairocffi` errors on Windows

Hi,

I have installed cairo on my Windows 8 machine by getting the necessary DLLs from the GTK project, as per the instructions in the cairo documentation.

I put the DLLs supplied from that page into my System32 folder.

Then, I used pip to install cairocffi.

When I try to run a script only with import cairocffi, I get the following error:

    import cairocffi
  File "A:\Anaconda\lib\site-packages\cairocffi\__init__.py", line 41, in <module>
    cairo = dlopen(ffi, *CAIRO_NAMES)
  File "A:\Anaconda\lib\site-packages\cairocffi\__init__.py", line 34, in dlopen
    return ffi.dlopen(names[0])  # pragma: no cover
  File "A:\Anaconda\lib\site-packages\cffi\api.py", line 127, in dlopen
    lib, function_cache = _make_ffi_library(self, name, flags)
  File "A:\Anaconda\lib\site-packages\cffi\api.py", line 572, in _make_ffi_library
    backendlib = _load_backend_lib(backend, libname, flags)
  File "A:\Anaconda\lib\site-packages\cffi\api.py", line 561, in _load_backend_lib
    return backend.load_library(name, flags)
OSError: cannot load library libcairo.so.2: error 0x7e

Why is this happening?

Font not found error reported as CAIRO_STATUS_NO_MEMORY

The module wanted one of the liberation fonts, but they weren't installed. The error returned was "out of memory". This confused me for a few hours until someone helped me search through strace output and found that the last thing before the exception was a collection of attempts to access fonts.

To replicate this issue:

  • Create a Centos 6.5 VM, update it (but do not install liberation-sans-fonts), install cairocffi, use it to make an SVG with text.

What I got:

  • CAIRO_STATUS_NO_MEMORY exception

What I expected:

  • Some kind of "font not found" message.

cairocffi throws on import when xcffib is installed

Greetings,
It seems cairocffi and xcffib are not/no longer compatible. Importing cairocffi with xcffib installed (both current versions, via pip) causes an Exception to be thrown:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/site-packages/cairocffi/__init__.py", line 105, in <module>
    from .xcb import XCBSurface
  File "/usr/lib/python3.4/site-packages/cairocffi/xcb.py", line 16, in <module>
    ffi.include(xcb_ffi)
  File "/usr/lib/python3.4/site-packages/cffi/api.py", line 430, in include
    type(ffi_to_include).__name__,))
TypeError: ffi.include() expects an argument that is also of type cffi.FFI, not 'CompiledFFI'

[1] suggests that the call to .include() is undesirable in runtime code, though I'm not experienced enough with cffi to be sure.

ArchLinux // Python 3.4.3 // pip 6.1.1 // cairocffi 0.6 // xcffib 0.3.1 (both installed via pip, not pacman)

[1] https://cffi.readthedocs.org/en/latest/cdef.html#ffi-include-combining-multiple-cffi-interfaces

set_source / set_source_surface ?

[Please give it the question status]

I try to use cairocffi because it should support Recording Surfaces. I reuse previously working code (with pycairo).

But now:

    cr.set_source_surface(self.image1,self.image1_cx,self.image1_cy)
    cr.paint_with_alpha(0.6)

raises this:

Traceback (most recent call last):
File "draw_4.py", line 45, in expose
cr.set_source_surface(self.image1,self.image1_cx,self.image1_cy)
TypeError: must be cairo.Surface, not ImageSurface

and

cr.set_source(self.image1) 
    cr.paint_with_alpha(0.6)

raises this:

Traceback (most recent call last):
File "draw_4.py", line 46, in expose
cr.set_source(self.image1)
TypeError: must be cairo.Pattern, not ImageSurface

What to use to paint from an ImageSurface?

cairocffi 0.7 fails to install when cffi<1.0 is installed

cairocffi 0.7 fails to be installed by pip when cffi<=1.0 is currently installed on the system, throwing the following error:

      File "<string>", line 17, in <module>
      File "/tmp/pip_build_root/cairocffi/setup.py", line 57, in <module>
        **cffi_args
      File "/usr/lib/python2.7/distutils/core.py", line 111, in setup
        _setup_distribution = dist = klass(attrs)
      File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 243, in __init__
        _Distribution.__init__(self,attrs)
      File "/usr/lib/python2.7/distutils/dist.py", line 287, in __init__
        self.finalize_options()
      File "/usr/lib/python2.7/dist-packages/setuptools/dist.py", line 277, in finalize_options
        ep.load()(self, ep.name, value)
      File "/usr/lib/python2.7/dist-packages/pkg_resources.py", line 2088, in load
        entry = __import__(self.module_name, globals(),globals(), ['__name__'])
    ImportError: No module named setuptools_ext

Here is a Dockerfile to reproduce:

FROM ubuntu:trusty

RUN apt-get update && apt-get -y --no-install-recommends install \
    build-essential \
    libffi-dev \
    python2.7 \
    python-dev \
    python-pip

RUN pip install --upgrade \
    "cffi<1.0"

RUN pip install --upgrade \
    cairocffi

The problem is slightly annoying as at least Ubuntu (both recent TLS and normal versions) ship a python-cffi (and also python3-cffi) version below 1.0 - which is nice to avoid the need for a compiler to be installed. Anyway, I think it should not fail, if an older version is currently installed.

Set version_info/version in install_as_pycairo

I'm playing around with matplotlib atm, which uses version_info and version to check if the installed pycairo is recent enough.

I suggest adding something like this in install_as_pycairo():

globals()["version_info"] = (1, 10, 0)
globals()["version"] = "1.10.0"

Unsupported cairo features

cairo still has a bunch of features that cairocffi could expose, but doesn’t yet. utils/cairo_coverage.py lists cairo functions that are not used in cairocffi, which is a pretty good indicator of such feature.

Feel free to comment of missing features you would like to see added.

Random CAIRO_STATUS_NULL_POINTER: NULL pointer with pypy2.4

I'm using graphite-api with pypy2.4 and receive random CAIRO_STATUS_NULL_POINTER: NULL pointer messages from cairo-cffi.

Though this happens not every time and I was unable to create minimal test case that doesn't involves setting up graphite and creating bunch of data.

Though after some investigation (and with a lot of help from LarstiQ from pypy channel on freenode) I've found that sometimes after https://github.com/SimonSapin/cairocffi/blob/master/cairocffi/context.py#L60:

path.data = <cdata 'cairo_path_data_t *' NULL>
path.status = STATUS_SUCCESS
path.num_data = 4

But if I add "pprint(data)" and "pprint(path.data)" after line 60 of this file, I saw that data is not null, but path.data is.

Maybe it's a pypy2.4 or cffi bug, but I don't understand how to debug this.

Segfault on PangoCairo.create_layout

python3 -c "
> from gi.repository import Gtk, Pango, PangoCairo
> import cairocffi as cairo
> surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 120, 120)
> context = cairo.Context(surface)
> layout = PangoCairo.create_layout(context)
> "
Segmentation fault (core dumped)

I do not get the same segfault when using cairo from pycairo.

Pixbuf error: GIF image was truncated or incomplete.

(This bug was initially reported as Kozea/WeasyPrint#179.)

Test image:
lorem

The image above loads fine in various image viewers. Asking GDK-PixBuf to load it directly from a file also works fine:

import cffi
ffi = cffi.FFI()
ffi.cdef('void* gdk_pixbuf_new_from_file (const char* filename, void** err);')
pixbuf = ffi.dlopen('gdk_pixbuf-2.0')
result = pixbuf.gdk_pixbuf_new_from_file(b'lorem.gif', ffi.NULL)
assert result != ffi.NULL

However, using cairocffi’s GDK-PixBuf support fails:

>>> from cairocffi.pixbuf import decode_to_pixbuf
>>> decode_to_pixbuf(open('lorem.gif', 'rb').read())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/simon/projects/cairocffi/cairocffi/pixbuf.py", line 155, in decode_to_pixbuf
    handle_g_error(error, gdk_pixbuf.gdk_pixbuf_loader_close(loader, error))
  File "/home/simon/projects/cairocffi/cairocffi/pixbuf.py", line 123, in handle_g_error
    raise ImageLoadingError(message)
cairocffi.pixbuf.ImageLoadingError: Pixbuf error: GIF image was truncated or incomplete.

This is either a bug in the way cairocffi uses GdkPixbufLoader (although this looks alright based on my reading of the documentation; unfortunately, gdk_pixbuf_new_from_file is not based on GdkPixbufLoader so we can’t just imitate that), or a bug in the underlying GDK-PixBuf library itself.

GdkPixbufLoader seems to be the only way to load an image without first having it on the local filesystem. (For example, downloading it from HTTP as WeasyPrint typically does.)

Many other images (including GIF) do not trigger this problem. The problem disappears after loading this image in GIMP and saving it back again to GIF. It looks like this file is broken/corrupted just enough to trip cairocffi.pixbuf or GdkPixbufLoader, but still allow other loaders to recover. I don’t know how to debug this further.

Pycairo Matrix __str__ shows Matrix content

cairo
Helpful for debugging :)

>>> cairo.Matrix(1.0, 0.0, 0.0, 1.0, 0.0, 0.0).__str__()
'cairo.Matrix(1, 0, 0, 1, 0, 0)'

cairocffi

>>> cairocffi.Matrix(1.0, 0.0, 0.0, 1.0, 0.0, 0.0).__str__()
'<cairocffi.Matrix object at 0x7facf725f690>'

dlopen() fails on Windows

Reported by @randfb on Reddit:

http://www.reddit.com/r/Python/comments/165bbf/cairocffi_dropin_pycairo_replacement_installs/c7tjwo7
http://www.reddit.com/r/Python/comments/165bbf/cairocffi_dropin_pycairo_replacement_installs/c7tkae4

I can't install on windows. I had pycairo working fine.
I can do a:

import cairo

without errors, but not

import cairocffi as cairo

319 path = ctypes.util.find_library(name)
320 if path is None:
--> 321 raise OSError("library not found: %r" % (name,))
322 #
323 backend = ffi._backend

OSError: library not found: 'cairo'

It seems that dlopen() fails to find cairo.dll.

@randfb, how did you install pycairo and cairo?

Change from using `dlopen` to `verify`

The cffi docs argue that using ffi.verify() is preferable to using ffi.dlopen() [1]. Moving to using verify would allow the generation of constants.py from the C headers to be dropped. An issues with this came up in #37 (comment) and #37 (comment) when trying to use ffi.verify() to implement a simple external pangocairo implementation using cairocffi. Cffi docs note that it is possible to package such that they can be used on systems without C compilers [2].

I'd propose then switching over to use ffi.verify. I can work on this project myself, but I wanted to get feedback on whether this would address your concerns and would be a welcome change.

[1] https://cffi.readthedocs.org/en/latest/#loading-libraries
[2] https://cffi.readthedocs.org/en/latest/#distributing-modules-using-cffi

cairocffi 'module' object has no attribute 'FFI'

Hi, I am trying to use cairocffi in weasyprint.
I can run it fine as root, but as user when I try to: python -c "import cairocffi"

I get:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.7/dist-packages/cairocffi/__init__.py", line 19, in 
    from ._ffi import ffi
  File "/usr/local/lib/python2.7/dist-packages/cairocffi/_ffi.py", line 4, in 
    ffi = _cffi_backend.FFI('cairocffi._ffi',
AttributeError: 'module' object has no attribute 'FFI'

I am using:
cairocffi==0.7
cffi==1.1.2
xcffib==0.3.2

and:
Operating System: Debian GNU/Linux stretch/sid
Kernel: Linux 3.2.0-4-amd64

any clues? thanks

pycairo cairo.Matrix constructor accepts another pycairo Matrix

In pycairo you can pass a Matrix into anothers constructor.

Error returned in cairocffi is

TypeError: type object argument after * must be a sequence, not Matrix

Not sure how the original support works - I guess either pycairo Matrices implement sequences or if the constructor code has explicit support for Matrices.

Couldn't get working on pypy

Hi,
I did a quick test on ubuntu, but didn't get very far. (Installed using pip + running in a virtualenv).. any idea what could be going on ?

$ python
Python 2.7.2 (1.9+dfsg-1, Jun 19 2012, 23:45:31)
[PyPy 1.9.0 with GCC 4.7.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
And now for something completely different: ``why there is no "PyPy 1.4
released" in topic any more?''
>>>> import cairocffi as cairo
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/stu/.virtualenvs/shoebot_pypy/site-packages/cairocffi/__init__.py", line 34, in <module>
    ffi = FFI()
  File "/home/stu/.virtualenvs/shoebot_pypy/site-packages/cffi/api.py", line 55, in __init__
    import _cffi_backend as backend
ImportError: No module named _cffi_backend
>>>> 

format_stride_for_width example in API docs doesn't work

The example on this page https://pythonhosted.org/cairocffi/api.html causes an exception:

from cairocffi import ImageSurface
stride = ImageSurface.stride_for_width(format, width)
data = bytearray(stride * height)
surface = ImageSurface(format, width, height, data, stride)

## -- End pasted text --
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-e39a39a18953> in <module>()
      1 from cairocffi import ImageSurface
----> 2 stride = ImageSurface.stride_for_width(format, width)
      3 data = bytearray(stride * height)
      4 surface = ImageSurface(format, width, height, data, stride)

AttributeError: type object 'ImageSurface' has no attribute 'stride_for_width'

surface.write_to_png() Fails when using with StringIO

We are currently using write_to_png into a StringIO buffer so that we can create a pixbuf with that later. The following code ilustrates the problem:

import StringIO

import cairocffi
import cairo as pycairo

def _write_to_png(cairo):
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 300, 200)
    context = cairo.Context(surface)
    context.set_source_rgb(255, 255, 255)
    context.paint()

    context.set_source_rgb(0, 0, 0)
    context.move_to(90, 140)
    context.rotate(-0.5)
    context.set_font_size(20)
    context.show_text(u'Hi from cairo!')

    buf = StringIO.StringIO()
    surface.write_to_png(buf)
    return buf.getvalue()

def test_write_to_png():
    py_str = _write_to_png(pycairo)
    cffi_str = _write_to_png(cairocffi)
    print cffi_str
    assert py_str == cffi_str

test_write_to_png()

If you run that, we can see that cffi_str has a value like:

"<_cffi_backend.buffer object at 0x14c8230><_cffi_backend.buffer object at 0x14c8230><_cffi_backe..."

RecordingSurface is not thread safe

I'm building an application where a bunch of threads are replaying the same RecordingSurface at different sizes / positions / orientations on different ImageSurface at the same time. And it looks like RecordingSurface is not thread safe.

Let's say I create a recording surface and draw text on it:

surface = cairocffi.RecordingSurface(cairocffi.CONTENT_COLOR_ALPHA, (0.0, 0.0, width, height))
ctx = cairocffi.Context(surface)
ctx.set_font_face(font)
ctx.set_font_size(size)
ctx.move_to(x, y)
ctx.set_source_rgb(0, 0, 0)
ctx.text_path(txt)
ctx.fill()

And then I have a bunch of threads that will use this RecordingSurface as a source and replay it at different scales / positions using this function:

def draw(ctx, surface, x, y, w, h):
    width_ratio = w / surface.get_width()
    height_ratio = h / surface.get_height()
    scale_xy = min(height_ratio, width_ratio)
    ctx.save()
    ctx.translate(x, y)
    ctx.scale(scale_xy, scale_xy)
    pattern = cairocffi.SurfacePattern(surface)
    ctx.set_source(pattern)
    ctx.paint()
    ctx.restore()

The issue is that the surface is not "locked" while being scaled / translated / used as a source. So these transformations affect all threads, and the result is all mixed up.

Thread safety issue

I bumped into a strange issue with cairocffi in a Django project, currently using the devserver on Windows.

The two images in the screenshot here are requested approximately simultaneously by the browser (as the user updates the values the images should display). Very often one of the images fails to render in some way -- either

  • Rendering the image wrong (!) like in the screenshot below (the "Esikatselu" text is somehow missing the "E" glyph)
  • Failing altogether with a "cairo returned CAIRO_STATUS_NO_MEMORY: out of memory" exception in a random place (usually during context.restore() apparently)
  • Or as occurs on one of the first two concurrent requests, with the traceback listed under "Initialization error?"

My hunch was that this smelled like a threading issue, so I wrapped the cairocffi-active bits of my code in a with render_lock: (where render_lock is a threading.Lock). This seems to resolve the issue, or at least work around it.

EDIT: Running the devserver with --nothreading also resolves the issue, so it pretty definitely is a thread safety issue.

Screenshot

scr

Initialization error?

File "generator.py", line 70, in render_pre
  context.set_antialias(cairo.constants.ANTIALIAS_BEST)
File "cairocffi\context.py", line 425, in set_antialias
  cairo.cairo_set_antialias(self._pointer, antialias)
File "cffi\api.py", line 414, in __getattr__
  make_accessor(name)
File "cffi\api.py", line 379, in make_accessor
  BType = ffi._get_cached_btype(tp)
File "cffi\api.py", line 295, in _get_cached_btype
  BType = type.get_cached_btype(self, finishlist)
File "cffi\model.py", line 34, in get_cached_btype
  BType = self.build_backend_type(ffi, finishlist)
File "cffi\model.py", line 166, in build_backend_type
  args.append(tp.get_cached_btype(ffi, finishlist))
File "cffi\model.py", line 36, in get_cached_btype
  assert BType2 is BType

Use cairocffi to double_buffer in Gtk3 drawing area

I'm trying to port some pygtk code to Gtk3 with gi.repository. I use an ImageSurface as a double buffer. It looks like last time I tried this I could use cairocffi.utils.pycairo_to_cairocffi._UNSAFE_pycairo_context_to_cairocffi to avoid

Traceback (most recent call last):
  File "/mnt/data/home/stu/projects/mine/shoebot/shoebot/gui/gtk_drawingarea.py", line 91, in draw
    cr.set_source_surface(self.backing_store)
TypeError: must be cairo.Surface, not ImageSurface

Whats the best way of approaching this now ?

IOError, [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: error while writing to output stream] 11

I installed cairo using pip: pip install cairocffi
then changed 'import cairo' to 'import cairocffi as cairo' in my code & in CairoPlot.py file.
but when I tried to generate bar graph,
I got this error 'CAIRO_STATUS_WRITE_ERROR'

My code is:

data = [[3,4], [4,8], [5,3], [9,1]]
v_labels = ["line1", "line2", "line3", "line4", "line5", "line6"]
h_labels = ["group1", "group2", "group3", "group4"]
CairoPlot.bar_plot ('graphName', data, 600, 200, border = 20, grid = True, h_labels = h_labels, v_labels = v_labels)

Pixelation when filling with RGBA source after stroking with RGB/RGBA source

The issue as described in the title occurs whether you stroke first or fill first, so long as the second operation is done with an RGBA source with A<1.

Test script to reproduce the effect:

import cairocffi as cairo

w, h = 237.6, 237.6
test_surf = cairo.PSSurface('test.ps', w, h)

a = cairo.Context(test_surf)
a.translate(w/2,h/2)
a.rotate(pi/4)
r_w, r_h = 175, 100
a.rectangle(-r_w/2,-r_h/2,r_w,r_h)
a.set_source_rgba(0,0,1,0.75)
a.fill_preserve()
a.set_source_rgba(1,0,0,0.25)
a.set_line_width(6)
a.stroke_preserve()

Is anyone else able to reproduce this? I'm not sure if it's an issue with GSView (i.e., that it's not a real effect - I'm doubtful of this), an issue with Cairo, or whether I'm doing something incorrectly with Cairo (I'm fairly new to it). I would upload a PNG showing what I mean, but the issue will be clearer, I think, if one were to simply to run the test script and examine the resulting PS file.

pip installation of cairocffi not working on mac

I tried to install cairocffi on Mac.
I am getting error while importing cairocffi.

Below are environment details:
Model: MacBook Pro
OS X: 10.8.5
Python: 2.7.2

Command Log:

sudo pip install cairocffi

...some warnings ....

    35 warnings generated.
    clang -bundle -undefined dynamic_lookup -Wl,-F. -arch i386 -arch x86_64 build/temp.macosx-10.8-intel-2.7/c/_cffi_backend.o -L/opt/local/lib -lffi -o build/lib.macosx-10.8-intel-2.7/_cffi_backend.so
    ld: warning: ignoring file /opt/local/lib/libffi.dylib, file was built for x86_64 which is not the architecture being linked (i386): /opt/local/lib/libffi.dylib

  Running setup.py install for pycparser

Successfully installed cairocffi cffi pycparser
Cleaning up...
SymMacToolkit-C02K824VF1G3:specs nitin_bodke$ python
Python 2.7.2 (default, Oct 11 2012, 20:14:37) 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import cairocffi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/cairocffi/__init__.py", line 39, in <module>
    cairo = dlopen(ffi, 'libcairo.so.2', 'libcairo-2.dll', 'cairo', 'libcairo-2')
  File "/Library/Python/2.7/site-packages/cairocffi/__init__.py", line 34, in dlopen
    return ffi.dlopen(names[0])  # pragma: no cover
  File "/Library/Python/2.7/site-packages/cffi/api.py", line 117, in dlopen
    lib, function_cache = _make_ffi_library(self, name, flags)
  File "/Library/Python/2.7/site-packages/cffi/api.py", line 399, in _make_ffi_library
    backendlib = backend.load_library(name, flags)
OSError: cannot load library libcairo.so.2: dlopen(libcairo.so.2, 2): image not found
>>> 
</snip>

IOError: [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: error while writing to output stream] 11

Environment

OSX Yosemite
System python 2.7

I'm completely new to the use of cairo. I have a case for converting svg files to png.

I found cairosvg as a suitable tool for this.

I had a lot of problems in installing cairo/py2cairo so at the end I decided to use cairocffi.

cairosvg test.svg -o test.png
Traceback (most recent call last):
  File "/usr/local/bin/cairosvg", line 25, in <module>
    cairosvg.main()
  File "/Library/Python/2.7/site-packages/cairosvg/__init__.py", line 92, in main
    SURFACES[output_format.upper()].convert(**kwargs)
  File "/Library/Python/2.7/site-packages/cairosvg/surface/__init__.py", line 87, in convert
    cls(tree, output, dpi).finish()
  File "/Library/Python/2.7/site-packages/cairosvg/surface/__init__.py", line 421, in finish
    self.cairo.write_to_png(self.output)
  File "/Library/Python/2.7/site-packages/cairocffi/surfaces.py", line 597, in write_to_png
    self._pointer, _encode_filename(target)))
  File "/Library/Python/2.7/site-packages/cairocffi/__init__.py", line 69, in _check_status
    raise exception(message, status)
IOError: [Errno cairo returned CAIRO_STATUS_WRITE_ERROR: error while writing to output stream] 11

Compiling CFFI under MinGW32 on Windows

Greetings,

I am attempting to compile CFFI for Win32 using the MinGW toolchain. I have resolved some minor compilation errors, and now everything works find up to the point of linking. This is the output I get:

[Cygwin] $ python setup.py build  -c mingw32
running build
running build_py
running build_ext
building '_cffi_backend' extension
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Ic/libffi_msvc -IC:\Anaconda\envs\py33\include -IC:\Anaconda\envs\py33\include -c c/_cffi_backend.c -o build\temp.win-amd64-3.3\Release\c\_cffi_backend.o
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Ic/libffi_msvc -IC:\Anaconda\envs\py33\include -IC:\Anaconda\envs\py33\include -c c/libffi_msvc\ffi.c -o build\temp.win-amd64-3.3\Release\c\libffi_msvc\ffi.o
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Ic/libffi_msvc -IC:\Anaconda\envs\py33\include -IC:\Anaconda\envs\py33\include -c c/libffi_msvc\prep_cif.c -o build\temp.win-amd64-3.3\Release\c\libffi_msvc\prep_cif.o
C:\MinGW\bin\gcc.exe -DMS_WIN64 -mdll -O -Wall -Ic/libffi_msvc -IC:\Anaconda\envs\py33\include -IC:\Anaconda\envs\py33\include -c c/libffi_msvc\types.c -o build\temp.win-amd64-3.3\Release\c\libffi_msvc\types.o
writing build\temp.win-amd64-3.3\Release\c\_cffi_backend.def
C:\MinGW\bin\gcc.exe -DMS_WIN64 -shared -s build\temp.win-amd64-3.3\Release\c\_cffi_backend.o build\temp.win-amd64-3.3\Release\c\libffi_msvc\ffi.o build\temp.win-amd64-3.3\Release\c\libffi_msvc\prep_cif.o build\temp.win-amd64-3.3\Release\c\libffi_msvc\types.o build\temp.win-amd64-3.3\Release\c\_cffi_backend.def -LC:\Anaconda\envs\py33\libs -LC:\Anaconda\envs\py33\PCbuild\amd64 -lpython33 -lmsvcr90 -o build\lib.win-amd64-3.3\_cffi_backend.pyd c/libffi_msvc\win64.obj
gcc: error: c/libffi_msvc\win64.obj: No such file or directory
error: command 'gcc' failed with exit status 1

It looks like the code is almost compiling, so perhaps with a few minor tweaks it would be possible to make CFFI MinGW-compatible. This would be a great help for those of us using Python under non-standard Windows environments.

TKA

Using cairocffi ImageSurface with Gtk?

In shoebot I've got a cairocffi branch I'd like to get working, we draw everything onto an ImageSurface which is then drawn using Gtk..

do_expose_event(...
        cr.set_source_surface(self.backing_store)   # Doesnt work since backing_store was created with cairocffi

I can see you've got functions to convert between pycairo + cairocffi contexts, is there something similar for surfaces?

(Also - if possible, it would be good to do this without having to have pycairo installed, as if possible I want to replace pycairo with cairocffi, to get the benefit of easy virtualenv installation).

test failure of test_png in test_pixbuf.py under pypy; cairocffi-0.6

I think this test passed under pypy months ago in a prior version. Version of pypy here is pypy-2.5.1.

rootdir: /mnt/gen2/TmpDir/portage/dev-python/cairocffi-0.6/work/cairocffi-0.6, inifile: 
collected 44 items

cairocffi/test_cairo.py ...x...x..............................
cairocffi/test_pixbuf.py ...F
cairocffi/test_xcb.py xx

=================================================================== FAILURES ===================================================================
___________________________________________________________________ test_png ___________________________________________________________________

    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')

cairocffi/test_pixbuf.py:60: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
cairocffi/pixbuf.py:252: in pixbuf_to_cairo_slices
    width, height, data, cairo_stride)
cairocffi/surfaces.py:646: in __init__
    address, length = from_buffer(data)
cairocffi/surfaces.py:68: in from_buffer
    return ctypes.addressof(ctypes.c_char.from_buffer(obj)), len(obj)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <class 'ctypes.c_char'>
obj = bytearray(b'\xff\x80\x00\xff\xff\x80\x00\xff\xff\x80\x00\xff\xff\x80\x00\xff\xff\x80\x00\xff\xff\x80\x00\xff'), offset = 0

    def from_buffer(self, obj, offset=0):
        size = self._sizeofinstances()
        buf = buffer(obj, offset, size)
        if len(buf) < size:
            raise ValueError(
                "Buffer size too small (%d instead of at least %d bytes)"
                % (len(buf) + offset, size + offset))
>       raw_addr = buf._pypy_raw_address()
E       ValueError: cannot find the underlying address of buffer that is internally <SubBuffer object at 0x1d71010>

/usr/lib64/pypy/lib_pypy/_ctypes/basics.py:93: ValueError
======== 1 failed, 39 passed, 4 xfailed in 3.97 seconds =========

this is a standard test of the suite and at face value is reporting the way pypy reads and manages the data in this test is incompatible with, something.

cairocffi SVGSurface fail to produce valid svg output

The code:

#import cairocffi
#cairocffi.install_as_pycairo()
import cairo
import StringIO

imageData = StringIO.StringIO()
surf = cairo.SVGSurface(imageData,200,200)
ctx = cairo.Context(surf)
ctx.set_line_width(1)
ctx.set_source_rgb(0,0,0)
ctx.move_to(0,0)
ctx.line_to(100,100)
surf.finish()
imageData.getvalue()

If I run it like this (so using original pycairo) I'll get:

'<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200pt" height="200pt" viewBox="0 0 200 200" version="1.1">\n<g id="surface1">\n</g>\n</svg>\n'

If I uncomment first two lines (use cairocffi) I'll get:

'<_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac><_cffi_backend.buffer object at 0xa4f22ac>'

Make cairo contexts work with with_statement.

This breaks with the pycairo ABI - so not sure what happens here (should we aim for this to go there first?)

If cairo contexts worked with the with statement, one could do something like:

with image_surface.get_context() as cr:
cr.set_source_rgb(1,1,1)
cr.rectangle(0, 1, 0)
cr.fill()

create_for_rectangle returns CAIRO_STATUS_INVALID_FORMAT: invalid value for an input cairo_format_t

I was trying to crop an input image (640x480) by using create_for_rectangle

        with open(input_image) as f:
            data = f.read()
            source_image, format = pixbuf.decode_to_image_surface( data )

            print source_image.get_width()
            print source_image.get_height()
            bottom_layer = source_image.create_for_rectangle(0, 65, 640, 350)
            #bottom_layer = source_image

Output:

640
480
CairoError: cairo returned CAIRO_STATUS_INVALID_FORMAT: invalid value for an input cairo_format_t

Create stub package to use cairocffi as drop in replacement for pycairo

I have next to no experience with Python, so I don't know if this is possible from your perspective or something I can only do locally.

I had a lot of trouble installing pycairo for use with some other Python programs that depend on it. Since I didn't write the code and did not want to keep local forks of each of the programs, I didn't want to use your recommendation to

import cairocffi as cairo (from http://stackoverflow.com/questions/11491268/install-pycairo-in-virtualenv/14205767#14205767)

In any case, I thought it would be great if there was a way to do that so you could force other packages to use cairocffi instead of pycairo.

I asked a Python programmer I know on Twitter:

twitter conversation about this request

So, is this something you can do at your level to make downstream consumption easy, or is it something only possible locally?

simple example writing onto existing numpy buffer dies

This example of dies -

http://stackoverflow.com/questions/10031580/how-to-write-simple-geometric-shapes-into-numpy-arrays/10031877#10031877

Code

import numpy
import cairo
#import cairocffi as cairo
import math
data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, 200, 200)
cr = cairo.Context(surface)

# fill with solid white
cr.set_source_rgb(1.0, 1.0, 1.0)
cr.paint()

# draw red circle
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()

# write output
print data[38:48, 38:48, 0]
surface.write_to_png("circle.png")

Output in pycairo:

## -- End pasted text --
[[255 255 255 255 255 255 255 253 110   0]
 [255 255 255 255 255 255 251  95   0   0]
 [255 255 255 255 255 246  73   0   0   0]
 [255 255 255 255 247  75   0   0   0  90]
 [255 255 255 247  70   0   0   0 108 254]
 [255 255 247  68   0   0   0 136 255 255]
 [255 251  82   0   0   0 127 255 255 255]
 [255  97   0   0   0 118 255 255 255 255]
 [127   0   0   0 119 255 255 255 255 255]
 [  1   0   0  91 254 255 255 255 255 255]]

Output in CairoCFFI

ValueError                                Traceback (most recent call last)
<ipython-input-7-7cdc9a0244d0> in <module>()
      3 data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
      4 surface = cairo.ImageSurface.create_for_data(
----> 5     data, cairo.FORMAT_ARGB32, 200, 200)
      6 cr = cairo.Context(surface)
      7 

/mnt/data/home/stu/.virtualenvs/tmp/local/lib/python2.7/site-packages/cairocffi/surfaces.pyc in create_for_data(cls, data, format, width, height, stride)
    658 
    659         """
--> 660         return cls(format, width, height, data, stride)
    661 
    662     @staticmethod

/mnt/data/home/stu/.virtualenvs/tmp/local/lib/python2.7/site-packages/cairocffi/surfaces.pyc in __init__(self, format, width, height, data, stride)
    647             if length < stride * height:
    648                 raise ValueError('Got a %d bytes buffer, needs at least %d.'
--> 649                                  % (length, stride * height))
    650             pointer = cairo.cairo_image_surface_create_for_data(
    651                 ffi.cast('char*', address), format, width, height, stride)

ValueError: Got a 200 bytes buffer, needs at least 160000.

Windows 7 compatibility

Hi,

I work on https://github.com/LaurentCabaret/pyVhdl2Sch which use your very useful package.
Everything is perfect under linux but fail under windows.

  1. I install python 2.7.8 (32bits)
  2. i processed : pip install cairocffi --upgrade and same for all others needed packages
  3. i used Alexander Shaduri’s GTK+ installer
    Result :
     import cairocffi as cairo
  File "build\bdist.win-amd64\egg\cairocffi\__init__.py", line 37, in <m
  File "C:\Python27\lib\site-packages\cffi\api.py", line 56, in __init__
    import _cffi_backend as backend
ImportError: DLL load failed: %1 nÆest pas une application Win32 valide.

Any idea ?

cairocffi 0.7 cannot load gdk-pixbuf library

with cairocffi 0.7, I get the following error:

In [1]: from cairocffi import pixbuf
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-1-502496f09f86> in <module>()
----> 1 from cairocffi import pixbuf

/home/cdevienne/.virtualenvs/unlish-dev/lib/python2.7/site-packages/cairocffi/pixbuf.py in <module>()
     28 
     29 gdk_pixbuf = dlopen(ffi, 'gdk_pixbuf-2.0', 'libgdk_pixbuf-2.0-0',
---> 30                     'libgdk_pixbuf-2.0.so')
     31 gobject = dlopen(ffi, 'gobject-2.0', 'libgobject-2.0-0', 'libgobject-2.0.so')
     32 glib = dlopen(ffi, 'glib-2.0', 'libglib-2.0-0', 'libglib-2.0.so')

/home/cdevienne/.virtualenvs/unlish-dev/lib/python2.7/site-packages/cairocffi/__init__.pyc in dlopen(ffi, *names)
     36             pass
     37     # Re-raise the exception.
---> 38     return ffi.dlopen(names[0])  # pragma: no cover
     39 
     40 

OSError: cannot load library 'gdk_pixbuf-2.0': gdk_pixbuf-2.0: cannot open shared object file: No such file or directory

The problem does not occur with cairocffi 0.6.

Digging a little, I found that it is related to the switch from cffi.FFI to _cffi_backend.FFI:

In [1]: import cffi

In [2]: import _cffi_backend

In [3]: cffi.FFI().dlopen('gdk_pixbuf-2')
Out[3]: <cffi.api.FFILibrary_gdk_pixbuf-2 at 0x7f893a299650>

In [4]: _cffi_backend.FFI().dlopen('gdk_pixbuf-2')                                                                              
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-4-eef9364611fa> in <module>()
----> 1 _cffi_backend.FFI().dlopen('gdk_pixbuf-2')

OSError: cannot load library 'gdk_pixbuf-2': gdk_pixbuf-2: cannot open shared object file: No such file or directory

That said, I have no clue why _cffi_backend is unable to load the library. I tried setting LD_LIBRARY_PATH, with no success.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.