#include <gtk/gtk.h>

static void
clicked (GtkButton *button,
         gpointer   user_data)
{
  GdkScreen *screen;
  gint width;
  gint height;
  GdkWindow *root;
  GdkPixbuf *pixbuf;
  gchar *filename;

  screen = gdk_screen_get_default ();
  width = gdk_screen_get_width (screen);
  height = gdk_screen_get_height (screen);
  root = gdk_get_default_root_window ();

  pixbuf = gdk_pixbuf_get_from_window (root, 0, 0, width, height);

  filename = g_strdup_printf ("test-%ld", time(NULL));
  gdk_pixbuf_save (pixbuf, filename, "png", NULL, NULL);
  g_free (filename);

  g_object_unref (pixbuf);
}

static void
activate (GtkApplication *application,
          gpointer        user_data)
{
  GtkWidget *window;
  GtkWidget *button;

  window = gtk_application_window_new (application);

  gtk_window_set_title (GTK_WINDOW (window), "Window");
  gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);

  button = gtk_button_new_with_label ("Get pixbuf");
  gtk_container_add (GTK_CONTAINER (window), button);

  gtk_widget_set_halign (button, GTK_ALIGN_CENTER);
  gtk_widget_set_valign (button, GTK_ALIGN_CENTER);

  g_signal_connect (button, "clicked",
                    G_CALLBACK (clicked), NULL);

  gtk_widget_show_all (window);
}

int
main (int argc, char *argv[])
{
  GtkApplication *application;
  int status;

  application = gtk_application_new ("com.example.test-gdk-pixbuf-from-window",
                                     G_APPLICATION_FLAGS_NONE);

  g_signal_connect (application, "activate",
                    G_CALLBACK (activate), NULL);

  status = g_application_run (G_APPLICATION (application), argc, argv);
  g_object_unref (application);

  return status;
}
