/* GTK - Mini Spell checker
 * Copyright (C) 1997 Paolo Molaro
 * This is GPL'ed software.
*/

#include <gtk/gtk.h>
#include "gtkspell.h"
#include <string.h>

static int correction = 0;
static GtkSpell* spell = NULL;

static void 
test_quit() {
	gtk_exit(0);
}

static void
test_check(GtkButton* b, GtkEntry* entry) {
	correction = 0;
	gtk_spell_check(spell, gtk_entry_get_text(entry));
}

static void
test_replace(GtkSpell* spell, GtkSpellInfo* sinfo, GtkEntry* entry) {
	gchar *buf;
	gint diff;
	gchar* s;
	
	if ( !sinfo->replacement )
		return;

	s = gtk_entry_get_text(entry);

	diff = strlen(sinfo->replacement) - strlen(sinfo->word);
	buf = alloca(strlen(s)+diff+1);

	memcpy(buf, s, sinfo->offset+correction);
	strcpy(buf+sinfo->offset+correction, sinfo->replacement);
	strcat(buf, s+sinfo->offset+correction+strlen(sinfo->word));
	gtk_entry_set_text(entry, buf);
	correction += diff;
}

int main(int argc, char* argv[]) {
	GtkWidget * mainw;
	GtkWidget * vbox;
	GtkWidget * entry;
	GtkWidget * button;
	GtkWidget* misc;
	
	gtk_init(&argc, &argv);
	gtk_rc_parse("gtkrc");

	mainw = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	vbox = gtk_vbox_new(FALSE, 10);
	gtk_widget_show(vbox);
	gtk_container_add(GTK_CONTAINER(mainw), vbox);
	spell = GTK_SPELL(gtk_spell_new());
	gtk_widget_show(GTK_WIDGET(spell));
	gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(spell));
	misc = gtk_hseparator_new();
	gtk_widget_show(misc);
	gtk_container_add(GTK_CONTAINER(vbox), misc);
	misc = gtk_label_new("Insert the words to spell-check:");
	gtk_widget_show(misc);
	gtk_container_add(GTK_CONTAINER(vbox), misc);
	entry = gtk_entry_new();
	gtk_widget_show(entry);
	gtk_container_add(GTK_CONTAINER(vbox), entry);
	button = gtk_button_new_with_label("Spell-check");
	gtk_widget_show(button);
	GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
	gtk_widget_grab_default(button);
	gtk_container_add(GTK_CONTAINER(vbox), button);
	gtk_signal_connect(GTK_OBJECT(button), "clicked", 
		(GtkSignalFunc)test_check, entry);
	button = gtk_button_new_with_label("Quit");
	gtk_widget_show(button);
	gtk_container_add(GTK_CONTAINER(vbox), button);
	gtk_widget_show(mainw);

	gtk_signal_connect(GTK_OBJECT(mainw), "destroy", 
		(GtkSignalFunc)test_quit, NULL);
	gtk_signal_connect(GTK_OBJECT(mainw), "delete_event", 
		(GtkSignalFunc)test_quit, NULL);
	gtk_signal_connect(GTK_OBJECT(button), "clicked", 
		(GtkSignalFunc)test_quit, NULL);
	gtk_signal_connect(GTK_OBJECT(spell), "handled_word", 
		(GtkSignalFunc)test_replace, entry);

	gtk_main();
	return 0;
}

