DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Untracked file

Line Code
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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Pierre Phaneuf <pp@ludusdesign.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "nsIServiceManager.h"
#include "nsIComponentManager.h" 
#include "rdf.h"
#include "nsIRDFDataSource.h"
#include "nsIRDFService.h"
#include "nsIRDFContainerUtils.h"
#include "nsRDFCID.h"
#include "nsXPIDLString.h"
#include "nsCharsetMenu.h"
#include "nsICharsetConverterManager.h"
#include "nsICollation.h"
#include "nsCollationCID.h"
#include "nsLocaleCID.h"
#include "nsILocaleService.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIPrefBranch2.h"
#include "nsIPrefLocalizedString.h"
#include "nsICurrentCharsetListener.h"
#include "nsQuickSort.h"
#include "nsIObserver.h"
#include "nsStringEnumerator.h"
#include "nsVoidArray.h"
#include "nsIObserverService.h"
#include "nsIRequestObserver.h"
#include "nsITimelineService.h"
#include "nsCRT.h"
#include "prmem.h"

//----------------------------------------------------------------------------
// Global functions and data [declaration]

static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
static NS_DEFINE_CID(kCharsetConverterManagerCID, NS_ICHARSETCONVERTERMANAGER_CID);
static NS_DEFINE_CID(kRDFInMemoryDataSourceCID, NS_RDFINMEMORYDATASOURCE_CID);
static NS_DEFINE_CID(kRDFContainerUtilsCID, NS_RDFCONTAINERUTILS_CID);
static NS_DEFINE_CID(kRDFContainerCID, NS_RDFCONTAINER_CID);
static NS_DEFINE_CID(kCollationFactoryCID, NS_COLLATIONFACTORY_CID);
static NS_DEFINE_CID(kLocaleServiceCID, NS_LOCALESERVICE_CID); 

static const char kURINC_BrowserAutodetMenuRoot[] = "NC:BrowserAutodetMenuRoot";
static const char kURINC_BrowserCharsetMenuRoot[] = "NC:BrowserCharsetMenuRoot";
static const char kURINC_BrowserMoreCharsetMenuRoot[] = "NC:BrowserMoreCharsetMenuRoot";
static const char kURINC_BrowserMore1CharsetMenuRoot[] = "NC:BrowserMore1CharsetMenuRoot";
static const char kURINC_BrowserMore2CharsetMenuRoot[] = "NC:BrowserMore2CharsetMenuRoot";
static const char kURINC_BrowserMore3CharsetMenuRoot[] = "NC:BrowserMore3CharsetMenuRoot";
static const char kURINC_BrowserMore4CharsetMenuRoot[] = "NC:BrowserMore4CharsetMenuRoot";
static const char kURINC_BrowserMore5CharsetMenuRoot[] = "NC:BrowserMore5CharsetMenuRoot";
static const char kURINC_BrowserUnicodeCharsetMenuRoot[] = "NC:BrowserUnicodeCharsetMenuRoot";
static const char kURINC_MaileditCharsetMenuRoot[] = "NC:MaileditCharsetMenuRoot";
static const char kURINC_MailviewCharsetMenuRoot[] = "NC:MailviewCharsetMenuRoot";
static const char kURINC_ComposerCharsetMenuRoot[] = "NC:ComposerCharsetMenuRoot";
static const char kURINC_DecodersRoot[] = "NC:DecodersRoot";
static const char kURINC_EncodersRoot[] = "NC:EncodersRoot";
DEFINE_RDF_VOCAB(NC_NAMESPACE_URI, NC, Name);
DEFINE_RDF_VOCAB(NC_NAMESPACE_URI, NC, Checked);
DEFINE_RDF_VOCAB(NC_NAMESPACE_URI, NC, BookmarkSeparator);
DEFINE_RDF_VOCAB(NC_NAMESPACE_URI, NC, CharsetDetector);
DEFINE_RDF_VOCAB(RDF_NAMESPACE_URI, NC, type);

// Note here that browser and mailview have the same static area and cache 
// size but the cache itself is separate.

#define kBrowserStaticPrefKey       "intl.charsetmenu.browser.static"
#define kBrowserCachePrefKey        "intl.charsetmenu.browser.cache"
#define kBrowserCacheSizePrefKey    "intl.charsetmenu.browser.cache.size"

#define kMailviewStaticPrefKey      "intl.charsetmenu.browser.static"
#define kMailviewCachePrefKey       "intl.charsetmenu.mailview.cache"
#define kMailviewCacheSizePrefKey   "intl.charsetmenu.browser.cache.size"

#define kComposerStaticPrefKey      "intl.charsetmenu.browser.static"
#define kComposerCachePrefKey       "intl.charsetmenu.composer.cache"
#define kComposerCacheSizePrefKey   "intl.charsetmenu.browser.cache.size"

#define kMaileditPrefKey            "intl.charsetmenu.mailedit"

static void CloneCStringArray(const nsCStringArray& src, nsCStringArray& dest)
{
  PRUint32 count = src.Count();
  PRUint32 i;
  for (i=0; i<count; i++) {
    dest.AppendCString(*src.CStringAt(i));
  }
}

//----------------------------------------------------------------------------
// Class nsMenuEntry [declaration]

/**
 * A little class holding all data needed for a menu item.
 *
 * @created         18/Apr/2000
 * @author  Catalin Rotaru [CATA]
 */
class nsMenuEntry
{
public: 
  // memory & ref counting & leak prevention stuff
  nsMenuEntry() { MOZ_COUNT_CTOR(nsMenuEntry); }
  ~nsMenuEntry() { MOZ_COUNT_DTOR(nsMenuEntry); }

  nsCAutoString mCharset;
  nsAutoString      mTitle;
};

MOZ_DECL_CTOR_COUNTER(nsMenuEntry)

//----------------------------------------------------------------------------
// Class nsCharsetMenu [declaration]

/**
 * The Charset Converter menu.
 *
 * God, our GUI programming disgusts me.
 *
 * @created         23/Nov/1999
 * @author  Catalin Rotaru [CATA]
 */
class nsCharsetMenu : public nsIRDFDataSource, public nsICurrentCharsetListener
{
  NS_DECL_ISUPPORTS

private:
  static nsIRDFResource * kNC_BrowserAutodetMenuRoot;
  static nsIRDFResource * kNC_BrowserCharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMoreCharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMore1CharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMore2CharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMore3CharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMore4CharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserMore5CharsetMenuRoot;
  static nsIRDFResource * kNC_BrowserUnicodeCharsetMenuRoot;
  static nsIRDFResource * kNC_MaileditCharsetMenuRoot;
  static nsIRDFResource * kNC_MailviewCharsetMenuRoot;
  static nsIRDFResource * kNC_ComposerCharsetMenuRoot;
  static nsIRDFResource * kNC_DecodersRoot;
  static nsIRDFResource * kNC_EncodersRoot;
  static nsIRDFResource * kNC_Name;
  static nsIRDFResource * kNC_Checked;
  static nsIRDFResource * kNC_CharsetDetector;
  static nsIRDFResource * kNC_BookmarkSeparator;
  static nsIRDFResource * kRDF_type;

  static nsIRDFDataSource * mInner;

  PRPackedBool mInitialized;
  PRPackedBool mBrowserMenuInitialized;
  PRPackedBool mMailviewMenuInitialized;
  PRPackedBool mComposerMenuInitialized;
  PRPackedBool mMaileditMenuInitialized;
  PRPackedBool mSecondaryTiersInitialized;
  PRPackedBool mAutoDetectInitialized;
  PRPackedBool mOthersInitialized;

  nsVoidArray   mBrowserMenu;
  PRInt32       mBrowserCacheStart;
  PRInt32       mBrowserCacheSize;
  PRInt32       mBrowserMenuRDFPosition;

  nsVoidArray   mMailviewMenu;
  PRInt32       mMailviewCacheStart;
  PRInt32       mMailviewCacheSize;
  PRInt32       mMailviewMenuRDFPosition;

  nsVoidArray   mComposerMenu;
  PRInt32       mComposerCacheStart;
  PRInt32       mComposerCacheSize;
  PRInt32       mComposerMenuRDFPosition;

  nsCOMPtr<nsIRDFService>               mRDFService;
  nsCOMPtr<nsICharsetConverterManager> mCCManager;
  nsCOMPtr<nsIPrefBranch>               mPrefs;
  nsCOMPtr<nsIObserver>                 mCharsetMenuObserver;
  nsCStringArray                        mDecoderList;

  nsresult Done();
  nsresult SetCharsetCheckmark(nsString * aCharset, PRBool aValue);

  nsresult FreeResources();

  nsresult InitStaticMenu(nsCStringArray& aDecs, 
                          nsIRDFResource * aResource,
                          const char * aKey,
                          nsVoidArray * aArray);
  nsresult InitCacheMenu(nsCStringArray& aDecs,
                         nsIRDFResource * aResource,
                         const char * aKey,
                         nsVoidArray * aArray);
  
  nsresult InitMoreMenu(nsCStringArray& aDecs,
                        nsIRDFResource * aResource, 
                        const char * aFlag);
  
  nsresult InitMoreSubmenus(nsCStringArray& aDecs);

  static nsresult SetArrayFromEnumerator(nsIUTF8StringEnumerator* aEnumerator,
                                         nsCStringArray& aArray);
  
  nsresult AddCharsetToItemArray(nsVoidArray* aArray,
                                 const nsAFlatCString& aCharset, 
                                 nsMenuEntry ** aResult,
                                 PRInt32 aPlace);
  nsresult AddCharsetArrayToItemArray(nsVoidArray &aArray, 
                                      const nsCStringArray& aCharsets);
  nsresult AddMenuItemToContainer(nsIRDFContainer * aContainer, 
    nsMenuEntry * aItem, nsIRDFResource * aType, const char * aIDPrefix, 
    PRInt32 aPlace);
  nsresult AddMenuItemArrayToContainer(nsIRDFContainer * aContainer, 
    nsVoidArray * aArray, nsIRDFResource * aType);
  nsresult AddCharsetToContainer(nsVoidArray * aArray, 
                                 nsIRDFContainer * aContainer,
                                 const nsAFlatCString& aCharset,
                                 const char * aIDPrefix, 
    PRInt32 aPlace, PRInt32 aRDFPlace);

  nsresult AddFromPrefsToMenu(nsVoidArray * aArray, 
                              nsIRDFContainer * aContainer,
                              const char * aKey,
                              nsCStringArray& aDecs,
                              const char * aIDPrefix);
  nsresult AddFromNolocPrefsToMenu(nsVoidArray * aArray, 
                                   nsIRDFContainer * aContainer,
                                   const char * aKey,
                                   nsCStringArray& aDecs,
                                   const char * aIDPrefix);
  nsresult AddFromStringToMenu(char * aCharsetList,
                               nsVoidArray * aArray,
                               nsIRDFContainer * aContainer,
                               nsCStringArray& aDecs,
                               const char * aIDPrefix);

  nsresult AddSeparatorToContainer(nsIRDFContainer * aContainer);
  nsresult AddCharsetToCache(const nsAFlatCString& aCharset,
                             nsVoidArray * aArray, 
                             nsIRDFResource * aRDFResource,
                             PRInt32 aCacheStart, PRInt32 aCacheSize, 
                             PRInt32 aRDFPlace);

  nsresult WriteCacheToPrefs(nsVoidArray * aArray, PRInt32 aCacheStart, 
    const char * aKey);
  nsresult UpdateCachePrefs(const char * aCacheKey, const char * aCacheSizeKey, 
    const char * aStaticKey, const PRUnichar * aCharset);

  nsresult ClearMenu(nsIRDFContainer * aContainer, nsVoidArray * aArray);
  nsresult RemoveLastMenuItem(nsIRDFContainer * aContainer, 
                              nsVoidArray * aArray);

  nsresult RemoveFlaggedCharsets(nsCStringArray& aList, nsString * aProp);
  nsresult NewRDFContainer(nsIRDFDataSource * aDataSource, 
    nsIRDFResource * aResource, nsIRDFContainer ** aResult);
  void FreeMenuItemArray(nsVoidArray * aArray);
  PRInt32 FindMenuItemInArray(const nsVoidArray* aArray,
                              const nsAFlatCString& aCharset, 
                              nsMenuEntry ** aResult);
  nsresult ReorderMenuItemArray(nsVoidArray * aArray);
  nsresult GetCollation(nsICollation ** aCollation);

public:
  nsCharsetMenu();
  virtual ~nsCharsetMenu();

  nsresult Init();
  nsresult InitBrowserMenu();
  nsresult InitMaileditMenu();
  nsresult InitMailviewMenu();
  nsresult InitComposerMenu();
  nsresult InitOthers();
  nsresult InitSecondaryTiers();
  nsresult InitAutodetMenu();
  nsresult RefreshBrowserMenu();
  nsresult RefreshMailviewMenu();
  nsresult RefreshMaileditMenu();
  nsresult RefreshComposerMenu();

  //--------------------------------------------------------------------------
  // Interface nsICurrentCharsetListener [declaration]

  NS_IMETHOD SetCurrentCharset(const PRUnichar * aCharset);
  NS_IMETHOD SetCurrentMailCharset(const PRUnichar * aCharset);
  NS_IMETHOD SetCurrentComposerCharset(const PRUnichar * aCharset);

  //--------------------------------------------------------------------------
  // Interface nsIRDFDataSource [declaration]

  NS_DECL_NSIRDFDATASOURCE
};

//----------------------------------------------------------------------------
// Global functions and data [implementation]

NS_IMETHODIMP NS_NewCharsetMenu(nsISupports * aOuter, const nsIID & aIID, 
                                void ** aResult)
{
  if (!aResult) {
    return NS_ERROR_NULL_POINTER;
  }
  if (aOuter) {
    *aResult = nsnull;
    return NS_ERROR_NO_AGGREGATION;
  }
  nsCharsetMenu* inst = new nsCharsetMenu();
  if (!inst) {
    *aResult = nsnull;
    return NS_ERROR_OUT_OF_MEMORY;
  }
  nsresult res = inst->QueryInterface(aIID, aResult);
  if (NS_FAILED(res)) {
    *aResult = nsnull;
    delete inst;
  }
  return res;
}

struct charsetMenuSortRecord {
  nsMenuEntry* item;
  PRUint8*     key;
  PRUint32     len;

};

static int PR_CALLBACK CompareMenuItems(const void* aArg1, const void* aArg2, void *data)
{
  PRInt32 res; 
  nsICollation * collation = (nsICollation *) data;
  charsetMenuSortRecord *rec1 = (charsetMenuSortRecord *) aArg1;
  charsetMenuSortRecord *rec2 = (charsetMenuSortRecord *) aArg2;

  collation->CompareRawSortKey(rec1->key, rec1->len, rec2->key, rec2->len, &res);

  return res;
}

nsresult
nsCharsetMenu::SetArrayFromEnumerator(nsIUTF8StringEnumerator* aEnumerator,
                                      nsCStringArray& aArray)
{
  nsresult rv;
  
  PRBool hasMore;
  rv = aEnumerator->HasMore(&hasMore);
  
  nsCAutoString value;
  while (NS_SUCCEEDED(rv) && hasMore) {
    rv = aEnumerator->GetNext(value);
    if (NS_SUCCEEDED(rv))
      aArray.AppendCString(value);

    rv = aEnumerator->HasMore(&hasMore);
  }

  return rv;
}
  
//----------------------------------------------------------------------------
// Class nsCharsetMenuObserver

class nsCharsetMenuObserver : public nsIObserver {

public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIOBSERVER

  nsCharsetMenuObserver(nsCharsetMenu * menu)
    : mCharsetMenu(menu)
  {
  }

  virtual ~nsCharsetMenuObserver() {}

private:
  nsCharsetMenu* mCharsetMenu;
};

NS_IMPL_ISUPPORTS1(nsCharsetMenuObserver, nsIObserver)

NS_IMETHODIMP nsCharsetMenuObserver::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *someData)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu:Observe");
  nsresult rv = NS_OK;
 
  //XUL event handler
  if (!nsCRT::strcmp(aTopic, "charsetmenu-selected")) {
    nsDependentString nodeName(someData);
    rv = mCharsetMenu->Init();
    if (nodeName.EqualsLiteral("browser")) {
      rv = mCharsetMenu->InitBrowserMenu();
    }
    if (nodeName.EqualsLiteral("composer")) {
      rv = mCharsetMenu->InitComposerMenu();
    }
    if (nodeName.EqualsLiteral("mailview")) {
      rv = mCharsetMenu->InitMailviewMenu();
    }
    if (nodeName.EqualsLiteral("mailedit")) {
      rv = mCharsetMenu->InitMaileditMenu();
      rv = mCharsetMenu->InitOthers();
    }
    if (nodeName.EqualsLiteral("more-menu")) {
      rv = mCharsetMenu->InitSecondaryTiers();
      rv = mCharsetMenu->InitAutodetMenu();
    }
    if (nodeName.EqualsLiteral("other")) {
      rv = mCharsetMenu->InitOthers();
      rv = mCharsetMenu->InitMaileditMenu();
    }
  }
   
   //pref event handler
  if (!nsCRT::strcmp(aTopic, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID)) {
    nsDependentString prefName(someData);

    if (prefName.EqualsLiteral(kBrowserStaticPrefKey)) {
      // refresh menus which share this pref
      rv = mCharsetMenu->RefreshBrowserMenu();
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mCharsetMenu->RefreshMailviewMenu();
      NS_ENSURE_SUCCESS(rv, rv);
      rv = mCharsetMenu->RefreshComposerMenu();
    }
    else if (prefName.EqualsLiteral(kMaileditPrefKey)) {
      rv = mCharsetMenu->RefreshMaileditMenu();
    }
  }

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu:Observe");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu:Observe");
  return rv;
}

//----------------------------------------------------------------------------
// Class nsCharsetMenu [implementation]

NS_IMPL_ISUPPORTS2(nsCharsetMenu, nsIRDFDataSource, nsICurrentCharsetListener)

nsIRDFDataSource * nsCharsetMenu::mInner = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserAutodetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMoreCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMore1CharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMore2CharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMore3CharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMore4CharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserMore5CharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BrowserUnicodeCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_MaileditCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_MailviewCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_ComposerCharsetMenuRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_DecodersRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_EncodersRoot = NULL;
nsIRDFResource * nsCharsetMenu::kNC_Name = NULL;
nsIRDFResource * nsCharsetMenu::kNC_Checked = NULL;
nsIRDFResource * nsCharsetMenu::kNC_CharsetDetector = NULL;
nsIRDFResource * nsCharsetMenu::kNC_BookmarkSeparator = NULL;
nsIRDFResource * nsCharsetMenu::kRDF_type = NULL;

nsCharsetMenu::nsCharsetMenu() 
: mInitialized(PR_FALSE), 
  mBrowserMenuInitialized(PR_FALSE),
  mMailviewMenuInitialized(PR_FALSE),
  mComposerMenuInitialized(PR_FALSE),
  mMaileditMenuInitialized(PR_FALSE),
  mSecondaryTiersInitialized(PR_FALSE),
  mAutoDetectInitialized(PR_FALSE),
  mOthersInitialized(PR_FALSE)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::nsCharsetMenu");
  nsresult res = NS_OK;

  //get charset manager
  mCCManager = do_GetService(kCharsetConverterManagerCID, &res);

  //initialize skeleton RDF source
  mRDFService = do_GetService(kRDFServiceCID, &res);

  if (NS_SUCCEEDED(res))  {
    mRDFService->RegisterDataSource(this, PR_FALSE);
  
    CallCreateInstance(kRDFInMemoryDataSourceCID, &mInner);

    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserCharsetMenuRoot),
                             &kNC_BrowserCharsetMenuRoot);
  }

  //get pref service
  nsCOMPtr<nsIPrefService> PrefService = do_GetService(NS_PREFSERVICE_CONTRACTID, &res);
  if (NS_SUCCEEDED(res))
    res = PrefService->GetBranch(nsnull, getter_AddRefs(mPrefs));

  //register event listener
  mCharsetMenuObserver = new nsCharsetMenuObserver(this);

  if (mCharsetMenuObserver)  {
    nsCOMPtr<nsIObserverService> observerService = 
             do_GetService("@mozilla.org/observer-service;1", &res);

    if (NS_SUCCEEDED(res))
      res = observerService->AddObserver(mCharsetMenuObserver, 
                                         "charsetmenu-selected", 
                                         PR_FALSE);
  }

  NS_ASSERTION(NS_SUCCEEDED(res), "Failed to initialize nsCharsetMenu");
  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::nsCharsetMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::nsCharsetMenu");
}

nsCharsetMenu::~nsCharsetMenu() 
{
  Done();

  FreeMenuItemArray(&mBrowserMenu);
  FreeMenuItemArray(&mMailviewMenu);
  FreeMenuItemArray(&mComposerMenu);

  FreeResources();
}

// XXX collapse these 2 in one

nsresult nsCharsetMenu::RefreshBrowserMenu()
{
  nsresult res = NS_OK;

  nsCOMPtr<nsIRDFContainer> container;
  res = NewRDFContainer(mInner, kNC_BrowserCharsetMenuRoot, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // clean the menu
  res = ClearMenu(container, &mBrowserMenu);
  if (NS_FAILED(res)) return res;

  // rebuild the menu
  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
  if (NS_FAILED(res)) return res;

  nsCStringArray decs;
  SetArrayFromEnumerator(decoders, decs);
  
  res = AddFromPrefsToMenu(&mBrowserMenu, container, kBrowserStaticPrefKey, 
                           decs, "charset.");
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing static charset menu from prefs");

  // mark the end of the static area, the rest is cache
  mBrowserCacheStart = mBrowserMenu.Count();

  res = InitCacheMenu(decs, kNC_BrowserCharsetMenuRoot, kBrowserCachePrefKey, 
                      &mBrowserMenu);
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing browser cache charset menu");

  return res;
}

nsresult nsCharsetMenu::RefreshMailviewMenu()
{
  nsresult res = NS_OK;

  nsCOMPtr<nsIRDFContainer> container;
  res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // clean the menu
  res = ClearMenu(container, &mMailviewMenu);
  if (NS_FAILED(res)) return res;

  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
  if (NS_FAILED(res)) return res;

  nsCStringArray decs;
  SetArrayFromEnumerator(decoders, decs);
  
  res = AddFromPrefsToMenu(&mMailviewMenu, container, kMailviewStaticPrefKey, 
                           decs, "charset.");
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing static charset menu from prefs");

  // mark the end of the static area, the rest is cache
  mMailviewCacheStart = mMailviewMenu.Count();

  res = InitCacheMenu(decs, kNC_MailviewCharsetMenuRoot, 
    kMailviewCachePrefKey, &mMailviewMenu);
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailview cache charset menu");

  return res;
}

nsresult nsCharsetMenu::RefreshMaileditMenu()
{
  nsresult res;

  nsCOMPtr<nsIRDFContainer> container;
  res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, getter_AddRefs(container));
  NS_ENSURE_SUCCESS(res, res);

  nsCOMPtr<nsISimpleEnumerator> enumerator;
  res = container->GetElements(getter_AddRefs(enumerator));
  NS_ENSURE_SUCCESS(res, res);

  // clear the menu
  nsCOMPtr<nsIRDFNode> node;
  while (NS_SUCCEEDED(enumerator->GetNext(getter_AddRefs(node)))) {

    res = mInner->Unassert(kNC_MaileditCharsetMenuRoot, kNC_Name, node);
    NS_ENSURE_SUCCESS(res, res);

    res = container->RemoveElement(node, PR_FALSE);
    NS_ENSURE_SUCCESS(res, res);
  }

  // get a list of available encoders
  nsCOMPtr<nsIUTF8StringEnumerator> encoders;
  res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
  NS_ENSURE_SUCCESS(res, res);

  nsCStringArray encs;
  SetArrayFromEnumerator(encoders, encs);
  
  // add menu items from pref
  res = AddFromPrefsToMenu(NULL, container, kMaileditPrefKey, encs, NULL);
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailedit charset menu from prefs");

  return res;
}

nsresult nsCharsetMenu::RefreshComposerMenu()
{
  nsresult res = NS_OK;

  nsCOMPtr<nsIRDFContainer> container;
  res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // clean the menu
  res = ClearMenu(container, &mComposerMenu);
  if (NS_FAILED(res)) return res;

  nsCOMPtr<nsIUTF8StringEnumerator> decoders;
  res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
  if (NS_FAILED(res)) return res;

  nsCStringArray decs;
  SetArrayFromEnumerator(decoders, decs);
  
  res = AddFromPrefsToMenu(&mComposerMenu, container, kComposerStaticPrefKey, 
                           decs, "charset.");
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing static charset menu from prefs");

  // mark the end of the static area, the rest is cache
  mComposerCacheStart = mComposerMenu.Count();

  res = InitCacheMenu(decs, kNC_ComposerCharsetMenuRoot, 
    kComposerCachePrefKey, &mComposerMenu);
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing composer cache charset menu");

  return res;
}

nsresult nsCharsetMenu::Init() 
{
  nsresult res = NS_OK;

  if (!mInitialized)  {

    //enumerate decoders
    nsCOMPtr<nsIUTF8StringEnumerator> decoders;
    res = mCCManager->GetDecoderList(getter_AddRefs(decoders));
    if (NS_FAILED(res)) return res;

    SetArrayFromEnumerator(decoders, mDecoderList);

    //initialize all remaining RDF template nodes
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserAutodetMenuRoot),
                             &kNC_BrowserAutodetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMoreCharsetMenuRoot),
                             &kNC_BrowserMoreCharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMore1CharsetMenuRoot),
                             &kNC_BrowserMore1CharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMore2CharsetMenuRoot),
                             &kNC_BrowserMore2CharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMore3CharsetMenuRoot),
                             &kNC_BrowserMore3CharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMore4CharsetMenuRoot),
                             &kNC_BrowserMore4CharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserMore5CharsetMenuRoot),
                             &kNC_BrowserMore5CharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BrowserUnicodeCharsetMenuRoot),
                             &kNC_BrowserUnicodeCharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_MaileditCharsetMenuRoot),
                             &kNC_MaileditCharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_MailviewCharsetMenuRoot),
                             &kNC_MailviewCharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_ComposerCharsetMenuRoot),
                             &kNC_ComposerCharsetMenuRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_DecodersRoot),
                             &kNC_DecodersRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_EncodersRoot),
                             &kNC_EncodersRoot);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_Name),
                             &kNC_Name);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_Checked),
                             &kNC_Checked);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_CharsetDetector),
                             &kNC_CharsetDetector);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_BookmarkSeparator),
                             &kNC_BookmarkSeparator);
    mRDFService->GetResource(NS_LITERAL_CSTRING(kURINC_type), &kRDF_type);

    nsIRDFContainerUtils * rdfUtil = NULL;
    res = CallGetService(kRDFContainerUtilsCID, &rdfUtil);
    if (NS_FAILED(res)) goto done;

    res = rdfUtil->MakeSeq(mInner, kNC_BrowserAutodetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMoreCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore1CharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore2CharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore3CharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore4CharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserMore5CharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_BrowserUnicodeCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_MaileditCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_MailviewCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_ComposerCharsetMenuRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_DecodersRoot, NULL);
    if (NS_FAILED(res)) goto done;
    res = rdfUtil->MakeSeq(mInner, kNC_EncodersRoot, NULL);
    if (NS_FAILED(res)) goto done;

  done:
    NS_IF_RELEASE(rdfUtil);
    if (NS_FAILED(res)) return res;
  }
  mInitialized = NS_SUCCEEDED(res);
  return res;
}

nsresult nsCharsetMenu::Done() 
{
  nsresult res = NS_OK;
  res = mRDFService->UnregisterDataSource(this);

  NS_IF_RELEASE(kNC_BrowserAutodetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserCharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMoreCharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMore1CharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMore2CharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMore3CharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMore4CharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserMore5CharsetMenuRoot);
  NS_IF_RELEASE(kNC_BrowserUnicodeCharsetMenuRoot);
  NS_IF_RELEASE(kNC_MaileditCharsetMenuRoot);
  NS_IF_RELEASE(kNC_MailviewCharsetMenuRoot);
  NS_IF_RELEASE(kNC_ComposerCharsetMenuRoot);
  NS_IF_RELEASE(kNC_DecodersRoot);
  NS_IF_RELEASE(kNC_EncodersRoot);
  NS_IF_RELEASE(kNC_Name);
  NS_IF_RELEASE(kNC_Checked);
  NS_IF_RELEASE(kNC_CharsetDetector);
  NS_IF_RELEASE(kNC_BookmarkSeparator);
  NS_IF_RELEASE(kRDF_type);
  NS_IF_RELEASE(mInner);

  return res;
}

nsresult nsCharsetMenu::SetCharsetCheckmark(nsString * aCharset, 
                                            PRBool aValue)
{
  nsresult res = NS_OK;
  nsCOMPtr<nsIRDFContainer> container;
  nsCOMPtr<nsIRDFResource> node;

  res = NewRDFContainer(mInner, kNC_BrowserCharsetMenuRoot, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // find RDF node for given charset
  res = mRDFService->GetUnicodeResource(*aCharset, getter_AddRefs(node));
  if (NS_FAILED(res)) return res;

  // set checkmark value
  nsCOMPtr<nsIRDFLiteral> checkedLiteral;
  nsAutoString checked; checked.AssignWithConversion((aValue == PR_TRUE) ? "true" : "false");
  res = mRDFService->GetLiteral(checked.get(), getter_AddRefs(checkedLiteral));
  if (NS_FAILED(res)) return res;
  res = Assert(node, kNC_Checked, checkedLiteral, PR_TRUE);
  if (NS_FAILED(res)) return res;

  return res;
}

/**
 * Free the resources no longer needed by the component.
 */
nsresult nsCharsetMenu::FreeResources()
{
  nsresult res = NS_OK;

  if (mCharsetMenuObserver) {
    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
    if (pbi) {
      pbi->RemoveObserver(kBrowserStaticPrefKey, mCharsetMenuObserver);
      pbi->RemoveObserver(kMaileditPrefKey, mCharsetMenuObserver);
    }
    /* nsIObserverService has to have released nsCharsetMenu already */
  }

  mRDFService = NULL;
  mCCManager  = NULL;
  mPrefs      = NULL;

  return res;
}

nsresult nsCharsetMenu::InitBrowserMenu() 
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitBrowserMenu");

  nsresult res = NS_OK;

  if (!mBrowserMenuInitialized)  {
    nsCOMPtr<nsIRDFContainer> container;
    res = NewRDFContainer(mInner, kNC_BrowserCharsetMenuRoot, getter_AddRefs(container));
    if (NS_FAILED(res)) return res;


    // how to clone mDecoderList??
    nsCStringArray browserDecoderList;
    CloneCStringArray(mDecoderList, browserDecoderList);

    res = InitStaticMenu(browserDecoderList, kNC_BrowserCharsetMenuRoot, 
                         kBrowserStaticPrefKey, &mBrowserMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing browser static charset menu");

    // mark the end of the static area, the rest is cache
    mBrowserCacheStart = mBrowserMenu.Count();
    mPrefs->GetIntPref(kBrowserCacheSizePrefKey, &mBrowserCacheSize);

    // compute the position of the menu in the RDF container
    res = container->GetCount(&mBrowserMenuRDFPosition);
    if (NS_FAILED(res)) return res;
    // this "1" here is a correction necessary because the RDF container 
    // elements are numbered from 1 (why god, WHY?!?!?!)
    mBrowserMenuRDFPosition -= mBrowserCacheStart - 1;

    res = InitCacheMenu(browserDecoderList, kNC_BrowserCharsetMenuRoot, kBrowserCachePrefKey, 
      &mBrowserMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing browser cache charset menu");

    // register prefs callback
    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
    if (pbi)
      res = pbi->AddObserver(kBrowserStaticPrefKey, mCharsetMenuObserver, PR_FALSE);
  }

  mBrowserMenuInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitBrowserMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitBrowserMenu");

  return res;
}

nsresult nsCharsetMenu::InitMaileditMenu() 
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitMaileditMenu");

  nsresult res = NS_OK;

  if (!mMaileditMenuInitialized)  {
    nsCOMPtr<nsIRDFContainer> container;
    res = NewRDFContainer(mInner, kNC_MaileditCharsetMenuRoot, getter_AddRefs(container));
    if (NS_FAILED(res)) return res;

    //enumerate encoders
    // this would bring in a whole bunch of 'font encoders' as well as genuine 
    // charset encoders, but it's safe because we rely on prefs to filter
    // them out. Moreover, 'customize' menu lists only genuine charset 
    // encoders further guarding  against  'font encoders' sneaking in. 
    nsCOMPtr<nsIUTF8StringEnumerator> encoders;
    res = mCCManager->GetEncoderList(getter_AddRefs(encoders));
    if (NS_FAILED(res))  return res;

    nsCStringArray maileditEncoderList;
    SetArrayFromEnumerator(encoders, maileditEncoderList);
  
    res = AddFromPrefsToMenu(NULL, container, kMaileditPrefKey, maileditEncoderList, NULL);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailedit charset menu from prefs");

    // register prefs callback
    nsCOMPtr<nsIPrefBranch2> pbi = do_QueryInterface(mPrefs);
    if (pbi)
      res = pbi->AddObserver(kMaileditPrefKey, mCharsetMenuObserver, PR_FALSE);
  }

  mMaileditMenuInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitMaileditMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitMaileditMenu");

  return res;
}

nsresult nsCharsetMenu::InitMailviewMenu() 
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitMailviewMenu");
  
  nsresult res = NS_OK;

  if (!mMailviewMenuInitialized)  {
    nsCOMPtr<nsIRDFContainer> container;
    res = NewRDFContainer(mInner, kNC_MailviewCharsetMenuRoot, getter_AddRefs(container));
    if (NS_FAILED(res)) return res;

    nsCStringArray mailviewDecoderList;
    CloneCStringArray(mDecoderList, mailviewDecoderList);

    res = InitStaticMenu(mailviewDecoderList, kNC_MailviewCharsetMenuRoot, 
                         kMailviewStaticPrefKey, &mMailviewMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailview static charset menu");

    // mark the end of the static area, the rest is cache
    mMailviewCacheStart = mMailviewMenu.Count();
    mPrefs->GetIntPref(kMailviewCacheSizePrefKey, &mMailviewCacheSize);

    // compute the position of the menu in the RDF container
    res = container->GetCount(&mMailviewMenuRDFPosition);
    if (NS_FAILED(res)) return res;
    // this "1" here is a correction necessary because the RDF container 
    // elements are numbered from 1 (why god, WHY?!?!?!)
    mMailviewMenuRDFPosition -= mMailviewCacheStart - 1;

    res = InitCacheMenu(mailviewDecoderList, kNC_MailviewCharsetMenuRoot, 
      kMailviewCachePrefKey, &mMailviewMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing mailview cache charset menu");
  }

  mMailviewMenuInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitMailviewMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitMailviewMenu");

  return res;
}

nsresult nsCharsetMenu::InitComposerMenu() 
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitComposerMenu");
 
  nsresult res = NS_OK;

  if (!mComposerMenuInitialized)  {
    nsCOMPtr<nsIRDFContainer> container;
    res = NewRDFContainer(mInner, kNC_ComposerCharsetMenuRoot, getter_AddRefs(container));
    if (NS_FAILED(res)) return res;

    nsCStringArray composerDecoderList;
    CloneCStringArray(mDecoderList, composerDecoderList);

    // even if we fail, the show must go on
    res = InitStaticMenu(composerDecoderList, kNC_ComposerCharsetMenuRoot, 
      kComposerStaticPrefKey, &mComposerMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing composer static charset menu");

    // mark the end of the static area, the rest is cache
    mComposerCacheStart = mComposerMenu.Count();
    mPrefs->GetIntPref(kComposerCacheSizePrefKey, &mComposerCacheSize);

    // compute the position of the menu in the RDF container
    res = container->GetCount(&mComposerMenuRDFPosition);
    if (NS_FAILED(res)) return res;
    // this "1" here is a correction necessary because the RDF container 
    // elements are numbered from 1 (why god, WHY?!?!?!)
    mComposerMenuRDFPosition -= mComposerCacheStart - 1;

    res = InitCacheMenu(composerDecoderList, kNC_ComposerCharsetMenuRoot, 
      kComposerCachePrefKey, &mComposerMenu);
    NS_ASSERTION(NS_SUCCEEDED(res), "error initializing composer cache charset menu");
  }

  mComposerMenuInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitComposerMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitComposerMenu");
  
  return res;
}

nsresult nsCharsetMenu::InitOthers() 
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitOthers");

  nsresult res = NS_OK;

  if (!mOthersInitialized) {
    nsCStringArray othersDecoderList;
    CloneCStringArray(mDecoderList, othersDecoderList);

    res = InitMoreMenu(othersDecoderList, kNC_DecodersRoot, ".notForBrowser");                 
    if (NS_FAILED(res))  return res;

    // Using mDecoderList instead of GetEncoderList(), we can avoid having to
    // tag a whole bunch of 'font encoders' with '.notForOutgoing' in 
    // charsetData.properties file. 
    nsCStringArray othersEncoderList;
    CloneCStringArray(mDecoderList, othersEncoderList);

    res = InitMoreMenu(othersEncoderList, kNC_EncodersRoot, ".notForOutgoing");                 
    if (NS_FAILED(res)) return res;
  }

  mOthersInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitOthers");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitOthers");

  return res;
}

/**
 * Inits the secondary tiers of the charset menu. Because currently all the CS 
 * menus are sharing the secondary tiers, one should call this method only 
 * once for all of them.
 */
nsresult nsCharsetMenu::InitSecondaryTiers()
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitSecondaryTiers");

  nsresult res = NS_OK;

  if (!mSecondaryTiersInitialized)  {
    nsCStringArray secondaryTiersDecoderList;
    CloneCStringArray(mDecoderList, secondaryTiersDecoderList);

    res = InitMoreSubmenus(secondaryTiersDecoderList);
    NS_ASSERTION(NS_SUCCEEDED(res), "err init browser charset more submenus");

    res = InitMoreMenu(secondaryTiersDecoderList, kNC_BrowserMoreCharsetMenuRoot, ".notForBrowser");
    NS_ASSERTION(NS_SUCCEEDED(res), "err init browser charset more menu");
  }

  mSecondaryTiersInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitSecondaryTiers");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitSecondaryTiers");

  return res;
}

nsresult nsCharsetMenu::InitStaticMenu(nsCStringArray& aDecs,
                                       nsIRDFResource * aResource, 
                                       const char * aKey, 
                                       nsVoidArray * aArray)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitStaticMenu");

  nsresult res = NS_OK;
  nsCOMPtr<nsIRDFContainer> container;

  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // XXX work around bug that causes the submenus to be first instead of last
  res = AddSeparatorToContainer(container);
  NS_ASSERTION(NS_SUCCEEDED(res), "error adding separator to container");

  res = AddFromPrefsToMenu(aArray, container, aKey, aDecs, "charset.");
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing static charset menu from prefs");

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitStaticMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitStaticMenu");

  return res;
}

nsresult nsCharsetMenu::InitCacheMenu(
                        nsCStringArray& aDecs,
                        nsIRDFResource * aResource, 
                        const char * aKey, 
                        nsVoidArray * aArray)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitCacheMenu");

  nsresult res = NS_OK;
  nsCOMPtr<nsIRDFContainer> container;

  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  res = AddFromNolocPrefsToMenu(aArray, container, aKey, aDecs, "charset.");
  NS_ASSERTION(NS_SUCCEEDED(res), "error initializing cache charset menu from prefs");

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitCacheMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitCacheMenu");

  return res;
}

nsresult nsCharsetMenu::InitAutodetMenu()
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitAutodetMenu");

  nsresult res = NS_OK;

  if (!mAutoDetectInitialized) {
    nsVoidArray chardetArray;
    nsCOMPtr<nsIRDFContainer> container;
    nsCStringArray detectorArray;

    res = NewRDFContainer(mInner, kNC_BrowserAutodetMenuRoot, getter_AddRefs(container));
    if (NS_FAILED(res)) return res;

    nsCOMPtr<nsIUTF8StringEnumerator> detectors;
    res = mCCManager->GetCharsetDetectorList(getter_AddRefs(detectors));
    if (NS_FAILED(res)) goto done;

    res = SetArrayFromEnumerator(detectors, detectorArray);
    if (NS_FAILED(res)) goto done;
    
    res = AddCharsetArrayToItemArray(chardetArray, detectorArray);
    if (NS_FAILED(res)) goto done;

    // reorder the array
    res = ReorderMenuItemArray(&chardetArray);
    if (NS_FAILED(res)) goto done;

    res = AddMenuItemArrayToContainer(container, &chardetArray, 
      kNC_CharsetDetector);
    if (NS_FAILED(res)) goto done;

  done:
    // free the elements in the VoidArray
    FreeMenuItemArray(&chardetArray);
  }

  mAutoDetectInitialized = NS_SUCCEEDED(res);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitAutodetMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitAutodetMenu");

  return res;
}

nsresult nsCharsetMenu::InitMoreMenu(nsCStringArray& aDecs, 
                                     nsIRDFResource * aResource, 
                                     const char * aFlag)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitMoreMenu");

  nsresult res = NS_OK;
  nsCOMPtr<nsIRDFContainer> container;
  nsVoidArray moreMenu;
  nsAutoString prop; prop.AssignWithConversion(aFlag);

  res = NewRDFContainer(mInner, aResource, getter_AddRefs(container));
  if (NS_FAILED(res)) goto done;

  // remove charsets "not for browser"
  res = RemoveFlaggedCharsets(aDecs, &prop);
  if (NS_FAILED(res)) goto done;

  res = AddCharsetArrayToItemArray(moreMenu, aDecs);
  if (NS_FAILED(res)) goto done;

  // reorder the array
  res = ReorderMenuItemArray(&moreMenu);
  if (NS_FAILED(res)) goto done;

  res = AddMenuItemArrayToContainer(container, &moreMenu, NULL);
  if (NS_FAILED(res)) goto done;

done:
  // free the elements in the VoidArray
  FreeMenuItemArray(&moreMenu);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitMoreMenu");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitMoreMenu");

  return res;
}

// XXX please make this method more general; the cut&pasted code is laughable
nsresult nsCharsetMenu::InitMoreSubmenus(nsCStringArray& aDecs)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu::InitMoreSubmenus");

  nsresult res = NS_OK;

  nsCOMPtr<nsIRDFContainer> container1;
  nsCOMPtr<nsIRDFContainer> container2;
  nsCOMPtr<nsIRDFContainer> container3;
  nsCOMPtr<nsIRDFContainer> container4;
  nsCOMPtr<nsIRDFContainer> container5;
  nsCOMPtr<nsIRDFContainer> containerU;
  const char key1[] = "intl.charsetmenu.browser.more1";
  const char key2[] = "intl.charsetmenu.browser.more2";
  const char key3[] = "intl.charsetmenu.browser.more3";
  const char key4[] = "intl.charsetmenu.browser.more4";
  const char key5[] = "intl.charsetmenu.browser.more5";
  const char keyU[] = "intl.charsetmenu.browser.unicode";

  res = NewRDFContainer(mInner, kNC_BrowserMore1CharsetMenuRoot, 
    getter_AddRefs(container1));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, container1, key1, aDecs, NULL);

  res = NewRDFContainer(mInner, kNC_BrowserMore2CharsetMenuRoot, 
    getter_AddRefs(container2));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, container2, key2, aDecs, NULL);

  res = NewRDFContainer(mInner, kNC_BrowserMore3CharsetMenuRoot, 
    getter_AddRefs(container3));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, container3, key3, aDecs, NULL);

  res = NewRDFContainer(mInner, kNC_BrowserMore4CharsetMenuRoot, 
    getter_AddRefs(container4));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, container4, key4, aDecs, NULL);

  res = NewRDFContainer(mInner, kNC_BrowserMore5CharsetMenuRoot, 
    getter_AddRefs(container5));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, container5, key5, aDecs, NULL);

  res = NewRDFContainer(mInner, kNC_BrowserUnicodeCharsetMenuRoot, 
    getter_AddRefs(containerU));
  if (NS_FAILED(res)) return res;
  AddFromPrefsToMenu(NULL, containerU, keyU, aDecs, NULL);

  NS_TIMELINE_STOP_TIMER("nsCharsetMenu::InitMoreSubmenus");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu::InitMoreSubmenus");

  return res;
}

nsresult nsCharsetMenu::AddCharsetToItemArray(nsVoidArray *aArray, 
                                              const nsAFlatCString& aCharset, 
                                              nsMenuEntry ** aResult,
                                              PRInt32 aPlace) 
{
  nsresult res = NS_OK;
  nsMenuEntry * item = NULL; 

  if (aResult != NULL) *aResult = NULL;
  
  item = new nsMenuEntry();
  if (item == NULL) {
    res = NS_ERROR_OUT_OF_MEMORY;
    goto done;
  }

  item->mCharset = aCharset;

  res = mCCManager->GetCharsetTitle(aCharset.get(), item->mTitle);
  if (NS_FAILED(res)) {
    item->mTitle.AssignWithConversion(aCharset.get());
  }

  if (aArray != NULL) {
    if (aPlace < 0) {
      res = aArray->AppendElement(item);
      if (NS_FAILED(res)) goto done;
    } else {
      res = aArray->InsertElementAt(item, aPlace);
      if (NS_FAILED(res)) goto done;
    }
  }

  if (aResult != NULL) *aResult = item;

  // if we have made another reference to "item", do not delete it 
  if ((aArray != NULL) || (aResult != NULL)) item = NULL; 

done:
  if (item != NULL) delete item;

  return res;
}

nsresult
nsCharsetMenu::AddCharsetArrayToItemArray(nsVoidArray& aArray, 
                                          const nsCStringArray& aCharsets) 
{
  PRUint32 count = aCharsets.Count();

  for (PRUint32 i = 0; i < count; i++) {

    nsCString* str = aCharsets.CStringAt(i);
    if (str) {
      nsresult res = AddCharsetToItemArray(&aArray, *str, NULL, -1);
    
      if (NS_FAILED(res)) return res;
    }
  }

  return NS_OK;
}

// aPlace < -1 for Remove
// aPlace < 0 for Append
nsresult nsCharsetMenu::AddMenuItemToContainer(
                        nsIRDFContainer * aContainer,
                        nsMenuEntry * aItem,
                        nsIRDFResource * aType,
                        const char * aIDPrefix,
                        PRInt32 aPlace) 
{
  nsresult res = NS_OK;
  nsCOMPtr<nsIRDFResource> node;

  nsCAutoString id;
  if (aIDPrefix != NULL) id.Assign(aIDPrefix);
  id.Append(aItem->mCharset);

  // Make up a unique ID and create the RDF NODE
  res = mRDFService->GetResource(id, getter_AddRefs(node));
  if (NS_FAILED(res)) return res;

  const PRUnichar * title = aItem->mTitle.get();

  // set node's title
  nsCOMPtr<nsIRDFLiteral> titleLiteral;
  res = mRDFService->GetLiteral(title, getter_AddRefs(titleLiteral));
  if (NS_FAILED(res)) return res;

  if (aPlace < -1) {
    res = Unassert(node, kNC_Name, titleLiteral);
    if (NS_FAILED(res)) return res;
  } else {
    res = Assert(node, kNC_Name, titleLiteral, PR_TRUE);
    if (NS_FAILED(res)) return res;
  }

  if (aType != NULL) {
    if (aPlace < -1) {
      res = Unassert(node, kRDF_type, aType);
      if (NS_FAILED(res)) return res;
    } else {
      res = Assert(node, kRDF_type, aType, PR_TRUE);
      if (NS_FAILED(res)) return res;
    }
  }

  // Add the element to the container
  if (aPlace < -1) {
    res = aContainer->RemoveElement(node, PR_TRUE);
    if (NS_FAILED(res)) return res;
  } else if (aPlace < 0) {
    res = aContainer->AppendElement(node);
    if (NS_FAILED(res)) return res;
  } else {
    res = aContainer->InsertElementAt(node, aPlace, PR_TRUE);
    if (NS_FAILED(res)) return res;
  } 

  return res;
}

nsresult nsCharsetMenu::AddMenuItemArrayToContainer(
                        nsIRDFContainer * aContainer,
                        nsVoidArray * aArray,
                        nsIRDFResource * aType) 
{
  PRUint32 count = aArray->Count();
  nsresult res = NS_OK;

  for (PRUint32 i = 0; i < count; i++) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(i);
    if (item == NULL) return NS_ERROR_UNEXPECTED;

    res = AddMenuItemToContainer(aContainer, item, aType, NULL, -1);
    if (NS_FAILED(res)) return res;
  }

  return NS_OK;
}

nsresult nsCharsetMenu::AddCharsetToContainer(nsVoidArray *aArray, 
                                              nsIRDFContainer * aContainer, 
                                              const nsAFlatCString& aCharset, 
                                              const char * aIDPrefix,
                                              PRInt32 aPlace,
						PRInt32 aRDFPlace)
{
  nsresult res = NS_OK;
  nsMenuEntry * item = NULL; 
  
  res = AddCharsetToItemArray(aArray, aCharset, &item, aPlace);
  if (NS_FAILED(res)) goto done;

  res = AddMenuItemToContainer(aContainer, item, NULL, aIDPrefix, 
    aPlace + aRDFPlace);
  if (NS_FAILED(res)) goto done;

  // if we have made another reference to "item", do not delete it 
  if (aArray != NULL) item = NULL; 

done:
  if (item != NULL) delete item;

  return res;
}

nsresult nsCharsetMenu::AddFromPrefsToMenu(
                        nsVoidArray * aArray, 
                        nsIRDFContainer * aContainer, 
                        const char * aKey, 
                        nsCStringArray& aDecs, 
                        const char * aIDPrefix)
{
  nsresult res = NS_OK;

  nsCOMPtr<nsIPrefLocalizedString> pls;
  res = mPrefs->GetComplexValue(aKey, NS_GET_IID(nsIPrefLocalizedString), getter_AddRefs(pls));
  if (NS_FAILED(res)) return res;

  if (pls) {
    nsXPIDLString ucsval;
    pls->ToString(getter_Copies(ucsval));
    NS_ConvertUCS2toUTF8 utf8val(ucsval);
    if (ucsval)
      res = AddFromStringToMenu(utf8val.BeginWriting(), aArray,
                                aContainer, aDecs, aIDPrefix);
  }

  return res;
}

nsresult
nsCharsetMenu::AddFromNolocPrefsToMenu(nsVoidArray * aArray, 
                                       nsIRDFContainer * aContainer, 
                                       const char * aKey, 
                                       nsCStringArray& aDecs, 
                                       const char * aIDPrefix)
{
  nsresult res = NS_OK;

  char * value = NULL;
  res = mPrefs->GetCharPref(aKey, &value);
  if (NS_FAILED(res)) return res;

  if (value != NULL) {
    res = AddFromStringToMenu(value, aArray, aContainer, aDecs, aIDPrefix);
    nsMemory::Free(value);
  }

  return res;
}

nsresult nsCharsetMenu::AddFromStringToMenu(
                        char * aCharsetList, 
                        nsVoidArray * aArray, 
                        nsIRDFContainer * aContainer, 
                        nsCStringArray& aDecs, 
                        const char * aIDPrefix)
{
  nsresult res = NS_OK;
  char * p = aCharsetList;
  char * q = p;
  while (*p != 0) {
	  for (; (*q != ',') && (*q != ' ') && (*q != 0); q++) {;}
    char temp = *q;
    *q = 0;

    // if this charset is not on the accepted list of charsets, ignore it
    PRInt32 index;
    index = aDecs.IndexOfIgnoreCase(nsCAutoString(p));
    if (index >= 0) {

      // else, add it to the menu
      res = AddCharsetToContainer(aArray, aContainer, nsDependentCString(p),
                                  aIDPrefix, -1, 0);
      NS_ASSERTION(NS_SUCCEEDED(res), "cannot add charset to menu");
      if (NS_FAILED(res)) break;

      res = aDecs.RemoveCStringAt(index);
      NS_ASSERTION(NS_SUCCEEDED(res), "cannot remove atom from array");
    }

    *q = temp;
    for (; (*q == ',') || (*q == ' '); q++) {;}
    p=q;
  }

  return NS_OK;
}

nsresult nsCharsetMenu::AddSeparatorToContainer(nsIRDFContainer * aContainer)
{
  nsCAutoString str;
  str.AssignLiteral("----");

  // hack to generate unique id's for separators
  static PRInt32 u = 0;
  u++;
  str.AppendInt(u);

  nsMenuEntry item;
  item.mCharset = str;
  item.mTitle.AssignWithConversion(str.get());

  return AddMenuItemToContainer(aContainer, &item, kNC_BookmarkSeparator, 
    NULL, -1);
}

nsresult
nsCharsetMenu::AddCharsetToCache(const nsAFlatCString& aCharset,
                                 nsVoidArray * aArray,
                                 nsIRDFResource * aRDFResource, 
                                 PRInt32 aCacheStart, 
                                 PRInt32 aCacheSize,
                                 PRInt32 aRDFPlace)
{
  PRInt32 i;
  nsresult res = NS_OK;

  i = FindMenuItemInArray(aArray, aCharset, NULL);
  if (i >= 0) return res;

  nsCOMPtr<nsIRDFContainer> container;
  res = NewRDFContainer(mInner, aRDFResource, getter_AddRefs(container));
  if (NS_FAILED(res)) return res;

  // iff too many items, remove last one
  if (aArray->Count() - aCacheStart >= aCacheSize){
    res = RemoveLastMenuItem(container, aArray);
    if (NS_FAILED(res)) return res;
  }

  res = AddCharsetToContainer(aArray, container, aCharset, "charset.", 
                              aCacheStart, aRDFPlace);

  return res;
}

nsresult nsCharsetMenu::WriteCacheToPrefs(nsVoidArray * aArray, 
                                          PRInt32 aCacheStart, 
                                          const char * aKey)
{
  nsresult res = NS_OK;

  // create together the cache string
  nsCAutoString cache;
  nsCAutoString sep(NS_LITERAL_CSTRING(", "));
  PRInt32 count = aArray->Count();

  for (PRInt32 i = aCacheStart; i < count; i++) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(i);
    if (item != NULL) {    
      cache.Append(item->mCharset);
      if (i < count - 1) {
        cache.Append(sep);
      }
    }
  }

  // write the pref
  res = mPrefs->SetCharPref(aKey, cache.get());

  return res;
}

nsresult nsCharsetMenu::UpdateCachePrefs(const char * aCacheKey,
                                         const char * aCacheSizeKey,
                                         const char * aStaticKey,
                                         const PRUnichar * aCharset)
{
  nsresult rv = NS_OK;
  nsXPIDLCString cachePrefValue;
  nsXPIDLCString staticPrefValue;
  NS_LossyConvertUTF16toASCII currentCharset(aCharset);
  PRInt32 cacheSize = 0;

  mPrefs->GetCharPref(aCacheKey, getter_Copies(cachePrefValue));
  mPrefs->GetCharPref(aStaticKey, getter_Copies(staticPrefValue));
  rv = mPrefs->GetIntPref(aCacheSizeKey, &cacheSize);

  if (NS_FAILED(rv) || cacheSize <= 0)
    return NS_ERROR_UNEXPECTED;

  if ((cachePrefValue.Find(currentCharset) == kNotFound) && 
      (staticPrefValue.Find(currentCharset) == kNotFound)) {

    if (!cachePrefValue.IsEmpty())
      cachePrefValue.Insert(", ", 0);

    cachePrefValue.Insert(currentCharset, 0);
    if (cacheSize < (PRInt32) cachePrefValue.CountChar(',') + 1)
      cachePrefValue.Truncate(cachePrefValue.RFindChar(','));

    rv = mPrefs->SetCharPref(aCacheKey, cachePrefValue);
  }

  return rv;
}

nsresult nsCharsetMenu::ClearMenu(nsIRDFContainer * aContainer,  
                                  nsVoidArray * aArray)
{
  nsresult res = NS_OK;

  // clean the RDF data source
  PRInt32 count = aArray->Count();
  for (PRInt32 i = 0; i < count; i++) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(i);
    if (item != NULL) {    
      res = AddMenuItemToContainer(aContainer, item, NULL, "charset.", -2);
      if (NS_FAILED(res)) return res;
    }
  }

  // clean the internal data structures
  FreeMenuItemArray(aArray);

  return res;
}

nsresult nsCharsetMenu::RemoveLastMenuItem(nsIRDFContainer * aContainer,
                                           nsVoidArray * aArray)
{
  nsresult res = NS_OK;

  PRInt32 last = aArray->Count() - 1;
  if (last >= 0) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(last);
    if (item != NULL) {    
      res = AddMenuItemToContainer(aContainer, item, NULL, "charset.", -2);
      if (NS_FAILED(res)) return res;

      res = aArray->RemoveElementAt(last);
      if (NS_FAILED(res)) return res;
    }
  }

  return res;
}

nsresult nsCharsetMenu::RemoveFlaggedCharsets(nsCStringArray& aList, 
                                              nsString * aProp)
{
  nsresult res = NS_OK;
  PRUint32 count;

  count = aList.Count();
  if (NS_FAILED(res)) return res;

  nsCString* charset;
  nsAutoString str;
  for (PRUint32 i = 0; i < count; i++) {

    charset = aList.CStringAt(i);
    if (!charset) continue;

    res = mCCManager->GetCharsetData(charset->get(), aProp->get(), str);
    if (NS_FAILED(res)) continue;

    aList.RemoveCStringAt(i);

    i--; 
    count--;
  }

  return NS_OK;
}

nsresult nsCharsetMenu::NewRDFContainer(nsIRDFDataSource * aDataSource, 
                                        nsIRDFResource * aResource, 
                                        nsIRDFContainer ** aResult)
{
  nsresult res = CallCreateInstance(kRDFContainerCID, aResult);
  if (NS_FAILED(res)) return res;

  res = (*aResult)->Init(aDataSource, aResource);
  if (NS_FAILED(res)) NS_RELEASE(*aResult);

  return res;
}

void nsCharsetMenu::FreeMenuItemArray(nsVoidArray * aArray)
{
  PRUint32 count = aArray->Count();
  for (PRUint32 i = 0; i < count; i++) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(i);
    if (item != NULL) {
      delete item;
    }
  }
  aArray->Clear();
}

PRInt32 nsCharsetMenu::FindMenuItemInArray(const nsVoidArray* aArray, 
                                           const nsAFlatCString& aCharset, 
                                           nsMenuEntry ** aResult)
{
  PRUint32 count = aArray->Count();

  for (PRUint32 i=0; i < count; i++) {
    nsMenuEntry * item = (nsMenuEntry *) aArray->ElementAt(i);
    if (item->mCharset == aCharset) {
      if (aResult != NULL) *aResult = item;
      return i;
    }
  }

  if (aResult != NULL) *aResult = NULL;
  return -1;
}

nsresult nsCharsetMenu::ReorderMenuItemArray(nsVoidArray * aArray)
{
  nsresult res = NS_OK;
  nsCOMPtr<nsICollation> collation;
  PRUint32 count = aArray->Count();
  PRUint32 i;

  // we need to use a temporary array
  charsetMenuSortRecord *array = new charsetMenuSortRecord [count];
  NS_ENSURE_TRUE(array, NS_ERROR_OUT_OF_MEMORY);
  for (i = 0; i < count; i++)
    array[i].key = nsnull;

  res = GetCollation(getter_AddRefs(collation));
  if (NS_FAILED(res))
    goto done;

  for (i = 0; i < count && NS_SUCCEEDED(res); i++) {
    array[i].item = (nsMenuEntry *)aArray->ElementAt(i);

    res = collation->AllocateRawSortKey(nsICollation::kCollationCaseInSensitive, 
                                       (array[i].item)->mTitle, &array[i].key, &array[i].len);
  }

  // reorder the array
  if (NS_SUCCEEDED(res)) {
    NS_QuickSort(array, count, sizeof(*array), CompareMenuItems, collation);

    // move the elements from the temporary array into the the real one
    aArray->Clear();
    for (i = 0; i < count; i++) {
      aArray->AppendElement(array[i].item);
    }
  }

done:
  for (i = 0; i < count; i++) {
    PR_FREEIF(array[i].key);
  }
  delete [] array;
  return res;
}

nsresult nsCharsetMenu::GetCollation(nsICollation ** aCollation)
{
  nsresult res = NS_OK;
  nsCOMPtr<nsILocale> locale = nsnull;
  nsICollationFactory * collationFactory = nsnull;
  
  nsCOMPtr<nsILocaleService> localeServ = 
           do_GetService(kLocaleServiceCID, &res);
  if (NS_FAILED(res)) return res;

  res = localeServ->GetApplicationLocale(getter_AddRefs(locale));
  if (NS_FAILED(res)) return res;

  res = CallCreateInstance(kCollationFactoryCID, &collationFactory);
  if (NS_FAILED(res)) return res;

  res = collationFactory->CreateCollation(locale, aCollation);
  NS_RELEASE(collationFactory);
  return res;
}

//----------------------------------------------------------------------------
// Interface nsICurrentCharsetListener [implementation]

NS_IMETHODIMP nsCharsetMenu::SetCurrentCharset(const PRUnichar * aCharset)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu:SetCurrentCharset");
  nsresult res = NS_OK;

  if (mBrowserMenuInitialized) {
    res = AddCharsetToCache(NS_LossyConvertUCS2toASCII(aCharset),
                            &mBrowserMenu, kNC_BrowserCharsetMenuRoot, 
                            mBrowserCacheStart, mBrowserCacheSize,
                            mBrowserMenuRDFPosition);
    if (NS_FAILED(res)) {
        NS_TIMELINE_LEAVE("nsCharsetMenu:SetCurrentCharset");
        return res;
    }

    res = WriteCacheToPrefs(&mBrowserMenu, mBrowserCacheStart, 
      kBrowserCachePrefKey);
  } else {
    res = UpdateCachePrefs(kBrowserCachePrefKey, kBrowserCacheSizePrefKey, 
                           kBrowserStaticPrefKey, aCharset);
  }
  NS_TIMELINE_STOP_TIMER("nsCharsetMenu:SetCurrentCharset");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu:SetCurrentCharset");
  return res;
}

NS_IMETHODIMP nsCharsetMenu::SetCurrentMailCharset(const PRUnichar * aCharset)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu:SetCurrentMailCharset");
  nsresult res = NS_OK;

  if (mMailviewMenuInitialized) {
    res = AddCharsetToCache(NS_LossyConvertUCS2toASCII(aCharset),
                            &mMailviewMenu, kNC_MailviewCharsetMenuRoot, 
                            mMailviewCacheStart, mMailviewCacheSize,
                            mMailviewMenuRDFPosition);
    if (NS_FAILED(res)) return res;

    res = WriteCacheToPrefs(&mMailviewMenu, mMailviewCacheStart, 
                            kMailviewCachePrefKey);
  } else {
    res = UpdateCachePrefs(kMailviewCachePrefKey, kMailviewCacheSizePrefKey, 
                           kMailviewStaticPrefKey, aCharset);
  }
  NS_TIMELINE_STOP_TIMER("nsCharsetMenu:SetCurrentMailCharset");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu:SetCurrentMailCharset");
  return res;
}

NS_IMETHODIMP nsCharsetMenu::SetCurrentComposerCharset(const PRUnichar * aCharset)
{
  NS_TIMELINE_START_TIMER("nsCharsetMenu:SetCurrentComposerCharset");
  nsresult res = NS_OK;

  if (mComposerMenuInitialized) {

    res = AddCharsetToCache(NS_LossyConvertUCS2toASCII(aCharset),
                            &mComposerMenu, kNC_ComposerCharsetMenuRoot, 
                            mComposerCacheStart, mComposerCacheSize,
                            mComposerMenuRDFPosition);
    if (NS_FAILED(res)) return res;

    res = WriteCacheToPrefs(&mComposerMenu, mComposerCacheStart, 
      kComposerCachePrefKey);
  } else {
    res = UpdateCachePrefs(kComposerCachePrefKey, kComposerCacheSizePrefKey, 
                           kComposerStaticPrefKey, aCharset);
  }
  NS_TIMELINE_STOP_TIMER("nsCharsetMenu:SetCurrentComposerCharset");
  NS_TIMELINE_MARK_TIMER("nsCharsetMenu:SetCurrentComposerCharset");
  return res;
}

//----------------------------------------------------------------------------
// Interface nsIRDFDataSource [implementation]

NS_IMETHODIMP nsCharsetMenu::GetURI(char ** uri)
{
  if (!uri) return NS_ERROR_NULL_POINTER;

  *uri = nsCRT::strdup("rdf:charset-menu");
  if (!(*uri)) return NS_ERROR_OUT_OF_MEMORY;

  return NS_OK;
}

NS_IMETHODIMP nsCharsetMenu::GetSource(nsIRDFResource* property,
                                       nsIRDFNode* target,
                                       PRBool tv,
                                       nsIRDFResource** source)
{
  return mInner->GetSource(property, target, tv, source);
}

NS_IMETHODIMP nsCharsetMenu::GetSources(nsIRDFResource* property,
                                        nsIRDFNode* target,
                                        PRBool tv,
                                        nsISimpleEnumerator** sources)
{
  return mInner->GetSources(property, target, tv, sources);
}

NS_IMETHODIMP nsCharsetMenu::GetTarget(nsIRDFResource* source,
                                       nsIRDFResource* property,
                                       PRBool tv,
                                       nsIRDFNode** target)
{
  return mInner->GetTarget(source, property, tv, target);
}

NS_IMETHODIMP nsCharsetMenu::GetTargets(nsIRDFResource* source,
                                        nsIRDFResource* property,
                                        PRBool tv,
                                        nsISimpleEnumerator** targets)
{
  return mInner->GetTargets(source, property, tv, targets);
}

NS_IMETHODIMP nsCharsetMenu::Assert(nsIRDFResource* aSource,
                                    nsIRDFResource* aProperty,
                                    nsIRDFNode* aTarget,
                                    PRBool aTruthValue)
{
  // TODO: filter out asserts we don't care about
  return mInner->Assert(aSource, aProperty, aTarget, aTruthValue);
}

NS_IMETHODIMP nsCharsetMenu::Unassert(nsIRDFResource* aSource,
                                      nsIRDFResource* aProperty,
                                      nsIRDFNode* aTarget)
{
  // TODO: filter out unasserts we don't care about
  return mInner->Unassert(aSource, aProperty, aTarget);
}


NS_IMETHODIMP nsCharsetMenu::Change(nsIRDFResource* aSource,
                                    nsIRDFResource* aProperty,
                                    nsIRDFNode* aOldTarget,
                                    nsIRDFNode* aNewTarget)
{
  // TODO: filter out changes we don't care about
  return mInner->Change(aSource, aProperty, aOldTarget, aNewTarget);
}

NS_IMETHODIMP nsCharsetMenu::Move(nsIRDFResource* aOldSource,
                                  nsIRDFResource* aNewSource,
                                  nsIRDFResource* aProperty,
                                  nsIRDFNode* aTarget)
{
  // TODO: filter out changes we don't care about
  return mInner->Move(aOldSource, aNewSource, aProperty, aTarget);
}


NS_IMETHODIMP nsCharsetMenu::HasAssertion(nsIRDFResource* source, 
                                          nsIRDFResource* property, 
                                          nsIRDFNode* target, PRBool tv, 
                                          PRBool* hasAssertion)
{
  return mInner->HasAssertion(source, property, target, tv, hasAssertion);
}

NS_IMETHODIMP nsCharsetMenu::AddObserver(nsIRDFObserver* n)
{
  return mInner->AddObserver(n);
}

NS_IMETHODIMP nsCharsetMenu::RemoveObserver(nsIRDFObserver* n)
{
  return mInner->RemoveObserver(n);
}

NS_IMETHODIMP 
nsCharsetMenu::HasArcIn(nsIRDFNode *aNode, nsIRDFResource *aArc, PRBool *result)
{
  return mInner->HasArcIn(aNode, aArc, result);
}

NS_IMETHODIMP 
nsCharsetMenu::HasArcOut(nsIRDFResource *source, nsIRDFResource *aArc, PRBool *result)
{
  return mInner->HasArcOut(source, aArc, result);
}

NS_IMETHODIMP nsCharsetMenu::ArcLabelsIn(nsIRDFNode* node, 
                                         nsISimpleEnumerator** labels)
{
  return mInner->ArcLabelsIn(node, labels);
}

NS_IMETHODIMP nsCharsetMenu::ArcLabelsOut(nsIRDFResource* source, 
                                          nsISimpleEnumerator** labels)
{
  return mInner->ArcLabelsOut(source, labels);
}

NS_IMETHODIMP nsCharsetMenu::GetAllResources(nsISimpleEnumerator** aCursor)
{
  return mInner->GetAllResources(aCursor);
}

NS_IMETHODIMP nsCharsetMenu::GetAllCmds(
                             nsIRDFResource* source,
                             nsISimpleEnumerator/*<nsIRDFResource>*/** commands)
{
  NS_NOTYETIMPLEMENTED("write me!");
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP nsCharsetMenu::IsCommandEnabled(
                             nsISupportsArray/*<nsIRDFResource>*/* aSources,
                             nsIRDFResource*   aCommand,
                             nsISupportsArray/*<nsIRDFResource>*/* aArguments,
                             PRBool* aResult)
{
  NS_NOTYETIMPLEMENTED("write me!");
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP nsCharsetMenu::DoCommand(nsISupportsArray* aSources,
                                       nsIRDFResource*   aCommand,
                                       nsISupportsArray* aArguments)
{
  NS_NOTYETIMPLEMENTED("write me!");
  return NS_ERROR_NOT_IMPLEMENTED;
}

NS_IMETHODIMP nsCharsetMenu::BeginUpdateBatch()
{
  return mInner->BeginUpdateBatch();
}

NS_IMETHODIMP nsCharsetMenu::EndUpdateBatch()
{
  return mInner->EndUpdateBatch();
}