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

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

static void
show_modal (GtkWidget *window)
{
	GMainLoop *loop;

	loop = g_main_loop_new (NULL, FALSE);

	g_signal_connect_swapped (window, "unmap", G_CALLBACK (g_main_loop_quit),  loop);
	g_signal_connect_swapped (window, "delete-event", G_CALLBACK (g_main_loop_quit),  loop);
	g_signal_connect_swapped (window, "destroy", G_CALLBACK (g_main_loop_quit),  loop);

	gtk_window_set_modal (GTK_WINDOW (window), TRUE);
	gtk_widget_show_all (window);

	g_main_loop_run (loop);
	g_main_loop_unref (loop);

	g_signal_handlers_disconnect_by_data (window, loop);
}

static gboolean
draw_into_layout (gpointer user_data)
{
	static gint at = -1;
	GtkLayout *layout = user_data;
	/*GtkAdjustment *adj;*/
	GdkWindow *window;
	guint w, h, x = 0, y = 0;
	cairo_t *cr;

	gtk_layout_get_size (layout, &w, &h);
	/*adj = gtk_layout_get_hadjustment (layout);
	x = gtk_adjustment_get_value (adj);
	adj = gtk_layout_get_vadjustment (layout);
	y = gtk_adjustment_get_value (adj);*/

	window = gtk_layout_get_bin_window (layout);
	cr = gdk_cairo_create (window);

	if (at == -1) {
		cairo_save (cr);
		cairo_set_source_rgb (cr, 1, 0.5, 0.0);
		cairo_move_to (cr, 0.5, 0.5);
		cairo_line_to (cr, w - 0.5, 0.5);
		cairo_line_to (cr, w - 0.5, h - 0.5);
		cairo_line_to (cr, 0.5, h - 0.5);
		cairo_line_to (cr, 0.5, 0.5);
		cairo_restore (cr);
	}

	at = (at + 1) % 15;

	#define draw(mlpt)	\
		cairo_set_source_rgb (cr, 1, 1, 1); \
		cairo_set_operator (cr, CAIRO_OPERATOR_DIFFERENCE); \
		cairo_set_line_cap (cr, CAIRO_LINE_CAP_SQUARE); \
		cairo_move_to (cr, (mlpt) * w / 15 + 0.5 + x, (mlpt) * h / 15 + 0.5 + y); \
		cairo_line_to (cr, ((mlpt) + 1) * w / 15 - 0.5 + x, ((mlpt) + 1) * h / 15 - 0.5 + y); \
		cairo_set_line_width (cr, 1); \
		cairo_stroke (cr);

	if (at == 0) {
		draw (at);
		at++;
	}

	draw (at - 1);
	draw (at);

	cairo_destroy (cr);

	return TRUE;
}

int main (int argc, char *argv[])
{
	GtkWidget *dialog, *widget, *into;
	GtkLayout *layout;

	gtk_init (&argc, &argv);

	dialog = gtk_window_new (GTK_WINDOW_TOPLEVEL);
	gtk_window_set_default_size (GTK_WINDOW (dialog), 320, 240);

	widget = gtk_scrolled_window_new (NULL, NULL);
	gtk_container_add (GTK_CONTAINER (dialog), widget);
	into = widget;

	widget = gtk_layout_new (NULL, NULL);
	gtk_container_add (GTK_CONTAINER (into), widget);
	layout = GTK_LAYOUT (widget);

	gtk_layout_set_size (GTK_LAYOUT (layout), 800, 600);
	gtk_adjustment_set_value (gtk_layout_get_hadjustment (layout), 100);
	gtk_adjustment_set_value (gtk_layout_get_vadjustment (layout), 100);

	g_timeout_add (50, draw_into_layout, layout);

	show_modal (dialog);

	gtk_widget_destroy (dialog);

	return 0;
}
