#include <gtk/gtk.h>

static GMenuModel *
create_model ()
{
  GMenu *menu = g_menu_new ();
  GMenu *section;
  GMenu *section2;
  GMenuItem *item;
  GIcon *icon;

  section = g_menu_new ();
  item = g_menu_item_new ("Beep", "app.beep");
  icon = g_themed_icon_new ("audio-volume-high");
  g_menu_item_set_icon (item, icon);
  g_menu_append_item (section, item);
  g_menu_append_section (menu, "Cool stuff", G_MENU_MODEL (section));
  g_object_unref (section);
  
  section = g_menu_new ();
  item = g_menu_item_new ("Quit", "app.quit");
  icon = g_themed_icon_new ("dialog-warning");
  g_menu_item_set_icon (item, icon);
  g_menu_append_item (section, item);

  section2 = g_menu_new ();
  g_menu_append_section (section2, "Another section of risky things", G_MENU_MODEL (section));
  g_menu_append_section (menu, "Risky things", G_MENU_MODEL (section2));
  g_object_unref (section);

  return G_MENU_MODEL (menu);
}

static GtkWidget *
create_menu_button ()
{
  GtkWidget *menu_button = gtk_menu_button_new ();

  GtkWidget *menu = gtk_menu_new_from_model (create_model ());
  gtk_menu_button_set_popup (GTK_MENU_BUTTON (menu_button), menu);

  return menu_button;
}

static void
on_activate_beep (GtkWindow *window)
{
  gtk_widget_error_bell (GTK_WIDGET (window));
}

static void
on_activate_quit (GtkWindow *window)
{
  gtk_widget_destroy (GTK_WIDGET (window));
}

static void
on_activate (GApplication *application,
             void         *user_data)
{
  GtkWidget *window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  GtkWidget *menu_button = create_menu_button ();
  GSimpleAction *action;

  gtk_container_add (GTK_CONTAINER (window), menu_button);
  gtk_widget_show_all (window);
  gtk_widget_show_all (window);
  gtk_application_add_window (GTK_APPLICATION (application),
                              GTK_WINDOW (window));

  action = g_simple_action_new ("beep", NULL);
  g_signal_connect_swapped (action, "activate",
                            G_CALLBACK (on_activate_beep), window);
  g_action_map_add_action (G_ACTION_MAP (application), G_ACTION (action));

  action = g_simple_action_new ("quit", NULL);
  g_signal_connect_swapped (action, "activate",
                            G_CALLBACK (on_activate_quit), window);
  g_action_map_add_action (G_ACTION_MAP (application), G_ACTION (action));
}

int
main (int   argc,
      char *argv[])
{
  GtkApplication *application = gtk_application_new ("org.gtk.test.menumodel",
                                                     G_APPLICATION_FLAGS_NONE);
  int result;

  g_signal_connect (application, "activate", G_CALLBACK (on_activate), NULL);

  result = g_application_run (G_APPLICATION (application), argc, argv);
  g_object_unref (application);
  return result;
}
