]> Pileus Git - ~andy/gtk/blob - gtk/gtkmenu.c
menus: Don't popdown submenus on button release for touch devices
[~andy/gtk] / gtk / gtkmenu.c
1 /* GTK - The GIMP Toolkit
2  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
16  */
17
18 /*
19  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
20  * file for a list of people on the GTK+ Team.  See the ChangeLog
21  * files for a list of changes.  These files are distributed with
22  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
23  */
24
25 /**
26  * SECTION:gtkmenu
27  * @Short_description: A menu widget
28  * @Title: GtkMenu
29  *
30  * A #GtkMenu is a #GtkMenuShell that implements a drop down menu
31  * consisting of a list of #GtkMenuItem objects which can be navigated
32  * and activated by the user to perform application functions.
33  *
34  * A #GtkMenu is most commonly dropped down by activating a
35  * #GtkMenuItem in a #GtkMenuBar or popped up by activating a
36  * #GtkMenuItem in another #GtkMenu.
37  *
38  * A #GtkMenu can also be popped up by activating a #GtkOptionMenu.
39  * Other composite widgets such as the #GtkNotebook can pop up a
40  * #GtkMenu as well.
41  *
42  * Applications can display a #GtkMenu as a popup menu by calling the 
43  * gtk_menu_popup() function.  The example below shows how an application
44  * can pop up a menu when the 3rd mouse button is pressed.  
45  *
46  * <example>
47  * <title>Connecting the popup signal handler.</title>
48  * <programlisting>
49  *   /<!---->* connect our handler which will popup the menu *<!---->/
50  *   g_signal_connect_swapped (window, "button_press_event",
51  *      G_CALLBACK (my_popup_handler), menu);
52  * </programlisting>
53  * </example>
54  *
55  * <example>
56  * <title>Signal handler which displays a popup menu.</title>
57  * <programlisting>
58  * static gint
59  * my_popup_handler (GtkWidget *widget, GdkEvent *event)
60  * {
61  *   GtkMenu *menu;
62  *   GdkEventButton *event_button;
63  *
64  *   g_return_val_if_fail (widget != NULL, FALSE);
65  *   g_return_val_if_fail (GTK_IS_MENU (widget), FALSE);
66  *   g_return_val_if_fail (event != NULL, FALSE);
67  *
68  *   /<!---->* The "widget" is the menu that was supplied when 
69  *    * g_signal_connect_swapped() was called.
70  *    *<!---->/
71  *   menu = GTK_MENU (widget);
72  *
73  *   if (event->type == GDK_BUTTON_PRESS)
74  *     {
75  *       event_button = (GdkEventButton *) event;
76  *       if (event_button->button == GDK_BUTTON_SECONDARY)
77  *         {
78  *           gtk_menu_popup (menu, NULL, NULL, NULL, NULL, 
79  *                           event_button->button, event_button->time);
80  *           return TRUE;
81  *         }
82  *     }
83  * 
84  *   return FALSE;
85  * }
86  * </programlisting>
87  * </example>
88  */
89
90 #include "config.h"
91
92 #include <string.h>
93
94 #include  <gobject/gvaluecollector.h>
95
96 #include "gtkaccellabel.h"
97 #include "gtkaccelmap.h"
98 #include "gtkbindings.h"
99 #include "gtkcheckmenuitem.h"
100 #include "gtkmain.h"
101 #include "gtkmarshalers.h"
102 #include "gtkmenuprivate.h"
103 #include "gtkmenuitemprivate.h"
104 #include "gtkmenushellprivate.h"
105 #include "gtkwindow.h"
106 #include "gtkbox.h"
107 #include "gtkscrollbar.h"
108 #include "gtksettings.h"
109 #include "gtkprivate.h"
110 #include "gtkwidgetprivate.h"
111 #include "gtkdnd.h"
112 #include "gtkintl.h"
113 #include "gtktypebuiltins.h"
114 #include "gtkwidgetprivate.h"
115
116 #include "deprecated/gtktearoffmenuitem.h"
117
118
119 #include "a11y/gtkmenuaccessible.h"
120
121 #define NAVIGATION_REGION_OVERSHOOT 50  /* How much the navigation region
122                                          * extends below the submenu
123                                          */
124
125 #define MENU_SCROLL_STEP1      8
126 #define MENU_SCROLL_STEP2     15
127 #define MENU_SCROLL_FAST_ZONE  8
128 #define MENU_SCROLL_TIMEOUT1  50
129 #define MENU_SCROLL_TIMEOUT2  20
130
131 #define ATTACH_INFO_KEY "gtk-menu-child-attach-info-key"
132 #define ATTACHED_MENUS "gtk-attached-menus"
133
134 typedef struct _GtkMenuAttachData  GtkMenuAttachData;
135 typedef struct _GtkMenuPopdownData GtkMenuPopdownData;
136
137 struct _GtkMenuAttachData
138 {
139   GtkWidget *attach_widget;
140   GtkMenuDetachFunc detacher;
141 };
142
143 struct _GtkMenuPopdownData
144 {
145   GtkMenu *menu;
146   GdkDevice *device;
147 };
148
149 typedef struct
150 {
151   gint left_attach;
152   gint right_attach;
153   gint top_attach;
154   gint bottom_attach;
155   gint effective_left_attach;
156   gint effective_right_attach;
157   gint effective_top_attach;
158   gint effective_bottom_attach;
159 } AttachInfo;
160
161 enum {
162   MOVE_SCROLL,
163   LAST_SIGNAL
164 };
165
166 enum {
167   PROP_0,
168   PROP_ACTIVE,
169   PROP_ACCEL_GROUP,
170   PROP_ACCEL_PATH,
171   PROP_ATTACH_WIDGET,
172   PROP_TEAROFF_STATE,
173   PROP_TEAROFF_TITLE,
174   PROP_MONITOR,
175   PROP_RESERVE_TOGGLE_SIZE
176 };
177
178 enum {
179   CHILD_PROP_0,
180   CHILD_PROP_LEFT_ATTACH,
181   CHILD_PROP_RIGHT_ATTACH,
182   CHILD_PROP_TOP_ATTACH,
183   CHILD_PROP_BOTTOM_ATTACH
184 };
185
186 static void     gtk_menu_set_property      (GObject          *object,
187                                             guint             prop_id,
188                                             const GValue     *value,
189                                             GParamSpec       *pspec);
190 static void     gtk_menu_get_property      (GObject          *object,
191                                             guint             prop_id,
192                                             GValue           *value,
193                                             GParamSpec       *pspec);
194 static void     gtk_menu_set_child_property(GtkContainer     *container,
195                                             GtkWidget        *child,
196                                             guint             property_id,
197                                             const GValue     *value,
198                                             GParamSpec       *pspec);
199 static void     gtk_menu_get_child_property(GtkContainer     *container,
200                                             GtkWidget        *child,
201                                             guint             property_id,
202                                             GValue           *value,
203                                             GParamSpec       *pspec);
204 static void     gtk_menu_destroy           (GtkWidget        *widget);
205 static void     gtk_menu_realize           (GtkWidget        *widget);
206 static void     gtk_menu_unrealize         (GtkWidget        *widget);
207 static void     gtk_menu_size_allocate     (GtkWidget        *widget,
208                                             GtkAllocation    *allocation);
209 static void     gtk_menu_show              (GtkWidget        *widget);
210 static gboolean gtk_menu_draw              (GtkWidget        *widget,
211                                             cairo_t          *cr);
212 static gboolean gtk_menu_key_press         (GtkWidget        *widget,
213                                             GdkEventKey      *event);
214 static gboolean gtk_menu_scroll            (GtkWidget        *widget,
215                                             GdkEventScroll   *event);
216 static gboolean gtk_menu_button_press      (GtkWidget        *widget,
217                                             GdkEventButton   *event);
218 static gboolean gtk_menu_button_release    (GtkWidget        *widget,
219                                             GdkEventButton   *event);
220 static gboolean gtk_menu_motion_notify     (GtkWidget        *widget,
221                                             GdkEventMotion   *event);
222 static gboolean gtk_menu_enter_notify      (GtkWidget        *widget,
223                                             GdkEventCrossing *event);
224 static gboolean gtk_menu_leave_notify      (GtkWidget        *widget,
225                                             GdkEventCrossing *event);
226 static void     gtk_menu_scroll_to         (GtkMenu          *menu,
227                                             gint              offset);
228 static void     gtk_menu_grab_notify       (GtkWidget        *widget,
229                                             gboolean          was_grabbed);
230 static gboolean gtk_menu_captured_event    (GtkWidget        *widget,
231                                             GdkEvent         *event);
232
233
234 static void     gtk_menu_stop_scrolling         (GtkMenu  *menu);
235 static void     gtk_menu_remove_scroll_timeout  (GtkMenu  *menu);
236 static gboolean gtk_menu_scroll_timeout         (gpointer  data);
237
238 static void     gtk_menu_scroll_item_visible (GtkMenuShell    *menu_shell,
239                                               GtkWidget       *menu_item);
240 static void     gtk_menu_select_item       (GtkMenuShell     *menu_shell,
241                                             GtkWidget        *menu_item);
242 static void     gtk_menu_real_insert       (GtkMenuShell     *menu_shell,
243                                             GtkWidget        *child,
244                                             gint              position);
245 static void     gtk_menu_scrollbar_changed (GtkAdjustment    *adjustment,
246                                             GtkMenu          *menu);
247 static void     gtk_menu_handle_scrolling  (GtkMenu          *menu,
248                                             gint              event_x,
249                                             gint              event_y,
250                                             gboolean          enter,
251                                             gboolean          motion);
252 static void     gtk_menu_set_tearoff_hints (GtkMenu          *menu,
253                                             gint             width);
254 static void     gtk_menu_style_updated     (GtkWidget        *widget);
255 static gboolean gtk_menu_focus             (GtkWidget        *widget,
256                                             GtkDirectionType direction);
257 static gint     gtk_menu_get_popup_delay   (GtkMenuShell     *menu_shell);
258 static void     gtk_menu_move_current      (GtkMenuShell     *menu_shell,
259                                             GtkMenuDirectionType direction);
260 static void     gtk_menu_real_move_scroll  (GtkMenu          *menu,
261                                             GtkScrollType     type);
262
263 static void     gtk_menu_stop_navigating_submenu       (GtkMenu          *menu);
264 static gboolean gtk_menu_stop_navigating_submenu_cb    (gpointer          user_data);
265 static gboolean gtk_menu_navigating_submenu            (GtkMenu          *menu,
266                                                         gint              event_x,
267                                                         gint              event_y);
268 static void     gtk_menu_set_submenu_navigation_region (GtkMenu          *menu,
269                                                         GtkMenuItem      *menu_item,
270                                                         GdkEventCrossing *event);
271  
272 static void gtk_menu_deactivate     (GtkMenuShell      *menu_shell);
273 static void gtk_menu_show_all       (GtkWidget         *widget);
274 static void gtk_menu_position       (GtkMenu           *menu,
275                                      gboolean           set_scroll_offset);
276 static void gtk_menu_reparent       (GtkMenu           *menu,
277                                      GtkWidget         *new_parent,
278                                      gboolean           unrealize);
279 static void gtk_menu_remove         (GtkContainer      *menu,
280                                      GtkWidget         *widget);
281
282 static void gtk_menu_update_title   (GtkMenu           *menu);
283
284 static void       menu_grab_transfer_window_destroy (GtkMenu *menu);
285 static GdkWindow *menu_grab_transfer_window_get     (GtkMenu *menu);
286
287 static gboolean gtk_menu_real_can_activate_accel (GtkWidget *widget,
288                                                   guint      signal_id);
289 static void _gtk_menu_refresh_accel_paths (GtkMenu *menu,
290                                            gboolean group_changed);
291
292 static void gtk_menu_get_preferred_width            (GtkWidget           *widget,
293                                                      gint                *minimum_size,
294                                                      gint                *natural_size);
295 static void gtk_menu_get_preferred_height           (GtkWidget           *widget,
296                                                      gint                *minimum_size,
297                                                      gint                *natural_size);
298 static void gtk_menu_get_preferred_height_for_width (GtkWidget           *widget,
299                                                      gint                 for_size,
300                                                      gint                *minimum_size,
301                                                      gint                *natural_size);
302
303
304 static const gchar attach_data_key[] = "gtk-menu-attach-data";
305
306 static guint menu_signals[LAST_SIGNAL] = { 0 };
307
308 G_DEFINE_TYPE (GtkMenu, gtk_menu, GTK_TYPE_MENU_SHELL)
309
310 static void
311 menu_queue_resize (GtkMenu *menu)
312 {
313   GtkMenuPrivate *priv = menu->priv;
314
315   priv->have_layout = FALSE;
316   gtk_widget_queue_resize (GTK_WIDGET (menu));
317 }
318
319 static void
320 attach_info_free (AttachInfo *info)
321 {
322   g_slice_free (AttachInfo, info);
323 }
324
325 static AttachInfo *
326 get_attach_info (GtkWidget *child)
327 {
328   GObject *object = G_OBJECT (child);
329   AttachInfo *ai = g_object_get_data (object, ATTACH_INFO_KEY);
330
331   if (!ai)
332     {
333       ai = g_slice_new0 (AttachInfo);
334       g_object_set_data_full (object, I_(ATTACH_INFO_KEY), ai,
335                               (GDestroyNotify) attach_info_free);
336     }
337
338   return ai;
339 }
340
341 static gboolean
342 is_grid_attached (AttachInfo *ai)
343 {
344   return (ai->left_attach >= 0 &&
345           ai->right_attach >= 0 &&
346           ai->top_attach >= 0 &&
347           ai->bottom_attach >= 0);
348 }
349
350 static void
351 menu_ensure_layout (GtkMenu *menu)
352 {
353   GtkMenuPrivate *priv = menu->priv;
354
355   if (!priv->have_layout)
356     {
357       GtkMenuShell *menu_shell = GTK_MENU_SHELL (menu);
358       GList *l;
359       gchar *row_occupied;
360       gint current_row;
361       gint max_right_attach;
362       gint max_bottom_attach;
363
364       /* Find extents of gridded portion
365        */
366       max_right_attach = 1;
367       max_bottom_attach = 0;
368
369       for (l = menu_shell->priv->children; l; l = l->next)
370         {
371           GtkWidget *child = l->data;
372           AttachInfo *ai = get_attach_info (child);
373
374           if (is_grid_attached (ai))
375             {
376               max_bottom_attach = MAX (max_bottom_attach, ai->bottom_attach);
377               max_right_attach = MAX (max_right_attach, ai->right_attach);
378             }
379         }
380
381       /* Find empty rows */
382       row_occupied = g_malloc0 (max_bottom_attach);
383
384       for (l = menu_shell->priv->children; l; l = l->next)
385         {
386           GtkWidget *child = l->data;
387           AttachInfo *ai = get_attach_info (child);
388
389           if (is_grid_attached (ai))
390             {
391               gint i;
392
393               for (i = ai->top_attach; i < ai->bottom_attach; i++)
394                 row_occupied[i] = TRUE;
395             }
396         }
397
398       /* Lay non-grid-items out in those rows
399        */
400       current_row = 0;
401       for (l = menu_shell->priv->children; l; l = l->next)
402         {
403           GtkWidget *child = l->data;
404           AttachInfo *ai = get_attach_info (child);
405
406           if (!is_grid_attached (ai))
407             {
408               while (current_row < max_bottom_attach && row_occupied[current_row])
409                 current_row++;
410
411               ai->effective_left_attach = 0;
412               ai->effective_right_attach = max_right_attach;
413               ai->effective_top_attach = current_row;
414               ai->effective_bottom_attach = current_row + 1;
415
416               current_row++;
417             }
418           else
419             {
420               ai->effective_left_attach = ai->left_attach;
421               ai->effective_right_attach = ai->right_attach;
422               ai->effective_top_attach = ai->top_attach;
423               ai->effective_bottom_attach = ai->bottom_attach;
424             }
425         }
426
427       g_free (row_occupied);
428
429       priv->n_rows = MAX (current_row, max_bottom_attach);
430       priv->n_columns = max_right_attach;
431       priv->have_layout = TRUE;
432     }
433 }
434
435
436 static gint
437 gtk_menu_get_n_columns (GtkMenu *menu)
438 {
439   GtkMenuPrivate *priv = menu->priv;
440
441   menu_ensure_layout (menu);
442
443   return priv->n_columns;
444 }
445
446 static gint
447 gtk_menu_get_n_rows (GtkMenu *menu)
448 {
449   GtkMenuPrivate *priv = menu->priv;
450
451   menu_ensure_layout (menu);
452
453   return priv->n_rows;
454 }
455
456 static void
457 get_effective_child_attach (GtkWidget *child,
458                             int       *l,
459                             int       *r,
460                             int       *t,
461                             int       *b)
462 {
463   GtkMenu *menu = GTK_MENU (gtk_widget_get_parent (child));
464   AttachInfo *ai;
465   
466   menu_ensure_layout (menu);
467
468   ai = get_attach_info (child);
469
470   if (l)
471     *l = ai->effective_left_attach;
472   if (r)
473     *r = ai->effective_right_attach;
474   if (t)
475     *t = ai->effective_top_attach;
476   if (b)
477     *b = ai->effective_bottom_attach;
478
479 }
480
481 static void
482 gtk_menu_class_init (GtkMenuClass *class)
483 {
484   GObjectClass *gobject_class = G_OBJECT_CLASS (class);
485   GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (class);
486   GtkContainerClass *container_class = GTK_CONTAINER_CLASS (class);
487   GtkMenuShellClass *menu_shell_class = GTK_MENU_SHELL_CLASS (class);
488   GtkBindingSet *binding_set;
489   
490   gobject_class->set_property = gtk_menu_set_property;
491   gobject_class->get_property = gtk_menu_get_property;
492
493   widget_class->destroy = gtk_menu_destroy;
494   widget_class->realize = gtk_menu_realize;
495   widget_class->unrealize = gtk_menu_unrealize;
496   widget_class->size_allocate = gtk_menu_size_allocate;
497   widget_class->show = gtk_menu_show;
498   widget_class->draw = gtk_menu_draw;
499   widget_class->scroll_event = gtk_menu_scroll;
500   widget_class->key_press_event = gtk_menu_key_press;
501   widget_class->button_press_event = gtk_menu_button_press;
502   widget_class->button_release_event = gtk_menu_button_release;
503   widget_class->motion_notify_event = gtk_menu_motion_notify;
504   widget_class->show_all = gtk_menu_show_all;
505   widget_class->enter_notify_event = gtk_menu_enter_notify;
506   widget_class->leave_notify_event = gtk_menu_leave_notify;
507   widget_class->style_updated = gtk_menu_style_updated;
508   widget_class->focus = gtk_menu_focus;
509   widget_class->can_activate_accel = gtk_menu_real_can_activate_accel;
510   widget_class->grab_notify = gtk_menu_grab_notify;
511   widget_class->get_preferred_width = gtk_menu_get_preferred_width;
512   widget_class->get_preferred_height = gtk_menu_get_preferred_height;
513   widget_class->get_preferred_height_for_width = gtk_menu_get_preferred_height_for_width;
514
515   container_class->remove = gtk_menu_remove;
516   container_class->get_child_property = gtk_menu_get_child_property;
517   container_class->set_child_property = gtk_menu_set_child_property;
518   
519   menu_shell_class->submenu_placement = GTK_LEFT_RIGHT;
520   menu_shell_class->deactivate = gtk_menu_deactivate;
521   menu_shell_class->select_item = gtk_menu_select_item;
522   menu_shell_class->insert = gtk_menu_real_insert;
523   menu_shell_class->get_popup_delay = gtk_menu_get_popup_delay;
524   menu_shell_class->move_current = gtk_menu_move_current;
525
526   /**
527    * GtkMenu::move-scroll:
528    * @menu: a #GtkMenu
529    * @scroll_type: a #GtkScrollType
530    */
531   menu_signals[MOVE_SCROLL] =
532     g_signal_new_class_handler (I_("move-scroll"),
533                                 G_OBJECT_CLASS_TYPE (gobject_class),
534                                 G_SIGNAL_RUN_LAST | G_SIGNAL_ACTION,
535                                 G_CALLBACK (gtk_menu_real_move_scroll),
536                                 NULL, NULL,
537                                 _gtk_marshal_VOID__ENUM,
538                                 G_TYPE_NONE, 1,
539                                 GTK_TYPE_SCROLL_TYPE);
540
541   /**
542    * GtkMenu:active:
543    *
544    * The index of the currently selected menu item, or -1 if no
545    * menu item is selected.
546    *
547    * Since: 2.14
548    **/
549   g_object_class_install_property (gobject_class,
550                                    PROP_ACTIVE,
551                                    g_param_spec_int ("active",
552                                                      P_("Active"),
553                                                      P_("The currently selected menu item"),
554                                                      -1, G_MAXINT, -1,
555                                                      GTK_PARAM_READWRITE));
556
557   /**
558    * GtkMenu:accel-group:
559    *
560    * The accel group holding accelerators for the menu.
561    *
562    * Since: 2.14
563    **/
564   g_object_class_install_property (gobject_class,
565                                    PROP_ACCEL_GROUP,
566                                    g_param_spec_object ("accel-group",
567                                                         P_("Accel Group"),
568                                                         P_("The accel group holding accelerators for the menu"),
569                                                         GTK_TYPE_ACCEL_GROUP,
570                                                         GTK_PARAM_READWRITE));
571
572   /**
573    * GtkMenu:accel-path:
574    *
575    * An accel path used to conveniently construct accel paths of child items.
576    *
577    * Since: 2.14
578    **/
579   g_object_class_install_property (gobject_class,
580                                    PROP_ACCEL_PATH,
581                                    g_param_spec_string ("accel-path",
582                                                         P_("Accel Path"),
583                                                         P_("An accel path used to conveniently construct accel paths of child items"),
584                                                         NULL,
585                                                         GTK_PARAM_READWRITE));
586
587   /**
588    * GtkMenu:attach-widget:
589    *
590    * The widget the menu is attached to. Setting this property attaches
591    * the menu without a #GtkMenuDetachFunc. If you need to use a detacher,
592    * use gtk_menu_attach_to_widget() directly.
593    *
594    * Since: 2.14
595    **/
596   g_object_class_install_property (gobject_class,
597                                    PROP_ATTACH_WIDGET,
598                                    g_param_spec_object ("attach-widget",
599                                                         P_("Attach Widget"),
600                                                         P_("The widget the menu is attached to"),
601                                                         GTK_TYPE_WIDGET,
602                                                         GTK_PARAM_READWRITE));
603
604   g_object_class_install_property (gobject_class,
605                                    PROP_TEAROFF_TITLE,
606                                    g_param_spec_string ("tearoff-title",
607                                                         P_("Tearoff Title"),
608                                                         P_("A title that may be displayed by the window manager when this menu is torn-off"),
609                                                         NULL,
610                                                         GTK_PARAM_READWRITE));
611
612   /**
613    * GtkMenu:tearoff-state:
614    *
615    * A boolean that indicates whether the menu is torn-off.
616    *
617    * Since: 2.6
618    **/
619   g_object_class_install_property (gobject_class,
620                                    PROP_TEAROFF_STATE,
621                                    g_param_spec_boolean ("tearoff-state",
622                                                          P_("Tearoff State"),
623                                                          P_("A boolean that indicates whether the menu is torn-off"),
624                                                          FALSE,
625                                                          GTK_PARAM_READWRITE));
626
627   /**
628    * GtkMenu:monitor:
629    *
630    * The monitor the menu will be popped up on.
631    *
632    * Since: 2.14
633    **/
634   g_object_class_install_property (gobject_class,
635                                    PROP_MONITOR,
636                                    g_param_spec_int ("monitor",
637                                                      P_("Monitor"),
638                                                      P_("The monitor the menu will be popped up on"),
639                                                      -1, G_MAXINT, -1,
640                                                      GTK_PARAM_READWRITE));
641
642   gtk_widget_class_install_style_property (widget_class,
643                                            g_param_spec_int ("vertical-padding",
644                                                              P_("Vertical Padding"),
645                                                              P_("Extra space at the top and bottom of the menu"),
646                                                              0,
647                                                              G_MAXINT,
648                                                              1,
649                                                              GTK_PARAM_READABLE));
650
651   /**
652    * GtkMenu:reserve-toggle-size:
653    *
654    * A boolean that indicates whether the menu reserves space for
655    * toggles and icons, regardless of their actual presence.
656    *
657    * This property should only be changed from its default value
658    * for special-purposes such as tabular menus. Regular menus that
659    * are connected to a menu bar or context menus should reserve
660    * toggle space for consistency.
661    *
662    * Since: 2.18
663    */
664   g_object_class_install_property (gobject_class,
665                                    PROP_RESERVE_TOGGLE_SIZE,
666                                    g_param_spec_boolean ("reserve-toggle-size",
667                                                          P_("Reserve Toggle Size"),
668                                                          P_("A boolean that indicates whether the menu reserves space for toggles and icons"),
669                                                          TRUE,
670                                                          GTK_PARAM_READWRITE));
671
672   gtk_widget_class_install_style_property (widget_class,
673                                            g_param_spec_int ("horizontal-padding",
674                                                              P_("Horizontal Padding"),
675                                                              P_("Extra space at the left and right edges of the menu"),
676                                                              0,
677                                                              G_MAXINT,
678                                                              0,
679                                                              GTK_PARAM_READABLE));
680
681   gtk_widget_class_install_style_property (widget_class,
682                                            g_param_spec_int ("vertical-offset",
683                                                              P_("Vertical Offset"),
684                                                              P_("When the menu is a submenu, position it this number of pixels offset vertically"),
685                                                              G_MININT,
686                                                              G_MAXINT,
687                                                              0,
688                                                              GTK_PARAM_READABLE));
689
690   gtk_widget_class_install_style_property (widget_class,
691                                            g_param_spec_int ("horizontal-offset",
692                                                              P_("Horizontal Offset"),
693                                                              P_("When the menu is a submenu, position it this number of pixels offset horizontally"),
694                                                              G_MININT,
695                                                              G_MAXINT,
696                                                              -2,
697                                                              GTK_PARAM_READABLE));
698
699   gtk_widget_class_install_style_property (widget_class,
700                                            g_param_spec_boolean ("double-arrows",
701                                                                  P_("Double Arrows"),
702                                                                  P_("When scrolling, always show both arrows."),
703                                                                  TRUE,
704                                                                  GTK_PARAM_READABLE));
705
706   /**
707    * GtkMenu:arrow-placement:
708    *
709    * Indicates where scroll arrows should be placed.
710    *
711    * Since: 2.16
712    **/
713   gtk_widget_class_install_style_property (widget_class,
714                                            g_param_spec_enum ("arrow-placement",
715                                                               P_("Arrow Placement"),
716                                                               P_("Indicates where scroll arrows should be placed"),
717                                                               GTK_TYPE_ARROW_PLACEMENT,
718                                                               GTK_ARROWS_BOTH,
719                                                               GTK_PARAM_READABLE));
720
721  gtk_container_class_install_child_property (container_class,
722                                              CHILD_PROP_LEFT_ATTACH,
723                                               g_param_spec_int ("left-attach",
724                                                                P_("Left Attach"),
725                                                                P_("The column number to attach the left side of the child to"),
726                                                                 -1, INT_MAX, -1,
727                                                                GTK_PARAM_READWRITE));
728
729  gtk_container_class_install_child_property (container_class,
730                                              CHILD_PROP_RIGHT_ATTACH,
731                                               g_param_spec_int ("right-attach",
732                                                                P_("Right Attach"),
733                                                                P_("The column number to attach the right side of the child to"),
734                                                                 -1, INT_MAX, -1,
735                                                                GTK_PARAM_READWRITE));
736
737  gtk_container_class_install_child_property (container_class,
738                                              CHILD_PROP_TOP_ATTACH,
739                                               g_param_spec_int ("top-attach",
740                                                                P_("Top Attach"),
741                                                                P_("The row number to attach the top of the child to"),
742                                                                 -1, INT_MAX, -1,
743                                                                GTK_PARAM_READWRITE));
744
745  gtk_container_class_install_child_property (container_class,
746                                              CHILD_PROP_BOTTOM_ATTACH,
747                                               g_param_spec_int ("bottom-attach",
748                                                                P_("Bottom Attach"),
749                                                                P_("The row number to attach the bottom of the child to"),
750                                                                 -1, INT_MAX, -1,
751                                                                GTK_PARAM_READWRITE));
752
753  /**
754   * GtkMenu:arrow-scaling
755   *
756   * Arbitrary constant to scale down the size of the scroll arrow.
757   *
758   * Since: 2.16
759   */
760   gtk_widget_class_install_style_property (widget_class,
761                                            g_param_spec_float ("arrow-scaling",
762                                                                P_("Arrow Scaling"),
763                                                                P_("Arbitrary constant to scale down the size of the scroll arrow"),
764                                                                0.0, 1.0, 0.7,
765                                                                GTK_PARAM_READABLE));
766
767   binding_set = gtk_binding_set_by_class (class);
768   gtk_binding_entry_add_signal (binding_set,
769                                 GDK_KEY_Up, 0,
770                                 I_("move-current"), 1,
771                                 GTK_TYPE_MENU_DIRECTION_TYPE,
772                                 GTK_MENU_DIR_PREV);
773   gtk_binding_entry_add_signal (binding_set,
774                                 GDK_KEY_KP_Up, 0,
775                                 "move-current", 1,
776                                 GTK_TYPE_MENU_DIRECTION_TYPE,
777                                 GTK_MENU_DIR_PREV);
778   gtk_binding_entry_add_signal (binding_set,
779                                 GDK_KEY_Down, 0,
780                                 "move-current", 1,
781                                 GTK_TYPE_MENU_DIRECTION_TYPE,
782                                 GTK_MENU_DIR_NEXT);
783   gtk_binding_entry_add_signal (binding_set,
784                                 GDK_KEY_KP_Down, 0,
785                                 "move-current", 1,
786                                 GTK_TYPE_MENU_DIRECTION_TYPE,
787                                 GTK_MENU_DIR_NEXT);
788   gtk_binding_entry_add_signal (binding_set,
789                                 GDK_KEY_Left, 0,
790                                 "move-current", 1,
791                                 GTK_TYPE_MENU_DIRECTION_TYPE,
792                                 GTK_MENU_DIR_PARENT);
793   gtk_binding_entry_add_signal (binding_set,
794                                 GDK_KEY_KP_Left, 0,
795                                 "move-current", 1,
796                                 GTK_TYPE_MENU_DIRECTION_TYPE,
797                                 GTK_MENU_DIR_PARENT);
798   gtk_binding_entry_add_signal (binding_set,
799                                 GDK_KEY_Right, 0,
800                                 "move-current", 1,
801                                 GTK_TYPE_MENU_DIRECTION_TYPE,
802                                 GTK_MENU_DIR_CHILD);
803   gtk_binding_entry_add_signal (binding_set,
804                                 GDK_KEY_KP_Right, 0,
805                                 "move-current", 1,
806                                 GTK_TYPE_MENU_DIRECTION_TYPE,
807                                 GTK_MENU_DIR_CHILD);
808   gtk_binding_entry_add_signal (binding_set,
809                                 GDK_KEY_Home, 0,
810                                 "move-scroll", 1,
811                                 GTK_TYPE_SCROLL_TYPE,
812                                 GTK_SCROLL_START);
813   gtk_binding_entry_add_signal (binding_set,
814                                 GDK_KEY_KP_Home, 0,
815                                 "move-scroll", 1,
816                                 GTK_TYPE_SCROLL_TYPE,
817                                 GTK_SCROLL_START);
818   gtk_binding_entry_add_signal (binding_set,
819                                 GDK_KEY_End, 0,
820                                 "move-scroll", 1,
821                                 GTK_TYPE_SCROLL_TYPE,
822                                 GTK_SCROLL_END);
823   gtk_binding_entry_add_signal (binding_set,
824                                 GDK_KEY_KP_End, 0,
825                                 "move-scroll", 1,
826                                 GTK_TYPE_SCROLL_TYPE,
827                                 GTK_SCROLL_END);
828   gtk_binding_entry_add_signal (binding_set,
829                                 GDK_KEY_Page_Up, 0,
830                                 "move-scroll", 1,
831                                 GTK_TYPE_SCROLL_TYPE,
832                                 GTK_SCROLL_PAGE_UP);
833   gtk_binding_entry_add_signal (binding_set,
834                                 GDK_KEY_KP_Page_Up, 0,
835                                 "move-scroll", 1,
836                                 GTK_TYPE_SCROLL_TYPE,
837                                 GTK_SCROLL_PAGE_UP);
838   gtk_binding_entry_add_signal (binding_set,
839                                 GDK_KEY_Page_Down, 0,
840                                 "move-scroll", 1,
841                                 GTK_TYPE_SCROLL_TYPE,
842                                 GTK_SCROLL_PAGE_DOWN);
843   gtk_binding_entry_add_signal (binding_set,
844                                 GDK_KEY_KP_Page_Down, 0,
845                                 "move-scroll", 1,
846                                 GTK_TYPE_SCROLL_TYPE,
847                                 GTK_SCROLL_PAGE_DOWN);
848
849   g_type_class_add_private (gobject_class, sizeof (GtkMenuPrivate));
850
851   gtk_widget_class_set_accessible_type (widget_class, GTK_TYPE_MENU_ACCESSIBLE);
852 }
853
854
855 static void
856 gtk_menu_set_property (GObject      *object,
857                        guint         prop_id,
858                        const GValue *value,
859                        GParamSpec   *pspec)
860 {
861   GtkMenu *menu = GTK_MENU (object);
862
863   switch (prop_id)
864     {
865     case PROP_ACTIVE:
866       gtk_menu_set_active (menu, g_value_get_int (value));
867       break;
868     case PROP_ACCEL_GROUP:
869       gtk_menu_set_accel_group (menu, g_value_get_object (value));
870       break;
871     case PROP_ACCEL_PATH:
872       gtk_menu_set_accel_path (menu, g_value_get_string (value));
873       break;
874     case PROP_ATTACH_WIDGET:
875       {
876         GtkWidget *widget;
877
878         widget = gtk_menu_get_attach_widget (menu);
879         if (widget)
880           gtk_menu_detach (menu);
881
882         widget = (GtkWidget*) g_value_get_object (value); 
883         if (widget)
884           gtk_menu_attach_to_widget (menu, widget, NULL);
885       }
886       break;
887     case PROP_TEAROFF_STATE:
888       gtk_menu_set_tearoff_state (menu, g_value_get_boolean (value));
889       break;
890     case PROP_TEAROFF_TITLE:
891       gtk_menu_set_title (menu, g_value_get_string (value));
892       break;
893     case PROP_MONITOR:
894       gtk_menu_set_monitor (menu, g_value_get_int (value));
895       break;
896     case PROP_RESERVE_TOGGLE_SIZE:
897       gtk_menu_set_reserve_toggle_size (menu, g_value_get_boolean (value));
898       break;
899     default:
900       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
901       break;
902     }
903 }
904
905 static void
906 gtk_menu_get_property (GObject     *object,
907                        guint        prop_id,
908                        GValue      *value,
909                        GParamSpec  *pspec)
910 {
911   GtkMenu *menu = GTK_MENU (object);
912
913   switch (prop_id)
914     {
915     case PROP_ACTIVE:
916       g_value_set_int (value, g_list_index (GTK_MENU_SHELL (menu)->priv->children, gtk_menu_get_active (menu)));
917       break;
918     case PROP_ACCEL_GROUP:
919       g_value_set_object (value, gtk_menu_get_accel_group (menu));
920       break;
921     case PROP_ACCEL_PATH:
922       g_value_set_string (value, gtk_menu_get_accel_path (menu));
923       break;
924     case PROP_ATTACH_WIDGET:
925       g_value_set_object (value, gtk_menu_get_attach_widget (menu));
926       break;
927     case PROP_TEAROFF_STATE:
928       g_value_set_boolean (value, gtk_menu_get_tearoff_state (menu));
929       break;
930     case PROP_TEAROFF_TITLE:
931       g_value_set_string (value, gtk_menu_get_title (menu));
932       break;
933     case PROP_MONITOR:
934       g_value_set_int (value, gtk_menu_get_monitor (menu));
935       break;
936     case PROP_RESERVE_TOGGLE_SIZE:
937       g_value_set_boolean (value, gtk_menu_get_reserve_toggle_size (menu));
938       break;
939     default:
940       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
941       break;
942     }
943 }
944
945 static void
946 gtk_menu_set_child_property (GtkContainer *container,
947                              GtkWidget    *child,
948                              guint         property_id,
949                              const GValue *value,
950                              GParamSpec   *pspec)
951 {
952   GtkMenu *menu = GTK_MENU (container);
953   AttachInfo *ai = get_attach_info (child);
954
955   switch (property_id)
956     {
957     case CHILD_PROP_LEFT_ATTACH:
958       ai->left_attach = g_value_get_int (value);
959       break;
960     case CHILD_PROP_RIGHT_ATTACH:
961       ai->right_attach = g_value_get_int (value);
962       break;
963     case CHILD_PROP_TOP_ATTACH:
964       ai->top_attach = g_value_get_int (value);
965       break;
966     case CHILD_PROP_BOTTOM_ATTACH:
967       ai->bottom_attach = g_value_get_int (value);
968       break;
969
970     default:
971       GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID (container, property_id, pspec);
972       return;
973     }
974
975   menu_queue_resize (menu);
976 }
977
978 static void
979 gtk_menu_get_child_property (GtkContainer *container,
980                              GtkWidget    *child,
981                              guint         property_id,
982                              GValue       *value,
983                              GParamSpec   *pspec)
984 {
985   AttachInfo *ai = get_attach_info (child);
986
987   switch (property_id)
988     {
989     case CHILD_PROP_LEFT_ATTACH:
990       g_value_set_int (value, ai->left_attach);
991       break;
992     case CHILD_PROP_RIGHT_ATTACH:
993       g_value_set_int (value, ai->right_attach);
994       break;
995     case CHILD_PROP_TOP_ATTACH:
996       g_value_set_int (value, ai->top_attach);
997       break;
998     case CHILD_PROP_BOTTOM_ATTACH:
999       g_value_set_int (value, ai->bottom_attach);
1000       break;
1001       
1002     default:
1003       GTK_CONTAINER_WARN_INVALID_CHILD_PROPERTY_ID (container, property_id, pspec);
1004       return;
1005     }
1006 }
1007
1008 static gboolean
1009 gtk_menu_window_event (GtkWidget *window,
1010                        GdkEvent  *event,
1011                        GtkWidget *menu)
1012 {
1013   gboolean handled = FALSE;
1014
1015   g_object_ref (window);
1016   g_object_ref (menu);
1017
1018   switch (event->type)
1019     {
1020     case GDK_KEY_PRESS:
1021     case GDK_KEY_RELEASE:
1022       handled = gtk_widget_event (menu, event);
1023       break;
1024     case GDK_WINDOW_STATE:
1025       /* Window for the menu has been closed by the display server or by GDK.
1026        * Update the internal state as if the user had clicked outside the
1027        * menu
1028        */
1029       if (event->window_state.new_window_state & GDK_WINDOW_STATE_WITHDRAWN &&
1030           event->window_state.changed_mask & GDK_WINDOW_STATE_WITHDRAWN)
1031         gtk_menu_shell_deactivate (GTK_MENU_SHELL(menu));
1032       break;
1033     default:
1034       break;
1035     }
1036
1037   g_object_unref (window);
1038   g_object_unref (menu);
1039
1040   return handled;
1041 }
1042
1043 static void
1044 gtk_menu_init (GtkMenu *menu)
1045 {
1046   GtkMenuPrivate *priv;
1047   GtkStyleContext *context;
1048
1049   priv = G_TYPE_INSTANCE_GET_PRIVATE (menu, GTK_TYPE_MENU, GtkMenuPrivate);
1050
1051   menu->priv = priv;
1052
1053   priv->toplevel = g_object_connect (g_object_new (GTK_TYPE_WINDOW,
1054                                                    "type", GTK_WINDOW_POPUP,
1055                                                    "child", menu,
1056                                                    NULL),
1057                                      "signal::event", gtk_menu_window_event, menu,
1058                                      "signal::destroy", gtk_widget_destroyed, &priv->toplevel,
1059                                      NULL);
1060   gtk_window_set_resizable (GTK_WINDOW (priv->toplevel), FALSE);
1061   gtk_window_set_mnemonic_modifier (GTK_WINDOW (priv->toplevel), 0);
1062
1063   /* Refloat the menu, so that reference counting for the menu isn't
1064    * affected by it being a child of the toplevel
1065    */
1066   g_object_force_floating (G_OBJECT (menu));
1067   priv->needs_destruction_ref = TRUE;
1068
1069   priv->monitor_num = -1;
1070   priv->drag_start_y = -1;
1071
1072   context = gtk_widget_get_style_context (GTK_WIDGET (menu));
1073   gtk_style_context_add_class (context, GTK_STYLE_CLASS_MENU);
1074
1075   _gtk_widget_set_captured_event_handler (GTK_WIDGET (menu), gtk_menu_captured_event);
1076 }
1077
1078 static void
1079 gtk_menu_destroy (GtkWidget *widget)
1080 {
1081   GtkMenu *menu = GTK_MENU (widget);
1082   GtkMenuPrivate *priv = menu->priv;
1083   GtkMenuAttachData *data;
1084
1085   gtk_menu_remove_scroll_timeout (menu);
1086
1087   data = g_object_get_data (G_OBJECT (widget), attach_data_key);
1088   if (data)
1089     gtk_menu_detach (menu);
1090
1091   gtk_menu_stop_navigating_submenu (menu);
1092
1093   if (priv->old_active_menu_item)
1094     g_clear_object (&priv->old_active_menu_item);
1095
1096   /* Add back the reference count for being a child */
1097   if (priv->needs_destruction_ref)
1098     {
1099       priv->needs_destruction_ref = FALSE;
1100       g_object_ref (widget);
1101     }
1102
1103   if (priv->accel_group)
1104     g_clear_object (&priv->accel_group);
1105
1106   if (priv->toplevel)
1107     gtk_widget_destroy (priv->toplevel);
1108
1109   if (priv->tearoff_window)
1110     gtk_widget_destroy (priv->tearoff_window);
1111
1112   if (priv->heights)
1113     {
1114       g_free (priv->heights);
1115       priv->heights = NULL;
1116     }
1117
1118   if (priv->title)
1119     {
1120       g_free (priv->title);
1121       priv->title = NULL;
1122     }
1123
1124   if (priv->position_func_data_destroy)
1125     {
1126       priv->position_func_data_destroy (priv->position_func_data);
1127       priv->position_func_data = NULL;
1128       priv->position_func_data_destroy = NULL;
1129     }
1130
1131   GTK_WIDGET_CLASS (gtk_menu_parent_class)->destroy (widget);
1132 }
1133
1134 static void
1135 menu_change_screen (GtkMenu   *menu,
1136                     GdkScreen *new_screen)
1137 {
1138   GtkMenuPrivate *priv = menu->priv;
1139
1140   if (gtk_widget_has_screen (GTK_WIDGET (menu)))
1141     {
1142       if (new_screen == gtk_widget_get_screen (GTK_WIDGET (menu)))
1143         return;
1144     }
1145
1146   if (priv->torn_off)
1147     {
1148       gtk_window_set_screen (GTK_WINDOW (priv->tearoff_window), new_screen);
1149       gtk_menu_position (menu, TRUE);
1150     }
1151
1152   gtk_window_set_screen (GTK_WINDOW (priv->toplevel), new_screen);
1153   priv->monitor_num = -1;
1154 }
1155
1156 static void
1157 attach_widget_screen_changed (GtkWidget *attach_widget,
1158                               GdkScreen *previous_screen,
1159                               GtkMenu   *menu)
1160 {
1161   if (gtk_widget_has_screen (attach_widget) &&
1162       !g_object_get_data (G_OBJECT (menu), "gtk-menu-explicit-screen"))
1163     menu_change_screen (menu, gtk_widget_get_screen (attach_widget));
1164 }
1165
1166 /**
1167  * gtk_menu_attach_to_widget:
1168  * @menu: a #GtkMenu
1169  * @attach_widget: the #GtkWidget that the menu will be attached to
1170  * @detacher: (scope async)(allow-none): the user supplied callback function
1171  *             that will be called when the menu calls gtk_menu_detach()
1172  *
1173  * Attaches the menu to the widget and provides a callback function
1174  * that will be invoked when the menu calls gtk_menu_detach() during
1175  * its destruction.
1176  */
1177 void
1178 gtk_menu_attach_to_widget (GtkMenu           *menu,
1179                            GtkWidget         *attach_widget,
1180                            GtkMenuDetachFunc  detacher)
1181 {
1182   GtkMenuAttachData *data;
1183   GList *list;
1184
1185   g_return_if_fail (GTK_IS_MENU (menu));
1186   g_return_if_fail (GTK_IS_WIDGET (attach_widget));
1187
1188   /* keep this function in sync with gtk_widget_set_parent() */
1189   data = g_object_get_data (G_OBJECT (menu), attach_data_key);
1190   if (data)
1191     {
1192       g_warning ("gtk_menu_attach_to_widget(): menu already attached to %s",
1193                  g_type_name (G_TYPE_FROM_INSTANCE (data->attach_widget)));
1194      return;
1195     }
1196
1197   g_object_ref_sink (menu);
1198
1199   data = g_slice_new (GtkMenuAttachData);
1200   data->attach_widget = attach_widget;
1201
1202   g_signal_connect (attach_widget, "screen-changed",
1203                     G_CALLBACK (attach_widget_screen_changed), menu);
1204   attach_widget_screen_changed (attach_widget, NULL, menu);
1205
1206   data->detacher = detacher;
1207   g_object_set_data (G_OBJECT (menu), I_(attach_data_key), data);
1208   list = g_object_steal_data (G_OBJECT (attach_widget), ATTACHED_MENUS);
1209   if (!g_list_find (list, menu))
1210     list = g_list_prepend (list, menu);
1211
1212   g_object_set_data_full (G_OBJECT (attach_widget), I_(ATTACHED_MENUS), list,
1213                           (GDestroyNotify) g_list_free);
1214
1215   if (gtk_widget_get_state_flags (GTK_WIDGET (menu)) != 0)
1216     gtk_widget_set_state_flags (GTK_WIDGET (menu), 0, TRUE);
1217
1218   /* Attach the widget to the toplevel window. */
1219   gtk_window_set_attached_to (GTK_WINDOW (menu->priv->toplevel), attach_widget);
1220
1221   /* Fallback title for menu comes from attach widget */
1222   gtk_menu_update_title (menu);
1223
1224   g_object_notify (G_OBJECT (menu), "attach-widget");
1225 }
1226
1227 /**
1228  * gtk_menu_get_attach_widget:
1229  * @menu: a #GtkMenu
1230  *
1231  * Returns the #GtkWidget that the menu is attached to.
1232  *
1233  * Returns: (transfer none): the #GtkWidget that the menu is attached to
1234  */
1235 GtkWidget*
1236 gtk_menu_get_attach_widget (GtkMenu *menu)
1237 {
1238   GtkMenuAttachData *data;
1239
1240   g_return_val_if_fail (GTK_IS_MENU (menu), NULL);
1241
1242   data = g_object_get_data (G_OBJECT (menu), attach_data_key);
1243   if (data)
1244     return data->attach_widget;
1245   return NULL;
1246 }
1247
1248 /**
1249  * gtk_menu_detach:
1250  * @menu: a #GtkMenu
1251  *
1252  * Detaches the menu from the widget to which it had been attached.
1253  * This function will call the callback function, @detacher, provided
1254  * when the gtk_menu_attach_to_widget() function was called.
1255  */
1256 void
1257 gtk_menu_detach (GtkMenu *menu)
1258 {
1259   GtkMenuAttachData *data;
1260   GList *list;
1261
1262   g_return_if_fail (GTK_IS_MENU (menu));
1263
1264   /* keep this function in sync with gtk_widget_unparent() */
1265   data = g_object_get_data (G_OBJECT (menu), attach_data_key);
1266   if (!data)
1267     {
1268       g_warning ("gtk_menu_detach(): menu is not attached");
1269       return;
1270     }
1271   g_object_set_data (G_OBJECT (menu), I_(attach_data_key), NULL);
1272
1273   /* Detach the toplevel window. */
1274   gtk_window_set_attached_to (GTK_WINDOW (menu->priv->toplevel), NULL);
1275
1276   g_signal_handlers_disconnect_by_func (data->attach_widget,
1277                                         (gpointer) attach_widget_screen_changed,
1278                                         menu);
1279
1280   if (data->detacher)
1281     data->detacher (data->attach_widget, menu);
1282   list = g_object_steal_data (G_OBJECT (data->attach_widget), ATTACHED_MENUS);
1283   list = g_list_remove (list, menu);
1284   if (list)
1285     g_object_set_data_full (G_OBJECT (data->attach_widget), I_(ATTACHED_MENUS), list,
1286                             (GDestroyNotify) g_list_free);
1287   else
1288     g_object_set_data (G_OBJECT (data->attach_widget), I_(ATTACHED_MENUS), NULL);
1289
1290   if (gtk_widget_get_realized (GTK_WIDGET (menu)))
1291     gtk_widget_unrealize (GTK_WIDGET (menu));
1292
1293   g_slice_free (GtkMenuAttachData, data);
1294
1295   /* Fallback title for menu comes from attach widget */
1296   gtk_menu_update_title (menu);
1297
1298   g_object_unref (menu);
1299 }
1300
1301 static void
1302 gtk_menu_remove (GtkContainer *container,
1303                  GtkWidget    *widget)
1304 {
1305   GtkMenu *menu = GTK_MENU (container);
1306   GtkMenuPrivate *priv = menu->priv;
1307
1308   /* Clear out old_active_menu_item if it matches the item we are removing */
1309   if (priv->old_active_menu_item == widget)
1310     g_clear_object (&priv->old_active_menu_item);
1311
1312   GTK_CONTAINER_CLASS (gtk_menu_parent_class)->remove (container, widget);
1313
1314   g_object_set_data (G_OBJECT (widget), I_(ATTACH_INFO_KEY), NULL);
1315
1316   menu_queue_resize (menu);
1317 }
1318
1319 /**
1320  * gtk_menu_new:
1321  *
1322  * Creates a new #GtkMenu
1323  *
1324  * Returns: a new #GtkMenu
1325  */
1326 GtkWidget*
1327 gtk_menu_new (void)
1328 {
1329   return g_object_new (GTK_TYPE_MENU, NULL);
1330 }
1331
1332 static void
1333 gtk_menu_real_insert (GtkMenuShell *menu_shell,
1334                       GtkWidget    *child,
1335                       gint          position)
1336 {
1337   GtkMenu *menu = GTK_MENU (menu_shell);
1338   GtkMenuPrivate *priv = menu->priv;
1339   AttachInfo *ai = get_attach_info (child);
1340
1341   ai->left_attach = -1;
1342   ai->right_attach = -1;
1343   ai->top_attach = -1;
1344   ai->bottom_attach = -1;
1345
1346   if (gtk_widget_get_realized (GTK_WIDGET (menu_shell)))
1347     gtk_widget_set_parent_window (child, priv->bin_window);
1348
1349   GTK_MENU_SHELL_CLASS (gtk_menu_parent_class)->insert (menu_shell, child, position);
1350
1351   menu_queue_resize (menu);
1352 }
1353
1354 static void
1355 gtk_menu_tearoff_bg_copy (GtkMenu *menu)
1356 {
1357   GtkMenuPrivate *priv = menu->priv;
1358   gint width, height;
1359
1360   if (priv->torn_off)
1361     {
1362       GdkWindow *window;
1363       cairo_surface_t *surface;
1364       cairo_pattern_t *pattern;
1365       cairo_t *cr;
1366
1367       priv->tearoff_active = FALSE;
1368       priv->saved_scroll_offset = priv->scroll_offset;
1369
1370       window = gtk_widget_get_window (priv->tearoff_window);
1371       width = gdk_window_get_width (window);
1372       height = gdk_window_get_height (window);
1373
1374       surface = gdk_window_create_similar_surface (window,
1375                                                    CAIRO_CONTENT_COLOR,
1376                                                    width,
1377                                                    height);
1378
1379       cr = cairo_create (surface);
1380       gdk_cairo_set_source_window (cr, window, 0, 0);
1381       cairo_paint (cr);
1382       cairo_destroy (cr);
1383
1384       gtk_widget_set_size_request (priv->tearoff_window, width, height);
1385
1386       pattern = cairo_pattern_create_for_surface (surface);
1387       gdk_window_set_background_pattern (window, pattern);
1388
1389       cairo_pattern_destroy (pattern);
1390       cairo_surface_destroy (surface);
1391     }
1392 }
1393
1394 static gboolean
1395 popup_grab_on_window (GdkWindow *window,
1396                       GdkDevice *keyboard,
1397                       GdkDevice *pointer,
1398                       guint32    activate_time)
1399 {
1400   if (keyboard &&
1401       gdk_device_grab (keyboard, window,
1402                        GDK_OWNERSHIP_WINDOW, TRUE,
1403                        GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK,
1404                        NULL, activate_time) != GDK_GRAB_SUCCESS)
1405     return FALSE;
1406
1407   if (pointer &&
1408       gdk_device_grab (pointer, window,
1409                        GDK_OWNERSHIP_WINDOW, TRUE,
1410                        GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
1411                        GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK |
1412                        GDK_POINTER_MOTION_MASK,
1413                        NULL, activate_time) != GDK_GRAB_SUCCESS)
1414     {
1415       if (keyboard)
1416         gdk_device_ungrab (keyboard, activate_time);
1417
1418       return FALSE;
1419     }
1420
1421   return TRUE;
1422 }
1423
1424 /**
1425  * gtk_menu_popup_for_device:
1426  * @menu: a #GtkMenu
1427  * @device: (allow-none): a #GdkDevice
1428  * @parent_menu_shell: (allow-none): the menu shell containing the triggering
1429  *     menu item, or %NULL
1430  * @parent_menu_item: (allow-none): the menu item whose activation triggered
1431  *     the popup, or %NULL
1432  * @func: (allow-none): a user supplied function used to position the menu,
1433  *     or %NULL
1434  * @data: (allow-none): user supplied data to be passed to @func
1435  * @destroy: (allow-none): destroy notify for @data
1436  * @button: the mouse button which was pressed to initiate the event
1437  * @activate_time: the time at which the activation event occurred
1438  *
1439  * Displays a menu and makes it available for selection.
1440  *
1441  * Applications can use this function to display context-sensitive menus,
1442  * and will typically supply %NULL for the @parent_menu_shell,
1443  * @parent_menu_item, @func, @data and @destroy parameters. The default
1444  * menu positioning function will position the menu at the current position
1445  * of @device (or its corresponding pointer).
1446  *
1447  * The @button parameter should be the mouse button pressed to initiate
1448  * the menu popup. If the menu popup was initiated by something other than
1449  * a mouse button press, such as a mouse button release or a keypress,
1450  * @button should be 0.
1451  *
1452  * The @activate_time parameter is used to conflict-resolve initiation of
1453  * concurrent requests for mouse/keyboard grab requests. To function
1454  * properly, this needs to be the time stamp of the user event (such as
1455  * a mouse click or key press) that caused the initiation of the popup.
1456  * Only if no such event is available, gtk_get_current_event_time() can
1457  * be used instead.
1458  *
1459  * Since: 3.0
1460  * Rename to: gtk_menu_popup
1461  */
1462 void
1463 gtk_menu_popup_for_device (GtkMenu             *menu,
1464                            GdkDevice           *device,
1465                            GtkWidget           *parent_menu_shell,
1466                            GtkWidget           *parent_menu_item,
1467                            GtkMenuPositionFunc  func,
1468                            gpointer             data,
1469                            GDestroyNotify       destroy,
1470                            guint                button,
1471                            guint32              activate_time)
1472 {
1473   GtkMenuPrivate *priv = menu->priv;
1474   GtkWidget *widget;
1475   GtkWidget *xgrab_shell;
1476   GtkWidget *parent;
1477   GdkEvent *current_event;
1478   GtkMenuShell *menu_shell;
1479   gboolean grab_keyboard;
1480   GtkWidget *parent_toplevel;
1481   GdkDevice *keyboard, *pointer, *source_device = NULL;
1482
1483   g_return_if_fail (GTK_IS_MENU (menu));
1484   g_return_if_fail (device == NULL || GDK_IS_DEVICE (device));
1485
1486   if (device == NULL)
1487     device = gtk_get_current_event_device ();
1488
1489   if (device == NULL)
1490     {
1491       GdkDisplay *display;
1492       GdkDeviceManager *device_manager;
1493       GList *devices;
1494
1495       display = gtk_widget_get_display (GTK_WIDGET (menu));
1496       device_manager = gdk_display_get_device_manager (display);
1497       devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
1498
1499       device = devices->data;
1500
1501       g_list_free (devices);
1502     }
1503
1504   widget = GTK_WIDGET (menu);
1505   menu_shell = GTK_MENU_SHELL (menu);
1506
1507   if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
1508     {
1509       keyboard = device;
1510       pointer = gdk_device_get_associated_device (device);
1511     }
1512   else
1513     {
1514       pointer = device;
1515       keyboard = gdk_device_get_associated_device (device);
1516     }
1517
1518   menu_shell->priv->parent_menu_shell = parent_menu_shell;
1519
1520   priv->seen_item_enter = FALSE;
1521
1522   /* Find the last viewable ancestor, and make an X grab on it
1523    */
1524   parent = GTK_WIDGET (menu);
1525   xgrab_shell = NULL;
1526   while (parent)
1527     {
1528       gboolean viewable = TRUE;
1529       GtkWidget *tmp = parent;
1530
1531       while (tmp)
1532         {
1533           if (!gtk_widget_get_mapped (tmp))
1534             {
1535               viewable = FALSE;
1536               break;
1537             }
1538           tmp = gtk_widget_get_parent (tmp);
1539         }
1540
1541       if (viewable)
1542         xgrab_shell = parent;
1543
1544       parent = GTK_MENU_SHELL (parent)->priv->parent_menu_shell;
1545     }
1546
1547   /* We want to receive events generated when we map the menu;
1548    * unfortunately, since there is probably already an implicit
1549    * grab in place from the button that the user used to pop up
1550    * the menu, we won't receive then -- in particular, the EnterNotify
1551    * when the menu pops up under the pointer.
1552    *
1553    * If we are grabbing on a parent menu shell, no problem; just grab
1554    * on that menu shell first before popping up the window with
1555    * owner_events = TRUE.
1556    *
1557    * When grabbing on the menu itself, things get more convoluted --
1558    * we do an explicit grab on a specially created window with
1559    * owner_events = TRUE, which we override further down with a
1560    * grab on the menu. (We can't grab on the menu until it is mapped;
1561    * we probably could just leave the grab on the other window,
1562    * with a little reorganization of the code in gtkmenu*).
1563    */
1564   grab_keyboard = gtk_menu_shell_get_take_focus (menu_shell);
1565   gtk_window_set_accept_focus (GTK_WINDOW (priv->toplevel), grab_keyboard);
1566
1567   if (!grab_keyboard)
1568     keyboard = NULL;
1569
1570   if (xgrab_shell && xgrab_shell != widget)
1571     {
1572       if (popup_grab_on_window (gtk_widget_get_window (xgrab_shell), keyboard, pointer, activate_time))
1573         {
1574           _gtk_menu_shell_set_grab_device (GTK_MENU_SHELL (xgrab_shell), pointer);
1575           GTK_MENU_SHELL (xgrab_shell)->priv->have_xgrab = TRUE;
1576         }
1577     }
1578   else
1579     {
1580       GdkWindow *transfer_window;
1581
1582       xgrab_shell = widget;
1583       transfer_window = menu_grab_transfer_window_get (menu);
1584       if (popup_grab_on_window (transfer_window, keyboard, pointer, activate_time))
1585         {
1586           _gtk_menu_shell_set_grab_device (GTK_MENU_SHELL (xgrab_shell), pointer);
1587           GTK_MENU_SHELL (xgrab_shell)->priv->have_xgrab = TRUE;
1588         }
1589     }
1590
1591   if (!GTK_MENU_SHELL (xgrab_shell)->priv->have_xgrab)
1592     {
1593       /* We failed to make our pointer/keyboard grab.
1594        * Rather than leaving the user with a stuck up window,
1595        * we just abort here. Presumably the user will try again.
1596        */
1597       menu_shell->priv->parent_menu_shell = NULL;
1598       menu_grab_transfer_window_destroy (menu);
1599       return;
1600     }
1601
1602   _gtk_menu_shell_set_grab_device (GTK_MENU_SHELL (menu), pointer);
1603   menu_shell->priv->active = TRUE;
1604   menu_shell->priv->button = button;
1605
1606   /* If we are popping up the menu from something other than, a button
1607    * press then, as a heuristic, we ignore enter events for the menu
1608    * until we get a MOTION_NOTIFY.
1609    */
1610
1611   current_event = gtk_get_current_event ();
1612   if (current_event)
1613     {
1614       if ((current_event->type != GDK_BUTTON_PRESS) &&
1615           (current_event->type != GDK_ENTER_NOTIFY))
1616         menu_shell->priv->ignore_enter = TRUE;
1617
1618       source_device = gdk_event_get_source_device (current_event);
1619       gdk_event_free (current_event);
1620     }
1621   else
1622     menu_shell->priv->ignore_enter = TRUE;
1623
1624   if (priv->torn_off)
1625     {
1626       gtk_menu_tearoff_bg_copy (menu);
1627
1628       gtk_menu_reparent (menu, priv->toplevel, FALSE);
1629     }
1630
1631   parent_toplevel = NULL;
1632   if (parent_menu_shell)
1633     parent_toplevel = gtk_widget_get_toplevel (parent_menu_shell);
1634   else if (!g_object_get_data (G_OBJECT (menu), "gtk-menu-explicit-screen"))
1635     {
1636       GtkWidget *attach_widget = gtk_menu_get_attach_widget (menu);
1637       if (attach_widget)
1638         parent_toplevel = gtk_widget_get_toplevel (attach_widget);
1639     }
1640
1641   /* Set transient for to get the right window group and parent */
1642   if (GTK_IS_WINDOW (parent_toplevel))
1643     gtk_window_set_transient_for (GTK_WINDOW (priv->toplevel),
1644                                   GTK_WINDOW (parent_toplevel));
1645
1646   priv->parent_menu_item = parent_menu_item;
1647   priv->position_func = func;
1648   priv->position_func_data = data;
1649   priv->position_func_data_destroy = destroy;
1650   menu_shell->priv->activate_time = activate_time;
1651
1652   /* We need to show the menu here rather in the init function
1653    * because code expects to be able to tell if the menu is onscreen
1654    * by looking at gtk_widget_get_visible (menu)
1655    */
1656   gtk_widget_show (GTK_WIDGET (menu));
1657
1658   /* Position the menu, possibly changing the size request
1659    */
1660   gtk_menu_position (menu, TRUE);
1661
1662   /* Compute the size of the toplevel and realize it so we
1663    * can scroll correctly.
1664    */
1665   if (!gtk_widget_get_realized (GTK_WIDGET (menu)))
1666   {
1667     GtkRequisition tmp_request;
1668     GtkAllocation tmp_allocation = { 0, };
1669
1670     /* Instead of trusting the menu position function to queue a
1671      * resize when the menu goes out of bounds, invalidate the cached
1672      * size here.
1673      */
1674     gtk_widget_queue_resize (GTK_WIDGET (menu));
1675     gtk_widget_get_preferred_size (priv->toplevel, &tmp_request, NULL);
1676
1677     tmp_allocation.width = tmp_request.width;
1678     tmp_allocation.height = tmp_request.height;
1679
1680     gtk_widget_size_allocate (priv->toplevel, &tmp_allocation);
1681
1682     gtk_widget_realize (priv->toplevel);
1683   }
1684
1685   gtk_menu_scroll_to (menu, priv->scroll_offset);
1686
1687   /* if no item is selected, select the first one */
1688   if (!menu_shell->priv->active_menu_item &&
1689       source_device && gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN)
1690     gtk_menu_shell_select_first (menu_shell, TRUE);
1691
1692   /* Once everything is set up correctly, map the toplevel */
1693   gtk_widget_show (priv->toplevel);
1694
1695   if (xgrab_shell == widget)
1696     popup_grab_on_window (gtk_widget_get_window (widget), keyboard, pointer, activate_time); /* Should always succeed */
1697
1698   gtk_device_grab_add (GTK_WIDGET (menu), pointer, TRUE);
1699
1700   if (parent_menu_shell)
1701     {
1702       gboolean keyboard_mode;
1703
1704       keyboard_mode = _gtk_menu_shell_get_keyboard_mode (GTK_MENU_SHELL (parent_menu_shell));
1705       _gtk_menu_shell_set_keyboard_mode (menu_shell, keyboard_mode);
1706     }
1707   else if (menu_shell->priv->button == 0) /* a keynav-activated context menu */
1708     _gtk_menu_shell_set_keyboard_mode (menu_shell, TRUE);
1709
1710   _gtk_menu_shell_update_mnemonics (menu_shell);
1711 }
1712
1713 /**
1714  * gtk_menu_popup: (skip)
1715  * @menu: a #GtkMenu
1716  * @parent_menu_shell: (allow-none): the menu shell containing the
1717  *     triggering menu item, or %NULL
1718  * @parent_menu_item: (allow-none): the menu item whose activation
1719  *     triggered the popup, or %NULL
1720  * @func: (allow-none): a user supplied function used to position
1721  *     the menu, or %NULL
1722  * @data: user supplied data to be passed to @func.
1723  * @button: the mouse button which was pressed to initiate the event.
1724  * @activate_time: the time at which the activation event occurred.
1725  *
1726  * Displays a menu and makes it available for selection.
1727  *
1728  * Applications can use this function to display context-sensitive
1729  * menus, and will typically supply %NULL for the @parent_menu_shell,
1730  * @parent_menu_item, @func and @data parameters. The default menu
1731  * positioning function will position the menu at the current mouse
1732  * cursor position.
1733  *
1734  * The @button parameter should be the mouse button pressed to initiate
1735  * the menu popup. If the menu popup was initiated by something other
1736  * than a mouse button press, such as a mouse button release or a keypress,
1737  * @button should be 0.
1738  *
1739  * The @activate_time parameter is used to conflict-resolve initiation
1740  * of concurrent requests for mouse/keyboard grab requests. To function
1741  * properly, this needs to be the timestamp of the user event (such as
1742  * a mouse click or key press) that caused the initiation of the popup.
1743  * Only if no such event is available, gtk_get_current_event_time() can
1744  * be used instead.
1745  */
1746 void
1747 gtk_menu_popup (GtkMenu             *menu,
1748                 GtkWidget           *parent_menu_shell,
1749                 GtkWidget           *parent_menu_item,
1750                 GtkMenuPositionFunc  func,
1751                 gpointer             data,
1752                 guint                button,
1753                 guint32              activate_time)
1754 {
1755   g_return_if_fail (GTK_IS_MENU (menu));
1756
1757   gtk_menu_popup_for_device (menu,
1758                              NULL,
1759                              parent_menu_shell,
1760                              parent_menu_item,
1761                              func, data, NULL,
1762                              button, activate_time);
1763 }
1764
1765 /**
1766  * gtk_menu_popdown:
1767  * @menu: a #GtkMenu
1768  *
1769  * Removes the menu from the screen.
1770  */
1771 void
1772 gtk_menu_popdown (GtkMenu *menu)
1773 {
1774   GtkMenuPrivate *priv;
1775   GtkMenuShell *menu_shell;
1776   GdkDevice *pointer;
1777
1778   g_return_if_fail (GTK_IS_MENU (menu));
1779
1780   menu_shell = GTK_MENU_SHELL (menu);
1781   priv = menu->priv;
1782
1783   menu_shell->priv->parent_menu_shell = NULL;
1784   menu_shell->priv->active = FALSE;
1785   menu_shell->priv->ignore_enter = FALSE;
1786
1787   priv->have_position = FALSE;
1788
1789   gtk_menu_stop_scrolling (menu);
1790   gtk_menu_stop_navigating_submenu (menu);
1791
1792   if (menu_shell->priv->active_menu_item)
1793     {
1794       if (priv->old_active_menu_item)
1795         g_object_unref (priv->old_active_menu_item);
1796       priv->old_active_menu_item = menu_shell->priv->active_menu_item;
1797       g_object_ref (priv->old_active_menu_item);
1798     }
1799
1800   gtk_menu_shell_deselect (menu_shell);
1801
1802   /* The X Grab, if present, will automatically be removed
1803    * when we hide the window
1804    */
1805   if (priv->toplevel)
1806     {
1807       gtk_widget_hide (priv->toplevel);
1808       gtk_window_set_transient_for (GTK_WINDOW (priv->toplevel), NULL);
1809     }
1810
1811   pointer = _gtk_menu_shell_get_grab_device (menu_shell);
1812
1813   if (priv->torn_off)
1814     {
1815       gtk_widget_set_size_request (priv->tearoff_window, -1, -1);
1816
1817       if (gtk_bin_get_child (GTK_BIN (priv->toplevel)))
1818         {
1819           gtk_menu_reparent (menu, priv->tearoff_hbox, TRUE);
1820         }
1821       else
1822         {
1823           /* We popped up the menu from the tearoff, so we need to
1824            * release the grab - we aren't actually hiding the menu.
1825            */
1826           if (menu_shell->priv->have_xgrab && pointer)
1827             {
1828               GdkDevice *keyboard;
1829
1830               gdk_device_ungrab (pointer, GDK_CURRENT_TIME);
1831               keyboard = gdk_device_get_associated_device (pointer);
1832
1833               if (keyboard)
1834                 gdk_device_ungrab (keyboard, GDK_CURRENT_TIME);
1835             }
1836         }
1837
1838       /* gtk_menu_popdown is called each time a menu item is selected from
1839        * a torn off menu. Only scroll back to the saved position if the
1840        * non-tearoff menu was popped down.
1841        */
1842       if (!priv->tearoff_active)
1843         gtk_menu_scroll_to (menu, priv->saved_scroll_offset);
1844       priv->tearoff_active = TRUE;
1845     }
1846   else
1847     gtk_widget_hide (GTK_WIDGET (menu));
1848
1849   menu_shell->priv->have_xgrab = FALSE;
1850
1851   if (pointer)
1852     gtk_device_grab_remove (GTK_WIDGET (menu), pointer);
1853
1854   _gtk_menu_shell_set_grab_device (menu_shell, NULL);
1855
1856   menu_grab_transfer_window_destroy (menu);
1857 }
1858
1859 /**
1860  * gtk_menu_get_active:
1861  * @menu: a #GtkMenu
1862  *
1863  * Returns the selected menu item from the menu.  This is used by the
1864  * #GtkOptionMenu.
1865  *
1866  * Returns: (transfer none): the #GtkMenuItem that was last selected
1867  *          in the menu.  If a selection has not yet been made, the
1868  *          first menu item is selected.
1869  */
1870 GtkWidget*
1871 gtk_menu_get_active (GtkMenu *menu)
1872 {
1873   GtkMenuPrivate *priv = menu->priv;
1874   GtkWidget *child;
1875   GList *children;
1876
1877   g_return_val_if_fail (GTK_IS_MENU (menu), NULL);
1878
1879   if (!priv->old_active_menu_item)
1880     {
1881       child = NULL;
1882       children = GTK_MENU_SHELL (menu)->priv->children;
1883
1884       while (children)
1885         {
1886           child = children->data;
1887           children = children->next;
1888
1889           if (gtk_bin_get_child (GTK_BIN (child)))
1890             break;
1891           child = NULL;
1892         }
1893
1894       priv->old_active_menu_item = child;
1895       if (priv->old_active_menu_item)
1896         g_object_ref (priv->old_active_menu_item);
1897     }
1898
1899   return priv->old_active_menu_item;
1900 }
1901
1902 /**
1903  * gtk_menu_set_active:
1904  * @menu: a #GtkMenu
1905  * @index: the index of the menu item to select.  Iindex values are
1906  *         from 0 to n-1
1907  *
1908  * Selects the specified menu item within the menu.  This is used by
1909  * the #GtkOptionMenu and should not be used by anyone else.
1910  */
1911 void
1912 gtk_menu_set_active (GtkMenu *menu,
1913                      guint    index)
1914 {
1915   GtkMenuPrivate *priv = menu->priv;
1916   GtkWidget *child;
1917   GList *tmp_list;
1918
1919   g_return_if_fail (GTK_IS_MENU (menu));
1920
1921   tmp_list = g_list_nth (GTK_MENU_SHELL (menu)->priv->children, index);
1922   if (tmp_list)
1923     {
1924       child = tmp_list->data;
1925       if (gtk_bin_get_child (GTK_BIN (child)))
1926         {
1927           if (priv->old_active_menu_item)
1928             g_object_unref (priv->old_active_menu_item);
1929           priv->old_active_menu_item = child;
1930           g_object_ref (priv->old_active_menu_item);
1931         }
1932     }
1933 }
1934
1935 /**
1936  * gtk_menu_set_accel_group:
1937  * @menu: a #GtkMenu
1938  * @accel_group: (allow-none): the #GtkAccelGroup to be associated
1939  *               with the menu.
1940  *
1941  * Set the #GtkAccelGroup which holds global accelerators for the
1942  * menu.  This accelerator group needs to also be added to all windows
1943  * that this menu is being used in with gtk_window_add_accel_group(),
1944  * in order for those windows to support all the accelerators
1945  * contained in this group.
1946  */
1947 void
1948 gtk_menu_set_accel_group (GtkMenu       *menu,
1949                           GtkAccelGroup *accel_group)
1950 {
1951   GtkMenuPrivate *priv = menu->priv;
1952   g_return_if_fail (GTK_IS_MENU (menu));
1953
1954   if (priv->accel_group != accel_group)
1955     {
1956       if (priv->accel_group)
1957         g_object_unref (priv->accel_group);
1958       priv->accel_group = accel_group;
1959       if (priv->accel_group)
1960         g_object_ref (priv->accel_group);
1961       _gtk_menu_refresh_accel_paths (menu, TRUE);
1962     }
1963 }
1964
1965 /**
1966  * gtk_menu_get_accel_group:
1967  * @menu: a #GtkMenu
1968  *
1969  * Gets the #GtkAccelGroup which holds global accelerators for the
1970  * menu. See gtk_menu_set_accel_group().
1971  *
1972  * Returns: (transfer none): the #GtkAccelGroup associated with the menu
1973  */
1974 GtkAccelGroup*
1975 gtk_menu_get_accel_group (GtkMenu *menu)
1976 {
1977   g_return_val_if_fail (GTK_IS_MENU (menu), NULL);
1978
1979   return menu->priv->accel_group;
1980 }
1981
1982 static gboolean
1983 gtk_menu_real_can_activate_accel (GtkWidget *widget,
1984                                   guint      signal_id)
1985 {
1986   /* Menu items chain here to figure whether they can activate their
1987    * accelerators.  Unlike ordinary widgets, menus allow accel
1988    * activation even if invisible since that's the usual case for
1989    * submenus/popup-menus. however, the state of the attach widget
1990    * affects the "activeness" of the menu.
1991    */
1992   GtkWidget *awidget = gtk_menu_get_attach_widget (GTK_MENU (widget));
1993
1994   if (awidget)
1995     return gtk_widget_can_activate_accel (awidget, signal_id);
1996   else
1997     return gtk_widget_is_sensitive (widget);
1998 }
1999
2000 /**
2001  * gtk_menu_set_accel_path
2002  * @menu:       a valid #GtkMenu
2003  * @accel_path: (allow-none): a valid accelerator path
2004  *
2005  * Sets an accelerator path for this menu from which accelerator paths
2006  * for its immediate children, its menu items, can be constructed.
2007  * The main purpose of this function is to spare the programmer the
2008  * inconvenience of having to call gtk_menu_item_set_accel_path() on
2009  * each menu item that should support runtime user changable accelerators.
2010  * Instead, by just calling gtk_menu_set_accel_path() on their parent,
2011  * each menu item of this menu, that contains a label describing its
2012  * purpose, automatically gets an accel path assigned.
2013  *
2014  * For example, a menu containing menu items "New" and "Exit", will, after
2015  * <literal>gtk_menu_set_accel_path (menu, "&lt;Gnumeric-Sheet&gt;/File");</literal>
2016  * has been called, assign its items the accel paths:
2017  * <literal>"&lt;Gnumeric-Sheet&gt;/File/New"</literal> and <literal>"&lt;Gnumeric-Sheet&gt;/File/Exit"</literal>.
2018  *
2019  * Assigning accel paths to menu items then enables the user to change
2020  * their accelerators at runtime. More details about accelerator paths
2021  * and their default setups can be found at gtk_accel_map_add_entry().
2022  *
2023  * Note that @accel_path string will be stored in a #GQuark. Therefore,
2024  * if you pass a static string, you can save some memory by interning
2025  * it first with g_intern_static_string().
2026  */
2027 void
2028 gtk_menu_set_accel_path (GtkMenu     *menu,
2029                          const gchar *accel_path)
2030 {
2031   GtkMenuPrivate *priv = menu->priv;
2032   g_return_if_fail (GTK_IS_MENU (menu));
2033
2034   if (accel_path)
2035     g_return_if_fail (accel_path[0] == '<' && strchr (accel_path, '/')); /* simplistic check */
2036
2037   /* FIXME: accel_path should be defined as const gchar* */
2038   priv->accel_path = (gchar*)g_intern_string (accel_path);
2039   if (priv->accel_path)
2040     _gtk_menu_refresh_accel_paths (menu, FALSE);
2041 }
2042
2043 /**
2044  * gtk_menu_get_accel_path
2045  * @menu: a valid #GtkMenu
2046  *
2047  * Retrieves the accelerator path set on the menu.
2048  *
2049  * Returns: the accelerator path set on the menu.
2050  *
2051  * Since: 2.14
2052  */
2053 const gchar*
2054 gtk_menu_get_accel_path (GtkMenu *menu)
2055 {
2056   g_return_val_if_fail (GTK_IS_MENU (menu), NULL);
2057
2058   return menu->priv->accel_path;
2059 }
2060
2061 typedef struct {
2062   GtkMenu *menu;
2063   gboolean group_changed;
2064 } AccelPropagation;
2065
2066 static void
2067 refresh_accel_paths_foreach (GtkWidget *widget,
2068                              gpointer   data)
2069 {
2070   GtkMenuPrivate *priv;
2071   AccelPropagation *prop = data;
2072
2073   if (GTK_IS_MENU_ITEM (widget))  /* should always be true */
2074     {
2075       priv = prop->menu->priv;
2076       _gtk_menu_item_refresh_accel_path (GTK_MENU_ITEM (widget),
2077                                          priv->accel_path,
2078                                          priv->accel_group,
2079                                          prop->group_changed);
2080     }
2081 }
2082
2083 static void
2084 _gtk_menu_refresh_accel_paths (GtkMenu  *menu,
2085                                gboolean  group_changed)
2086 {
2087   GtkMenuPrivate *priv = menu->priv;
2088   g_return_if_fail (GTK_IS_MENU (menu));
2089
2090   if (priv->accel_path && priv->accel_group)
2091     {
2092       AccelPropagation prop;
2093
2094       prop.menu = menu;
2095       prop.group_changed = group_changed;
2096       gtk_container_foreach (GTK_CONTAINER (menu),
2097                              refresh_accel_paths_foreach,
2098                              &prop);
2099     }
2100 }
2101
2102 /**
2103  * gtk_menu_reposition:
2104  * @menu: a #GtkMenu
2105  *
2106  * Repositions the menu according to its position function.
2107  */
2108 void
2109 gtk_menu_reposition (GtkMenu *menu)
2110 {
2111   g_return_if_fail (GTK_IS_MENU (menu));
2112
2113   if (!menu->priv->torn_off && gtk_widget_is_drawable (GTK_WIDGET (menu)))
2114     gtk_menu_position (menu, FALSE);
2115 }
2116
2117 static void
2118 gtk_menu_scrollbar_changed (GtkAdjustment *adjustment,
2119                             GtkMenu       *menu)
2120 {
2121   double value;
2122
2123   value = gtk_adjustment_get_value (adjustment);
2124   if (menu->priv->scroll_offset != value)
2125     gtk_menu_scroll_to (menu, value);
2126 }
2127
2128 static void
2129 gtk_menu_set_tearoff_hints (GtkMenu *menu,
2130                             gint     width)
2131 {
2132   GtkMenuPrivate *priv = menu->priv;
2133   GdkGeometry geometry_hints;
2134
2135   if (!priv->tearoff_window)
2136     return;
2137
2138   if (gtk_widget_get_visible (priv->tearoff_scrollbar))
2139     {
2140       GtkRequisition requisition;
2141
2142       gtk_widget_get_preferred_size (priv->tearoff_scrollbar,
2143                                      &requisition, NULL);
2144       width += requisition.width;
2145     }
2146
2147   geometry_hints.min_width = width;
2148   geometry_hints.max_width = width;
2149
2150   geometry_hints.min_height = 0;
2151   geometry_hints.max_height = priv->requested_height;
2152
2153   gtk_window_set_geometry_hints (GTK_WINDOW (priv->tearoff_window),
2154                                  NULL,
2155                                  &geometry_hints,
2156                                  GDK_HINT_MAX_SIZE|GDK_HINT_MIN_SIZE);
2157 }
2158
2159 static void
2160 gtk_menu_update_title (GtkMenu *menu)
2161 {
2162   GtkMenuPrivate *priv = menu->priv;
2163
2164   if (priv->tearoff_window)
2165     {
2166       const gchar *title;
2167       GtkWidget *attach_widget;
2168
2169       title = gtk_menu_get_title (menu);
2170       if (!title)
2171         {
2172           attach_widget = gtk_menu_get_attach_widget (menu);
2173           if (GTK_IS_MENU_ITEM (attach_widget))
2174             {
2175               GtkWidget *child = gtk_bin_get_child (GTK_BIN (attach_widget));
2176               if (GTK_IS_LABEL (child))
2177                 title = gtk_label_get_text (GTK_LABEL (child));
2178             }
2179         }
2180
2181       if (title)
2182         gtk_window_set_title (GTK_WINDOW (priv->tearoff_window), title);
2183     }
2184 }
2185
2186 static GtkWidget*
2187 gtk_menu_get_toplevel (GtkWidget *menu)
2188 {
2189   GtkWidget *attach, *toplevel;
2190
2191   attach = gtk_menu_get_attach_widget (GTK_MENU (menu));
2192
2193   if (GTK_IS_MENU_ITEM (attach))
2194     attach = gtk_widget_get_parent (attach);
2195
2196   if (GTK_IS_MENU (attach))
2197     return gtk_menu_get_toplevel (attach);
2198   else if (GTK_IS_WIDGET (attach))
2199     {
2200       toplevel = gtk_widget_get_toplevel (attach);
2201       if (gtk_widget_is_toplevel (toplevel))
2202         return toplevel;
2203     }
2204
2205   return NULL;
2206 }
2207
2208 static void
2209 tearoff_window_destroyed (GtkWidget *widget,
2210                           GtkMenu   *menu)
2211 {
2212   gtk_menu_set_tearoff_state (menu, FALSE);
2213 }
2214
2215 /**
2216  * gtk_menu_set_tearoff_state:
2217  * @menu: a #GtkMenu
2218  * @torn_off: If %TRUE, menu is displayed as a tearoff menu.
2219  *
2220  * Changes the tearoff state of the menu.  A menu is normally
2221  * displayed as drop down menu which persists as long as the menu is
2222  * active.  It can also be displayed as a tearoff menu which persists
2223  * until it is closed or reattached.
2224  */
2225 void
2226 gtk_menu_set_tearoff_state (GtkMenu  *menu,
2227                             gboolean  torn_off)
2228 {
2229   GtkMenuPrivate *priv = menu->priv;
2230   gint height;
2231
2232   g_return_if_fail (GTK_IS_MENU (menu));
2233
2234   if (priv->torn_off != torn_off)
2235     {
2236       priv->torn_off = torn_off;
2237       priv->tearoff_active = torn_off;
2238
2239       if (priv->torn_off)
2240         {
2241           if (gtk_widget_get_visible (GTK_WIDGET (menu)))
2242             gtk_menu_popdown (menu);
2243
2244           if (!priv->tearoff_window)
2245             {
2246               GtkWidget *toplevel;
2247
2248               priv->tearoff_window = g_object_new (GTK_TYPE_WINDOW,
2249                                                    "type", GTK_WINDOW_TOPLEVEL,
2250                                                    "screen", gtk_widget_get_screen (priv->toplevel),
2251                                                    "app-paintable", TRUE,
2252                                                    NULL);
2253
2254               gtk_window_set_type_hint (GTK_WINDOW (priv->tearoff_window),
2255                                         GDK_WINDOW_TYPE_HINT_MENU);
2256               gtk_window_set_mnemonic_modifier (GTK_WINDOW (priv->tearoff_window), 0);
2257               g_signal_connect (priv->tearoff_window, "destroy",
2258                                 G_CALLBACK (tearoff_window_destroyed), menu);
2259               g_signal_connect (priv->tearoff_window, "event",
2260                                 G_CALLBACK (gtk_menu_window_event), menu);
2261
2262               gtk_menu_update_title (menu);
2263
2264               gtk_widget_realize (priv->tearoff_window);
2265
2266               toplevel = gtk_menu_get_toplevel (GTK_WIDGET (menu));
2267               if (toplevel != NULL)
2268                 gtk_window_set_transient_for (GTK_WINDOW (priv->tearoff_window),
2269                                               GTK_WINDOW (toplevel));
2270
2271               priv->tearoff_hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0);
2272               gtk_container_add (GTK_CONTAINER (priv->tearoff_window),
2273                                  priv->tearoff_hbox);
2274
2275               height = gdk_window_get_height (gtk_widget_get_window (GTK_WIDGET (menu)));
2276               priv->tearoff_adjustment = gtk_adjustment_new (0,
2277                                                              0, priv->requested_height,
2278                                                              MENU_SCROLL_STEP2,
2279                                                              height/2,
2280                                                              height);
2281               g_object_connect (priv->tearoff_adjustment,
2282                                 "signal::value-changed", gtk_menu_scrollbar_changed, menu,
2283                                 NULL);
2284               priv->tearoff_scrollbar = gtk_scrollbar_new (GTK_ORIENTATION_VERTICAL, priv->tearoff_adjustment);
2285
2286               gtk_box_pack_end (GTK_BOX (priv->tearoff_hbox),
2287                                 priv->tearoff_scrollbar,
2288                                 FALSE, FALSE, 0);
2289
2290               if (gtk_adjustment_get_upper (priv->tearoff_adjustment) > height)
2291                 gtk_widget_show (priv->tearoff_scrollbar);
2292
2293               gtk_widget_show (priv->tearoff_hbox);
2294             }
2295
2296           gtk_menu_reparent (menu, priv->tearoff_hbox, FALSE);
2297
2298           /* Update menu->requisition */
2299           gtk_widget_get_preferred_size (GTK_WIDGET (menu), NULL, NULL);
2300
2301           gtk_menu_set_tearoff_hints (menu, gdk_window_get_width (gtk_widget_get_window (GTK_WIDGET (menu))));
2302
2303           gtk_widget_realize (priv->tearoff_window);
2304           gtk_menu_position (menu, TRUE);
2305
2306           gtk_widget_show (GTK_WIDGET (menu));
2307           gtk_widget_show (priv->tearoff_window);
2308
2309           gtk_menu_scroll_to (menu, 0);
2310
2311         }
2312       else
2313         {
2314           gtk_widget_hide (GTK_WIDGET (menu));
2315           gtk_widget_hide (priv->tearoff_window);
2316           if (GTK_IS_CONTAINER (priv->toplevel))
2317             gtk_menu_reparent (menu, priv->toplevel, FALSE);
2318           gtk_widget_destroy (priv->tearoff_window);
2319
2320           priv->tearoff_window = NULL;
2321           priv->tearoff_hbox = NULL;
2322           priv->tearoff_scrollbar = NULL;
2323           priv->tearoff_adjustment = NULL;
2324         }
2325
2326       g_object_notify (G_OBJECT (menu), "tearoff-state");
2327     }
2328 }
2329
2330 /**
2331  * gtk_menu_get_tearoff_state:
2332  * @menu: a #GtkMenu
2333  *
2334  * Returns whether the menu is torn off.
2335  * See gtk_menu_set_tearoff_state().
2336  *
2337  * Return value: %TRUE if the menu is currently torn off.
2338  */
2339 gboolean
2340 gtk_menu_get_tearoff_state (GtkMenu *menu)
2341 {
2342   g_return_val_if_fail (GTK_IS_MENU (menu), FALSE);
2343
2344   return menu->priv->torn_off;
2345 }
2346
2347 /**
2348  * gtk_menu_set_title:
2349  * @menu: a #GtkMenu
2350  * @title: a string containing the title for the menu
2351  *
2352  * Sets the title string for the menu.
2353  *
2354  * The title is displayed when the menu is shown as a tearoff
2355  * menu. If @title is %NULL, the menu will see if it is attached
2356  * to a parent menu item, and if so it will try to use the same
2357  * text as that menu item's label.
2358  */
2359 void
2360 gtk_menu_set_title (GtkMenu     *menu,
2361                     const gchar *title)
2362 {
2363   GtkMenuPrivate *priv = menu->priv;
2364   char *old_title;
2365
2366   g_return_if_fail (GTK_IS_MENU (menu));
2367
2368   old_title = priv->title;
2369   priv->title = g_strdup (title);
2370   g_free (old_title);
2371
2372   gtk_menu_update_title (menu);
2373   g_object_notify (G_OBJECT (menu), "tearoff-title");
2374 }
2375
2376 /**
2377  * gtk_menu_get_title:
2378  * @menu: a #GtkMenu
2379  *
2380  * Returns the title of the menu. See gtk_menu_set_title().
2381  *
2382  * Return value: the title of the menu, or %NULL if the menu
2383  *     has no title set on it. This string is owned by GTK+
2384  *     and should not be modified or freed.
2385  **/
2386 const gchar *
2387 gtk_menu_get_title (GtkMenu *menu)
2388 {
2389   g_return_val_if_fail (GTK_IS_MENU (menu), NULL);
2390
2391   return menu->priv->title;
2392 }
2393
2394 /**
2395  * gtk_menu_reorder_child:
2396  * @menu: a #GtkMenu
2397  * @child: the #GtkMenuItem to move
2398  * @position: the new position to place @child.
2399  *     Positions are numbered from 0 to n - 1
2400  *
2401  * Moves @child to a new @position in the list of @menu
2402  * children.
2403  */
2404 void
2405 gtk_menu_reorder_child (GtkMenu   *menu,
2406                         GtkWidget *child,
2407                         gint       position)
2408 {
2409   GtkMenuShell *menu_shell;
2410
2411   g_return_if_fail (GTK_IS_MENU (menu));
2412   g_return_if_fail (GTK_IS_MENU_ITEM (child));
2413
2414   menu_shell = GTK_MENU_SHELL (menu);
2415
2416   if (g_list_find (menu_shell->priv->children, child))
2417     {
2418       menu_shell->priv->children = g_list_remove (menu_shell->priv->children, child);
2419       menu_shell->priv->children = g_list_insert (menu_shell->priv->children, child, position);
2420
2421       menu_queue_resize (menu);
2422     }
2423 }
2424
2425 static void
2426 gtk_menu_style_updated (GtkWidget *widget)
2427 {
2428   GTK_WIDGET_CLASS (gtk_menu_parent_class)->style_updated (widget);
2429
2430   if (gtk_widget_get_realized (widget))
2431     {
2432       GtkMenu *menu = GTK_MENU (widget);
2433       GtkMenuPrivate *priv = menu->priv;
2434       GtkStyleContext *context;
2435
2436       context = gtk_widget_get_style_context (widget);
2437
2438       gtk_style_context_set_background (context, priv->bin_window);
2439       gtk_style_context_set_background (context, priv->view_window);
2440       gtk_style_context_set_background (context, gtk_widget_get_window (widget));
2441     }
2442 }
2443
2444 static void
2445 get_arrows_border (GtkMenu   *menu,
2446                    GtkBorder *border)
2447 {
2448   GtkMenuPrivate *priv = menu->priv;
2449   guint scroll_arrow_height;
2450   GtkArrowPlacement arrow_placement;
2451
2452   gtk_widget_style_get (GTK_WIDGET (menu),
2453                         "scroll-arrow-vlength", &scroll_arrow_height,
2454                         "arrow_placement", &arrow_placement,
2455                         NULL);
2456
2457   switch (arrow_placement)
2458     {
2459     case GTK_ARROWS_BOTH:
2460       border->top = priv->upper_arrow_visible ? scroll_arrow_height : 0;
2461       border->bottom = priv->lower_arrow_visible ? scroll_arrow_height : 0;
2462       break;
2463
2464     case GTK_ARROWS_START:
2465       border->top = (priv->upper_arrow_visible ||
2466                      priv->lower_arrow_visible) ? scroll_arrow_height : 0;
2467       border->bottom = 0;
2468       break;
2469
2470     case GTK_ARROWS_END:
2471       border->top = 0;
2472       border->bottom = (priv->upper_arrow_visible ||
2473                         priv->lower_arrow_visible) ? scroll_arrow_height : 0;
2474       break;
2475     }
2476
2477   border->left = border->right = 0;
2478 }
2479
2480 static void
2481 get_menu_padding (GtkWidget *widget,
2482                   GtkBorder *padding)
2483 {
2484   GtkStyleContext *context;
2485   GtkStateFlags state;
2486
2487   context = gtk_widget_get_style_context (widget);
2488   state = gtk_widget_get_state_flags (widget);
2489
2490   gtk_style_context_get_padding (context, state, padding);
2491 }
2492
2493 static void
2494 gtk_menu_realize (GtkWidget *widget)
2495 {
2496   GtkMenu *menu = GTK_MENU (widget);
2497   GtkMenuPrivate *priv = menu->priv;
2498   GtkAllocation allocation;
2499   GtkStyleContext *context;
2500   GdkWindow *window;
2501   GdkWindowAttr attributes;
2502   gint attributes_mask;
2503   gint border_width;
2504   GtkWidget *child;
2505   GList *children;
2506   guint vertical_padding;
2507   guint horizontal_padding;
2508   GtkBorder arrow_border, padding;
2509
2510   g_return_if_fail (GTK_IS_MENU (widget));
2511
2512   gtk_widget_set_realized (widget, TRUE);
2513
2514   gtk_widget_get_allocation (widget, &allocation);
2515
2516   attributes.window_type = GDK_WINDOW_CHILD;
2517   attributes.x = allocation.x;
2518   attributes.y = allocation.y;
2519   attributes.width = allocation.width;
2520   attributes.height = allocation.height;
2521   attributes.wclass = GDK_INPUT_OUTPUT;
2522   attributes.visual = gtk_widget_get_visual (widget);
2523   attributes.event_mask = gtk_widget_get_events (widget);
2524   attributes.event_mask |= (GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK |
2525                             GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK );
2526
2527   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL;
2528
2529   window = gdk_window_new (gtk_widget_get_parent_window (widget),
2530                            &attributes, attributes_mask);
2531   gtk_widget_set_window (widget, window);
2532   gdk_window_set_user_data (window, widget);
2533
2534   get_menu_padding (widget, &padding);
2535   border_width = gtk_container_get_border_width (GTK_CONTAINER (widget));
2536   context = gtk_widget_get_style_context (widget);
2537
2538   gtk_widget_style_get (GTK_WIDGET (menu),
2539                         "vertical-padding", &vertical_padding,
2540                         "horizontal-padding", &horizontal_padding,
2541                         NULL);
2542
2543   gtk_widget_get_allocation (widget, &allocation);
2544
2545   attributes.x = border_width + padding.left + horizontal_padding;
2546   attributes.y = border_width + padding.top + vertical_padding;
2547   attributes.width = allocation.width -
2548     (2 * (border_width + horizontal_padding)) - padding.left - padding.right;
2549   attributes.height = allocation.height -
2550     (2 * (border_width + vertical_padding)) - padding.top - padding.bottom;
2551
2552   get_arrows_border (menu, &arrow_border);
2553   attributes.y += arrow_border.top;
2554   attributes.height -= arrow_border.top;
2555   attributes.height -= arrow_border.bottom;
2556
2557   attributes.width = MAX (1, attributes.width);
2558   attributes.height = MAX (1, attributes.height);
2559
2560   priv->view_window = gdk_window_new (window,
2561                                       &attributes, attributes_mask);
2562   gdk_window_set_user_data (priv->view_window, menu);
2563
2564   gtk_widget_get_allocation (widget, &allocation);
2565
2566   attributes.x = 0;
2567   attributes.y = 0;
2568   attributes.width = allocation.width + (2 * (border_width + horizontal_padding)) +
2569     padding.left + padding.right;
2570   attributes.height = priv->requested_height - (2 * (border_width + vertical_padding)) +
2571     padding.top + padding.bottom;
2572
2573   attributes.width = MAX (1, attributes.width);
2574   attributes.height = MAX (1, attributes.height);
2575
2576   priv->bin_window = gdk_window_new (priv->view_window,
2577                                      &attributes, attributes_mask);
2578   gdk_window_set_user_data (priv->bin_window, menu);
2579
2580   children = GTK_MENU_SHELL (menu)->priv->children;
2581   while (children)
2582     {
2583       child = children->data;
2584       children = children->next;
2585
2586       gtk_widget_set_parent_window (child, priv->bin_window);
2587     }
2588
2589   gtk_style_context_set_background (context, priv->bin_window);
2590   gtk_style_context_set_background (context, priv->view_window);
2591   gtk_style_context_set_background (context, window);
2592
2593   if (GTK_MENU_SHELL (widget)->priv->active_menu_item)
2594     gtk_menu_scroll_item_visible (GTK_MENU_SHELL (widget),
2595                                   GTK_MENU_SHELL (widget)->priv->active_menu_item);
2596
2597   gdk_window_show (priv->bin_window);
2598   gdk_window_show (priv->view_window);
2599 }
2600
2601 static gboolean
2602 gtk_menu_focus (GtkWidget       *widget,
2603                 GtkDirectionType direction)
2604 {
2605   /* A menu or its menu items cannot have focus */
2606   return FALSE;
2607 }
2608
2609 /* See notes in gtk_menu_popup() for information
2610  * about the "grab transfer window"
2611  */
2612 static GdkWindow *
2613 menu_grab_transfer_window_get (GtkMenu *menu)
2614 {
2615   GdkWindow *window = g_object_get_data (G_OBJECT (menu), "gtk-menu-transfer-window");
2616   if (!window)
2617     {
2618       GdkWindowAttr attributes;
2619       gint attributes_mask;
2620
2621       attributes.x = -100;
2622       attributes.y = -100;
2623       attributes.width = 10;
2624       attributes.height = 10;
2625       attributes.window_type = GDK_WINDOW_TEMP;
2626       attributes.wclass = GDK_INPUT_ONLY;
2627       attributes.override_redirect = TRUE;
2628       attributes.event_mask = 0;
2629
2630       attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_NOREDIR;
2631
2632       window = gdk_window_new (gtk_widget_get_root_window (GTK_WIDGET (menu)),
2633                                &attributes, attributes_mask);
2634       gdk_window_set_user_data (window, menu);
2635
2636       gdk_window_show (window);
2637
2638       g_object_set_data (G_OBJECT (menu), I_("gtk-menu-transfer-window"), window);
2639     }
2640
2641   return window;
2642 }
2643
2644 static void
2645 menu_grab_transfer_window_destroy (GtkMenu *menu)
2646 {
2647   GdkWindow *window = g_object_get_data (G_OBJECT (menu), "gtk-menu-transfer-window");
2648   if (window)
2649     {
2650       gdk_window_set_user_data (window, NULL);
2651       gdk_window_destroy (window);
2652       g_object_set_data (G_OBJECT (menu), I_("gtk-menu-transfer-window"), NULL);
2653     }
2654 }
2655
2656 static void
2657 gtk_menu_unrealize (GtkWidget *widget)
2658 {
2659   GtkMenu *menu = GTK_MENU (widget);
2660   GtkMenuPrivate *priv = menu->priv;
2661
2662   menu_grab_transfer_window_destroy (menu);
2663
2664   gdk_window_set_user_data (priv->view_window, NULL);
2665   gdk_window_destroy (priv->view_window);
2666   priv->view_window = NULL;
2667
2668   gdk_window_set_user_data (priv->bin_window, NULL);
2669   gdk_window_destroy (priv->bin_window);
2670   priv->bin_window = NULL;
2671
2672   GTK_WIDGET_CLASS (gtk_menu_parent_class)->unrealize (widget);
2673 }
2674
2675 static gint
2676 calculate_line_heights (GtkMenu *menu,
2677                         gint     for_width,
2678                         guint  **ret_min_heights,
2679                         guint  **ret_nat_heights)
2680 {
2681   GtkBorder       padding;
2682   GtkMenuPrivate *priv;
2683   GtkMenuShell   *menu_shell;
2684   GtkWidget      *child, *widget;
2685   GList          *children;
2686   guint           horizontal_padding;
2687   guint           border_width;
2688   guint           n_columns;
2689   gint            n_heights;
2690   guint          *min_heights;
2691   guint          *nat_heights;
2692   gint            avail_width;
2693
2694   priv         = menu->priv;
2695   widget       = GTK_WIDGET (menu);
2696   menu_shell   = GTK_MENU_SHELL (widget);
2697
2698   min_heights  = g_new0 (guint, gtk_menu_get_n_rows (menu));
2699   nat_heights  = g_new0 (guint, gtk_menu_get_n_rows (menu));
2700   n_heights    = gtk_menu_get_n_rows (menu);
2701   n_columns    = gtk_menu_get_n_columns (menu);
2702   avail_width  = for_width - (2 * priv->toggle_size + priv->accel_size) * n_columns;
2703
2704   gtk_widget_style_get (GTK_WIDGET (menu),
2705                         "horizontal-padding", &horizontal_padding,
2706                         NULL);
2707   get_menu_padding (widget, &padding);
2708
2709   border_width = gtk_container_get_border_width (GTK_CONTAINER (menu));
2710   avail_width -= (border_width + horizontal_padding) * 2 + padding.left + padding.right;
2711
2712   for (children = menu_shell->priv->children; children; children = children->next)
2713     {
2714       gint part;
2715       gint toggle_size;
2716       gint l, r, t, b;
2717       gint child_min, child_nat;
2718
2719       child = children->data;
2720
2721       if (!gtk_widget_get_visible (child))
2722         continue;
2723
2724       get_effective_child_attach (child, &l, &r, &t, &b);
2725
2726       part = avail_width / (r - l);
2727
2728       gtk_widget_get_preferred_height_for_width (child, part,
2729                                                  &child_min, &child_nat);
2730
2731       gtk_menu_item_toggle_size_request (GTK_MENU_ITEM (child), &toggle_size);
2732
2733       part = MAX (child_min, toggle_size) / (b - t);
2734       min_heights[t] = MAX (min_heights[t], part);
2735
2736       part = MAX (child_nat, toggle_size) / (b - t);
2737       nat_heights[t] = MAX (nat_heights[t], part);
2738     }
2739
2740   if (ret_min_heights)
2741     *ret_min_heights = min_heights;
2742   else
2743     g_free (min_heights);
2744
2745   if (ret_nat_heights)
2746     *ret_nat_heights = nat_heights;
2747   else
2748     g_free (nat_heights);
2749
2750   return n_heights;
2751 }
2752
2753 static void
2754 gtk_menu_size_allocate (GtkWidget     *widget,
2755                         GtkAllocation *allocation)
2756 {
2757   GtkMenu *menu;
2758   GtkMenuPrivate *priv;
2759   GtkMenuShell *menu_shell;
2760   GtkWidget *child;
2761   GtkAllocation child_allocation;
2762   GList *children;
2763   gint x, y, i;
2764   gint width, height;
2765   guint border_width;
2766   guint vertical_padding;
2767   guint horizontal_padding;
2768   GtkBorder padding;
2769
2770   g_return_if_fail (GTK_IS_MENU (widget));
2771   g_return_if_fail (allocation != NULL);
2772
2773   menu = GTK_MENU (widget);
2774   menu_shell = GTK_MENU_SHELL (widget);
2775   priv = menu->priv;
2776
2777   gtk_widget_set_allocation (widget, allocation);
2778
2779   gtk_widget_style_get (GTK_WIDGET (menu),
2780                         "vertical-padding", &vertical_padding,
2781                         "horizontal-padding", &horizontal_padding,
2782                         NULL);
2783
2784   get_menu_padding (widget, &padding);
2785   border_width = gtk_container_get_border_width (GTK_CONTAINER (menu));
2786
2787   g_free (priv->heights);
2788   priv->heights_length = calculate_line_heights (menu,
2789                                                  allocation->width,
2790                                                  &priv->heights,
2791                                                  NULL);
2792
2793   /* refresh our cached height request */
2794   priv->requested_height = (2 * (border_width + vertical_padding)) +
2795     padding.top + padding.bottom;
2796   for (i = 0; i < priv->heights_length; i++)
2797     priv->requested_height += priv->heights[i];
2798
2799   x = border_width + padding.left + horizontal_padding;
2800   y = border_width + padding.top + vertical_padding;
2801   width = allocation->width - (2 * (border_width + horizontal_padding)) -
2802     padding.left - padding.right;
2803   height = allocation->height - (2 * (border_width + vertical_padding)) -
2804     padding.top - padding.bottom;
2805
2806   if (menu_shell->priv->active)
2807     gtk_menu_scroll_to (menu, priv->scroll_offset);
2808
2809   if (!priv->tearoff_active)
2810     {
2811       GtkBorder arrow_border;
2812
2813       get_arrows_border (menu, &arrow_border);
2814       y += arrow_border.top;
2815       height -= arrow_border.top;
2816       height -= arrow_border.bottom;
2817     }
2818
2819   width = MAX (1, width);
2820   height = MAX (1, height);
2821
2822   if (gtk_widget_get_realized (widget))
2823     {
2824       gdk_window_move_resize (gtk_widget_get_window (widget),
2825                               allocation->x, allocation->y,
2826                               allocation->width, allocation->height);
2827
2828       gdk_window_move_resize (priv->view_window, x, y, width, height);
2829     }
2830
2831   if (menu_shell->priv->children)
2832     {
2833       gint base_width = width / gtk_menu_get_n_columns (menu);
2834
2835       children = menu_shell->priv->children;
2836       while (children)
2837         {
2838           child = children->data;
2839           children = children->next;
2840
2841           if (gtk_widget_get_visible (child))
2842             {
2843               gint i;
2844               gint l, r, t, b;
2845
2846               get_effective_child_attach (child, &l, &r, &t, &b);
2847
2848               if (gtk_widget_get_direction (GTK_WIDGET (menu)) == GTK_TEXT_DIR_RTL)
2849                 {
2850                   guint tmp;
2851                   tmp = gtk_menu_get_n_columns (menu) - l;
2852                   l = gtk_menu_get_n_columns (menu) - r;
2853                   r = tmp;
2854                 }
2855
2856               child_allocation.width = (r - l) * base_width;
2857               child_allocation.height = 0;
2858               child_allocation.x = l * base_width;
2859               child_allocation.y = 0;
2860
2861               for (i = 0; i < b; i++)
2862                 {
2863                   if (i < t)
2864                     child_allocation.y += priv->heights[i];
2865                   else
2866                     child_allocation.height += priv->heights[i];
2867                 }
2868
2869               gtk_menu_item_toggle_size_allocate (GTK_MENU_ITEM (child),
2870                                                   priv->toggle_size);
2871
2872               gtk_widget_size_allocate (child, &child_allocation);
2873               gtk_widget_queue_draw (child);
2874             }
2875         }
2876
2877       /* Resize the item window */
2878       if (gtk_widget_get_realized (widget))
2879         {
2880           gint i;
2881           gint width, height;
2882
2883           height = 0;
2884           for (i = 0; i < gtk_menu_get_n_rows (menu); i++)
2885             height += priv->heights[i];
2886
2887           width = gtk_menu_get_n_columns (menu) * base_width;
2888           gdk_window_resize (priv->bin_window, width, height);
2889         }
2890
2891       if (priv->tearoff_active)
2892         {
2893           if (height >= priv->requested_height)
2894             {
2895               if (gtk_widget_get_visible (priv->tearoff_scrollbar))
2896                 {
2897                   gtk_widget_hide (priv->tearoff_scrollbar);
2898                   gtk_menu_set_tearoff_hints (menu, allocation->width);
2899
2900                   gtk_menu_scroll_to (menu, 0);
2901                 }
2902             }
2903           else
2904             {
2905               gtk_adjustment_configure (priv->tearoff_adjustment,
2906                                         gtk_adjustment_get_value (priv->tearoff_adjustment),
2907                                         0,
2908                                         priv->requested_height,
2909                                         gtk_adjustment_get_step_increment (priv->tearoff_adjustment),
2910                                         gtk_adjustment_get_page_increment (priv->tearoff_adjustment),
2911                                         allocation->height);
2912
2913               if (!gtk_widget_get_visible (priv->tearoff_scrollbar))
2914                 {
2915                   gtk_widget_show (priv->tearoff_scrollbar);
2916                   gtk_menu_set_tearoff_hints (menu, allocation->width);
2917                 }
2918             }
2919         }
2920     }
2921 }
2922
2923 static void
2924 get_arrows_visible_area (GtkMenu      *menu,
2925                          GdkRectangle *border,
2926                          GdkRectangle *upper,
2927                          GdkRectangle *lower,
2928                          gint         *arrow_space)
2929 {
2930   GtkArrowPlacement arrow_placement;
2931   GtkWidget *widget = GTK_WIDGET (menu);
2932   guint border_width;
2933   guint vertical_padding;
2934   guint horizontal_padding;
2935   gint scroll_arrow_height;
2936   GtkBorder menu_padding;
2937
2938   gtk_widget_style_get (widget,
2939                         "vertical-padding", &vertical_padding,
2940                         "horizontal-padding", &horizontal_padding,
2941                         "scroll-arrow-vlength", &scroll_arrow_height,
2942                         "arrow-placement", &arrow_placement,
2943                         NULL);
2944
2945   get_menu_padding (widget, &menu_padding);
2946   border_width = gtk_container_get_border_width (GTK_CONTAINER (widget));
2947   border->x = border_width + menu_padding.left + horizontal_padding;
2948   border->y = border_width + menu_padding.top + vertical_padding;
2949   border->width = gdk_window_get_width (gtk_widget_get_window (widget));
2950   border->height = gdk_window_get_height (gtk_widget_get_window (widget));
2951
2952   switch (arrow_placement)
2953     {
2954     case GTK_ARROWS_BOTH:
2955       upper->x = border->x;
2956       upper->y = border->y;
2957       upper->width = border->width - 2 * border->x;
2958       upper->height = scroll_arrow_height;
2959
2960       lower->x = border->x;
2961       lower->y = border->height - border->y - scroll_arrow_height;
2962       lower->width = border->width - 2 * border->x;
2963       lower->height = scroll_arrow_height;
2964       break;
2965
2966     case GTK_ARROWS_START:
2967       upper->x = border->x;
2968       upper->y = border->y;
2969       upper->width = (border->width - 2 * border->x) / 2;
2970       upper->height = scroll_arrow_height;
2971
2972       lower->x = border->x + upper->width;
2973       lower->y = border->y;
2974       lower->width = (border->width - 2 * border->x) / 2;
2975       lower->height = scroll_arrow_height;
2976       break;
2977
2978     case GTK_ARROWS_END:
2979       upper->x = border->x;
2980       upper->y = border->height - border->y - scroll_arrow_height;
2981       upper->width = (border->width - 2 * border->x) / 2;
2982       upper->height = scroll_arrow_height;
2983
2984       lower->x = border->x + upper->width;
2985       lower->y = border->height - border->y - scroll_arrow_height;
2986       lower->width = (border->width - 2 * border->x) / 2;
2987       lower->height = scroll_arrow_height;
2988       break;
2989
2990     default:
2991        g_assert_not_reached();
2992        upper->x = upper->y = upper->width = upper->height = 0;
2993        lower->x = lower->y = lower->width = lower->height = 0;
2994     }
2995
2996   *arrow_space = scroll_arrow_height - menu_padding.top - menu_padding.bottom;
2997 }
2998
2999 static gboolean
3000 gtk_menu_draw (GtkWidget *widget,
3001                cairo_t   *cr)
3002 {
3003   GtkMenu *menu;
3004   GtkMenuPrivate *priv;
3005   GtkStyleContext *context;
3006   GdkRectangle border;
3007   GdkRectangle upper;
3008   GdkRectangle lower;
3009   gint arrow_space;
3010   GtkBorder menu_padding;
3011
3012   menu = GTK_MENU (widget);
3013   priv = menu->priv;
3014   context = gtk_widget_get_style_context (widget);
3015
3016   get_arrows_visible_area (menu, &border, &upper, &lower, &arrow_space);
3017   get_menu_padding (widget, &menu_padding);
3018
3019   if (gtk_cairo_should_draw_window (cr, gtk_widget_get_window (widget)))
3020     {
3021       gfloat arrow_scaling;
3022       gint arrow_size;
3023
3024       gtk_widget_style_get (widget, "arrow-scaling", &arrow_scaling, NULL);
3025       arrow_size = arrow_scaling * arrow_space;
3026
3027       gtk_render_background (context, cr, 0, 0,
3028                              gtk_widget_get_allocated_width (widget),
3029                              gtk_widget_get_allocated_height (widget));
3030       gtk_render_frame (context, cr, 0, 0,
3031                         gtk_widget_get_allocated_width (widget),
3032                         gtk_widget_get_allocated_height (widget));
3033
3034       gtk_style_context_save (context);
3035       gtk_style_context_add_class (context, GTK_STYLE_CLASS_BUTTON);
3036
3037       if (priv->upper_arrow_visible && !priv->tearoff_active)
3038         {
3039           gtk_style_context_save (context);
3040           gtk_style_context_set_state (context, priv->upper_arrow_state);
3041
3042           gtk_render_background (context, cr,
3043                                  upper.x, upper.y,
3044                                  upper.width, upper.height);
3045           gtk_render_frame (context, cr,
3046                             upper.x, upper.y,
3047                             upper.width, upper.height);
3048
3049           gtk_render_arrow (context, cr, 0,
3050                             upper.x + (upper.width - arrow_size) / 2,
3051                             upper.y + menu_padding.top + (arrow_space - arrow_size) / 2,
3052                             arrow_size);
3053
3054           gtk_style_context_restore (context);
3055         }
3056
3057       if (priv->lower_arrow_visible && !priv->tearoff_active)
3058         {
3059           gtk_style_context_save (context);
3060           gtk_style_context_set_state (context, priv->lower_arrow_state);
3061
3062           gtk_render_background (context, cr,
3063                                  lower.x, lower.y,
3064                                  lower.width, lower.height);
3065           gtk_render_frame (context, cr,
3066                             lower.x, lower.y,
3067                             lower.width, lower.height);
3068
3069           gtk_render_arrow (context, cr, G_PI,
3070                             lower.x + (lower.width - arrow_size) / 2,
3071                             lower.y + menu_padding.bottom + (arrow_space - arrow_size) / 2,
3072                             arrow_size);
3073
3074           gtk_style_context_restore (context);
3075         }
3076
3077       gtk_style_context_restore (context);
3078     }
3079
3080   if (gtk_cairo_should_draw_window (cr, priv->bin_window))
3081     {
3082       gint y = -border.y + priv->scroll_offset;
3083
3084       cairo_save (cr);
3085       gtk_cairo_transform_to_window (cr, widget, priv->bin_window);
3086
3087       if (!priv->tearoff_active)
3088         {
3089           GtkBorder arrow_border;
3090
3091           get_arrows_border (menu, &arrow_border);
3092           y -= arrow_border.top;
3093         }
3094
3095       gtk_render_background (context, cr,
3096                              - border.x, y,
3097                              border.width, border.height);
3098       gtk_render_frame (context, cr,
3099                         - border.x, y,
3100                         border.width, border.height);
3101
3102       cairo_restore (cr);
3103     }
3104
3105   GTK_WIDGET_CLASS (gtk_menu_parent_class)->draw (widget, cr);
3106
3107   return FALSE;
3108 }
3109
3110 static void
3111 gtk_menu_show (GtkWidget *widget)
3112 {
3113   GtkMenu *menu = GTK_MENU (widget);
3114
3115   _gtk_menu_refresh_accel_paths (menu, FALSE);
3116
3117   GTK_WIDGET_CLASS (gtk_menu_parent_class)->show (widget);
3118 }
3119
3120
3121 static void 
3122 gtk_menu_get_preferred_width (GtkWidget *widget,
3123                               gint      *minimum_size,
3124                               gint      *natural_size)
3125 {
3126   GtkMenu        *menu;
3127   GtkMenuShell   *menu_shell;
3128   GtkMenuPrivate *priv;
3129   GtkWidget      *child;
3130   GList          *children;
3131   guint           max_toggle_size;
3132   guint           max_accel_width;
3133   guint           horizontal_padding;
3134   guint           border_width;
3135   gint            child_min, child_nat;
3136   gint            min_width, nat_width;
3137   GtkBorder       padding;
3138
3139   menu       = GTK_MENU (widget);
3140   menu_shell = GTK_MENU_SHELL (widget);
3141   priv       = menu->priv;
3142
3143   min_width = nat_width = 0;
3144
3145   max_toggle_size = 0;
3146   max_accel_width = 0;
3147
3148   children = menu_shell->priv->children;
3149   while (children)
3150     {
3151       gint part;
3152       gint toggle_size;
3153       gint l, r, t, b;
3154
3155       child = children->data;
3156       children = children->next;
3157
3158       if (! gtk_widget_get_visible (child))
3159         continue;
3160
3161       get_effective_child_attach (child, &l, &r, &t, &b);
3162
3163       /* It's important to size_request the child
3164        * before doing the toggle size request, in
3165        * case the toggle size request depends on the size
3166        * request of a child of the child (e.g. for ImageMenuItem)
3167        */
3168        gtk_widget_get_preferred_width (child, &child_min, &child_nat);
3169
3170        gtk_menu_item_toggle_size_request (GTK_MENU_ITEM (child), &toggle_size);
3171        max_toggle_size = MAX (max_toggle_size, toggle_size);
3172        max_accel_width = MAX (max_accel_width,
3173                               GTK_MENU_ITEM (child)->priv->accelerator_width);
3174
3175        part = child_min / (r - l);
3176        min_width = MAX (min_width, part);
3177
3178        part = child_nat / (r - l);
3179        nat_width = MAX (nat_width, part);
3180     }
3181
3182   /* If the menu doesn't include any images or check items
3183    * reserve the space so that all menus are consistent.
3184    * We only do this for 'ordinary' menus, not for combobox
3185    * menus or multi-column menus
3186    */
3187   if (max_toggle_size == 0 &&
3188       gtk_menu_get_n_columns (menu) == 1 &&
3189       !priv->no_toggle_size)
3190     {
3191       GtkStyleContext *context;
3192       GtkWidgetPath *menu_path, *check_path;
3193       guint toggle_spacing;
3194       guint indicator_size;
3195
3196       context = gtk_widget_get_style_context (widget);
3197       menu_path = gtk_widget_path_copy (gtk_style_context_get_path (context));
3198
3199       /* Create a GtkCheckMenuItem path, only to query indicator spacing */
3200       check_path = gtk_widget_path_copy (menu_path);
3201       gtk_widget_path_append_type (check_path, GTK_TYPE_CHECK_MENU_ITEM);
3202
3203       gtk_style_context_set_path (context, check_path);
3204       gtk_widget_path_free (check_path);
3205
3206       gtk_style_context_get_style (context,
3207                                    "toggle-spacing", &toggle_spacing,
3208                                    "indicator-size", &indicator_size,
3209                                    NULL);
3210
3211       max_toggle_size = indicator_size + toggle_spacing;
3212
3213       /* Restore real widget path */
3214       gtk_style_context_set_path (context, menu_path);
3215       gtk_widget_path_free (menu_path);
3216     }
3217
3218   min_width += 2 * max_toggle_size + max_accel_width;
3219   min_width *= gtk_menu_get_n_columns (menu);
3220
3221   nat_width += 2 * max_toggle_size + max_accel_width;
3222   nat_width *= gtk_menu_get_n_columns (menu);
3223
3224   gtk_widget_style_get (GTK_WIDGET (menu),
3225                         "horizontal-padding", &horizontal_padding,
3226                         NULL);
3227
3228   get_menu_padding (widget, &padding);
3229   border_width = gtk_container_get_border_width (GTK_CONTAINER (menu));
3230   min_width   += (2 * (border_width + horizontal_padding)) +
3231     padding.left + padding.right;
3232   nat_width   += (2 * (border_width + horizontal_padding)) +
3233     padding.left + padding.right;
3234
3235   priv->toggle_size = max_toggle_size;
3236   priv->accel_size  = max_accel_width;
3237
3238   if (minimum_size)
3239     *minimum_size = min_width;
3240
3241   if (natural_size)
3242     *natural_size = nat_width;
3243
3244   /* Don't resize the tearoff if it is not active,
3245    * because it won't redraw (it is only a background pixmap).
3246    */
3247   if (priv->tearoff_active)
3248     gtk_menu_set_tearoff_hints (menu, min_width);
3249 }
3250
3251 static void
3252 gtk_menu_get_preferred_height (GtkWidget *widget,
3253                                gint      *minimum_size,
3254                                gint      *natural_size)
3255 {
3256   gint min_width;
3257
3258   /* Menus are height-for-width only, just return the height
3259    * for the minimum width
3260    */
3261   GTK_WIDGET_GET_CLASS (widget)->get_preferred_width (widget, &min_width, NULL);
3262   GTK_WIDGET_GET_CLASS (widget)->get_preferred_height_for_width (widget, min_width, minimum_size, natural_size);
3263 }
3264
3265 static void
3266 gtk_menu_get_preferred_height_for_width (GtkWidget *widget,
3267                                          gint       for_size,
3268                                          gint      *minimum_size,
3269                                          gint      *natural_size)
3270 {
3271   GtkBorder       padding;
3272   GtkMenu        *menu = GTK_MENU (widget);
3273   GtkMenuPrivate *priv = menu->priv;
3274   guint          *min_heights, *nat_heights;
3275   guint           vertical_padding, border_width;
3276   gint            n_heights, i;
3277   gint            min_height, nat_height;
3278
3279   gtk_widget_style_get (widget, "vertical-padding", &vertical_padding, NULL);
3280   border_width = gtk_container_get_border_width (GTK_CONTAINER (menu));
3281   get_menu_padding (widget, &padding);
3282
3283   min_height = nat_height = (border_width + vertical_padding) * 2 +
3284           padding.top + padding.bottom;
3285
3286   n_heights =
3287     calculate_line_heights (menu, for_size, &min_heights, &nat_heights);
3288
3289   for (i = 0; i < n_heights; i++)
3290     {
3291       min_height += min_heights[i];
3292       nat_height += nat_heights[i];
3293     }
3294
3295   if (priv->have_position)
3296     {
3297       GdkScreen *screen = gtk_widget_get_screen (priv->toplevel);
3298       GdkRectangle monitor;
3299
3300       gdk_screen_get_monitor_workarea (screen, priv->monitor_num, &monitor);
3301
3302       if (priv->position_y + min_height > monitor.y + monitor.height)
3303         min_height = monitor.y + monitor.height - priv->position_y;
3304
3305       if (priv->position_y + nat_height > monitor.y + monitor.height)
3306         nat_height = monitor.y + monitor.height - priv->position_y;
3307
3308       if (priv->position_y < monitor.y)
3309         {
3310           min_height -= monitor.y - priv->position_y;
3311           nat_height -= monitor.y - priv->position_y;
3312         }
3313     }
3314
3315   if (minimum_size)
3316     *minimum_size = min_height;
3317
3318   if (natural_size)
3319     *natural_size = nat_height;
3320
3321   g_free (min_heights);
3322   g_free (nat_heights);
3323 }
3324
3325 static gboolean
3326 pointer_in_menu_window (GtkWidget *widget,
3327                         gdouble    x_root,
3328                         gdouble    y_root)
3329 {
3330   GtkMenu *menu = GTK_MENU (widget);
3331   GtkMenuPrivate *priv = menu->priv;
3332   GtkAllocation allocation;
3333
3334   if (gtk_widget_get_mapped (priv->toplevel))
3335     {
3336       GtkMenuShell *menu_shell;
3337       gint          window_x, window_y;
3338
3339       gdk_window_get_position (gtk_widget_get_window (priv->toplevel),
3340                                &window_x, &window_y);
3341
3342       gtk_widget_get_allocation (widget, &allocation);
3343       if (x_root >= window_x && x_root < window_x + allocation.width &&
3344           y_root >= window_y && y_root < window_y + allocation.height)
3345         return TRUE;
3346
3347       menu_shell = GTK_MENU_SHELL (widget);
3348
3349       if (GTK_IS_MENU (menu_shell->priv->parent_menu_shell))
3350         return pointer_in_menu_window (menu_shell->priv->parent_menu_shell,
3351                                        x_root, y_root);
3352     }
3353
3354   return FALSE;
3355 }
3356
3357 static gboolean
3358 gtk_menu_button_press (GtkWidget      *widget,
3359                        GdkEventButton *event)
3360 {
3361   GdkDevice *source_device;
3362   GtkWidget *event_widget;
3363   GtkMenu *menu;
3364
3365   if (event->type != GDK_BUTTON_PRESS)
3366     return FALSE;
3367
3368   source_device = gdk_event_get_source_device ((GdkEvent *) event);
3369   event_widget = gtk_get_event_widget ((GdkEvent *) event);
3370   menu = GTK_MENU (widget);
3371
3372   /*  Don't pass down to menu shell if a non-menuitem part of the menu
3373    *  was clicked. The check for the event_widget being a GtkMenuShell
3374    *  works because we have the pointer grabbed on menu_shell->window
3375    *  with owner_events=TRUE, so all events that are either outside
3376    *  the menu or on its border are delivered relative to
3377    *  menu_shell->window.
3378    */
3379   if (GTK_IS_MENU_SHELL (event_widget) &&
3380       pointer_in_menu_window (widget, event->x_root, event->y_root))
3381     return TRUE;
3382
3383   if (GTK_IS_MENU_ITEM (event_widget) &&
3384       gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN &&
3385       GTK_MENU_ITEM (event_widget)->priv->submenu != NULL &&
3386       !gtk_widget_is_drawable (GTK_MENU_ITEM (event_widget)->priv->submenu))
3387     menu->priv->ignore_button_release = TRUE;
3388
3389   return GTK_WIDGET_CLASS (gtk_menu_parent_class)->button_press_event (widget, event);
3390 }
3391
3392 static gboolean
3393 gtk_menu_button_release (GtkWidget      *widget,
3394                          GdkEventButton *event)
3395 {
3396   GtkMenuPrivate *priv = GTK_MENU (widget)->priv;
3397
3398   if (priv->ignore_button_release)
3399     {
3400       priv->ignore_button_release = FALSE;
3401       return FALSE;
3402     }
3403
3404   if (event->type != GDK_BUTTON_RELEASE)
3405     return FALSE;
3406
3407   /*  Don't pass down to menu shell if a non-menuitem part of the menu
3408    *  was clicked (see comment in button_press()).
3409    */
3410   if (GTK_IS_MENU_SHELL (gtk_get_event_widget ((GdkEvent *) event)) &&
3411       pointer_in_menu_window (widget, event->x_root, event->y_root))
3412     {
3413       /*  Ugly: make sure menu_shell->button gets reset to 0 when we
3414        *  bail out early here so it is in a consistent state for the
3415        *  next button_press/button_release in GtkMenuShell.
3416        *  See bug #449371.
3417        */
3418       if (GTK_MENU_SHELL (widget)->priv->active)
3419         GTK_MENU_SHELL (widget)->priv->button = 0;
3420
3421       return TRUE;
3422     }
3423
3424   return GTK_WIDGET_CLASS (gtk_menu_parent_class)->button_release_event (widget, event);
3425 }
3426
3427 static const gchar *
3428 get_accel_path (GtkWidget *menu_item,
3429                 gboolean  *locked)
3430 {
3431   const gchar *path;
3432   GtkWidget *label;
3433   GClosure *accel_closure;
3434   GtkAccelGroup *accel_group;
3435
3436   path = _gtk_widget_get_accel_path (menu_item, locked);
3437   if (!path)
3438     {
3439       path = GTK_MENU_ITEM (menu_item)->priv->accel_path;
3440
3441       if (locked)
3442         {
3443           *locked = TRUE;
3444
3445           label = gtk_bin_get_child (GTK_BIN (menu_item));
3446
3447           if (GTK_IS_ACCEL_LABEL (label))
3448             {
3449               g_object_get (label,
3450                             "accel-closure", &accel_closure,
3451                             NULL);
3452               if (accel_closure)
3453                 {
3454                   accel_group = gtk_accel_group_from_accel_closure (accel_closure);
3455
3456                   *locked = gtk_accel_group_get_is_locked (accel_group);
3457                 }
3458             }
3459         }
3460     }
3461
3462   return path;
3463 }
3464
3465 static gboolean
3466 gtk_menu_key_press (GtkWidget   *widget,
3467                     GdkEventKey *event)
3468 {
3469   GtkMenuShell *menu_shell;
3470   GtkMenu *menu;
3471   gboolean delete = FALSE;
3472   gboolean can_change_accels;
3473   gchar *accel = NULL;
3474   guint accel_key, accel_mods;
3475   GdkModifierType consumed_modifiers;
3476   GdkDisplay *display;
3477
3478   g_return_val_if_fail (GTK_IS_MENU (widget), FALSE);
3479   g_return_val_if_fail (event != NULL, FALSE);
3480
3481   menu_shell = GTK_MENU_SHELL (widget);
3482   menu = GTK_MENU (widget);
3483
3484   gtk_menu_stop_navigating_submenu (menu);
3485
3486   if (GTK_WIDGET_CLASS (gtk_menu_parent_class)->key_press_event (widget, event))
3487     return TRUE;
3488
3489   display = gtk_widget_get_display (widget);
3490
3491   g_object_get (gtk_widget_get_settings (widget),
3492                 "gtk-menu-bar-accel", &accel,
3493                 "gtk-can-change-accels", &can_change_accels,
3494                 NULL);
3495
3496   if (accel && *accel)
3497     {
3498       guint keyval = 0;
3499       GdkModifierType mods = 0;
3500
3501       gtk_accelerator_parse (accel, &keyval, &mods);
3502
3503       if (keyval == 0)
3504         g_warning ("Failed to parse menu bar accelerator '%s'\n", accel);
3505
3506       /* FIXME this is wrong, needs to be in the global accel resolution
3507        * thing, to properly consider i18n etc., but that probably requires
3508        * AccelGroup changes etc.
3509        */
3510       if (event->keyval == keyval && (mods & event->state) == mods)
3511         {
3512           gtk_menu_shell_cancel (menu_shell);
3513           g_free (accel);
3514           return TRUE;
3515         }
3516     }
3517
3518   g_free (accel);
3519
3520   switch (event->keyval)
3521     {
3522     case GDK_KEY_Delete:
3523     case GDK_KEY_KP_Delete:
3524     case GDK_KEY_BackSpace:
3525       delete = TRUE;
3526       break;
3527     default:
3528       break;
3529     }
3530
3531   /* Figure out what modifiers went into determining the key symbol */
3532   _gtk_translate_keyboard_accel_state (gdk_keymap_get_for_display (display),
3533                                        event->hardware_keycode,
3534                                        event->state,
3535                                        gtk_accelerator_get_default_mod_mask (),
3536                                        event->group,
3537                                        &accel_key, NULL, NULL, &consumed_modifiers);
3538
3539   accel_key = gdk_keyval_to_lower (accel_key);
3540   accel_mods = event->state & gtk_accelerator_get_default_mod_mask () & ~consumed_modifiers;
3541
3542   /* If lowercasing affects the keysym, then we need to include SHIFT
3543    * in the modifiers, We re-upper case when we match against the
3544    * keyval, but display and save in caseless form.
3545    */
3546   if (accel_key != event->keyval)
3547     accel_mods |= GDK_SHIFT_MASK;
3548
3549   /* Modify the accelerators */
3550   if (can_change_accels &&
3551       menu_shell->priv->active_menu_item &&
3552       gtk_bin_get_child (GTK_BIN (menu_shell->priv->active_menu_item)) && /* no separators */
3553       GTK_MENU_ITEM (menu_shell->priv->active_menu_item)->priv->submenu == NULL &&  /* no submenus */
3554       (delete || gtk_accelerator_valid (accel_key, accel_mods)))
3555     {
3556       GtkWidget *menu_item = menu_shell->priv->active_menu_item;
3557       gboolean locked, replace_accels = TRUE;
3558       const gchar *path;
3559
3560       path = get_accel_path (menu_item, &locked);
3561       if (!path || locked)
3562         {
3563           /* Can't change accelerators on menu_items without paths
3564            * (basically, those items are accelerator-locked).
3565            */
3566           gtk_widget_error_bell (widget);
3567         }
3568       else
3569         {
3570           gboolean changed;
3571
3572           /* For the keys that act to delete the current setting,
3573            * we delete the current setting if there is one, otherwise,
3574            * we set the key as the accelerator.
3575            */
3576           if (delete)
3577             {
3578               GtkAccelKey key;
3579
3580               if (gtk_accel_map_lookup_entry (path, &key) &&
3581                   (key.accel_key || key.accel_mods))
3582                 {
3583                   accel_key = 0;
3584                   accel_mods = 0;
3585                 }
3586             }
3587           changed = gtk_accel_map_change_entry (path, accel_key, accel_mods, replace_accels);
3588
3589           if (!changed)
3590             {
3591               /* We failed, probably because this key is in use
3592                * and locked already.
3593                */
3594               gtk_widget_error_bell (widget);
3595             }
3596         }
3597     }
3598
3599   return TRUE;
3600 }
3601
3602 static gboolean
3603 check_threshold (GtkWidget *widget,
3604                  gint       start_x,
3605                  gint       start_y,
3606                  gint       x,
3607                  gint       y)
3608 {
3609 #define THRESHOLD 8
3610
3611   return
3612     ABS (start_x - x) > THRESHOLD ||
3613     ABS (start_y - y) > THRESHOLD;
3614 }
3615
3616 static gboolean
3617 definitely_within_item (GtkWidget *widget,
3618                         gint       x,
3619                         gint       y)
3620 {
3621   GdkWindow *window = GTK_MENU_ITEM (widget)->priv->event_window;
3622   int w, h;
3623
3624   w = gdk_window_get_width (window);
3625   h = gdk_window_get_height (window);
3626
3627   return
3628     check_threshold (widget, 0, 0, x, y) &&
3629     check_threshold (widget, w - 1, 0, x, y) &&
3630     check_threshold (widget, w - 1, h - 1, x, y) &&
3631     check_threshold (widget, 0, h - 1, x, y);
3632 }
3633
3634 static gboolean
3635 gtk_menu_has_navigation_triangle (GtkMenu *menu)
3636 {
3637   GtkMenuPrivate *priv = menu->priv;
3638
3639   return priv->navigation_height && priv->navigation_width;
3640 }
3641
3642 static gboolean
3643 gtk_menu_motion_notify (GtkWidget      *widget,
3644                         GdkEventMotion *event)
3645 {
3646   GtkWidget *menu_item;
3647   GtkMenu *menu;
3648   GtkMenuShell *menu_shell;
3649   GtkWidget *parent;
3650   GdkDevice *source_device;
3651
3652   gboolean need_enter;
3653
3654   source_device = gdk_event_get_source_device ((GdkEvent *) event);
3655
3656   if (GTK_IS_MENU (widget) &&
3657       gdk_device_get_source (source_device) != GDK_SOURCE_TOUCHSCREEN)
3658     {
3659       GtkMenuPrivate *priv = GTK_MENU(widget)->priv;
3660
3661       if (priv->ignore_button_release)
3662         priv->ignore_button_release = FALSE;
3663
3664       gtk_menu_handle_scrolling (GTK_MENU (widget), event->x_root, event->y_root,
3665                                  TRUE, TRUE);
3666     }
3667
3668   /* We received the event for one of two reasons:
3669    *
3670    * a) We are the active menu, and did gtk_grab_add()
3671    * b) The widget is a child of ours, and the event was propagated
3672    *
3673    * Since for computation of navigation regions, we want the menu which
3674    * is the parent of the menu item, for a), we need to find that menu,
3675    * which may be different from 'widget'.
3676    */
3677   menu_item = gtk_get_event_widget ((GdkEvent*) event);
3678   parent = gtk_widget_get_parent (menu_item);
3679   if (!GTK_IS_MENU_ITEM (menu_item) ||
3680       !GTK_IS_MENU (parent))
3681     return FALSE;
3682
3683   menu_shell = GTK_MENU_SHELL (parent);
3684   menu = GTK_MENU (menu_shell);
3685
3686   if (definitely_within_item (menu_item, event->x, event->y))
3687     menu_shell->priv->activate_time = 0;
3688
3689   need_enter = (gtk_menu_has_navigation_triangle (menu) || menu_shell->priv->ignore_enter);
3690
3691   /* Check to see if we are within an active submenu's navigation region
3692    */
3693   if (gtk_menu_navigating_submenu (menu, event->x_root, event->y_root))
3694     return TRUE;
3695
3696   /* Make sure we pop down if we enter a non-selectable menu item, so we
3697    * don't show a submenu when the cursor is outside the stay-up triangle.
3698    */
3699   if (!_gtk_menu_item_is_selectable (menu_item))
3700     {
3701       /* We really want to deselect, but this gives the menushell code
3702        * a chance to do some bookkeeping about the menuitem.
3703        */
3704       gtk_menu_shell_select_item (menu_shell, menu_item);
3705       return FALSE;
3706     }
3707
3708   if (need_enter)
3709     {
3710       /* The menu is now sensitive to enter events on its items, but
3711        * was previously sensitive.  So we fake an enter event.
3712        */
3713       menu_shell->priv->ignore_enter = FALSE;
3714
3715       if (event->x >= 0 && event->x < gdk_window_get_width (event->window) &&
3716           event->y >= 0 && event->y < gdk_window_get_height (event->window))
3717         {
3718           GdkEvent *send_event = gdk_event_new (GDK_ENTER_NOTIFY);
3719           gboolean result;
3720
3721           send_event->crossing.window = g_object_ref (event->window);
3722           send_event->crossing.time = event->time;
3723           send_event->crossing.send_event = TRUE;
3724           send_event->crossing.x_root = event->x_root;
3725           send_event->crossing.y_root = event->y_root;
3726           send_event->crossing.x = event->x;
3727           send_event->crossing.y = event->y;
3728           send_event->crossing.state = event->state;
3729           gdk_event_set_device (send_event, gdk_event_get_device ((GdkEvent *) event));
3730
3731           /* We send the event to 'widget', the currently active menu,
3732            * instead of 'menu', the menu that the pointer is in. This
3733            * will ensure that the event will be ignored unless the
3734            * menuitem is a child of the active menu or some parent
3735            * menu of the active menu.
3736            */
3737           result = gtk_widget_event (widget, send_event);
3738           gdk_event_free (send_event);
3739
3740           return result;
3741         }
3742     }
3743
3744   return FALSE;
3745 }
3746
3747 static gboolean
3748 get_double_arrows (GtkMenu *menu)
3749 {
3750   GtkMenuPrivate   *priv = menu->priv;
3751   gboolean          double_arrows;
3752   GtkArrowPlacement arrow_placement;
3753
3754   gtk_widget_style_get (GTK_WIDGET (menu),
3755                         "double-arrows", &double_arrows,
3756                         "arrow-placement", &arrow_placement,
3757                         NULL);
3758
3759   if (arrow_placement != GTK_ARROWS_BOTH)
3760     return TRUE;
3761
3762   return double_arrows || (priv->initially_pushed_in &&
3763                            priv->scroll_offset != 0);
3764 }
3765
3766 static void
3767 gtk_menu_scroll_by (GtkMenu *menu,
3768                     gint     step)
3769 {
3770   GtkMenuPrivate *priv = menu->priv;
3771   GtkBorder arrow_border;
3772   GtkWidget *widget;
3773   gint offset;
3774   gint view_height;
3775   gboolean double_arrows;
3776
3777   widget = GTK_WIDGET (menu);
3778   offset = priv->scroll_offset + step;
3779
3780   get_arrows_border (menu, &arrow_border);
3781
3782   double_arrows = get_double_arrows (menu);
3783
3784   /* If we scroll upward and the non-visible top part
3785    * is smaller than the scroll arrow it would be
3786    * pretty stupid to show the arrow and taking more
3787    * screen space than just scrolling to the top.
3788    */
3789   if (!double_arrows)
3790     if ((step < 0) && (offset < arrow_border.top))
3791       offset = 0;
3792
3793   /* Don't scroll over the top if we weren't before: */
3794   if ((priv->scroll_offset >= 0) && (offset < 0))
3795     offset = 0;
3796
3797   view_height = gdk_window_get_height (gtk_widget_get_window (widget));
3798
3799   if (priv->scroll_offset == 0 &&
3800       view_height >= priv->requested_height)
3801     return;
3802
3803   /* Don't scroll past the bottom if we weren't before: */
3804   if (priv->scroll_offset > 0)
3805     view_height -= arrow_border.top;
3806
3807   /* When both arrows are always shown,
3808    * reduce view height even more.
3809    */
3810   if (double_arrows)
3811     view_height -= arrow_border.bottom;
3812
3813   if ((priv->scroll_offset + view_height <= priv->requested_height) &&
3814       (offset + view_height > priv->requested_height))
3815     offset = priv->requested_height - view_height;
3816
3817   if (offset != priv->scroll_offset)
3818     gtk_menu_scroll_to (menu, offset);
3819 }
3820
3821 static gboolean
3822 gtk_menu_scroll_timeout (gpointer data)
3823 {
3824   GtkMenu  *menu;
3825
3826   menu = GTK_MENU (data);
3827   gtk_menu_scroll_by (menu, menu->priv->scroll_step);
3828
3829   return TRUE;
3830 }
3831
3832 static gboolean
3833 gtk_menu_scroll (GtkWidget      *widget,
3834                  GdkEventScroll *event)
3835 {
3836   GtkMenu *menu = GTK_MENU (widget);
3837
3838   switch (event->direction)
3839     {
3840     case GDK_SCROLL_RIGHT:
3841     case GDK_SCROLL_DOWN:
3842       gtk_menu_scroll_by (menu, MENU_SCROLL_STEP2);
3843       break;
3844     case GDK_SCROLL_LEFT:
3845     case GDK_SCROLL_UP:
3846       gtk_menu_scroll_by (menu, - MENU_SCROLL_STEP2);
3847       break;
3848     }
3849
3850   return TRUE;
3851 }
3852
3853 static void
3854 get_arrows_sensitive_area (GtkMenu      *menu,
3855                            GdkRectangle *upper,
3856                            GdkRectangle *lower)
3857 {
3858   GtkArrowPlacement arrow_placement;
3859   GtkWidget *widget = GTK_WIDGET (menu);
3860   GdkWindow *window;
3861   gint width, height;
3862   guint border;
3863   guint vertical_padding;
3864   gint win_x, win_y;
3865   gint scroll_arrow_height;
3866   GtkBorder padding;
3867
3868   window = gtk_widget_get_window (widget);
3869   width = gdk_window_get_width (window);
3870   height = gdk_window_get_height (window);
3871
3872   gtk_widget_style_get (widget,
3873                         "vertical-padding", &vertical_padding,
3874                         "scroll-arrow-vlength", &scroll_arrow_height,
3875                         "arrow-placement", &arrow_placement,
3876                         NULL);
3877
3878   border = gtk_container_get_border_width (GTK_CONTAINER (menu)) + vertical_padding;
3879   get_menu_padding (widget, &padding);
3880
3881   gdk_window_get_position (window, &win_x, &win_y);
3882
3883   switch (arrow_placement)
3884     {
3885     case GTK_ARROWS_BOTH:
3886       if (upper)
3887         {
3888           upper->x = win_x;
3889           upper->y = win_y;
3890           upper->width = width;
3891           upper->height = scroll_arrow_height + border + padding.top;
3892         }
3893
3894       if (lower)
3895         {
3896           lower->x = win_x;
3897           lower->y = win_y + height - border - padding.bottom - scroll_arrow_height;
3898           lower->width = width;
3899           lower->height = scroll_arrow_height + border + padding.bottom;
3900         }
3901       break;
3902
3903     case GTK_ARROWS_START:
3904       if (upper)
3905         {
3906           upper->x = win_x;
3907           upper->y = win_y;
3908           upper->width = width / 2;
3909           upper->height = scroll_arrow_height + border + padding.top;
3910         }
3911
3912       if (lower)
3913         {
3914           lower->x = win_x + width / 2;
3915           lower->y = win_y;
3916           lower->width = width / 2;
3917           lower->height = scroll_arrow_height + border + padding.bottom;
3918         }
3919       break;
3920
3921     case GTK_ARROWS_END:
3922       if (upper)
3923         {
3924           upper->x = win_x;
3925           upper->y = win_y + height - border - scroll_arrow_height;
3926           upper->width = width / 2;
3927           upper->height = scroll_arrow_height + border + padding.top;
3928         }
3929
3930       if (lower)
3931         {
3932           lower->x = win_x + width / 2;
3933           lower->y = win_y + height - border - scroll_arrow_height;
3934           lower->width = width / 2;
3935           lower->height = scroll_arrow_height + border + padding.bottom;
3936         }
3937       break;
3938     }
3939 }
3940
3941
3942 static void
3943 gtk_menu_handle_scrolling (GtkMenu *menu,
3944                            gint     x,
3945                            gint     y,
3946                            gboolean enter,
3947                            gboolean motion)
3948 {
3949   GtkMenuPrivate *priv = menu->priv;
3950   GtkMenuShell *menu_shell;
3951   GdkRectangle rect;
3952   gboolean in_arrow;
3953   gboolean scroll_fast = FALSE;
3954   gint top_x, top_y;
3955
3956   menu_shell = GTK_MENU_SHELL (menu);
3957
3958   gdk_window_get_position (gtk_widget_get_window (priv->toplevel),
3959                            &top_x, &top_y);
3960   x -= top_x;
3961   y -= top_y;
3962
3963   /*  upper arrow handling  */
3964
3965   get_arrows_sensitive_area (menu, &rect, NULL);
3966
3967   in_arrow = FALSE;
3968   if (priv->upper_arrow_visible && !priv->tearoff_active &&
3969       (x >= rect.x) && (x < rect.x + rect.width) &&
3970       (y >= rect.y) && (y < rect.y + rect.height))
3971     {
3972       in_arrow = TRUE;
3973     }
3974
3975   if ((priv->upper_arrow_state & GTK_STATE_FLAG_INSENSITIVE) == 0)
3976     {
3977       gboolean arrow_pressed = FALSE;
3978
3979       if (priv->upper_arrow_visible && !priv->tearoff_active)
3980         {
3981           scroll_fast = (y < rect.y + MENU_SCROLL_FAST_ZONE);
3982
3983           if (enter && in_arrow &&
3984               (!priv->upper_arrow_prelight ||
3985                priv->scroll_fast != scroll_fast))
3986             {
3987               priv->upper_arrow_prelight = TRUE;
3988               priv->scroll_fast = scroll_fast;
3989
3990               /* Deselect the active item so that
3991                * any submenus are popped down
3992                */
3993               gtk_menu_shell_deselect (menu_shell);
3994
3995               gtk_menu_remove_scroll_timeout (menu);
3996               priv->scroll_step = scroll_fast
3997                                     ? -MENU_SCROLL_STEP2
3998                                     : -MENU_SCROLL_STEP1;
3999
4000               priv->scroll_timeout =
4001                 gdk_threads_add_timeout (scroll_fast
4002                                            ? MENU_SCROLL_TIMEOUT2
4003                                            : MENU_SCROLL_TIMEOUT1,
4004                                          gtk_menu_scroll_timeout, menu);
4005             }
4006           else if (!enter && !in_arrow && priv->upper_arrow_prelight)
4007             {
4008               gtk_menu_stop_scrolling (menu);
4009             }
4010         }
4011
4012       /*  check if the button isn't insensitive before
4013        *  changing it to something else.
4014        */
4015       if ((priv->upper_arrow_state & GTK_STATE_FLAG_INSENSITIVE) == 0)
4016         {
4017           GtkStateFlags arrow_state = 0;
4018
4019           if (arrow_pressed)
4020             arrow_state |= GTK_STATE_FLAG_ACTIVE;
4021
4022           if (priv->upper_arrow_prelight)
4023             arrow_state |= GTK_STATE_FLAG_PRELIGHT;
4024
4025           if (arrow_state != priv->upper_arrow_state)
4026             {
4027               priv->upper_arrow_state = arrow_state;
4028
4029               gdk_window_invalidate_rect (gtk_widget_get_window (GTK_WIDGET (menu)),
4030                                           &rect, FALSE);
4031             }
4032         }
4033     }
4034
4035   /*  lower arrow handling  */
4036
4037   get_arrows_sensitive_area (menu, NULL, &rect);
4038
4039   in_arrow = FALSE;
4040   if (priv->lower_arrow_visible && !priv->tearoff_active &&
4041       (x >= rect.x) && (x < rect.x + rect.width) &&
4042       (y >= rect.y) && (y < rect.y + rect.height))
4043     {
4044       in_arrow = TRUE;
4045     }
4046
4047   if ((priv->lower_arrow_state & GTK_STATE_FLAG_INSENSITIVE) == 0)
4048     {
4049       gboolean arrow_pressed = FALSE;
4050
4051       if (priv->lower_arrow_visible && !priv->tearoff_active)
4052         {
4053           scroll_fast = (y > rect.y + rect.height - MENU_SCROLL_FAST_ZONE);
4054
4055           if (enter && in_arrow &&
4056               (!priv->lower_arrow_prelight ||
4057                priv->scroll_fast != scroll_fast))
4058             {
4059               priv->lower_arrow_prelight = TRUE;
4060               priv->scroll_fast = scroll_fast;
4061
4062               /* Deselect the active item so that
4063                * any submenus are popped down
4064                */
4065               gtk_menu_shell_deselect (menu_shell);
4066
4067               gtk_menu_remove_scroll_timeout (menu);
4068               priv->scroll_step = scroll_fast
4069                                     ? MENU_SCROLL_STEP2
4070                                     : MENU_SCROLL_STEP1;
4071
4072               priv->scroll_timeout =
4073                 gdk_threads_add_timeout (scroll_fast
4074                                            ? MENU_SCROLL_TIMEOUT2
4075                                            : MENU_SCROLL_TIMEOUT1,
4076                                          gtk_menu_scroll_timeout, menu);
4077             }
4078           else if (!enter && !in_arrow && priv->lower_arrow_prelight)
4079             {
4080               gtk_menu_stop_scrolling (menu);
4081             }
4082         }
4083
4084       /*  check if the button isn't insensitive before
4085        *  changing it to something else.
4086        */
4087       if ((priv->lower_arrow_state & GTK_STATE_FLAG_INSENSITIVE) == 0)
4088         {
4089           GtkStateFlags arrow_state = 0;
4090
4091           if (arrow_pressed)
4092             arrow_state |= GTK_STATE_FLAG_ACTIVE;
4093
4094           if (priv->lower_arrow_prelight)
4095             arrow_state |= GTK_STATE_FLAG_PRELIGHT;
4096
4097           if (arrow_state != priv->lower_arrow_state)
4098             {
4099               priv->lower_arrow_state = arrow_state;
4100
4101               gdk_window_invalidate_rect (gtk_widget_get_window (GTK_WIDGET (menu)),
4102                                           &rect, FALSE);
4103             }
4104         }
4105     }
4106 }
4107
4108 static gboolean
4109 gtk_menu_enter_notify (GtkWidget        *widget,
4110                        GdkEventCrossing *event)
4111 {
4112   GtkWidget *menu_item;
4113   GtkWidget *parent;
4114   GdkDevice *source_device;
4115
4116   if (event->mode == GDK_CROSSING_GTK_GRAB ||
4117       event->mode == GDK_CROSSING_GTK_UNGRAB ||
4118       event->mode == GDK_CROSSING_STATE_CHANGED)
4119     return TRUE;
4120
4121   source_device = gdk_event_get_source_device ((GdkEvent *) event);
4122   menu_item = gtk_get_event_widget ((GdkEvent*) event);
4123
4124   if (GTK_IS_MENU (widget) &&
4125       gdk_device_get_source (source_device) != GDK_SOURCE_TOUCHSCREEN)
4126     {
4127       GtkMenuShell *menu_shell = GTK_MENU_SHELL (widget);
4128
4129       if (!menu_shell->priv->ignore_enter)
4130         gtk_menu_handle_scrolling (GTK_MENU (widget),
4131                                    event->x_root, event->y_root, TRUE, TRUE);
4132     }
4133
4134   if (gdk_device_get_source (source_device) != GDK_SOURCE_TOUCHSCREEN &&
4135       GTK_IS_MENU_ITEM (menu_item))
4136     {
4137       GtkWidget *menu = gtk_widget_get_parent (menu_item);
4138
4139       if (GTK_IS_MENU (menu))
4140         {
4141           GtkMenuPrivate *priv = (GTK_MENU (menu))->priv;
4142           GtkMenuShell *menu_shell = GTK_MENU_SHELL (menu);
4143
4144           if (priv->seen_item_enter)
4145             {
4146               /* This is the second enter we see for an item
4147                * on this menu. This means a release should always
4148                * mean activate.
4149                */
4150               menu_shell->priv->activate_time = 0;
4151             }
4152           else if ((event->detail != GDK_NOTIFY_NONLINEAR &&
4153                     event->detail != GDK_NOTIFY_NONLINEAR_VIRTUAL))
4154             {
4155               if (definitely_within_item (menu_item, event->x, event->y))
4156                 {
4157                   /* This is an actual user-enter (ie. not a pop-under)
4158                    * In this case, the user must either have entered
4159                    * sufficiently far enough into the item, or he must move
4160                    * far enough away from the enter point. (see
4161                    * gtk_menu_motion_notify())
4162                    */
4163                   menu_shell->priv->activate_time = 0;
4164                 }
4165             }
4166
4167           priv->seen_item_enter = TRUE;
4168         }
4169     }
4170
4171   /* If this is a faked enter (see gtk_menu_motion_notify), 'widget'
4172    * will not correspond to the event widget's parent.  Check to see
4173    * if we are in the parent's navigation region.
4174    */
4175   parent = gtk_widget_get_parent (menu_item);
4176   if (GTK_IS_MENU_ITEM (menu_item) && GTK_IS_MENU (parent) &&
4177       gtk_menu_navigating_submenu (GTK_MENU (parent),
4178                                    event->x_root, event->y_root))
4179     return TRUE;
4180
4181   return GTK_WIDGET_CLASS (gtk_menu_parent_class)->enter_notify_event (widget, event);
4182 }
4183
4184 static gboolean
4185 gtk_menu_leave_notify (GtkWidget        *widget,
4186                        GdkEventCrossing *event)
4187 {
4188   GtkMenuShell *menu_shell;
4189   GtkMenu *menu;
4190   GtkMenuItem *menu_item;
4191   GtkWidget *event_widget;
4192   GdkDevice *source_device;
4193
4194   if (event->mode == GDK_CROSSING_GTK_GRAB ||
4195       event->mode == GDK_CROSSING_GTK_UNGRAB ||
4196       event->mode == GDK_CROSSING_STATE_CHANGED)
4197     return TRUE;
4198
4199   menu = GTK_MENU (widget);
4200   menu_shell = GTK_MENU_SHELL (widget);
4201
4202   if (gtk_menu_navigating_submenu (menu, event->x_root, event->y_root))
4203     return TRUE;
4204
4205   source_device = gdk_event_get_source_device ((GdkEvent *) event);
4206
4207   if (gdk_device_get_source (source_device) != GDK_SOURCE_TOUCHSCREEN)
4208     gtk_menu_handle_scrolling (menu, event->x_root, event->y_root, FALSE, TRUE);
4209
4210   event_widget = gtk_get_event_widget ((GdkEvent*) event);
4211
4212   if (!GTK_IS_MENU_ITEM (event_widget))
4213     return TRUE;
4214
4215   menu_item = GTK_MENU_ITEM (event_widget);
4216
4217   /* Here we check to see if we're leaving an active menu item
4218    * with a submenu, in which case we enter submenu navigation mode.
4219    */
4220   if (menu_shell->priv->active_menu_item != NULL
4221       && menu_item->priv->submenu != NULL
4222       && menu_item->priv->submenu_placement == GTK_LEFT_RIGHT)
4223     {
4224       if (GTK_MENU_SHELL (menu_item->priv->submenu)->priv->active)
4225         {
4226           gtk_menu_set_submenu_navigation_region (menu, menu_item, event);
4227           return TRUE;
4228         }
4229       else if (menu_item == GTK_MENU_ITEM (menu_shell->priv->active_menu_item))
4230         {
4231           /* We are leaving an active menu item with nonactive submenu.
4232            * Deselect it so we don't surprise the user with by popping
4233            * up a submenu _after_ he left the item.
4234            */
4235           gtk_menu_shell_deselect (menu_shell);
4236           return TRUE;
4237         }
4238     }
4239
4240   return GTK_WIDGET_CLASS (gtk_menu_parent_class)->leave_notify_event (widget, event);
4241 }
4242
4243 static gboolean
4244 pointer_on_menu_widget (GtkMenu *menu,
4245                         gdouble  x_root,
4246                         gdouble  y_root)
4247 {
4248   GtkMenuPrivate *priv = menu->priv;
4249   GtkAllocation allocation;
4250   gint window_x, window_y;
4251
4252   gtk_widget_get_allocation (GTK_WIDGET (menu), &allocation);
4253   gdk_window_get_position (gtk_widget_get_window (priv->toplevel),
4254                            &window_x, &window_y);
4255
4256   if (x_root >= window_x && x_root < window_x + allocation.width &&
4257       y_root >= window_y && y_root < window_y + allocation.height)
4258     return TRUE;
4259
4260   return FALSE;
4261 }
4262
4263 static gboolean
4264 gtk_menu_captured_event (GtkWidget *widget,
4265                          GdkEvent  *event)
4266 {
4267   GdkDevice *source_device;
4268   gboolean retval = FALSE;
4269   GtkMenuPrivate *priv;
4270   GtkMenu *menu;
4271   gdouble x_root, y_root;
4272   guint button;
4273   GdkModifierType state;
4274
4275   menu = GTK_MENU (widget);
4276   priv = menu->priv;
4277
4278   if (!priv->upper_arrow_visible && !priv->lower_arrow_visible)
4279     return retval;
4280
4281   source_device = gdk_event_get_source_device (event);
4282   gdk_event_get_root_coords (event, &x_root, &y_root);
4283
4284   switch (event->type)
4285     {
4286     case GDK_TOUCH_BEGIN:
4287     case GDK_BUTTON_PRESS:
4288       if ((!gdk_event_get_button (event, &button) || button == 1) &&
4289           gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN &&
4290           pointer_on_menu_widget (menu, x_root, y_root))
4291         {
4292           priv->drag_start_y = event->button.y_root;
4293           priv->initial_drag_offset = priv->scroll_offset;
4294           priv->drag_scroll_started = FALSE;
4295         }
4296       else
4297         priv->drag_start_y = -1;
4298
4299       priv->drag_already_pressed = TRUE;
4300       break;
4301     case GDK_TOUCH_END:
4302     case GDK_BUTTON_RELEASE:
4303       if (priv->drag_scroll_started)
4304         {
4305           priv->drag_scroll_started = FALSE;
4306           priv->drag_start_y = -1;
4307           priv->drag_already_pressed = FALSE;
4308           retval = TRUE;
4309         }
4310       break;
4311     case GDK_TOUCH_UPDATE:
4312     case GDK_MOTION_NOTIFY:
4313       if ((!gdk_event_get_state (event, &state) || (state & GDK_BUTTON1_MASK) 
4314 != 0) &&
4315           gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN)
4316         {
4317           if (!priv->drag_already_pressed)
4318             {
4319               if (pointer_on_menu_widget (menu, x_root, y_root))
4320                 {
4321                   priv->drag_start_y = y_root;
4322                   priv->initial_drag_offset = priv->scroll_offset;
4323                   priv->drag_scroll_started = FALSE;
4324                 }
4325               else
4326                 priv->drag_start_y = -1;
4327
4328               priv->drag_already_pressed = TRUE;
4329             }
4330
4331           if (priv->drag_start_y < 0 && !priv->drag_scroll_started)
4332             break;
4333
4334           if (priv->drag_scroll_started)
4335             {
4336               gint offset, view_height;
4337               GtkBorder arrow_border;
4338               gdouble y_diff;
4339
4340               y_diff = y_root - priv->drag_start_y;
4341               offset = priv->initial_drag_offset - y_diff;
4342
4343               view_height = gdk_window_get_height (gtk_widget_get_window (widget));
4344               get_arrows_border (menu, &arrow_border);
4345
4346               if (priv->upper_arrow_visible)
4347                 view_height -= arrow_border.top;
4348
4349               if (priv->lower_arrow_visible)
4350                 view_height -= arrow_border.bottom;
4351
4352               offset = CLAMP (offset, 0, priv->requested_height - view_height);
4353               gtk_menu_scroll_to (menu, offset);
4354
4355               retval = TRUE;
4356             }
4357           else if (gtk_drag_check_threshold (widget,
4358                                              0, priv->drag_start_y,
4359                                              0, y_root))
4360             {
4361               priv->drag_scroll_started = TRUE;
4362               gtk_menu_shell_deselect (GTK_MENU_SHELL (menu));
4363               retval = TRUE;
4364             }
4365         }
4366       break;
4367     case GDK_ENTER_NOTIFY:
4368     case GDK_LEAVE_NOTIFY:
4369       if (priv->drag_scroll_started)
4370         retval = TRUE;
4371       break;
4372     default:
4373       break;
4374     }
4375
4376   return retval;
4377 }
4378
4379 static void
4380 gtk_menu_stop_navigating_submenu (GtkMenu *menu)
4381 {
4382   GtkMenuPrivate *priv = menu->priv;
4383
4384   priv->navigation_x = 0;
4385   priv->navigation_y = 0;
4386   priv->navigation_width = 0;
4387   priv->navigation_height = 0;
4388
4389   if (priv->navigation_timeout)
4390     {
4391       g_source_remove (priv->navigation_timeout);
4392       priv->navigation_timeout = 0;
4393     }
4394 }
4395
4396 /* When the timeout is elapsed, the navigation region is destroyed
4397  * and the menuitem under the pointer (if any) is selected.
4398  */
4399 static gboolean
4400 gtk_menu_stop_navigating_submenu_cb (gpointer user_data)
4401 {
4402   GtkMenuPopdownData *popdown_data = user_data;
4403   GtkMenu *menu = popdown_data->menu;
4404   GtkMenuPrivate *priv = menu->priv;
4405   GdkWindow *child_window;
4406
4407   gtk_menu_stop_navigating_submenu (menu);
4408
4409   if (gtk_widget_get_realized (GTK_WIDGET (menu)))
4410     {
4411       child_window = gdk_window_get_device_position (priv->bin_window,
4412                                                      popdown_data->device,
4413                                                      NULL, NULL, NULL);
4414
4415       if (child_window)
4416         {
4417           GdkEvent *send_event = gdk_event_new (GDK_ENTER_NOTIFY);
4418
4419           send_event->crossing.window = g_object_ref (child_window);
4420           send_event->crossing.time = GDK_CURRENT_TIME; /* Bogus */
4421           send_event->crossing.send_event = TRUE;
4422           gdk_event_set_device (send_event, popdown_data->device);
4423
4424           GTK_WIDGET_CLASS (gtk_menu_parent_class)->enter_notify_event (GTK_WIDGET (menu), (GdkEventCrossing *)send_event);
4425
4426           gdk_event_free (send_event);
4427         }
4428     }
4429
4430   return FALSE;
4431 }
4432
4433 static gboolean
4434 gtk_menu_navigating_submenu (GtkMenu *menu,
4435                              gint     event_x,
4436                              gint     event_y)
4437 {
4438   GtkMenuPrivate *priv = menu->priv;
4439   gint width, height;
4440
4441   if (!gtk_menu_has_navigation_triangle (menu))
4442     return FALSE;
4443
4444   width = priv->navigation_width;
4445   height = priv->navigation_height;
4446
4447   /* Check if x/y are in the triangle spanned by the navigation parameters */
4448
4449   /* 1) Move the coordinates so the triangle starts at 0,0 */
4450   event_x -= priv->navigation_x;
4451   event_y -= priv->navigation_y;
4452
4453   /* 2) Ensure both legs move along the positive axis */
4454   if (width < 0)
4455     {
4456       event_x = -event_x;
4457       width = -width;
4458     }
4459   if (height < 0)
4460     {
4461       event_y = -event_y;
4462       height = -height;
4463     }
4464
4465   /* 3) Check that the given coordinate is inside the triangle. The formula
4466    * is a transformed form of this formula: x/w + y/h <= 1
4467    */
4468   if (event_x >= 0 && event_y >= 0 &&
4469       event_x * height + event_y * width <= width * height)
4470     {
4471       return TRUE;
4472     }
4473   else
4474     {
4475       gtk_menu_stop_navigating_submenu (menu);
4476       return FALSE;
4477     }
4478 }
4479
4480 static void
4481 gtk_menu_set_submenu_navigation_region (GtkMenu          *menu,
4482                                         GtkMenuItem      *menu_item,
4483                                         GdkEventCrossing *event)
4484 {
4485   GtkMenuPrivate *priv = menu->priv;
4486   gint submenu_left = 0;
4487   gint submenu_right = 0;
4488   gint submenu_top = 0;
4489   gint submenu_bottom = 0;
4490   gint width = 0;
4491   GtkWidget *event_widget;
4492   GtkMenuPopdownData *popdown_data;
4493   GdkWindow *window;
4494
4495   g_return_if_fail (menu_item->priv->submenu != NULL);
4496   g_return_if_fail (event != NULL);
4497
4498   event_widget = gtk_get_event_widget ((GdkEvent*) event);
4499
4500   window = gtk_widget_get_window (menu_item->priv->submenu);
4501   gdk_window_get_origin (window, &submenu_left, &submenu_top);
4502
4503   submenu_right = submenu_left + gdk_window_get_width (window);
4504   submenu_bottom = submenu_top + gdk_window_get_height (window);
4505
4506   width = gdk_window_get_width (gtk_widget_get_window (event_widget));
4507
4508   if (event->x >= 0 && event->x < width)
4509     {
4510       gint popdown_delay;
4511
4512       gtk_menu_stop_navigating_submenu (menu);
4513
4514       /* The navigation region is the triangle closest to the x/y
4515        * location of the rectangle. This is why the width or height
4516        * can be negative.
4517        */
4518       if (menu_item->priv->submenu_direction == GTK_DIRECTION_RIGHT)
4519         {
4520           /* right */
4521           priv->navigation_x = submenu_left;
4522           priv->navigation_width = event->x_root - submenu_left;
4523         }
4524       else
4525         {
4526           /* left */
4527           priv->navigation_x = submenu_right;
4528           priv->navigation_width = event->x_root - submenu_right;
4529         }
4530
4531       if (event->y < 0)
4532         {
4533           /* top */
4534           priv->navigation_y = event->y_root;
4535           priv->navigation_height = submenu_top - event->y_root - NAVIGATION_REGION_OVERSHOOT;
4536
4537           if (priv->navigation_height >= 0)
4538             return;
4539         }
4540       else
4541         {
4542           /* bottom */
4543           priv->navigation_y = event->y_root;
4544           priv->navigation_height = submenu_bottom - event->y_root + NAVIGATION_REGION_OVERSHOOT;
4545
4546           if (priv->navigation_height <= 0)
4547             return;
4548         }
4549
4550       g_object_get (gtk_widget_get_settings (GTK_WIDGET (menu)),
4551                     "gtk-menu-popdown-delay", &popdown_delay,
4552                     NULL);
4553
4554       popdown_data = g_new (GtkMenuPopdownData, 1);
4555       popdown_data->menu = menu;
4556       popdown_data->device = gdk_event_get_device ((GdkEvent *) event);
4557
4558       priv->navigation_timeout = gdk_threads_add_timeout_full (G_PRIORITY_DEFAULT,
4559                                                                popdown_delay,
4560                                                                gtk_menu_stop_navigating_submenu_cb,
4561                                                                popdown_data,
4562                                                                (GDestroyNotify) g_free);
4563     }
4564 }
4565
4566 static void
4567 gtk_menu_deactivate (GtkMenuShell *menu_shell)
4568 {
4569   GtkWidget *parent;
4570
4571   g_return_if_fail (GTK_IS_MENU (menu_shell));
4572
4573   parent = menu_shell->priv->parent_menu_shell;
4574
4575   menu_shell->priv->activate_time = 0;
4576   gtk_menu_popdown (GTK_MENU (menu_shell));
4577
4578   if (parent)
4579     gtk_menu_shell_deactivate (GTK_MENU_SHELL (parent));
4580 }
4581
4582 static void
4583 gtk_menu_position (GtkMenu  *menu,
4584                    gboolean  set_scroll_offset)
4585 {
4586   GtkMenuPrivate *priv = menu->priv;
4587   GtkWidget *widget;
4588   GtkRequisition requisition;
4589   gint x, y;
4590   gint scroll_offset;
4591   GdkScreen *screen;
4592   GdkScreen *pointer_screen;
4593   GdkRectangle monitor;
4594   GdkDevice *pointer;
4595
4596   widget = GTK_WIDGET (menu);
4597
4598   screen = gtk_widget_get_screen (widget);
4599   pointer = _gtk_menu_shell_get_grab_device (GTK_MENU_SHELL (menu));
4600   gdk_device_get_position (pointer, &pointer_screen, &x, &y);
4601
4602   /* Realize so we have the proper width and heigh to figure out
4603    * the right place to popup the menu.
4604    */
4605   gtk_widget_realize (priv->toplevel);
4606   requisition.width = gtk_widget_get_allocated_width (widget);
4607   requisition.height = gtk_widget_get_allocated_height (widget);
4608
4609   if (pointer_screen != screen)
4610     {
4611       /* Pointer is on a different screen; roughly center the
4612        * menu on the screen. If someone was using multiscreen
4613        * + Xinerama together they'd probably want something
4614        * fancier; but that is likely to be vanishingly rare.
4615        */
4616       x = MAX (0, (gdk_screen_get_width (screen) - requisition.width) / 2);
4617       y = MAX (0, (gdk_screen_get_height (screen) - requisition.height) / 2);
4618     }
4619
4620   priv->monitor_num = gdk_screen_get_monitor_at_point (screen, x, y);
4621   priv->initially_pushed_in = FALSE;
4622
4623   /* Set the type hint here to allow custom position functions
4624    * to set a different hint
4625    */
4626   if (!gtk_widget_get_visible (priv->toplevel))
4627     gtk_window_set_type_hint (GTK_WINDOW (priv->toplevel), GDK_WINDOW_TYPE_HINT_POPUP_MENU);
4628
4629   if (priv->position_func)
4630     {
4631       (* priv->position_func) (menu, &x, &y, &priv->initially_pushed_in,
4632                                priv->position_func_data);
4633
4634       if (priv->monitor_num < 0)
4635         priv->monitor_num = gdk_screen_get_monitor_at_point (screen, x, y);
4636
4637       gdk_screen_get_monitor_workarea (screen, priv->monitor_num, &monitor);
4638     }
4639   else
4640     {
4641       gint space_left, space_right, space_above, space_below;
4642       gint needed_width;
4643       gint needed_height;
4644       GtkBorder padding;
4645       gboolean rtl = (gtk_widget_get_direction (widget) == GTK_TEXT_DIR_RTL);
4646
4647       get_menu_padding (widget, &padding);
4648
4649       /* The placement of popup menus horizontally works like this (with
4650        * RTL in parentheses)
4651        *
4652        * - If there is enough room to the right (left) of the mouse cursor,
4653        *   position the menu there.
4654        *
4655        * - Otherwise, if if there is enough room to the left (right) of the
4656        *   mouse cursor, position the menu there.
4657        *
4658        * - Otherwise if the menu is smaller than the monitor, position it
4659        *   on the side of the mouse cursor that has the most space available
4660        *
4661        * - Otherwise (if there is simply not enough room for the menu on the
4662        *   monitor), position it as far left (right) as possible.
4663        *
4664        * Positioning in the vertical direction is similar: first try below
4665        * mouse cursor, then above.
4666        */
4667       gdk_screen_get_monitor_workarea (screen, priv->monitor_num, &monitor);
4668
4669       space_left = x - monitor.x;
4670       space_right = monitor.x + monitor.width - x - 1;
4671       space_above = y - monitor.y;
4672       space_below = monitor.y + monitor.height - y - 1;
4673
4674       /* Position horizontally. */
4675
4676       /* the amount of space we need to position the menu.
4677        * Note the menu is offset "thickness" pixels
4678        */
4679       needed_width = requisition.width - padding.left;
4680
4681       if (needed_width <= space_left ||
4682           needed_width <= space_right)
4683         {
4684           if ((rtl  && needed_width <= space_left) ||
4685               (!rtl && needed_width >  space_right))
4686             {
4687               /* position left */
4688               x = x + padding.left - requisition.width + 1;
4689             }
4690           else
4691             {
4692               /* position right */
4693               x = x - padding.right;
4694             }
4695
4696           /* x is clamped on-screen further down */
4697         }
4698       else if (requisition.width <= monitor.width)
4699         {
4700           /* the menu is too big to fit on either side of the mouse
4701            * cursor, but smaller than the monitor. Position it on
4702            * the side that has the most space
4703            */
4704           if (space_left > space_right)
4705             {
4706               /* left justify */
4707               x = monitor.x;
4708             }
4709           else
4710             {
4711               /* right justify */
4712               x = monitor.x + monitor.width - requisition.width;
4713             }
4714         }
4715       else /* menu is simply too big for the monitor */
4716         {
4717           if (rtl)
4718             {
4719               /* right justify */
4720               x = monitor.x + monitor.width - requisition.width;
4721             }
4722           else
4723             {
4724               /* left justify */
4725               x = monitor.x;
4726             }
4727         }
4728
4729       /* Position vertically.
4730        * The algorithm is the same as above, but simpler
4731        * because we don't have to take RTL into account.
4732        */
4733       needed_height = requisition.height - padding.top;
4734
4735       if (needed_height <= space_above ||
4736           needed_height <= space_below)
4737         {
4738           if (needed_height <= space_below)
4739             y = y - padding.top;
4740           else
4741             y = y + padding.bottom - requisition.height + 1;
4742
4743           y = CLAMP (y, monitor.y,
4744                      monitor.y + monitor.height - requisition.height);
4745         }
4746       else if (needed_height > space_below && needed_height > space_above)
4747         {
4748           if (space_below >= space_above)
4749             y = monitor.y + monitor.height - requisition.height;
4750           else
4751             y = monitor.y;
4752         }
4753       else
4754         {
4755           y = monitor.y;
4756         }
4757     }
4758
4759   scroll_offset = 0;
4760
4761   if (y + requisition.height > monitor.y + monitor.height)
4762     {
4763       if (priv->initially_pushed_in)
4764         scroll_offset += (monitor.y + monitor.height) - requisition.height - y;
4765       y = (monitor.y + monitor.height) - requisition.height;
4766     }
4767
4768   if (y < monitor.y)
4769     {
4770       if (priv->initially_pushed_in)
4771         scroll_offset += monitor.y - y;
4772       y = monitor.y;
4773     }
4774
4775   x = CLAMP (x, monitor.x, MAX (monitor.x, monitor.x + monitor.width - requisition.width));
4776
4777   if (GTK_MENU_SHELL (menu)->priv->active)
4778     {
4779       priv->have_position = TRUE;
4780       priv->position_x = x;
4781       priv->position_y = y;
4782     }
4783
4784   if (scroll_offset != 0)
4785     {
4786       GtkBorder arrow_border;
4787
4788       get_arrows_border (menu, &arrow_border);
4789       scroll_offset += arrow_border.top;
4790     }
4791
4792   gtk_window_move (GTK_WINDOW (GTK_MENU_SHELL (menu)->priv->active ? priv->toplevel : priv->tearoff_window),
4793                    x, y);
4794
4795   if (!GTK_MENU_SHELL (menu)->priv->active)
4796     {
4797       gtk_window_resize (GTK_WINDOW (priv->tearoff_window),
4798                          requisition.width, requisition.height);
4799     }
4800
4801   if (set_scroll_offset)
4802     priv->scroll_offset = scroll_offset;
4803 }
4804
4805 static void
4806 gtk_menu_remove_scroll_timeout (GtkMenu *menu)
4807 {
4808   GtkMenuPrivate *priv = menu->priv;
4809
4810   if (priv->scroll_timeout)
4811     {
4812       g_source_remove (priv->scroll_timeout);
4813       priv->scroll_timeout = 0;
4814     }
4815 }
4816
4817 static void
4818 gtk_menu_stop_scrolling (GtkMenu *menu)
4819 {
4820   GtkMenuPrivate *priv = menu->priv;
4821
4822   gtk_menu_remove_scroll_timeout (menu);
4823   priv->upper_arrow_prelight = FALSE;
4824   priv->lower_arrow_prelight = FALSE;
4825 }
4826
4827 static void
4828 gtk_menu_scroll_to (GtkMenu *menu,
4829                     gint    offset)
4830 {
4831   GtkMenuPrivate *priv = menu->priv;
4832   GtkBorder arrow_border, padding;
4833   GtkWidget *widget;
4834   gint x, y;
4835   gint view_width, view_height;
4836   gint border_width;
4837   gint menu_height;
4838   guint vertical_padding;
4839   guint horizontal_padding;
4840   gboolean double_arrows;
4841
4842   widget = GTK_WIDGET (menu);
4843
4844   if (priv->tearoff_active && priv->tearoff_adjustment)
4845     gtk_adjustment_set_value (priv->tearoff_adjustment, offset);
4846
4847   /* Move/resize the viewport according to arrows: */
4848   view_width = gtk_widget_get_allocated_width (widget);
4849   view_height = gtk_widget_get_allocated_height (widget);
4850
4851   gtk_widget_style_get (GTK_WIDGET (menu),
4852                         "vertical-padding", &vertical_padding,
4853                         "horizontal-padding", &horizontal_padding,
4854                         NULL);
4855
4856   get_menu_padding (widget, &padding);
4857   double_arrows = get_double_arrows (menu);
4858
4859   border_width = gtk_container_get_border_width (GTK_CONTAINER (menu));
4860
4861   view_width -= (2 * (border_width + horizontal_padding)) + padding.left + padding.right;
4862   view_height -= (2 * (border_width + vertical_padding)) + padding.top + padding.bottom;
4863   menu_height = priv->requested_height - (2 * (border_width + vertical_padding)) -
4864     padding.top - padding.bottom;
4865
4866   x = border_width + padding.left + horizontal_padding;
4867   y = border_width + padding.top + vertical_padding;
4868
4869   if (double_arrows && !priv->tearoff_active)
4870     {
4871       if (view_height < menu_height               ||
4872           (offset > 0 && priv->scroll_offset > 0) ||
4873           (offset < 0 && priv->scroll_offset < 0))
4874         {
4875           GtkStateFlags upper_arrow_previous_state = priv->upper_arrow_state;
4876           GtkStateFlags lower_arrow_previous_state = priv->lower_arrow_state;
4877
4878           if (!priv->upper_arrow_visible || !priv->lower_arrow_visible)
4879             gtk_widget_queue_draw (GTK_WIDGET (menu));
4880
4881           priv->upper_arrow_visible = priv->lower_arrow_visible = TRUE;
4882
4883           get_arrows_border (menu, &arrow_border);
4884           y += arrow_border.top;
4885           view_height -= arrow_border.top;
4886           view_height -= arrow_border.bottom;
4887
4888           if (offset <= 0)
4889             priv->upper_arrow_state |= GTK_STATE_FLAG_INSENSITIVE;
4890           else
4891             {
4892               priv->upper_arrow_state &= ~(GTK_STATE_FLAG_INSENSITIVE);
4893
4894               if (priv->upper_arrow_prelight)
4895                 priv->upper_arrow_state |= GTK_STATE_FLAG_PRELIGHT;
4896               else
4897                 priv->upper_arrow_state &= ~(GTK_STATE_FLAG_PRELIGHT);
4898             }
4899
4900           if (offset >= menu_height - view_height)
4901             priv->lower_arrow_state |= GTK_STATE_FLAG_INSENSITIVE;
4902           else
4903             {
4904               priv->lower_arrow_state &= ~(GTK_STATE_FLAG_INSENSITIVE);
4905
4906               if (priv->lower_arrow_prelight)
4907                 priv->lower_arrow_state |= GTK_STATE_FLAG_PRELIGHT;
4908               else
4909                 priv->lower_arrow_state &= ~(GTK_STATE_FLAG_PRELIGHT);
4910             }
4911
4912           if ((priv->upper_arrow_state != upper_arrow_previous_state) ||
4913               (priv->lower_arrow_state != lower_arrow_previous_state))
4914             gtk_widget_queue_draw (GTK_WIDGET (menu));
4915
4916           if ((upper_arrow_previous_state & GTK_STATE_FLAG_INSENSITIVE) == 0 &&
4917               (priv->upper_arrow_state & GTK_STATE_FLAG_INSENSITIVE) != 0)
4918             {
4919               /* At the upper border, possibly remove timeout */
4920               if (priv->scroll_step < 0)
4921                 {
4922                   gtk_menu_stop_scrolling (menu);
4923                   gtk_widget_queue_draw (GTK_WIDGET (menu));
4924                 }
4925             }
4926
4927           if ((lower_arrow_previous_state & GTK_STATE_FLAG_INSENSITIVE) == 0 &&
4928               (priv->lower_arrow_state & GTK_STATE_FLAG_INSENSITIVE) != 0)
4929             {
4930               /* At the lower border, possibly remove timeout */
4931               if (priv->scroll_step > 0)
4932                 {
4933                   gtk_menu_stop_scrolling (menu);
4934                   gtk_widget_queue_draw (GTK_WIDGET (menu));
4935                 }
4936             }
4937         }
4938       else if (priv->upper_arrow_visible || priv->lower_arrow_visible)
4939         {
4940           offset = 0;
4941
4942           priv->upper_arrow_visible = priv->lower_arrow_visible = FALSE;
4943           priv->upper_arrow_prelight = priv->lower_arrow_prelight = FALSE;
4944
4945           gtk_menu_stop_scrolling (menu);
4946           gtk_widget_queue_draw (GTK_WIDGET (menu));
4947         }
4948     }
4949   else if (!priv->tearoff_active)
4950     {
4951       gboolean last_visible;
4952
4953       last_visible = priv->upper_arrow_visible;
4954       priv->upper_arrow_visible = offset > 0;
4955
4956       /* upper_arrow_visible may have changed, so requery the border */
4957       get_arrows_border (menu, &arrow_border);
4958       view_height -= arrow_border.top;
4959
4960       if ((last_visible != priv->upper_arrow_visible) &&
4961           !priv->upper_arrow_visible)
4962         {
4963           priv->upper_arrow_prelight = FALSE;
4964
4965           /* If we hide the upper arrow, possibly remove timeout */
4966           if (priv->scroll_step < 0)
4967             {
4968               gtk_menu_stop_scrolling (menu);
4969               gtk_widget_queue_draw (GTK_WIDGET (menu));
4970             }
4971         }
4972
4973       last_visible = priv->lower_arrow_visible;
4974       priv->lower_arrow_visible = offset < menu_height - view_height;
4975
4976       /* lower_arrow_visible may have changed, so requery the border */
4977       get_arrows_border (menu, &arrow_border);
4978       view_height -= arrow_border.bottom;
4979
4980       if ((last_visible != priv->lower_arrow_visible) &&
4981            !priv->lower_arrow_visible)
4982         {
4983           priv->lower_arrow_prelight = FALSE;
4984
4985           /* If we hide the lower arrow, possibly remove timeout */
4986           if (priv->scroll_step > 0)
4987             {
4988               gtk_menu_stop_scrolling (menu);
4989               gtk_widget_queue_draw (GTK_WIDGET (menu));
4990             }
4991         }
4992
4993       y += arrow_border.top;
4994     }
4995
4996   /* Scroll the menu: */
4997   if (gtk_widget_get_realized (widget))
4998     gdk_window_move (priv->bin_window, 0, -offset);
4999
5000   if (gtk_widget_get_realized (widget))
5001     gdk_window_move_resize (priv->view_window, x, y, view_width, view_height);
5002
5003   priv->scroll_offset = offset;
5004 }
5005
5006 static gboolean
5007 compute_child_offset (GtkMenu   *menu,
5008                       GtkWidget *menu_item,
5009                       gint      *offset,
5010                       gint      *height,
5011                       gboolean  *is_last_child)
5012 {
5013   GtkMenuPrivate *priv = menu->priv;
5014   gint item_top_attach;
5015   gint item_bottom_attach;
5016   gint child_offset = 0;
5017   gint i;
5018
5019   get_effective_child_attach (menu_item, NULL, NULL,
5020                               &item_top_attach, &item_bottom_attach);
5021
5022   /* there is a possibility that we get called before _size_request,
5023    * so check the height table for safety.
5024    */
5025   if (!priv->heights || priv->heights_length < gtk_menu_get_n_rows (menu))
5026     return FALSE;
5027
5028   /* when we have a row with only invisible children, its height will
5029    * be zero, so there's no need to check WIDGET_VISIBLE here
5030    */
5031   for (i = 0; i < item_top_attach; i++)
5032     child_offset += priv->heights[i];
5033
5034   if (is_last_child)
5035     *is_last_child = (item_bottom_attach == gtk_menu_get_n_rows (menu));
5036   if (offset)
5037     *offset = child_offset;
5038   if (height)
5039     *height = priv->heights[item_top_attach];
5040
5041   return TRUE;
5042 }
5043
5044 static void
5045 gtk_menu_scroll_item_visible (GtkMenuShell *menu_shell,
5046                               GtkWidget    *menu_item)
5047 {
5048   GtkMenu *menu = GTK_MENU (menu_shell);
5049   GtkMenuPrivate *priv = menu->priv;
5050   GtkWidget *widget = GTK_WIDGET (menu_shell);
5051   gint child_offset, child_height;
5052   gint height;
5053   gint y;
5054   gint arrow_height;
5055   gboolean last_child = 0;
5056
5057   /* We need to check if the selected item fully visible.
5058    * If not we need to scroll the menu so that it becomes fully
5059    * visible.
5060    */
5061   if (compute_child_offset (menu, menu_item,
5062                             &child_offset, &child_height, &last_child))
5063     {
5064       guint vertical_padding;
5065       gboolean double_arrows;
5066       GtkBorder padding;
5067
5068       y = priv->scroll_offset;
5069       height = gdk_window_get_height (gtk_widget_get_window (widget));
5070
5071       gtk_widget_style_get (widget,
5072                             "vertical-padding", &vertical_padding,
5073                             NULL);
5074
5075       double_arrows = get_double_arrows (menu);
5076       get_menu_padding (widget, &padding);
5077
5078       height -= 2 * gtk_container_get_border_width (GTK_CONTAINER (menu)) +
5079                 padding.top + padding.bottom +
5080                 2 * vertical_padding;
5081       if (child_offset < y)
5082         {
5083           /* Ignore the enter event we might get if the pointer
5084            * is on the menu
5085            */
5086           menu_shell->priv->ignore_enter = TRUE;
5087           gtk_menu_scroll_to (menu, child_offset);
5088         }
5089       else
5090         {
5091           GtkBorder arrow_border;
5092
5093           arrow_height = 0;
5094
5095           get_arrows_border (menu, &arrow_border);
5096           if (!priv->tearoff_active)
5097             arrow_height = arrow_border.top + arrow_border.bottom;
5098
5099           if (child_offset + child_height > y + height - arrow_height)
5100             {
5101               arrow_height = 0;
5102               if ((!last_child && !priv->tearoff_active) || double_arrows)
5103                 arrow_height += arrow_border.bottom;
5104
5105               y = child_offset + child_height - height + arrow_height;
5106               if (((y > 0) && !priv->tearoff_active) || double_arrows)
5107                 {
5108                   /* Need upper arrow */
5109                   arrow_height += arrow_border.top;
5110                   y = child_offset + child_height - height + arrow_height;
5111                 }
5112               /* Ignore the enter event we might get if the pointer
5113                * is on the menu
5114                */
5115               menu_shell->priv->ignore_enter = TRUE;
5116               gtk_menu_scroll_to (menu, y);
5117             }
5118         }
5119     }
5120 }
5121
5122 static void
5123 gtk_menu_select_item (GtkMenuShell *menu_shell,
5124                       GtkWidget    *menu_item)
5125 {
5126   GtkMenu *menu = GTK_MENU (menu_shell);
5127
5128   if (gtk_widget_get_realized (GTK_WIDGET (menu)))
5129     gtk_menu_scroll_item_visible (menu_shell, menu_item);
5130
5131   GTK_MENU_SHELL_CLASS (gtk_menu_parent_class)->select_item (menu_shell, menu_item);
5132 }
5133
5134
5135 /* Reparent the menu, taking care of the refcounting
5136  *
5137  * If unrealize is true we force a unrealize while reparenting the parent.
5138  * This can help eliminate flicker in some cases.
5139  *
5140  * What happens is that when the menu is unrealized and then re-realized,
5141  * the allocations are as follows:
5142  *
5143  *  parent - 1x1 at (0,0)
5144  *  child1 - 100x20 at (0,0)
5145  *  child2 - 100x20 at (0,20)
5146  *  child3 - 100x20 at (0,40)
5147  *
5148  * That is, the parent is small but the children are full sized. Then,
5149  * when the queued_resize gets processed, the parent gets resized to
5150  * full size.
5151  *
5152  * But in order to eliminate flicker when scrolling, gdkgeometry-x11.c
5153  * contains the following logic:
5154  *
5155  * - if a move or resize operation on a window would change the clip
5156  *   region on the children, then before the window is resized
5157  *   the background for children is temporarily set to None, the
5158  *   move/resize done, and the background for the children restored.
5159  *
5160  * So, at the point where the parent is resized to final size, the
5161  * background for the children is temporarily None, and thus they
5162  * are not cleared to the background color and the previous background
5163  * (the image of the menu) is left in place.
5164  */
5165 static void
5166 gtk_menu_reparent (GtkMenu   *menu,
5167                    GtkWidget *new_parent,
5168                    gboolean   unrealize)
5169 {
5170   GObject *object = G_OBJECT (menu);
5171   GtkWidget *widget = GTK_WIDGET (menu);
5172   gboolean was_floating = g_object_is_floating (object);
5173
5174   g_object_ref_sink (object);
5175
5176   if (unrealize)
5177     {
5178       g_object_ref (object);
5179       gtk_container_remove (GTK_CONTAINER (gtk_widget_get_parent (widget)), widget);
5180       gtk_container_add (GTK_CONTAINER (new_parent), widget);
5181       g_object_unref (object);
5182     }
5183   else
5184     gtk_widget_reparent (widget, new_parent);
5185
5186   if (was_floating)
5187     g_object_force_floating (object);
5188   else
5189     g_object_unref (object);
5190 }
5191
5192 static void
5193 gtk_menu_show_all (GtkWidget *widget)
5194 {
5195   /* Show children, but not self. */
5196   gtk_container_foreach (GTK_CONTAINER (widget), (GtkCallback) gtk_widget_show_all, NULL);
5197 }
5198
5199 /**
5200  * gtk_menu_set_screen:
5201  * @menu: a #GtkMenu
5202  * @screen: (allow-none): a #GdkScreen, or %NULL if the screen should be
5203  *          determined by the widget the menu is attached to
5204  *
5205  * Sets the #GdkScreen on which the menu will be displayed.
5206  *
5207  * Since: 2.2
5208  */
5209 void
5210 gtk_menu_set_screen (GtkMenu   *menu,
5211                      GdkScreen *screen)
5212 {
5213   g_return_if_fail (GTK_IS_MENU (menu));
5214   g_return_if_fail (screen == NULL || GDK_IS_SCREEN (screen));
5215
5216   g_object_set_data (G_OBJECT (menu), I_("gtk-menu-explicit-screen"), screen);
5217
5218   if (screen)
5219     {
5220       menu_change_screen (menu, screen);
5221     }
5222   else
5223     {
5224       GtkWidget *attach_widget = gtk_menu_get_attach_widget (menu);
5225       if (attach_widget)
5226         attach_widget_screen_changed (attach_widget, NULL, menu);
5227     }
5228 }
5229
5230 /**
5231  * gtk_menu_attach:
5232  * @menu: a #GtkMenu
5233  * @child: a #GtkMenuItem
5234  * @left_attach: The column number to attach the left side of the item to
5235  * @right_attach: The column number to attach the right side of the item to
5236  * @top_attach: The row number to attach the top of the item to
5237  * @bottom_attach: The row number to attach the bottom of the item to
5238  *
5239  * Adds a new #GtkMenuItem to a (table) menu. The number of 'cells' that
5240  * an item will occupy is specified by @left_attach, @right_attach,
5241  * @top_attach and @bottom_attach. These each represent the leftmost,
5242  * rightmost, uppermost and lower column and row numbers of the table.
5243  * (Columns and rows are indexed from zero).
5244  *
5245  * Note that this function is not related to gtk_menu_detach().
5246  *
5247  * Since: 2.4
5248  */
5249 void
5250 gtk_menu_attach (GtkMenu   *menu,
5251                  GtkWidget *child,
5252                  guint      left_attach,
5253                  guint      right_attach,
5254                  guint      top_attach,
5255                  guint      bottom_attach)
5256 {
5257   GtkMenuShell *menu_shell;
5258   GtkWidget *parent;
5259
5260   g_return_if_fail (GTK_IS_MENU (menu));
5261   g_return_if_fail (GTK_IS_MENU_ITEM (child));
5262   parent = gtk_widget_get_parent (child);
5263   g_return_if_fail (parent == NULL || parent == GTK_WIDGET (menu));
5264   g_return_if_fail (left_attach < right_attach);
5265   g_return_if_fail (top_attach < bottom_attach);
5266
5267   menu_shell = GTK_MENU_SHELL (menu);
5268
5269   if (!parent)
5270     {
5271       AttachInfo *ai = get_attach_info (child);
5272
5273       ai->left_attach = left_attach;
5274       ai->right_attach = right_attach;
5275       ai->top_attach = top_attach;
5276       ai->bottom_attach = bottom_attach;
5277
5278       menu_shell->priv->children = g_list_append (menu_shell->priv->children, child);
5279
5280       gtk_widget_set_parent (child, GTK_WIDGET (menu));
5281
5282       menu_queue_resize (menu);
5283     }
5284   else
5285     {
5286       gtk_container_child_set (GTK_CONTAINER (parent), child,
5287                                "left-attach",   left_attach,
5288                                "right-attach",  right_attach,
5289                                "top-attach",    top_attach,
5290                                "bottom-attach", bottom_attach,
5291                                NULL);
5292     }
5293 }
5294
5295 static gint
5296 gtk_menu_get_popup_delay (GtkMenuShell *menu_shell)
5297 {
5298   gint popup_delay;
5299
5300   g_object_get (gtk_widget_get_settings (GTK_WIDGET (menu_shell)),
5301                 "gtk-menu-popup-delay", &popup_delay,
5302                 NULL);
5303
5304   return popup_delay;
5305 }
5306
5307 static GtkWidget *
5308 find_child_containing (GtkMenuShell *menu_shell,
5309                        int           left,
5310                        int           right,
5311                        int           top,
5312                        int           bottom)
5313 {
5314   GList *list;
5315
5316   /* find a child which includes the area given by
5317    * left, right, top, bottom.
5318    */
5319   for (list = menu_shell->priv->children; list; list = list->next)
5320     {
5321       gint l, r, t, b;
5322
5323       if (!_gtk_menu_item_is_selectable (list->data))
5324         continue;
5325
5326       get_effective_child_attach (list->data, &l, &r, &t, &b);
5327
5328       if (l <= left && right <= r && t <= top && bottom <= b)
5329         return GTK_WIDGET (list->data);
5330     }
5331
5332   return NULL;
5333 }
5334
5335 static void
5336 gtk_menu_move_current (GtkMenuShell         *menu_shell,
5337                        GtkMenuDirectionType  direction)
5338 {
5339   GtkMenu *menu = GTK_MENU (menu_shell);
5340   gint i;
5341   gint l, r, t, b;
5342   GtkWidget *match = NULL;
5343
5344   if (gtk_widget_get_direction (GTK_WIDGET (menu_shell)) == GTK_TEXT_DIR_RTL)
5345     {
5346       switch (direction)
5347         {
5348         case GTK_MENU_DIR_CHILD:
5349           direction = GTK_MENU_DIR_PARENT;
5350           break;
5351         case GTK_MENU_DIR_PARENT:
5352           direction = GTK_MENU_DIR_CHILD;
5353           break;
5354         default: ;
5355         }
5356     }
5357
5358   /* use special table menu key bindings */
5359   if (menu_shell->priv->active_menu_item && gtk_menu_get_n_columns (menu) > 1)
5360     {
5361       get_effective_child_attach (menu_shell->priv->active_menu_item, &l, &r, &t, &b);
5362
5363       if (direction == GTK_MENU_DIR_NEXT)
5364         {
5365           for (i = b; i < gtk_menu_get_n_rows (menu); i++)
5366             {
5367               match = find_child_containing (menu_shell, l, l + 1, i, i + 1);
5368               if (match)
5369                 break;
5370             }
5371
5372           if (!match)
5373             {
5374               /* wrap around */
5375               for (i = 0; i < t; i++)
5376                 {
5377                   match = find_child_containing (menu_shell,
5378                                                  l, l + 1, i, i + 1);
5379                   if (match)
5380                     break;
5381                 }
5382             }
5383         }
5384       else if (direction == GTK_MENU_DIR_PREV)
5385         {
5386           for (i = t; i > 0; i--)
5387             {
5388               match = find_child_containing (menu_shell,
5389                                              l, l + 1, i - 1, i);
5390               if (match)
5391                 break;
5392             }
5393
5394           if (!match)
5395             {
5396               /* wrap around */
5397               for (i = gtk_menu_get_n_rows (menu); i > b; i--)
5398                 {
5399                   match = find_child_containing (menu_shell,
5400                                                  l, l + 1, i - 1, i);
5401                   if (match)
5402                     break;
5403                 }
5404             }
5405         }
5406       else if (direction == GTK_MENU_DIR_PARENT)
5407         {
5408           /* we go one left if possible */
5409           if (l > 0)
5410             match = find_child_containing (menu_shell,
5411                                            l - 1, l, t, t + 1);
5412
5413           if (!match)
5414             {
5415               GtkWidget *parent = menu_shell->priv->parent_menu_shell;
5416
5417               if (!parent
5418                   || g_list_length (GTK_MENU_SHELL (parent)->priv->children) <= 1)
5419                 match = menu_shell->priv->active_menu_item;
5420             }
5421         }
5422       else if (direction == GTK_MENU_DIR_CHILD)
5423         {
5424           /* we go one right if possible */
5425           if (r < gtk_menu_get_n_columns (menu))
5426             match = find_child_containing (menu_shell, r, r + 1, t, t + 1);
5427
5428           if (!match)
5429             {
5430               GtkWidget *parent = menu_shell->priv->parent_menu_shell;
5431
5432               if (! GTK_MENU_ITEM (menu_shell->priv->active_menu_item)->priv->submenu &&
5433                   (!parent ||
5434                    g_list_length (GTK_MENU_SHELL (parent)->priv->children) <= 1))
5435                 match = menu_shell->priv->active_menu_item;
5436             }
5437         }
5438
5439       if (match)
5440         {
5441           gtk_menu_shell_select_item (menu_shell, match);
5442           return;
5443         }
5444     }
5445
5446   GTK_MENU_SHELL_CLASS (gtk_menu_parent_class)->move_current (menu_shell, direction);
5447 }
5448
5449 static gint
5450 get_visible_size (GtkMenu *menu)
5451 {
5452   GtkMenuPrivate *priv = menu->priv;
5453   GtkAllocation allocation;
5454   GtkWidget *widget = GTK_WIDGET (menu);
5455   GtkContainer *container = GTK_CONTAINER (menu);
5456   GtkBorder padding;
5457   gint menu_height;
5458
5459   gtk_widget_get_allocation (widget, &allocation);
5460   get_menu_padding (widget, &padding);
5461
5462   menu_height = (allocation.height -
5463                  (2 * gtk_container_get_border_width (container)) -
5464                  padding.top - padding.bottom);
5465
5466   if (!priv->tearoff_active)
5467     {
5468       GtkBorder arrow_border;
5469
5470       get_arrows_border (menu, &arrow_border);
5471       menu_height -= arrow_border.top;
5472       menu_height -= arrow_border.bottom;
5473     }
5474
5475   return menu_height;
5476 }
5477
5478 /* Find the sensitive on-screen child containing @y, or if none,
5479  * the nearest selectable onscreen child. (%NULL if none)
5480  */
5481 static GtkWidget *
5482 child_at (GtkMenu *menu,
5483           gint     y)
5484 {
5485   GtkMenuPrivate *priv = menu->priv;
5486   GtkMenuShell *menu_shell = GTK_MENU_SHELL (menu);
5487   GtkWidget *child = NULL;
5488   gint child_offset = 0;
5489   GList *children;
5490   gint menu_height;
5491   gint lower, upper; /* Onscreen bounds */
5492
5493   menu_height = get_visible_size (menu);
5494   lower = priv->scroll_offset;
5495   upper = priv->scroll_offset + menu_height;
5496
5497   for (children = menu_shell->priv->children; children; children = children->next)
5498     {
5499       if (gtk_widget_get_visible (children->data))
5500         {
5501           GtkRequisition child_requisition;
5502
5503           gtk_widget_get_preferred_size (children->data,
5504                                          &child_requisition, NULL);
5505
5506           if (_gtk_menu_item_is_selectable (children->data) &&
5507               child_offset >= lower &&
5508               child_offset + child_requisition.height <= upper)
5509             {
5510               child = children->data;
5511
5512               if (child_offset + child_requisition.height > y &&
5513                   !GTK_IS_TEAROFF_MENU_ITEM (child))
5514                 return child;
5515             }
5516
5517           child_offset += child_requisition.height;
5518         }
5519     }
5520
5521   return child;
5522 }
5523
5524 static gint
5525 get_menu_height (GtkMenu *menu)
5526 {
5527   GtkMenuPrivate *priv = menu->priv;
5528   GtkAllocation allocation;
5529   GtkWidget *widget = GTK_WIDGET (menu);
5530   GtkBorder padding;
5531   gint height;
5532
5533   gtk_widget_get_allocation (widget, &allocation);
5534   get_menu_padding (widget, &padding);
5535
5536   height = allocation.height;
5537   height -= (gtk_container_get_border_width (GTK_CONTAINER (widget)) * 2) +
5538     padding.top + padding.bottom;
5539
5540   if (!priv->tearoff_active)
5541     {
5542       GtkBorder arrow_border;
5543
5544       get_arrows_border (menu, &arrow_border);
5545       height -= arrow_border.top;
5546       height -= arrow_border.bottom;
5547     }
5548
5549   return height;
5550 }
5551
5552 static void
5553 gtk_menu_real_move_scroll (GtkMenu       *menu,
5554                            GtkScrollType  type)
5555 {
5556   GtkMenuPrivate *priv = menu->priv;
5557   gint page_size = get_visible_size (menu);
5558   gint end_position = get_menu_height (menu);
5559   GtkMenuShell *menu_shell = GTK_MENU_SHELL (menu);
5560
5561   switch (type)
5562     {
5563     case GTK_SCROLL_PAGE_UP:
5564     case GTK_SCROLL_PAGE_DOWN:
5565       {
5566         gint old_offset;
5567         gint new_offset;
5568         gint child_offset = 0;
5569         gboolean old_upper_arrow_visible;
5570         gint step;
5571
5572         if (type == GTK_SCROLL_PAGE_UP)
5573           step = - page_size;
5574         else
5575           step = page_size;
5576
5577         if (menu_shell->priv->active_menu_item)
5578           {
5579             gint child_height;
5580
5581             compute_child_offset (menu, menu_shell->priv->active_menu_item,
5582                                   &child_offset, &child_height, NULL);
5583             child_offset += child_height / 2;
5584           }
5585
5586         menu_shell->priv->ignore_enter = TRUE;
5587         old_upper_arrow_visible = priv->upper_arrow_visible && !priv->tearoff_active;
5588         old_offset = priv->scroll_offset;
5589
5590         new_offset = priv->scroll_offset + step;
5591         new_offset = CLAMP (new_offset, 0, end_position - page_size);
5592
5593         gtk_menu_scroll_to (menu, new_offset);
5594
5595         if (menu_shell->priv->active_menu_item)
5596           {
5597             GtkWidget *new_child;
5598             gboolean new_upper_arrow_visible = priv->upper_arrow_visible && !priv->tearoff_active;
5599             GtkBorder arrow_border;
5600             get_arrows_border (menu, &arrow_border);
5601
5602             if (priv->scroll_offset != old_offset)
5603               step = priv->scroll_offset - old_offset;
5604
5605             step -= (new_upper_arrow_visible - old_upper_arrow_visible) * arrow_border.top;
5606
5607             new_child = child_at (menu, child_offset + step);
5608             if (new_child)
5609               gtk_menu_shell_select_item (menu_shell, new_child);
5610           }
5611       }
5612       break;
5613     case GTK_SCROLL_START:
5614       /* Ignore the enter event we might get if the pointer is on the menu */
5615       menu_shell->priv->ignore_enter = TRUE;
5616       gtk_menu_scroll_to (menu, 0);
5617       gtk_menu_shell_select_first (menu_shell, TRUE);
5618       break;
5619     case GTK_SCROLL_END:
5620       /* Ignore the enter event we might get if the pointer is on the menu */
5621       menu_shell->priv->ignore_enter = TRUE;
5622       gtk_menu_scroll_to (menu, end_position - page_size);
5623       _gtk_menu_shell_select_last (menu_shell, TRUE);
5624       break;
5625     default:
5626       break;
5627     }
5628 }
5629
5630 /**
5631  * gtk_menu_set_monitor:
5632  * @menu: a #GtkMenu
5633  * @monitor_num: the number of the monitor on which the menu should
5634  *    be popped up
5635  *
5636  * Informs GTK+ on which monitor a menu should be popped up.
5637  * See gdk_screen_get_monitor_geometry().
5638  *
5639  * This function should be called from a #GtkMenuPositionFunc
5640  * if the menu should not appear on the same monitor as the pointer.
5641  * This information can't be reliably inferred from the coordinates
5642  * returned by a #GtkMenuPositionFunc, since, for very long menus,
5643  * these coordinates may extend beyond the monitor boundaries or even
5644  * the screen boundaries.
5645  *
5646  * Since: 2.4
5647  */
5648 void
5649 gtk_menu_set_monitor (GtkMenu *menu,
5650                       gint     monitor_num)
5651 {
5652   GtkMenuPrivate *priv = menu->priv;
5653
5654   g_return_if_fail (GTK_IS_MENU (menu));
5655
5656   priv->monitor_num = monitor_num;
5657 }
5658
5659 /**
5660  * gtk_menu_get_monitor:
5661  * @menu: a #GtkMenu
5662  *
5663  * Retrieves the number of the monitor on which to show the menu.
5664  *
5665  * Returns: the number of the monitor on which the menu should
5666  *    be popped up or -1, if no monitor has been set
5667  *
5668  * Since: 2.14
5669  */
5670 gint
5671 gtk_menu_get_monitor (GtkMenu *menu)
5672 {
5673   g_return_val_if_fail (GTK_IS_MENU (menu), -1);
5674
5675   return menu->priv->monitor_num;
5676 }
5677
5678 /**
5679  * gtk_menu_get_for_attach_widget:
5680  * @widget: a #GtkWidget
5681  *
5682  * Returns a list of the menus which are attached to this widget.
5683  * This list is owned by GTK+ and must not be modified.
5684  *
5685  * Return value: (element-type GtkWidget) (transfer none): the list
5686  *     of menus attached to his widget.
5687  *
5688  * Since: 2.6
5689  */
5690 GList*
5691 gtk_menu_get_for_attach_widget (GtkWidget *widget)
5692 {
5693   GList *list;
5694
5695   g_return_val_if_fail (GTK_IS_WIDGET (widget), NULL);
5696
5697   list = g_object_get_data (G_OBJECT (widget), ATTACHED_MENUS);
5698
5699   return list;
5700 }
5701
5702 static void
5703 gtk_menu_grab_notify (GtkWidget *widget,
5704                       gboolean   was_grabbed)
5705 {
5706   GtkMenu *menu;
5707   GtkWidget *toplevel;
5708   GtkWindowGroup *group;
5709   GtkWidget *grab;
5710   GdkDevice *pointer;
5711
5712   menu = GTK_MENU (widget);
5713   pointer = _gtk_menu_shell_get_grab_device (GTK_MENU_SHELL (widget));
5714
5715   if (!pointer ||
5716       !gtk_widget_device_is_shadowed (widget, pointer))
5717     return;
5718
5719   toplevel = gtk_widget_get_toplevel (widget);
5720
5721   if (!GTK_IS_WINDOW (toplevel))
5722     return;
5723
5724   group = gtk_window_get_group (GTK_WINDOW (toplevel));
5725   grab = gtk_window_group_get_current_device_grab (group, pointer);
5726
5727   if (GTK_MENU_SHELL (widget)->priv->active && !GTK_IS_MENU_SHELL (grab))
5728     gtk_menu_shell_cancel (GTK_MENU_SHELL (widget));
5729
5730   menu->priv->drag_scroll_started = FALSE;
5731 }
5732
5733 /**
5734  * gtk_menu_set_reserve_toggle_size:
5735  * @menu: a #GtkMenu
5736  * @reserve_toggle_size: whether to reserve size for toggles
5737  *
5738  * Sets whether the menu should reserve space for drawing toggles
5739  * or icons, regardless of their actual presence.
5740  *
5741  * Since: 2.18
5742  */
5743 void
5744 gtk_menu_set_reserve_toggle_size (GtkMenu  *menu,
5745                                   gboolean  reserve_toggle_size)
5746 {
5747   GtkMenuPrivate *priv = menu->priv;
5748   gboolean no_toggle_size;
5749
5750   g_return_if_fail (GTK_IS_MENU (menu));
5751
5752   no_toggle_size = !reserve_toggle_size;
5753
5754   if (priv->no_toggle_size != no_toggle_size)
5755     {
5756       priv->no_toggle_size = no_toggle_size;
5757
5758       g_object_notify (G_OBJECT (menu), "reserve-toggle-size");
5759     }
5760 }
5761
5762 /**
5763  * gtk_menu_get_reserve_toggle_size:
5764  * @menu: a #GtkMenu
5765  *
5766  * Returns whether the menu reserves space for toggles and
5767  * icons, regardless of their actual presence.
5768  *
5769  * Returns: Whether the menu reserves toggle space
5770  *
5771  * Since: 2.18
5772  */
5773 gboolean
5774 gtk_menu_get_reserve_toggle_size (GtkMenu *menu)
5775 {
5776   g_return_val_if_fail (GTK_IS_MENU (menu), FALSE);
5777
5778   return !menu->priv->no_toggle_size;
5779 }