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