Skip to content

Instantly share code, notes, and snippets.

@tobyp
Created November 21, 2020 11:40
Show Gist options
  • Save tobyp/a4cb297c866fe53cc044467c9a866457 to your computer and use it in GitHub Desktop.
Save tobyp/a4cb297c866fe53cc044467c9a866457 to your computer and use it in GitHub Desktop.
Minimal GLFW+Cairo+Xlib example
//gcc $(pkg-config --cflags --libs glfw3 cairo) glfw-cairo-xlib.c
#include <math.h>
#include <stdio.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <GLFW/glfw3.h>
#define GLFW_EXPOSE_NATIVE_X11
#include <GLFW/glfw3native.h>
int main(int argc, char * argv[]) {
/* Initialize the library */
if (!glfwInit())
return -1;
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow * window = glfwCreateWindow(800, 600, "Test", NULL, NULL);
if (!window) {
glfwTerminate();
return -1;
}
glfwSwapInterval(1);
int fb_w, fb_h;
glfwGetFramebufferSize(window, &fb_w, &fb_h);
Display * x11_display = glfwGetX11Display();
Window x11_window = glfwGetX11Window(window);
Visual * vis = DefaultVisual(x11_display, DefaultScreen(x11_display));
cairo_surface_t * surface = cairo_xlib_surface_create(x11_display, x11_window, vis, fb_w, fb_h);
cairo_t * ctx = cairo_create(surface);
while (!glfwWindowShouldClose(window)) {
// on framebuffer size change, resize the surface
glfwGetFramebufferSize(window, &fb_w, &fb_h);
cairo_xlib_surface_set_size(surface, fb_w, fb_h);
// have to group, else the x server does weird queueing
cairo_push_group(ctx);
//clear
cairo_set_source_rgb(ctx, 1.0, 0.0, 0.0);
cairo_set_operator(ctx, CAIRO_OPERATOR_SOURCE);
cairo_paint(ctx);
// RENDER HERE
// ungroup and actually display
cairo_pop_group_to_source(ctx);
cairo_paint(ctx);
cairo_surface_flush(surface);
glfwSwapBuffers(window);
glfwPollEvents();
glfwSetWindowShouldClose(window, 1);
}
cairo_destroy(ctx);
cairo_surface_finish(surface);
cairo_surface_destroy(surface);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment