/* gcc -g `pkg-config --cflags --libs gtk+-3.0` gtktest.c */

#include <gtk/gtk.h>

static GtkWidget* gProtoWindow;
static GtkWidget* gProtoLayout;
static GtkWidget* gEntryWidget;

void cairo_debug(cairo_t *cr)
{
  static int count = 0;
  cairo_surface_t * tsurf = cairo_get_target(cr);
  if(cairo_surface_status(tsurf) == CAIRO_STATUS_SUCCESS) {
    char filename[500];
    sprintf(filename, "moz_widget-%.4d.png", count);
    cairo_surface_write_to_png(tsurf, filename);
  }
}

static void
moz_gtk_set_widget_name(GtkWidget* widget)
{   
    gtk_widget_set_name(widget, "MozillaGtkWidget");
}

static gint
ensure_window_widget()
{ 
    if (!gProtoWindow) {
        gProtoWindow = gtk_window_new(GTK_WINDOW_POPUP);
        gtk_widget_realize(gProtoWindow);
        moz_gtk_set_widget_name(gProtoWindow);
    }
    return TRUE;
}

static gint
setup_widget_prototype(GtkWidget* widget)
{
    ensure_window_widget();
    if (!gProtoLayout) {
        gProtoLayout = gtk_fixed_new();
        gtk_container_add(GTK_CONTAINER(gProtoWindow), gProtoLayout);
    }

    gtk_container_add(GTK_CONTAINER(gProtoLayout), widget);
    gtk_widget_realize(widget);
}

void
surface_test(void)
{
  cairo_surface_t *surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 1200, 600);
  cairo_t *cr = cairo_create (surface);

  if (!gEntryWidget) {
      gEntryWidget = gtk_entry_new();
      setup_widget_prototype(gEntryWidget);
  }

  // Set a cairo path which is used as a clipping area
  cairo_rectangle(cr,0,0,500,400);

  GtkStyleContext* style = gtk_widget_get_style_context(gEntryWidget);

  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_ENTRY);

  gtk_render_background(style, cr, 30, 40, 400, 32);
  gtk_render_frame(style, cr, 30, 40, 400, 32);

  gtk_style_context_restore(style);

  cairo_debug(cr);
}

int
main (int argc, char **argv)
{
  if (!gtk_parse_args (&argc, &argv))
    return 1;

  const char *display_name = gdk_get_display_arg_name();
  GdkDisplay *display = gdk_display_open(display_name);
  if (!display)
    return 1;

  gdk_display_manager_set_default_display (gdk_display_manager_get(), display);

  GtkWidget *win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  surface_test();

  return 0;
}
