Yes, it's definitely possible to embed an SDL2 application inside a GTK widget. This is a common approach for creating game level editors and other GUI applications that need SDL2's rendering capabilities alongside GTK's UI widgets.
Here are the main approaches:
Using SDL2's Window ID Hint
The most straightforward method is to create a GTK widget (typically a GtkDrawingArea or GtkGLArea) and then tell SDL2 to use that widget's native window handle:
c
// Get the native window handle from GTK
GdkWindow *gdk_window = gtk_widget_get_window(gtk_widget);
Window x11_window = GDK_WINDOW_XID(gdk_window); // For X11
// Create SDL window using the GTK widget's window
SDL_Window *window = SDL_CreateWindowFrom((void*)(intptr_t)x11_window);
You'll need to handle platform-specific window handles:
X11: Use GDK_WINDOW_XID()
Windows: Use GDK_WINDOW_HWND()
Wayland: More complex, may need gdk_wayland_window_get_wl_surface()
Using GtkGLArea with SDL2
Another approach is to use GtkGLArea for OpenGL rendering and share the context with SDL2:
c
// In your GtkGLArea render callback
SDL_GL_MakeCurrent(sdl_window, gl_context);
// Do your SDL2/OpenGL rendering
SDL_GL_SwapWindow(sdl_window);
Important Considerations
Event Handling: You'll need to carefully manage event handling between GTK and SDL2. Usually, you'll want GTK to handle UI events and forward relevant ones (like mouse/keyboard in the rendering area) to SDL2.
Threading: GTK and SDL2 both have their own event loops. You typically run GTK's main loop and use idle callbacks or timers to update SDL2 rendering.
Initialization Order: Initialize GTK first, create your widgets, then initialize SDL2 with the appropriate video driver hints.
Here's a minimal example structure:
c
// Initialize GTK
gtk_init(&argc, &argv);
// Create GTK window and drawing area
GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
GtkWidget *drawing_area = gtk_drawing_area_new();
gtk_container_add(GTK_CONTAINER(window), drawing_area);
// Show and realize widgets
gtk_widget_show_all(window);
// Initialize SDL2 with the drawing area's window
SDL_Init(SDL_INIT_VIDEO);
GdkWindow *gdk_window = gtk_widget_get_window(drawing_area);
SDL_Window *sdl_window = SDL_CreateWindowFrom((void*)GDK_WINDOW_XID(gdk_window));
SDL_Renderer *renderer = SDL_CreateRenderer(sdl_window, -1, SDL_RENDERER_ACCELERATED);
// Set up rendering callback
g_timeout_add(16, render_callback, renderer); // ~60 FPS
// Run GTK main loop
gtk_main();
This approach works well for level editors where you want SDL2's game rendering in the center with GTK toolbars, property panels, and menus around it. Many game engines and tools use similar techniques to combine their rendering engines with native UI toolkits.