#define _GNU_SOURCE

#include <unistd.h>
#include <errno.h>
#include <string.h>

#include "support.h"
#include "interface.h"
#include "perspic.h"

void
gtk_err(const char *file,const char *func,int line,
	const char *fmt,...) {

  static GtkWidget *d,*t;
  static char *v1,*v,*ve;
  char *vv;
  va_list args;
  int n;

  if (!fmt)
    return;

  if (!d && !(d=create_dialog1()))
    return;
  if (!t && !(t=lookup_widget(GTK_WIDGET(d),"text4")))
    return;
     
  v=v1;
  if (file && func && line) {
    l_str(v,"Error in file %s, function %s, line %d\n",file,func,line);
    if (errno) {
      l_str(v,strerror(errno));
      l_str(v,"\n");
      errno=0;
    }
  }
  va_start(args,fmt);
  if (vasprintf(&vv,fmt,args)<0)
    return;
  va_end(args);
  l_str(v,vv);
  free(vv);

  n=gtk_text_get_length(GTK_TEXT(t));
  gtk_text_set_point(GTK_TEXT(t),n);
  gtk_text_freeze(GTK_TEXT(t));
  gtk_text_insert(GTK_TEXT(t),NULL,NULL,NULL,v1,v-v1);
  gtk_text_thaw(GTK_TEXT(t));
  while (gtk_events_pending())
    gtk_main_iteration();
  gtk_adjustment_set_value(GTK_ADJUSTMENT(GTK_TEXT(t)->vadj),
			   (GTK_TEXT(t)->vadj->upper-GTK_TEXT(t)->vadj->lower)*
			   (gfloat)1.0 -
			   0.5*(GTK_TEXT(t)->vadj->page_size));

  gtk_widget_show(d);
  usleep(10000);

}


