-
-
Notifications
You must be signed in to change notification settings - Fork 53
/
surfaces.py
1545 lines (1224 loc) · 56.4 KB
/
surfaces.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
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 ``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 ``cairo_surface_t *`` cdata pointer.
:type incref: bool
:param incref:
Whether increase the :ref:`reference count <refcounting>` 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 ``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 str mime_type: The MIME type of the image data.
:param bytes data: The image data to attach to the surface.
*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 str mime_type: The MIME type of the image data.
: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 ``mime_type``.
:param str mime_type: The MIME type of the image data.
*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 :term:`file object` with a `write` method,
or :obj:`None`.
:returns:
If ``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, MemoryError): # 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 ``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 ``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 :term:`file object` with a ``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:`~Surface.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 ``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.
``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 :term:`file object` with a ``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 ``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.