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