This file is indexed.

/usr/share/cinnamon/js/ui/popupMenu.js is in cinnamon-common 3.6.7-8ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

const Cairo = imports.cairo;
const Mainloop = imports.mainloop;
const Clutter = imports.gi.Clutter;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const Cinnamon = imports.gi.Cinnamon;
const Signals = imports.signals;
const St = imports.gi.St;
const Atk = imports.gi.Atk;

const BoxPointer = imports.ui.boxpointer;
const DND = imports.ui.dnd;
const Main = imports.ui.main;
const SignalManager = imports.misc.signalManager;
const Tweener = imports.ui.tweener;
const CheckBox = imports.ui.checkBox;
const RadioButton = imports.ui.radioButton;

const Params = imports.misc.params;
const Util = imports.misc.util;

const SLIDER_SCROLL_STEP = 0.05; /* Slider scrolling step in % */

const PanelLoc = {
    top : 0,
    bottom : 1,
    left : 2,
    right : 3
};

const OrnamentType = {
    NONE: 0,
    CHECK: 1,
    DOT: 2,
    ICON: 3
};

const FactoryClassTypes = {
    'RootMenuClass'            : "RootMenuClass",
    'MenuItemClass'            : "MenuItemClass",
    'SubMenuMenuItemClass'     : "SubMenuMenuItemClass",
    'MenuSectionMenuItemClass' : "MenuSectionMenuItemClass",
    'SeparatorMenuItemClass'   : "SeparatorMenuItemClass"
};

const FactoryEventTypes = {
    'opened'    : "opened",
    'closed'    : "closed",
    'clicked'   : "clicked"
};

function _ensureStyle(actor) {
    if (actor.get_children) {
        let children = actor.get_children();
        for (let i = 0; i < children.length; i++)
            _ensureStyle(children[i]);
    }

    if (actor instanceof St.Widget)
        actor.ensure_style();
}

/**
 * @side Side to which the arrow points.
 */
function arrowIcon(side) {
    let iconName;
    switch (side) {
        case St.Side.TOP:
            iconName = 'pan-up';
            break;
        case St.Side.RIGHT:
            iconName = 'pan-end';
            break;
        case St.Side.BOTTOM:
            iconName = 'pan-down';
            break;
        case St.Side.LEFT:
            iconName = 'pan-start';
            break;
    }

    let arrow = new St.Icon({ style_class: 'popup-menu-arrow',
                              icon_name: iconName,
                              icon_type: St.IconType.SYMBOLIC,
                              y_expand: true,
                              y_align: Clutter.ActorAlign.CENTER,
                              important: true });

    return arrow;
}

function PopupBaseMenuItem(params) {
    this._init(params);
}

PopupBaseMenuItem.prototype = {
    _init: function (params) {
        params = Params.parse (params, { reactive: true,
                                         activate: true,
                                         hover: true,
                                         sensitive: true,
                                         style_class: null,
                                         focusOnHover: true
                                       });
        this._signals = new SignalManager.SignalManager(null);
        this.actor = new Cinnamon.GenericContainer({ style_class: 'popup-menu-item',
                                                  reactive: params.reactive,
                                                  track_hover: params.reactive,
                                                  can_focus: params.reactive,
                                                  accessible_role: Atk.Role.MENU_ITEM });
        this._signals.connect(this.actor, 'get-preferred-width', Lang.bind(this, this._getPreferredWidth));
        this._signals.connect(this.actor, 'get-preferred-height', Lang.bind(this, this._getPreferredHeight));
        this._signals.connect(this.actor, 'allocate', Lang.bind(this, this._allocate));
        this._signals.connect(this.actor, 'style-changed', Lang.bind(this, this._onStyleChanged));
        this.actor._delegate = this;

        this._children = [];
        this._dot = null;
        this._columnWidths = null;
        this._spacing = 0;
        this.active = false;
        this._activatable = params.reactive && params.activate;
        this.sensitive = true;
        this.focusOnHover = params.focusOnHover;

        this.setSensitive(this._activatable && params.sensitive);

        if (params.style_class)
            this.actor.add_style_class_name(params.style_class);

        if (this._activatable) {
            this._signals.connect(this.actor, 'button-release-event', Lang.bind(this, this._onButtonReleaseEvent));
            this._signals.connect(this.actor, 'key-press-event', Lang.bind(this, this._onKeyPressEvent));
        }
        if (params.reactive && params.hover)
            this._signals.connect(this.actor, 'notify::hover', Lang.bind(this, this._onHoverChanged));
        if (params.reactive) {
            this._signals.connect(this.actor, 'key-focus-in', Lang.bind(this, this._onKeyFocusIn));
            this._signals.connect(this.actor, 'key-focus-out', Lang.bind(this, this._onKeyFocusOut));
        }
    },

    _onStyleChanged: function (actor) {
        this._spacing = Math.round(actor.get_theme_node().get_length('spacing'));
    },

    _onButtonReleaseEvent: function (actor, event) {
        this.activate(event, false);
        return true;
    },

    _onKeyPressEvent: function (actor, event) {
        let symbol = event.get_key_symbol();

        if (symbol == Clutter.KEY_space || symbol == Clutter.KEY_Return) {
            this.activate(event);
            return true;
        }
        return false;
    },

    _onKeyFocusIn: function (actor) {
        this.setActive(true);
    },

    _onKeyFocusOut: function (actor) {
        this.setActive(false);
    },

    _onHoverChanged: function (actor) {
        this.setActive(actor.hover);
    },

    activate: function (event, keepMenu) {
        this.emit('activate', event, keepMenu);
    },

    setActive: function (active) {
        let activeChanged = active != this.active;

        if (activeChanged) {
            this.active = active;
            this.actor.change_style_pseudo_class('active', active);
            if (this.focusOnHover && this.active) this.actor.grab_key_focus();

            this.emit('active-changed', active);
        }
    },

    setSensitive: function(sensitive) {
        if (!this._activatable)
            return;
        if (this.sensitive == sensitive)
            return;

        this.sensitive = sensitive;
        this.actor.reactive = sensitive;
        this.actor.can_focus = sensitive;

        this.actor.change_style_pseudo_class('insensitive', !sensitive);
        this.emit('sensitive-changed', sensitive);
    },

    destroy: function() {
        this._signals.disconnectAllSignals();
        this.actor.destroy();
        this.emit('destroy');
    },

    // adds an actor to the menu item; @params can contain %span
    // (column span; defaults to 1, -1 means "all the remaining width", 0 means "no new column after this actor"),
    // %expand (defaults to #false), and %align (defaults to
    // #St.Align.START)
    addActor: function(child, params) {
        params = Params.parse(params, { span: 1,
                                        expand: false,
                                        align: St.Align.START });
        params.actor = child;
        this._children.push(params);
        this._signals.connect(this.actor, 'destroy', Lang.bind(this, function () { this._removeChild(child); }));
        this.actor.add_actor(child);
    },

    _removeChild: function(child) {
        for (let i = 0; i < this._children.length; i++) {
            if (this._children[i].actor == child) {
                this._children.splice(i, 1);
                return;
            }
        }
    },

    removeActor: function(child) {
        this.actor.remove_actor(child);
        this._removeChild(child);
    },

    setShowDot: function(show) {
        if (show) {
            if (this._dot)
                return;

            this._dot = new St.DrawingArea({ style_class: 'popup-menu-item-dot' });
            this._signals.connect(this._dot, 'repaint', Lang.bind(this, this._onRepaintDot));
            this.actor.add_actor(this._dot);
            this.actor.add_accessible_state (Atk.StateType.CHECKED);
        } else {
            if (!this._dot)
                return;

            this._dot.destroy();
            this._dot = null;
            this.actor.remove_accessible_state (Atk.StateType.CHECKED);
        }
    },

    _onRepaintDot: function(area) {
        let cr = area.get_context();
        let [width, height] = area.get_surface_size();
        let color = area.get_theme_node().get_foreground_color();

        cr.setSourceRGBA (
            color.red / 255,
            color.green / 255,
            color.blue / 255,
            color.alpha / 255);
        cr.arc(width / 2, height / 2, width / 3, 0, 2 * Math.PI);
        cr.fill();

        cr.$dispose();
    },

    // This returns column widths in logical order (i.e. from the dot
    // to the image), not in visual order (left to right)
    getColumnWidths: function() {
        let widths = [];
        for (let i = 0, col = 0; i < this._children.length; i++) {
            let child = this._children[i];
            let [min, natural] = child.actor.get_preferred_width(-1);

            if (widths[col])
                widths[col] += this._spacing + natural;
            else
                widths[col] = natural;

            if (child.span > 0) {
                col++;
                for (let j = 1; j < child.span; j++)
                    widths[col++] = 0;
            }
        }
        return widths;
    },

    setColumnWidths: function(widths) {
        this._columnWidths = widths;
    },

    _getPreferredWidth: function(actor, forHeight, alloc) {
        let width = 0;
        if (this._columnWidths) {
            for (let i = 0; i < this._columnWidths.length; i++) {
                if (i > 0)
                    width += this._spacing;
                width += this._columnWidths[i];
            }
        } else {
            for (let i = 0; i < this._children.length; i++) {
                let child = this._children[i];
                if (i > 0)
                    width += this._spacing;
                let [min, natural] = child.actor.get_preferred_width(-1);
                width += natural;
            }
        }
        alloc.min_size = alloc.natural_size = width;
    },

    _getPreferredHeight: function(actor, forWidth, alloc) {
        let height = 0, x = 0, minWidth, childWidth;
        for (let i = 0; i < this._children.length; i++) {
            let child = this._children[i];
            if (this._columnWidths) {
                if (child.span == -1) {
                    childWidth = 0;
                    for (let j = i; j < this._columnWidths.length; j++)
                        childWidth += this._columnWidths[j]
                } else
                    childWidth = this._columnWidths[i];
            } else {
                if (child.span == -1)
                    childWidth = forWidth - x;
                else
                    [minWidth, childWidth] = child.actor.get_preferred_width(-1);
            }
            x += childWidth;

            let [min, natural] = child.actor.get_preferred_height(childWidth);
            if (natural > height)
                height = natural;
        }
        alloc.min_size = alloc.natural_size = height;
    },

    _allocate: function(actor, box, flags) {
        let height = box.y2 - box.y1;
        let direction = this.actor.get_direction();

        if (this._dot) {
            // The dot is placed outside box
            // one quarter of padding from the border of the container
            // (so 3/4 from the inner border)
            // (padding is box.x1)
            let dotBox = new Clutter.ActorBox();
            let dotWidth = Math.round(box.x1 / 2);

            if (direction == St.TextDirection.LTR) {
                dotBox.x1 = Math.round(box.x1 / 4);
                dotBox.x2 = dotBox.x1 + dotWidth;
            } else {
                dotBox.x2 = box.x2 + 3 * Math.round(box.x1 / 4);
                dotBox.x1 = dotBox.x2 - dotWidth;
            }
            dotBox.y1 = Math.round(box.y1 + (height - dotWidth) / 2);
            dotBox.y2 = dotBox.y1 + dotWidth;
            this._dot.allocate(dotBox, flags);
        }

        let x;
        if (direction == St.TextDirection.LTR)
            x = box.x1;
        else
            x = box.x2;

        let cols;
        //clone _columnWidths, if it exists, to be able to modify it without any impact
        if (this._columnWidths instanceof Array)
            cols = this._columnWidths.slice(0);

        // if direction is ltr, x is the right edge of the last added
        // actor, and it's constantly increasing, whereas if rtl, x is
        // the left edge and it decreases
        for (let i = 0, col = 0; i < this._children.length; i++) {
            let child = this._children[i];
            let childBox = new Clutter.ActorBox();

            let [minWidth, naturalWidth] = child.actor.get_preferred_width(-1);
            let availWidth, extraWidth;
            if (cols) {
                if (child.span == -1) {
                    if (direction == St.TextDirection.LTR)
                        availWidth = box.x2 - x;
                    else
                        availWidth = x - box.x1;
                } else if (child.span == 0) {
                    availWidth = naturalWidth;
                    cols[col] -= naturalWidth + this._spacing;
                } else {
                    availWidth = 0;
                    for (let j = 0; j < child.span; j++)
                        availWidth += cols[col++];
                }
                extraWidth = availWidth - naturalWidth;
            } else {
                if (child.span == -1) {
                    if (direction == St.TextDirection.LTR)
                        availWidth = box.x2 - x;
                    else
                        availWidth = x - box.x1;
                } else {
                    availWidth = naturalWidth;
                }
                extraWidth = 0;
            }

            if (direction == St.TextDirection.LTR) {
                if (child.expand) {
                    childBox.x1 = x;
                    childBox.x2 = x + availWidth;
                } else if (child.align === St.Align.MIDDLE) {
                    childBox.x1 = x + Math.round(extraWidth / 2);
                    childBox.x2 = childBox.x1 + naturalWidth;
                } else if (child.align === St.Align.END) {
                    childBox.x2 = x + availWidth;
                    childBox.x1 = childBox.x2 - naturalWidth;
                } else {
                    childBox.x1 = x;
                    childBox.x2 = x + naturalWidth;
                }

                //when somehow the actor is wider than the box, cut it off
                if(childBox.x2 > box.x2)
                    childBox.x2 = box.x2;
            } else {
                if (child.expand) {
                    childBox.x1 = x - availWidth;
                    childBox.x2 = x;
                } else if (child.align === St.Align.MIDDLE) {
                    childBox.x1 = x - Math.round(extraWidth / 2);
                    childBox.x2 = childBox.x1 + naturalWidth;
                } else if (child.align === St.Align.END) {
                    // align to the left
                    childBox.x1 = x - availWidth;
                    childBox.x2 = childBox.x1 + naturalWidth;
                } else {
                    // align to the right
                    childBox.x2 = x;
                    childBox.x1 = x - naturalWidth;
                }

                //when somehow the actor is wider than the box, cut it off
                if(childBox.x1 < box.x1)
                    childBox.x1 = box.x1;
            }

            let [minHeight, naturalHeight] = child.actor.get_preferred_height(childBox.x2 - childBox.x1);
            childBox.y1 = Math.round(box.y1 + (height - naturalHeight) / 2);
            childBox.y2 = childBox.y1 + naturalHeight;

            child.actor.allocate(childBox, flags);

            if (direction == St.TextDirection.LTR)
                x += availWidth + this._spacing;
            else
                x -= availWidth + this._spacing;
        }
    }
};
Signals.addSignalMethods(PopupBaseMenuItem.prototype);

function PopupMenuItem() {
    this._init.apply(this, arguments);
}

PopupMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function (text, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this.label = new St.Label({ text: text });
        this.addActor(this.label);
        this.actor.label_actor = this.label;
    }
};

function PopupSeparatorMenuItem() {
    this._init();
}

PopupSeparatorMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function () {
        PopupBaseMenuItem.prototype._init.call(this, { reactive: false });

        this._drawingArea = new St.DrawingArea({ style_class: 'popup-separator-menu-item' });
        this.addActor(this._drawingArea, { span: -1, expand: true });
        this._signals.connect(this._drawingArea, 'repaint', Lang.bind(this, this._onRepaint));
    },

    _onRepaint: function(area) {
        let cr = area.get_context();
        let themeNode = area.get_theme_node();
        let [width, height] = area.get_surface_size();
        let margin = themeNode.get_length('-margin-horizontal');
        let gradientHeight = themeNode.get_length('-gradient-height');
        let startColor = themeNode.get_color('-gradient-start');
        let endColor = themeNode.get_color('-gradient-end');

        let gradientWidth = (width - margin * 2);
        let gradientOffset = (height - gradientHeight) / 2;
        let pattern = new Cairo.LinearGradient(margin, gradientOffset, width - margin, gradientOffset + gradientHeight);
        pattern.addColorStopRGBA(0, startColor.red / 255, startColor.green / 255, startColor.blue / 255, startColor.alpha / 255);
        pattern.addColorStopRGBA(0.5, endColor.red / 255, endColor.green / 255, endColor.blue / 255, endColor.alpha / 255);
        pattern.addColorStopRGBA(1, startColor.red / 255, startColor.green / 255, startColor.blue / 255, startColor.alpha / 255);
        cr.setSource(pattern);
        cr.rectangle(margin, gradientOffset, gradientWidth, gradientHeight);
        cr.fill();

        cr.$dispose();
    }
};

const PopupAlternatingMenuItemState = {
    DEFAULT: 0,
    ALTERNATIVE: 1
}

function PopupAlternatingMenuItem() {
    this._init.apply(this, arguments);
}

PopupAlternatingMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function(text, alternateText, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);
        this.actor.add_style_class_name('popup-alternating-menu-item');

        this._text = text;
        this._alternateText = alternateText;
        this.label = new St.Label({ text: text });
        this.state = PopupAlternatingMenuItemState.DEFAULT;
        this.addActor(this.label);

        this._signals.connect(this.actor, 'notify::mapped', Lang.bind(this, this._onMapped));
    },

    _onMapped: function() {
        if (this.actor.mapped) {
            this._capturedEventId = global.stage.connect('captured-event',
                                                         Lang.bind(this, this._onCapturedEvent));
            this._updateStateFromModifiers();
        } else {
            if (this._capturedEventId != 0) {
                global.stage.disconnect(this._capturedEventId);
                this._capturedEventId = 0;
            }
        }
    },

    _setState: function(state) {
        if (this.state != state) {
            if (state == PopupAlternatingMenuItemState.ALTERNATIVE && !this._canAlternate())
                return;

            this.state = state;
            this._updateLabel();
        }
    },

    _updateStateFromModifiers: function() {
        let [x, y, mods] = global.get_pointer();
        let state;

        if ((mods & Clutter.ModifierType.MOD1_MASK) == 0) {
            state = PopupAlternatingMenuItemState.DEFAULT;
        } else {
            state = PopupAlternatingMenuItemState.ALTERNATIVE;
        }

        this._setState(state);
    },

    _onCapturedEvent: function(actor, event) {
        if (event.type() != Clutter.EventType.KEY_PRESS &&
            event.type() != Clutter.EventType.KEY_RELEASE)
            return false;

        let key = event.get_key_symbol();

        if (key == Clutter.KEY_Alt_L || key == Clutter.KEY_Alt_R)
            this._updateStateFromModifiers();

        return false;
    },

    _updateLabel: function() {
        if (this.state == PopupAlternatingMenuItemState.ALTERNATIVE) {
            this.actor.add_style_pseudo_class('alternate');
            this.label.set_text(this._alternateText);
        } else {
            this.actor.remove_style_pseudo_class('alternate');
            this.label.set_text(this._text);
        }
    },

    _canAlternate: function() {
        if (this.state == PopupAlternatingMenuItemState.DEFAULT && !this._alternateText)
            return false;
        return true;
    },

    updateText: function(text, alternateText) {
        this._text = text;
        this._alternateText = alternateText;

        if (!this._canAlternate())
            this._setState(PopupAlternatingMenuItemState.DEFAULT);

        this._updateLabel();
    }
};

function PopupSliderMenuItem() {
    this._init.apply(this, arguments);
}

PopupSliderMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function(value) {
        PopupBaseMenuItem.prototype._init.call(this, { activate: false });

        this._signals.connect(this.actor, 'key-press-event', Lang.bind(this, this._onKeyPressEvent));

        if (isNaN(value))
            // Avoid spreading NaNs around
            throw TypeError('The slider value must be a number');
        this._value = Math.max(Math.min(value, 1), 0);

        this._slider = new St.DrawingArea({ style_class: 'popup-slider-menu-item', reactive: true });
        this.addActor(this._slider, { span: -1, expand: true });
        this._signals.connect(this._slider, 'repaint', Lang.bind(this, this._sliderRepaint));
        this._signals.connect(this.actor, 'button-press-event', Lang.bind(this, this._startDragging));
        this._signals.connect(this.actor, 'scroll-event', Lang.bind(this, this._onScrollEvent));

        this._releaseId = this._motionId = 0;
        this._dragging = false;
    },

    setValue: function(value) {
        if (isNaN(value))
            throw TypeError('The slider value must be a number');

        this._value = Math.max(Math.min(value, 1), 0);
        this._slider.queue_repaint();
    },

    _sliderRepaint: function(area) {
        let cr = area.get_context();
        let themeNode = area.get_theme_node();
        let [width, height] = area.get_surface_size();

        let handleRadius = themeNode.get_length('-slider-handle-radius');

        let sliderWidth = width - 2 * handleRadius;
        let sliderHeight = themeNode.get_length('-slider-height');

        let sliderBorderWidth = themeNode.get_length('-slider-border-width');
        let sliderBorderRadius = Math.min(width, sliderHeight) / 2;

        let sliderBorderColor = themeNode.get_color('-slider-border-color');
        let sliderColor = themeNode.get_color('-slider-background-color');

        let sliderActiveBorderColor = themeNode.get_color('-slider-active-border-color');
        let sliderActiveColor = themeNode.get_color('-slider-active-background-color');

        const TAU = Math.PI * 2;

        let handleX = handleRadius + (width - 2 * handleRadius) * this._value;

        cr.arc(sliderBorderRadius + sliderBorderWidth, height / 2, sliderBorderRadius, TAU * 1/4, TAU * 3/4);
        cr.lineTo(handleX, (height - sliderHeight) / 2);
        cr.lineTo(handleX, (height + sliderHeight) / 2);
        cr.lineTo(sliderBorderRadius + sliderBorderWidth, (height + sliderHeight) / 2);
        Clutter.cairo_set_source_color(cr, sliderActiveColor);
        cr.fillPreserve();
        Clutter.cairo_set_source_color(cr, sliderActiveBorderColor);
        cr.setLineWidth(sliderBorderWidth);
        cr.stroke();

        cr.arc(width - sliderBorderRadius - sliderBorderWidth, height / 2, sliderBorderRadius, TAU * 3/4, TAU * 1/4);
        cr.lineTo(handleX, (height + sliderHeight) / 2);
        cr.lineTo(handleX, (height - sliderHeight) / 2);
        cr.lineTo(width - sliderBorderRadius - sliderBorderWidth, (height - sliderHeight) / 2);
        Clutter.cairo_set_source_color(cr, sliderColor);
        cr.fillPreserve();
        Clutter.cairo_set_source_color(cr, sliderBorderColor);
        cr.setLineWidth(sliderBorderWidth);
        cr.stroke();

        let handleY = height / 2;

        let color = themeNode.get_foreground_color();
        Clutter.cairo_set_source_color(cr, color);
        cr.arc(handleX, handleY, handleRadius, 0, 2 * Math.PI);
        cr.fill();

        cr.$dispose();
    },

    _startDragging: function(actor, event) {
        if (this._dragging) // don't allow two drags at the same time
            return;

        this.emit('drag-begin');
        this._dragging = true;

        // FIXME: we should only grab the specific device that originated
        // the event, but for some weird reason events are still delivered
        // outside the slider if using clutter_grab_pointer_for_device
        Clutter.grab_pointer(this._slider);
        this._signals.connect(this._slider, 'button-release-event', Lang.bind(this, this._endDragging));
        this._signals.connect(this._slider, 'motion-event', Lang.bind(this, this._motionEvent));
        let absX, absY;
        [absX, absY] = event.get_coords();
        this._moveHandle(absX, absY);
    },

    _endDragging: function() {
        if (this._dragging) {
            this._signals.disconnect('button-release-event', this._slider);
            this._signals.disconnect('motion-event', this._slider);

            Clutter.ungrab_pointer();
            this._dragging = false;

            this.emit('drag-end');
        }
        return true;
    },

    _onScrollEvent: function (actor, event) {
        let direction = event.get_scroll_direction();

        if (direction == Clutter.ScrollDirection.DOWN) {
            this._value = Math.max(0, this._value - SLIDER_SCROLL_STEP);
        }
        else if (direction == Clutter.ScrollDirection.UP) {
            this._value = Math.min(1, this._value + SLIDER_SCROLL_STEP);
        }

        this._slider.queue_repaint();
        this.emit('value-changed', this._value);
    },

    _motionEvent: function(actor, event) {
        let absX, absY;
        [absX, absY] = event.get_coords();
        this._moveHandle(absX, absY);
        return true;
    },

    _moveHandle: function(absX, absY) {
        let relX, relY, sliderX, sliderY;
        [sliderX, sliderY] = this._slider.get_transformed_position();
        relX = absX - sliderX;
        relY = absY - sliderY;

        let width = this._slider.width;
        let handleRadius = this._slider.get_theme_node().get_length('-slider-handle-radius');

        let newvalue;
        if (relX < handleRadius)
            newvalue = 0;
        else if (relX > width - handleRadius)
            newvalue = 1;
        else
            newvalue = (relX - handleRadius) / (width - 2 * handleRadius);
        this._value = newvalue;
        this._slider.queue_repaint();
        this.emit('value-changed', this._value);
    },

    get value() {
        return this._value;
    },

    _onKeyPressEvent: function (actor, event) {
        let key = event.get_key_symbol();
        if (key == Clutter.KEY_Right || key == Clutter.KEY_Left) {
            let delta = key == Clutter.KEY_Right ? 0.1 : -0.1;
            this._value = Math.max(0, Math.min(this._value + delta, 1));
            this._slider.queue_repaint();
            this.emit('value-changed', this._value);
            this.emit('drag-end');
            return true;
        }
        return false;
    }
};

function Switch() {
    this._init.apply(this, arguments);
}

Switch.prototype = {
    _init: function(state) {
        this.actor = new St.Bin({ style_class: 'toggle-switch' ,
                                  accessible_role: Atk.Role.CHECK_BOX});
        // Translators: this MUST be either "toggle-switch-us"
        // (for toggle switches containing the English words
        // "ON" and "OFF") or "toggle-switch-intl" (for toggle
        // switches containing "O" and "|"). Other values will
        // simply result in invisible toggle switches.
        this.actor.add_style_class_name("toggle-switch-us");
        this.setToggleState(state);
    },

    setToggleState: function(state) {
        this.actor.change_style_pseudo_class('checked', state);
        this.state = state;
    },

    toggle: function() {
        this.setToggleState(!this.state);
    }
};

function PopupSwitchMenuItem() {
    this._init.apply(this, arguments);
}

PopupSwitchMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function(text, active, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this.label = new St.Label({ text: text });
        this._statusLabel = new St.Label({ text: '', style_class: 'popup-inactive-menu-item' });

        this._switch = new Switch(active);

        this.addActor(this.label);
        this.addActor(this._statusLabel);

        this._statusBin = new St.Bin({ x_align: St.Align.END });
        this.addActor(this._statusBin, { expand: true, span: -1, align: St.Align.END });
        this._statusBin.child = this._switch.actor;
    },

    setStatus: function(text) {
        if (text != null) {
            this._statusLabel.set_text(text);
        } else {
            this._statusLabel.set_text('');
        }
    },

    activate: function(event) {
        if (this._switch.actor.mapped) {
            this.toggle();
        }

        PopupBaseMenuItem.prototype.activate.call(this, event, true);
    },

    toggle: function() {
        this._switch.toggle();
        this.emit('toggled', this._switch.state);
    },

    get state() {
        return this._switch.state;
    },

    setToggleState: function(state) {
        this._switch.setToggleState(state);
    }
};

function PopupSwitchIconMenuItem() {
    this._init.apply(this, arguments);
}

PopupSwitchIconMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    /**
     * _init:
     * @text (string): text to display in the label
     * @active: boolean to set switch on or off
     * @iconName (string): name of the icon used
     * @iconType (St.IconType): the type of icon (usually #St.IconType.SYMBOLIC
     * or #St.IconType.FULLCOLOR)
     * @params (JSON): parameters to pass to %PopupMenu.PopupBaseMenuItem._init
     */
    _init: function(text, active, iconName, iconType, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this.label = new St.Label({ text: text });
        this._statusLabel = new St.Label({ text: '', style_class: 'popup-inactive-menu-item' });

        this._icon = new St.Icon({ style_class: 'popup-menu-icon',
            icon_name: iconName,
            icon_type: iconType});

        this._switch = new Switch(active);

        this.addActor(this._icon, {span: 0});
        this.addActor(this.label);
        this.addActor(this._statusLabel);

        this._statusBin = new St.Bin({ x_align: St.Align.END });
        this.addActor(this._statusBin, { expand: true, span: -1, align: St.Align.END });
        this._statusBin.child = this._switch.actor;
    },

    /**
     * setIconSymbolicName:
     * @iconName (string): name of the icon
     *
     * Changes the icon to a symbolic icon with name @iconName.
     */
    setIconSymbolicName: function (iconName) {
        this._icon.set_icon_name(iconName);
        this._icon.set_icon_type(St.IconType.SYMBOLIC);
    },

    /**
     * setIconName:
     * @iconName (string): name of the icon
     *
     * Changes the icon to a full color icon with name @iconName.
     */
    setIconName: function (iconName) {
        this._icon.set_icon_name(iconName);
        this._icon.set_icon_type(St.IconType.FULLCOLOR);
    },

    setStatus: function(text) {
        if (text != null) {
            this._statusLabel.set_text(text);
        } else {
            this._statusLabel.set_text('');
        }
    },

    activate: function(event) {
        if (this._switch.actor.mapped) {
            this.toggle();
        }

        PopupBaseMenuItem.prototype.activate.call(this, event, true);
    },

    toggle: function() {
        this._switch.toggle();
        this.emit('toggled', this._switch.state);
    },

    get state() {
        return this._switch.state;
    },

    setToggleState: function(state) {
        this._switch.setToggleState(state);
    }
};

/**
 * #PopupIconMenuItem:
 * @short_description: A menu item with an icon and a text.
 *
 * This is a popup menu item displaying an icon and a text. The icon is
 * displayed to the left of the text. #PopupImageMenuItem is a similar,
 * deprecated item, that displays the icon to the right of the text, which is
 * ugly in most cases. Do not use it. If you think you need to display the icon
 * on the right, make your own menu item (by copy and pasting the code found
 * below) because PopupImageMenuItem is deprecated and may disappear any time.
 */
function PopupIconMenuItem() {
    this._init.apply(this, arguments);
}

PopupIconMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    /**
     * _init:
     * @text (string): text to display in the label
     * @iconName (string): name of the icon used
     * @iconType (St.IconType): the type of icon (usually #St.IconType.SYMBOLIC
     * or #St.IconType.FULLCOLOR)
     * @params (JSON): parameters to pass to %PopupMenu.PopupBaseMenuItem._init
     */
    _init: function (text, iconName, iconType, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this.label = new St.Label({text: text});
        this._icon = new St.Icon({ style_class: 'popup-menu-icon',
            icon_name: iconName,
            icon_type: iconType});
        this.addActor(this._icon, {span: 0});
        this.addActor(this.label);
    },

    /**
     * setIconSymbolicName:
     * @iconName (string): name of the icon
     *
     * Changes the icon to a symbolic icon with name @iconName.
     */
    setIconSymbolicName: function (iconName) {
        this._icon.set_icon_name(iconName);
        this._icon.set_icon_type(St.IconType.SYMBOLIC);
    },

    /**
     * setIconName:
     * @iconName (string): name of the icon
     *
     * Changes the icon to a full color icon with name @iconName.
     */
    setIconName: function (iconName) {
        this._icon.set_icon_name(iconName);
        this._icon.set_icon_type(St.IconType.FULLCOLOR);
    }
}

// Deprecated. Do not use
function PopupImageMenuItem() {
    this._init.apply(this, arguments);
}

PopupImageMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function (text, iconName, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this.label = new St.Label({ text: text });
        this.addActor(this.label);
        this._icon = new St.Icon({ style_class: 'popup-menu-icon' });
        this.addActor(this._icon, { align: St.Align.END });

        this.setIcon(iconName);
    },

    setIcon: function(name) {
        this._icon.icon_name = name;
    }
};

/**
 * #PopupIndicatorMenuItem:
 * @short_description: A menu item with text, ornaments and accel.
 *
 * This is a popup menu item displaying an text, a accel, and a ornament. The ornament
 * is displayed to the left of the text and the accel will be displayed at the end of
 * the item. The default ornament is an icon,  but can be replace for a check button,
 * a radio button or empty.
 */
function PopupIndicatorMenuItem() {
    this._init.apply(this, arguments);
}

PopupIndicatorMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function(text, params) {
        PopupBaseMenuItem.prototype._init.call(this, params);
        this.actor._delegate = this;
        this._displayIcon = false;

        this.label = new St.Label({ text: text });
        this._accel = new St.Label({ x_align: St.Align.END });
        this._ornament = new St.Bin();
        this._icon = new St.Icon({ style_class: 'popup-menu-icon', icon_type: St.IconType.FULLCOLOR });

        this._ornament.child = this._icon;
        this._ornament.child._delegate = this._ornament;
        this.addActor(this._ornament, {span: 0});
        this.addActor(this.label);
        this.addActor(this._accel, { align: St.Align.END });
    },

    setAccel: function(accel) {
        this._accel.set_text(accel);
    },

    haveIcon: function() {
        return ((this._icon)&&((this._icon.icon_name && this._icon.icon_name != "") || (this._icon.gicon)));
    },

    setIconName: function(name) {
        if (this._icon)
            this._icon.icon_name = name;
    },

    setGIcon: function(gicon) {
        if (this._icon)
            this._icon.gicon = gicon;
    },

    setOrnament: function(ornamentType, state) {
        switch (ornamentType) {
        case OrnamentType.CHECK:
            if ((this._ornament.child)&&(!(this._ornament.child._delegate instanceof CheckBox.CheckButton))) {
                this._ornament.child.destroy();
                this._ornament.child = null;
            }
            if (!this._ornament.child) {
                let switchOrn = new CheckBox.CheckButton(state);
                this._ornament.child = switchOrn.actor;
            } else {
                this._ornament.child._delegate.setToggleState(state);
            }
            this._icon = null;
            break;
        case OrnamentType.DOT:
            if ((this._ornament.child)&&(!(this._ornament.child._delegate instanceof RadioButton.RadioBox))) {
                this._ornament.child.destroy();
                this._ornament.child = null;
            }
            if (!this._ornament.child) {
                let radioOrn = new RadioButton.RadioBox(state);
                this._ornament.child = radioOrn.actor;
            } else {
                this._ornament.child._delegate.setToggleState(state);
            }
            this._icon = null;
            break;
        }
    },

    destroy: function() {
        if (this.actor) {
            PopupMenuItem.prototype.destroy.call(this);
            this.actor = null;
        }
    }
};

/**
 * #PopupMenuAbstractItem:
 * @short_description: A class to represent any abstract menu item.
 *
 * This is an abstract class for create a binding between the PopupMenuItem class ,
 * and an abstract representation of a menu item. If you want to create a cinnamon
 * menu structure, you need to inherit from this class and implement the functions
 * getItemById and handleEvent. All instances of this class need to have a unique
 * id to represent a menu item.
 */
function PopupMenuAbstractItem() {
    throw new TypeError('Trying to instantiate abstract class PopupMenuAbstractItem');
}

PopupMenuAbstractItem.prototype = {
    _init: function(id, childrenIds, params) {
        this._id = id;
        this._childrenIds = childrenIds;
        if (!this._childrenIds)
            this._childrenIds = new Array();

        /*this._shellMenuSignalsHandlers = null;
        this._internalSignalsHandlers = new SignalManager.SignalManager(this);
        this._externalSignalsHandlers = new SignalManager.SignalManager(this);*/

        this._internalSignalsHandlers = new Array();
        this._externalSignalsHandlers = new Array();
        this._shellItemSignalsHandlers = null;
        this._shellMenuSignalsHandlers = null;

        this.shellItem = null;
        this.parent = null;

        // Properties
        params = Params.parse (params, { label: "",
                                         accel: "",
                                         sensitive: true,
                                         visible: true,
                                         toggleType: "",
                                         toggleState: false,
                                         iconName: "",
                                         iconData: null,
                                         action:"",
                                         paramType: "", // This is a variant for GTK, better remove it?
                                         type: FactoryClassTypes.MenuItemClass
                                       });
        this._label = params.label;
        this._accel = params.accel;
        this._sensitive = params.sensitive;
        this._visible = params.visible;
        this._toggleType = params.toggleType;
        this._toggleState = params.toggleState;
        this._iconName = params.iconName;
        this._iconData = params.iconData;
        this._type = params.type;
        this._action = params.action;
        this._paramType = params.paramType;
    },

    getItemById: function(id) {throw new Error('Trying to use abstract function getItemById');},
    handleEvent: function(event, params) {throw new Error('Trying to use abstract function handleEvent');},
    //FIXME: Will be intresting this function? We don't use it anyway...
    //is_root: function() {throw new Error('Trying to use abstract function is_root');},

    isVisible: function() {
        return this._visible;
    },

    setVisible: function(visible) {
        if (this._visible != visible) {
            this._visible = visible;
            this._updateVisible();
        }
    },

    isSensitive: function() {
        return this._sensitive;
    },

    setSensitive: function(sensitive) {
        if (this._sensitive != sensitive) {
            this._sensitive = sensitive;
            this._updateSensitive();
        }
    },

    getLabel: function() {
        return this._label;
    },

    setLabel: function(label) {
        if (this._label != label) {
            this._label = label;
            this._updateLabel();
        }
    },

    getAction: function() {
        return this._action;
    },

    setAction: function(action) {
        if (this._action != action) {
            this._action = action;
        }
    },

    getParamType: function() {
        return this._paramType;
    },

    setParamType: function(paramType) {
        if (this._paramType != paramType) {
            this._paramType = paramType;
        }
    },

    getFactoryType: function() {
        return this._type;
    },

    setFactoryType: function(type) {
        if ((type) && (this._type != type)) {
            this._type = type;
            this._updateType();
        }
    },

    getIconName: function() {
        return this._iconName;
    },

    setIconName: function(iconName) {
        if (this._iconName != iconName) {
            this._iconName = iconName;
            this._updateImage();
        }
    },

    getGdkIcon: function() {
        return this._iconData;
    },

    setGdkIcon: function(iconData) {
        if (this._iconData != iconData) {
            this._iconData = iconData;
            this._updateImage();
        }
    },

    getToggleType: function() {
        return this._toggleType;
    },

    setToggleType: function(toggleType) {
        if (this._toggleType != toggleType) {
            this._toggleType = toggleType;
            this._updateOrnament();
        }
    },

    getToggleState: function() {
        return this._toggleState;
    },

    setToggleState: function(toggleState) {
        if (this._toggleState != toggleState) {
            this._toggleState = toggleState;
            this._updateOrnament();
        }
    },

    getAccel: function() {
        return this._accel;
    },

    setAccel: function(accel) {
        if (this._accel != accel) {
            this._accel = accel;
            this._updateAccel();
        }
    },

    setShellItem: function(shellItem, handlers) {
        if (this.shellItem != shellItem) {
            if (this.shellItem) {
                // FIXME: This create problems, why?
                //this.shellItem.destroy();
                global.logWarning("Attempt to override a shellItem, so we automatically destroy our original shellItem.");
            }
            this.shellItem = shellItem;

            if (this.shellItem) {
                // Initialize our state
                this._updateLabel();
                this._updateOrnament();
                this._updateAccel();
                this._updateImage();
                this._updateVisible();
                this._updateSensitive();

                /*for (let signal in handlers) {
                    this._internalSignalsHandlers.connect(this, signal, handlers[signal]);
                }*/
                this._connectAndSaveId(this, handlers, this._internalSignalsHandlers);

                this._shellItemSignalsHandlers = this._connectAndSaveId(this.shellItem, {
                    'activate':  Lang.bind(this, this._onActivate),
                    'destroy' :  Lang.bind(this, this._onShellItemDestroyed)
                });
                /*this._internalSignalsHandlers.connect(this.shellItem, 'activate', this._onActivate);
                this._internalSignalsHandlers.connect(this.shellItem, 'destroy', this._onShellItemDestroyed);*/

                if (this.shellItem.menu) {
                    /*this._shellMenuSignalsHandlers = new SignalManager.SignalManager(this);
                    this._shellMenuSignalsHandlers.connect(this.shellItem.menu, 'open-state-changed', this._onOpenStateChanged);
                    this._shellMenuSignalsHandlers.connect(this.shellItem.menu, 'destroy', this._onShellMenuDestroyed);*/
                    this._shellMenuSignalsHandlers = this._connectAndSaveId(this.shellItem.menu, {
                        'open-state-changed': Lang.bind(this, this._onOpenStateChanged),
                        'destroy'           : Lang.bind(this, this._onShellMenuDestroyed)
                    });
                } else {
                    //this._internalSignalsHandlers.connect(this.shellItem, 'open-state-changed', this._onOpenStateChanged);
                    this._connectAndSaveId(this.shellItem, {
                        'open-state-changed': Lang.bind(this, this._onOpenStateChanged),
                    }, this._shellItemSignalsHandlers);
                }
            }
        }
    },

    _updateLabel: function() {
        if ((this.shellItem)&&(this.shellItem.label)) {
            let label = this.getLabel();
            // The separator item might not even have a hidden label
            if (this.shellItem.label)
                this.shellItem.label.set_text(label);
        }
    },

    _updateOrnament: function() {
        // Separators and alike might not have gotten the setOrnament function
        if ((this.shellItem)&&(this.shellItem.setOrnament)) {
            if (this.getToggleType() == "checkmark") {
                this.shellItem.setOrnament(OrnamentType.CHECK, this.getToggleState());
            } else if (this.getToggleType() == "radio") {
                this.shellItem.setOrnament(OrnamentType.DOT, this.getToggleState());
            } else {
                this.shellItem.setOrnament(OrnamentType.NONE);
            }
        }
    },

    _updateAccel: function() {
        if ((this.shellItem)&&(this.shellItem._accel)) {
            let accel = this.getAccel();
            if (accel) {
                this.shellItem._accel.set_text(accel);
            }
        }
    },

    _updateImage: function() {
        // Might be missing on submenus / separators
        if ((this.shellItem)&&(this.shellItem._icon)) {
            let iconName = this.getIconName();
            if (iconName) {
                if (this.shellItem.setIconName)
                    this.shellItem.setIconName(iconName);
                else if (this.shellItem._icon) {
                    this.shellItem._icon.icon_name = iconName;
                    this.shellItem._icon.show();
                }
            } else {
                let gicon = this.getGdkIcon();
                if (gicon) {
                    if (this.shellItem.setGIcon)
                        this.shellItem.setGIcon(gicon);
                    else if (this.shellItem._icon) {
                        this.shellItem._icon.gicon = gicon;
                        this.shellItem._icon.show();
                    }
                }
            }
        }
    },

    _updateVisible: function() {
        if (this.shellItem) {
            this.shellItem.actor.visible = this.isVisible();
        }
    },

    _updateSensitive: function() {
        if ((this.shellItem)&&(this.shellItem.setSensitive)) {
            this.shellItem.setSensitive(this.isSensitive());
        }
    },

    _updateType: function() {
        this.emit('type-changed');
    },

    getShellItem: function() {
        return this.shellItem;
    },

    getId: function() {
        return this._id;
    },

    getChildrenIds: function() {
        // Clone it!
        return this._childrenIds.concat();
    },

    getChildren: function() {
        return this._childrenIds.map(function(child_id) {
            return this.getItemById(child_id);
        }, this);
    },

    getParent: function() {
        return this.parent;
    },

    setParent: function(parent) {
        this.parent = parent;
    },

    addChild: function(pos, child_id) {
        let factoryItem = this.getItemById(child_id);
        if (factoryItem) {
            // If our item is previusly assigned, so destroy first the shell item.
            factoryItem.destroyShellItem();
            factoryItem.setParent(this);
            this._childrenIds.splice(pos, 0, child_id);
            this.emit('child-added', factoryItem, pos);
        }
    },

    removeChild: function(child_id) {
        // Find it
        let pos = -1;
        for (let i = 0; i < this._childrenIds.length; ++i) {
            if (this._childrenIds[i] == child_id) {
                pos = i;
                break;
            }
        }

        if (pos < 0) {
            global.logError("Trying to remove child which doesn't exist");
        } else {
            this._childrenIds.splice(pos, 1);
            let factoryItem = this.getItemById(child_id);
            if (factoryItem) {
                let shellItem = factoryItem.getShellItem();
                this._destroyShellItem(shellItem);
                factoryItem.setParent(null);
                this.emit('child-removed', factoryItem);
            }
        }
        if (this._childrenIds.length == 0) {
            this.emit('childs-empty');
        }
    },

    moveChild: function(child_id, newpos) {
        // Find the old position
        let oldpos = -1;
        for (let i = 0; i < this._childrenIds.length; ++i) {
            if (this._childrenIds[i] == child_id) {
                oldpos = i;
                break;
            }
        }

        if (oldpos < 0) {
            global.logError("Tried to move child which wasn't in the list");
            return;
        }

        if (oldpos != newpos) {
            this._childrenIds.splice(oldpos, 1);
            this._childrenIds.splice(newpos, 0, child_id);
            this.emit('child-moved', this.getItemById(child_id), oldpos, newpos);
        }
    },

    // handlers = { "signal": handler }
    connectAndRemoveOnDestroy: function(handlers) {
        /*for (let signal in handlers) {
            this._externalSignalsHandlers.connect(this, signal, handlers[signal]);
        }*/
        this._connectAndSaveId(this, handlers, this._externalSignalsHandlers);
    },

    destroyShellItem: function() {
        this._destroyShellItem(this.shellItem);
    },

    // We try to not crash cinnamon if a shellItem will be destroyed and has the focus,
    // then we are moving the focus to the source actor.
    _destroyShellItem: function(shellItem) {
        if (shellItem) {
            let focus = global.stage.key_focus;
            if (shellItem.close)
                shellItem.close();
            if (shellItem.menu)
                shellItem.menu.close();
            if (focus && shellItem.actor && shellItem.actor.contains(focus)) {
                if (shellItem.sourceActor)
                    shellItem.sourceActor.grab_key_focus();
                else if ((shellItem.menu)&&(shellItem.menu.sourceActor))
                    shellItem.menu.sourceActor.grab_key_focus();
                else
                    global.stage.set_key_focus(null);
            }
            shellItem.destroy();
        }
    },

    // handlers = { "signal": handler }
    _connectAndSaveId: function(target, handlers , idArray) {
        idArray = typeof idArray != 'undefined' ? idArray : [];
        for (let signal in handlers) {
            idArray.push(target.connect(signal, handlers[signal]));
        }
        return idArray;
    },

    _disconnectSignals: function(obj, signals_handlers) {
        if ((obj)&&(signals_handlers)) {
            for (let pos in signals_handlers)
                obj.disconnect(signals_handlers[pos]);
        }
    },

    _onActivate: function(shellItem, event, keepMenu) {
        this.handleEvent("clicked");
    },

    _onOpenStateChanged: function(menu, open) {
        if (open) {
            this.handleEvent("opened");
        } else {
            this.handleEvent("closed");
        }
    },

    _onShellItemDestroyed: function(shellItem) {
        if ((this.shellItem)&&(this.shellItem == shellItem)) {
            this.shellItem = null;
            /*if (this._internalSignalsHandlers) {
                this._internalSignalsHandlers.disconnectAllSignals();
            }*/
            if (this._internalSignalsHandlers) {
                this._disconnectSignals(this, this._internalSignalsHandlers);
                this._internalSignalsHandlers = [];
            }
            if (this._shellItemSignalsHandlers) {
                this._disconnectSignals(shellItem, this._shellItemSignalsHandlers);
                this._shellItemSignalsHandlers = null;
            }
        } else if (this.shellItem) {
            global.logError("We are not connected with " + shellItem);
        } else {
            global.logWarning("We are not connected with any shellItem");
        }
    },

    _onShellMenuDestroyed: function(shellMenu) {
        /*if (this._shellMenuSignalsHandlers) {
            this._shellMenuSignalsHandlers.disconnectAllSignals();
            this._shellMenuSignalsHandlers = null;
        }*/
        if (this._shellMenuSignalsHandlers) {
            this._disconnectSignals(shellMenu, this._shellMenuSignalsHandlers);
            this._shellMenuSignalsHandlers = null;
        }
    },

    destroy: function() {
        if (this._externalSignalsHandlers) {
            // Emit the destroy signal first, to allow the external listener know about it,
            // then, disconnect the listener handler.
            this.emit("destroy");
            this.destroyShellItem();
            this.shellItem = null;
            //this._externalSignalsHandlers.disconnectAllSignals();
            this._disconnectSignals(this, this._externalSignalsHandlers);
            this._externalSignalsHandlers = null;
            this._internalSignalsHandlers = null;
        }
    }
};
Signals.addSignalMethods(PopupMenuAbstractItem.prototype);

/**
 * #PopupMenuBase
 * @short_description: The base class of all popup menus
 * @sourceActor (St.Widget): The actor that owns the popup menu
 * @box (St.BoxLayout): The box containing the popup menu widgets.
 * @isOpen (boolean): Whether the popup menu is open.
 * @blockSourceEvents (boolean): If set, we don't send events (including
 * crossing events) to the source actor for the menu which causes its prelight
 * state to freeze
 *
 * @passEvents (boolean): Can be set while a menu is up to let all events
 * through without special menu handling useful for scrollbars in menus, and
 * probably not otherwise.
 *
 * @firstMenuItem (PopupMenu.PopupBaseMenuItem): The first item in the popup
 * menu
 * @numMenuItems (int): The number of items in the popup menu.
 *
 * This is a base popup menu class for more sophisticated popup menus to
 * inherit. This cannot be instantiated.
 */
function PopupMenuBase() {
    throw new TypeError('Trying to instantiate abstract class PopupMenuBase');
}

PopupMenuBase.prototype = {
    /**
     * _init:
     * @sourceActor (St.Widget): the actor that owns the popup menu
     * @styleClass (string): (optional) the style class of the popup menu
     */
    _init: function(sourceActor, styleClass) {
        this.sourceActor = sourceActor;

        this._signals = new SignalManager.SignalManager(null);
        if (styleClass !== undefined) {
            this.box = new St.BoxLayout({ style_class: styleClass,
                                          vertical: true });
        } else {
            this.box = new St.BoxLayout({ vertical: true });
        }
        this._signals.connect_after(this.box, 'queue-relayout', Lang.bind(this, this._menuQueueRelayout));
        this.length = 0;

        this.isOpen = false;
        this.blockSourceEvents = false;
        this.passEvents = false;

        this._activeMenuItem = null;
        this._childMenus = [];
    },

    /**
     * addAction:
     * @title (string): the text to display on the item
     * @callback (function): the function to call when clicked
     *
     * Adds a #PopupMenuItem with label @title to the menu. When the item is
     * clicked, @callback will be called.
     *
     * Returns (PopupMenu.PopupMenuItem): the menu item created.
     */
    addAction: function(title, callback) {
        let menuItem = new PopupMenuItem(title);
        this.addMenuItem(menuItem);
        this._signals.connect(menuItem, 'activate', Lang.bind(this, function (menuItem, event) {
            callback(event);
        }));

        return menuItem;
    },

    /**
     * addSettingsAction:
     * @title (string): the text to display on the item
     * @module (string): the module to launch
     *
     * Adds a #PopupMenuItem with label @title to the menu. When the item is
     * clicked, Cinnamon Settings will be launched with the module @module
     * activated.
     *
     * Returns (PopupMenu.PopupMenuItem): the menu item created.
     */
    addSettingsAction: function(title, module) {
        let menuItem = this.addAction(title, function() {
                           Util.spawnCommandLine("cinnamon-settings " + module);
                       });
        return menuItem;
    },

    /**
     * addCommandlineAction:
     * @title (string): the text to display on the item
     * @cmd (string): the command to call
     *
     * Adds a #PopupMenuItem with label @title to the menu. When the item is
     * clicked, the command @cmd will be executed.
     *
     * Returns (PopupMenu.PopupMenuItem): the menu item created.
     */
    addCommandlineAction: function(title, cmd) {
        let menuItem = this.addAction(title, function() {
                           Util.spawnCommandLine(cmd);
                       });
        return menuItem
    },

    /**
     * isChildMenu:
     * @menu (PopupMenu.PopupMenuBase): the menu of interest
     *
     * Returns: whether @menu is a submenu of this menu.
     */
    isChildMenu: function(menu) {
        return this._childMenus.indexOf(menu) != -1;
    },

    /**
     * addChildMenu:
     * @menu (PopupMenu.PopupMenuBase): the menu of interest
     *
     * Makes @menu a submenu of this menu.
     */
    addChildMenu: function(menu) {
        if (this.isChildMenu(menu))
            return;

        this._childMenus.push(menu);
        /**
         * SIGNAL:child-menu-added
         * @menu (PopupMenu.PopupMenuBase): The menu added
         *
         * Emitted when an menu is added as a submenu.
         */
        this.emit('child-menu-added', menu);
    },

    /**
     * removeChildMenu:
     * @menu (PopupMenuBase): the menu of interest
     *
     * Removes @menu from the current menu if it is a child.
     */
    removeChildMenu: function(menu) {
        let index = this._childMenus.indexOf(menu);

        if (index == -1)
            return;

        this._childMenus.splice(index, 1);
        this.emit('child-menu-removed', menu);
        /**
         * SIGNAL:child-menu-removed
         * @menu (PopupMenu.PopupMenuBase): The menu removed
         *
         * Emitted when an submenu is removed.
         */
    },

    _connectSubMenuSignals: function(object, menu) {
        /**
         * SIGNAL:activate
         * @menuItem (PopupBaseMenuItem): the item activated
         * @keepMenu (boolean): whether the menu should remain opened
         *
         * Emitted when an item of the menu is activated.
         */

        /**
         * SIGNAL:active-changed
         * @menuItem (PopupBaseMenuItem): the current active item (possibly null)
         *
         * Emitted when the active item of menu is changed.
         */

        this._signals.connect(menu, 'activate', Lang.bind(this, function(submenu, submenuItem, keepMenu) {
            this.emit('activate', submenuItem, keepMenu);
            if (!keepMenu){
                this.close(true);
            }
        }));
        this._signals.connect(menu, 'active-changed', Lang.bind(this, function(submenu, submenuItem) {
            if (this._activeMenuItem && this._activeMenuItem != submenuItem)
                this._activeMenuItem.setActive(false);
            this._activeMenuItem = submenuItem;
            this.emit('active-changed', submenuItem);
        }));
    },

    _connectItemSignals: function(menuItem) {
        this._signals.connect(menuItem, 'active-changed', Lang.bind(this, function (menuItem, active) {
            if (active && this._activeMenuItem != menuItem) {
                if (this._activeMenuItem)
                    this._activeMenuItem.setActive(false);
                this._activeMenuItem = menuItem;
                this.emit('active-changed', menuItem);
            } else if (!active && this._activeMenuItem == menuItem) {
                this._activeMenuItem = null;
                this.emit('active-changed', null);
            }
        }));
        this._signals.connect(menuItem, 'sensitive-changed', Lang.bind(this, function(menuItem, sensitive) {
            if (!sensitive && this._activeMenuItem == menuItem) {
                if (!this.actor.navigate_focus(menuItem.actor,
                                               Gtk.DirectionType.TAB_FORWARD,
                                               true))
                    this.actor.grab_key_focus();
            } else if (sensitive && this._activeMenuItem == null) {
                if (global.stage.get_key_focus() == this.actor)
                    menuItem.actor.grab_key_focus();
            }
        }));
        this._signals.connect(menuItem, 'activate', Lang.bind(this, function (menuItem, event, keepMenu) {
            this.emit('activate', menuItem, keepMenu);
            if (!keepMenu){
                this.close(true);
            }
        }));
        this._signals.connect(menuItem, 'destroy', Lang.bind(this, function(emitter) {
            this._signals.disconnect('activate', menuItem);
            this._signals.disconnect('active-changed', menuItem);
            this._signals.disconnect('sensitive-changed', menuItem);
            if (menuItem.menu) {
                this._signals.disconnect('activate', menuItem.menu);
                this._signals.disconnect('active-changed', menuItem.menu);
                this._signals.disconnect('open-state-changed', this);
            }
            if (menuItem == this._activeMenuItem)
                this._activeMenuItem = null;
            this.length--;
        }));
    },

    _updateSeparatorVisibility: function(menuItem) {
        let children = this.box.get_children();

        let index = children.indexOf(menuItem.actor);

        if (index < 0)
            return;

        let childBeforeIndex = index - 1;

        while (childBeforeIndex >= 0 && !children[childBeforeIndex].visible)
            childBeforeIndex--;

        if (childBeforeIndex < 0
            || children[childBeforeIndex].maybeGet("_delegate") instanceof PopupSeparatorMenuItem) {
            menuItem.actor.hide();
            return;
        }

        let childAfterIndex = index + 1;

        while (childAfterIndex < children.length && !children[childAfterIndex].visible)
            childAfterIndex++;

        if (childAfterIndex >= children.length
            || children[childAfterIndex]._delegate instanceof PopupSeparatorMenuItem) {
            menuItem.actor.hide();
            return;
        }

        menuItem.actor.show();
    },

    /**
     * addMenuItem:
     * @menuItem (PopupMenu.PopupBaseMenuItem): the item to include (can also
     * be a #PopupMenuSection)
     * @position (int): (optional) position to add the item at (empty for end
     * of menu)
     *
     * Adds the @menuItem to the menu.
     */
    addMenuItem: function(menuItem, position) {
        let before_item = null;
        if (position == undefined) {
            this.box.add(menuItem.actor);
        } else {
            let items = this._getMenuItems();
            if (position < items.length) {
                before_item = items[position].actor;
                this.box.insert_child_below(menuItem.actor, before_item);
            } else
                this.box.add(menuItem.actor);
        }
        if (menuItem instanceof PopupMenuSection) {
            this._connectSubMenuSignals(menuItem, menuItem);
            this._signals.connect(menuItem, 'destroy', Lang.bind(this, function() {
                this._signals.disconnect('activate', menuItem);
                this._signals.disconnect('active-changed', menuItem);

                this.length--;
            }));
        } else if (menuItem instanceof PopupSubMenuMenuItem) {
            if (before_item == null)
                this.box.add(menuItem.menu.actor);
            else
                this.box.insert_child_below(menuItem.menu.actor, before_item);
            this._connectSubMenuSignals(menuItem, menuItem.menu);
            this._connectItemSignals(menuItem);
            this._signals.connect(this, 'open-state-changed', function(self, open) {
                if (!open)
                    menuItem.menu.close(false);
            }, this);
        } else if (menuItem instanceof PopupSeparatorMenuItem) {
            this._connectItemSignals(menuItem);

            // updateSeparatorVisibility needs to get called any time the
            // separator's adjacent siblings change visibility or position.
            // open-state-changed isn't exactly that, but doing it in more
            // precise ways would require a lot more bookkeeping.
            this._signals.connect(this, 'open-state-changed', Lang.bind(this, function() { this._updateSeparatorVisibility(menuItem); }));
            this._signals.connect(this.box, 'allocation-changed', Lang.bind(this, function() { this._updateSeparatorVisibility(menuItem); }));
        } else if (menuItem instanceof PopupBaseMenuItem)
            this._connectItemSignals(menuItem);
        else
            throw TypeError("Invalid argument to PopupMenuBase.addMenuItem()");

        this.length++;
    },

    /**
     * getColumnWidths:
     *
     * Gets the width of each column this thing has. In popup menus, everything
     * is put into columns, and the columns of all items align. This is used
     * internally and shouldn't be fiddled with unless you are implementing
     * other popup menu items.
     */
    getColumnWidths: function() {
        let columnWidths = [];
        let items = this.box.get_children();
        for (let i = 0; i < items.length; i++) {
            if (!items[i].visible)
                continue;
            if (items[i].maybeGet("_delegate") instanceof PopupBaseMenuItem || items[i].maybeGet("_delegate") instanceof PopupMenuBase) {
                let itemColumnWidths = items[i]._delegate.getColumnWidths();
                for (let j = 0; j < itemColumnWidths.length; j++) {
                    if (j >= columnWidths.length || itemColumnWidths[j] > columnWidths[j])
                        columnWidths[j] = itemColumnWidths[j];
                }
            }
        }
        return columnWidths;
    },

    /**
     * setColumnWidths:
     * @widths (array): the widths of each column
     *
     * Sets the widths of each column according to @widths so that things can
     * align.
     */
    setColumnWidths: function(widths) {
        let items = this.box.get_children();
        for (let i = 0; i < items.length; i++) {
            if (items[i].maybeGet("_delegate") instanceof PopupBaseMenuItem || items[i].maybeGet("_delegate") instanceof PopupMenuBase)
                items[i]._delegate.setColumnWidths(widths);
        }
    },

    // Because of the above column-width funniness, we need to do a
    // queue-relayout on every item whenever the menu itself changes
    // size, to force clutter to drop its cached size requests. (The
    // menuitems will in turn call queue_relayout on their parent, the
    // menu, but that call will be a no-op since the menu already
    // has a relayout queued, so we won't get stuck in a loop.
    _menuQueueRelayout: function() {
        this.box.get_children().map(function (actor) { actor.queue_relayout(); });
    },

    addActor: function(actor) {
        this.box.add(actor);
    },

    _getMenuItems: function() {
        return this.box.get_children().filter(function(actor) {
            return (actor._delegate !== undefined
                && (actor._delegate instanceof PopupBaseMenuItem || actor._delegate instanceof PopupMenuSection));
        }).map(function (actor) {
            return actor._delegate;
        });
    },

    get firstMenuItem() {
        let items = this._getMenuItems();
        if (items.length)
            return items[0];
        else
            return null;
    },

    get numMenuItems() {
        return this._getMenuItems().length;
    },

    /**
     * removeAll:
     *
     * Clears everything inside the menu.
     */
    removeAll: function() {
        let children = this._getMenuItems();
        for (let i = 0; i < children.length; i++) {
            let item = children[i];
            item.destroy();
        }
    },

    /**
     * toggle:
     *
     * Toggles the open/close state of the menu.
     */
    toggle: function() {
        if (this.isOpen)
            this.close(true);
        else
            this.open(true);
    },

    /**
     * toggle_with_options:
     * @animate (boolean): whether or not to animate the open/close.
     * @onComplete (function): the function to call when the toggle action
     * completes.
     *
     * Toggles the open/close state of the menu with extra parameters
     */
    toggle_with_options: function (animate, onComplete) {
        if (this.isOpen) {
            this.close(animate, onComplete);
        } else {
            this.open(animate, onComplete);
        }
    },

    /**
     * destroy:
     *
     * Destroys the popup menu completely.
     */
    destroy: function() {
        this._signals.disconnectAllSignals();
        this.removeAll();
        this.actor.destroy();
        /**
         * SIGNAL:destroy
         *
         * Emitted when the menu is destroyed.
         */
        this.emit('destroy');
    }
};
Signals.addSignalMethods(PopupMenuBase.prototype);

/**
 * #PopupMenu
 * @short_description: An actual popup menu
 * @actor (St.Bin): The actor of the popup menu.
 * @animating (boolean): Whether the popup menu is currently performing the
 * open/close animation.
 * @slidePosition (number): Position relative to the @sourceActor of the menu upon which the menu will be centered
 * (if possible). If -1, the menu will be centered on the @sourceActor. See %shiftToPosition for more details.
 */
function PopupMenu() {
    // orientation used to be passed as the third argument, but now we only have 2 args so if we get 3, we assume
    // that it's old code and only grab the ones we need
    if (arguments.length > 2) {
        this._init(arguments[0], arguments[2]);
    }
    else {
        this._init.apply(this, arguments);
    }
}

PopupMenu.prototype = {
    __proto__: PopupMenuBase.prototype,

    /**
     * _init:
     * @sourceActor (St.Widget): the actor that owns the popup menu
     * @orientation (St.Side): the side of the menu that will be attached to @sourceActor. See %setOrientation() for details
     */
    _init: function(sourceActor, orientation) {
        PopupMenuBase.prototype._init.call (this, sourceActor, 'popup-menu-content');

        this.paint_count = 0;
        this.animating = false;
        this._slidePosition = -1;

        this.actor = new St.Bin({ style_class: 'menu',
                                  important: true });
        this.actor._delegate = this;
        this._signals.connect(this.actor, 'key-press-event', Lang.bind(this, this._onKeyPressEvent));

        this.setOrientation(orientation);

        this._boxWrapper = new Cinnamon.GenericContainer();
        this._signals.connect(this._boxWrapper, 'get-preferred-width', Lang.bind(this, this._boxGetPreferredWidth));
        this._signals.connect(this._boxWrapper, 'get-preferred-height', Lang.bind(this, this._boxGetPreferredHeight));
        this._signals.connect(this._boxWrapper, 'allocate', Lang.bind(this, this._boxAllocate));
        this.actor.set_child(this._boxWrapper);
        this._boxWrapper.add_actor(this.box);

        global.focus_manager.add_group(this.actor);
        this.actor.reactive = true;
    },

    /**
     * setArrowSide:
     * @side (St.Side): The new side of the menu
     *
     * Sets the orientation of the @sourceActor with respect to the menu. This function is deprecated and kept
     * for compatibility with older code. Please use %setOrientation instead.
     */
    setArrowSide: function(side) {
        this.setOrientation(side);
    },

    /**
     * setOrientation:
     * @orientation (St.Side): The new orientation of the menu
     *
     * Sets the orientation of the @sourceActor with respect to the menu. For example, if you use St.Side.TOP,
     * the menu will try to place itself below the @sourcActor unless there is not enough room for it.
     */
    setOrientation: function(orientation) {
        this._orientation = orientation;
    },

    /**
     * setCustomStyleClass:
     * @className (string): the custom class name to add
     *
     * Adds a custom class name to the menu which allows it to be styled separately from other menus.
     */
    setCustomStyleClass: function(className) {
        this.customStyleClass = className;
        if (this.actor.get_style_class_name()) {
            this.actor.set_style_class_name(this.actor.get_style_class_name() + "" + className)
        } else {
            this.actor.set_style_class_name(className);
        }
    },

    /**
     * setSourceAlignment:
     * @alignment (real): the position of the arrow relative to the source
     * actor.
     *
     * Since the boxpointer was removed from the menu, this function now does nothing. Please do not use this
     * function in new code.
     */
    setSourceAlignment: function(alignment) {},

    /**
     * open:
     * @animate (boolean): whether to animate the open effect or not
     *
     * Opens the popup menu
     */
    open: function(animate) {
        if (this.isOpen)
            return;

        Main.popup_rendering_actor = this.actor;

        this.setMaxHeight();

        /* I'd rather this be inside the active tween scope as an onUpdate param, but how do you modify
         * a tweens own parameters during said tweening? */
        this._breadth = 0;

        this.isOpen = true;
        if (global.menuStackLength == undefined)
            global.menuStackLength = 0;
        global.menuStackLength += 1;

        this._signals.connect(this.actor, "paint", Lang.bind(this, this.on_paint));

        /* If the sourceActor of our menu is located on a panel or from the panel itself, we want to position it just
           below the panel actors. This prevents some cases where the menu will otherwise partially overlap the panel
           and look strange visually */
        let parentPanel = null;
        if (this.sourceActor.get_name() == "panel") {
            parentPanel = this.sourceActor;
        } else {
            let parent = this.sourceActor.get_parent();
            while (parent) {
                if (parent.get_name() == "panel") {
                    parentPanel = parent;
                    break;
                }
                parent = parent.get_parent();
            }
        }

        if (parentPanel) {
            let monitor = Main.layoutManager.findMonitorForActor(this.sourceActor)
            let panels = Main.panelManager.getPanelsInMonitor(Main.layoutManager.monitors.indexOf(monitor));
            let children = Main.uiGroup.get_children();
            let panelIndex = children.indexOf(parentPanel);

            for (let i = 0; i < panels.length; i++) {
                let idx = children.indexOf(panels[i].actor);
                if (idx < panelIndex)
                    panelIndex = idx;
            }

            Main.uiGroup.set_child_below_sibling(this.actor, Main.uiGroup.get_child_at_index(panelIndex));
        } else {
            Main.uiGroup.set_child_above_sibling(this.actor, null);
        }

        if (animate && global.settings.get_boolean("desktop-effects-on-menus")) {
            this.animating = true;
            this.actor.show();

            let tweenParams = {
                transition: "easeOutQuad",
                time: .15,
                onUpdate: Lang.bind(this, function(dest) {
                    let clipY = 0;
                    let clipX = 0;
                    let xUpdate = 0;
                    let yUpdate = 0;

                    switch (this._orientation) {
                        case St.Side.TOP:
                        case St.Side.BOTTOM:
                            clipY = dest - this.actor.y;

                            if (this.actor.width != this._breadth) {
                                [xUpdate, yUpdate] = this._calculatePosition();
                                this.actor.x = xUpdate;
                                this._breadth = this.actor.width;
                            }

                            break;
                        case St.Side.LEFT:
                        case St.Side.RIGHT:
                            clipX = dest - this.actor.x;

                            if (this.actor.height != this._breadth) {
                                [xUpdate, yUpdate] = this._calculatePosition();
                                this.actor.y = yUpdate;
                                this._breadth = this.actor.height;
                            }

                            break;
                    }

                    this.actor.set_clip(clipX, clipY, this.actor.width, this.actor.height);
                }),
                onCompleteScope: this,
                onComplete: function() {
                    this.animating = false;
                    this.actor.remove_clip();
                }
            }

            let [xPos, yPos] = this._calculatePosition();

            switch (this._orientation) {
                case St.Side.TOP:
                case St.Side.BOTTOM:
                    this.actor.x = xPos;
                    this._breadth = this.actor.width;
                    tweenParams["y"] = yPos;
                    tweenParams["onUpdateParams"] = [yPos];
                    if (this.sideFlipped)
                        this.actor.y = yPos + this.actor.height;
                    else
                        this.actor.y = yPos - this.actor.height;
                    break;
                case St.Side.LEFT:
                case St.Side.RIGHT:
                    this.actor.y = yPos;
                    this._breadth = this.actor.height;
                    tweenParams["x"] = xPos;
                    tweenParams["onUpdateParams"] = [xPos];
                    if (this.sideFlipped)
                        this.actor.x = xPos + this.actor.width;
                    else
                        this.actor.x = xPos - this.actor.width;
                    break;
            }

            Tweener.addTween(this.actor, tweenParams);
        } else {
            this.animating = false;
            this.actor.show();
        }

        this.emit('open-state-changed', true);
    },

    /**
     * close:
     * @animate (boolean): whether to animate the close effect or not
     *
     * Closes the popup menu.
     */
    close: function(animate) {
        if (!this.isOpen)
            return;

        this.isOpen = false;
        global.menuStackLength -= 1;

        Main.panelManager.updatePanelsVisibility();

        if (this._activeMenuItem)
            this._activeMenuItem.setActive(false);

        if (animate && global.settings.get_boolean("desktop-effects-on-menus")) {
            this.animating = true;
            let tweenParams = {
                transition: "easeInQuad",
                time: .15,
                onUpdate: Lang.bind(this, function(dest) {
                        let clipY = 0;
                        let clipX = 0;
                        switch (this._orientation) {
                            case St.Side.TOP:
                            case St.Side.BOTTOM:
                                clipY = dest - this.actor.y;
                                break;
                            case St.Side.LEFT:
                            case St.Side.RIGHT:
                                clipX = dest - this.actor.x;
                                break;
                        }
                        this.actor.set_clip(clipX, clipY, this.actor.width, this.actor.height);
                    }),
                onCompleteScope: this,
                onComplete: function() {
                    this.animating = false;
                    this.actor.hide();
                    this.actor.remove_clip();
                }
            }

            switch (this._orientation) {
                case St.Side.TOP:
                case St.Side.BOTTOM:
                    let yPos = this.actor.y;
                    tweenParams["onUpdateParams"] = [yPos];
                    if (this.sideFlipped)
                        tweenParams["y"] = this.actor.y + this.actor.height;
                    else
                        tweenParams["y"] = this.actor.y - this.actor.height;
                    break;
                case St.Side.LEFT:
                case St.Side.RIGHT:
                    let xPos = this.actor.x;
                    tweenParams["onUpdateParams"] = [xPos];
                    if (this.sideFlipped)
                        tweenParams["x"] = this.actor.x + this.actor.width;
                    else
                        tweenParams["x"] = this.actor.x - this.actor.width;
                    break;
            }

            Tweener.addTween(this.actor, tweenParams);
        }
        else {
            this.animating = false;
            this.actor.hide();
        }
        this.emit('open-state-changed', false);
    },

    /**
     * shiftToPosition:
     * @slidePosition (number): Position relative to the @sourceActor of the menu upon which the menu will be centered
     * (if possible). If -1, the menu will be centered on the @sourceActor.
     *
     * This function specifies a new position at which to center the menu. The position is given in coordinates
     * relative to the @sourceActor, and as such should always be positive. This is useful if, for example, you want
     * the menu to open at the location of a mouse click rather than at the center of the actor. This function only
     * moves the menu along one axis as determined by the orientation of the menu, so that the menu is always attached
     * to the @sourceActor. For example, if the orientation is set to St.Side.TOP, this function will move the center
     * along the x axis. If you have set the @slidePosition using this function and then wish to return to centering
     * the menu on the center of the @sourceActor, you can do so by setting it to -1.
     */
    shiftToPosition: function(slidePosition) {
        this._slidePosition = slidePosition;
        let [xPos, yPos] = this._calculatePosition();
        this.actor.set_position(xPos, yPos);
    },

    /**
     * setMaxHeight:
     *
     * This function is called internally to set the max-height and max-width
     * properties of the popup menu such that it does not grow to a size larger
     * than the monitor. Individual popup menus can override this method to
     * change the max height/width if they really want to.
     *
     * Note that setting the max-height won't do any good if the minimum height
     * of the menu is higher then the screen; it's useful if part of the menu
     * is scrollable so the minimum height is smaller than the natural height.
     */
    setMaxHeight: function() {
        let monitor = Main.layoutManager.findMonitorForActor(this.sourceActor)

        let maxHeight = monitor.height;
        let maxWidth = monitor.width;

        let panels = Main.panelManager.getPanelsInMonitor(Main.layoutManager.monitors.indexOf(monitor));

        for (let panel of panels) {
            if (panel.panelPosition == PanelLoc.top || panel.panelPosition == PanelLoc.bottom) {
                maxHeight -= panel.actor.height;
            }
            else {
                maxWidth -= panel.actor.width;
            }
        }

        let themeNode = this.actor.get_theme_node();
        maxHeight -= (themeNode.get_border_width(St.Side.TOP) + themeNode.get_border_width(St.Side.BOTTOM));
        maxWidth -= (themeNode.get_border_width(St.Side.LEFT) + themeNode.get_border_width(St.Side.RIGHT));

        this.actor.style = 'max-height: ' + Math.floor(maxHeight / global.ui_scale) + 'px; ' +
                           'max-width: ' + Math.floor(maxWidth / global.ui_scale) + 'px;';
    },

    _calculatePosition: function() {
        if (!this.actor.visible) {
            this.box.show();
        }
        let sourceBox = Cinnamon.util_get_transformed_allocation(this.sourceActor);
        let [minWidth, minHeight, natWidth, natHeight] = this.actor.get_preferred_size();
        let monitor = Main.layoutManager.findMonitorForActor(this.sourceActor);
        let x1 = monitor.x;
        let x2 = x1 + monitor.width;
        let y1 = monitor.y;
        let y2 = y1 + monitor.height;

        // remove visible panels from workable area to avoid overlapping them
        let panels = Main.panelManager.getPanelsInMonitor(Main.layoutManager.monitors.indexOf(monitor));

        for (let panel of panels) {
            if (!panel.getIsVisible()) continue;
            switch (panel.panelPosition) {
                case PanelLoc.top:
                    y1 += panel.actor.height;
                    break;
                case PanelLoc.bottom:
                    y2 -= panel.actor.height;
                    break;
                case PanelLoc.left:
                    x1 += panel.actor.width;
                    break;
                case PanelLoc.right:
                    x2 -= panel.actor.width;
                    break;
            }
        }

        let xPos, yPos;
        let styleClasses = ["menu"];
        switch (this._orientation) {
            case St.Side.TOP:
            case St.Side.BOTTOM:
                // get center position of the actor and calculate the position needed to center the menu on the actor
                let xCenter = (this._slidePosition == -1) ? sourceBox.x1 + (sourceBox.x2 - sourceBox.x1) / 2 : this._slidePosition;
                xPos = xCenter - (natWidth / 2);

                // we don't want to go off the screen so we adjust if needed
                if (xPos < x1) xPos = x1;
                else if (xPos + natWidth > x2) xPos = x2 - natWidth;

                // now we calculate the x postion based on the orientation
                if (this._orientation == St.Side.BOTTOM) {
                    this.sideFlipped = true;
                    yPos = sourceBox.y1 - natHeight;
                    styleClasses.push("bottom");
                }
                else {
                    this.sideFlipped = false;
                    yPos = sourceBox.y2;
                    styleClasses.push("top");
                }
                break;
            case St.Side.LEFT:
            case St.Side.RIGHT:
                // align the top of the menu with the top of the source
                yPos = (this._slidePosition == -1) ? sourceBox.y1 : this._slidePosition;

                // we don't want to go off the screen so we adjust if needed
                if (yPos < y1) yPos = y1;
                else if (yPos + natHeight > y2) yPos = y2 - natHeight;

                // now we calculate the x postion based on the orientation
                // if the menu opens to the right, we also need to make sure we have room for it on that side
                if (this._orientation == St.Side.RIGHT || x2 - sourceBox.x2 < natWidth) {
                    this.sideFlipped = true;
                    xPos = sourceBox.x1 - natWidth;
                    styleClasses.push("right");
                }
                else {
                    this.sideFlipped = false;
                    xPos = sourceBox.x2;
                    styleClasses.push("left");
                }
                break;
        }
        if (this.customStyleClass) styleClasses.push(this.customStyleClass);
        this.actor.set_style_class_name(styleClasses.join(" "));
        return [Math.round(xPos), Math.round(yPos)];
    },

    _boxGetPreferredWidth: function (actor, forHeight, alloc) {
        let columnWidths = this.getColumnWidths();
        this.setColumnWidths(columnWidths);

        // Now they will request the right sizes
        [alloc.min_size, alloc.natural_size] = this.box.get_preferred_width(forHeight);
    },

    _boxGetPreferredHeight: function (actor, forWidth, alloc) {
        [alloc.min_size, alloc.natural_size] = this.box.get_preferred_height(forWidth);
    },

    _boxAllocate: function (actor, box, flags) {
        this.box.allocate(box, flags);
        if (!this.animating && this.sourceActor.get_stage() != null) {
            let [xPos, yPos] = this._calculatePosition();
            this.actor.set_position(xPos, yPos);
        }
    },

    _onKeyPressEvent: function(actor, event) {
        if (event.get_key_symbol() == Clutter.Escape) {
            this.close(true);
            return true;
        }

        return false;
    },

    on_paint: function(actor) {
        if (this.paint_count < 2 || this.animating) {
            this.paint_count++;
            return;
        }

        if (this._signals.isConnected('paint', this.actor)) {
            this._signals.disconnect('paint', this.actor);
        }

        this.paint_count = 0;
        Main.popup_rendering_actor = null;
    }
};

/**
 * #PopupSubMenu
 * @short_description: A submenu that can show and hide
 * @actor (St.ScrollView): The actor of the submenu.
 *
 * A submenu to be included in #PopupMenus/#PopupMenuSections. You usually
 * don't want to create these manually. Instead you want to create a
 * #PopupSubMenuMenuItem, which creates a #PopupSubMenu, and shows/hides the
 * menu when clicked.
 *
 * Since submenus are usually used to hide long lists of things, they are
 * automatically put into a #St.ScrollView such that their height will be limited
 * by the css max-height property.
 *
 * Inherits: PopupMenu.PopupMenuBase
 */
function PopupSubMenu() {
    this._init.apply(this, arguments);
}

PopupSubMenu.prototype = {
    __proto__: PopupMenuBase.prototype,

    /**
     * _init:
     * @sourceActor (St.Widget): the actor that owns the popup menu
     * @sourceArrow (St.Icon): (optional) a little arrow object inside the
     * #PopupSubMenuMenuItem. When the submenu opens, the arrow is rotated by
     * pi/2 clockwise to denote the status of the submenu.
     */
    _init: function(sourceActor, sourceArrow) {
        PopupMenuBase.prototype._init.call(this, sourceActor);

        if (sourceArrow) {
            this._arrow = sourceArrow;
        }

        this.actor = new St.ScrollView({ style_class: 'popup-sub-menu',
                                         hscrollbar_policy: Gtk.PolicyType.NEVER,
                                         vscrollbar_policy: Gtk.PolicyType.NEVER });

        // StScrollbar plays dirty tricks with events, calling
        // clutter_set_motion_events_enabled (FALSE) during the scroll; this
        // confuses our event tracking, so we just turn it off during the
        // scroll.
        let vscroll = this.actor.get_vscroll_bar();
        this._signals.connect(vscroll, 'scroll-start',
                        Lang.bind(this, function() {
                                      let topMenu = this._getTopMenu();
                                      if (topMenu)
                                          topMenu.passEvents = true;
                                  }));
        this._signals.connect(vscroll, 'scroll-stop',
                        Lang.bind(this, function() {
                                      let topMenu = this._getTopMenu();
                                      if (topMenu)
                                          topMenu.passEvents = false;
                                  }));

        this.actor.add_actor(this.box);
        this.actor._delegate = this;
        this.actor.clip_to_allocation = true;
        this._signals.connect(this.actor, 'key-press-event', Lang.bind(this, this._onKeyPressEvent));
        this.actor.hide();
    },

    _getTopMenu: function() {
        let actor = this.actor.get_parent();
        while (actor) {
            if (actor._delegate && actor._delegate instanceof PopupMenu)
                return actor._delegate;

            actor = actor.get_parent();
        }

        return null;
    },

    _needsScrollbar: function() {
        let topMenu = this._getTopMenu();
        if(!topMenu)
            return false;
        let [topMinHeight, topNaturalHeight] = topMenu.actor.get_preferred_height(-1);
        let topThemeNode = topMenu.actor.get_theme_node();

        let topMaxHeight = topThemeNode.get_max_height();
        return topMaxHeight >= 0 && topNaturalHeight >= topMaxHeight;
    },

    /**
     * open:
     * @animate (boolean): whether the animate the open effect
     *
     * Opens the submenu
     */
    open: function(animate) {
        if (this.isOpen)
            return;

        this.isOpen = true;

        this.actor.show();

        let needsScrollbar = this._needsScrollbar();

        // St.ScrollView always requests space horizontally for a possible vertical
        // scrollbar if in AUTOMATIC mode. Doing better would require implementation
        // of width-for-height in St.BoxLayout and St.ScrollView. This looks bad
        // when we *don't* need it, so turn off the scrollbar when that's true.
        // Dynamic changes in whether we need it aren't handled properly.
        this.actor.vscrollbar_policy =
            needsScrollbar ? Gtk.PolicyType.AUTOMATIC : Gtk.PolicyType.NEVER;

        // It looks funny if we animate with a scrollbar (at what point is
        // the scrollbar added?) so just skip that case
        animate = animate && !needsScrollbar

        let targetAngle = this.actor.text_direction == Clutter.TextDirection.RTL ? -90 : 90;

        if (animate && global.settings.get_boolean("desktop-effects-on-menus")) {
            let [minHeight, naturalHeight] = this.actor.get_preferred_height(-1);
            this.actor.height = 0;
            if (this._arrow)
                this.actor._arrowRotation = this._arrow.rotation_angle_z;
            else
                this.actor._arrowRotation = targetAngle;
            Tweener.addTween(this.actor,
                             { _arrowRotation: targetAngle,
                               height: naturalHeight,
                               time: 0.25,
                               onUpdateScope: this,
                               onUpdate: function() {
                                   if (this._arrow)
                                       this._arrow.rotation_angle_z = this.actor._arrowRotation;
                               },
                               onCompleteScope: this,
                               onComplete: function() {
                                   this.actor.set_height(-1);
                                   this.emit('open-state-changed', true);
                               }
                             });
        } else {
            if (this._arrow)
                this._arrow.rotation_angle_z = targetAngle;
            this.emit('open-state-changed', true);
        }
    },

    /**
     * close:
     * @animate (boolean): whether the animate the close effect
     *
     * Closes the submenu
     */
    close: function(animate) {
        if (!this.isOpen)
            return;

        this.isOpen = false;

        if (this._activeMenuItem)
            this._activeMenuItem.setActive(false);

        animate = animate && !this._needsScrollbar();

        if (animate && global.settings.get_boolean("desktop-effects-on-menus")) {
            if (this._arrow)
                this.actor._arrowRotation = this._arrow.rotation_angle_z;
            Tweener.addTween(this.actor,
                             { _arrowRotation: 0,
                               height: 0,
                               time: 0.25,
                               onCompleteScope: this,
                               onComplete: function() {
                                   this.actor.hide();
                                   this.actor.set_height(-1);

                                   this.emit('open-state-changed', false);
                               },
                               onUpdateScope: this,
                               onUpdate: function() {
                                   if (this._arrow)
                                       this._arrow.rotation_angle_z = this.actor._arrowRotation;
                               }
                             });
            } else {
                if (this._arrow)
                    this._arrow.rotation_angle_z = 0;
                this.actor.hide();

                this.isOpen = false;
                this.emit('open-state-changed', false);
            }
    },

    _onKeyPressEvent: function(actor, event) {
        // Move focus back to parent menu if the user types Left.

        if (this.isOpen && event.get_key_symbol() == Clutter.KEY_Left) {
            this.close(true);
            this.sourceActor._delegate.setActive(true);
            return true;
        }

        return false;
    }
};

/**
 * #PopupMenuSection:
 * @short_description: A section of a #PopupMenu that is transparent to user
 *
 * A section of a PopupMenu which is handled like a submenu (you can add and
 * remove items, you can destroy it, you can add it to another menu), but is
 * completely transparent to the user. This is helpful for grouping things
 * together so that you can manage them in bulk. A common use case might be to
 * let an object inherit a #PopupMenuSection and then add the whole object to a
 * popup menu.
 *
 * Note that you cannot close a #PopupMenuSection.
 *
 * Inherits: PopupMenu.PopupMenuBase
 */
function PopupMenuSection() {
    this._init.apply(this, arguments);
}

PopupMenuSection.prototype = {
    __proto__: PopupMenuBase.prototype,

    _init: function() {
        PopupMenuBase.prototype._init.call(this);

        this.actor = this.box;
        this.actor._delegate = this;
        this.isOpen = true;
    },

    // deliberately ignore any attempt to open() or close()
    open: function(animate) { },
    close: function() { },

}

function PopupSubMenuMenuItem() {
    this._init.apply(this, arguments);
}

PopupSubMenuMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function(text) {
        PopupBaseMenuItem.prototype._init.call(this);

        this._triangle = null;

        // This check allows PopupSubMenu to be used as a generic scrollable container.
        if (typeof text === 'string') {
            this.actor.add_style_class_name('popup-submenu-menu-item');

            this.label = new St.Label({ text: text,
                                        y_expand: true,
                                        y_align: Clutter.ActorAlign.CENTER });
            this.addActor(this.label);
            this.actor.label_actor = this.label;

            this._triangleBin = new St.Bin({ x_align: St.Align.END });
            this.addActor(this._triangleBin, { expand: true,
                                               span: -1,
                                               align: St.Align.END });

            this._triangle = arrowIcon(St.Side.RIGHT);
            this._triangle.pivot_point = new Clutter.Point({ x: 0.5, y: 0.5 });
            this._triangleBin.child = this._triangle;
        }

        this.menu = new PopupSubMenu(this.actor, this._triangle);
        this._signals.connect(this.menu, 'open-state-changed', Lang.bind(this, this._subMenuOpenStateChanged));
    },

    _subMenuOpenStateChanged: function(menu, open) {
        this.actor.change_style_pseudo_class('open', open);
    },

    destroy: function() {
        this.menu.destroy();
        PopupBaseMenuItem.prototype.destroy.call(this);
    },

    _onKeyPressEvent: function(actor, event) {
        let symbol = event.get_key_symbol();

        if (symbol == Clutter.KEY_Right) {
            this.menu.open(true);
            this.menu.actor.navigate_focus(null, Gtk.DirectionType.DOWN, false);
            return true;
        } else if (symbol == Clutter.KEY_Left && this.menu.isOpen) {
            this.menu.close();
            return true;
        }

        return PopupBaseMenuItem.prototype._onKeyPressEvent.call(this, actor, event);
    },

    activate: function(event) {
        this.menu.open(true);
    },

    _onButtonReleaseEvent: function(actor) {
        this.menu.toggle();
    }
};

function PopupComboMenu() {
    this._init.apply(this, arguments);
}

PopupComboMenu.prototype = {
    __proto__: PopupMenuBase.prototype,

    _init: function(sourceActor) {
        PopupMenuBase.prototype._init.call(this,
                                           sourceActor, 'popup-combo-menu');
        this.actor = this.box;
        this.actor._delegate = this;
        this._signals.connect(this.actor, 'key-press-event', Lang.bind(this, this._onKeyPressEvent));
        this._signals.connect(this.actor, 'key-focus-in', Lang.bind(this, this._onKeyFocusIn));
        this._activeItemPos = -1;
        global.focus_manager.add_group(this.actor);
    },

    _onKeyPressEvent: function(actor, event) {
        if (event.get_key_symbol() == Clutter.Escape) {
            this.close(true);
            return true;
        }

        return false;
    },

    _onKeyFocusIn: function(actor) {
        let items = this._getMenuItems();
        let activeItem = items[this._activeItemPos];
        activeItem.actor.grab_key_focus();
    },

    open: function() {
        if (this.isOpen)
            return;

        this.isOpen = true;

        let activeItem = this._getMenuItems()[this._activeItemPos];

        let [sourceX, sourceY] = this.sourceActor.get_transformed_position();
        this.actor.set_position(Math.round(sourceX), Math.round(sourceY - activeItem.actor.y));

        this.actor.raise_top();

        this.actor.opacity = 0;
        this.actor.show();

        if (global.settings.get_boolean("desktop-effects-on-menus")) {
            Tweener.addTween(this.actor,
                             { opacity: 255,
                               transition: 'linear',
                               time: BoxPointer.POPUP_ANIMATION_TIME });
        }

        this.savedFocusActor = global.stage.get_key_focus();
        global.stage.set_key_focus(this.actor);
        this.emit('open-state-changed', true);
    },

    close: function() {
        if (!this.isOpen)
            return;

        this.isOpen = false;
        if (global.settings.get_boolean("desktop-effects-on-menus")) {
            Tweener.addTween(this.actor,
                             { opacity: 0,
                               transition: 'linear',
                               time: BoxPointer.POPUP_ANIMATION_TIME,
                               onComplete: Lang.bind(this,
                                   function() {
                                       this.actor.hide();
                                   })
                             });
        } else {
            this.actor.hide();
        }
        this.emit('open-state-changed', false);
        global.stage.set_key_focus(this.savedFocusActor);
    },

    setActiveItem: function(position) {
        this._activeItemPos = position;
    },

    setItemVisible: function(position, visible) {
        if (!visible && position == this._activeItemPos) {
            log('Trying to hide the active menu item.');
            return;
        }

        this._getMenuItems()[position].actor.visible = visible;
    },

    getItemVisible: function(position) {
        return this._getMenuItems()[position].actor.visible;
    }
};

function PopupComboBoxMenuItem() {
    this._init.apply(this, arguments);
}

PopupComboBoxMenuItem.prototype = {
    __proto__: PopupBaseMenuItem.prototype,

    _init: function (params) {
        PopupBaseMenuItem.prototype._init.call(this, params);

        this._itemBox = new Cinnamon.Stack();

        this.actor.accessible_role = Atk.Role.COMBO_BOX;

        this.addActor(this._itemBox);

        let expander = new St.Label({ text: '\u2304' });
        this.addActor(expander, { align: St.Align.END,
                                  span: -1 });

        this._menu = new PopupComboMenu(this.actor);
        Main.uiGroup.add_actor(this._menu.actor);
        this._menu.actor.hide();

        if (params.style_class)
            this._menu.actor.add_style_class_name(params.style_class);

        this._signals.connect(this.actor, 'scroll-event', Lang.bind(this, this._onScrollEvent));

        this._activeItemPos = -1;
        this._items = [];
    },

    _getTopMenu: function() {
        let actor = this.actor.get_parent();
        while (actor) {
            if (actor._delegate &&
                (actor._delegate instanceof PopupMenu ||
                 actor._delegate instanceof PopupComboMenu))
                return actor._delegate;

            actor = actor.get_parent();
        }

        return null;
    },

    _onScrollEvent: function(actor, event) {
        if (this._activeItemPos == -1)
            return;

        let position = this._activeItemPos;
        let direction = event.get_scroll_direction();
        if (direction == Clutter.ScrollDirection.DOWN) {
            while (position < this._items.length - 1) {
                position++;
                if (this._menu.getItemVisible(position))
                    break;
            }
        } else if (direction == Clutter.ScrollDirection.UP) {
            while (position > 0) {
                position--;
                if (this._menu.getItemVisible(position))
                    break;
            }
        }

        if (position == this._activeItemPos)
            return;

        this.setActiveItem(position);
        this.emit('active-item-changed', position);
    },

    activate: function(event) {
        let topMenu = this._getTopMenu();
        if (!topMenu)
            return;

        topMenu.addChildMenu(this._menu);
        this._menu.toggle();
    },

    addMenuItem: function(menuItem, position) {
        if (position === undefined)
            position = this._menu.numMenuItems;

        this._menu.addMenuItem(menuItem, position);
        _ensureStyle(this._menu.actor);

        let item = new St.BoxLayout({ style_class: 'popup-combobox-item' });

        let children = menuItem.actor.get_children();
        for (let i = 0; i < children.length; i++) {
            let clone = new Clutter.Clone({ source: children[i] });
            item.add(clone, { y_fill: false });
        }

        let oldItem = this._items[position];
        if (oldItem)
            this._itemBox.remove_actor(oldItem);

        this._items[position] = item;
        this._itemBox.add_actor(item);

        this._signals.connect(menuItem, 'activate',
                         Lang.bind(this, this._itemActivated, position));
    },

    checkAccessibleLabel: function() {
        let activeItem = this._menu.getActiveItem();
        this.actor.label_actor = activeItem.label;
    },

    setActiveItem: function(position) {
        let item = this._items[position];
        if (!item)
            return;
        if (this._activeItemPos == position)
            return;
        this._menu.setActiveItem(position);
        this._activeItemPos = position;
        for (let i = 0; i < this._items.length; i++)
            this._items[i].visible = (i == this._activeItemPos);

        this.checkAccessibleLabel();
    },

    setItemVisible: function(position, visible) {
        this._menu.setItemVisible(position, visible);
    },

    _itemActivated: function(menuItem, event, position) {
        this.setActiveItem(position);
        this.emit('active-item-changed', position);
    }
};

/**
 * #PopupMenuFactory:
 * @short_description: A class to build a cinnamon menu using some abstract menu items.
 *
 * This class can build a cinnamon menu, using the instances of a heir of the
 * PopupMenuAbstractItem class. Please see the description of the PopupMenuAbstractItem
 * class to more details. To initialize the construction you need to provide the root
 * instance of your abstract menu items.
 */
function PopupMenuFactory() {
    this._init.apply(this, arguments);
}

PopupMenuFactory.prototype = {

    _init: function() {
        this._menuLikend = new Array();
    },

    _createShellItem: function(factoryItem, launcher, orientation) {
        // Decide whether it's a submenu or not
        let shellItem = null;
        let item_type = factoryItem.getFactoryType();
        if (item_type == FactoryClassTypes.RootMenuClass)
            shellItem = new PopupMenu(launcher.actor, orientation);
        if (item_type == FactoryClassTypes.SubMenuMenuItemClass)
            shellItem = new PopupSubMenuMenuItem("FIXME");
        else if (item_type == FactoryClassTypes.MenuSectionMenuItemClass)
            shellItem = new PopupMenuSection();
        else if (item_type == FactoryClassTypes.SeparatorMenuItemClass)
            shellItem = new PopupSeparatorMenuItem('');
        else if (item_type == FactoryClassTypes.MenuItemClass)
            shellItem = new PopupIndicatorMenuItem("FIXME");
        return shellItem;
    },

    getShellMenu: function(factoryMenu) {
        let index = this._menuLikend.indexOf(factoryMenu);
        if (index != -1) {
            return factoryMenu.getShellItem();
        }
        return null;
    },

    buildShellMenu: function(client, launcher, orientation) {
        let factoryMenu = client.getRoot();
        if (!(factoryMenu instanceof PopupMenuAbstractItem)) {
            throw new Error("MenuFactory: can't construct an instance of \
                PopupMenu using a non instance of the class PopupMenuAbstractItem");
        }

        if (factoryMenu.shellItem)
            return factoryMenu.shellItem;

        // The shell menu
        let shellItem = this._createShellItem(factoryMenu, launcher, orientation);
        this._attachToMenu(shellItem, factoryMenu);
        return shellItem;
    },

    // This will attach the root factoryItem to an already existing menu that will be used as the root menu.
    // it will also connect the factoryItem to be automatically destroyed when the menu dies.
    _attachToMenu: function(shellItem, factoryItem) {
        // Cleanup: remove existing childs (just in case)
        shellItem.removeAll();

        // Fill the menu for the first time
        factoryItem.getChildren().forEach(function(child) {
            shellItem.addMenuItem(this._createItem(child));
        }, this);

        factoryItem.setShellItem(shellItem, {
            'child-added'   : Lang.bind(this, this._onChildAdded),
            'child-moved'   : Lang.bind(this, this._onChildMoved)
        });
        this._menuLikend.push(factoryItem);
        factoryItem.connectAndRemoveOnDestroy({
            'destroy'           : Lang.bind(this, this._onDestroyMainMenu)
        });
    },

    _onDestroyMainMenu: function(factoryItem) {
        let index = this._menuLikend.indexOf(factoryItem);
        if (index != -1) {
            this._menuLikend.splice(index, 1);
        }
    },

    _createItem: function(factoryItem) {
        // Don't allow to override previusly preasigned items, destroy the shell item first.
        factoryItem.destroyShellItem();
        let shellItem = this._createShellItem(factoryItem);

        // Initially create children on idle, to not stop cinnamon mainloop.
        Mainloop.idle_add(Lang.bind(this, this._createChildrens, factoryItem));

        // Now, connect various events
        factoryItem.setShellItem(shellItem, {
            'type-changed':       Lang.bind(this, this._onTypeChanged),
            'child-added':        Lang.bind(this, this._onChildAdded),
            'child-moved':        Lang.bind(this, this._onChildMoved)
        });
        return shellItem;
    },

    _createChildrens: function(factoryItem) {
        if (factoryItem) {
            let shellItem = factoryItem.getShellItem();
            if (shellItem instanceof PopupSubMenuMenuItem) {
                let children = factoryItem.getChildren();
                for (let i = 0; i < children.length; ++i) {
                    let ch_item = this._createItem(children[i]);
                    shellItem.menu.addMenuItem(ch_item);
                }
            } else if (shellItem instanceof PopupMenuSection) {
                let children = factoryItem.getChildren();
                for (let i = 0; i < children.length; ++i) {
                    let ch_item = this._createItem(children[i]);
                    shellItem.addMenuItem(ch_item);
                }
            }
        }
    },

    _onChildAdded: function(factoryItem, child, position) {
        let shellItem = factoryItem.getShellItem();
        if (shellItem) {
            if (shellItem instanceof PopupSubMenuMenuItem) {
                shellItem.menu.addMenuItem(this._createItem(child), position, "factor");
            } else if ((shellItem instanceof PopupMenuSection) ||
                       (shellItem instanceof PopupMenu)) {
                shellItem.addMenuItem(this._createItem(child), position);
            } else {
                global.logWarning("Tried to add a child to non-submenu item. Better recreate it as whole");
                this._onTypeChanged(factoryItem);
            }
        } else {
            global.logWarning("Tried to add a child shell item to non existing shell item.");
        }
    },

    _onChildMoved: function(factoryItem, child, oldpos, newpos) {
        let shellItem = factoryItem.getShellItem();
        if (shellItem) {
            if (shellItem instanceof PopupSubMenuMenuItem) {
                this._moveItemInMenu(shellItem.menu, child, newpos);
            } else if ((shellItem instanceof PopupMenuSection) ||
                       (shellItem instanceof PopupMenu)) {
                this._moveItemInMenu(shellItem, child, newpos);
            } else {
                global.logWarning("Tried to move a child in non-submenu item. Better recreate it as whole");
                this._onTypeChanged(factoryItem);
            }
        } else {
            global.logWarning("Tried to move a child shell item in non existing shell item.");
        }
    },

    // FIXME: If this function it is applied, this mean that our old shell Item
    // is not valid right now, so we can destroy it with all the obsolete submenu
    // structure and then create again for the new factoryItems source. Anyway
    // there are a lot of possible scenarios when this was called, sure we are
    // missing some of them.
    _onTypeChanged: function(factoryItem) {
        let shellItem = factoryItem.getShellItem();
        let factoryItemParent = factoryItem.getParent();
        let parentMenu = null;
        if (factoryItemParent) {
            let shellItemParent = factoryItemParent.getShellItem();
            if (shellItemParent instanceof PopupMenuSection)
                parentMenu = shellItemParent;
            else
                parentMenu = shellItemParent.menu;
        }
        // First, we need to find our old position
        let pos = -1;
        if ((parentMenu)&&(shellItem)) {
            let family = parentMenu._getMenuItems();
            for (let i = 0; i < family.length; ++i) {
                if (family[i] == shellItem)
                    pos = i;
            }
        }
        // if not insert the item in first position.
        if (pos < 0)
            pos = 0;
        // Now destroy our old self
        factoryItem.destroyShellItem();
        if (parentMenu) {
            // Add our new self
            let newShellItem = this._createItem(factoryItem);
            parentMenu.addMenuItem(newShellItem, pos);
        }
    },

    // FIXME: This is a HACK. We're really getting into the internals of the PopupMenu implementation.
    // First, find our wrapper. Children tend to lie. We do not trust the old positioning.
    // Will be better add this function inside the PopupMenuBase class?
    _moveItemInMenu: function(menu, factoryItem, newpos) {
        let shellItem = factoryItem.getShellItem();
        if (shellItem) {
            let family = menu._getMenuItems();
            for (let i = 0; i < family.length; ++i) {
                if (family[i] == shellItem) {
                    // Now, remove it
                    menu.box.remove_child(shellItem.actor);

                    // Add it again somewhere else
                    if (newpos < family.length && family[newpos] != shellItem)
                        menu.box.insert_child_below(shellItem.actor, family[newpos].actor);
                    else
                        menu.box.add(shellItem.actor);

                    // Skip the rest
                    break;
                }
            }
        }
    }
};

/* Basic implementation of a menu manager.
 * Call addMenu to add menus
 */
function PopupMenuManager(owner) {
    this._init(owner);
}

PopupMenuManager.prototype = {
    _init: function(owner) {
        this._owner = owner;
        this.grabbed = false;

        this._eventCaptureId = 0;
        this._enterEventId = 0;
        this._leaveEventId = 0;
        this._keyFocusNotifyId = 0;
        this._activeMenu = null;
        this._menus = [];
        this._menuStack = [];
        this._preGrabInputMode = null;
        this._grabbedFromKeynav = false;
        this._signals = new SignalManager.SignalManager(null);
    },

    addMenu: function(menu, position) {
        this._signals.connect(menu, 'open-state-changed', this._onMenuOpenState, this);
        this._signals.connect(menu, 'child-menu-added', this._onChildMenuAdded, this);
        this._signals.connect(menu, 'child-menu-removed', this._onChildMenuRemoved, this);
        this._signals.connect(menu, 'destroy', this._onMenuDestroy, this);

        let source = menu.sourceActor;

        if (source) {
            this._signals.connect(source, 'enter-event', function() { this._onMenuSourceEnter(menu); }, this);
            this._signals.connect(source, 'key-focus-in', function() { this._onMenuSourceEnter(menu); }, this);
        }

        if (position == undefined)
            this._menus.push(menu);
        else
            this._menus.splice(position, 0, menu);
    },

    removeMenu: function(menu) {
        if (menu == this._activeMenu)
            this._closeMenu();

        let position = this._menus.indexOf(menu);

        if (position == -1) // not a menu we manage
            return;

        this._signals.disconnect(null, menu);

        if (menu.sourceActor)
            this._signals.disconnect(null, menu.sourceActor);

        this._menus.splice(position, 1);
    },

    _grab: function() {
        if (!Main.pushModal(this._owner.actor)) {
            return;
        }
        this._signals.connect(global.stage, 'captured-event', this._onEventCapture, this);
        // captured-event doesn't see enter/leave events
        this._signals.connect(global.stage, 'enter-event', this._onEventCapture, this);
        this._signals.connect(global.stage, 'leave-event', this._onEventCapture, this);
        this._signals.connect(global.stage, 'notify::key-focus', this._onKeyFocusChanged, this);

        this.grabbed = true;
    },

    _ungrab: function() {
        if (!this.grabbed) {
            return;
        }

        this._signals.disconnect(null, global.stage);

        this.grabbed = false;
        Main.popModal(this._owner.actor);
    },

    _onMenuOpenState: function(menu, open) {
        if (open) {
            if (this._activeMenu && this._activeMenu.isChildMenu(menu)) {
                this._menuStack.push(this._activeMenu);
                menu.actor.grab_key_focus();
            }
            this._activeMenu = menu;
        } else {
            if (this._menuStack.length > 0) {
                this._activeMenu = this._menuStack.pop();
                if (menu.sourceActor)
                    menu.sourceActor.grab_key_focus();
                this._didPop = true;
            }
        }

        // Check what the focus was before calling pushModal/popModal
        let focus = global.stage.key_focus;
        let hadFocus = focus && this._activeMenuContains(focus);

        if (open) {
            if (!this.grabbed) {
                this._preGrabInputMode = global.stage_input_mode;
                this._grabbedFromKeynav = hadFocus;
                this._grab();
            }

            if (hadFocus)
                focus.grab_key_focus();
            else
                menu.actor.grab_key_focus();
        } else if (menu == this._activeMenu) {
            if (this.grabbed)
                this._ungrab();
            this._activeMenu = null;

            if (this._grabbedFromKeynav) {
                if (this._preGrabInputMode == Cinnamon.StageInputMode.FOCUSED)
                    global.stage_input_mode = Cinnamon.StageInputMode.FOCUSED;
                if (hadFocus && menu.sourceActor)
                    menu.sourceActor.grab_key_focus();
                else if (focus)
                    focus.grab_key_focus();
            }
        }
    },

    _onChildMenuAdded: function(menu, childMenu) {
        this.addMenu(childMenu);
    },

    _onChildMenuRemoved: function(menu, childMenu) {
        this.removeMenu(childMenu);
    },

    // change the currently-open menu without dropping grab
    _changeMenu: function(newMenu) {
        if (this._activeMenu) {
            // _onOpenMenuState will drop the grab if it sees
            // this._activeMenu being closed; so clear _activeMenu
            // before closing it to keep that from happening
            let oldMenu = this._activeMenu;
            this._activeMenu = null;
            for (let i = this._menuStack.length - 1; i >= 0; i--)
                this._menuStack[i].close(false);
            oldMenu.close(false);
            newMenu.open(false);
        } else
            newMenu.open(true);
    },

    _onMenuSourceEnter: function(menu) {
        if (!this.grabbed || menu == this._activeMenu)
            return false;

        if (this._activeMenu && this._activeMenu.isChildMenu(menu))
            return false;

        if (this._menuStack.indexOf(menu) != -1)
            return false;

        if (this._menuStack.length > 0 && this._menuStack[0].isChildMenu(menu))
            return false;

        this._changeMenu(menu);
        return false;
    },

    _onKeyFocusChanged: function() {
        if (!this.grabbed || !this._activeMenu || DND.isDragging())
            return;

        let focus = global.stage.key_focus;
        if (focus) {
            if (this._activeMenuContains(focus))
                return;
            if (this._menuStack.length > 0)
                return;
            if (focus._delegate && focus._delegate.menu &&
                this._menus.indexOf(focus._delegate.menu) != -1)
                return;
        }

        this._closeMenu();
    },

    _onMenuDestroy: function(menu) {
        this.removeMenu(menu);
    },

    _activeMenuContains: function(actor) {
        return this._activeMenu != null
                && (this._activeMenu.actor.contains(actor) ||
                    (this._activeMenu.sourceActor && this._activeMenu.sourceActor.contains(actor)));
    },

    _eventIsOnActiveMenu: function(event) {
        return this._activeMenuContains(event.get_source());
    },

    _shouldBlockEvent: function(event) {
        let src = event.get_source();

        if (this._activeMenu != null && this._activeMenu.actor.contains(src))
            return false;

        return (this._menus.find(x => x.sourceActor &&
                                      !x.blockSourceEvents &&
                                      x.sourceActor.contains(src)) === undefined);
    },

    _onEventCapture: function(actor, event) {
        if (!this.grabbed)
            return false;

        if (Main.keyboard.shouldTakeEvent(event))
            return Clutter.EVENT_PROPAGATE;

        if (this._owner.menuEventFilter &&
            this._owner.menuEventFilter(event))
            return true;

        if (this._activeMenu != null && this._activeMenu.passEvents)
            return false;

        if (this._didPop) {
            this._didPop = false;
            return true;
        }

        let activeMenuContains = this._eventIsOnActiveMenu(event);
        let eventType = event.type();

        if (eventType == Clutter.EventType.BUTTON_RELEASE) {
            if (activeMenuContains) {
                return false;
            } else {
                this._closeMenu();
                return true;
            }
        } else if (eventType == Clutter.EventType.BUTTON_PRESS && !activeMenuContains) {
            this._closeMenu();
            return true;
        } else if (!this._shouldBlockEvent(event)) {
            return false;
        }

        return true;
    },

    _closeMenu: function() {
        if (this._activeMenu != null)
            this._activeMenu.close(true);
    },

    destroy: function() {
        this._signals.disconnectAllSignals();
        this.emit('destroy');
    }
};
Signals.addSignalMethods(PopupMenuManager.prototype);