1 <appendix id="language-bindings">
2 <title>Creating a language binding for cairo</title>
4 While cairo is implemented and C, and has a C API, it is expected
5 that many users of cairo will be using it from languages other
6 than C. The glue that connects the core cairo library to another
7 language is known as a <firstterm>language
8 binding</firstterm>. This appendix attempts to collect together
9 issues that come up when creating a language bindings for cairo
10 and present standardized solutions to promote consistency among
11 the different language bindings.
13 <sect1 id="bindings-general">
14 <title>General considerations</title>
16 The naming of the central <link
17 linkend="cairo-t"><type>cairo_t</type></link> type is a
18 special exception. The object is “a cairo context” not “a
19 cairo”, and names such as <type>cairo_t</type> rather than
20 <type>cairo_context_t</type> and
21 <function>cairo_set_source()</function> rather than
22 <function>cairo_context_set_source()</function> are simply
23 abbreviations to make the C API more palatable. In languages
24 which have object-oriented syntax, this abbreviation is much
25 less useful. In fact, if ‘Cairo’ is used as a namespace, then
26 in many languages, you'd end up with a ridiculous type name
27 like ‘Cairo.Cairo’. For this reason, and for inter-language
28 consistency all object-oriented languages should name this
29 type as if it were <type>cairo_context_t</type>.
32 The punctuation and casing of the type names and
33 method names of cairo should be changed to match the general
34 convention of the language. In Java, where type names are written
35 in StudlyCaps and method names in javaCaps, cairo_font_extents_t
36 will become FontExtents and
37 <literal>cairo_set_source(cr,source)</literal>,
38 <literal>cr.setSource(source)</literal>.
39 As compared to changing the punctuation, and casing, much
40 more reluctance should be used in changing the method names
41 themselves. Even if get is usually omitted from getters in
42 your language, you shouldn't bind cairo_get_source() as
46 <sect1 id="bindings-memory">
47 <title>Memory management</title>
49 The objects in cairo can roughly be divided into two types:
50 reference-counted, opaque types like
52 linkend="cairo-surface-t"><type>cairo_surface_t</type></link>
53 and plain structures like
55 linkend="cairo-glyph-t"><type>cairo_glyph_t</type></link>.
57 linkend="cairo-path-t"><type>cairo_path_t</type></link>
60 linkend="cairo-path-data-t"><type>cairo_path_data_t</type></link>
61 are special cases and are treated separately in this appendix.
64 Refcounted opaque types all have a
65 <function>..._reference()</function>
66 function to increase the refcount by one and a
67 <function>..._destroy()</function> to decrease the refcount
68 by one. These should not be exposed to the user of the language
69 binding, but rather used to implement memory management within
70 the language binding. The simplest way to do memory management
71 for a language binding is to treat the language binding object
72 as a simple handle to the cairo object. The language binding
73 object references the cairo object, and unreferences it when
74 finalized. This is the recommended method, though there are
75 a couple of caveats to be noted:
80 Equality won't work as expected. You can have two language
81 objects for the same cairo and they won't necessarily
82 compare equal. If the language allows customizing the
83 equality operation, then this is fixable by comparing
84 the underlying pointers. It also can be fixed by creating
85 at most one language object per cairo object, and
86 uniquifying via a <firstterm>pin table</firstterm> (a hash
87 table that goes from cairo object to language object).
88 For <type>cairo_surface_t</type> you can use also
90 linkend="cairo-surface-set-user-data"><function>cairo_surface_set_user_data()</function></link>
91 instead of a separate pin table.
96 Derivation from the language object doesn't work because
97 you can lose the language object while keeping the Cairo
101 public class MySurface (ImageSurface) {
102 public MySurface (width, height) {
103 super (Format.ARGB32, width, height);
105 public int get42 () {
110 cr = Cairo(MySurface(width, height));
111 surface = cr.getTarget();
114 Can result in <varname>surface</varname> containing an
115 <classname>ImageSurface</classname> not a <classname>MySurface</classname>.
116 This is not easily fixable without creating memory leaks,
117 and it's probably best to simply forbid deriving from the
123 When a plain structure is used as a return value from cairo,
124 this is done by passing it as a “out parameter”.
127 cairo_font_extents_t extents;
129 cairo_font_extents (cr, &extents);</programlisting>
131 In a language binding, this should typically be treated
135 FontExtents extents = cr.fontExtents ();</programlisting>
137 A language binding has a choice in how it implements the
138 language objects for plain structures. It can use a pure
139 language object with fields corresponding to those of the C
140 structure, and convert from and to the C structure when calling
141 cairo functions or converting cairo return values. Or it
142 can keep a pointer to the C structure internally and wrap
143 it inside a language object much like occurs for refcounted
144 objects. The choice should be invisible to the user: they should
145 be able to imagine that it is implemented as a pure language
149 <sect1 id="bindings-return-values">
150 <title>Multiple return values</title>
152 There are a number of functions in the cairo API that have
153 multiple <firstterm>out parameters</firstterm> or
154 <firstterm>in-out parameters</firstterm>. In some languages
155 these can be translated into multiple return values. In Python,
159 cairo_user_to_device (cr, &x, &y);</programlisting>
164 (x, y) = cr.user_to_device (cr, x, y);</programlisting>
166 but many languages don't have provisions for multiple return
167 values, so it is necessary to introduce auxiliary types.
168 Most of the functions that require the auxiliary types
169 require a type that would, in C, look like
172 typedef struct _cairo_point cairo_point_t;
173 struct _cairo_point {
178 The same type should be used both for functions that use a pair
179 of coordinates as an absolute position, and functions that use
180 a pair of coordinates as a displacement. While an argument could
181 be made that having a separate “distance” type is more correct,
182 it is more likely just to confuse users.
186 cairo_user_to_device (cairo_t *cr, double *x, double *y);
189 cairo_user_to_device_distance (cairo_t *cr, double *dx, double *dy);
192 cairo_device_to_user (cairo_t *cr, double *x, double *y);
195 cairo_device_to_user_distance (cairo_t *cr, double *dx, double *dy);
198 cairo_matrix_transform_distance (cairo_matrix_t *matrix, double *dx, double *dy);
201 cairo_matrix_transform_point (cairo_matrix_t *matrix, double *x, double *y);
204 cairo_get_current_point (cairo_t *cr, double *x, double *y);
207 There are also a couple of functions that return four values
208 representing a rectangle. These should be mapped to a
209 “rectangle” type that looks like:
212 typedef struct _cairo_rectangle cairo_rectangle_t;
213 struct _cairo_rectangle {
220 The C function returns the rectangle as a set of two points to
221 facilitate rounding to integral extents, but this isn't worth
222 adding a “box” type to go along with the more obvious
223 “rectangle” representation.
226 Q: Would it make sense here to define a standard
227 <function>cairo_rectangle_round()</function> method
228 that language bindings should map?
232 cairo_stroke_extents (cairo_t *cr,
233 double *x1, double *y1,
234 double *x2, double *y2);
237 cairo_fill_extents (cairo_t *cr,
238 double *x1, double *y1,
239 double *x2, double *y2);
242 <sect1 id="bindings-overloading">
243 <title>Overloading and optional arguments</title>
245 Function overloading (having a several variants of a function
246 with the same name and different arguments) is a language
247 feature available in many languages but not in C.
250 In general, language binding authors should use restraint in
251 combining functions in the cairo API via function
252 overloading. What may seem like an obvious overload now may
253 turn out to be strange with future additions to cairo.
254 It might seem logical to make
256 linkend="cairo-set-source-rgb"><function>cairo_set_source_rgb()</function></link>
257 an overload of <function>cairo_set_source()</function>, but future plans to add
258 <function>cairo_set_source_rgb_premultiplied()</function>,
259 which will also take three doubles make this a bad idea. For
260 this reason, only the following pairs of functions should
261 be combined via overloading
265 cairo_set_source (cairo_t *cr, cairo_pattern_t *source);
268 cairo_set_source_surface (cairo_t *cr,
269 cairo_surface_t *source,
274 cairo_mask (cairo_t *cr,
275 cairo_pattern_t *pattern);
278 cairo_mask_surface (cairo_t *cr,
279 cairo_surface_t *surface,
284 cairo_image_surface_create (cairo_format_t format,
288 cairo_image_surface_create_for_data (unsigned char *data,
289 cairo_format_t format,
295 cairo_surface_write_to_png (cairo_surface_t *surface,
296 const char *filename);
299 cairo_surface_write_to_png_stream (cairo_surface_t *surface,
300 cairo_write_func_t write_func,
304 cairo_image_surface_create_from_png (const char *filename);
307 cairo_image_surface_create_from_png_stream (cairo_read_func_t read_func,
311 Note that there are cases where all constructors for a type
312 aren't overloaded together. For example
314 linkend="cairo-image-surface-create-from-png"><function>cairo_image_surface_create_from_png()</function></link>
315 should <emphasis>not</emphasis> be overloaded together with
317 linkend="cairo-image-surface-create"><function>cairo_image_surface_create()</function></link>.
318 In such cases, the remaining constructors will typically need to
319 be bound as static methods. In Java, for example, we might have:
322 Surface surface1 = ImageSurface(Format.RGB24, 100, 100);
323 Surface surface2 = ImageSurface.createFromPNG("camera.png");</programlisting>
325 Some other overloads that add combinations not found in C may be
326 convenient for users for language bindings that provide
327 <type>cairo_point_t</type> and <type>cairo_rectangle_t</type>
332 cairo_move_to (cairo_t *cr,
333 cairo_point_t *point);
335 cairo_rectangle (cairo_t *cr,
336 cairo_rectangle_t *rectangle);
339 <sect1 id="bindings-streams">
340 <title>Streams and File I/O</title>
342 Various places in the cairo API deal with reading and writing
343 data, whether from and to files, or to other sources and
344 destinations. In these cases, what is typically provided in the
345 C API is a simple version that just takes a filename, and a
346 complex version that takes a callback function.
347 An example is the PNG handling functions:
351 cairo_image_surface_create_from_png (const char *filename);
354 cairo_image_surface_create_from_png_stream (cairo_read_func_t read_func,
358 cairo_surface_write_to_png (cairo_surface_t *surface,
359 const char *filename);
362 cairo_surface_write_to_png_stream (cairo_surface_t *surface,
363 cairo_write_func_t write_func,
364 void *closure);</programlisting>
366 The expectation is that the filename version will be mapped
367 literally in the language binding, but the callback version
368 will be mapped to a version that takes a language stream
369 object. For example, in Java, the four functions above
373 static public ImageSurface createFromPNG (String filename) throws IOException;
374 static public ImageSurface createFromPNG (InputStream stream) throws IOException;
375 public void writeToPNG (String filename) throws IOException;
376 public void writeToPNG (OutputStream stream) throws IOException;
379 In many cases, it will be better to
380 implement the filename version internally
381 using the stream version, rather than building it on top of the
382 filename version in C. The reason for this is that will
383 naturally give a more standard handling of file errors for
384 the language, as seen in the above Java example, where
385 <methodname>createFromPNG()</methodname> is marked as raising
386 an exception. Propagating exceptions from inside the callback
387 function to the caller will pose a challenge to the language
388 binding implementor, since an exception must not propagate
389 through the Cairo code. A technique that will be useful in
390 some cases is to catch the exception in the callback,
391 store the exception object inside a structure pointed to by
392 <parameter>closure</parameter>, and then rethrow it once
393 the function returns.
396 I'm not sure how to handle this for
398 linkend="cairo-pdf-surface-create-for-stream"><function>cairo_pdf_surface_create_for_stream()</function></link>.
399 Other than keep a “exception to rethrow” thread-specific
401 that is checked after <emphasis>every</emphasis> call to a Cairo
405 <sect1 id="bindings-errors">
406 <title>Error handling</title>
408 The error handling approach in C for Cairo has multiple
413 When a method on an object fails, the object is put into
414 an error state. Subsequent operations on the object do
415 nothing. The status of the object can be queried with
416 a function like <link
417 linkend="cairo-status"><function>status()</function></link>.
420 Constructors, rather than
421 returning <constant>NULL</constant> on out-of-memory failure,
422 return a special singleton object on which all
423 operations do nothing. Retrieving the status of the
424 singleton object returns <constant>CAIRO_STATUS_NO_MEMORY</constant>
427 Is this going to apply to
428 <type>cairo_surface_t</type> as well?
431 What about cairo_copy_path_data()? It's probably going to
432 have to return <constant>NULL</constant>.
436 Errors propagate from object to object. Setting a pattern
437 in an out-of-memory state as the source of a
438 <type>cairo_t</type> puts the type into an error state.
441 <remark>Much of the above is not yet implemented at the time of
442 this writing</remark>
444 A language binding could copy the C approach, and for a
445 language without exceptions, this is likely the right thing
446 to do. However, for a language with exceptions, exposing
447 a completely different style of error handling for cairo
448 would be strange. So, instead, status should be checked
449 after every call to cairo, and exceptions thrown as necessary.
452 One problem that can arise with this, in languages
453 where handling exceptions is mandatory (like Java), is that almost
454 every cairo function can result in a status being set,
455 usually because of an out-of-memory condition. This could make
456 cairo hard to use. To resolve this problem, let's classify then
461 CAIRO_STATUS_NO_MEMORY,
463 /* Programmer error */
464 CAIRO_STATUS_INVALID_RESTORE
465 CAIRO_STATUS_INVALID_POP_GROUP
466 CAIRO_STATUS_NO_CURRENT_POINT
467 CAIRO_STATUS_INVALID_MATRIX
468 CAIRO_STATUS_NO_TARGET_SURFACE
469 CAIRO_STATUS_INVALID_STRING
470 CAIRO_STATUS_SURFACE_FINISHED
471 CAIRO_STATUS_BAD_NESTING
473 /* Language binding implementation */
474 CAIRO_STATUS_NULL_POINTER
475 CAIRO_STATUS_INVALID_PATH_DATA
476 CAIRO_STATUS_SURFACE_TYPE_MISMATCH
479 CAIRO_STATUS_READ_ERROR
480 CAIRO_STATUS_WRITE_ERROR
483 If we look at these, the
484 <constant>CAIRO_STATUS_NO_MEMORY</constant>
485 should map to the native out-of-memory exception, which could
486 happen at any point in any case. Most of the others indicate
487 programmer error, and handling them in user code would be
488 silly. These should be mapped into whatever the language uses
489 for assertion failures, rather than errors that are normally
490 handled. (In Java, a subclass of Error rather than Exception,
491 perhaps.) And <constant>CAIRO_STATUS_READ_ERROR</constant>,
492 and <constant>CAIRO_STATUS_WRITE_ERROR</constant> can occur
493 only in very specific places. (In fact, as described
494 in <xref linkend="bindings-streams"/>, these errors may be
495 mapped into the language's native I/O error types.)
496 So, there really aren't exceptions that the programmer must
497 handle at most points in the Cairo API.
500 <sect1 id="bindings-patterns">
501 <title>Patterns</title>
503 The cairo C API allows for creating a number of different types
504 of patterns. All of these different types of patterns map to
506 linkend="cairo-pattern-t"><type>cairo_pattern_t</type></link>
507 in C, but in an object oriented language, there should instead
508 be a hierarchy of types. (The functions that should map to
509 constructors or static methods for the various types are listed
510 after the type, methods on that type are listed below. Note that
511 cairo_pattern_create_rgb() and cairo_pattern_create_rgba()
512 should not be overloaded with each other as a SolidPattern()
513 constructor, but should appear as static methods instead. This
514 is to maintain code clarity by making it clear how the arguments
515 relate to color components.)
519 <link linkend="cairo-pattern-set-matrix"><function>cairo_pattern_set_matrix()</function></link>
520 <link linkend="cairo-pattern-get-matrix"><function>cairo_pattern_get_matrix()</function></link>
521 cairo_solid_pattern_t (<link linkend="cairo-pattern-create-rgb"><function>cairo_pattern_create_rgb()</function></link> and <link linkend="cairo-pattern-create-rgba"><function>cairo_pattern_create_rgba()</function></link>)
522 cairo_surface_pattern_t (<link linkend="cairo-pattern-create-for-surface"><function>cairo_pattern_create_for_surface()</function></link>)
523 <link linkend="cairo-pattern-set-extend"><function>cairo_pattern_set_extend()</function></link>
524 <link linkend="cairo-pattern-get-extend"><function>cairo_pattern_get_extend()</function></link>
525 <link linkend="cairo-pattern-set-filter"><function>cairo_pattern_set_filter()</function></link>
526 <link linkend="cairo-pattern-get-filter"><function>cairo_pattern_get_filter()</function></link>
528 <link linkend="cairo-pattern-add-color-stop-rgb"><function>cairo_pattern_add_color_stop_rgb()</function></link>
529 <link linkend="cairo-pattern-add-color-stop-rgba"><function>cairo_pattern_add_color_stop_rgba()</function></link>
530 cairo_linear_gradient_t (<link linkend="cairo-pattern-create-linear"><function>cairo_pattern_create_linear()</function></link>)
531 cairo_radial_gradient_t (<link linkend="cairo-pattern-create-radial"><function>cairo_pattern_create_radial()</function></link>)
532 cairo_mesh_t (<link linkend="cairo-pattern-create-mesh"><function>cairo_pattern_create_mesh()</function></link>)
533 <link linkend="cairo-mesh-pattern-begin-patch"><function>cairo_mesh_pattern_begin_patch()</function></link>
534 <link linkend="cairo-mesh-pattern-end-patch"><function>cairo_mesh_pattern_end_patch()</function></link>
535 <link linkend="cairo-mesh-pattern-move-to"><function>cairo_mesh_pattern_move_to()</function></link>
536 <link linkend="cairo-mesh-pattern-line-to"><function>cairo_mesh_pattern_line_to()</function></link>
537 <link linkend="cairo-mesh-pattern-curve-to"><function>cairo_mesh_pattern_curve_to()</function></link>
538 <link linkend="cairo-mesh-pattern-set-control-point"><function>cairo_mesh_pattern_set_control_point()</function></link>
539 <link linkend="cairo-mesh-pattern-set-corner-color-rgb"><function>cairo_mesh_pattern_set_corner_color_rgb()</function></link>
540 <link linkend="cairo-mesh-pattern-set-corner-color-rgba"><function>cairo_mesh_pattern_set_corner_color_rgba()</function></link>
541 <link linkend="cairo-mesh-pattern-get-patch-count"><function>cairo_mesh_pattern_get_patch_count()</function></link>
542 <link linkend="cairo-mesh-pattern-get-path"><function>cairo_mesh_pattern_get_path()</function></link>
543 <link linkend="cairo-mesh-pattern-get-control-point"><function>cairo_mesh_pattern_get_control_point()</function></link>
544 <link linkend="cairo-mesh-pattern-get-corner-color-rgba"><function>cairo_mesh_pattern_get_corner_color_rgba()</function></link>
549 <sect1 id="bindings-surfaces">
550 <title>Surfaces</title>
552 Like patterns, surfaces, which use only the
554 linkend="cairo-surface-t"><type>cairo_surface_t</type></link>
555 type in the C API should be broken up into a hierarchy of types
556 in a language binding.
560 cairo_image_surface_t
561 cairo_atsui_surface_t
562 cairo_win32_surface_t
567 Unlike patterns, the constructors and methods on these types are
568 clearly named, and can be trivially associated with the
569 appropriate subtype. Many language bindings will want to avoid
570 binding the platform-specific subtypes at all, since the
571 methods on these types are not useful without passing in native
572 C types. Unless there is a language binding for Xlib available,
573 there is no way to represent a XLib <type>Display</type> * in
577 This doesn't mean that platform-specific surface types can't
578 be used in a language binding that doesn't bind the constructor.
579 A very common situation is to use a cairo language binding in
580 combination with a binding for a higher level system like
581 the <ulink url="http://www.gtk.org/">GTK+</ulink> widget
582 toolkit. In such a situation, the higher level toolkit provides
583 ways to get references to platform specific surfaces.
587 linkend="cairo-surface-set-user-data"><function>cairo_surface_set_user_data()</function></link>,
589 linkend="cairo-surface-get-user-data"><function>cairo_surface_get_user_data()</function></link>
590 methods are provided for use in language bindings, and should
591 not be directly exposed to applications. One example of the use
592 of these functions in a language binding is creating a binding for:
596 <link linkend="cairo-image-surface-create-for-data"><function>cairo_image_surface_create_for_data</function></link> (unsigned char *data,
597 cairo_format_t format,
603 The memory block passed in for <parameter>data</parameter> must be
604 kept around until the surface is destroyed, so the language
605 binding must have some way of determining when that happens. The
606 way to do this is to use the <parameter>destroy</parameter>
607 argument to <function>cairo_surface_set_user_data()</function>.
610 Some languages may not have a suitable “pointer to a block of
611 data” type to pass in for <parameter>data</parameter>. And even
612 where a language does have such a type, the user will be
613 frequently able to cause the backing store to be reallocated
614 to a different location or truncated. Should we recommend a
615 standard type name and binding for a buffer object here?
618 <sect1 id="bindings-fonts">
621 Fonts are once more an area where there is a hierarchy of types:
626 cairo_win32_font_face_t
628 cairo_ft_scaled_font_t
629 cairo_win32_scaled_font_t
632 The methods on the subtypes are, however, not useful without
633 bindings for fontconfig and FreeType or for the Win32 GDI,
634 so most language bindings will choose not to bind these
639 linkend="cairo-font-face-set-user-data"><function>cairo_font_face_set_user_data()</function></link>,
641 linkend="cairo-font-face-get-user-data"><function>cairo_font_face_get_user_data()</function></link>
642 methods are provided for use in language bindings, and should
643 not be directly exposed to applications.
646 <sect1 id="bindings-path">
647 <title>cairo_path_t</title>
649 The <link linkend="cairo-path-t"><type>cairo_path_t</type></link> type is one
650 area in which most language bindings will differ significantly
651 from the C API. The C API for <type>cairo_path_t</type> is
652 designed for efficiency and to avoid auxiliary objects that
653 would be have to be manually memory managed by the
654 application. However,
655 a language binding should not present <type>cairo_path_t</type> as an
656 array, but rather as an opaque that can be iterated
657 over. Different languages have quite different conventions for
658 how iterators work, so it is impossible to give an exact
659 specification for how this API should work, but the type names
660 and methods should be similar to the language's mapping of the following:
663 typedef struct cairo_path_iterator cairo_path_iterator_t;
664 typedef struct cairo_path_element cairo_path_element_t;
666 cairo_path_iterator_t *
667 cairo_path_get_iterator (cairo_path_t *path);
670 cairo_path_iterator_has_next (cairo_path_iterator_t *iterator);
672 cairo_path_element_t *
673 cairo_path_iterator_next (cairo_path_iterator_t *iterator);
675 cairo_path_element_type_t
676 cairo_path_element_get_type (cairo_path_element_t *element);
679 cairo_path_element_get_point (cairo_path_element_t *element,
685 The above is written using the Java conventions for
686 iterators. To illustrate how the API for PathIterator might
687 depend on the native iteration conventions of the API, examine
688 three versions of the loop, first written in a hypothetical Java
692 PathIterator iter = cr.copyPath().iterator();
693 while (cr.hasNext()) {
694 PathElement element = iter.next();
695 if (element.getType() == PathElementType.MOVE_TO) {
696 Point p = element.getPoint(0);
701 And then in a hypothetical C++ binding:
704 Path path = cr.copyPath();
705 for (PathIterator iter = path.begin(); iter != path.end(); iter++) {
706 PathElement element = *iter;
707 if (element.getType() == PathElementType.MOVE_TO) {
708 Point p = element.getPoint(0);
713 And then finally in a Python binding:
716 for element in cr.copy_path():
717 if element.getType == cairo.PATH_ELEMENT_MOVE_TO:
718 (x, y) = element.getPoint(0)
719 doMoveTo (x, y);</programlisting>
721 While many of the API elements stay the same in the three
722 examples, the exact iteration mechanism is quite different, to
723 match how users of the language would expect to iterate over
727 You should not present an API for mutating or for creating new
728 <type>cairo_path_t</type> objects. In the future, these
729 guidelines may be extended to present an API for creating a
730 <type>cairo_path_t</type> from scratch for use with
732 linkend="cairo-append-path"><function>cairo_append_path()</function></link>
733 but the current expectation is that <function>cairo_append_path()</function> will
734 mostly be used with paths from
736 linkend="cairo-append-path"><function>cairo_copy_path()</function></link>.
743 sgml-parent-document: ("cairo-docs.xml" "book" "book" "appendix")