/*
 * compile with:
 * gcc -o combo `pkg-config --cflags --libs gtk+-3.0` combo.c
 */

#include <gtk/gtk.h>

static GtkTreeModel *
two_line_model (const gchar * line1, const gchar * line2)
{
  GtkListStore *store = gtk_list_store_new (1, G_TYPE_STRING);
  GtkTreeIter iter;

  gtk_list_store_append (store, &iter);
  gtk_list_store_set (store, &iter, 0, line1, -1);
  gtk_list_store_append (store, &iter);
  gtk_list_store_set (store, &iter, 0, line2, -1);

  return GTK_TREE_MODEL (store);
}

static void
edited_cb (GtkCellRendererText * cell, const gchar * path_string,
	   const gchar * new_text, GtkTreeView * tree_view)
{
  GtkTreeModel *model = gtk_tree_view_get_model (tree_view);
  GtkTreePath *path;
  GtkTreeIter iter;

  path = gtk_tree_path_new_from_string (path_string);
  gtk_tree_model_get_iter (model, &iter, path);
  gtk_list_store_set (GTK_LIST_STORE (model), &iter, 0, new_text, -1);
  gtk_tree_path_free (path);
}

int
main (int argc, char *argv[])
{
  GtkWidget *window;
  GtkWidget *vbox;
  GtkTreeModel *model;
  GtkWidget *combo;
  GtkWidget *tree_view;
  GtkCellRenderer *cell;
  GtkTreeViewColumn *column;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  g_signal_connect (G_OBJECT (window), "destroy",
		    G_CALLBACK (gtk_main_quit), NULL);
  g_signal_connect (G_OBJECT (window), "delete_event",
		    G_CALLBACK (gtk_main_quit), NULL);

  vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 72);
  gtk_container_add (GTK_CONTAINER (window), vbox);

  model = two_line_model ("A real combo box", "with a second line");
  combo = gtk_combo_box_new_with_model (model);
  g_object_unref (model);
  gtk_combo_box_set_active (GTK_COMBO_BOX (combo), 0);

  cell = gtk_cell_renderer_text_new ();
  gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, TRUE);
  gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo),
				  cell, "text", 0, NULL);

  gtk_box_pack_start (GTK_BOX (vbox), combo, FALSE, FALSE, 0);

  cell = gtk_cell_renderer_combo_new ();
  model = two_line_model ("A combo box in a tree view", "also with a second line");
  g_object_set (cell, "model", model, "text-column", 0, "editable", TRUE,
		"has-entry", FALSE, NULL);
  g_object_unref (model);

  model = two_line_model ("Click me", "or me");
  tree_view = gtk_tree_view_new_with_model (model);
  g_object_unref (model);

  column = gtk_tree_view_column_new_with_attributes ("Combo column",
						     cell, NULL);
  gtk_tree_view_column_set_attributes (column, cell, "text", 0, NULL);
  g_signal_connect (cell, "edited", G_CALLBACK (edited_cb), tree_view);

  gtk_tree_view_append_column (GTK_TREE_VIEW (tree_view), column);
  gtk_box_pack_start (GTK_BOX (vbox), tree_view, TRUE, FALSE, 0);

  gtk_widget_show_all (window);

  gtk_main ();

  return 0;
}
