1 /*! Simple Cairo/Xlib example.
2 * @author Bernhard R. Fischer, 2048R/5C5FFD47 <bf@abenteuerland.at>.
5 * gcc -Wall $(pkg-config --libs --cflags cairo x11) -o cairo_xlib_simple cairo_xlib_simple.c
10 /*! Check for Xlib Mouse/Keypress events. All other events are discarded.
11 * @param sfc Pointer to Xlib surface.
12 * @param block If block is set to 0, this function always returns immediately
13 * and does not block. if set to a non-zero value, the function will block
14 * until the next event is received.
15 * @return The function returns 0 if no event occured (and block is set). A
16 * positive value indicates that a key was pressed and the X11 key symbol as
17 * defined in <X11/keysymdef.h> is returned. A negative value indicates a mouse
18 * button event. -1 is button 1 (left button), -2 is the middle button, and -3
21 int cairo_check_event (cairo_surface_t
* sfc
, int block
) {
26 if (block ||
XPending(cairo_xlib_surface_get_display(sfc
))) XNextEvent(cairo_xlib_surface_get_display(sfc
), &e
); else return 0;
28 case ButtonPress
: return -e
.xbutton
.button
;
29 case KeyPress
: XLookupString(&e
.xkey
, keybuf
.ptr
, keybuf
.length
, &key
, null); return key
;
30 default: //fprintf(stderr, "Dropping unhandled XEevent.type = %d.\n", e.type);
36 /*! Open an X11 window and create a cairo surface base on that window.
37 * @param x Width of window.
38 * @param y Height of window.
39 * @return Returns a pointer to a valid Xlib cairo surface. The function does
40 * not return on error (exit(3)).
42 cairo_surface_t
* cairo_create_x11_surface0 (int x
, int y
) {
48 if ((dsp
= XOpenDisplay(null)) is null) assert(0, "can't open X11 display");
49 screen
= DefaultScreen(dsp
);
50 da = XCreateSimpleWindow(dsp
, DefaultRootWindow(dsp
), 0, 0, x
, y
, 0, 0, 0);
51 XSelectInput(dsp
, da, ButtonPressMask|KeyPressMask
);
54 sfc
= cairo_xlib_surface_create(dsp
, da, DefaultVisual(dsp
, screen
), x
, y
);
55 cairo_xlib_surface_set_size(sfc
, x
, y
);
61 /*! Destroy cairo Xlib surface and close X connection.
63 void cairo_close_x11_surface (cairo_surface_t
* sfc
) {
64 Display
*dsp
= cairo_xlib_surface_get_display(sfc
);
65 cairo_surface_destroy(sfc
);
74 sfc
= cairo_create_x11_surface0(500, 500);
76 ctx
= cairo_create(sfc
);
77 cairo_set_source_rgb(ctx
, 1, 1, 1);
79 cairo_move_to(ctx
, 20, 20);
80 cairo_line_to(ctx
, 200, 400);
81 cairo_line_to(ctx
, 450, 100);
82 cairo_line_to(ctx
, 20, 20);
83 cairo_set_source_rgb(ctx
, 0, 0, 1);
84 cairo_fill_preserve(ctx
);
85 cairo_set_line_width(ctx
, 5);
86 cairo_set_source_rgb(ctx
, 1, 1, 0);
90 cairo_check_event(sfc
, 1);
92 cairo_close_x11_surface(sfc
);