#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include "gtksocket.h"

#include <unistd.h>
#include <stdlib.h>

GtkWidget *vbox;

void
steal (GtkWidget *window, GtkEntry *entry)
{
  guint32 xid;
  gchar *text;
  GtkWidget *socket;

  text = gtk_entry_get_text (entry);

  xid = strtol (text, NULL, 0);
  if (xid == 0)
    {
      g_warning ("Invalid window id '%s'\n", text);
      return;
    }

  socket = gtk_socket_new ();
  gtk_box_pack_start (GTK_BOX (vbox), socket, TRUE, TRUE, 0);
  gtk_widget_show (socket);

  gtk_socket_steal (GTK_SOCKET (socket), xid);
}

void
add_child (GtkWidget *window)
{
  GtkWidget *socket;
  char buffer[20];
  int pid;

  socket = gtk_socket_new ();
  gtk_box_pack_start (GTK_BOX (vbox), socket, TRUE, TRUE, 0);
  gtk_widget_show (socket);

  sprintf(buffer, "%#lx", GDK_WINDOW_XWINDOW (socket->window));

  gdk_flush();

#if 1
  if ((pid = fork()) == 0)	/* child */
    {
      execl ("./testsocket_child", "./testsocket_child", buffer, NULL);
      fprintf(stderr, "can't exec child\n");
      _exit (1);
    }
  else if (pid > 0)		/* parent */
    {
    }
  else
    fprintf(stderr, "Can't fork\n");
#else
  fprintf(stderr,"%s\n", buffer);
#endif
}

int
main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *button;
  GtkWidget *hbox;
  GtkWidget *entry;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  gtk_signal_connect (GTK_OBJECT (window), "destroy",
		      (GtkSignalFunc) gtk_exit, NULL);
  gtk_window_set_title (GTK_WINDOW (window), "Socket Test");
  gtk_container_border_width (GTK_CONTAINER (window), 0);

  vbox = gtk_vbox_new (FALSE, 0);
  gtk_container_add (GTK_CONTAINER (window), vbox);
  gtk_widget_show (vbox);

  button = gtk_button_new_with_label ("Add Child");
  gtk_box_pack_start (GTK_BOX(vbox), button, FALSE, FALSE, 0);
  gtk_widget_show(button);

  gtk_signal_connect_object (GTK_OBJECT(button), "clicked",
			     GTK_SIGNAL_FUNC(add_child),
			     GTK_OBJECT(vbox));

  button = gtk_button_new_with_label ("Quit");
  gtk_box_pack_start (GTK_BOX(vbox), button, FALSE, FALSE, 0);
  gtk_widget_show(button);

  gtk_signal_connect_object (GTK_OBJECT(button), "clicked",
			     GTK_SIGNAL_FUNC(gtk_widget_destroy),
			     GTK_OBJECT(window));

  hbox = gtk_hbox_new (FALSE, 0);
  gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, FALSE, 0);
  gtk_widget_show(hbox);

  entry = gtk_entry_new ();
  gtk_box_pack_start (GTK_BOX(hbox), entry, FALSE, FALSE, 0);
  gtk_widget_show (entry);

  button = gtk_button_new_with_label ("Steal");
  gtk_box_pack_start (GTK_BOX(hbox), button, FALSE, FALSE, 0);
  gtk_widget_show(button);

  gtk_signal_connect (GTK_OBJECT(button), "clicked",
		      GTK_SIGNAL_FUNC(steal),
		      entry);

  gtk_widget_show (window);

  gtk_main ();

  return 0;
}


