#include <string.h>
#include <ctype.h>

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

static GdkFont *font;


void
text_write_text(GtkWidget *item,Hit *h) {

  GtkText *text;
  unsigned n,nl,tnl;
  const char *c;
  static GdkColormap *cmap;
  static GdkColor colour;
  float pos;

  if (!cmap) {

    cmap = gdk_colormap_get_system();
    colour.red = 0xffff;
    colour.green = 0;
    colour.blue = 0;
    if (!gdk_color_alloc(cmap, &colour)) {
      g_error("couldn't allocate colour");
    }

  }

  text=GTK_TEXT(lookup_widget(item,"text1"));
  n=gtk_text_get_length(text);
  gtk_text_set_point(text,0);
  gtk_text_forward_delete(text,n);
  gtk_text_freeze(text);
  if (!font)
    font=gdk_font_load("-adobe-times-medium-r-normal-*-*-120-*-*-m-*-iso8859-1");
  pos=0.0;
  if (h) {
    gtk_text_insert(text,font,NULL,NULL,h->b,h->l-h->b);
    for (c=h->l;*c && isspace(*c);c++);
    for (;*c && !isspace(*c);c++);
    gtk_text_insert(text,font,&colour,NULL,h->l,c-h->l);
    gtk_text_insert(text,font,NULL,NULL,c,h->be-c);
    for (c=h->b,nl=tnl=0;(c=strchr(c,10)) && c<h->be;c++,tnl++)
      if (c<h->l)
	nl++;
    pos = (float)nl/tnl;
  }
  gtk_object_set_data(GTK_OBJECT(text),"hit",h);
  gtk_text_thaw(text);
  while (gtk_events_pending())
    gtk_main_iteration();
  gtk_adjustment_set_value(GTK_ADJUSTMENT(GTK_TEXT(text)->vadj),
			   (GTK_TEXT(text)->vadj->upper-GTK_TEXT(text)->vadj->lower)*
			   pos -
			   0.5*(GTK_TEXT(text)->vadj->page_size));

}



void
text_set_font(GtkWidget *text,GdkFont *f) {

  static GdkFont *lfont;
  void *h;

  if (!font || !gdk_font_equal(font,f)) {
    
    if (lfont)
      gdk_font_unref(lfont);
    
    lfont=font=f;
    gdk_font_ref(lfont);

    h=gtk_object_get_data(GTK_OBJECT(text),"hit");
    text_write_text(text,h);

  }
  
}
