/* Pawel Salek, pawsa@theochem.kth.se, 2001-08-22
   Program demonstrating bug in gnome_url_show() and related functions.
   Basically, gnome_url_show() will hang when the program creates ANY thread 
   (no matter if the thread has been detached, joined, or contiunes 
   execution).

   Wrong behavior observed with: gnome-libs-1.2.13-7
   Correct (no hang) behavior observed with: 
   COMPILE with:
   cc `gnome-config --cflags gnome` url-test.c \
   `gnome-config --libs gnomeui` -lgthread -o url-test
   EXECUTE:
   ./url-test
   no thread is created. Clicking on the button brings up given page.
   ./url-test n
   a thread is created and joined. Clicking on the button hangs the program.
   ./url-test f
   a thread is created and joined. A fork handlers are registered.
   Clicking on the button hangs the program. The fork handlers are not
   executed.
*/


#include <gnome.h>
#include <pthread.h>

#define PACKAGE "url-test"
#define VERSION "1.0.0"

void*
my_thread(void* data)
{
  printf("my_thread.\n");
}

void
press_cb(GtkWidget* w, const char* url)
{
  printf("press_cb\n");
  /* ERROR 1: This never exececutes the browser - and never returns
   * when there was at least one extra thread running. */
  gnome_url_show(url);
}

void
unlock_parent()
{
  printf("Unlocking parent\n");
}

void
unlock_child()
{
  printf("Unlocking child\n");
}

int main(int argc, char* argv[])
{
  const static char* the_url = "http://www.redhat.com/";
  GtkWidget* window, * button;
  pthread_t open_thread;
  void* ret;

  printf("gnomepthread tester. Give any parameter and a thread will be run.\n"
	 "If the parameter begins with letter 'f', fork handlers will be "
	 "installed.\n");
  g_thread_init(NULL);
  gnome_init(PACKAGE, VERSION, argc, argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  button = gtk_button_new_with_label(the_url);
  gtk_signal_connect(GTK_OBJECT(button), "pressed", press_cb,
		     (gpointer)the_url);
  gtk_signal_connect(GTK_OBJECT(window), "delete_event", gtk_main_quit, NULL);
  gtk_container_add(GTK_CONTAINER(window), button);
  gtk_widget_show_all(window);

  if(argc>1) {
    /* ERROR 2: the registered functions are never executed. */
    if(*argv[1] == 'f') {
      pthread_atfork(NULL, unlock_parent, unlock_child);
      printf("Fork handlers installed.\n");
    }
    pthread_create(&open_thread, NULL, my_thread, NULL);
    pthread_join(open_thread, &ret);
    printf("thread started.. and joined. Continuing...\n");
  } else printf("Starting without any threads.\n");
  gdk_threads_enter();
  gtk_main();
  gdk_threads_leave();

  return 0;
}
