William Bowling is sharing code with you

Bitbucket is a code hosting site. Unlimited public and private repositories. Free for small teams.

Don't show this again

wbowling / adium (fork of adium / adium)

Fork of Adium for patches/improvements

Clone this repository (size: 338.7 MB): HTTPS / SSH
hg clone https://bitbucket.org/wbowling/adium
hg clone ssh://hg@bitbucket.org/wbowling/adium

adium / Source / AIInterfaceController.m

   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
/* 
 * Adium is the legal property of its developers, whose names are listed in the copyright file included
 * with this source distribution.
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation; either version 2 of the License,
 * or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// $Id$

#import "AIInterfaceController.h"

#import <Adium/AIAccountControllerProtocol.h>
#import <Adium/AIContactControllerProtocol.h>
#import <Adium/AIChatControllerProtocol.h>
#import <Adium/AIContentControllerProtocol.h>
#import <Adium/AIMenuControllerProtocol.h>
#import <Adium/AIAuthorizationRequestsWindowController.h>
#import <AIUtilities/AIAttributedStringAdditions.h>
#import <AIUtilities/AIColorAdditions.h>
#import <AIUtilities/AIFontAdditions.h>
#import <AIUtilities/AIImageDrawingAdditions.h>
#import <AIUtilities/AIMenuAdditions.h>
#import <AIUtilities/AIStringAdditions.h>
#import <AIUtilities/AITooltipUtilities.h>
#import <AIUtilities/AIWindowAdditions.h>
#import <AIUtilities/AITextAttributes.h>
#import <AIUtilities/AIWindowControllerAdditions.h>
#import <Adium/AIChat.h>
#import <Adium/AIListContact.h>
#import <Adium/AIListGroup.h>
#import <Adium/AIListObject.h>
#import <Adium/AIMetaContact.h>
#import <Adium/AIService.h>
#import <Adium/AIServiceIcons.h>
#import <Adium/AISortController.h>
#import "AIMessageTabViewItem.h"
#import "KNShelfSplitview.h"
#import <Adium/AIContactList.h>

#import "AIMessageViewController.h"

#define ERROR_MESSAGE_WINDOW_TITLE              AILocalizedString(@"Adium : Error","Error message window title")
#define LABEL_ENTRY_SPACING                             4.0
#define DISPLAY_IMAGE_ON_RIGHT                  NO

#define PREF_GROUP_FORMATTING                   @"Formatting"
#define KEY_FORMATTING_FONT                             @"Default Font"

#define MESSAGES_WINDOW_MENU_TITLE              AILocalizedString(@"Chats","Title for the messages window menu item")

//#define       LOG_RESPONDER_CHAIN

@interface AIInterfaceController ()
- (void)_resetOpenChatsCache;
- (void)_addItemToMainMenuAndDock:(NSMenuItem *)item;
- (NSAttributedString *)_tooltipTitleForObject:(AIListObject *)object;
- (NSAttributedString *)_tooltipBodyForObject:(AIListObject *)object;
- (void)_pasteWithPreferredSelector:(SEL)preferredSelector sender:(id)sender;
- (void)updateCloseMenuKeys;

- (void)saveContainers;
- (void)restoreSavedContainers;

//Window Menu
- (void)updateActiveWindowMenuItem;
- (void)buildWindowMenu;

- (AIChat *)mostRecentActiveChat;
@end

/*!
 * @class AIInterfaceController
 * @brief Interface controller
 *
 * Chat window related requests, such as opening and closing chats, are routed through the interface controller
 * to the appropriate component. The interface controller keeps track of the most recently active chat, handles chat
 * cycling (switching between chats), chat sorting, and so on.  The interface controller also handles switching to
 * an appropriate window or chat when the dock icon is clicked for a 'reopen' event.
 *
 * Contact list window requests, such as toggling window visibilty are routed to the contact list controller component.
 *
 * Error messages are routed through the interface controller.
 *
 * Tooltips, such as seen on hover in the contact list are generated and displayed here.  Tooltip display components and
 * plugins register with the interface controller to be queried for contact information when a tooltip is displayed.
 *
 * When displays in Adium flash, such as in the dock or the contact list for unviewed content, the interface controller
 * manages keeping the flashing synchronized.
 *
 * Finally, the interface controller manages many menu items, providing better menu item validation and target routing
 * than the responder chain alone would do.
 */
@implementation AIInterfaceController

- (id)init
{
        if ((self = [super init])) {
                contactListViewArray = [[NSMutableArray alloc] init];
                messageViewArray = [[NSMutableArray alloc] init];
                contactListTooltipEntryArray = [[NSMutableArray alloc] init];
                contactListTooltipSecondaryEntryArray = [[NSMutableArray alloc] init];
                closeMenuConfiguredForChat = NO;
                _cachedOpenChats = nil;
                mostRecentActiveChat = nil;
                activeChat = nil;
                
                tooltipListObject = nil;
                tooltipTitle = nil;
                tooltipBody = nil;
                tooltipImage = nil;
                flashObserverArray = nil;
                flashTimer = nil;
                flashState = 0;
                
                windowMenuArray = nil;
                
#ifdef LOG_RESPONDER_CHAIN
                [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(reportResponderChain:) userInfo:nil repeats:YES];
#endif
        }
        
        return self;
}

#ifdef LOG_RESPONDER_CHAIN
//Can be called by a timer to periodically log the responder chain
//[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(reportResponderChain:) userInfo:nil repeats:YES];
- (void)reportResponderChain:(NSTimer *)inTimer
{
        NSMutableString *responderChain = [NSMutableString string];
        
        NSWindow        *keyWindow = [[NSApplication sharedApplication] keyWindow];
#warning 64BIT: Check formatting arguments
        [responderChain appendFormat:@"%@ (%i): ",keyWindow,[keyWindow respondsToSelector:@selector(print:)]];
        
        NSResponder     *responder = [keyWindow firstResponder];
        
        //First, walk down the responder chain looking for a responder which can handle the preferred selector
        while (responder) {
#warning 64BIT: Check formatting arguments
                [responderChain appendFormat:@"%@ (%i)",responder,[responder respondsToSelector:@selector(print:)]];
                responder = [responder nextResponder];
                if (responder) [responderChain appendString:@" -> "];
        }

        NSLog(responderChain);
}
#endif

- (void)controllerDidLoad
{
    //Load the interface
    [interfacePlugin openInterface];

        //Open the contact list window
    [self showContactList:nil];
        
        //Userlist show/hide item
        menuItem_toggleUserlist = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Toggle User List", nil)
                                                                                                                                                                                         target:self
                                                                                                                                                                                         action:@selector(toggleUserlist:)
                                                                                                                                                                          keyEquivalent:@"/"];
        [menuItem_toggleUserlist setKeyEquivalentModifierMask:(NSCommandKeyMask | NSAlternateKeyMask)];
        
        [adium.menuController addMenuItem:menuItem_toggleUserlist toLocation:LOC_Display_General];
        
        menuItem_toggleUserlistSide = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Toggle User List Side", nil)
                                                                                                                                                                   target:self
                                                                                                                                                                   action:@selector(toggleUserlistSide:)
                                                                                                                                                        keyEquivalent:@""];
        
        [adium.menuController addMenuItem:menuItem_toggleUserlistSide toLocation:LOC_Display_General];

        NSMenuItem *menuItem = [[[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Toggle User List", nil)
                                                                                                                                                                target:self
                                                                                                                                                                action:@selector(toggleUserlist:)
                                                                                                                                                 keyEquivalent:@""] autorelease];
        
        [adium.menuController addContextualMenuItem:menuItem toLocation:Context_GroupChat_Action];
        
        // Clear display
        menuItem_clearDisplay = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Clear Display", nil)
                                                                                                                                                                 target:self
                                                                                                                                                                 action:@selector(clearDisplay:)
                                                                                                                                                  keyEquivalent:@""];
        [adium.menuController addMenuItem:menuItem_clearDisplay toLocation:LOC_Display_MessageControl];
                                                                                                                                                          
        //Contact list menu item
        menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Contact List","Name of the window which lists contacts")
                                                                                                                                                                target:self
                                                                                                                                                                action:@selector(toggleContactList:)
                                                                                                                                                 keyEquivalent:@"/"];
        [adium.menuController addMenuItem:menuItem toLocation:LOC_Window_Fixed];
        [adium.menuController addMenuItem:[[menuItem copy] autorelease] toLocation:LOC_Dock_Status];
        [menuItem release];
        
        menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Close Chat","Title for the close chat menu item")
                                                                                                                                        target:self
                                                                                                                                        action:@selector(closeContextualChat:)
                                                                                                                         keyEquivalent:@""];
        [adium.menuController addContextualMenuItem:menuItem toLocation:Context_Tab_Action];
        [menuItem release];
        
        // Authorization requests menu item
        menuItem = [[NSMenuItem alloc] initWithTitle:AUTHORIZATION_REQUESTS
                                                                                                           target:self
                                                                                                           action:@selector(openAuthorizationWindow:)
                                                                                                keyEquivalent:@""];
        
        [adium.menuController addMenuItem:menuItem toLocation:LOC_Window_Auxiliary];
        [menuItem release];

    //Observe content so we can open chats as necessary
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveContent:) 
                                                                           name:CONTENT_MESSAGE_RECEIVED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveContent:) 
                                                                           name:CONTENT_MESSAGE_RECEIVED_GROUP object:nil];
        
        //Observe Adium finishing loading so we can do things which may require other components or plugins
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                   selector:@selector(adiumDidFinishLoading:)
                                                                           name:AIApplicationDidFinishLoadingNotification
                                                                         object:nil];
        
        //Observe quits so we can save containers.
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                   selector:@selector(saveContainersOnQuit:)
                                                                           name:AIAppWillTerminateNotification
                                                                         object:nil];
}

- (void)controllerWillClose
{
    [contactListPlugin closeContactList];
    [interfacePlugin closeInterface];
}

// Dealloc
- (void)dealloc
{
    [contactListViewArray release]; contactListViewArray = nil;
    [messageViewArray release]; messageViewArray = nil;
    [interfaceArray release]; interfaceArray = nil;
        
    [tooltipListObject release]; tooltipListObject = nil;
        [tooltipTitle release]; tooltipTitle = nil;
        [tooltipBody release]; tooltipBody = nil;
        [tooltipImage release]; tooltipImage = nil;
        
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [adium.preferenceController unregisterPreferenceObserver:self];
        
    [super dealloc];
}

- (void)adiumDidFinishLoading:(NSNotification *)inNotification
{
        //Observe preference changes. This will also restore saved containers if appropriate.
        [adium.preferenceController registerPreferenceObserver:self forGroup:PREF_GROUP_INTERFACE];
        
        [[NSNotificationCenter defaultCenter] removeObserver:self
                                                                                  name:AIApplicationDidFinishLoadingNotification
                                                                                object:nil];
}

//Registers code to handle the interface
- (void)registerInterfaceController:(id <AIInterfaceComponent>)inController
{
        if (!interfacePlugin) interfacePlugin = [inController retain];
}

//Register code to handle the contact list
- (void)registerContactListController:(id <AIContactListComponent>)inController
{
        if (!contactListPlugin) contactListPlugin = [inController retain];
}

//Preferences changed
- (void)preferencesChangedForGroup:(NSString *)group key:(NSString *)key
                                                        object:(AIListObject *)object preferenceDict:(NSDictionary *)prefDict firstTime:(BOOL)firstTime
{
        if (!object) {
                //Update prefs
                tabbedChatting = [[prefDict objectForKey:KEY_TABBED_CHATTING] boolValue];
                groupChatsByContactGroup = [[prefDict objectForKey:KEY_GROUP_CHATS_BY_GROUP] boolValue];
                saveContainers = [[prefDict objectForKey:KEY_SAVE_CONTAINERS] boolValue];
        
                if (firstTime) {
                        if (saveContainers) {
                                //Restore saved containers
                                [self restoreSavedContainers];  
                        } else if ([prefDict objectForKey:KEY_CONTAINERS]) {
                                /* We've loaded without wanting to save containers; clear any saved
                                 * from a previous session.
                                 */
                                [adium.preferenceController setPreference:nil
                                                                                                         forKey:KEY_CONTAINERS
                                                                                                          group:PREF_GROUP_INTERFACE];
                        }
                }
        }
}

//Handle a reopen/dock icon click
- (BOOL)handleReopenWithVisibleWindows:(BOOL)visibleWindows
{
        if (![self contactListIsVisibleAndMain] && [[interfacePlugin openContainerIDs] count] == 0) {
                //The contact list is not visible, and there are no chat windows. Make the contact list visible.
                [self showContactList:nil];

        } else {
                AIChat  *mostRecentUnviewedChat;

                //If windows are open, try switching to a chat with unviewed content
                if ((mostRecentUnviewedChat = [adium.chatController mostRecentUnviewedChat])) {
                        if ([mostRecentActiveChat unviewedContentCount]) {
                                //If the most recently active chat has unviewed content, ensure it is in the front
                                [self setActiveChat:mostRecentActiveChat];
                        } else {
                                //Otherwise, switch to the chat which most recently received content
                                [self setActiveChat:mostRecentUnviewedChat];
                        }

                } else {
                        NSWindow *targetWindow = nil;
                        BOOL     unMinimizedWindows = 0;
                        
                        //If there was no unviewed content, ensure that atleast one of Adium's windows is unminimized
                        for (NSWindow *window in [NSApp windows]) {
                                //Check stylemask to rule out the system menu's window (Which reports itself as visible like a real window)
                                if (([window styleMask] & (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask))) {
                                        if (!targetWindow) targetWindow = window;
                                        if (![window isMiniaturized]) unMinimizedWindows++;
                                }
                        }
                        
                        //If there are no unminimized windows, unminimize the last one
                        if (unMinimizedWindows == 0 && targetWindow) {
                                [targetWindow deminiaturize:nil];
                        }
                }
        }

        return YES; 
}

//Contact List ---------------------------------------------------------------------------------------------------------
#pragma mark Contact list
/*!
 * @brief Toggles contact list between visible and hiden
 */
- (IBAction)toggleContactList:(id)sender
{
    if ([self contactListIsVisibleAndMain]) {
                [self closeContactList:nil];
    } else {
                [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
                [self showContactList:nil];
    } 
}

/*!
 * @brief Brings contact list to the front
 */
- (IBAction)showContactList:(id)sender
{
        [contactListPlugin showContactListAndBringToFront:YES];
}

/*!
 * @brief Show the contact list window and bring Adium to the front
 */
- (IBAction)showContactListAndBringToFront:(id)sender
{
        [contactListPlugin showContactListAndBringToFront:YES];
        [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
}

/*!
 * @brief Close the contact list window
 */
- (IBAction)closeContactList:(id)sender
{
        [contactListPlugin closeContactList];
}

/*!
 * @returns YES if contact list is visible and selected, otherwise NO
 */
- (BOOL)contactListIsVisibleAndMain
{
        return [contactListPlugin contactListIsVisibleAndMain];
}

/*!
* @returns YES if contact list is visible, otherwise NO
 */
- (BOOL)contactListIsVisible
{
        return [contactListPlugin contactListIsVisible];
}

//Detachable Contact List ----------------------------------------------------------------------------------------------
#pragma mark Detachable Contact List

/*!
 * @returns Created contact list controller for detached contact list
 */
- (AIListWindowController *)detachContactList:(AIContactList *)aContactList
{
        return [contactListPlugin detachContactList:aContactList];
}


#pragma mark Container Saving
/*!
 * @brief Restores containers saved from a previous session
 */
- (void)restoreSavedContainers
{
        NSData                          *savedData = [adium.preferenceController preferenceForKey:KEY_CONTAINERS
                                                                                                                                        group:PREF_GROUP_INTERFACE];
        
        // If there's no data, we can't restore anything.
        if (!savedData)
                return;

        for (NSDictionary *dict in [NSKeyedUnarchiver unarchiveObjectWithData:savedData]) {
                AIMessageWindowController *windowController = [self openContainerWithID:[dict objectForKey:@"ID"]
                                                                                                                                 name:[dict objectForKey:@"Name"]];
                AIChat *containerActiveChat = nil;
                
                // Position the container where it was last saved (using -savedFrameFromString: to prevent going offscreen)
                [[windowController window] setFrame:[windowController savedFrameFromString:[dict objectForKey:@"Frame"]] display:YES];
                
                for (NSDictionary *chatDict in [dict objectForKey:@"Content"]) {
                        AIChat                  *chat = nil;
                        AIService               *service = [adium.accountController firstServiceWithServiceID:[chatDict objectForKey:@"serviceID"]];
                        AIAccount               *account = [adium.accountController accountWithInternalObjectID:[chatDict objectForKey:@"AccountID"]];
                                        
                        if ([[chatDict objectForKey:@"IsGroupChat"] boolValue]) {
                                chat = [adium.chatController chatWithName:[chatDict objectForKey:@"Name"]
                                                                                                 identifier:nil
                                                                                                  onAccount:account
                                                                                   chatCreationInfo:[chatDict objectForKey:@"ChatCreationInfo"]];
                        } else {
                                AIListContact           *contact = [adium.contactController contactWithService:service
                                                                                                                                                                        account:account
                                                                                                                                                                                UID:[chatDict objectForKey:@"UID"]];
                                
                                chat = [adium.chatController chatWithContact:contact];
                        }
                        
                        // Tag the chat as restored.
                        [chat setValue:[NSNumber numberWithBool:YES]
                           forProperty:@"Restored Chat"
                                        notify:NotifyNow];
                        
                        if ([[chatDict objectForKey:@"ActiveChat"] boolValue]) {
                                containerActiveChat = chat;
                        }
                                        
                        // Open the chat into the container we've created above.
                        [self openChat:chat inContainerWithID:[dict objectForKey:@"ID"] atIndex:-1];
                }
                
                if (containerActiveChat)
                        [self setActiveChat:containerActiveChat];
        }
}

/*!
 * @brief Saves open container information with their content when Adium quits
 */
- (void)saveContainersOnQuit:(NSNotification *)notification
{
        [self saveContainers];
}

/*!
 * @brief Save opened containers and windows
 *
 * @param withContent Save the current buffer of the window to restore at a later point
 */
- (void)saveContainers
{
        if (!saveContainers) {
                // Don't save anything if we're not set to.
                return;
        }

        // Save active containers.
        NSMutableArray          *savedContainers = [NSMutableArray array];
        
        for (NSDictionary *dict in [interfacePlugin openContainersAndChats]) {
                NSMutableArray          *containerContents = [NSMutableArray array];
                
                for (AIChat *chat in [dict objectForKey:@"Content"]) {
                        NSMutableDictionary             *newContainerDict = [NSMutableDictionary dictionary];

                        [newContainerDict setObject:chat.account.internalObjectID forKey:@"AccountID"];
                        
                        // Save chat-specific information.
                        if (chat.isGroupChat) {
                                // -chatCreationDictionary may be nil, so put it last.
                                [newContainerDict addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                                                        [NSNumber numberWithBool:YES], @"IsGroupChat",
                                                                                                                        [NSNumber numberWithBool:([dict objectForKey:@"ActiveChat"] == chat)], @"ActiveChat",
                                                                                                                        chat.name, @"Name",
                                                                                                                        [chat chatCreationDictionary], @"ChatCreationInfo",nil]];
                        } else {
                                [newContainerDict addEntriesFromDictionary:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                                                                        [NSNumber numberWithBool:([dict objectForKey:@"ActiveChat"] == chat)], @"ActiveChat",
                                                                                                                        chat.listObject.UID, @"UID",
                                                                                                                        chat.account.service.serviceID, @"serviceID",
                                                                                                                        chat.account.internalObjectID, @"AccountID",nil]];
                        }
                                        
                        [containerContents addObject:newContainerDict];
                }
                
                // Replace the "Content" key in -openContainersAndChats with our version of the content.
                // Remove the ActiveChat reference
                // We use the same keys otherwise that -openContainersAndChats provides (Name, ID, Frame)
                NSMutableDictionary *saveDict = [[dict mutableCopy] autorelease];

                [saveDict removeObjectForKey:@"ActiveChat"];
                
                [saveDict setObject:containerContents
                                         forKey:@"Content"];
                
                [savedContainers addObject:saveDict];
        }
        
        [adium.preferenceController setPreference:[NSKeyedArchiver archivedDataWithRootObject:savedContainers]
                                                                                 forKey:KEY_CONTAINERS
                                                                                  group:PREF_GROUP_INTERFACE];
}

//Messaging ------------------------------------------------------------------------------------------------------------
//Methods for instructing the interface to provide a representation of chats, and to determine which chat has user focus
#pragma mark Messaging

/*!
 * @brief Opens window for chat
 */
- (void)openChat:(AIChat *)inChat
{
        NSArray         *containerIDs = [interfacePlugin openContainerIDs];
        NSString        *containerID = nil;
        NSString        *containerName = nil;
        
        //Determine the correct container for this chat
        
        if (!tabbedChatting) {
                //We're not using tabs; each chat starts in its own container, based on the destination object or the chat name
                if ([inChat listObject]) {
                        containerID = inChat.listObject.internalObjectID;
                } else {
                        containerID = inChat.name;
                }
                
        } else if (groupChatsByContactGroup) {
                if (inChat.isGroupChat) {
                        containerID = AILocalizedString(@"Group Chats",nil);
                        
                } else {
                        //XXX multiple containers: this is "correct" but maybe not desirable, as it is non-deterministic
                        AIListGroup     *group = inChat.listObject.parentContact.groups.anyObject;
                        
                        //If the contact is in the contact list root, we don't have a group
                        if (group && ![group isKindOfClass:[AIContactList class]]) {
                                containerID = group.displayName;
                        }
                }
                
                containerName = containerID;
        }
        
        if (!containerID) {
                //Open new chats into the first container (if not available, create a new one)
                if ([containerIDs count] > 0) {
                        containerID = [containerIDs objectAtIndex:0];
                } else {
                        containerID = nil;
                }
        }

        //Determine the correct placement for this chat within the container
        [interfacePlugin openChat:inChat inContainerWithID:containerID withName:containerName atIndex:-1];
        if (![inChat isOpen]) {
                [inChat setIsOpen:YES];
                
                //Post the notification last, so observers receive a chat whose isOpen flag is yes.
                [[NSNotificationCenter defaultCenter] postNotificationName:Chat_DidOpen object:inChat userInfo:nil];
        }
}

- (id)openChat:(AIChat *)inChat inContainerWithID:(NSString *)containerID atIndex:(NSUInteger)index
{       
        NSArray         *openContainerIDs = [interfacePlugin openContainerIDs];

        if (!containerID) {
                //Open new chats into the first container (if not available, create a new one)
                if ([openContainerIDs count] > 0) {
                        containerID = [openContainerIDs objectAtIndex:0];
                } else {
                        containerID = AILocalizedString(@"Chats",nil);
                }
        }

        //Determine the correct placement for this chat within the container
        id tabViewItem = [interfacePlugin openChat:inChat inContainerWithID:containerID withName:nil atIndex:index];
        if (![inChat isOpen]) {
                [inChat setIsOpen:YES];
                
                //Post the notification last, so observers receive a chat whose isOpen flag is yes.
                [[NSNotificationCenter defaultCenter] postNotificationName:Chat_DidOpen object:inChat userInfo:nil];
        }
        return tabViewItem;
}

/**
 * @brief Opens a container with a specific ID
 *
 * Asks the interfacePlugin to openContainerWithID:
 */
- (AIMessageWindowController *)openContainerWithID:(NSString *)containerID name:(NSString *)containerName
{
        return [interfacePlugin openContainerWithID:containerID name:containerName];
}

/*!
 * @brief Close the interface for a chat
 *
 * Tell the interface plugin to close the chat.
 */
- (void)closeChat:(AIChat *)inChat
{
        if (inChat) {
                if ([adium.chatController closeChat:inChat]) {
                        [interfacePlugin closeChat:inChat];
                }
        }
}

/*!
 * @brief Consolidate chats into a single container
 */
- (void)consolidateChats
{
        //We work with copies of these arrays, since moving chats may change their contents
        NSArray                 *openContainerIDs = [[interfacePlugin openContainerIDs] copy];
        NSEnumerator    *containerEnumerator = [openContainerIDs objectEnumerator];
        NSString                *firstContainerID = [containerEnumerator nextObject];
        NSString                *containerID;
        
        //For all containers but the first, move the chats they contain to the first container
        while ((containerID = [containerEnumerator nextObject])) {
                NSArray                 *openChats = [[interfacePlugin openChatsInContainerWithID:containerID] copy];
                NSEnumerator    *chatEnumerator = [openChats objectEnumerator];
                AIChat                  *chat;

                //Move all the chats, providing a target index if chat sorting is enabled
                while ((chat = [chatEnumerator nextObject])) {
                        [interfacePlugin moveChat:chat
                                        toContainerWithID:firstContainerID
                                                                index:-1];
                }
                
                [openChats release];
        }
        
        [self chatOrderDidChange];
        
        [openContainerIDs release];
}

- (void)moveChatToNewContainer:(AIChat *)inChat
{
        [interfacePlugin moveChatToNewContainer:inChat];
}

/*!
 * @returns Active chat
 */
- (AIChat *)activeChat
{
        return activeChat;
}

/*!
 * @brief Set the active chat window
 */
- (void)setActiveChat:(AIChat *)inChat
{
        [interfacePlugin setActiveChat:inChat];
}

/*!
 * @returns Last chat to be active, nil if not chat is open
 */
- (AIChat *)mostRecentActiveChat
{
        return mostRecentActiveChat;
}

/*!
 * @brief Sets active chat window based on chat
 */
- (void)setMostRecentActiveChat:(AIChat *)inChat
{
        [self setActiveChat:inChat];
}

/*!
 * @returns Array of open chats (cached, so call as frequently as desired)
 */
- (NSArray *)openChats
{
        if (!_cachedOpenChats) {
                _cachedOpenChats = [[interfacePlugin openChats] retain];
        }
        
        return _cachedOpenChats;
}

- (NSArray *)openContainerIDs
{
        return [interfacePlugin openContainerIDs];
}

/*!
 * @param containerID ID for chat window
 *
 * @returns Array of all chats in chat window
 */
- (NSArray *)openChatsInContainerWithID:(NSString *)containerID
{
        return [interfacePlugin openChatsInContainerWithID:containerID];
}

/*!
 * @brief Resets the cache of open chats
 */
- (void)_resetOpenChatsCache
{
        [_cachedOpenChats release]; _cachedOpenChats = nil;
}



//Interface plugin callbacks -------------------------------------------------------------------------------------------
//These methods are called by the interface to let us know what's going on.  We're informed of chats opening, closing,
//changing order, etc.
#pragma mark Interface plugin callbacks
/*!
 * @brief A chat window did open: rebuild our window menu to show the new chat
 *
 * This should be called by the interface plugin (e.g. AIDualWindowInterfacePlugin) after a chat opens
 *
 * @param inChat Newly created chat 
 */
- (void)chatDidOpen:(AIChat *)inChat
{
        [self _resetOpenChatsCache];
        [self buildWindowMenu];
        [self saveContainers];
}

/*!
 * @brief A chat has become active: update our chat closing keys and flag this chat as selected in the window menu
 *
 * @param inChat Chat which has become active
 */
- (void)chatDidBecomeActive:(AIChat *)inChat
{
        AIChat  *previouslyActiveChat = activeChat;
        
        activeChat = [inChat retain];
        
        [self updateCloseMenuKeys];
        [self updateActiveWindowMenuItem];
        
        if (inChat && (inChat != mostRecentActiveChat)) {
                [mostRecentActiveChat release]; mostRecentActiveChat = nil;
                mostRecentActiveChat = [inChat retain];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Chat_BecameActive
                                                                                          object:inChat 
                                                                                        userInfo:(previouslyActiveChat ?
                                                                                                          [NSDictionary dictionaryWithObject:previouslyActiveChat
                                                                                                                                                                  forKey:@"PreviouslyActiveChat"] :
                                                                                                          nil)];
        
        if (inChat) {
                /* Clear the unviewed content on the next event loop so other methods have a chance to react to the chat becoming
                * active. Specifically, this lets the handleReopenWithVisibleWindows: method have a chance to know that this chat
                * had unviewed content.
                */
                [inChat performSelector:@selector(clearUnviewedContentCount)
                                         withObject:nil
                                         afterDelay:0];
        }
        
        [previouslyActiveChat release]; 
}

/*!
 * @brief A chat has become visible: send out a notification for components and plugins to take action
 *
 * @param inChat Chat that has become active
 * @param nWindow Containing chat window
 */
- (void)chatDidBecomeVisible:(AIChat *)inChat inWindow:(NSWindow *)inWindow
{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AIChatDidBecomeVisible"
                                                                                          object:inChat
                                                                                        userInfo:[NSDictionary dictionaryWithObject:inWindow
                                                                                                                                                                 forKey:@"NSWindow"]];
}

/*!
 * @brief Find the window currently displaying a chat
 *
 * @returns Window for chat otherwise if the chat is not in any window, or is not visible in any window, returns nil
 */
- (NSWindow *)windowForChat:(AIChat *)inChat
{
        return [interfacePlugin windowForChat:inChat];
}

/*!
 * @brief Find the chat active in a window
 *
 * If the window does not have an active chat, nil is returned
 */
- (AIChat *)activeChatInWindow:(NSWindow *)window
{
        return [interfacePlugin activeChatInWindow:window];
}

/*!
 * @brief A chat window did close: rebuild our window menu to remove the chat
 * 
 * @param inChat Chat that closed
 */
- (void)chatDidClose:(AIChat *)inChat
{
        [self _resetOpenChatsCache];
        [inChat clearUnviewedContentCount];
        [self buildWindowMenu];
        
        if (!adium.isQuitting) {
                // Don't save containers when the chats are closed while quitting
                [self saveContainers];
        }
        
        if (inChat == activeChat) {
                [activeChat release]; activeChat = nil;
        }
        
        if (inChat == mostRecentActiveChat) {
                [mostRecentActiveChat release]; mostRecentActiveChat = nil;
        }
}

/*!
 * @brief The order of chats has changed: rebuild our window menu to reflect the new order
 */
- (void)chatOrderDidChange
{
        [self _resetOpenChatsCache];
        [self buildWindowMenu];

        if (!adium.isQuitting) {
                // Don't save containers when the chats are closed while quitting
                [self saveContainers];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Chat_OrderDidChange object:nil userInfo:nil];
        
}

#pragma mark Unviewed content

/*!
 * @breif Content was received, increase the unviewed content count of the chat (if it's not currently active)
 */
- (void)didReceiveContent:(NSNotification *)notification
{
        AIChat          *chat = [[notification userInfo] objectForKey:@"AIChat"];
        
        if (chat != activeChat) {
                [chat incrementUnviewedContentCount];
        }
}


//Chat close menus -----------------------------------------------------------------------------------------------------
#pragma mark Chat close menus

/*!
 * @brief Closes currently active window
 */
- (IBAction)closeMenu:(id)sender
{
    [[[NSApplication sharedApplication] keyWindow] performClose:nil];
}

/*!
 * @brief Closes currently active chat (if there is an active chat)
 */
- (IBAction)closeChatMenu:(id)sender
{
        if (activeChat) [self closeChat:activeChat];
}

/*!
 * @brief Closes currently selected chat based on current chat contextual menu
 */
- (IBAction)closeContextualChat:(id)sender
{
        [self closeChat:[adium.menuController currentContextMenuChat]];
}

/*!
 * @brief Loop through open chats and close them
 */
- (IBAction)closeAllChats:(id)sender
{
        for (AIChat *chatToClose in [[interfacePlugin.openChats copy] autorelease]) {
                [self closeChat:chatToClose];
        }
}

/*!
 * @brief Updates the key equivalents on 'close' and 'close chat' (dynamically changed to make cmd-w less destructive)
 */
- (void)updateCloseMenuKeys
{
        if (activeChat && !closeMenuConfiguredForChat) {
        [menuItem_close setKeyEquivalent:@"W"];
        [menuItem_closeChat setKeyEquivalent:@"w"];
                closeMenuConfiguredForChat = YES;
        } else if (!activeChat && closeMenuConfiguredForChat) {
        [menuItem_close setKeyEquivalent:@"w"];
                [menuItem_closeChat removeKeyEquivalent];               
                closeMenuConfiguredForChat = NO;
        }
}


//Window Menu ----------------------------------------------------------------------------------------------------------
#pragma mark Window Menu

/*!
 * @brief Open the authorization requests window.
 */
- (void)openAuthorizationWindow:(id)sender
{
        [[AIAuthorizationRequestsWindowController sharedController] showWindow:nil];
}

/*!
 * @brief Make a chat window active
 * 
 * Invoked by a selection in the window menu
 */
- (IBAction)showChatWindow:(id)sender
{
        [self setActiveChat:[sender representedObject]];
    [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
}

/*!
 * @brief Updates the 'check' icon so it's next to the active window
 */
- (void)updateActiveWindowMenuItem
{
    NSMenuItem          *item;

    for (item in windowMenuArray) {
                if ([item representedObject]) [item setState:([item representedObject] == activeChat ? NSOnState : NSOffState)];
    }
}

/*!
 * @brief Builds the window menu
 * 
 * This function gets called whenever chats are opened, closed, or re-ordered - so improvements and optimizations here
 * would probably be helpful
 */
- (void)buildWindowMenu
{       
    NSMenuItem                          *item;
    NSInteger                                           windowKey = 1;
        
    //Remove any existing menus
    for (item in windowMenuArray) {
        [adium.menuController removeMenuItem:item];
    }
    [windowMenuArray release]; windowMenuArray = [[NSMutableArray alloc] init];
        
    //Messages window and any open messasges    
        for (NSDictionary *containerDict in [interfacePlugin openContainersAndChats]) {
                NSString                *containerName = [containerDict objectForKey:@"Name"];
                NSArray                 *contentArray = [containerDict objectForKey:@"Content"];
                
                //Add a menu item for the container
                if (contentArray.count > 1) {
                        item = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:([containerName length] ? containerName : AILocalizedString(@"Chats", nil))
                                                                                                                                                target:nil
                                                                                                                                                action:nil
                                                                                                                                 keyEquivalent:@""];
                        [self _addItemToMainMenuAndDock:item];
                        [item release];
                }
                
                //Add items for the chats it contains
                for (AIChat *chat in [contentArray objectEnumerator]) {
                        NSString                *windowKeyString;
                        
                        //Prepare a key equivalent for the controller
                        if (windowKey < 10) {
                                windowKeyString = [NSString stringWithFormat:@"%ld", (windowKey)];
                        } else if (windowKey == 10) {
                                windowKeyString = [NSString stringWithString:@"0"];
                        } else {
                                windowKeyString = [NSString stringWithString:@""];
                        }
                        
                        item = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:chat.displayName
                                                                                                                                                target:self
                                                                                                                                                action:@selector(showChatWindow:)
                                                                                                                                 keyEquivalent:windowKeyString];
                        if ([contentArray count] > 1) [item setIndentationLevel:1];
                        [item setRepresentedObject:chat];
                        [item setImage:chat.chatMenuImage];
                        [self _addItemToMainMenuAndDock:item];
                        [item release];

                        windowKey++;
                }
        }

        [self updateActiveWindowMenuItem];
}

/*!
 * brief Adds a menu item to the internal array, dock menu, and main menu
 *
 * Should be used for adding a new window to the window menu (and dock menu)
 */
- (void)_addItemToMainMenuAndDock:(NSMenuItem *)item
{
        //Add to main menu first
        [adium.menuController addMenuItem:item toLocation:LOC_Window_Fixed];
        [windowMenuArray addObject:item];
        
        //Make a copy, and add to the dock
        item = [item copy];
        [item setKeyEquivalent:@""];
        [adium.menuController addMenuItem:item toLocation:LOC_Dock_Status];
        [windowMenuArray addObject:item];
        [item release];
}


//Chat Cycling ---------------------------------------------------------------------------------------------------------
#pragma mark Chat Cycling

/*!
 * @brief Cycles to the next active chat
 */
- (void)nextChat:(id)sender
{
        NSArray *openChats = [self openChats];

        if ([openChats count]) {
                if (activeChat) {
                        NSInteger chatIndex = [openChats indexOfObject:activeChat]+1;
                        [self setActiveChat:[openChats objectAtIndex:(chatIndex < [openChats count] ? chatIndex : 0)]];
                } else {
                        [self setActiveChat:[openChats objectAtIndex:0]];
                }
        }
}

/*!
 * @brief Cycles to the previus active chat
 */
- (void)previousChat:(id)sender
{
        NSArray *openChats = [self openChats];
        
        if ([openChats count]) {
                if (activeChat) {
                        NSInteger chatIndex = [openChats indexOfObject:activeChat]-1;
                        [self setActiveChat:[openChats objectAtIndex:(chatIndex >= 0 ? chatIndex : [openChats count]-1)]];
                } else {
                        [self setActiveChat:[openChats lastObject]];
                }
        }
}

//Selected contact ------------------------------------------------
#pragma mark Selected contact
- (id)_performSelectorOnFirstAvailableResponder:(SEL)selector
{
    NSResponder *responder = [[[NSApplication sharedApplication] mainWindow] firstResponder];
    //Check the first responder
    if ([responder respondsToSelector:selector]) {
        return [responder performSelector:selector];
    }
        
    //Search the responder chain
    do{
        responder = [responder nextResponder];
        if ([responder respondsToSelector:selector]) {
            return [responder performSelector:selector];
        }
                
    } while (responder != nil);
        
    //None found, return nil
    return nil;
}
- (id)_performSelectorOnFirstAvailableResponder:(SEL)selector conformingToProtocol:(Protocol *)protocol
{
        NSResponder *responder = [[[NSApplication sharedApplication] mainWindow] firstResponder];
        //Check the first responder
        if ([responder conformsToProtocol:protocol] && [responder respondsToSelector:selector]) {
                return [responder performSelector:selector];
        }
        
    //Search the responder chain
    do{
        responder = [responder nextResponder];
        if ([responder conformsToProtocol:protocol] && [responder respondsToSelector:selector]) {
            return [responder performSelector:selector];
        }
                
    } while (responder != nil);
        
    //None found, return nil
    return nil;
}

/*!
 * @returns The "selected"(represented) contact (By finding the first responder that returns a contact)
 * If no listObject is found, try to find a list object selected in a group chat
 */
- (AIListObject *)selectedListObject
{
        AIListObject *listObject = [self _performSelectorOnFirstAvailableResponder:@selector(listObject)];
        if ( !listObject) {
                listObject = [self _performSelectorOnFirstAvailableResponder:@selector(preferredListObject)];
        }
        return listObject;
}

- (AIListObject *)selectedListObjectInContactList
{
        return [self _performSelectorOnFirstAvailableResponder:@selector(listObject) conformingToProtocol:@protocol(ContactListOutlineView)];
}
- (NSArray *)arrayOfSelectedListObjectsInContactList
{
        return [self _performSelectorOnFirstAvailableResponder:@selector(arrayOfListObjects) conformingToProtocol:@protocol(ContactListOutlineView)];
}
- (NSArray *)arrayOfSelectedListObjectsWithGroupsInContactList
{
        return [self _performSelectorOnFirstAvailableResponder:@selector(arrayOfListObjectsWithGroups) conformingToProtocol:@protocol(ContactListOutlineView)];
}

//Message View ---------------------------------------------------------------------------------------------------------
//Message view is abstracted from the containing interface, since they're not directly related to eachother
#pragma mark Message View
//Registers a view to handle the contact list
- (void)registerMessageDisplayPlugin:(id <AIMessageDisplayPlugin>)inPlugin
{
    [messageViewArray addObject:inPlugin];
}
- (void)unregisterMessageDisplayPlugin:(id <AIMessageDisplayPlugin>)inPlugin
{
    [messageViewArray removeObject:inPlugin];
}
- (id <AIMessageDisplayController>)messageDisplayControllerForChat:(AIChat *)inChat
{
        //Sometimes our users find it amusing to disable plugins that are located within the Adium bundle.  This error
        //trap prevents us from crashing if they happen to disable all the available message view plugins.
        //PUT THAT PLUGIN BACK IT WAS IMPORTANT!
        if ([messageViewArray count] == 0) {
                NSRunCriticalAlertPanel(@"No Message View Plugin Installed",
                                                                @"Adium cannot find its message view plugin. Please re-install.  If you've manually disabled Adium's message view plugin, please re-enable it.",
                                                                @"Quit",
                                                                nil,
                                                                nil);
                [NSApp terminate:nil];
        }
        
        return [[messageViewArray objectAtIndex:0] messageDisplayControllerForChat:inChat];
}


//Error Display --------------------------------------------------------------------------------------------------------
#pragma mark Error Display
- (void)handleErrorMessage:(NSString *)inTitle withDescription:(NSString *)inDesc
{
    [self handleMessage:inTitle withDescription:inDesc withWindowTitle:ERROR_MESSAGE_WINDOW_TITLE];
}

- (void)handleMessage:(NSString *)inTitle withDescription:(NSString *)inDesc withWindowTitle:(NSString *)inWindowTitle;
{
    NSDictionary        *errorDict;
    
    //Post a notification that an error was recieved
    errorDict = [NSDictionary dictionaryWithObjectsAndKeys:inTitle,@"Title",inDesc,@"Description",inWindowTitle,@"Window Title",nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Interface_ShouldDisplayErrorMessage object:nil userInfo:errorDict];
}

//Display then clear the last disconnection error
- (void)account:(AIAccount *)inAccount disconnectedWithError:(NSString *)disconnectionError
{

}

//Question Display -----------------------------------------------------------------------------------------------------
#pragma mark Question Display
- (void)displayQuestion:(NSString *)inTitle withAttributedDescription:(NSAttributedString *)inDesc withWindowTitle:(NSString *)inWindowTitle
                  defaultButton:(NSString *)inDefaultButton alternateButton:(NSString *)inAlternateButton otherButton:(NSString *)inOtherButton suppression:(NSString *)inSuppression
                                 target:(id)inTarget selector:(SEL)inSelector userInfo:(id)inUserInfo
{
        NSMutableDictionary *questionDict = [NSMutableDictionary dictionary];
        
        if(inTitle != nil)
                [questionDict setObject:inTitle forKey:@"Title"];
        if(inDesc != nil)
                [questionDict setObject:inDesc forKey:@"Description"];
        if(inWindowTitle != nil)
                [questionDict setObject:inWindowTitle forKey:@"Window Title"];
        if(inDefaultButton != nil)
                [questionDict setObject:inDefaultButton forKey:@"Default Button"];
        if(inAlternateButton != nil)
                [questionDict setObject:inAlternateButton forKey:@"Alternate Button"];
        if(inOtherButton != nil)
                [questionDict setObject:inOtherButton forKey:@"Other Button"];
        if(inSuppression != nil)
                [questionDict setObject:inSuppression forKey:@"Suppression Checkbox"];
        if(inTarget != nil)
                [questionDict setObject:inTarget forKey:@"Target"];
        if(inSelector != NULL)
                [questionDict setObject:NSStringFromSelector(inSelector) forKey:@"Selector"];
        if(inUserInfo != nil)
                [questionDict setObject:inUserInfo forKey:@"Userinfo"];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:Interface_ShouldDisplayQuestion object:nil userInfo:questionDict];
}

- (void)displayQuestion:(NSString *)inTitle withDescription:(NSString *)inDesc withWindowTitle:(NSString *)inWindowTitle
                  defaultButton:(NSString *)inDefaultButton alternateButton:(NSString *)inAlternateButton otherButton:(NSString *)inOtherButton suppression:(NSString *)inSuppression
                                 target:(id)inTarget selector:(SEL)inSelector userInfo:(id)inUserInfo
{
        [self displayQuestion:inTitle
withAttributedDescription:[[[NSAttributedString alloc] initWithString:inDesc
                                                                                                                   attributes:[NSDictionary dictionaryWithObject:[NSFont systemFontOfSize:0]
                                                                                                                                                                                                  forKey:NSFontAttributeName]] autorelease]
                  withWindowTitle:inWindowTitle
                        defaultButton:inDefaultButton
                  alternateButton:inAlternateButton
                          otherButton:inOtherButton
                          suppression:inSuppression
                                   target:inTarget
                                 selector:inSelector
                                 userInfo:inUserInfo];
}
//Synchronized Flashing ------------------------------------------------------------------------------------------------
#pragma mark Synchronized Flashing
//Register to observe the synchronized flashing
- (void)registerFlashObserver:(id <AIFlashObserver>)inObserver
{
    //Setup the timer if we don't have one yet
    if (!flashObserverArray) {
        flashObserverArray = [[NSMutableArray alloc] init];
        flashTimer = [[NSTimer scheduledTimerWithTimeInterval:(1.0/2.0) 
                                                       target:self 
                                                     selector:@selector(flashTimer:) 
                                                     userInfo:nil
                                                      repeats:YES] retain];
    }
    
    //Add the new observer to the array
    [flashObserverArray addObject:inObserver];
}

//Unregister from observing flashing
- (void)unregisterFlashObserver:(id <AIFlashObserver>)inObserver
{
    //Remove the observer from our array
    [flashObserverArray removeObject:inObserver];
    
    //Release the observer array and uninstall the timer
    if ([flashObserverArray count] == 0) {
        [flashObserverArray release]; flashObserverArray = nil;
        [flashTimer invalidate];
        [flashTimer release]; flashTimer = nil;
    }
}

//Timer, invoke a flash
- (void)flashTimer:(NSTimer *)inTimer
{
        flashState++;

        for (id<AIFlashObserver>observer in [[flashObserverArray copy] autorelease]) {
                [observer flash:flashState];
        }
}

//Current state of flashing.  This is an integer the increases by 1 with every flash.  Mod to whatever range is desired
- (int)flashState
{
    return flashState;
}


//Tooltips -------------------------------------------------------------------------------------------------------------
#pragma mark Tooltips
//Registers code to display tooltip info about a contact
- (void)registerContactListTooltipEntry:(id <AIContactListTooltipEntry>)inEntry secondaryEntry:(BOOL)isSecondary
{
    if (isSecondary)
        [contactListTooltipSecondaryEntryArray addObject:inEntry];
    else
        [contactListTooltipEntryArray addObject:inEntry];
}

//Unregisters code to display tooltip info about a contact
- (void)unregisterContactListTooltipEntry:(id <AIContactListTooltipEntry>)inEntry secondaryEntry:(BOOL)isSecondary
{
    if (isSecondary)
        [contactListTooltipSecondaryEntryArray removeObject:inEntry];
    else
        [contactListTooltipEntryArray removeObject:inEntry];
}

- (NSArray *)contactListTooltipPrimaryEntries
{
        return contactListTooltipEntryArray;
}

- (NSArray *)contactListTooltipSecondaryEntries
{
        return contactListTooltipSecondaryEntryArray;
}

//list object tooltips
- (void)showTooltipForListObject:(AIListObject *)object atScreenPoint:(NSPoint)point onWindow:(NSWindow *)inWindow 
{
    if (object) {
        if (object == tooltipListObject) { //If we already have this tooltip open
                                         //Move the existing tooltip
            [AITooltipUtilities showTooltipWithTitle:tooltipTitle
                                                                                                body:tooltipBody
                                                                                           image:tooltipImage 
                                                                                imageOnRight:DISPLAY_IMAGE_ON_RIGHT 
                                                                                        onWindow:inWindow
                                                                                         atPoint:point 
                                                                                 orientation:TooltipBelow];
            
        } else { //This is a new tooltip
            NSArray                     *tabArray;
            NSMutableParagraphStyle     *paragraphStyleTitle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
            NSMutableParagraphStyle     *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
            
            //Hold onto the new object
            [tooltipListObject release]; tooltipListObject = [object retain];
            
            //Buddy Icon
            [tooltipImage release];
                        tooltipImage = [[tooltipListObject userIcon] retain];
                        if (!tooltipImage) tooltipImage = [[AIServiceIcons serviceIconForObject:tooltipListObject
                                                                                                                                                         type:AIServiceIconLarge
                                                                                                                                                direction:AIIconNormal] retain];
            
            //Reset the maxLabelWidth for the tooltip generation
            maxLabelWidth = 0;
            
            //Build a tooltip string for the primary information
            [tooltipTitle release]; tooltipTitle = [[self _tooltipTitleForObject:object] retain];
            
            //If there is an image, set the title tab and indentation settings independently
            if (tooltipImage) {
                //Set a right-align tab at the maximum label width and a left-align just past it
                tabArray = [[NSArray alloc] initWithObjects:[[[NSTextTab alloc] initWithType:NSRightTabStopType 
                                                                                                                                                                        location:maxLabelWidth] autorelease]
                                                            ,[[[NSTextTab alloc] initWithType:NSLeftTabStopType 
                                                                                   location:maxLabelWidth + LABEL_ENTRY_SPACING] autorelease]
                                                            ,nil];
                
                [paragraphStyleTitle setTabStops:tabArray];
                [tabArray release];
                tabArray = nil;
                [paragraphStyleTitle setHeadIndent:(maxLabelWidth + LABEL_ENTRY_SPACING)];
                
                [tooltipTitle addAttribute:NSParagraphStyleAttributeName 
                                     value:paragraphStyleTitle
                                     range:NSMakeRange(0,[tooltipTitle length])];
                
                //Reset the max label width since the body will be independent
                maxLabelWidth = 0;
            }
            
            //Build a tooltip string for the secondary information
            [tooltipBody release]; tooltipBody = nil;
            tooltipBody = [[self _tooltipBodyForObject:object] retain];
            
            //Set a right-align tab at the maximum label width for the body and a left-align just past it
            tabArray = [[NSArray alloc] initWithObjects:[[[NSTextTab alloc] initWithType:NSRightTabStopType 
                                                                                 location:maxLabelWidth] autorelease]
                                                        ,[[[NSTextTab alloc] initWithType:NSLeftTabStopType 
                                                                                location:maxLabelWidth + LABEL_ENTRY_SPACING] autorelease]
                                                        ,nil];
            [paragraphStyle setTabStops:tabArray];
            [tabArray release];
            [paragraphStyle setHeadIndent:(maxLabelWidth + LABEL_ENTRY_SPACING)];
            
            [tooltipBody addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[tooltipBody length])];
            //If there is no image, also use these settings for the top part
            if (!tooltipImage) {
                [tooltipTitle addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[tooltipTitle length])];
            }
            
            //Display the new tooltip
            [AITooltipUtilities showTooltipWithTitle:tooltipTitle
                                                body:tooltipBody 
                                               image:tooltipImage
                                        imageOnRight:DISPLAY_IMAGE_ON_RIGHT
                                            onWindow:inWindow
                                             atPoint:point 
                                         orientation:TooltipBelow];
                        
                        [paragraphStyleTitle release];
                        [paragraphStyle release];
        }
        
    } else {
        //Hide the existing tooltip
        if (tooltipListObject) {
            [AITooltipUtilities showTooltipWithTitle:nil 
                                                body:nil
                                               image:nil 
                                            onWindow:nil
                                             atPoint:point
                                         orientation:TooltipBelow];
            [tooltipListObject release]; tooltipListObject = nil;
                        
                        [tooltipTitle release]; tooltipTitle = nil;
                        [tooltipBody release]; tooltipBody = nil;
                        [tooltipImage release]; tooltipImage = nil;
        }
    }
}

- (NSAttributedString *)_tooltipTitleForObject:(AIListObject *)object
{
    NSMutableAttributedString           *titleString = [[NSMutableAttributedString alloc] init];
    
    id <AIContactListTooltipEntry>              tooltipEntry;
    NSEnumerator                        *labelEnumerator;
    NSMutableArray                      *labelArray = [NSMutableArray array];
    NSMutableArray                      *entryArray = [NSMutableArray array];
    NSMutableAttributedString           *entryString;
    CGFloat                               labelWidth;
    BOOL                                isFirst = YES;
    
    NSString                            *formattedUID = object.formattedUID;
    
    //Configure fonts and attributes
    NSFontManager                       *fontManager = [NSFontManager sharedFontManager];
    NSFont                              *toolTipsFont = [NSFont toolTipsFontOfSize:10];
    NSMutableDictionary                 *titleDict = [NSMutableDictionary dictionaryWithObject:[fontManager convertFont:[NSFont toolTipsFontOfSize:12] toHaveTrait:NSBoldFontMask]
                                                                                            forKey:NSFontAttributeName];
    NSMutableDictionary                 *labelDict = [NSMutableDictionary dictionaryWithObject:[fontManager convertFont:[NSFont toolTipsFontOfSize:9] toHaveTrait:NSBoldFontMask]
                                                                                            forKey:NSFontAttributeName];
    NSMutableDictionary                 *labelEndLineDict = [NSMutableDictionary dictionaryWithObject:[NSFont toolTipsFontOfSize:2]
                                                                                                   forKey:NSFontAttributeName];
    NSMutableDictionary                 *entryDict = [NSMutableDictionary dictionaryWithObject:toolTipsFont
                                                                                            forKey:NSFontAttributeName];
        
        //Get the user's display name as an attributed string
    NSAttributedString                  *displayName = [[NSAttributedString alloc] initWithString:object.displayName
                                                                                                                                                                           attributes:titleDict];
        NSAttributedString                                      *filteredDisplayName = [adium.contentController filterAttributedString:displayName
                                                                                                                                                                                                 usingFilterType:AIFilterTooltips
                                                                                                                                                                                                           direction:AIFilterIncoming
                                                                                                                                                                                                                 context:nil];
        
        //Append the user's display name
        if (filteredDisplayName) {
                [titleString appendAttributedString:filteredDisplayName];
        }
        
        //Append the user's formatted UID if there is one that's different to the display name
        if (formattedUID && (!([[[displayName string] compactedString] isEqualToString:[formattedUID compactedString]]))) {
                [titleString appendString:[NSString stringWithFormat:@" (%@)", formattedUID] withAttributes:titleDict];
        }
        [displayName release];
    
    if ([object isKindOfClass:[AIListContact class]]) {
                if ((![object isKindOfClass:[AIMetaContact class]] || [(AIMetaContact *)object containsOnlyOneService]) &&
                        [object userIcon]) {
                        NSImage *serviceIcon = [[AIServiceIcons serviceIconForObject:object type:AIServiceIconSmall direction:AIIconNormal]
                                                                        imageByScalingToSize:NSMakeSize(14,14)];
                        if (serviceIcon) {
                                NSTextAttachment                *attachment;
                                NSTextAttachmentCell    *cell;
                                
                                cell = [[NSTextAttachmentCell alloc] init];
                                [cell setImage:serviceIcon];
                                
                                attachment = [[NSTextAttachment alloc] init];
                                [attachment setAttachmentCell:cell];
                                [cell release];
        
                                [titleString appendString:@" " withAttributes:nil];
                                [titleString appendAttributedString:[NSAttributedString attributedStringWithAttachment:attachment]];
                                [attachment release];
                        }
                }
        }
                
    if ([object isKindOfClass:[AIListGroup class]]) {
        [titleString appendString:[NSString stringWithFormat:@" (%ld/%ld)",[(AIListGroup *)object visibleCount],[(AIListGroup *)object countOfContainedObjects]] 
                   withAttributes:titleDict];
    }
    
    //Entries from plugins
    
    //Calculate the widest label while loading the arrays
    
    for (tooltipEntry in contactListTooltipEntryArray) {
        
        entryString = [[tooltipEntry entryForObject:object] mutableCopy];
        if (entryString && [entryString length]) {
            
            NSString        *labelString = [tooltipEntry labelForObject:object];
            if (labelString && [labelString length]) {
                
                [entryArray addObject:entryString];
                [labelArray addObject:labelString];
                
                NSAttributedString * labelAttribString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:",labelString] 
                                                                                                                                                                                 attributes:labelDict];
                
                //The largest size should be the label's size plus the distance to the next tab at least a space past its end
                labelWidth = [labelAttribString size].width;
                [labelAttribString release];
                
                if (labelWidth > maxLabelWidth)
                    maxLabelWidth = labelWidth;
            }
        }
        [entryString release];
    }
    
    //Add labels plus entires to the toolTip
    labelEnumerator = [labelArray objectEnumerator];
    
    for (entryString in entryArray) {        
        NSAttributedString * labelAttribString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"\t%@:\t",[labelEnumerator nextObject]]
                                                                                                                                                                 attributes:labelDict];
        
        //Add a carriage return
        [titleString appendString:@"\n" withAttributes:labelEndLineDict];
        
        if (isFirst) {
            //skip a line
            [titleString appendString:@"\n" withAttributes:labelEndLineDict];
            isFirst = NO;
        }
        
        //Add the label (with its spacing)
        [titleString appendAttributedString:labelAttribString];
                [labelAttribString release];

                [entryString addAttributes:entryDict range:NSMakeRange(0,[entryString length])];
        [titleString appendAttributedString:entryString];
    }

    return [titleString autorelease];
}

- (NSAttributedString *)_tooltipBodyForObject:(AIListObject *)object
{
    NSMutableAttributedString       *tipString = [[NSMutableAttributedString alloc] init];
    
    //Configure fonts and attributes
    NSFontManager                   *fontManager = [NSFontManager sharedFontManager];
    NSFont                          *toolTipsFont = [NSFont toolTipsFontOfSize:10];
    NSMutableDictionary             *labelDict = [NSMutableDictionary dictionaryWithObject:[fontManager convertFont:[NSFont toolTipsFontOfSize:9] toHaveTrait:NSBoldFontMask]
                                                                                        forKey:NSFontAttributeName];
    NSMutableDictionary             *labelEndLineDict = [NSMutableDictionary dictionaryWithObject:[NSFont toolTipsFontOfSize:1]
                                                                                               forKey:NSFontAttributeName];
    NSMutableDictionary             *entryDict = [NSMutableDictionary dictionaryWithObject:toolTipsFont
                                                                                        forKey:NSFontAttributeName];
    
    //Entries from plugins
    NSEnumerator                    *labelEnumerator; 
    NSMutableArray                  *labelArray = [NSMutableArray array]; //Array of NSStrings
    NSMutableArray                  *entryArray = [NSMutableArray array]; //Array of NSMutableStrings   
    CGFloat                         labelWidth;
    BOOL                            firstEntry = YES;
    
    //Calculate the widest label while loading the arrays
        for (id <AIContactListTooltipEntry>tooltipEntry in contactListTooltipSecondaryEntryArray) {
                NSMutableAttributedString *entryString = [[tooltipEntry entryForObject:object] mutableCopy];
                if (entryString && entryString.length) {
                        NSString        *labelString = [tooltipEntry labelForObject:object];

                        if (labelString && labelString.length) {
                                [entryArray addObject:entryString];
                                [labelArray addObject:labelString];
                                
                                NSAttributedString *labelAttribString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@:",labelString] 
                                                                                                                                                                                attributes:labelDict];
                                
                                //The largest size should be the label's size plus the distance to the next tab at least a space past its end
                                labelWidth = labelAttribString.size.width;
                                [labelAttribString release];
                                
                                if (labelWidth > maxLabelWidth)
                                        maxLabelWidth = labelWidth;
                        }
                }
                [entryString release];
        }
                
    //Add labels plus entires to the toolTip
    labelEnumerator = [labelArray objectEnumerator];
    for (NSMutableAttributedString *entryString in entryArray) {
        NSMutableAttributedString *labelString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"\t%@:\t",[labelEnumerator nextObject]]
                                                                                                                                                                                attributes:labelDict];
        
        if (firstEntry) {
            firstEntry = NO;
        } else {
            //Add a carriage return and skip a line
            [tipString appendString:@"\n\n" withAttributes:labelEndLineDict];
        }
        
        //Add the label (with its spacing)
        [tipString appendAttributedString:labelString];
        [labelString release];

        NSRange fullLength = NSMakeRange(0, [entryString length]);
        
        //remove any background coloration
        [entryString removeAttribute:NSBackgroundColorAttributeName range:fullLength];
        
        //adjust foreground colors for the tooltip background
        [entryString adjustColorsToShowOnBackground:[NSColor colorWithCalibratedRed:1.000 green:1.000 blue:0.800 alpha:1.0]];

        //headIndent doesn't apply to the first line of a paragraph... so when new lines are in the entry, we need to tab over to the proper location
                if ([entryString replaceOccurrencesOfString:@"\r" withString:@"\r\t\t" options:NSLiteralSearch range:fullLength])
            fullLength = NSMakeRange(0, [entryString length]);
        if ([entryString replaceOccurrencesOfString:@"\n" withString:@"\n\t\t" options:NSLiteralSearch range:fullLength])
            fullLength = NSMakeRange(0, [entryString length]);
                
        //Run the entry through the filters and add it to tipString
                entryString = [[adium.contentController filterAttributedString:entryString
                                                                                                                 usingFilterType:AIFilterTooltips
                                                                                                                           direction:AIFilterIncoming
                                                                                                                                 context:object] mutableCopy];
                
                [entryString addAttributes:entryDict range:NSMakeRange(0,[entryString length])];
        [tipString appendAttributedString:entryString];
                [entryString release];
    }

    return [tipString autorelease];
}

//Custom pasting ----------------------------------------------------------------------------------------------------
#pragma mark Custom Pasting
//Paste, stripping formatting
- (IBAction)paste:(id)sender
{
        [self _pasteWithPreferredSelector:@selector(pasteAsPlainTextWithTraits:) sender:sender];
}

//Paste with formatting
- (IBAction)pasteAndMatchStyle:(id)sender
{
        [self _pasteWithPreferredSelector:@selector(pasteAsPlainText:) sender:sender];
}

- (IBAction)pasteWithImagesAndColors:(id)sender
{
        [self _pasteWithPreferredSelector:@selector(pasteAsRichText:) sender:sender];   
}

/*!
 * @brief Send a paste message, using preferredSelector if possible and paste: if not
 *
 * Walks the responder chain looking for a responder which can handle pasting, skipping instances of
 * WebHTMLView.  These are skipped because we can control what paste does to WebView (by using a custom subclass) but
 * have no control over what the WebHTMLView would do.
 *
 * If no responder is found, repeats the process looking for the simpler paste: selector.
 */
- (void)_pasteWithPreferredSelector:(SEL)selector sender:(id)sender
{
        NSWindow        *keyWindow = [[NSApplication sharedApplication] keyWindow];
        NSResponder     *responder;

        //First, look for a responder which can handle the preferred selector
        if (!(responder = [keyWindow earliestResponderWhichRespondsToSelector:selector
                                                                                                                  andIsNotOfClass:NSClassFromString(@"WebHTMLView")])) {                
                //No responder found.  Try again, looking for one which will respond to paste:
                selector = @selector(paste:);
                responder = [keyWindow earliestResponderWhichRespondsToSelector:selector
                                                                                                                andIsNotOfClass:NSClassFromString(@"WebHTMLView")];
        }

        //Sending pasteAsRichText: to a non rich text NSTextView won't do anything; change it to a generic paste:
        if ([responder isKindOfClass:[NSTextView class]] && ![(NSTextView *)responder isRichText]) {
                selector = @selector(paste:);
        }

        if (selector) {
                [keyWindow makeFirstResponder:responder];
                [responder performSelector:selector
                                                withObject:sender];
        }
}

//Custom Printing ------------------------------------------------------------------------------------------------------
#pragma mark Custom Printing
- (IBAction)adiumPrint:(id)sender
{
        //Pass the print command to the window, which is responsible for routing it to the correct place or
        //creating a view and printing.  Adium will not print from a window that does not respond to adiumPrint:
        NSWindow        *keyWindowController = [[[NSApplication sharedApplication] keyWindow] windowController];
        if ([keyWindowController respondsToSelector:@selector(adiumPrint:)]) {
                [keyWindowController performSelector:@selector(adiumPrint:)
                                                                  withObject:sender];
        }
}

#pragma mark Preferences Display
- (IBAction)showPreferenceWindow:(id)sender
{
        [adium.preferenceController showPreferenceWindow:sender];
}

#pragma mark Font Panel
- (IBAction)toggleFontPanel:(id)sender
{
        if ([NSFontPanel sharedFontPanelExists] &&
                [[NSFontPanel sharedFontPanel] isVisible]) {
                [[NSFontPanel sharedFontPanel] close];

        } else {
                NSFontPanel     *fontPanel = [NSFontPanel sharedFontPanel];
                
                if (!fontPanelAccessoryView) {
                        [NSBundle loadNibNamed:@"FontPanelAccessoryView" owner:self];
                        [fontPanel setAccessoryView:fontPanelAccessoryView];
                }
                
                [fontPanel orderFront:self]; 
        }
}

- (IBAction)setFontPanelSettingsAsDefaultFont:(id)sender
{
        NSFont  *selectedFont = [[NSFontManager sharedFontManager] selectedFont];

        [adium.preferenceController setPreference:[selectedFont stringRepresentation]
                                                                                 forKey:KEY_FORMATTING_FONT
                                                                                  group:PREF_GROUP_FORMATTING];
        
        //We can't get foreground/background color from the font panel so far as I can tell... so we do the best we can.
        NSWindow        *keyWindow = [[NSApplication sharedApplication] keyWindow];
        NSResponder *responder = [keyWindow firstResponder]; 
        if ([responder isKindOfClass:[NSTextView class]]) {
                NSDictionary    *typingAttributes = [(NSTextView *)responder typingAttributes];
                NSColor                 *foregroundColor, *backgroundColor;

                if ((foregroundColor = [typingAttributes objectForKey:NSForegroundColorAttributeName])) {
                        [adium.preferenceController setPreference:[foregroundColor stringRepresentation]
                                                                                                 forKey:KEY_FORMATTING_TEXT_COLOR
                                                                                                  group:PREF_GROUP_FORMATTING];
                }

                if ((backgroundColor = [typingAttributes objectForKey:AIBodyColorAttributeName])) {
                        [adium.preferenceController setPreference:[backgroundColor stringRepresentation]
                                                                                                 forKey:KEY_FORMATTING_BACKGROUND_COLOR
                                                                                                  group:PREF_GROUP_FORMATTING];
                }
        }
}

//Custom Dimming menu items --------------------------------------------------------------------------------------------
#pragma mark Custom Dimming menu items
//The standard ones do not dim correctly when unavailable
- (IBAction)toggleFontTrait:(id)sender
{
    NSFontManager       *fontManager = [NSFontManager sharedFontManager];
    
    if ([fontManager traitsOfFont:[fontManager selectedFont]] & [sender tag]) {
        [fontManager removeFontTrait:sender];
    } else {
        [fontManager addFontTrait:sender];
    }
}

- (void)toggleToolbarShown:(id)sender
{
        NSWindow        *window = [[NSApplication sharedApplication] keyWindow];        
        [window toggleToolbarShown:sender];
}

- (void)runToolbarCustomizationPalette:(id)sender
{
        NSWindow        *window = [[NSApplication sharedApplication] keyWindow];        
        [window runToolbarCustomizationPalette:sender];
}

//Menu item validation
- (BOOL)validateMenuItem:(NSMenuItem *)menuItem
{
        
        NSWindow        *keyWindow = [[NSApplication sharedApplication] keyWindow];
        NSResponder *responder = [keyWindow firstResponder]; 
        
    if (menuItem == menuItem_bold || menuItem == menuItem_italic) {
                NSFont                  *selectedFont = [[NSFontManager sharedFontManager] selectedFont];
                
                //We must be in a text view, have text on the pasteboard, and have a font that supports bold or italic
                if ([responder isKindOfClass:[NSTextView class]]) {
                        return (menuItem == menuItem_bold ? [selectedFont supportsBold] : [selectedFont supportsItalics]);
                }
                return NO;
                
        } else if (menuItem == menuItem_paste || menuItem == menuItem_pasteAndMatchStyle || menuItem == menuItem_pasteWithImagesAndColors) {

                //The user can paste if the pasteboard contains an image, some text, one or more files, or one or more URLs.
                NSPasteboard *pboard = [NSPasteboard generalPasteboard];
                NSArray *nonImageTypes = [NSArray arrayWithObjects:
                        NSStringPboardType,
                        NSRTFPboardType,
                        NSURLPboardType,
                        NSFilenamesPboardType,
                        NSFilesPromisePboardType,
                        NSRTFDPboardType,
                        nil];
                return ([pboard availableTypeFromArray:nonImageTypes] != nil) || [NSImage canInitWithPasteboard:pboard];
        
        } else if (menuItem == menuItem_showToolbar) {
                [menuItem_showToolbar setTitle:([[keyWindow toolbar] isVisible] ? 
                                                                                AILocalizedString(@"Hide Toolbar",nil) : 
                                                                                AILocalizedString(@"Show Toolbar",nil))];
                return [keyWindow toolbar] != nil;
        
        } else if (menuItem == menuItem_customizeToolbar) {
                return ([keyWindow toolbar] != nil && [[keyWindow toolbar] isVisible] && [[keyWindow windowController] canCustomizeToolbar]);

        } else if (menuItem == menuItem_close) {
                return (keyWindow && ([[keyWindow standardWindowButton:NSWindowCloseButton] isEnabled] ||
                                                          ([[keyWindow windowController] respondsToSelector:@selector(windowPermitsClose)] &&
                                                           [[keyWindow windowController] windowPermitsClose])));
                
        } else if (menuItem == menuItem_closeChat || menuItem == menuItem_clearDisplay) {
                return activeChat != nil;
                
        } else if( menuItem == menuItem_closeAllChats) {
                return [[self openChats] count] > 0;

        } else if (menuItem == menuItem_print) {
                NSWindowController *windowController = [keyWindow windowController];

                return ([windowController respondsToSelector:@selector(adiumPrint:)] &&
                                (![windowController respondsToSelector:@selector(validatePrintMenuItem:)] ||
                                 [windowController validatePrintMenuItem:menuItem]));
                
        } else if (menuItem == menuItem_showFonts) {
                [menuItem_showFonts setTitle:(([NSFontPanel sharedFontPanelExists] && [[NSFontPanel sharedFontPanel] isVisible]) ?
                                                                          AILocalizedString(@"Hide Fonts",nil) :
                                                                          AILocalizedString(@"Show Fonts",nil))];
                return YES;
        } else if (menuItem == menuItem_toggleUserlist || menuItem == menuItem_toggleUserlistSide) {
                        return self.activeChat.isGroupChat;
        } else {
                return YES;
        }
}

#pragma mark Window levels
- (NSMenu *)menuForWindowLevelsNotifyingTarget:(id)target
{
        NSMenu          *windowPositionMenu = [[NSMenu allocWithZone:[NSMenu zone]] init];
        NSMenuItem      *menuItem;
        
        menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Above other windows",nil)
                                                                                                                                        target:target
                                                                                                                                        action:@selector(selectedWindowLevel:)
                                                                                                                         keyEquivalent:@""];
        [menuItem setEnabled:YES];
        [menuItem setTag:AIFloatingWindowLevel];
        [windowPositionMenu addItem:menuItem];
        [menuItem release];
        
        menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Normally",nil)
                                                                                                                                        target:target
                                                                                                                                        action:@selector(selectedWindowLevel:)
                                                                                                                         keyEquivalent:@""];
        [menuItem setEnabled:YES];
        [menuItem setTag:AINormalWindowLevel];
        [windowPositionMenu addItem:menuItem];
        [menuItem release];
        
        menuItem = [[NSMenuItem allocWithZone:[NSMenu menuZone]] initWithTitle:AILocalizedString(@"Below other windows",nil)
                                                                                                                                        target:target
                                                                                                                                        action:@selector(selectedWindowLevel:)
                                                                                                                         keyEquivalent:@""];
        [menuItem setEnabled:YES];
        [menuItem setTag:AIDesktopWindowLevel];
        [windowPositionMenu addItem:menuItem];
        [menuItem release];
        
        [windowPositionMenu setAutoenablesItems:NO];

        return [windowPositionMenu autorelease];
}

-(void)toggleUserlist:(id)sender
{
        [self.activeChat.chatContainer.chatViewController toggleUserList];
}

-(void)toggleUserlistSide:(id)sender
{
        [self.activeChat.chatContainer.chatViewController toggleUserListSide];
}

-(void)clearDisplay:(id)sender
{
        [self.activeChat.chatContainer.messageViewController.messageDisplayController clearView];
}

@end