summaryrefslogtreecommitdiff
path: root/chromium/ui/views/controls/menu/menu_controller.cc
blob: 960130da9ad4e5c7b0c956ccb224ae8948c033ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/controls/menu/menu_controller.h"

#if defined(OS_WIN)
#include <windowsx.h>
#endif

#include "base/i18n/case_conversion.h"
#include "base/i18n/rtl.h"
#include "base/run_loop.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "ui/base/dragdrop/drag_utils.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/events/event_constants.h"
#include "ui/base/events/event_utils.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/screen.h"
#include "ui/native_theme/native_theme.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/menu/menu_config.h"
#include "ui/views/controls/menu/menu_controller_delegate.h"
#include "ui/views/controls/menu/menu_scroll_view_container.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/drag_utils.h"
#include "ui/views/view_constants.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"

#if defined(USE_AURA)
#include "ui/aura/env.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window.h"
#endif

#if defined(OS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif

#if defined(USE_X11)
#include <X11/Xlib.h>
#endif

using base::Time;
using base::TimeDelta;
using ui::OSExchangeData;

// Period of the scroll timer (in milliseconds).
static const int kScrollTimerMS = 30;

// Amount of time from when the drop exits the menu and the menu is hidden.
static const int kCloseOnExitTime = 1200;

// If a context menu is invoked by touch, we shift the menu by this offset so
// that the finger does not obscure the menu.
static const int kCenteredContextMenuYOffset = -15;

namespace views {

namespace {

// When showing context menu on mouse down, the user might accidentally select
// the menu item on the subsequent mouse up. To prevent this, we add the
// following delay before the user is able to select an item.
static int context_menu_selection_hold_time_ms = 200;

// The spacing offset for the bubble tip.
const int kBubbleTipSizeLeftRight = 12;
const int kBubbleTipSizeTopBottom = 11;

// Returns true if the mnemonic of |menu| matches key.
bool MatchesMnemonic(MenuItemView* menu, char16 key) {
  return menu->GetMnemonic() == key;
}

// Returns true if |menu| doesn't have a mnemonic and first character of the its
// title is |key|.
bool TitleMatchesMnemonic(MenuItemView* menu, char16 key) {
  if (menu->GetMnemonic())
    return false;

  string16 lower_title = base::i18n::ToLower(menu->title());
  return !lower_title.empty() && lower_title[0] == key;
}

}  // namespace

// Returns the first descendant of |view| that is hot tracked.
static View* GetFirstHotTrackedView(View* view) {
  if (!view)
    return NULL;

  if (!strcmp(view->GetClassName(), CustomButton::kViewClassName)) {
    CustomButton* button = static_cast<CustomButton*>(view);
    if (button->IsHotTracked())
      return button;
  }

  for (int i = 0; i < view->child_count(); ++i) {
    View* hot_view = GetFirstHotTrackedView(view->child_at(i));
    if (hot_view)
      return hot_view;
  }
  return NULL;
}

// Recurses through the child views of |view| returning the first view starting
// at |start| that is focusable. A value of -1 for |start| indicates to start at
// the first view (if |forward| is false, iterating starts at the last view). If
// |forward| is true the children are considered first to last, otherwise last
// to first.
static View* GetFirstFocusableView(View* view, int start, bool forward) {
  if (forward) {
    for (int i = start == -1 ? 0 : start; i < view->child_count(); ++i) {
      View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
      if (deepest)
        return deepest;
    }
  } else {
    for (int i = start == -1 ? view->child_count() - 1 : start; i >= 0; --i) {
      View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward);
      if (deepest)
        return deepest;
    }
  }
  return view->IsFocusable() ? view : NULL;
}

// Returns the first child of |start| that is focusable.
static View* GetInitialFocusableView(View* start, bool forward) {
  return GetFirstFocusableView(start, -1, forward);
}

// Returns the next view after |start_at| that is focusable. Returns NULL if
// there are no focusable children of |ancestor| after |start_at|.
static View* GetNextFocusableView(View* ancestor,
                                  View* start_at,
                                  bool forward) {
  DCHECK(ancestor->Contains(start_at));
  View* parent = start_at;
  do {
    View* new_parent = parent->parent();
    int index = new_parent->GetIndexOf(parent);
    index += forward ? 1 : -1;
    if (forward || index != -1) {
      View* next = GetFirstFocusableView(new_parent, index, forward);
      if (next)
        return next;
    }
    parent = new_parent;
  } while (parent != ancestor);
  return NULL;
}

// MenuScrollTask --------------------------------------------------------------

// MenuScrollTask is used when the SubmenuView does not all fit on screen and
// the mouse is over the scroll up/down buttons. MenuScrollTask schedules
// itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls
// appropriately.

class MenuController::MenuScrollTask {
 public:
  MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) {
    pixels_per_second_ = MenuItemView::pref_menu_height() * 20;
  }

  void Update(const MenuController::MenuPart& part) {
    if (!part.is_scroll()) {
      StopScrolling();
      return;
    }
    DCHECK(part.submenu);
    SubmenuView* new_menu = part.submenu;
    bool new_is_up = (part.type == MenuController::MenuPart::SCROLL_UP);
    if (new_menu == submenu_ && is_scrolling_up_ == new_is_up)
      return;

    start_scroll_time_ = base::Time::Now();
    start_y_ = part.submenu->GetVisibleBounds().y();
    submenu_ = new_menu;
    is_scrolling_up_ = new_is_up;

    if (!scrolling_timer_.IsRunning()) {
      scrolling_timer_.Start(FROM_HERE,
                             TimeDelta::FromMilliseconds(kScrollTimerMS),
                             this, &MenuScrollTask::Run);
    }
  }

  void StopScrolling() {
    if (scrolling_timer_.IsRunning()) {
      scrolling_timer_.Stop();
      submenu_ = NULL;
    }
  }

  // The menu being scrolled. Returns null if not scrolling.
  SubmenuView* submenu() const { return submenu_; }

 private:
  void Run() {
    DCHECK(submenu_);
    gfx::Rect vis_rect = submenu_->GetVisibleBounds();
    const int delta_y = static_cast<int>(
        (base::Time::Now() - start_scroll_time_).InMilliseconds() *
        pixels_per_second_ / 1000);
    vis_rect.set_y(is_scrolling_up_ ?
        std::max(0, start_y_ - delta_y) :
        std::min(submenu_->height() - vis_rect.height(), start_y_ + delta_y));
    submenu_->ScrollRectToVisible(vis_rect);
  }

  // SubmenuView being scrolled.
  SubmenuView* submenu_;

  // Direction scrolling.
  bool is_scrolling_up_;

  // Timer to periodically scroll.
  base::RepeatingTimer<MenuScrollTask> scrolling_timer_;

  // Time we started scrolling at.
  base::Time start_scroll_time_;

  // How many pixels to scroll per second.
  int pixels_per_second_;

  // Y-coordinate of submenu_view_ when scrolling started.
  int start_y_;

  DISALLOW_COPY_AND_ASSIGN(MenuScrollTask);
};

// MenuController:SelectByCharDetails ----------------------------------------

struct MenuController::SelectByCharDetails {
  SelectByCharDetails()
      : first_match(-1),
        has_multiple(false),
        index_of_item(-1),
        next_match(-1) {
  }

  // Index of the first menu with the specified mnemonic.
  int first_match;

  // If true there are multiple menu items with the same mnemonic.
  bool has_multiple;

  // Index of the selected item; may remain -1.
  int index_of_item;

  // If there are multiple matches this is the index of the item after the
  // currently selected item whose mnemonic matches. This may remain -1 even
  // though there are matches.
  int next_match;
};

// MenuController:State ------------------------------------------------------

MenuController::State::State()
    : item(NULL),
      submenu_open(false),
      anchor(views::MenuItemView::TOPLEFT),
      context_menu(false) {}

MenuController::State::~State() {}

// MenuController ------------------------------------------------------------

// static
MenuController* MenuController::active_instance_ = NULL;

// static
MenuController* MenuController::GetActiveInstance() {
  return active_instance_;
}

MenuItemView* MenuController::Run(Widget* parent,
                                  MenuButton* button,
                                  MenuItemView* root,
                                  const gfx::Rect& bounds,
                                  MenuItemView::AnchorPosition position,
                                  bool context_menu,
                                  int* result_event_flags) {
  exit_type_ = EXIT_NONE;
  possible_drag_ = false;
  drag_in_progress_ = false;
  closing_event_time_ = base::TimeDelta();
  menu_start_time_ = base::TimeTicks::Now();

  // If we are shown on mouse press, we will eat the subsequent mouse down and
  // the parent widget will not be able to reset its state (it might have mouse
  // capture from the mouse down). So we clear its state here.
  if (parent && parent->GetRootView())
    parent->GetRootView()->SetMouseHandler(NULL);

  bool nested_menu = showing_;
  if (showing_) {
    // Only support nesting of blocking_run menus, nesting of
    // blocking/non-blocking shouldn't be needed.
    DCHECK(blocking_run_);

    // We're already showing, push the current state.
    menu_stack_.push_back(state_);

    // The context menu should be owned by the same parent.
    DCHECK_EQ(owner_, parent);
  } else {
    showing_ = true;
  }

  // Reset current state.
  pending_state_ = State();
  state_ = State();
  UpdateInitialLocation(bounds, position, context_menu);

  if (owner_)
    owner_->RemoveObserver(this);
  owner_ = parent;
  if (owner_)
    owner_->AddObserver(this);

  // Set the selection, which opens the initial menu.
  SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);

  if (!blocking_run_) {
    // Start the timer to hide the menu. This is needed as we get no
    // notification when the drag has finished.
    StartCancelAllTimer();
    return NULL;
  }

  if (button)
    menu_button_ = button;

  // Make sure Chrome doesn't attempt to shut down while the menu is showing.
  if (ViewsDelegate::views_delegate)
    ViewsDelegate::views_delegate->AddRef();

  // We need to turn on nestable tasks as in some situations (pressing alt-f for
  // one) the menus are run from a task. If we don't do this and are invoked
  // from a task none of the tasks we schedule are processed and the menu
  // appears totally broken.
  message_loop_depth_++;
  DCHECK_LE(message_loop_depth_, 2);
  RunMessageLoop(nested_menu);
  message_loop_depth_--;

  if (ViewsDelegate::views_delegate)
    ViewsDelegate::views_delegate->ReleaseRef();

  // Close any open menus.
  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);

  if (nested_menu) {
    DCHECK(!menu_stack_.empty());
    // We're running from within a menu, restore the previous state.
    // The menus are already showing, so we don't have to show them.
    state_ = menu_stack_.back();
    pending_state_ = menu_stack_.back();
    menu_stack_.pop_back();
  } else {
    showing_ = false;
    did_capture_ = false;
  }

  MenuItemView* result = result_;
  // In case we're nested, reset result_.
  result_ = NULL;

  if (result_event_flags)
    *result_event_flags = accept_event_flags_;

  if (exit_type_ == EXIT_OUTERMOST) {
    SetExitType(EXIT_NONE);
  } else {
    if (nested_menu && result) {
      // We're nested and about to return a value. The caller might enter
      // another blocking loop. We need to make sure all menus are hidden
      // before that happens otherwise the menus will stay on screen.
      CloseAllNestedMenus();
      SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);

      // Set exit_all_, which makes sure all nested loops exit immediately.
      if (exit_type_ != EXIT_DESTROYED)
        SetExitType(EXIT_ALL);
    }
  }

  // If we stopped running because one of the menus was destroyed chances are
  // the button was also destroyed.
  if (exit_type_ != EXIT_DESTROYED && menu_button_) {
    menu_button_->SetState(CustomButton::STATE_NORMAL);
    menu_button_->SchedulePaint();
  }

  return result;
}

void MenuController::Cancel(ExitType type) {
  // If the menu has already been destroyed, no further cancellation is
  // needed.  We especially don't want to set the |exit_type_| to a lesser
  // value.
  if (exit_type_ == EXIT_DESTROYED || exit_type_ == type)
    return;

  if (!showing_) {
    // This occurs if we're in the process of notifying the delegate for a drop
    // and the delegate cancels us.
    return;
  }

  MenuItemView* selected = state_.item;
  SetExitType(type);

  SendMouseCaptureLostToActiveView();

  // Hide windows immediately.
  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);

  if (!blocking_run_) {
    // If we didn't block the caller we need to notify the menu, which
    // triggers deleting us.
    DCHECK(selected);
    showing_ = false;
    delegate_->DropMenuClosed(
        internal::MenuControllerDelegate::NOTIFY_DELEGATE,
        selected->GetRootMenuItem());
    // WARNING: the call to MenuClosed deletes us.
    return;
  }
}

void MenuController::OnMousePressed(SubmenuView* source,
                                    const ui::MouseEvent& event) {
  SetSelectionOnPointerDown(source, event);
}

void MenuController::OnMouseDragged(SubmenuView* source,
                                    const ui::MouseEvent& event) {
  MenuPart part = GetMenuPart(source, event.location());
  UpdateScrolling(part);

  if (!blocking_run_)
    return;

  if (possible_drag_) {
    if (View::ExceededDragThreshold(event.location() - press_pt_))
      StartDrag(source, press_pt_);
    return;
  }
  MenuItemView* mouse_menu = NULL;
  if (part.type == MenuPart::MENU_ITEM) {
    if (!part.menu)
      part.menu = source->GetMenuItem();
    else
      mouse_menu = part.menu;
    SetSelection(part.menu ? part.menu : state_.item, SELECTION_OPEN_SUBMENU);
  } else if (part.type == MenuPart::NONE) {
    ShowSiblingMenu(source, event.location());
  }
  UpdateActiveMouseView(source, event, mouse_menu);
}

void MenuController::OnMouseReleased(SubmenuView* source,
                                     const ui::MouseEvent& event) {
  if (!blocking_run_)
    return;

  DCHECK(state_.item);
  possible_drag_ = false;
  DCHECK(blocking_run_);
  MenuPart part = GetMenuPart(source, event.location());
  if (event.IsRightMouseButton() && part.type == MenuPart::MENU_ITEM) {
    MenuItemView* menu = part.menu;
    // |menu| is NULL means this event is from an empty menu or a separator.
    // If it is from an empty menu, use parent context menu instead of that.
    if (menu == NULL &&
        part.submenu->child_count() == 1 &&
        part.submenu->child_at(0)->id()
           == views::MenuItemView::kEmptyMenuItemViewID)
      menu = part.parent;

    if (menu != NULL && ShowContextMenu(menu, source, event,
                                        ui::MENU_SOURCE_MOUSE))
      return;
  }

  // We can use Ctrl+click or the middle mouse button to recursively open urls
  // for selected folder menu items. If it's only a left click, show the
  // contents of the folder.
  if (!part.is_scroll() && part.menu &&
      !(part.menu->HasSubmenu() &&
        (event.flags() & ui::EF_LEFT_MOUSE_BUTTON))) {
    if (active_mouse_view_) {
      SendMouseReleaseToActiveView(source, event);
      return;
    }
    if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu(
            part.menu->GetCommand(), event)) {
      part.menu->GetDelegate()->ExecuteCommand(part.menu->GetCommand(),
                                               event.flags());
      return;
    }
    if (!part.menu->NonIconChildViewsCount() &&
        part.menu->GetDelegate()->IsTriggerableEvent(part.menu, event)) {
      int64 time_since_menu_start =
          (base::TimeTicks::Now() - menu_start_time_).InMilliseconds();
      if (!state_.context_menu || !View::ShouldShowContextMenuOnMousePress() ||
          time_since_menu_start > context_menu_selection_hold_time_ms)
        Accept(part.menu, event.flags());
      return;
    }
  } else if (part.type == MenuPart::MENU_ITEM) {
    // User either clicked on empty space, or a menu that has children.
    SetSelection(part.menu ? part.menu : state_.item,
                 SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
  }
  SendMouseCaptureLostToActiveView();
}

void MenuController::OnMouseMoved(SubmenuView* source,
                                  const ui::MouseEvent& event) {
  HandleMouseLocation(source, event.location());
}

void MenuController::OnMouseEntered(SubmenuView* source,
                                    const ui::MouseEvent& event) {
  // MouseEntered is always followed by a mouse moved, so don't need to
  // do anything here.
}

#if defined(OS_LINUX)
bool MenuController::OnMouseWheel(SubmenuView* source,
                                  const ui::MouseWheelEvent& event) {
  MenuPart part = GetMenuPart(source, event.location());
  return part.submenu && part.submenu->OnMouseWheel(event);
}
#endif

void MenuController::OnGestureEvent(SubmenuView* source,
                                    ui::GestureEvent* event) {
  MenuPart part = GetMenuPart(source, event->location());
  if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
    SetSelectionOnPointerDown(source, *event);
    event->StopPropagation();
  } else if (event->type() == ui::ET_GESTURE_LONG_PRESS) {
    if (part.type == MenuPart::MENU_ITEM && part.menu) {
      if (ShowContextMenu(part.menu, source, *event, ui::MENU_SOURCE_TOUCH))
        event->StopPropagation();
    }
  } else if (event->type() == ui::ET_GESTURE_TAP) {
    if (!part.is_scroll() && part.menu &&
        !(part.menu->HasSubmenu())) {
      if (part.menu->GetDelegate()->IsTriggerableEvent(
          part.menu, *event)) {
        Accept(part.menu, event->flags());
      }
      event->StopPropagation();
    } else if (part.type == MenuPart::MENU_ITEM) {
      // User either tapped on empty space, or a menu that has children.
      SetSelection(part.menu ? part.menu : state_.item,
                   SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
      event->StopPropagation();
    }
  } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL &&
             part.menu &&
             part.type == MenuPart::MENU_ITEM) {
    // Move the selection to the parent menu so that the selection in the
    // current menu is unset. Make sure the submenu remains open by sending the
    // appropriate SetSelectionTypes flags.
    SetSelection(part.menu->GetParentMenuItem(),
        SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
    event->StopPropagation();
  }

  if (event->stopped_propagation())
      return;

  if (!part.submenu)
    return;
  part.submenu->OnGestureEvent(event);
}

bool MenuController::GetDropFormats(
      SubmenuView* source,
      int* formats,
      std::set<OSExchangeData::CustomFormat>* custom_formats) {
  return source->GetMenuItem()->GetDelegate()->GetDropFormats(
      source->GetMenuItem(), formats, custom_formats);
}

bool MenuController::AreDropTypesRequired(SubmenuView* source) {
  return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired(
      source->GetMenuItem());
}

bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) {
  return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(),
                                                       data);
}

void MenuController::OnDragEntered(SubmenuView* source,
                                   const ui::DropTargetEvent& event) {
  valid_drop_coordinates_ = false;
}

int MenuController::OnDragUpdated(SubmenuView* source,
                                  const ui::DropTargetEvent& event) {
  StopCancelAllTimer();

  gfx::Point screen_loc(event.location());
  View::ConvertPointToScreen(source, &screen_loc);
  if (valid_drop_coordinates_ && screen_loc == drop_pt_)
    return last_drop_operation_;
  drop_pt_ = screen_loc;
  valid_drop_coordinates_ = true;

  MenuItemView* menu_item = GetMenuItemAt(source, event.x(), event.y());
  bool over_empty_menu = false;
  if (!menu_item) {
    // See if we're over an empty menu.
    menu_item = GetEmptyMenuItemAt(source, event.x(), event.y());
    if (menu_item)
      over_empty_menu = true;
  }
  MenuDelegate::DropPosition drop_position = MenuDelegate::DROP_NONE;
  int drop_operation = ui::DragDropTypes::DRAG_NONE;
  if (menu_item) {
    gfx::Point menu_item_loc(event.location());
    View::ConvertPointToTarget(source, menu_item, &menu_item_loc);
    MenuItemView* query_menu_item;
    if (!over_empty_menu) {
      int menu_item_height = menu_item->height();
      if (menu_item->HasSubmenu() &&
          (menu_item_loc.y() > kDropBetweenPixels &&
           menu_item_loc.y() < (menu_item_height - kDropBetweenPixels))) {
        drop_position = MenuDelegate::DROP_ON;
      } else {
        drop_position = (menu_item_loc.y() < menu_item_height / 2) ?
            MenuDelegate::DROP_BEFORE : MenuDelegate::DROP_AFTER;
      }
      query_menu_item = menu_item;
    } else {
      query_menu_item = menu_item->GetParentMenuItem();
      drop_position = MenuDelegate::DROP_ON;
    }
    drop_operation = menu_item->GetDelegate()->GetDropOperation(
        query_menu_item, event, &drop_position);

    // If the menu has a submenu, schedule the submenu to open.
    SetSelection(menu_item, menu_item->HasSubmenu() ? SELECTION_OPEN_SUBMENU :
                 SELECTION_DEFAULT);

    if (drop_position == MenuDelegate::DROP_NONE ||
        drop_operation == ui::DragDropTypes::DRAG_NONE)
      menu_item = NULL;
  } else {
    SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU);
  }
  SetDropMenuItem(menu_item, drop_position);
  last_drop_operation_ = drop_operation;
  return drop_operation;
}

void MenuController::OnDragExited(SubmenuView* source) {
  StartCancelAllTimer();

  if (drop_target_) {
    StopShowTimer();
    SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
  }
}

int MenuController::OnPerformDrop(SubmenuView* source,
                                  const ui::DropTargetEvent& event) {
  DCHECK(drop_target_);
  // NOTE: the delegate may delete us after invoking OnPerformDrop, as such
  // we don't call cancel here.

  MenuItemView* item = state_.item;
  DCHECK(item);

  MenuItemView* drop_target = drop_target_;
  MenuDelegate::DropPosition drop_position = drop_position_;

  // Close all menus, including any nested menus.
  SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT);
  CloseAllNestedMenus();

  // Set state such that we exit.
  showing_ = false;
  SetExitType(EXIT_ALL);

  // If over an empty menu item, drop occurs on the parent.
  if (drop_target->id() == MenuItemView::kEmptyMenuItemViewID)
    drop_target = drop_target->GetParentMenuItem();

  if (!IsBlockingRun()) {
    delegate_->DropMenuClosed(
        internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE,
        item->GetRootMenuItem());
  }

  // WARNING: the call to MenuClosed deletes us.

  return drop_target->GetDelegate()->OnPerformDrop(
      drop_target, drop_position, event);
}

void MenuController::OnDragEnteredScrollButton(SubmenuView* source,
                                               bool is_up) {
  MenuPart part;
  part.type = is_up ? MenuPart::SCROLL_UP : MenuPart::SCROLL_DOWN;
  part.submenu = source;
  UpdateScrolling(part);

  // Do this to force the selection to hide.
  SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DROP_NONE);

  StopCancelAllTimer();
}

void MenuController::OnDragExitedScrollButton(SubmenuView* source) {
  StartCancelAllTimer();
  SetDropMenuItem(NULL, MenuDelegate::DROP_NONE);
  StopScrolling();
}

void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) {
  if (submenu->IsShowing()) {
    gfx::Point point = GetScreen()->GetCursorScreenPoint();
    const SubmenuView* root_submenu =
        submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu();
    views::View::ConvertPointFromScreen(
        root_submenu->GetWidget()->GetRootView(), &point);
    HandleMouseLocation(submenu, point);
  }
}

void MenuController::OnWidgetDestroying(Widget* widget) {
  DCHECK_EQ(owner_, widget);
  owner_->RemoveObserver(this);
  owner_ = NULL;
}

// static
void MenuController::TurnOffContextMenuSelectionHoldForTest() {
  context_menu_selection_hold_time_ms = -1;
}

void MenuController::SetSelection(MenuItemView* menu_item,
                                  int selection_types) {
  size_t paths_differ_at = 0;
  std::vector<MenuItemView*> current_path;
  std::vector<MenuItemView*> new_path;
  BuildPathsAndCalculateDiff(pending_state_.item, menu_item, &current_path,
                             &new_path, &paths_differ_at);

  size_t current_size = current_path.size();
  size_t new_size = new_path.size();

  bool pending_item_changed = pending_state_.item != menu_item;
  if (pending_item_changed && pending_state_.item) {
    View* current_hot_view = GetFirstHotTrackedView(pending_state_.item);
    if (current_hot_view && !strcmp(current_hot_view->GetClassName(),
                                    CustomButton::kViewClassName)) {
      CustomButton* button = static_cast<CustomButton*>(current_hot_view);
      button->SetHotTracked(false);
    }
  }

  // Notify the old path it isn't selected.
  MenuDelegate* current_delegate =
      current_path.empty() ? NULL : current_path.front()->GetDelegate();
  for (size_t i = paths_differ_at; i < current_size; ++i) {
    if (current_delegate &&
        current_path[i]->GetType() == MenuItemView::SUBMENU) {
      current_delegate->WillHideMenu(current_path[i]);
    }
    current_path[i]->SetSelected(false);
  }

  // Notify the new path it is selected.
  for (size_t i = paths_differ_at; i < new_size; ++i) {
    new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds());
    new_path[i]->SetSelected(true);
  }

  if (menu_item && menu_item->GetDelegate())
    menu_item->GetDelegate()->SelectionChanged(menu_item);

  DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0);

  pending_state_.item = menu_item;
  pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0;

  // Stop timers.
  StopCancelAllTimer();
  // Resets show timer only when pending menu item is changed.
  if (pending_item_changed)
    StopShowTimer();

  if (selection_types & SELECTION_UPDATE_IMMEDIATELY)
    CommitPendingSelection();
  else if (pending_item_changed)
    StartShowTimer();

  // Notify an accessibility focus event on all menu items except for the root.
  if (menu_item &&
      (MenuDepth(menu_item) != 1 ||
       menu_item->GetType() != MenuItemView::SUBMENU)) {
    menu_item->NotifyAccessibilityEvent(
        ui::AccessibilityTypes::EVENT_FOCUS, true);
  }
}

void MenuController::SetSelectionOnPointerDown(SubmenuView* source,
                                               const ui::LocatedEvent& event) {
  if (!blocking_run_)
    return;

  DCHECK(!active_mouse_view_);

  MenuPart part = GetMenuPart(source, event.location());
  if (part.is_scroll())
    return;  // Ignore presses on scroll buttons.

  // When this menu is opened through a touch event, a simulated right-click
  // is sent before the menu appears.  Ignore it.
  if ((event.flags() & ui::EF_RIGHT_MOUSE_BUTTON) &&
      (event.flags() & ui::EF_FROM_TOUCH))
    return;

  if (part.type == MenuPart::NONE ||
      (part.type == MenuPart::MENU_ITEM && part.menu &&
       part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) {
    // Remember the time when we repost the event. The owner can then use this
    // to figure out if this menu was finished with the same click which is
    // sent to it thereafter. Note that the time stamp front he event cannot be
    // used since the reposting will set a new timestamp when the event gets
    // processed. As such it is better to take the current time which will be
    // closer to the time when it arrives again in the menu handler.
    closing_event_time_ = ui::EventTimeForNow();

    // Mouse wasn't pressed over any menu, or the active menu, cancel.

#if defined(OS_WIN)
    // We're going to close and we own the mouse capture. We need to repost the
    // mouse down, otherwise the window the user clicked on won't get the
    // event.
    RepostEvent(source, event);
#endif

    // And close.
    ExitType exit_type = EXIT_ALL;
    if (!menu_stack_.empty()) {
      // We're running nested menus. Only exit all if the mouse wasn't over one
      // of the menus from the last run.
      gfx::Point screen_loc(event.location());
      View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
      MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu(
          menu_stack_.back().item, screen_loc);
      if (last_part.type != MenuPart::NONE)
        exit_type = EXIT_OUTERMOST;
    }
    Cancel(exit_type);

#if defined(USE_AURA) && !defined(OS_WIN)
    // We're going to exit the menu and want to repost the event so that is
    // is handled normally after the context menu has exited. We call
    // RepostEvent after Cancel so that mouse capture has been released so
    // that finding the event target is unaffected by the current capture.
    RepostEvent(source, event);
#endif

    return;
  }

  // On a press we immediately commit the selection, that way a submenu
  // pops up immediately rather than after a delay.
  int selection_types = SELECTION_UPDATE_IMMEDIATELY;
  if (!part.menu) {
    part.menu = part.parent;
    selection_types |= SELECTION_OPEN_SUBMENU;
  } else {
    if (part.menu->GetDelegate()->CanDrag(part.menu)) {
      possible_drag_ = true;
      press_pt_ = event.location();
    }
    if (part.menu->HasSubmenu())
      selection_types |= SELECTION_OPEN_SUBMENU;
  }
  SetSelection(part.menu, selection_types);
}

void MenuController::StartDrag(SubmenuView* source,
                               const gfx::Point& location) {
  MenuItemView* item = state_.item;
  DCHECK(item);
  // Points are in the coordinates of the submenu, need to map to that of
  // the selected item. Additionally source may not be the parent of
  // the selected item, so need to map to screen first then to item.
  gfx::Point press_loc(location);
  View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc);
  View::ConvertPointToTarget(NULL, item, &press_loc);
  gfx::Point widget_loc(press_loc);
  View::ConvertPointToWidget(item, &widget_loc);
  scoped_ptr<gfx::Canvas> canvas(views::GetCanvasForDragImage(
      source->GetWidget(), gfx::Size(item->width(), item->height())));
  item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG);

  OSExchangeData data;
  item->GetDelegate()->WriteDragData(item, &data);
  drag_utils::SetDragImageOnDataObject(*canvas, item->size(),
                                       press_loc.OffsetFromOrigin(),
                                       &data);
  StopScrolling();
  int drag_ops = item->GetDelegate()->GetDragOperations(item);
  drag_in_progress_ = true;
  // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below.
  item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops,
      ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE);
  drag_in_progress_ = false;

  if (GetActiveInstance() == this) {
    if (showing_) {
      // We're still showing, close all menus.
      CloseAllNestedMenus();
      Cancel(EXIT_ALL);
    }  // else case, drop was on us.
  }  // else case, someone canceled us, don't do anything
}

#if defined(OS_WIN)
bool MenuController::Dispatch(const MSG& msg) {
  DCHECK(blocking_run_);

  if (exit_type_ == EXIT_ALL || exit_type_ == EXIT_DESTROYED) {
    // We must translate/dispatch the message here, otherwise we would drop
    // the message on the floor.
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    return false;
  }

  // NOTE: we don't get WM_ACTIVATE or anything else interesting in here.
  switch (msg.message) {
    case WM_CONTEXTMENU: {
      MenuItemView* item = pending_state_.item;
      if (item && item->GetRootMenuItem() != item) {
        gfx::Point screen_loc(0, item->height());
        View::ConvertPointToScreen(item, &screen_loc);
        ui::MenuSourceType source_type = ui::MENU_SOURCE_MOUSE;
        if (GET_X_LPARAM(msg.lParam) == -1 && GET_Y_LPARAM(msg.lParam) == -1)
          source_type = ui::MENU_SOURCE_KEYBOARD;
        item->GetDelegate()->ShowContextMenu(item, item->GetCommand(),
                                             screen_loc, source_type);
      }
      return true;
    }

    // NOTE: focus wasn't changed when the menu was shown. As such, don't
    // dispatch key events otherwise the focused window will get the events.
    case WM_KEYDOWN: {
      bool result = OnKeyDown(ui::KeyboardCodeFromNative(msg));
      TranslateMessage(&msg);
      return result;
    }
    case WM_CHAR:
      return !SelectByChar(static_cast<char16>(msg.wParam));
    case WM_KEYUP:
      return true;

    case WM_SYSKEYUP:
      // We may have been shown on a system key, as such don't do anything
      // here. If another system key is pushed we'll get a WM_SYSKEYDOWN and
      // close the menu.
      return true;

    case WM_CANCELMODE:
    case WM_SYSKEYDOWN:
      // Exit immediately on system keys.
      Cancel(EXIT_ALL);
      return false;

    default:
      break;
  }
  TranslateMessage(&msg);
  DispatchMessage(&msg);
  return exit_type_ == EXIT_NONE;
}
#elif defined(USE_AURA)
bool MenuController::Dispatch(const base::NativeEvent& event) {
  if (exit_type_ == EXIT_ALL || exit_type_ == EXIT_DESTROYED) {
    aura::Env::GetInstance()->GetDispatcher()->Dispatch(event);
    return false;
  }
  // Activates mnemonics only when it it pressed without modifiers except for
  // caps and shift.
  int flags = ui::EventFlagsFromNative(event) &
      ~ui::EF_CAPS_LOCK_DOWN & ~ui::EF_SHIFT_DOWN;
  if (flags == ui::EF_NONE) {
    switch (ui::EventTypeFromNative(event)) {
      case ui::ET_KEY_PRESSED:
        if (!OnKeyDown(ui::KeyboardCodeFromNative(event)))
          return false;

        return !SelectByChar(ui::KeyboardCodeFromNative(event));
      case ui::ET_KEY_RELEASED:
        return true;
      default:
        break;
    }
  }

  aura::Env::GetInstance()->GetDispatcher()->Dispatch(event);
  return exit_type_ == EXIT_NONE;
}
#endif

bool MenuController::OnKeyDown(ui::KeyboardCode key_code) {
  DCHECK(blocking_run_);

  switch (key_code) {
    case ui::VKEY_UP:
      IncrementSelection(-1);
      break;

    case ui::VKEY_DOWN:
      IncrementSelection(1);
      break;

    // Handling of VK_RIGHT and VK_LEFT is different depending on the UI
    // layout.
    case ui::VKEY_RIGHT:
      if (base::i18n::IsRTL())
        CloseSubmenu();
      else
        OpenSubmenuChangeSelectionIfCan();
      break;

    case ui::VKEY_LEFT:
      if (base::i18n::IsRTL())
        OpenSubmenuChangeSelectionIfCan();
      else
        CloseSubmenu();
      break;

    case ui::VKEY_SPACE:
      if (SendAcceleratorToHotTrackedView() == ACCELERATOR_PROCESSED_EXIT)
        return false;
      break;

    case ui::VKEY_RETURN:
      if (pending_state_.item) {
        if (pending_state_.item->HasSubmenu()) {
          OpenSubmenuChangeSelectionIfCan();
        } else {
          SendAcceleratorResultType result = SendAcceleratorToHotTrackedView();
          if (result == ACCELERATOR_NOT_PROCESSED &&
              pending_state_.item->enabled()) {
            Accept(pending_state_.item, 0);
            return false;
          } else if (result == ACCELERATOR_PROCESSED_EXIT) {
            return false;
          }
        }
      }
      break;

    case ui::VKEY_ESCAPE:
      if (!state_.item->GetParentMenuItem() ||
          (!state_.item->GetParentMenuItem()->GetParentMenuItem() &&
           (!state_.item->HasSubmenu() ||
            !state_.item->GetSubmenu()->IsShowing()))) {
        // User pressed escape and only one menu is shown, cancel it.
        Cancel(EXIT_OUTERMOST);
        return false;
      }
      CloseSubmenu();
      break;

#if defined(OS_WIN)
    case VK_APPS:
      break;
#endif

    default:
      break;
  }
  return true;
}

MenuController::MenuController(ui::NativeTheme* theme,
                               bool blocking,
                               internal::MenuControllerDelegate* delegate)
    : blocking_run_(blocking),
      showing_(false),
      exit_type_(EXIT_NONE),
      did_capture_(false),
      result_(NULL),
      accept_event_flags_(0),
      drop_target_(NULL),
      drop_position_(MenuDelegate::DROP_UNKNOWN),
      owner_(NULL),
      possible_drag_(false),
      drag_in_progress_(false),
      valid_drop_coordinates_(false),
      last_drop_operation_(MenuDelegate::DROP_UNKNOWN),
      showing_submenu_(false),
      menu_button_(NULL),
      active_mouse_view_(NULL),
      delegate_(delegate),
      message_loop_depth_(0),
      menu_config_(theme),
      closing_event_time_(base::TimeDelta()),
      menu_start_time_(base::TimeTicks()) {
  active_instance_ = this;
}

MenuController::~MenuController() {
  DCHECK(!showing_);
  if (owner_)
    owner_->RemoveObserver(this);
  if (active_instance_ == this)
    active_instance_ = NULL;
  StopShowTimer();
  StopCancelAllTimer();
}

MenuController::SendAcceleratorResultType
    MenuController::SendAcceleratorToHotTrackedView() {
  View* hot_view = GetFirstHotTrackedView(pending_state_.item);
  if (!hot_view)
    return ACCELERATOR_NOT_PROCESSED;

  ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE);
  hot_view->AcceleratorPressed(accelerator);
  if (!strcmp(hot_view->GetClassName(), CustomButton::kViewClassName)) {
    CustomButton* button = static_cast<CustomButton*>(hot_view);
    button->SetHotTracked(true);
  }
  return (exit_type_ == EXIT_NONE) ?
      ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT;
}

void MenuController::UpdateInitialLocation(
    const gfx::Rect& bounds,
    MenuItemView::AnchorPosition position,
    bool context_menu) {
  pending_state_.context_menu = context_menu;
  pending_state_.initial_bounds = bounds;
  if (bounds.height() > 1) {
    // Inset the bounds slightly, otherwise drag coordinates don't line up
    // nicely and menus close prematurely.
    pending_state_.initial_bounds.Inset(0, 1);
  }

  // Reverse anchor position for RTL languages.
  if (base::i18n::IsRTL() &&
      (position == MenuItemView::TOPRIGHT ||
       position == MenuItemView::TOPLEFT)) {
    pending_state_.anchor = position == MenuItemView::TOPRIGHT ?
        MenuItemView::TOPLEFT : MenuItemView::TOPRIGHT;
  } else {
    pending_state_.anchor = position;
  }

  // Calculate the bounds of the monitor we'll show menus on. Do this once to
  // avoid repeated system queries for the info.
  pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint(
      bounds.origin()).work_area();
#if defined(USE_ASH)
  if (!pending_state_.monitor_bounds.Contains(bounds)) {
    // Use the monitor area if the work area doesn't contain the bounds. This
    // handles showing a menu from the launcher.
    gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint(
        bounds.origin()).bounds();
    if (monitor_area.Contains(bounds))
      pending_state_.monitor_bounds = monitor_area;
  }
#endif
}

void MenuController::Accept(MenuItemView* item, int event_flags) {
  DCHECK(IsBlockingRun());
  result_ = item;
  if (item && !menu_stack_.empty() &&
      !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) {
    SetExitType(EXIT_OUTERMOST);
  } else {
    SetExitType(EXIT_ALL);
  }
  accept_event_flags_ = event_flags;
}

bool MenuController::ShowSiblingMenu(SubmenuView* source,
                                     const gfx::Point& mouse_location) {
  if (!menu_stack_.empty() || !menu_button_)
    return false;

  View* source_view = source->GetScrollViewContainer();
  if (mouse_location.x() >= 0 &&
      mouse_location.x() < source_view->width() &&
      mouse_location.y() >= 0 &&
      mouse_location.y() < source_view->height()) {
    // The mouse is over the menu, no need to continue.
    return false;
  }

  gfx::NativeWindow window_under_mouse =
      GetScreen()->GetWindowAtCursorScreenPoint();
  // TODO(oshima): Replace with views only API.
  if (!owner_ || window_under_mouse != owner_->GetNativeWindow())
    return false;

  // The user moved the mouse outside the menu and over the owning window. See
  // if there is a sibling menu we should show.
  gfx::Point screen_point(mouse_location);
  View::ConvertPointToScreen(source_view, &screen_point);
  MenuItemView::AnchorPosition anchor;
  bool has_mnemonics;
  MenuButton* button = NULL;
  MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()->
      GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(),
                     screen_point, &anchor, &has_mnemonics, &button);
  if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu))
    return false;

  delegate_->SiblingMenuCreated(alt_menu);

  if (!button) {
    // If the delegate returns a menu, they must also return a button.
    NOTREACHED();
    return false;
  }

  // There is a sibling menu, update the button state, hide the current menu
  // and show the new one.
  menu_button_->SetState(CustomButton::STATE_NORMAL);
  menu_button_->SchedulePaint();
  menu_button_ = button;
  menu_button_->SetState(CustomButton::STATE_PRESSED);
  menu_button_->SchedulePaint();

  // Need to reset capture when we show the menu again, otherwise we aren't
  // going to get any events.
  did_capture_ = false;
  gfx::Point screen_menu_loc;
  View::ConvertPointToScreen(button, &screen_menu_loc);

  // It is currently not possible to show a submenu recursively in a bubble.
  DCHECK(!MenuItemView::IsBubble(anchor));
  // Subtract 1 from the height to make the popup flush with the button border.
  UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(),
                                  button->width(), button->height() - 1),
                        anchor, state_.context_menu);
  alt_menu->PrepareForRun(
      false, has_mnemonics,
      source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_);
  alt_menu->controller_ = this;
  SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
  return true;
}

bool MenuController::ShowContextMenu(MenuItemView* menu_item,
                                     SubmenuView* source,
                                     const ui::LocatedEvent& event,
                                     ui::MenuSourceType source_type) {
  // Set the selection immediately, making sure the submenu is only open
  // if it already was.
  int selection_types = SELECTION_UPDATE_IMMEDIATELY;
  if (state_.item == pending_state_.item && state_.submenu_open)
    selection_types |= SELECTION_OPEN_SUBMENU;
  SetSelection(pending_state_.item, selection_types);
  gfx::Point loc(event.location());
  View::ConvertPointToScreen(source->GetScrollViewContainer(), &loc);

  if (menu_item->GetDelegate()->ShowContextMenu(
          menu_item, menu_item->GetCommand(), loc, source_type)) {
    SendMouseCaptureLostToActiveView();
    return true;
  }
  return false;
}

void MenuController::CloseAllNestedMenus() {
  for (std::list<State>::iterator i = menu_stack_.begin();
       i != menu_stack_.end(); ++i) {
    MenuItemView* last_item = i->item;
    for (MenuItemView* item = last_item; item;
         item = item->GetParentMenuItem()) {
      CloseMenu(item);
      last_item = item;
    }
    i->submenu_open = false;
    i->item = last_item;
  }
}

MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) {
  // Walk the view hierarchy until we find a menu item (or the root).
  View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
  while (child_under_mouse &&
         child_under_mouse->id() != MenuItemView::kMenuItemViewID) {
    child_under_mouse = child_under_mouse->parent();
  }
  if (child_under_mouse && child_under_mouse->enabled() &&
      child_under_mouse->id() == MenuItemView::kMenuItemViewID) {
    return static_cast<MenuItemView*>(child_under_mouse);
  }
  return NULL;
}

MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) {
  View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y));
  if (child_under_mouse &&
      child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) {
    return static_cast<MenuItemView*>(child_under_mouse);
  }
  return NULL;
}

bool MenuController::IsScrollButtonAt(SubmenuView* source,
                                      int x,
                                      int y,
                                      MenuPart::Type* part) {
  MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer();
  View* child_under_mouse =
      scroll_view->GetEventHandlerForPoint(gfx::Point(x, y));
  if (child_under_mouse && child_under_mouse->enabled()) {
    if (child_under_mouse == scroll_view->scroll_up_button()) {
      *part = MenuPart::SCROLL_UP;
      return true;
    }
    if (child_under_mouse == scroll_view->scroll_down_button()) {
      *part = MenuPart::SCROLL_DOWN;
      return true;
    }
  }
  return false;
}

MenuController::MenuPart MenuController::GetMenuPart(
    SubmenuView* source,
    const gfx::Point& source_loc) {
  gfx::Point screen_loc(source_loc);
  View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
  return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc);
}

MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu(
    MenuItemView* item,
    const gfx::Point& screen_loc) {
  MenuPart part;
  for (; item; item = item->GetParentMenuItem()) {
    if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
        GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc,
                                          &part)) {
      return part;
    }
  }
  return part;
}

bool MenuController::GetMenuPartByScreenCoordinateImpl(
    SubmenuView* menu,
    const gfx::Point& screen_loc,
    MenuPart* part) {
  // Is the mouse over the scroll buttons?
  gfx::Point scroll_view_loc = screen_loc;
  View* scroll_view_container = menu->GetScrollViewContainer();
  View::ConvertPointToTarget(NULL, scroll_view_container, &scroll_view_loc);
  if (scroll_view_loc.x() < 0 ||
      scroll_view_loc.x() >= scroll_view_container->width() ||
      scroll_view_loc.y() < 0 ||
      scroll_view_loc.y() >= scroll_view_container->height()) {
    // Point isn't contained in menu.
    return false;
  }
  if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(),
                       &(part->type))) {
    part->submenu = menu;
    return true;
  }

  // Not over the scroll button. Check the actual menu.
  if (DoesSubmenuContainLocation(menu, screen_loc)) {
    gfx::Point menu_loc = screen_loc;
    View::ConvertPointToTarget(NULL, menu, &menu_loc);
    part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y());
    part->type = MenuPart::MENU_ITEM;
    part->submenu = menu;
    if (!part->menu)
      part->parent = menu->GetMenuItem();
    return true;
  }

  // While the mouse isn't over a menu item or the scroll buttons of menu, it
  // is contained by menu and so we return true. If we didn't return true other
  // menus would be searched, even though they are likely obscured by us.
  return true;
}

bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu,
                                                const gfx::Point& screen_loc) {
  gfx::Point view_loc = screen_loc;
  View::ConvertPointToTarget(NULL, submenu, &view_loc);
  gfx::Rect vis_rect = submenu->GetVisibleBounds();
  return vis_rect.Contains(view_loc.x(), view_loc.y());
}

void MenuController::CommitPendingSelection() {
  StopShowTimer();

  size_t paths_differ_at = 0;
  std::vector<MenuItemView*> current_path;
  std::vector<MenuItemView*> new_path;
  BuildPathsAndCalculateDiff(state_.item, pending_state_.item, &current_path,
                             &new_path, &paths_differ_at);

  // Hide the old menu.
  for (size_t i = paths_differ_at; i < current_path.size(); ++i) {
    if (current_path[i]->HasSubmenu()) {
      current_path[i]->GetSubmenu()->Hide();
    }
  }

  // Copy pending to state_, making sure to preserve the direction menus were
  // opened.
  std::list<bool> pending_open_direction;
  state_.open_leading.swap(pending_open_direction);
  state_ = pending_state_;
  state_.open_leading.swap(pending_open_direction);

  int menu_depth = MenuDepth(state_.item);
  if (menu_depth == 0) {
    state_.open_leading.clear();
  } else {
    int cached_size = static_cast<int>(state_.open_leading.size());
    DCHECK_GE(menu_depth, 0);
    while (cached_size-- >= menu_depth)
      state_.open_leading.pop_back();
  }

  if (!state_.item) {
    // Nothing to select.
    StopScrolling();
    return;
  }

  // Open all the submenus preceeding the last menu item (last menu item is
  // handled next).
  if (new_path.size() > 1) {
    for (std::vector<MenuItemView*>::iterator i = new_path.begin();
         i != new_path.end() - 1; ++i) {
      OpenMenu(*i);
    }
  }

  if (state_.submenu_open) {
    // The submenu should be open, open the submenu if the item has a submenu.
    if (state_.item->HasSubmenu()) {
      OpenMenu(state_.item);
    } else {
      state_.submenu_open = false;
    }
  } else if (state_.item->HasSubmenu() &&
             state_.item->GetSubmenu()->IsShowing()) {
    state_.item->GetSubmenu()->Hide();
  }

  if (scroll_task_.get() && scroll_task_->submenu()) {
    // Stop the scrolling if none of the elements of the selection contain
    // the menu being scrolled.
    bool found = false;
    for (MenuItemView* item = state_.item; item && !found;
         item = item->GetParentMenuItem()) {
      found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() &&
               item->GetSubmenu() == scroll_task_->submenu());
    }
    if (!found)
      StopScrolling();
  }
}

void MenuController::CloseMenu(MenuItemView* item) {
  DCHECK(item);
  if (!item->HasSubmenu())
    return;
  item->GetSubmenu()->Hide();
}

void MenuController::OpenMenu(MenuItemView* item) {
  DCHECK(item);
  if (item->GetSubmenu()->IsShowing()) {
    return;
  }

  OpenMenuImpl(item, true);
  did_capture_ = true;
}

void MenuController::OpenMenuImpl(MenuItemView* item, bool show) {
  // TODO(oshima|sky): Don't show the menu if drag is in progress and
  // this menu doesn't support drag drop. See crbug.com/110495.
  if (show) {
    int old_count = item->GetSubmenu()->child_count();
    item->GetDelegate()->WillShowMenu(item);
    if (old_count != item->GetSubmenu()->child_count()) {
      // If the number of children changed then we may need to add empty items.
      item->AddEmptyMenus();
    }
  }
  bool prefer_leading =
      state_.open_leading.empty() ? true : state_.open_leading.back();
  bool resulting_direction;
  gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ?
      CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) :
      CalculateMenuBounds(item, prefer_leading, &resulting_direction);
  state_.open_leading.push_back(resulting_direction);
  bool do_capture = (!did_capture_ && blocking_run_);
  showing_submenu_ = true;
  if (show)
    item->GetSubmenu()->ShowAt(owner_, bounds, do_capture);
  else
    item->GetSubmenu()->Reposition(bounds);
  showing_submenu_ = false;
}

void MenuController::MenuChildrenChanged(MenuItemView* item) {
  DCHECK(item);
  // Menu shouldn't be updated during drag operation.
  DCHECK(!active_mouse_view_);

  // If the current item or pending item is a descendant of the item
  // that changed, move the selection back to the changed item.
  const MenuItemView* ancestor = state_.item;
  while (ancestor && ancestor != item)
    ancestor = ancestor->GetParentMenuItem();
  if (!ancestor) {
    ancestor = pending_state_.item;
    while (ancestor && ancestor != item)
      ancestor = ancestor->GetParentMenuItem();
    if (!ancestor)
      return;
  }
  SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
  if (item->HasSubmenu())
    OpenMenuImpl(item, false);
}

void MenuController::BuildPathsAndCalculateDiff(
    MenuItemView* old_item,
    MenuItemView* new_item,
    std::vector<MenuItemView*>* old_path,
    std::vector<MenuItemView*>* new_path,
    size_t* first_diff_at) {
  DCHECK(old_path && new_path && first_diff_at);
  BuildMenuItemPath(old_item, old_path);
  BuildMenuItemPath(new_item, new_path);

  size_t common_size = std::min(old_path->size(), new_path->size());

  // Find the first difference between the two paths, when the loop
  // returns, diff_i is the first index where the two paths differ.
  for (size_t i = 0; i < common_size; ++i) {
    if ((*old_path)[i] != (*new_path)[i]) {
      *first_diff_at = i;
      return;
    }
  }

  *first_diff_at = common_size;
}

void MenuController::BuildMenuItemPath(MenuItemView* item,
                                       std::vector<MenuItemView*>* path) {
  if (!item)
    return;
  BuildMenuItemPath(item->GetParentMenuItem(), path);
  path->push_back(item);
}

void MenuController::StartShowTimer() {
  show_timer_.Start(FROM_HERE,
                    TimeDelta::FromMilliseconds(menu_config_.show_delay),
                    this, &MenuController::CommitPendingSelection);
}

void MenuController::StopShowTimer() {
  show_timer_.Stop();
}

void MenuController::StartCancelAllTimer() {
  cancel_all_timer_.Start(FROM_HERE,
                          TimeDelta::FromMilliseconds(kCloseOnExitTime),
                          this, &MenuController::CancelAll);
}

void MenuController::StopCancelAllTimer() {
  cancel_all_timer_.Stop();
}

gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item,
                                              bool prefer_leading,
                                              bool* is_leading) {
  DCHECK(item);

  SubmenuView* submenu = item->GetSubmenu();
  DCHECK(submenu);

  gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();

  // Don't let the menu go too wide.
  pref.set_width(std::min(pref.width(),
                            item->GetDelegate()->GetMaxWidthForMenu(item)));
  if (!state_.monitor_bounds.IsEmpty())
    pref.set_width(std::min(pref.width(), state_.monitor_bounds.width()));

  // Assume we can honor prefer_leading.
  *is_leading = prefer_leading;

  int x, y;

  const MenuConfig& menu_config = item->GetMenuConfig();

  if (!item->GetParentMenuItem()) {
    // First item, position relative to initial location.
    x = state_.initial_bounds.x();

    // Offsets for context menu prevent menu items being selected by
    // simply opening the menu (bug 142992).
    if (menu_config.offset_context_menus && state_.context_menu)
      x += 1;

    y = state_.initial_bounds.bottom();
    if (state_.anchor == MenuItemView::TOPRIGHT) {
      x = x + state_.initial_bounds.width() - pref.width();
      if (menu_config.offset_context_menus && state_.context_menu)
        x -= 1;
    } else if (state_.anchor == MenuItemView::BOTTOMCENTER) {
      x = x - (pref.width() - state_.initial_bounds.width()) / 2;
      if (pref.height() >
          state_.initial_bounds.y() + kCenteredContextMenuYOffset) {
        // Menu does not fit above the anchor. We move it to below.
        y = state_.initial_bounds.y() - kCenteredContextMenuYOffset;
      } else {
        y = std::max(0, state_.initial_bounds.y() - pref.height()) +
            kCenteredContextMenuYOffset;
      }
    }

    if (!state_.monitor_bounds.IsEmpty() &&
        y + pref.height() > state_.monitor_bounds.bottom()) {
      // The menu doesn't fit fully below the button on the screen. The menu
      // position with respect to the bounds will be preserved if it has
      // already been drawn. When the requested positioning is below the bounds
      // it will shrink the menu to make it fit below.
      // If the requested positioning is best fit, it will first try to fit the
      // menu below. If that does not fit it will try to place it above. If
      // that will not fit it will place it at the bottom of the work area and
      // moving it off the initial_bounds region to avoid overlap.
      // In all other requested position styles it will be flipped above and
      // the height will be shrunken to the usable height.
      if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) {
        pref.set_height(std::min(pref.height(),
                                 state_.monitor_bounds.bottom() - y));
      } else if (item->actual_menu_position() ==
                 MenuItemView::POSITION_BEST_FIT) {
        MenuItemView::MenuPosition orientation =
            MenuItemView::POSITION_BELOW_BOUNDS;
        if (state_.monitor_bounds.height() < pref.height()) {
          // Handle very tall menus.
          pref.set_height(state_.monitor_bounds.height());
          y = state_.monitor_bounds.y();
        } else if (state_.monitor_bounds.y() + pref.height() <
            state_.initial_bounds.y()) {
          // Flipping upwards if there is enough space.
          y = state_.initial_bounds.y() - pref.height();
          orientation = MenuItemView::POSITION_ABOVE_BOUNDS;
        } else {
          // It is allowed to move the menu a bit around in order to get the
          // best fit and to avoid showing scroll elements.
          y = state_.monitor_bounds.bottom() - pref.height();
        }
        if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) {
          // The menu should never overlap the owning button. So move it.
          // We use the anchor view style to determine the preferred position
          // relative to the owning button.
          if (state_.anchor == MenuItemView::TOPLEFT) {
            // The menu starts with the same x coordinate as the owning button.
            if (x + state_.initial_bounds.width() + pref.width() >
                state_.monitor_bounds.right())
              x -= pref.width();  // Move the menu to the left of the button.
            else
              x += state_.initial_bounds.width(); // Move the menu right.
          } else {
            // The menu should end with the same x coordinate as the owning
            // button.
            if (state_.monitor_bounds.x() >
                state_.initial_bounds.x() - pref.width())
              x = state_.initial_bounds.right();  // Move right of the button.
            else
              x = state_.initial_bounds.x() - pref.width(); // Move left.
          }
        }
        item->set_actual_menu_position(orientation);
      } else {
        pref.set_height(std::min(pref.height(),
            state_.initial_bounds.y() - state_.monitor_bounds.y()));
        y = state_.initial_bounds.y() - pref.height();
        item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS);
      }
    } else if (item->actual_menu_position() ==
               MenuItemView::POSITION_ABOVE_BOUNDS) {
      pref.set_height(std::min(pref.height(),
          state_.initial_bounds.y() - state_.monitor_bounds.y()));
      y = state_.initial_bounds.y() - pref.height();
    } else {
      item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS);
    }
    if (state_.monitor_bounds.width() != 0 &&
        menu_config.offset_context_menus && state_.context_menu) {
      if (x + pref.width() > state_.monitor_bounds.right())
        x = state_.initial_bounds.x() - pref.width() - 1;
      if (x < state_.monitor_bounds.x())
        x = state_.monitor_bounds.x();
    }
  } else {
    // Not the first menu; position it relative to the bounds of the menu
    // item.
    gfx::Point item_loc;
    View::ConvertPointToScreen(item, &item_loc);

    // We must make sure we take into account the UI layout. If the layout is
    // RTL, then a 'leading' menu is positioned to the left of the parent menu
    // item and not to the right.
    bool layout_is_rtl = base::i18n::IsRTL();
    bool create_on_the_right = (prefer_leading && !layout_is_rtl) ||
                               (!prefer_leading && layout_is_rtl);
    int submenu_horizontal_inset = menu_config.submenu_horizontal_inset;

    if (create_on_the_right) {
      x = item_loc.x() + item->width() - submenu_horizontal_inset;
      if (state_.monitor_bounds.width() != 0 &&
          x + pref.width() > state_.monitor_bounds.right()) {
        if (layout_is_rtl)
          *is_leading = true;
        else
          *is_leading = false;
        x = item_loc.x() - pref.width() + submenu_horizontal_inset;
      }
    } else {
      x = item_loc.x() - pref.width() + submenu_horizontal_inset;
      if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) {
        if (layout_is_rtl)
          *is_leading = false;
        else
          *is_leading = true;
        x = item_loc.x() + item->width() - submenu_horizontal_inset;
      }
    }
    y = item_loc.y() - menu_config.menu_vertical_border_size;
    if (state_.monitor_bounds.width() != 0) {
      pref.set_height(std::min(pref.height(), state_.monitor_bounds.height()));
      if (y + pref.height() > state_.monitor_bounds.bottom())
        y = state_.monitor_bounds.bottom() - pref.height();
      if (y < state_.monitor_bounds.y())
        y = state_.monitor_bounds.y();
    }
  }

  if (state_.monitor_bounds.width() != 0) {
    if (x + pref.width() > state_.monitor_bounds.right())
      x = state_.monitor_bounds.right() - pref.width();
    if (x < state_.monitor_bounds.x())
      x = state_.monitor_bounds.x();
  }
  return gfx::Rect(x, y, pref.width(), pref.height());
}

gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item,
                                                    bool prefer_leading,
                                                    bool* is_leading) {
  DCHECK(item);
  DCHECK(!item->GetParentMenuItem());

  // Assume we can honor prefer_leading.
  *is_leading = prefer_leading;

  SubmenuView* submenu = item->GetSubmenu();
  DCHECK(submenu);

  gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize();
  const gfx::Rect& owner_bounds = pending_state_.initial_bounds;

  // First the size gets reduced to the possible space.
  if (!state_.monitor_bounds.IsEmpty()) {
    int max_width = state_.monitor_bounds.width();
    int max_height = state_.monitor_bounds.height();
    // In case of bubbles, the maximum width is limited by the space
    // between the display corner and the target area + the tip size.
    if (state_.anchor == MenuItemView::BUBBLE_LEFT) {
      max_width = owner_bounds.x() - state_.monitor_bounds.x() +
                  kBubbleTipSizeLeftRight;
    } else if (state_.anchor == MenuItemView::BUBBLE_RIGHT) {
      max_width = state_.monitor_bounds.right() - owner_bounds.right() +
                  kBubbleTipSizeLeftRight;
    } else if (state_.anchor == MenuItemView::BUBBLE_ABOVE) {
      max_height = owner_bounds.y() - state_.monitor_bounds.y() +
                   kBubbleTipSizeTopBottom;
    } else if (state_.anchor == MenuItemView::BUBBLE_BELOW) {
      max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() +
                   kBubbleTipSizeTopBottom;
    }
    // The space for the menu to cover should never get empty.
    DCHECK_GE(max_width, kBubbleTipSizeLeftRight);
    DCHECK_GE(max_height, kBubbleTipSizeTopBottom);
    pref.set_width(std::min(pref.width(), max_width));
    pref.set_height(std::min(pref.height(), max_height));
  }
  // Also make sure that the menu does not go too wide.
  pref.set_width(std::min(pref.width(),
                          item->GetDelegate()->GetMaxWidthForMenu(item)));

  int x, y;
  if (state_.anchor == MenuItemView::BUBBLE_ABOVE ||
      state_.anchor == MenuItemView::BUBBLE_BELOW) {
    if (state_.anchor == MenuItemView::BUBBLE_ABOVE)
      y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom;
    else
      y = owner_bounds.bottom() - kBubbleTipSizeTopBottom;

    x = owner_bounds.CenterPoint().x() - pref.width() / 2;
    int x_old = x;
    if (x < state_.monitor_bounds.x()) {
      x = state_.monitor_bounds.x();
    } else if (x + pref.width() > state_.monitor_bounds.right()) {
      x = state_.monitor_bounds.right() - pref.width();
    }
    submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
        pref.width() / 2 - x + x_old);
  } else {
    if (state_.anchor == MenuItemView::BUBBLE_RIGHT)
      x = owner_bounds.right() - kBubbleTipSizeLeftRight;
    else
      x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight;

    y = owner_bounds.CenterPoint().y() - pref.height() / 2;
    int y_old = y;
    if (y < state_.monitor_bounds.y()) {
      y = state_.monitor_bounds.y();
    } else if (y + pref.height() > state_.monitor_bounds.bottom()) {
      y = state_.monitor_bounds.bottom() - pref.height();
    }
    submenu->GetScrollViewContainer()->SetBubbleArrowOffset(
        pref.height() / 2 - y + y_old);
  }
  return gfx::Rect(x, y, pref.width(), pref.height());
}

// static
int MenuController::MenuDepth(MenuItemView* item) {
  return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0;
}

void MenuController::IncrementSelection(int delta) {
  MenuItemView* item = pending_state_.item;
  DCHECK(item);
  if (pending_state_.submenu_open && item->HasSubmenu() &&
      item->GetSubmenu()->IsShowing()) {
    // A menu is selected and open, but none of its children are selected,
    // select the first menu item.
    if (item->GetSubmenu()->GetMenuItemCount()) {
      SetSelection(item->GetSubmenu()->GetMenuItemAt(0), SELECTION_DEFAULT);
      return;
    }
  }

  if (item->has_children()) {
    View* hot_view = GetFirstHotTrackedView(item);
    if (hot_view &&
        !strcmp(hot_view->GetClassName(), CustomButton::kViewClassName)) {
      CustomButton* button = static_cast<CustomButton*>(hot_view);
      button->SetHotTracked(false);
      View* to_make_hot = GetNextFocusableView(item, button, delta == 1);
      if (to_make_hot &&
          !strcmp(to_make_hot->GetClassName(), CustomButton::kViewClassName)) {
        CustomButton* button_hot = static_cast<CustomButton*>(to_make_hot);
        button_hot->SetHotTracked(true);
        return;
      }
    } else {
      View* to_make_hot = GetInitialFocusableView(item, delta == 1);
      if (to_make_hot &&
          !strcmp(to_make_hot->GetClassName(), CustomButton::kViewClassName)) {
        CustomButton* button_hot = static_cast<CustomButton*>(to_make_hot);
        button_hot->SetHotTracked(true);
        return;
      }
    }
  }

  MenuItemView* parent = item->GetParentMenuItem();
  if (parent) {
    int parent_count = parent->GetSubmenu()->GetMenuItemCount();
    if (parent_count > 1) {
      for (int i = 0; i < parent_count; ++i) {
        if (parent->GetSubmenu()->GetMenuItemAt(i) == item) {
          MenuItemView* to_select =
              FindNextSelectableMenuItem(parent, i, delta);
          if (!to_select)
            break;
          SetSelection(to_select, SELECTION_DEFAULT);
          View* to_make_hot = GetInitialFocusableView(to_select, delta == 1);
          if (to_make_hot && !strcmp(to_make_hot->GetClassName(),
                                     CustomButton::kViewClassName)) {
            CustomButton* button_hot = static_cast<CustomButton*>(to_make_hot);
            button_hot->SetHotTracked(true);
          }
          break;
        }
      }
    }
  }
}

MenuItemView* MenuController::FindNextSelectableMenuItem(MenuItemView* parent,
                                                         int index,
                                                         int delta) {
  int start_index = index;
  int parent_count = parent->GetSubmenu()->GetMenuItemCount();
  // Loop through the menu items skipping any invisible menus. The loop stops
  // when we wrap or find a visible child.
  do {
    index = (index + delta + parent_count) % parent_count;
    if (index == start_index)
      return NULL;
    MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index);
    if (child->visible())
      return child;
  } while (index != start_index);
  return NULL;
}

void MenuController::OpenSubmenuChangeSelectionIfCan() {
  MenuItemView* item = pending_state_.item;
  if (item->HasSubmenu() && item->enabled()) {
    if (item->GetSubmenu()->GetMenuItemCount() > 0) {
      SetSelection(item->GetSubmenu()->GetMenuItemAt(0),
                   SELECTION_UPDATE_IMMEDIATELY);
    } else {
      // No menu items, just show the sub-menu.
      SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
    }
  }
}

void MenuController::CloseSubmenu() {
  MenuItemView* item = state_.item;
  DCHECK(item);
  if (!item->GetParentMenuItem())
    return;
  if (item->HasSubmenu() && item->GetSubmenu()->IsShowing())
    SetSelection(item, SELECTION_UPDATE_IMMEDIATELY);
  else if (item->GetParentMenuItem()->GetParentMenuItem())
    SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY);
}

MenuController::SelectByCharDetails MenuController::FindChildForMnemonic(
    MenuItemView* parent,
    char16 key,
    bool (*match_function)(MenuItemView* menu, char16 mnemonic)) {
  SubmenuView* submenu = parent->GetSubmenu();
  DCHECK(submenu);
  SelectByCharDetails details;

  for (int i = 0, menu_item_count = submenu->GetMenuItemCount();
       i < menu_item_count; ++i) {
    MenuItemView* child = submenu->GetMenuItemAt(i);
    if (child->enabled() && child->visible()) {
      if (child == pending_state_.item)
        details.index_of_item = i;
      if (match_function(child, key)) {
        if (details.first_match == -1)
          details.first_match = i;
        else
          details.has_multiple = true;
        if (details.next_match == -1 && details.index_of_item != -1 &&
            i > details.index_of_item)
          details.next_match = i;
      }
    }
  }
  return details;
}

bool MenuController::AcceptOrSelect(MenuItemView* parent,
                                    const SelectByCharDetails& details) {
  // This should only be invoked if there is a match.
  DCHECK(details.first_match != -1);
  DCHECK(parent->HasSubmenu());
  SubmenuView* submenu = parent->GetSubmenu();
  DCHECK(submenu);
  if (!details.has_multiple) {
    // There's only one match, activate it (or open if it has a submenu).
    if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) {
      SetSelection(submenu->GetMenuItemAt(details.first_match),
                   SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY);
    } else {
      Accept(submenu->GetMenuItemAt(details.first_match), 0);
      return true;
    }
  } else if (details.index_of_item == -1 || details.next_match == -1) {
    SetSelection(submenu->GetMenuItemAt(details.first_match),
                 SELECTION_DEFAULT);
  } else {
    SetSelection(submenu->GetMenuItemAt(details.next_match),
                 SELECTION_DEFAULT);
  }
  return false;
}

bool MenuController::SelectByChar(char16 character) {
  char16 char_array[] = { character, 0 };
  char16 key = base::i18n::ToLower(char_array)[0];
  MenuItemView* item = pending_state_.item;
  if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing())
    item = item->GetParentMenuItem();
  DCHECK(item);
  DCHECK(item->HasSubmenu());
  DCHECK(item->GetSubmenu());
  if (item->GetSubmenu()->GetMenuItemCount() == 0)
    return false;

  // Look for matches based on mnemonic first.
  SelectByCharDetails details =
      FindChildForMnemonic(item, key, &MatchesMnemonic);
  if (details.first_match != -1)
    return AcceptOrSelect(item, details);

  // If no mnemonics found, look at first character of titles.
  details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic);
  if (details.first_match != -1)
    return AcceptOrSelect(item, details);

  return false;
}

#if defined(OS_WIN)
void MenuController::RepostEvent(SubmenuView* source,
                                 const ui::LocatedEvent& event) {
  if (!state_.item) {
    // We some times get an event after closing all the menus. Ignore it.
    // Make sure the menu is in fact not visible. If the menu is visible, then
    // we're in a bad state where we think the menu isn't visibile but it is.
    DCHECK(!source->GetWidget()->IsVisible());
    return;
  }

  gfx::Point screen_loc(event.location());
  View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc);
  HWND window = WindowFromPoint(screen_loc.ToPOINT());
  if (window) {
    // Release the capture.
    SubmenuView* submenu = state_.item->GetRootMenuItem()->GetSubmenu();
    submenu->ReleaseCapture();

    if (submenu->GetWidget()->GetNativeView() &&
        GetWindowThreadProcessId(
            views::HWNDForNativeView(submenu->GetWidget()->GetNativeView()),
            NULL) != GetWindowThreadProcessId(window, NULL)) {
      // Even though we have mouse capture, windows generates a mouse event
      // if the other window is in a separate thread. Don't generate an event in
      // this case else the target window can get double events leading to bad
      // behavior.
      return;
    }

    // Convert the coordinates to the target window.
    RECT window_bounds;
    GetWindowRect(window, &window_bounds);
    int window_x = screen_loc.x() - window_bounds.left;
    int window_y = screen_loc.y() - window_bounds.top;

    // Determine whether the click was in the client area or not.
    // NOTE: WM_NCHITTEST coordinates are relative to the screen.
    LRESULT nc_hit_result = SendMessage(window, WM_NCHITTEST, 0,
                                        MAKELPARAM(screen_loc.x(),
                                                   screen_loc.y()));
    const bool in_client_area = (nc_hit_result == HTCLIENT);

    // TODO(sky): this isn't right. The event to generate should correspond
    // with the event we just got. MouseEvent only tells us what is down,
    // which may differ. Need to add ability to get changed button from
    // MouseEvent.
    int event_type;
    int flags = event.flags();
    if (flags & ui::EF_LEFT_MOUSE_BUTTON)
      event_type = in_client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN;
    else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON)
      event_type = in_client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN;
    else if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
      event_type = in_client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN;
    else
      event_type = 0;  // Unknown mouse press.

    if (event_type) {
      if (in_client_area) {
        PostMessage(window, event_type, event.native_event().wParam,
                    MAKELPARAM(window_x, window_y));
      } else {
        PostMessage(window, event_type, nc_hit_result,
                    MAKELPARAM(screen_loc.x(), screen_loc.y()));
      }
    }
  }
}
#elif defined(USE_AURA)
void MenuController::RepostEvent(SubmenuView* source,
                                 const ui::LocatedEvent& event) {
  aura::RootWindow* root_window =
      source->GetWidget()->GetNativeWindow()->GetRootWindow();
  DCHECK(root_window);
  root_window->RepostEvent(event);
}
#endif

void MenuController::SetDropMenuItem(
    MenuItemView* new_target,
    MenuDelegate::DropPosition new_position) {
  if (new_target == drop_target_ && new_position == drop_position_)
    return;

  if (drop_target_) {
    drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
        NULL, MenuDelegate::DROP_NONE);
  }
  drop_target_ = new_target;
  drop_position_ = new_position;
  if (drop_target_) {
    drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem(
        drop_target_, drop_position_);
  }
}

void MenuController::UpdateScrolling(const MenuPart& part) {
  if (!part.is_scroll() && !scroll_task_.get())
    return;

  if (!scroll_task_.get())
    scroll_task_.reset(new MenuScrollTask());
  scroll_task_->Update(part);
}

void MenuController::StopScrolling() {
  scroll_task_.reset(NULL);
}

void MenuController::UpdateActiveMouseView(SubmenuView* event_source,
                                           const ui::MouseEvent& event,
                                           View* target_menu) {
  View* target = NULL;
  gfx::Point target_menu_loc(event.location());
  if (target_menu && target_menu->has_children()) {
    // Locate the deepest child view to send events to.  This code assumes we
    // don't have to walk up the tree to find a view interested in events. This
    // is currently true for the cases we are embedding views, but if we embed
    // more complex hierarchies it'll need to change.
    View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
                               &target_menu_loc);
    View::ConvertPointToTarget(NULL, target_menu, &target_menu_loc);
    target = target_menu->GetEventHandlerForPoint(target_menu_loc);
    if (target == target_menu || !target->enabled())
      target = NULL;
  }
  if (target != active_mouse_view_) {
    SendMouseCaptureLostToActiveView();
    active_mouse_view_ = target;
    if (active_mouse_view_) {
      gfx::Point target_point(target_menu_loc);
      View::ConvertPointToTarget(
          target_menu, active_mouse_view_, &target_point);
      ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED,
                                         target_point, target_point,
                                         0);
      active_mouse_view_->OnMouseEntered(mouse_entered_event);

      ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED,
                                         target_point, target_point,
                                         event.flags());
      active_mouse_view_->OnMousePressed(mouse_pressed_event);
    }
  }

  if (active_mouse_view_) {
    gfx::Point target_point(target_menu_loc);
    View::ConvertPointToTarget(target_menu, active_mouse_view_, &target_point);
    ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED,
                                       target_point, target_point,
                                       event.flags());
    active_mouse_view_->OnMouseDragged(mouse_dragged_event);
  }
}

void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source,
                                                  const ui::MouseEvent& event) {
  if (!active_mouse_view_)
    return;

  gfx::Point target_loc(event.location());
  View::ConvertPointToScreen(event_source->GetScrollViewContainer(),
                             &target_loc);
  View::ConvertPointToTarget(NULL, active_mouse_view_, &target_loc);
  ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED,
                           target_loc, target_loc,
                           event.flags());
  // Reset the active_mouse_view_ before sending mouse released. That way if it
  // calls back to us, we aren't in a weird state.
  View* active_view = active_mouse_view_;
  active_mouse_view_ = NULL;
  active_view->OnMouseReleased(release_event);
}

void MenuController::SendMouseCaptureLostToActiveView() {
  if (!active_mouse_view_)
    return;

  // Reset the active_mouse_view_ before sending mouse capture lost. That way if
  // it calls back to us, we aren't in a weird state.
  View* active_view = active_mouse_view_;
  active_mouse_view_ = NULL;
  active_view->OnMouseCaptureLost();
}

void MenuController::SetExitType(ExitType type) {
  exit_type_ = type;
  // Exit nested message loops as soon as possible. We do this as
  // MessageLoop::Dispatcher is only invoked before native events, which means
  // its entirely possible for a Widget::CloseNow() task to be processed before
  // the next native message. By using QuitNow() we ensures the nested message
  // loop returns as soon as possible and avoids having deleted views classes
  // (such as widgets and rootviews) on the stack when the nested message loop
  // stops.
  //
  // It's safe to invoke QuitNow multiple times, it only effects the current
  // loop.
  bool quit_now = ShouldQuitNow() && exit_type_ != EXIT_NONE &&
      message_loop_depth_;

  if (quit_now)
    base::MessageLoop::current()->QuitNow();
}

void MenuController::HandleMouseLocation(SubmenuView* source,
                                         const gfx::Point& mouse_location) {
  if (showing_submenu_)
    return;

  // Ignore mouse events if we're closing the menu.
  if (exit_type_ != EXIT_NONE)
    return;

  MenuPart part = GetMenuPart(source, mouse_location);

  UpdateScrolling(part);

  if (!blocking_run_)
    return;

  if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location))
    return;

  if (part.type == MenuPart::MENU_ITEM && part.menu) {
    SetSelection(part.menu, SELECTION_OPEN_SUBMENU);
  } else if (!part.is_scroll() && pending_state_.item &&
             pending_state_.item->GetParentMenuItem() &&
             (!pending_state_.item->HasSubmenu() ||
              !pending_state_.item->GetSubmenu()->IsShowing())) {
    // On exit if the user hasn't selected an item with a submenu, move the
    // selection back to the parent menu item.
    SetSelection(pending_state_.item->GetParentMenuItem(),
                 SELECTION_OPEN_SUBMENU);
  }
}

}  // namespace views