#include <gtk/gtk.h>

/* to ensure two menus fit on screen side by side */ 
#define EXTRA_MARGIN 16

static void
position_0x0 (GtkMenu *menu, gint *x, gint *y, gboolean *push_in, gpointer user_data)
{
  *x = *y = 0;
}

static void
on_size_request (GtkWidget *menu, GtkRequisition *requisition, 
		 gint screen_width)
{
  int max_width = (screen_width / 2) - EXTRA_MARGIN;

  if (requisition->width > max_width)
    gtk_widget_set_size_request (menu, max_width, -1);
  else
    gtk_widget_set_size_request (menu, -1, -1);
}

int
main (int argc, char **argv)
{
  GtkWidget *menu;
  GtkWidget *item;
  GtkWidget *submenu;
  int screen_width;

  gtk_init (&argc, &argv);

  menu = gtk_menu_new ();

  screen_width = gdk_screen_get_width (gtk_widget_get_screen (menu));

  item = gtk_menu_item_new_with_label ("Foo");
  gtk_widget_set_size_request (item, (screen_width / 2) - EXTRA_MARGIN, -1);

  gtk_container_add (GTK_CONTAINER (menu), item);
  gtk_widget_show_all (menu);

  submenu = gtk_menu_new ();
  gtk_menu_item_set_submenu (GTK_MENU_ITEM (item), submenu);

  /* emulate a too wide item, so that we can restrict the menu size  */
  item = gtk_menu_item_new_with_label ("Foo");
  gtk_widget_set_size_request (item, screen_width + 1, -1);
  g_signal_connect (submenu, "size-request", G_CALLBACK (on_size_request), GINT_TO_POINTER (screen_width));
  gtk_container_add (GTK_CONTAINER (submenu), item);
  gtk_widget_show_all (submenu);

  gtk_menu_popup (GTK_MENU (menu), NULL, NULL,
		  position_0x0, NULL,
		  0, GDK_CURRENT_TIME);
  g_signal_connect (menu, "selection-done", G_CALLBACK (gtk_main_quit), NULL);

  gtk_main ();

  return 0;
}
