#include <gtk/gtk.h>
#include "gtkmozarea.h"
#include "gtkmozbox.h"
#include "gdksuperwin.h"

GtkWidget *mozarea;
gint x_offset = 0;
gint y_offset = 0;

#define MYMOD(i,m) (((i)%(m))>=0 ? (i)%(m) : ((i)%(m))+(m))
#define MYDIV(i,m) ((i)>=0 ? (i)/(m) : ((i)-(m)+1)/(m))

static void
superwin_event (GdkSuperWin *superwin, XEvent *event, gpointer data)
{
  gint i,j;
  gint imin, imax, jmin, jmax;
  
  switch (event->xany.type)
    {
    case Expose:
      imin = MYDIV (x_offset + event->xexpose.x, 10);
      imax = MYDIV (x_offset + event->xexpose.x + event->xexpose.width + 9, 10);
      
      jmin = MYDIV (y_offset + event->xexpose.y, 10);
      jmax = MYDIV (y_offset + event->xexpose.y + event->xexpose.height + 9, 10);

      gdk_draw_rectangle (superwin->bin_window,
			  mozarea->style->white_gc, TRUE,
			  event->xexpose.x, event->xexpose.y,
			  event->xexpose.width, event->xexpose.height);
      
      for (i=imin; i<imax; i++)
	for (j=jmin; j<jmax; j++)
	  if ((i+j) % 2)
	    gdk_draw_rectangle (superwin->bin_window, 
				mozarea->style->black_gc,
				TRUE,
				10*i - x_offset, 10*j - y_offset, 1+MYMOD(i,10), 1+1+MYMOD(j,10));
    }
}

GdkWindow *create_window ()
{
  GdkWindow *window;
  GdkWindowAttr attributes;
  guint attributes_mask;

  attributes.window_type = GDK_WINDOW_CHILD;
  attributes.width = 200;
  attributes.height = 200;
  attributes.wclass = GDK_INPUT_OUTPUT;
  attributes.event_mask = GDK_EXPOSURE_MASK;
  attributes_mask = 0;

  window = gdk_window_new (NULL, &attributes, attributes_mask);
  return window;
}

static gboolean
change_timeout (gpointer data)
{
  static guint count = 10;
  GtkWidget *button = data;
  gint dx, dy;
  
  gchar *label = g_strdup_printf ("Button %u", count++);
  gtk_label_set_text (GTK_LABEL (GTK_BIN (button)->child), label);
  g_free (label);

  dx = (count / 100) % 2 ? -1 : 1;
  dy = (count / 50) % 2 ? -1 : 1;
  
  gdk_superwin_scroll (GTK_MOZAREA(mozarea)->superwin, dx, dy);
  x_offset -= dx;
  y_offset -= dy;
  
  return TRUE;
}

int main (int argc, char **argv)
{
  GtkWidget *mozboxes[10];
  GtkWidget *button;
  GtkWidget *window;
  gchar *label;
  int i;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  mozarea = gtk_mozarea_new ();
  gtk_container_add (GTK_CONTAINER (window), mozarea);
  gtk_widget_realize (mozarea);

  gdk_superwin_set_event_func (GTK_MOZAREA(mozarea)->superwin, superwin_event, NULL, NULL);
  
  for (i=0; i<10; i++)
    {
      mozboxes[i] = gtk_mozbox_new (GTK_MOZAREA(mozarea)->superwin->bin_window);
      label = g_strdup_printf ("Button %d", i);
      
      gtk_mozbox_set_position (GTK_MOZBOX (mozboxes[i]), i*15, i*15);
      button = gtk_button_new_with_label (label);
      gtk_container_add (GTK_CONTAINER (mozboxes[i]), button);

      g_free (label);

      gtk_widget_show_all (mozboxes[i]);
    }
  
  gtk_widget_show_all (window);
  gtk_timeout_add (100, change_timeout, button);
  gtk_main();

  return 0;
}
