The first call to SDL_GetWindowSurface causes the window to be reopened on Linux/X11

Below is the minimal example to reproduce the issue. I haven’t tested on other platforms, but on Linux/X11, the first call to SDL_GetWindowSurface causes the window to be reopened. I put getchar between the calls to make a clear distinction. From the second call and on doesn’t have any effect to the opened window.

// gcc -O3 `pkg-config sdl2 --cflags --libs` -otest test.c

#include <stdio.h>
#include <stdlib.h>
#include <SDL.h>

static void check_sdl(int ok) {
  if (!ok) {
    printf("error: %s", SDL_GetError());
    abort();
  }
}

int main(int argc, char **argv) {
  (void)argc, (void)argv;
  check_sdl(!SDL_Init(SDL_INIT_VIDEO));
  SDL_Window *w = SDL_CreateWindow("test", SDL_WINDOWPOS_UNDEFINED,
    SDL_WINDOWPOS_UNDEFINED, 500, 500, 0);
  check_sdl(!!w);
  getchar();
  check_sdl(!!SDL_GetWindowSurface(w));
  getchar();
  check_sdl(!!SDL_GetWindowSurface(w));
  SDL_Event e;
  while (SDL_WaitEvent(&e)) {
    if (e.type == SDL_QUIT) {
      SDL_DestroyWindow(w);
      SDL_Quit();
      return 0;
    }
  }
  check_sdl(0);
}

I did find a workaround, though. You can initially set SDL_WINDOW_HIDDEN, and call SDL_ShowWindow after the first SDL_GetWindowSurface.

I skimmed through SDL_x11framebuffer.c in the source. While I’m not familiar with the X11 API, maybe it’s because the initial SDL_GetWindowSurface resolves to a X11_CreateWindowFramebuffer which calls X11_DestroyWindowFramebuffer and then creates a new software framebuffer.

what happens if you use the example code here

The window gets opened twice.