0
# Constants and Enumerations
1
2
Cairo provides extensive enumeration types and constants that control drawing behavior, format specifications, and rendering options. These enumerations ensure type safety and provide meaningful names for Cairo's various modes and parameters.
3
4
## Capabilities
5
6
### Drawing and Rendering Enumerations
7
8
```python { .api }
9
class Antialias:
10
"""Antialiasing modes for rendering."""
11
DEFAULT: int = 0 # Use default antialiasing for subsystem and target device
12
NONE: int = 1 # Use bilevel alpha mask
13
GRAY: int = 2 # Perform single-color antialiasing using shades of gray
14
SUBPIXEL: int = 3 # Perform antialiasing by taking advantage of subpixel order
15
FAST: int = 4 # Hint to use speed over quality
16
GOOD: int = 5 # Hint to balance speed and quality
17
BEST: int = 6 # Hint to favor quality over speed
18
19
class Operator:
20
"""Compositing operators for blending operations."""
21
CLEAR: int = 0 # Clear destination layer
22
SOURCE: int = 1 # Replace destination with source
23
OVER: int = 2 # Draw source on top of destination (default)
24
IN: int = 3 # Draw source where there was destination content
25
OUT: int = 4 # Draw source where there was no destination content
26
ATOP: int = 5 # Draw source on top of destination content
27
DEST: int = 6 # Ignore source
28
DEST_OVER: int = 7 # Draw destination on top of source
29
DEST_IN: int = 8 # Leave destination only where source
30
DEST_OUT: int = 9 # Leave destination only where no source
31
DEST_ATOP: int = 10 # Leave destination on top of source content
32
XOR: int = 11 # Source and destination exclusive or
33
ADD: int = 12 # Source and destination are added
34
SATURATE: int = 13 # Like OVER but clamp to maximum
35
MULTIPLY: int = 14 # Source and destination multiplied
36
SCREEN: int = 15 # Source and destination complemented then multiplied
37
OVERLAY: int = 16 # Mix of MULTIPLY and SCREEN
38
DARKEN: int = 17 # Darker of source and destination
39
LIGHTEN: int = 18 # Lighter of source and destination
40
COLOR_DODGE: int = 19 # Brighten destination based on source
41
COLOR_BURN: int = 20 # Darken destination based on source
42
HARD_LIGHT: int = 21 # Mix of MULTIPLY and SCREEN based on source
43
SOFT_LIGHT: int = 22 # Softer version of HARD_LIGHT
44
DIFFERENCE: int = 23 # Absolute difference of source and destination
45
EXCLUSION: int = 24 # Similar to DIFFERENCE but lower contrast
46
HSL_HUE: int = 25 # Use hue of source with saturation and luminosity of destination
47
HSL_SATURATION: int = 26 # Use saturation of source
48
HSL_COLOR: int = 27 # Use hue and saturation of source
49
HSL_LUMINOSITY: int = 28 # Use luminosity of source
50
51
class FillRule:
52
"""Fill rules for determining interior of paths."""
53
WINDING: int = 0 # Non-zero winding rule (default)
54
EVEN_ODD: int = 1 # Even-odd rule
55
56
class LineCap:
57
"""Line cap styles for stroke endpoints."""
58
BUTT: int = 0 # Start/stop exactly at path endpoints (default)
59
ROUND: int = 1 # Circular arc with diameter equal to line width
60
SQUARE: int = 2 # Square end with width equal to line width
61
62
class LineJoin:
63
"""Line join styles for stroke corners."""
64
MITER: int = 0 # Sharp corner with miter limit (default)
65
ROUND: int = 1 # Circular arc joining path segments
66
BEVEL: int = 2 # Straight line connecting endpoints
67
68
class Filter:
69
"""Scaling filters for pattern sampling."""
70
FAST: int = 0 # Nearest-neighbor sampling
71
GOOD: int = 1 # Linear sampling (default)
72
BEST: int = 2 # Best available sampling algorithm
73
NEAREST: int = 3 # Nearest-neighbor sampling (same as FAST)
74
BILINEAR: int = 4 # Linear sampling (same as GOOD)
75
GAUSSIAN: int = 5 # Gaussian sampling
76
77
class Extend:
78
"""Pattern extend modes for areas outside pattern."""
79
NONE: int = 0 # Pixels outside pattern are transparent (default)
80
REPEAT: int = 1 # Pattern is tiled by repeating
81
REFLECT: int = 2 # Pattern is tiled by reflecting
82
PAD: int = 3 # Pattern is extended by repeating edge pixels
83
```
84
85
### Format and Content Enumerations
86
87
```python { .api }
88
class Format:
89
"""Pixel formats for image surfaces."""
90
INVALID: int = -1 # Invalid format
91
ARGB32: int = 0 # 32-bit ARGB (default for color images)
92
RGB24: int = 1 # 24-bit RGB
93
A8: int = 2 # 8-bit alpha channel only
94
A1: int = 3 # 1-bit alpha channel only
95
RGB16_565: int = 4 # 16-bit RGB in 5-6-5 format
96
RGB30: int = 5 # 30-bit RGB with 10 bits per component
97
RGB96F: int = 6 # 96-bit floating-point RGB (version 1.23+)
98
RGBA128F: int = 7 # 128-bit floating-point RGBA (version 1.23+)
99
100
@staticmethod
101
def stride_for_width(format: Format, width: int) -> int:
102
"""Calculate stride in bytes for given format and width."""
103
104
class Content:
105
"""Surface content types."""
106
COLOR: int = 0x1000 # Surface will hold color content only
107
ALPHA: int = 0x2000 # Surface will hold alpha content only
108
COLOR_ALPHA: int = 0x3000 # Surface will hold color and alpha content
109
```
110
111
### Font and Text Enumerations
112
113
```python { .api }
114
class FontSlant:
115
"""Font slant styles."""
116
NORMAL: int = 0 # Upright font (default)
117
ITALIC: int = 1 # Italic font
118
OBLIQUE: int = 2 # Oblique font
119
120
class FontWeight:
121
"""Font weight specifications."""
122
NORMAL: int = 0 # Normal weight (default)
123
BOLD: int = 1 # Bold weight
124
125
class HintStyle:
126
"""Font hinting styles."""
127
DEFAULT: int = 0 # Use default hint style for font backend and target
128
NONE: int = 1 # Do not hint outlines
129
SLIGHT: int = 2 # Hint outlines slightly for improved contrast
130
MEDIUM: int = 3 # Hint outlines with medium strength
131
FULL: int = 4 # Hint outlines to maximize contrast
132
133
class HintMetrics:
134
"""Font metrics hinting modes."""
135
DEFAULT: int = 0 # Hint metrics in default manner for target
136
OFF: int = 1 # Do not hint font metrics
137
ON: int = 2 # Hint font metrics
138
139
class SubpixelOrder:
140
"""Subpixel orders for LCD displays."""
141
DEFAULT: int = 0 # Use default subpixel order for target
142
RGB: int = 1 # Subpixels are arranged horizontally with red at left
143
BGR: int = 2 # Subpixels are arranged horizontally with blue at left
144
VRGB: int = 3 # Subpixels are arranged vertically with red at top
145
VBGR: int = 4 # Subpixels are arranged vertically with blue at top
146
147
class TextClusterFlags:
148
"""Text cluster direction flags."""
149
BACKWARD: int = 0x1 # Clusters represent text flowing backward
150
151
class ColorMode:
152
"""Color font rendering modes."""
153
DEFAULT: int = 0 # Use default color mode
154
NO_COLOR: int = 1 # Disable color font rendering
155
COLOR: int = 2 # Enable color font rendering
156
157
class Dither:
158
"""Dithering modes."""
159
NONE: int = 0 # No dithering
160
DEFAULT: int = 1 # Default dithering
161
FAST: int = 2 # Fast dithering
162
GOOD: int = 3 # Good quality dithering
163
BEST: int = 4 # Best quality dithering
164
```
165
166
### Path and Geometry Enumerations
167
168
```python { .api }
169
class PathDataType:
170
"""Path element types."""
171
MOVE_TO: int = 0 # Move to point
172
LINE_TO: int = 1 # Line to point
173
CURVE_TO: int = 2 # Cubic Bézier curve to point
174
CLOSE_PATH: int = 3 # Close current sub-path
175
176
class RegionOverlap:
177
"""Region overlap types."""
178
IN: int = 0 # Completely inside region
179
OUT: int = 1 # Completely outside region
180
PART: int = 2 # Partially overlaps region
181
```
182
183
### Surface-Specific Enumerations
184
185
```python { .api }
186
class PDFVersion:
187
"""PDF version constants."""
188
VERSION_1_4: int = 0 # PDF version 1.4
189
VERSION_1_5: int = 1 # PDF version 1.5
190
VERSION_1_6: int = 2 # PDF version 1.6 (version 1.23+)
191
VERSION_1_7: int = 3 # PDF version 1.7 (version 1.23+)
192
193
class PDFMetadata:
194
"""PDF metadata keys."""
195
TITLE: int = 0 # Document title
196
AUTHOR: int = 1 # Document author
197
SUBJECT: int = 2 # Document subject
198
KEYWORDS: int = 3 # Document keywords
199
CREATOR: int = 4 # Creating application
200
CREATE_DATE: int = 5 # Creation date
201
MOD_DATE: int = 6 # Modification date
202
203
class PDFOutlineFlags:
204
"""PDF outline item flags."""
205
OPEN: int = 1 # Outline item initially open
206
BOLD: int = 2 # Outline item text is bold
207
ITALIC: int = 4 # Outline item text is italic
208
209
class PSLevel:
210
"""PostScript language levels."""
211
LEVEL_2: int = 0 # PostScript Level 2
212
LEVEL_3: int = 1 # PostScript Level 3
213
214
class SVGVersion:
215
"""SVG version constants."""
216
VERSION_1_1: int = 0 # SVG version 1.1
217
VERSION_1_2: int = 1 # SVG version 1.2
218
219
class SVGUnit:
220
"""SVG unit types."""
221
USER: int = 0 # User units (default)
222
EM: int = 1 # Em units
223
EX: int = 2 # Ex units
224
PX: int = 3 # Pixel units
225
IN: int = 4 # Inch units
226
CM: int = 5 # Centimeter units
227
MM: int = 6 # Millimeter units
228
PT: int = 7 # Point units (1/72 inch)
229
PC: int = 8 # Pica units (12 points)
230
PERCENT: int = 9 # Percentage units
231
232
class ScriptMode:
233
"""Script recording modes."""
234
ASCII: int = 0 # Emit human-readable text
235
BINARY: int = 1 # Emit binary data
236
237
class SurfaceObserverMode:
238
"""Surface observer modes."""
239
NORMAL: int = 0 # Normal surface observation
240
RECORD_OPERATIONS: int = 1 # Record all drawing operations
241
242
class DeviceType:
243
"""Device types."""
244
DRM: int = 0 # DRM device
245
GL: int = 1 # OpenGL device
246
SCRIPT: int = 2 # Script recording device
247
XCB: int = 3 # XCB device
248
XLIB: int = 4 # Xlib device
249
XML: int = 5 # XML device
250
COGL: int = 6 # Cogl device
251
WIN32: int = 7 # Win32 device
252
INVALID: int = -1 # Invalid device type
253
254
class FontType:
255
"""Font face types."""
256
TOY: int = 0 # Toy font face
257
FT: int = 1 # FreeType font face
258
WIN32: int = 2 # Win32 font face
259
QUARTZ: int = 3 # Quartz font face
260
USER: int = 4 # User font face
261
DWRITE: int = 5 # DirectWrite font face
262
```
263
264
### Status and Error Enumerations
265
266
```python { .api }
267
class Status:
268
"""Cairo operation status codes."""
269
SUCCESS: int = 0 # No error has occurred
270
NO_MEMORY: int = 1 # Out of memory
271
INVALID_RESTORE: int = 2 # Context stack underflow
272
INVALID_POP_GROUP: int = 3 # No saved group to pop
273
NO_CURRENT_POINT: int = 4 # No current point defined
274
INVALID_MATRIX: int = 5 # Invalid matrix transformation
275
INVALID_STATUS: int = 6 # Invalid value for Status enum
276
NULL_POINTER: int = 7 # Null pointer
277
INVALID_STRING: int = 8 # Input string not valid UTF-8
278
INVALID_PATH_DATA: int = 9 # Input path data not valid
279
READ_ERROR: int = 10 # Error while reading from input stream
280
WRITE_ERROR: int = 11 # Error while writing to output stream
281
SURFACE_FINISHED: int = 12 # Target surface finished
282
SURFACE_TYPE_MISMATCH: int = 13 # Surface type not appropriate
283
PATTERN_TYPE_MISMATCH: int = 14 # Pattern type not appropriate
284
INVALID_CONTENT: int = 15 # Invalid value for Content enum
285
INVALID_FORMAT: int = 16 # Invalid value for Format enum
286
INVALID_VISUAL: int = 17 # Invalid value for Visual
287
FILE_NOT_FOUND: int = 18 # File not found
288
INVALID_DASH: int = 19 # Invalid value for dash setting
289
INVALID_DSC_COMMENT: int = 20 # Invalid DSC comment
290
INVALID_INDEX: int = 21 # Invalid index passed
291
CLIP_NOT_REPRESENTABLE: int = 22 # Clip region not representable
292
TEMP_FILE_ERROR: int = 23 # Error creating temporary file
293
INVALID_STRIDE: int = 24 # Invalid value for stride
294
FONT_TYPE_MISMATCH: int = 25 # Font type not appropriate
295
USER_FONT_IMMUTABLE: int = 26 # User font is immutable
296
USER_FONT_ERROR: int = 27 # Error in user font
297
NEGATIVE_COUNT: int = 28 # Negative number used where not allowed
298
INVALID_CLUSTERS: int = 29 # Invalid clusters
299
INVALID_SLANT: int = 30 # Invalid value for FontSlant enum
300
INVALID_WEIGHT: int = 31 # Invalid value for FontWeight enum
301
INVALID_SIZE: int = 32 # Invalid value for size
302
USER_FONT_NOT_IMPLEMENTED: int = 33 # User font method not implemented
303
DEVICE_TYPE_MISMATCH: int = 34 # Device type not appropriate
304
DEVICE_ERROR: int = 35 # Error in device
305
INVALID_MESH_CONSTRUCTION: int = 36 # Invalid mesh construction
306
DEVICE_FINISHED: int = 37 # Device finished
307
JBIG2_GLOBAL_MISSING: int = 38 # JBIG2 global segment missing
308
PNG_ERROR: int = 39 # PNG format error (version 1.18+)
309
FREETYPE_ERROR: int = 40 # FreeType error (version 1.18+)
310
WIN32_GDI_ERROR: int = 41 # Win32 GDI error (version 1.18+)
311
TAG_ERROR: int = 42 # PDF tagging error (version 1.18+)
312
DWRITE_ERROR: int = 43 # DirectWrite error (version 1.23+)
313
SVG_FONT_ERROR: int = 44 # SVG font error (version 1.25+)
314
```
315
316
### Version and Feature Constants
317
318
```python { .api }
319
# Version information
320
version: str # Pycairo version string
321
version_info: tuple[int, int, int] # Pycairo version tuple
322
323
CAIRO_VERSION: int # Cairo library version (encoded)
324
CAIRO_VERSION_STRING: str # Cairo library version string
325
CAIRO_VERSION_MAJOR: int # Cairo major version
326
CAIRO_VERSION_MINOR: int # Cairo minor version
327
CAIRO_VERSION_MICRO: int # Cairo micro version
328
329
# Feature availability flags
330
HAS_ATSUI_FONT: bool # ATSUI font backend available
331
HAS_FT_FONT: bool # FreeType font backend available
332
HAS_GLITZ_SURFACE: bool # Glitz surface backend available
333
HAS_IMAGE_SURFACE: bool # Image surface backend available
334
HAS_MIME_SURFACE: bool # MIME surface support available
335
HAS_PDF_SURFACE: bool # PDF surface backend available
336
HAS_PNG_FUNCTIONS: bool # PNG read/write functions available
337
HAS_PS_SURFACE: bool # PostScript surface backend available
338
HAS_QUARTZ_SURFACE: bool # Quartz surface backend available
339
HAS_RECORDING_SURFACE: bool # Recording surface backend available
340
HAS_SCRIPT_SURFACE: bool # Script surface backend available
341
HAS_SVG_SURFACE: bool # SVG surface backend available
342
HAS_TEE_SURFACE: bool # Tee surface backend available
343
HAS_USER_FONT: bool # User font backend available
344
HAS_WIN32_FONT: bool # Win32 font backend available
345
HAS_WIN32_SURFACE: bool # Win32 surface backend available
346
HAS_XCB_SURFACE: bool # XCB surface backend available
347
HAS_XLIB_SURFACE: bool # Xlib surface backend available
348
HAS_DWRITE_FONT: bool # DirectWrite font backend available
349
350
# Special constants
351
PDF_OUTLINE_ROOT: int # Root outline item ID for PDF
352
COLOR_PALETTE_DEFAULT: int # Default color palette index
353
354
# MIME type constants
355
MIME_TYPE_JPEG: str # JPEG MIME type
356
MIME_TYPE_PNG: str # PNG MIME type
357
MIME_TYPE_URI: str # URI MIME type
358
MIME_TYPE_UNIQUE_ID: str # Unique ID MIME type
359
MIME_TYPE_CCITT_FAX: str # CCITT FAX MIME type
360
MIME_TYPE_CCITT_FAX_PARAMS: str # CCITT FAX parameters MIME type
361
MIME_TYPE_EPS: str # EPS MIME type
362
MIME_TYPE_EPS_PARAMS: str # EPS parameters MIME type
363
364
# Tag constants
365
TAG_DEST: str # Destination tag
366
TAG_LINK: str # Link tag
367
TAG_CONTENT: str # Content tag
368
TAG_CONTENT_REF: str # Content reference tag
369
370
# MIME type constants
371
MIME_TYPE_JPEG: str = "image/jpeg" # JPEG format
372
MIME_TYPE_PNG: str = "image/png" # PNG format
373
MIME_TYPE_JP2: str = "image/jp2" # JPEG 2000 format
374
MIME_TYPE_URI: str = "text/x-uri" # URI for image file
375
MIME_TYPE_UNIQUE_ID: str = "application/x-cairo.uuid" # Unique surface identifier
376
MIME_TYPE_CCITT_FAX: str = "image/g3fax" # CCITT fax encoding
377
MIME_TYPE_CCITT_FAX_PARAMS: str = "application/x-cairo.ccitt.params" # CCITT fax parameters
378
MIME_TYPE_EPS: str = "application/postscript" # Encapsulated PostScript
379
MIME_TYPE_EPS_PARAMS: str = "application/x-cairo.eps.params" # EPS parameters
380
MIME_TYPE_JBIG2: str = "application/x-cairo.jbig2" # JBIG2 format
381
MIME_TYPE_JBIG2_GLOBAL: str = "application/x-cairo.jbig2-global" # JBIG2 global segment
382
MIME_TYPE_JBIG2_GLOBAL_ID: str = "application/x-cairo.jbig2-global-id" # JBIG2 identifier
383
384
# Tag constants
385
TAG_DEST: str = "cairo.dest" # Hyperlink destination tag
386
TAG_LINK: str = "Link" # Hyperlink tag
387
TAG_CONTENT: str = "cairo.content" # Content tag
388
TAG_CONTENT_REF: str = "cairo.content_ref" # Content reference tag
389
390
# C API interface
391
CAPI: Any # C API interface object
392
```
393
394
## Usage Examples
395
396
### Working with Enumerations
397
398
```python
399
import cairo
400
401
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
402
ctx = cairo.Context(surface)
403
404
# Using operator enums
405
operators = [
406
cairo.OPERATOR_OVER,
407
cairo.OPERATOR_MULTIPLY,
408
cairo.OPERATOR_SCREEN,
409
cairo.OPERATOR_OVERLAY,
410
cairo.OPERATOR_DARKEN,
411
cairo.OPERATOR_LIGHTEN
412
]
413
414
# Draw rectangles with different operators
415
ctx.set_source_rgb(0.8, 0.2, 0.2)
416
ctx.rectangle(50, 50, 100, 80)
417
ctx.fill()
418
419
for i, op in enumerate(operators):
420
ctx.set_operator(op)
421
ctx.set_source_rgba(0.2, 0.2, 0.8, 0.7)
422
ctx.rectangle(100 + i * 30, 70, 60, 60)
423
ctx.fill()
424
425
# Reset operator
426
ctx.set_operator(cairo.OPERATOR_OVER)
427
428
surface.write_to_png("operators.png")
429
```
430
431
### Line Styles and Caps
432
433
```python
434
import cairo
435
436
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
437
ctx = cairo.Context(surface)
438
439
ctx.set_source_rgb(1, 1, 1)
440
ctx.paint()
441
442
# Line cap styles
443
line_caps = [
444
(cairo.LINE_CAP_BUTT, "BUTT"),
445
(cairo.LINE_CAP_ROUND, "ROUND"),
446
(cairo.LINE_CAP_SQUARE, "SQUARE")
447
]
448
449
ctx.set_source_rgb(0, 0, 0)
450
ctx.set_line_width(20)
451
452
y = 50
453
for cap, name in line_caps:
454
ctx.set_line_cap(cap)
455
ctx.move_to(50, y)
456
ctx.line_to(200, y)
457
ctx.stroke()
458
459
# Label
460
ctx.save()
461
ctx.set_line_width(1)
462
ctx.select_font_face("Arial")
463
ctx.set_font_size(12)
464
ctx.move_to(220, y + 5)
465
ctx.show_text(name)
466
ctx.restore()
467
468
y += 40
469
470
# Line join styles
471
line_joins = [
472
(cairo.LINE_JOIN_MITER, "MITER"),
473
(cairo.LINE_JOIN_ROUND, "ROUND"),
474
(cairo.LINE_JOIN_BEVEL, "BEVEL")
475
]
476
477
x = 50
478
for join, name in line_joins:
479
ctx.set_line_join(join)
480
ctx.set_line_width(15)
481
482
# Draw angle
483
ctx.move_to(x, 200)
484
ctx.line_to(x + 30, 160)
485
ctx.line_to(x + 60, 200)
486
ctx.stroke()
487
488
# Label
489
ctx.save()
490
ctx.set_line_width(1)
491
ctx.move_to(x, 220)
492
ctx.show_text(name)
493
ctx.restore()
494
495
x += 100
496
497
surface.write_to_png("line_styles.png")
498
```
499
500
### Fill Rules
501
502
```python
503
import cairo
504
505
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 500, 300)
506
ctx = cairo.Context(surface)
507
508
ctx.set_source_rgb(1, 1, 1)
509
ctx.paint()
510
511
# Create self-intersecting path
512
def create_star_path(ctx, x, y, size):
513
ctx.move_to(x, y - size)
514
ctx.line_to(x + size * 0.3, y + size * 0.8)
515
ctx.line_to(x - size * 0.8, y - size * 0.3)
516
ctx.line_to(x + size * 0.8, y - size * 0.3)
517
ctx.line_to(x - size * 0.3, y + size * 0.8)
518
ctx.close_path()
519
520
# Even-odd fill rule
521
ctx.save()
522
ctx.translate(120, 150)
523
create_star_path(ctx, 0, 0, 80)
524
ctx.set_fill_rule(cairo.FILL_RULE_EVEN_ODD)
525
ctx.set_source_rgb(0.8, 0.2, 0.2)
526
ctx.fill()
527
ctx.restore()
528
529
# Winding fill rule
530
ctx.save()
531
ctx.translate(350, 150)
532
create_star_path(ctx, 0, 0, 80)
533
ctx.set_fill_rule(cairo.FILL_RULE_WINDING)
534
ctx.set_source_rgb(0.2, 0.2, 0.8)
535
ctx.fill()
536
ctx.restore()
537
538
# Labels
539
ctx.set_source_rgb(0, 0, 0)
540
ctx.select_font_face("Arial")
541
ctx.set_font_size(14)
542
ctx.move_to(60, 260)
543
ctx.show_text("EVEN_ODD")
544
ctx.move_to(300, 260)
545
ctx.show_text("WINDING")
546
547
surface.write_to_png("fill_rules.png")
548
```
549
550
### Format and Feature Detection
551
552
```python
553
import cairo
554
555
# Check available features
556
print("Available Cairo features:")
557
features = [
558
("Image Surface", cairo.HAS_IMAGE_SURFACE),
559
("PDF Surface", cairo.HAS_PDF_SURFACE),
560
("SVG Surface", cairo.HAS_SVG_SURFACE),
561
("PS Surface", cairo.HAS_PS_SURFACE),
562
("PNG Functions", cairo.HAS_PNG_FUNCTIONS),
563
("FreeType Fonts", cairo.HAS_FT_FONT),
564
("Win32 Fonts", cairo.HAS_WIN32_FONT),
565
("Win32 Surface", cairo.HAS_WIN32_SURFACE),
566
("User Fonts", cairo.HAS_USER_FONT),
567
("Script Surface", cairo.HAS_SCRIPT_SURFACE),
568
("Recording Surface", cairo.HAS_RECORDING_SURFACE),
569
("Tee Surface", cairo.HAS_TEE_SURFACE),
570
("DirectWrite Fonts", cairo.HAS_DWRITE_FONT)
571
]
572
573
for name, available in features:
574
status = "✓" if available else "✗"
575
print(f" {status} {name}")
576
577
# Version information
578
print(f"\nVersion information:")
579
print(f" Pycairo version: {cairo.version}")
580
print(f" Pycairo version info: {cairo.version_info}")
581
print(f" Cairo version: {cairo.CAIRO_VERSION_STRING}")
582
print(f" Cairo version components: {cairo.CAIRO_VERSION_MAJOR}.{cairo.CAIRO_VERSION_MINOR}.{cairo.CAIRO_VERSION_MICRO}")
583
584
# Format information
585
formats = [
586
("ARGB32", cairo.FORMAT_ARGB32),
587
("RGB24", cairo.FORMAT_RGB24),
588
("A8", cairo.FORMAT_A8),
589
("A1", cairo.FORMAT_A1),
590
("RGB16_565", cairo.FORMAT_RGB16_565),
591
("RGB30", cairo.FORMAT_RGB30)
592
]
593
594
print(f"\nSupported formats:")
595
for name, format_val in formats:
596
# Calculate stride for 100px width
597
stride = cairo.ImageSurface.format_stride_for_width(format_val, 100)
598
print(f" {name}: stride for 100px = {stride} bytes")
599
600
# Create surfaces with different formats
601
surface_argb32 = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
602
surface_rgb24 = cairo.ImageSurface(cairo.FORMAT_RGB24, 100, 100)
603
surface_a8 = cairo.ImageSurface(cairo.FORMAT_A8, 100, 100)
604
605
print(f"\nSurface properties:")
606
print(f" ARGB32 surface: {surface_argb32.get_width()}x{surface_argb32.get_height()}, stride={surface_argb32.get_stride()}")
607
print(f" RGB24 surface: {surface_rgb24.get_width()}x{surface_rgb24.get_height()}, stride={surface_rgb24.get_stride()}")
608
print(f" A8 surface: {surface_a8.get_width()}x{surface_a8.get_height()}, stride={surface_a8.get_stride()}")
609
```
610
611
### Using Status and Error Handling
612
613
```python
614
import cairo
615
616
try:
617
# Create surface
618
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 400, 300)
619
ctx = cairo.Context(surface)
620
621
# Try to create an invalid matrix
622
matrix = cairo.Matrix(1, 0, 0, 0, 0, 0) # Singular matrix
623
624
try:
625
matrix.invert()
626
print("Matrix inversion succeeded")
627
except cairo.Error as e:
628
print(f"Matrix inversion failed: {e}")
629
630
# Try to use invalid path data
631
try:
632
# This should work fine
633
ctx.move_to(50, 50)
634
ctx.line_to(100, 100)
635
path = ctx.copy_path()
636
637
# Use the path
638
ctx.new_path()
639
ctx.append_path(path)
640
ctx.stroke()
641
642
print("Path operations succeeded")
643
644
except cairo.Error as e:
645
print(f"Path operation failed: {e}")
646
647
# Try to read a non-existent PNG
648
try:
649
invalid_surface = cairo.ImageSurface.create_from_png("nonexistent.png")
650
print("PNG loading succeeded")
651
except cairo.Error as e:
652
print(f"PNG loading failed: {e}")
653
654
surface.write_to_png("error_handling.png")
655
print("Surface write succeeded")
656
657
except cairo.Error as e:
658
print(f"Cairo error: {e}")
659
except Exception as e:
660
print(f"Other error: {e}")
661
```
662
663
### Constants in Practice
664
665
```python
666
import cairo
667
668
# Using MIME type constants
669
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 200, 200)
670
ctx = cairo.Context(surface)
671
672
# Draw something
673
ctx.set_source_rgb(0.8, 0.2, 0.2)
674
ctx.rectangle(50, 50, 100, 100)
675
ctx.fill()
676
677
# Attach MIME data (conceptual example)
678
# In practice, you would have actual image data
679
example_data = b"example image data"
680
surface.set_mime_data(cairo.MIME_TYPE_PNG, example_data)
681
682
# Check if MIME type is supported
683
png_supported = surface.supports_mime_type(cairo.MIME_TYPE_PNG)
684
jpeg_supported = surface.supports_mime_type(cairo.MIME_TYPE_JPEG)
685
686
print(f"PNG MIME support: {png_supported}")
687
print(f"JPEG MIME support: {jpeg_supported}")
688
689
# Using tag constants in PDF (conceptual)
690
if cairo.HAS_PDF_SURFACE:
691
pdf_surface = cairo.PDFSurface("tagged.pdf", 400, 300)
692
pdf_ctx = cairo.Context(pdf_surface)
693
694
# These would be used with PDF tagging operations
695
print(f"Available tags: {cairo.TAG_DEST}, {cairo.TAG_LINK}, {cairo.TAG_CONTENT}")
696
697
pdf_surface.finish()
698
699
# Using special constants
700
print(f"PDF outline root: {cairo.PDF_OUTLINE_ROOT}")
701
print(f"Default color palette: {cairo.COLOR_PALETTE_DEFAULT}")
702
703
surface.write_to_png("constants_demo.png")
704
```