package entrycompletion;

import org.gnu.gtk.DataColumn;
import org.gnu.gtk.DataColumnString;
import org.gnu.gtk.Dialog;
import org.gnu.gtk.Entry;
import org.gnu.gtk.EntryCompletion;
import org.gnu.gtk.Gtk;
import org.gnu.gtk.Label;
import org.gnu.gtk.ListStore;
import org.gnu.gtk.TreeIter;
import org.gnu.gtk.TreeModel;
import org.gnu.gtk.VBox;
import org.gnu.gtk.event.LifeCycleEvent;
import org.gnu.gtk.event.LifeCycleListener;

/**
 * EntryCompletion provides a mechanism for adding support for completion in
 * Entry.
 */
public class EntryCompletionExample {

    public EntryCompletionExample() {
        Dialog dialog = new Dialog();
        dialog.addButton("Close", 0);
        dialog.setResizable(false);
        dialog.addListener(new LifeCycleListener() {
            public void lifeCycleEvent(LifeCycleEvent event) {
            }

            public boolean lifeCycleQuery(LifeCycleEvent event) {
                if (event.isOfType(LifeCycleEvent.Type.DESTROY)
                        || event.isOfType(LifeCycleEvent.Type.DELETE)) {
                    Gtk.mainQuit();
                }
                return true;
            }
        });

        VBox vbox = new VBox(false, 5);
        dialog.getDialogLayout().packStart(vbox, true, true, 0);
        vbox.setBorderWidth(5);

        Label label = new Label("");
        label
                .setMarkup("Completion demo, try writing <b>total</b> or <b>gnome</b> for example.");
        vbox.packStart(label, false, false, 0);

        Entry entry = new Entry();
        vbox.packStart(entry, false, false, 0);

        EntryCompletion completion = new EntryCompletion();
        entry.setCompletion(completion);

        TreeModel completionModel = createCompletionModel();
        completion.setModel(completionModel);
        completion.setTextColumn(0);

        dialog.showAll();
        dialog.run();
        dialog.destroy();
    }

    private TreeModel createCompletionModel() {
        DataColumnString s1 = new DataColumnString();

        ListStore list = new ListStore(new DataColumn[] { s1 });

        TreeIter iter = list.appendRow();
        list.setValue(iter, s1, "GNOME");

        iter = list.appendRow();
        list.setValue(iter, s1, "total");

        iter = list.appendRow();
        list.setValue(iter, s1, "totally");

        return list;
    }

    public static void main(String[] args) {
        // Initialize GTK
        Gtk.init(args);

        EntryCompletionExample example = new EntryCompletionExample();

        Gtk.main();
    }
}
