/* gcc `pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.0` test-wk2.c -g -O0 -o test-wk2 && ./test-wk2 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <webkit2/webkit2.h>

static GTimer *timer = NULL;

static void
ready_to_show_cb (WebKitWebView *web_view,
		  gpointer user_data)
{
	printf ("%s: after %gs\n", __FUNCTION__, g_timer_elapsed (timer, NULL));
}

static void
load_changed_cb (WebKitWebView *web_view,
		 WebKitLoadEvent load_event,
		 gpointer user_data)
{
	printf ("%s: %s after %gs\n", __FUNCTION__,
		load_event == WEBKIT_LOAD_STARTED ? "WEBKIT_LOAD_STARTED" :
		load_event == WEBKIT_LOAD_REDIRECTED ? "WEBKIT_LOAD_REDIRECTED" :
		load_event == WEBKIT_LOAD_COMMITTED ? "WEBKIT_LOAD_COMMITTED" :
		load_event == WEBKIT_LOAD_FINISHED ? "WEBKIT_LOAD_FINISHED" : "???",
		g_timer_elapsed (timer, NULL));
}

static void
print_preview_cb (GtkWidget *button,
		  WebKitWebView *web_view)
{
	WebKitPrintOperation *prn;

	prn = webkit_print_operation_new (web_view);
	webkit_print_operation_run_dialog (prn, NULL);
	g_object_unref (prn);
}

int main (int argc, char *argv[])
{
	GtkWidget *dialog, *container, *wk, *btn;
	WebKitSettings *settings;

	gtk_init (&argc, &argv);

	dialog = gtk_dialog_new_with_buttons ("test-wk2", NULL, 0, "_Cancel", GTK_RESPONSE_CANCEL, NULL);
	gtk_window_set_default_size (GTK_WINDOW (dialog), 640, 480);

	container = gtk_dialog_get_content_area (GTK_DIALOG (dialog));

	btn = gtk_button_new_with_mnemonic ("_Print preview");
	gtk_widget_show (btn);
	gtk_container_add (GTK_CONTAINER (container), btn);

	wk = webkit_web_view_new ();

	g_signal_connect (btn, "clicked", G_CALLBACK (print_preview_cb), wk);

	settings = webkit_web_view_get_settings (WEBKIT_WEB_VIEW (wk));

	webkit_settings_set_enable_frame_flattening (settings, TRUE);

	gtk_container_add (GTK_CONTAINER (container), wk);
	g_object_set (G_OBJECT (wk),
		"hexpand", TRUE,
		"halign", GTK_ALIGN_FILL,
		"vexpand", TRUE,
		"valign", GTK_ALIGN_FILL,
		"height-request", 90,
		"width-request", 90,
		NULL);

	timer = g_timer_new ();
	g_signal_connect (wk, "ready-to-show", G_CALLBACK (ready_to_show_cb), NULL);
	g_signal_connect (wk, "load-changed", G_CALLBACK (load_changed_cb), NULL);
	webkit_web_view_load_uri (WEBKIT_WEB_VIEW (wk), "http://www.webkitgtk.org");

	gtk_widget_show_all (gtk_dialog_get_content_area (GTK_DIALOG (dialog)));
	gtk_dialog_run (GTK_DIALOG (dialog));

	gtk_widget_destroy (dialog);
	g_timer_destroy (timer);

	return 0;
}
