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 / AIAdium.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
/* 
 * 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.
 */

#import "AIAdium.h"
#import "AIURLHandlerPlugin.h"
#import "AIAccountController.h"
#import "AIChatController.h"
#import "AIContactController.h"
#import "AIContentController.h"
#import "AICoreComponentLoader.h"
#import "AICorePluginLoader.h"
//#import "AICrashController.h"
#import "AIDockController.h"
#import "AIEmoticonController.h"
//#import "AIExceptionController.h"
#import "AIInterfaceController.h"
#import "AILoginController.h"
#import "AIMenuController.h"
#import "AIPreferenceController.h"
#import "AISoundController.h"
#import "AIStatusController.h"
#import "AIToolbarController.h"
#import "ESApplescriptabilityController.h"
#import "ESContactAlertsController.h"
#import "ESFileTransferController.h"
#import "LNAboutBoxController.h"
#import "AIXtrasManager.h"
#import "AdiumSetupWizard.h"
#import "ESTextAndButtonsWindowController.h"
#import "AIAppearancePreferences.h"
#import <Adium/AIPathUtilities.h>
#import <AIUtilities/AIFileManagerAdditions.h>
#import <AIUtilities/AIApplicationAdditions.h>
#import <AIUtilities/AISharedWriterQueue.h>
#import <Adium/AIListContact.h>
#import <Adium/AIService.h>
#import "AIAddressBookController.h"
#import <Adium/AIContactHidingController.h>
#import <Sparkle/Sparkle.h>
#import "ESAddressBookIntegrationAdvancedPreferences.h"
#import <Adium/AdiumAuthorization.h>
#import <sys/sysctl.h>
#import "ESDebugController.h"

#define ADIUM_TRAC_PAGE                                         @"http://trac.adium.im/"
#define ADIUM_CONTRIBUTE_PAGE                           @"http://trac.adium.im/wiki/Development"
#define ADIUM_REPORT_BUG_PAGE                           @"http://trac.adium.im/wiki/ReportingBugs"
#define ADIUM_FORUM_PAGE                                        AILocalizedString(@"http://forum.adium.im/","Adium forums page. Localized only if a translated version exists.")
#define ADIUM_FEEDBACK_PAGE                                     @"mailto:feedback@adium.im"

//Portable Adium prefs key
#define PORTABLE_ADIUM_KEY                                      @"Preference Folder Location"

#define ALWAYS_RUN_SETUP_WIZARD FALSE

static NSString *prefsCategory;

@interface AIAdium ()
- (void)completeLogin;
- (void)openAppropriatePreferencesIfNeeded;
- (void)deleteTemporaryFiles;
@end

@implementation AIAdium

- (id)init
{
        if ((self = [super init])) {
                setSharedAdium(self);
        }

        return self;
}

#pragma mark Core Controllers
@synthesize accountController, chatController, contactController, contentController, dockController, emoticonController, interfaceController, loginController, menuController, preferenceController, soundController, statusController, toolbarController, contactAlertsController, fileTransferController, applescriptabilityController, debugController;

#pragma mark Loaders

@synthesize componentLoader, pluginLoader;

#pragma mark Notifications
//This is a compatibility alias to avoid breaking older plugins. It used to return a separate notification center
- (NSNotificationCenter *)notificationCenter
{
    return [NSNotificationCenter defaultCenter];
}

#pragma mark Startup and Shutdown
//Adium is almost done launching, init
- (void)applicationWillFinishLaunching:(NSNotification *)notification
{
        completedApplicationLoad = NO;
        advancedPrefsName = nil;
        prefsCategory = nil;
        queuedURLEvents = nil;
        
        //Load the crash reporter
/*
#ifdef CRASH_REPORTER
#warning Crash reporter enabled.
    [AICrashController enableCrashCatching];
    [AIExceptionController enableExceptionCatching];
#endif
 */
    //Ignore SIGPIPE, which is a harmless error signal
    //sent when write() or similar function calls fail due to a broken pipe in the network connection
    signal(SIGPIPE, SIG_IGN);
        
        [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self 
                                                                                                   andSelector:@selector(handleURLEvent:withReplyEvent:)
                                                                                                 forEventClass:kInternetEventClass
                                                                                                        andEventID:kAEGetURL];
}

- (void)handleURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
        if (!completedApplicationLoad) {
                if (!queuedURLEvents) {
                        queuedURLEvents = [[NSMutableArray alloc] init];
                }
                [queuedURLEvents addObject:[[event descriptorAtIndex:1] stringValue]];
        } else {
                [[NSNotificationCenter defaultCenter] postNotificationName:AIURLHandleNotification object:[[event descriptorAtIndex:1] stringValue]];
        }
}

//Adium has finished launching
- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
        //Begin loading and initing the components
        loginController = [[AILoginController alloc] init];
    
    //Begin Login
    [loginController requestUserNotifyingTarget:self selector:@selector(completeLogin)];
}

//Forward a re-open message to the interface controller
- (BOOL)applicationShouldHandleReopen:(NSApplication *)sender hasVisibleWindows:(BOOL)flag
{
    return [interfaceController handleReopenWithVisibleWindows:flag];
}

//Called by the login controller when a user has been selected, continue logging in
- (void)completeLogin
{
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

        /* Init the controllers.
         * Menu and interface controllers are created by MainMenu.nib when it loads.
         */
        preferenceController = [[AIPreferenceController alloc] init];
        toolbarController = [[AIToolbarController alloc] init];
        debugController = [[ESDebugController alloc] init];
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"AIEnableDebugLogging"])
                AIEnableDebugLogging();
        contactAlertsController = [[ESContactAlertsController alloc] init];
        soundController = [[AISoundController alloc] init];
        emoticonController = [[AIEmoticonController alloc] init];
        accountController = [[AIAccountController alloc] init];
        contactController = [[AIContactController alloc] init];
        [AIContactHidingController sharedController];
        [AdiumAuthorization start];
        chatController = [[AIChatController alloc] init];
        contentController = [[AIContentController alloc] init];
        dockController = [[AIDockController alloc] init];
        fileTransferController = [[ESFileTransferController alloc] init];
        applescriptabilityController = [[ESApplescriptabilityController alloc] init];
        statusController = [[AIStatusController alloc] init];

        //Finish setting up the preference controller before the components and plugins load so they can read prefs 
        [preferenceController controllerDidLoad];
        [debugController controllerDidLoad];
        [pool release];

        //Plugins and components should always init last, since they rely on everything else.
        pool = [[NSAutoreleasePool alloc] init];
        componentLoader = [[AICoreComponentLoader alloc] init];
        pluginLoader = [[AICorePluginLoader alloc] init];
        [pool release];

        //Finish initing
        pool = [[NSAutoreleasePool alloc] init];
        [menuController controllerDidLoad];                     //Loaded by nib
        [accountController controllerDidLoad];          //** Before contactController so accounts and services are available for contact creation
        
        [AIAddressBookController startAddressBookIntegration];//** Before contactController so AB contacts are available
        [ESAddressBookIntegrationAdvancedPreferences preferencePane];
        
        [contactController controllerDidLoad];          //** Before interfaceController so the contact list is available to the interface
        [interfaceController controllerDidLoad];        //Loaded by nib
        [pool release];

        pool = [[NSAutoreleasePool alloc] init];
        [toolbarController controllerDidLoad];
        [contactAlertsController controllerDidLoad];
        [soundController controllerDidLoad];
        [emoticonController controllerDidLoad];
        [chatController controllerDidLoad];
        [contentController controllerDidLoad];
        [dockController controllerDidLoad];
        [fileTransferController controllerDidLoad];
        [pool release];

        pool = [[NSAutoreleasePool alloc] init];
        [applescriptabilityController controllerDidLoad];
        [statusController controllerDidLoad];

        //Open the preferences if we were unable to because application:openFile: was called before we got here
        [self openAppropriatePreferencesIfNeeded];

        //If no accounts are setup, run the setup wizard
        if (accountController.accounts.count == 0 || ALWAYS_RUN_SETUP_WIZARD) {
                [AdiumSetupWizard runWizard];
        }

        //Process any delayed URL events 
        if (queuedURLEvents) {
                for (NSString *eventString in queuedURLEvents) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:AIURLHandleNotification object:eventString];
                }
                [queuedURLEvents release]; queuedURLEvents = nil;
        }
        
        //If we were asked to open a log at launch, do it now
        if (queuedLogPathToShow) {
                [[NSNotificationCenter defaultCenter] postNotificationName:AIShowLogAtPathNotification
                                                                                                 object:queuedLogPathToShow];
                [queuedLogPathToShow release];
        }
        
        completedApplicationLoad = YES;
        
        [[NSDistributedNotificationCenter defaultCenter] addObserver:self
                                                                                                                selector:@selector(systemTimeZoneDidChange:)
                                                                                                                        name:@"NSSystemTimeZoneDidChangeDistributedNotification"
                                                                                                                  object:nil];
        
        //Broadcast our presence
        NSConnection *connection = [[NSConnection alloc] init];
        [connection setRootObject:self];
        [connection registerName:@"com.adiumX.adiumX"];

        [[NSNotificationCenter defaultCenter] postNotificationName:AIApplicationDidFinishLoadingNotification object:nil];
        [[NSDistributedNotificationCenter defaultCenter]  postNotificationName:AIApplicationDidFinishLoadingNotification object:nil];

        [pool release];
        
        //When no events are coming in (i.e. the user is away from their computer), the runloop doesn't iterate, and we accumulate autoreleased objects
        [[NSTimer scheduledTimerWithTimeInterval:60.0f target:self selector:@selector(kickRunLoop:) userInfo:nil repeats:YES] retain];
}

- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
        if (![[preferenceController preferenceForKey:@"Confirm Quit"
                                                                                   group:@"Confirmations"] boolValue]) {
                return NSTerminateNow;
        }
                
        AIQuitConfirmationType          confirmationType = [[preferenceController preferenceForKey:@"Confirm Quit Type"
                                                                                                                                                                                        group:@"Confirmations"] integerValue];
        BOOL confirmUnreadMessages      = ![[preferenceController preferenceForKey:@"Suppress Quit Confirmation for Unread Messages"
                                                                                                                                        group:@"Confirmations"] boolValue];
        BOOL confirmFileTransfers       = ![[preferenceController preferenceForKey:@"Suppress Quit Confirmation for File Transfers"
                                                                                                                                        group:@"Confirmations"] boolValue];
        BOOL confirmOpenChats           = ![[preferenceController preferenceForKey:@"Suppress Quit Confirmation for Open Chats"
                                                                                                                                        group:@"Confirmations"] boolValue];
        
        NSString        *questionToAsk = [NSString string];
        SEL                     questionSelector = nil;

        NSApplicationTerminateReply allowQuit = NSTerminateNow;
        
        switch (confirmationType) {
                case AIQuitConfirmAlways:
                        questionSelector = @selector(confirmQuitQuestion:userInfo:suppression:);
                        
                        allowQuit = NSTerminateLater;
                        break;
                        
                case AIQuitConfirmSelective:
                        if ([chatController unviewedContentCount] > 0 && confirmUnreadMessages) {
                                questionToAsk = AILocalizedString(@"You have unread messages.",@"Quit Confirmation");
                                questionSelector = @selector(unreadQuitQuestion:userInfo:suppression:);
                                allowQuit = NSTerminateLater;
                        } else if ([fileTransferController activeTransferCount] > 0 && confirmFileTransfers) {
                                questionToAsk = AILocalizedString(@"You have file transfers in progress.",@"Quit Confirmation");
                                questionSelector = @selector(fileTransferQuitQuestion:userInfo:suppression:);
                                allowQuit = NSTerminateLater;
                        } else if ([[chatController openChats] count] > 0 && confirmOpenChats) {
                                questionToAsk = AILocalizedString(@"You have open chats.",@"Quit Confirmation");
                                questionSelector = @selector(openChatQuitQuestion:userInfo:suppression:);
                                allowQuit = NSTerminateLater;
                        }

                        break;
        }
        
        if (allowQuit == NSTerminateLater) {
                [self.interfaceController displayQuestion:AILocalizedString(@"Confirm Quit", nil)
                                                                        withDescription:[questionToAsk stringByAppendingFormat:@"%@%@",
                                                                                                                ([questionToAsk length] > 0 ? @"\n" : @""),
                                                                                                                AILocalizedString(@"Are you sure you want to quit Adium?",@"Quit Confirmation")]
                                                                        withWindowTitle:nil
                                                                          defaultButton:AILocalizedString(@"Quit", nil)
                                                                        alternateButton:AILocalizedString(@"Cancel", nil)
                                                                                otherButton:nil
                                                                                 suppression:AILocalizedString(@"Don't ask again", nil)
                                                                                         target:self
                                                                                   selector:questionSelector
                                                                                   userInfo:nil];
        }

        return allowQuit;
}

//Give all the controllers a chance to close down
- (void)applicationWillTerminate:(NSNotification *)notification
{
        //Take no action if we didn't complete the application load
        if (!completedApplicationLoad) return;

        isQuitting = YES;

        [[NSNotificationCenter defaultCenter] postNotificationName:AIAppWillTerminateNotification object:nil];

        //Close the preference window before we shut down the plugins that compose it
        [preferenceController closePreferenceWindow:nil];

        //Close the controllers in reverse order
        [pluginLoader controllerWillClose];                             //** First because plugins rely on all the controllers
        [componentLoader controllerWillClose];                          //** First because components rely on all the controllers
        [statusController controllerWillClose];                         //** Before accountController so account states are saved before being set to offline
        [chatController controllerWillClose];                           //** Before interfaceController so chats can be correctly closed
        [contactAlertsController controllerWillClose];
        [fileTransferController controllerWillClose];
        [dockController controllerWillClose];
        [interfaceController controllerWillClose];
        [contentController controllerWillClose];
        [contactController controllerWillClose];
        [AIAddressBookController stopAddressBookIntegration];
        [accountController controllerWillClose];
        [emoticonController controllerWillClose];
        [soundController controllerWillClose];
        [menuController controllerWillClose];
        [applescriptabilityController controllerWillClose];
        [debugController controllerWillClose];
        [toolbarController controllerWillClose];
        
        [AISharedWriterQueue waitUntilAllOperationsAreFinished];
        [preferenceController controllerWillClose];                     //** Last since other controllers may want to write preferences as they close
        
        [self deleteTemporaryFiles];
}

- (void)deleteTemporaryFiles
{
        [[NSFileManager defaultManager] removeFilesInDirectory:[self cachesPath]
                                                                                                withPrefix:@"TEMP"
                                                                                         movingToTrash:NO];
}

@synthesize isQuitting;

#pragma mark Menu Item Hooks

- (IBAction)showAboutBox:(id)sender
{
    [[LNAboutBoxController aboutBoxController] showWindow:nil];
}

- (IBAction)reportABug:(id)sender{
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:ADIUM_REPORT_BUG_PAGE]];
}
- (IBAction)sendFeedback:(id)sender{
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:ADIUM_FEEDBACK_PAGE]];
}
- (IBAction)showForums:(id)sender{
    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:ADIUM_FORUM_PAGE]];
}
- (IBAction)showXtras:(id)sender{
        [[AIXtrasManager sharedManager] showXtras];
}

- (IBAction)contibutingToAdium:(id)sender
{
        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:ADIUM_CONTRIBUTE_PAGE]];
}
- (IBAction)donate:(id)sender
{
        [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&submit.x=57&submit.y=8&encrypted=-----BEGIN+PKCS7-----%0D%0AMIIHFgYJKoZIhvcNAQcEoIIHBzCCBwMCAQExggEwMIIBLAIBADCBlDCBjjELMAkG%0D%0AA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQw%0D%0AEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UE%0D%0AAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20CAQAwDQYJ%0D%0AKoZIhvcNAQEBBQAEgYAFR5tF%2BRKUV3BS49vJraDG%2BIoWDoZMieUT%2FJJ1Fzjsr511%0D%0Au7hS1F2piJuHuqmm%2F0r8Kf8oaycOo74K3zLmUQ6T6hUS6%2Bh6lZAoIlhI3A1YmqIP%0D%0AdrdY%2FtfKRbWfolDumJ9Mdv%2FzJxPnpdQiTN5K1PMrPYE6GgPWE9WC4V9lqstSmTEL%0D%0AMAkGBSsOAwIaBQAwgZMGCSqGSIb3DQEHATAUBggqhkiG9w0DBwQIjtd%2BN9o4ZB6A%0D%0AcIbH8ZjOLmE35xBQ%2F93chtzIcRXHhIQJVpBRCkyJkdTD3libP3F7TgkrLij1DBxg%0D%0AfFlE0V%2FGTk29Ys%2FwsPO7hNs3YSNuSz0HT5F6sa8aXwFtMCE%2FgB1Ha4qdtYY%2BNETJ%0D%0AEETwNMLefjhaBfI%2BnRxl2K2gggOHMIIDgzCCAuygAwIBAgIBADANBgkqhkiG9w0B%0D%0AAQUFADCBjjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3Vu%0D%0AdGFpbiBWaWV3MRQwEgYDVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9j%0D%0AZXJ0czERMA8GA1UEAxQIbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBh%0D%0AbC5jb20wHhcNMDQwMjEzMTAxMzE1WhcNMzUwMjEzMTAxMzE1WjCBjjELMAkGA1UE%0D%0ABhMCVVMxCzAJBgNVBAgTAkNBMRYwFAYDVQQHEw1Nb3VudGFpbiBWaWV3MRQwEgYD%0D%0AVQQKEwtQYXlQYWwgSW5jLjETMBEGA1UECxQKbGl2ZV9jZXJ0czERMA8GA1UEAxQI%0D%0AbGl2ZV9hcGkxHDAaBgkqhkiG9w0BCQEWDXJlQHBheXBhbC5jb20wgZ8wDQYJKoZI%0D%0AhvcNAQEBBQADgY0AMIGJAoGBAMFHTt38RMxLXJyO2SmS%2BNdl72T7oKJ4u4uw%2B6aw%0D%0AntALWh03PewmIJuzbALScsTS4sZoS1fKciBGoh11gIfHzylvkdNe%2FhJl66%2FRGqrj%0D%0A5rFb08sAABNTzDTiqqNpJeBsYs%2Fc2aiGozptX2RlnBktH%2BSUNpAajW724Nv2Wvhi%0D%0Af6sFAgMBAAGjge4wgeswHQYDVR0OBBYEFJaffLvGbxe9WT9S1wob7BDWZJRrMIG7%0D%0ABgNVHSMEgbMwgbCAFJaffLvGbxe9WT9S1wob7BDWZJRroYGUpIGRMIGOMQswCQYD%0D%0AVQQGEwJVUzELMAkGA1UECBMCQ0ExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxFDAS%0D%0ABgNVBAoTC1BheVBhbCBJbmMuMRMwEQYDVQQLFApsaXZlX2NlcnRzMREwDwYDVQQD%0D%0AFAhsaXZlX2FwaTEcMBoGCSqGSIb3DQEJARYNcmVAcGF5cGFsLmNvbYIBADAMBgNV%0D%0AHRMEBTADAQH%2FMA0GCSqGSIb3DQEBBQUAA4GBAIFfOlaagFrl71%2Bjq6OKidbWFSE%2B%0D%0AQ4FqROvdgIONth%2B8kSK%2F%2FY%2F4ihuE4Ymvzn5ceE3S%2FiBSQQMjyvb%2Bs2TWbQYDwcp1%0D%0A29OPIbD9epdr4tJOUNiSojw7BHwYRiPh58S1xGlFgHFXwrEBb3dgNbMUa%2Bu4qect%0D%0AsMAXpVHnD9wIyfmHMYIBmjCCAZYCAQEwgZQwgY4xCzAJBgNVBAYTAlVTMQswCQYD%0D%0AVQQIEwJDQTEWMBQGA1UEBxMNTW91bnRhaW4gVmlldzEUMBIGA1UEChMLUGF5UGFs%0D%0AIEluYy4xEzARBgNVBAsUCmxpdmVfY2VydHMxETAPBgNVBAMUCGxpdmVfYXBpMRww%0D%0AGgYJKoZIhvcNAQkBFg1yZUBwYXlwYWwuY29tAgEAMAkGBSsOAwIaBQCgXTAYBgkq%0D%0AhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wNDAzMjUwNDQ0%0D%0AMzRaMCMGCSqGSIb3DQEJBDEWBBRzTAS6zk5cmMeC49IorY8CM%2BkX0TANBgkqhkiG%0D%0A9w0BAQEFAASBgBsyRfMv9mSyoYq00wIB7BmUHFGq5x%2Ffnr8M24XbKjhkyeULk2NC%0D%0As4jbCgaWNg6grvccJtjbvmDskMKt%2BdS%2BEAkeWwm1Zf%2F%2B5u1fMyb5vo1NNcRIs5oq%0D%0A7SvXiLTPRzVqzQdhVs7PoZG0i0RRIb0tMeo1IssZeB2GE5Nsg0D8PwpB%0D%0A-----END+PKCS7-----"]];
}

- (void)unreadQuitQuestion:(NSNumber *)number userInfo:(id)info suppression:(NSNumber *)suppressed
{
        if ([suppressed boolValue]){
                //Don't Ask Again
                [[self preferenceController] setPreference:[NSNumber numberWithBool:YES]
                                                                                        forKey:@"Suppress Quit Confirmation for Unread Messages"
                                                                                         group:@"Confirmations"];
        }
        
        AITextAndButtonsReturnCode result = [number integerValue];
        switch(result)
        {
                case AITextAndButtonsDefaultReturn:
                        //Quit
                        //Should we ask about File Transfers here?????
                        [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
                        break;
                default:
                        //Cancel
                        [NSApp replyToApplicationShouldTerminate:NSTerminateCancel];
                        break;
        }
}

- (void)openChatQuitQuestion:(NSNumber *)number userInfo:(id)info suppression:(NSNumber *)suppressed
{
        if ([suppressed boolValue]){
                //Don't Ask Again
                [[self preferenceController] setPreference:[NSNumber numberWithBool:YES]
                                                                                        forKey:@"Suppress Quit Confirmation for Open Chats"
                                                                                         group:@"Confirmations"];
        }
        
        AITextAndButtonsReturnCode result = [number integerValue];
        switch(result)
        {
                case AITextAndButtonsDefaultReturn:
                        //Quit
                        //Should we ask about File Transfers here?????
                        [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
                        break;
                default:
                        //Cancel
                        [NSApp replyToApplicationShouldTerminate:NSTerminateCancel];
                        break;
        }
}

- (void)fileTransferQuitQuestion:(NSNumber *)number userInfo:(id)info suppression:(NSNumber *)suppressed
{
        if ([suppressed boolValue]){
                //Don't Ask Again
                [[self preferenceController] setPreference:[NSNumber numberWithBool:YES]
                                                                                        forKey:@"Suppress Quit Confirmation for File Transfers"
                                                                                         group:@"Confirmations"];
        }
        
        AITextAndButtonsReturnCode result = [number integerValue];
        switch(result)
        {
                case AITextAndButtonsDefaultReturn:
                        //Quit
                        [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
                        break;
                default:
                        //Cancel
                        [NSApp replyToApplicationShouldTerminate:NSTerminateCancel];
                        break;
        }
}

- (void)confirmQuitQuestion:(NSNumber *)number userInfo:(id)info suppression:(NSNumber *)suppressed
{
        if ([suppressed boolValue]){
                //Don't Ask Again
                [[self preferenceController] setPreference:[NSNumber numberWithBool:NO]
                                                                                        forKey:@"Confirm Quit"
                                                                                         group:@"Confirmations"];
        }
        
        AITextAndButtonsReturnCode result = [number integerValue];
        switch(result)
        {
                case AITextAndButtonsDefaultReturn:
                        //Quit
                        [NSApp replyToApplicationShouldTerminate:NSTerminateNow];
                        break;
                default:
                        //Cancel
                        [NSApp replyToApplicationShouldTerminate:NSTerminateCancel];
                        break;
        }
}


//Last call to perform actions before the app shuffles off its mortal coil and joins the bleeding choir invisible
- (IBAction)confirmQuit:(id)sender
{
        /* We may have received a message or begun a file transfer while the menu was open, if this is reached via a menu item.
         * Wait one last run loop before beginning to quit so that activity can be registered, since menus run in
         * a different run loop mode, NSEventTrackingRunLoopMode.
         */
        [NSObject cancelPreviousPerformRequestsWithTarget:NSApp
                                                                                         selector:@selector(terminate:)
                                                                                           object:nil];
        [NSApp performSelector:@selector(terminate:)
                           withObject:nil
                           afterDelay:0];
}

#pragma mark Other
//If Adium was launched by double-clicking an associated file, we get this call after willFinishLaunching but before
//didFinishLaunching
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
    NSString                    *extension = [filename pathExtension];
    NSString                    *destination = nil;
        NSString                        *errorMessage = nil;
    NSString                    *fileDescription = nil, *prefsButton = nil;
        BOOL                            success = NO, requiresRestart = NO;
        NSInteger                                       buttonPressed;
        
        if (([extension caseInsensitiveCompare:@"AdiumLog"] == NSOrderedSame) ||
                ([extension caseInsensitiveCompare:@"AdiumHtmlLog"] == NSOrderedSame) ||
                ([extension caseInsensitiveCompare:@"chatlog"] == NSOrderedSame)) {
                if (completedApplicationLoad) {
                        //Request display of the log immediately if Adium is ready
                        [[NSNotificationCenter defaultCenter] postNotificationName:AIShowLogAtPathNotification
                                                                                                         object:filename];
                } else {
                        //Queue the request until Adium is done launching if Adium is not ready
                        [queuedLogPathToShow release]; queuedLogPathToShow = [filename retain];
                }
                
                //Don't continue to the xtras installation code. Return YES because we handled the open.
                return YES;
        }       
        
        /* Installation of Xtras below this point */

        [prefsCategory release]; prefsCategory = nil;
    [advancedPrefsName release]; advancedPrefsName = nil;

    /* Specify a file extension and a human-readable description of what the files of this type do
         * We reassign the extension so that regardless of its original case we end up with the case we want; this allows installation of
         * xtras to proceed properly on case-sensitive file systems.
         */
    if ([extension caseInsensitiveCompare:@"AdiumPlugin"] == NSOrderedSame) {
        destination = [AISearchPathForDirectories(AIPluginsDirectory) objectAtIndex:0];
        //Plugins haven't been loaded yet if the application isn't done loading, so only request a restart if it has finished loading already 
        requiresRestart = completedApplicationLoad;
        fileDescription = AILocalizedString(@"Adium plugin",nil);
                extension = @"AdiumPlugin";

    } else if ([extension caseInsensitiveCompare:@"AdiumLibpurplePlugin"] == NSOrderedSame) {
        destination = [AISearchPathForDirectories(AIPluginsDirectory) objectAtIndex:0];
        //Plugins haven't been loaded yet if the application isn't done loading, so only request a restart if it has finished loading already 
        requiresRestart = completedApplicationLoad;
        fileDescription = AILocalizedString(@"Adium plugin",nil);
                extension = @"AdiumLibpurplePlugin";

        } else if ([extension caseInsensitiveCompare:@"AdiumIcon"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIDockIconsDirectory) objectAtIndex:0];
        fileDescription = AILocalizedString(@"dock icon set",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"AdiumIcon";

        } else if ([extension caseInsensitiveCompare:@"AdiumSoundset"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AISoundsDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"sound set",nil);
                prefsButton = AILocalizedString(@"Open Event Prefs",nil);
                prefsCategory = @"Events";
                extension = @"AdiumSoundset";

        } else if ([extension caseInsensitiveCompare:@"AdiumEmoticonset"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIEmoticonsDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"emoticon set",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"AdiumEmoticonset";

        } else if ([extension caseInsensitiveCompare:@"AdiumScripts"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIScriptsDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"AppleScript set",nil);
                extension = @"AdiumScripts";

        } else if ([extension caseInsensitiveCompare:@"AdiumMessageStyle"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIMessageStylesDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"message style",nil);
                prefsButton = AILocalizedString(@"Open Message Prefs",nil);
                prefsCategory = @"Messages";
                extension = @"AdiumMessageStyle";

        } else if ([extension caseInsensitiveCompare:@"ListLayout"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIContactListDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"contact list layout",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"ListLayout";

        } else if ([extension caseInsensitiveCompare:@"ListTheme"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIContactListDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"contact list theme",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"ListTheme";

        } else if ([extension caseInsensitiveCompare:@"AdiumServiceIcons"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIServiceIconsDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"service icons",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"AdiumServiceIcons";

        } else if ([extension caseInsensitiveCompare:@"AdiumMenuBarIcons"] == NSOrderedSame) {
                destination = [AISearchPathForDirectories(AIMenuBarIconsDirectory) objectAtIndex:0];
                fileDescription = AILocalizedString(@"menu bar icons",nil);
                prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                prefsCategory = @"Appearance";
                extension = @"AdiumMenuBarIcons";

        } else if ([extension caseInsensitiveCompare:@"AdiumStatusIcons"] == NSOrderedSame) {
                NSString        *packName = [[filename lastPathComponent] stringByDeletingPathExtension];
/*
 //Can't do this because the preferenceController isn't ready yet
 NSString       *defaultPackName = [[self preferenceController] defaultPreferenceForKey:@"Status Icon Pack"
                                                                                                                                                          group:@"Appearance"
                                                                                                                                                         object:nil];
*/
                NSString        *defaultPackName = @"Gems";

                if (![packName isEqualToString:defaultPackName]) {
                        destination = [AISearchPathForDirectories(AIStatusIconsDirectory) objectAtIndex:0];
                        fileDescription = AILocalizedString(@"status icons",nil);
                        prefsButton = AILocalizedString(@"Open Appearance Prefs",nil);
                        prefsCategory = @"Appearance";
                        extension = @"AdiumStatusIcons";

                } else {
                        errorMessage = [NSString stringWithFormat:AILocalizedString(@"%@ is the name of the default status icon pack; this pack therefore can not be installed.",nil),
                                packName];
                }
        }

    if (destination) {
        NSString    *destinationFilePath;
                destinationFilePath = [destination stringByAppendingPathComponent:[[filename lastPathComponent] stringByDeletingPathExtension]];
                destinationFilePath = [destinationFilePath stringByAppendingPathExtension:extension];

        NSString        *alertTitle = nil;
        NSString        *alertMsg = nil;
                NSString        *format;
                
                if ([filename caseInsensitiveCompare:destinationFilePath] == NSOrderedSame) {
                        // Don't copy the file if it's already in the right place!!
                        alertTitle= AILocalizedString(@"Installation Successful","Title of installation successful window");
                        
                        format = AILocalizedString(@"Installation of the %@ %@ was successful because the file was already in the correct location.",
                                                                           "Installation introduction, like 'Installation of the message style Fiat was successful...'.");
                        
                        alertMsg = [NSString stringWithFormat:format,
                                fileDescription,
                                [[filename lastPathComponent] stringByDeletingPathExtension]];
                        
                } else {
                        //Trash the old file if one exists (since we know it isn't ourself)
                        [[NSFileManager defaultManager] trashFileAtPath:destinationFilePath];
                        
                        //Ensure the directory exists

                        [[NSFileManager defaultManager] createDirectoryAtPath:destination withIntermediateDirectories:YES attributes:nil error:NULL];
                        
                        //Perform the copy and display an alert informing the user of its success or failure
                        if ([[NSFileManager defaultManager] copyItemAtPath:filename 
                                                                                                  toPath:destinationFilePath 
                                                                                                 error:NULL]) {
                                
                                alertTitle = AILocalizedString(@"Installation Successful","Title of installation successful window");
                                alertMsg = [NSString stringWithFormat:AILocalizedString(@"Installation of the %@ %@ was successful.",
                                                                                                                                                   "Installation sentence, like 'Installation of the message style Fiat was successful.'."),
                                        fileDescription,
                                        [[filename lastPathComponent] stringByDeletingPathExtension]];
                                
                                if (requiresRestart) {
                                        alertMsg = [alertMsg stringByAppendingString:AILocalizedString(@" Please restart Adium.",nil)];
                                }
                                
                                success = YES;
                        } else {
                                alertTitle = AILocalizedString(@"Installation Failed","Title of installation failed window");
                                alertMsg = [NSString stringWithFormat:AILocalizedString(@"Installation of the %@ %@ was unsuccessful.",
                                                                                                                                                "Installation failed sentence, like 'Installation of the message style Fiat was unsuccessful.'."),
                                        fileDescription,
                                        [[filename lastPathComponent] stringByDeletingPathExtension]];
                        }
                }
                
                [[NSNotificationCenter defaultCenter] postNotificationName:AIXtrasDidChangeNotification
                                                                                                 object:[[filename lastPathComponent] pathExtension]];
                
        buttonPressed = NSRunInformationalAlertPanel(alertTitle,alertMsg,nil,prefsButton,nil);
                
                // User clicked the "open prefs" button
                if (buttonPressed == NSAlertAlternateReturn) {
                        //If we're done loading the app, open the prefs now; if not, it'll be done once the load is finished
                        //so the controllers and plugins have had a chance to initialize
                        if (completedApplicationLoad) {
                                [self openAppropriatePreferencesIfNeeded];
                        }
                } else {
                        //If the user didn't press the "open prefs" button, clear the pref opening information
                        [prefsCategory release]; prefsCategory = nil;
                        [advancedPrefsName release]; advancedPrefsName = nil;
                }
                
    } else {
                if (!errorMessage) {
                        errorMessage = AILocalizedString(@"An error occurred while installing the X(tra).",nil);
                }
                
                NSRunAlertPanel(AILocalizedString(@"Installation Failed","Title of installation failed window"),
                                                errorMessage,
                                                nil,nil,nil);
        }

    return success;
}

- (BOOL)application:(NSApplication *)theApplication openTempFile:(NSString *)filename
{
        BOOL success;
        
        success = [self application:theApplication openFile:filename];
        [[NSFileManager defaultManager] removeItemAtPath:filename error:NULL];
        
        return success;
}

- (void)openAppropriatePreferencesIfNeeded
{
        if (prefsCategory) {
                [preferenceController openPreferencesToCategoryWithIdentifier:prefsCategory];
                
                [prefsCategory release]; prefsCategory = nil;
        }
}

/*!
 * @brief Returns the location of Adium's preference folder
 * 
 * This may be specified in our bundle's info dictionary keyed as PORTABLE_ADIUM_KEY
 * or, by default, be within the system's 'application support' directory.
 */
- (NSString *)applicationSupportDirectory
{
        //Path to the preferences folder
        static NSString *_preferencesFolderPath = nil;
        
    //Determine the preferences path if neccessary
        if (!_preferencesFolderPath) {
                _preferencesFolderPath = [[[[[NSBundle mainBundle] infoDictionary] objectForKey:PORTABLE_ADIUM_KEY] stringByExpandingTildeInPath] retain];
                if (!_preferencesFolderPath)
                        _preferencesFolderPath = [[[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Application Support"] stringByAppendingPathComponent:@"Adium 2.0"] retain];
        }
        
        return _preferencesFolderPath;
}

/*!
 * @brief Create a resource folder in the Library/Application\ Support/Adium\ 2.0 folder.
 *
 * Pass it the name of the folder (e.g. @"Scripts").
 * If it is found to already in a library folder, return that pathname, using the same order of preference as
 * -[AIAdium resourcePathsForName:]. Otherwise, create it in the user library and return the pathname to it.
 */
- (NSString *)createResourcePathForName:(NSString *)name
{
    NSString            *targetPath;    //This is the subfolder for the user domain (i.e. ~/L/AS/Adium\ 2.0).
    NSFileManager       *defaultManager;
    NSArray                     *existingResourcePaths;

        defaultManager = [NSFileManager defaultManager];
        existingResourcePaths = [self resourcePathsForName:name];
        targetPath = [[self applicationSupportDirectory] stringByAppendingPathComponent:name];  
        
    /*
         If the targetPath doesn't exist, create it, as this method was called to ensure that it exists
         for creating files in the user domain.
         */
    if ([existingResourcePaths indexOfObject:targetPath] == NSNotFound) {
                
                //XXX seems like we could use the error argument to do this with less guesswork
        if (![defaultManager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:NULL]) {
                        BOOL error;

                        //If the directory could not be created, there may be a file in the way. Death to file.
                        error = ![defaultManager trashFileAtPath:targetPath];

                        if (!error) error = ![defaultManager createDirectoryAtPath:targetPath withIntermediateDirectories:YES attributes:nil error:NULL];

                        if (error) {
                                targetPath = nil;
                                
                                NSInteger result = NSRunCriticalAlertPanel([NSString stringWithFormat:AILocalizedString(@"Could not create the %@ folder.",nil), name],
                                                                                                 AILocalizedString(@"Try running Repair Permissions from Disk Utility.",nil),
                                                                                                 AILocalizedString(@"OK",nil), 
                                                                                                 AILocalizedString(@"Launch Disk Utility",nil), 
                                                                                                 nil);
                                if (result == NSAlertAlternateReturn) {
                                        [[NSWorkspace sharedWorkspace] launchApplication:@"Disk Utility"];
                                }
                        }
                }
    } else {
        targetPath = [existingResourcePaths objectAtIndex:0];
    }

    return targetPath;
}

/*!
 * @brief Return zero or more resource pathnames to an filename 
 *
 * Searches in the Application Support folders and the Resources/ folder of the Adium.app bundle.
 * Only those pathnames that exist are returned.  The Adium bundle's resource path will be the last item in the array,
 * so precedence is given to the user and system Application Support folders.
 * 
 * Pass nil to receive an array of paths to existing Adium Application Support folders (plus the Resouces folder).
 *
 * Example: If you call[adium resourcePathsForName:@"Scripts"], and there's a
 * Scripts folder in ~/Library/Application Support/Adium\ 2.0 and in /Library/Application Support/Adium\ 2.0, but not
 * in /System/Library/ApplicationSupport/Adium\ 2.0 or /Network/Library/Application Support/Adium\ 2.0.
 * The array you get back will be { @"/Users/username/Library/Application Support/Adium 2.0/Scripts",
 * @"/Library/Application Support/Adium 2.0/Scripts" }.
 *
 * @param name The full name (including extension as appropriate) of the resource for which to search
 */
- (NSArray *)resourcePathsForName:(NSString *)name
{
        NSMutableArray  *pathArray = [NSMutableArray arrayWithCapacity:4];
        NSFileManager   *defaultManager = [NSFileManager defaultManager];
        BOOL                    isDir;
                        
        NSString *adiumFolderName = [@"Application Support" stringByAppendingPathComponent:@"Adium 2.0"];
        if (name)
                adiumFolderName = [adiumFolderName stringByAppendingPathComponent:name];

        //Find Library directories in all domains except /System (as of Panther, that's ~/Library, /Library, and /Network/Library)
        NSArray *librarySearchPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSAllDomainsMask - NSSystemDomainMask, YES);

        //Copy each discovered path into the pathArray after adding our subfolder path
        for (NSString *path in librarySearchPaths) {
                NSString        *fullPath = [path stringByAppendingPathComponent:adiumFolderName];
                if ([defaultManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) {
                        [pathArray addObject:fullPath];
                }
        }
        
        /* Check our application support directory directly. It may have been covered by the NSSearchPathForDirectoriesInDomains() search,
         * or it may be distinct via the Portable Adium preference.
         */
        NSString *path = [self applicationSupportDirectory];
        if (name)
                path = [path stringByAppendingPathComponent:name];
        if (![pathArray containsObject:path] &&
                ([defaultManager fileExistsAtPath:path isDirectory:&isDir]) &&
                (isDir)) {
                //Our application support directory should always be first
                if ([pathArray count]) {
                        [pathArray insertObject:path atIndex:0];
                } else {
                        [pathArray addObject:path];                     
                }
        }

        //Add the path to the resource in Adium's bundle
        if (name) {
                path = [[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:name] stringByExpandingTildeInPath];
                if (([defaultManager fileExistsAtPath:path isDirectory:&isDir]) &&
                   (isDir)) {
                        [pathArray addObject:path];
                }
        }
    
        return pathArray;
}


/*!
 * @brief Returns an array of the paths to all of the resources for a given name, filtering out those without a certain extension
 * @param name The full name (including extension as appropriate) of the resource for which to search
 * @param extensions The extension(s) of the resources for which to search, either an NSString or an NSArray
 */
- (NSArray *)allResourcesForName:(NSString *)name withExtensions:(id)extensions
{
        NSMutableArray *resources = [NSMutableArray array];
        BOOL extensionsArray = [extensions isKindOfClass:[NSArray class]];
        
        // Get every path that can contain these resources
        
        for (NSString *resourceDir in [self resourcePathsForName:name]) {
                for (NSString *resourcePath in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resourceDir error:NULL]) {
                        // Add each resource to the array
                        if (extensionsArray) {
                                for (NSString *extension in extensions) {
                                        if ([resourcePath.pathExtension caseInsensitiveCompare:extension] == NSOrderedSame)
                                                [resources addObject:[resourceDir stringByAppendingPathComponent:resourcePath]];
                                }
                        } else {
                                if ([resourcePath.pathExtension caseInsensitiveCompare:extensions] == NSOrderedSame)
                                        [resources addObject:[resourceDir stringByAppendingPathComponent:resourcePath]];
                        }
                }
        }

        return resources;
}

/*!
 * @brief Return the path to be used for caching files for this user.
 *
 * @result A cached, tilde-expanded full path.
 */
- (NSString *)cachesPath
{
        static NSString *cachesPath = nil;

        if (!cachesPath) {
                NSString                *generalAdiumCachesPath;
                NSFileManager   *defaultManager = NSFileManager.defaultManager;

                generalAdiumCachesPath = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"Adium"];
                cachesPath = [[generalAdiumCachesPath stringByAppendingPathComponent:self.loginController.currentUser] retain];

                //Ensure our cache path exists
                if ([defaultManager createDirectoryAtPath:cachesPath withIntermediateDirectories:YES attributes:nil error:NULL]) {
                        //If we have to make directories, try to move old cache files into the new directory
                        BOOL                    isDir;

                        for (NSString *filename in [defaultManager contentsOfDirectoryAtPath:generalAdiumCachesPath error:NULL]) {
                                NSString        *fullPath = [generalAdiumCachesPath stringByAppendingPathComponent:filename];
                                
                                if (([defaultManager fileExistsAtPath:fullPath isDirectory:&isDir]) &&
                                   (!isDir)) {
                                        [defaultManager moveItemAtPath:fullPath
                                                                          toPath:[cachesPath stringByAppendingPathComponent:filename]
                                                                         error:NULL];
                                }
                        }
                }
        }
        
        return cachesPath;
}

- (NSString *)pathOfPackWithName:(NSString *)name extension:(NSString *)extension resourceFolderName:(NSString *)folderName
{
        NSFileManager   *fileManager = [NSFileManager defaultManager];
    NSString            *packFileName = [name stringByAppendingPathExtension:extension];

        //Search all our resource paths for the requested pack
    for (NSString *resourcePath in [self resourcePathsForName:folderName]) {
                NSString *packPath = [resourcePath stringByAppendingPathComponent:packFileName];
                if ([fileManager fileExistsAtPath:packPath]) return [packPath stringByExpandingTildeInPath];
        }

    return nil; 
}

- (void)systemTimeZoneDidChange:(NSNotification *)inNotification
{
        [NSTimeZone resetSystemTimeZone];
}

- (NSApplication *)application
{
        return [NSApplication sharedApplication];
}

- (void) kickRunLoop:(NSTimer *)dummy
{
        // Send a fake event to wake the loop up.
        [NSApp postEvent:[NSEvent otherEventWithType:NSApplicationDefined
                                                                                location:NSMakePoint(0,0)
                                                                   modifierFlags:0
                                                                           timestamp:0
                                                                        windowNumber:0
                                                                                 context:NULL
                                                                                 subtype:0
                                                                                   data1:0
                                                                                   data2:0]
                         atStart:NO];
}

#pragma mark Scripting
- (BOOL)application:(NSApplication *)sender delegateHandlesKey:(NSString *)key {
        BOOL handleKey = NO;
        
        if ([key isEqualToString:@"applescriptabilityController"] || 
           [key isEqualToString:@"interfaceController"] ) {
                handleKey = YES;
                
        }
        
        return handleKey;
}

#pragma mark Sparkle Delegate Methods

#define NIGHTLY_UPDATE_DICT [NSDictionary dictionaryWithObjectsAndKeys:@"type", @"key", @"nightly", @"value", nil]
#define BETA_UPDATE_DICT [NSDictionary dictionaryWithObjectsAndKeys:@"type", @"key", @"beta", @"value", nil]
#define RELEASE_UPDATE_DICT [NSDictionary dictionaryWithObjectsAndKeys:@"type", @"key", @"release", @"value", nil]

//Nightlies should update to other nightlies
#if defined(NIGHTLY_RELEASE)
#define UPDATE_TYPE_DICT NIGHTLY_UPDATE_DICT
//For a beta release, always use the beta appcast
#elif defined(BETA_RELEASE)
#define UPDATE_TYPE_DICT BETA_UPDATE_DICT
//For a release, use the beta appcast if AIAlwaysUpdateToBetas is enabled; otherwise, use the release appcast
#else
#define UPDATE_TYPE_DICT ([[NSUserDefaults standardUserDefaults] boolForKey:@"AIAlwaysUpdateToBetas"] ? BETA_UPDATE_DICT : RELEASE_UPDATE_DICT)
#endif

//The first generation ended with 1.0.5 and 1.1. Our Sparkle Plus up to that point had a bug that left it unable to properly handle the sparkle:minimumSystemVersion element.
//The second generation began with 1.0.6 and 1.1.1, with a Sparkle Plus that can handle that element.
#define UPDATE_GENERATION_DICT [NSDictionary dictionaryWithObjectsAndKeys:@"generation", @"key", @"2", @"value", nil]

/* This method gives the delegate the opportunity to customize the information that will
 * be included with update checks.  Add or remove items from the dictionary as desired.
 * Each entry in profileInfo is an NSDictionary with the following keys:
 *              key:            The key to be used  when reporting data to the server
 *              value:          Value to be used when reporting data to the server
 */
- (NSArray *)feedParametersForUpdater:(SUUpdater *)updater sendingSystemProfile:(BOOL)sendProfileInfo
{
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

        //Sparkle 1.5 has a different defaults key, do a one time migration of the value
        if ([defaults boolForKey:@"SUIncludeProfile"]) {
                [defaults setBool:YES forKey:@"SUSendProfileInfo"];
                sendProfileInfo = YES;
                [defaults setBool:NO forKey:@"SUIncludeProfile"]; //make sure this only runs once
        }

        //If we're not sending profile information, or if it hasn't been long enough since the last profile submission, return just the type of update we're looking for and the generation number.
        NSMutableArray *profileInfo = [NSMutableArray array];

        [profileInfo addObject:UPDATE_GENERATION_DICT];
        [profileInfo addObject:UPDATE_TYPE_DICT];
#ifdef NIGHTLY_RELEASE
        NSString *buildId = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"AIBuildIdentifier"];
        [profileInfo addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"revision", @"key", @"Revision", @"visibleKey", buildId, @"value", buildId, @"visibleValue", nil]];
#endif

        if (sendProfileInfo) {          
                NSString *value = ([defaults boolForKey:@"AIHasSentSparkleProfileInfo"]) ? @"no" : @"yes";

                NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"FirstSubmission", @"key", 
                        value, @"value",
                        nil];

                [profileInfo addObject:entry];

                [defaults setBool:YES forKey:@"AIHasSentSparkleProfileInfo"];

                /*************** Include info about what IM services are used ************/
                NSMutableString *accountInfo = [NSMutableString string];
                NSCountedSet *condensedAccountInfo = [NSCountedSet set];
                for (AIAccount *account in adium.accountController.accounts) {
                        NSString *serviceID = account.service.serviceID;
                        [accountInfo appendFormat:@"%@, ", serviceID];
                        if([serviceID isEqualToString:@"Yahoo! Japan"]) 
                                serviceID = @"YJ";
                        [condensedAccountInfo addObject:[NSString stringWithFormat:@"%@", [serviceID substringToIndex:2]]]; 
                }

                NSMutableString *accountInfoString = [NSMutableString string];
                for (value in [[condensedAccountInfo allObjects] sortedArrayUsingSelector:@selector(compare:)])
                        [accountInfoString appendFormat:@"%@%lu", value, [condensedAccountInfo countForObject:value]];

                entry = [NSDictionary dictionaryWithObjectsAndKeys:
                        @"IMServices", @"key", 
                        accountInfoString, @"value",
                        nil];
                [profileInfo addObject:entry];
                
                /** Temporary: get a combined type/bitness value, like PPC64 **/
                // CPU type (decoder info for values found here is in mach/machine.h)
                int sysctlvalue = 0;
                unsigned long length = sizeof(sysctlvalue);
                int error = sysctlbyname("hw.cputype", &sysctlvalue, &length, NULL, 0);
                int cpuType = -1;
                if (error == 0) {
                        cpuType = sysctlvalue;
                }
                BOOL is64bit = NO;
                error = sysctlbyname("hw.cpu64bit_capable", &sysctlvalue, &length, NULL, 0);
                if(error != 0)
                        error = sysctlbyname("hw.optional.x86_64", &sysctlvalue, &length, NULL, 0); //x86 specific
                if(error != 0)
                        error = sysctlbyname("hw.optional.64bitops", &sysctlvalue, &length, NULL, 0); //PPC specific
                
                if (error == 0) {
                        is64bit = sysctlvalue == 1;
                        NSString *visibleCPUType;
                        switch(cpuType) {
                                case 7:         visibleCPUType=@"Intel";        break;
                                case 18:        visibleCPUType=@"PowerPC";      break;
                                default:        visibleCPUType=@"Unknown";      break;
                        }
                        visibleCPUType = [visibleCPUType stringByAppendingFormat:@"%@", is64bit ? @"64" : @"32"];
                        [profileInfo addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"detailedcputype",@"Detailed CPU Type", visibleCPUType, visibleCPUType,nil] forKeys:[NSArray arrayWithObjects:@"key", @"displayKey", @"value", @"displayValue", nil]]];
                }
                
        }


        return profileInfo;
}

- (NSArray *)updaterInfoWithoutProfile
{
    return [NSArray arrayWithObjects:UPDATE_GENERATION_DICT, UPDATE_TYPE_DICT, nil];
}

- (id <SUVersionComparison>)versionComparatorForUpdater:(SUUpdater *)updater
{
    return self;
}

#pragma mark Version Comparison (Copied from SUStandardVersionComparator)

typedef enum {
    kNumberType,
    kStringType,
    kPeriodType
} SUCharacterType;

- (SUCharacterType)typeOfCharacter:(NSString *)character
{
    if ([character isEqualToString:@"."]) {
        return kPeriodType;
    } else if ([[NSCharacterSet decimalDigitCharacterSet] characterIsMember:[character characterAtIndex:0]]) {
        return kNumberType;
    } else {
        return kStringType;
    }   
}

- (NSArray *)splitVersionString:(NSString *)version
{
    NSString *character;
    NSMutableString *s;
    NSInteger i, n, oldType, newType;
    NSMutableArray *parts = [NSMutableArray array];
    if ([version length] == 0) {
        // Nothing to do here
        return parts;
    }
    s = [[[version substringToIndex:1] mutableCopy] autorelease];
    oldType = [self typeOfCharacter:s];
    n = [version length] - 1;
    for (i = 1; i <= n; ++i) {
        character = [version substringWithRange:NSMakeRange(i, 1)];
        newType = [self typeOfCharacter:character];
        if (oldType != newType || oldType == kPeriodType) {
            // We've reached a new segment
            NSString *aPart = [[NSString alloc] initWithString:s];
            [parts addObject:aPart];
            [aPart release];
            [s setString:character];
        } else {
            // Add character to string and continue
            [s appendString:character];
        }
        oldType = newType;
    }
    
    // Add the last part onto the array
    [parts addObject:[NSString stringWithString:s]];
    return parts;
}

- (NSComparisonResult)compareVersion:(NSString *)appVersion toVersion:(NSString *)appcastVersion;
{
        /*********** Adium Changes **********/
        NSRange debugRange = [appVersion rangeOfString:@"-debug"];
        if (debugRange.location != NSNotFound)
                appVersion = [appVersion substringToIndex:debugRange.location];
        
        NSRange hgOurs = [appVersion rangeOfString:@"hg"];
        NSRange hgTheirs = [appcastVersion rangeOfString:@"hg"];
        NSRange svnOurs = [appVersion rangeOfString:@"svn"];
        NSRange svnTheirs = [appcastVersion rangeOfString:@"svn"];
        
        if (hgOurs.location != NSNotFound && svnTheirs.location != NSNotFound)
                return NSOrderedDescending;
        if (hgTheirs.location != NSNotFound && svnOurs.location != NSNotFound)
                return NSOrderedAscending;
                
        /*********** End Adium Changes *******/
    
    NSArray *partsA = [self splitVersionString:appVersion];
    NSArray *partsB = [self splitVersionString:appcastVersion];
    
    NSString *partA, *partB;
    NSInteger i, n, typeA, typeB, intA, intB;
    
    n = MIN([partsA count], [partsB count]);
    for (i = 0; i < n; ++i) {
        partA = [partsA objectAtIndex:i];
        partB = [partsB objectAtIndex:i];
        
        typeA = [self typeOfCharacter:partA];
        typeB = [self typeOfCharacter:partB];
        
        // Compare types
        if (typeA == typeB) {
            // Same type; we can compare
            if (typeA == kNumberType) {
                intA = [partA intValue];
                intB = [partB intValue];
                if (intA > intB) {
                    return NSOrderedDescending;
                } else if (intA < intB) {
                    return NSOrderedAscending;
                }
            } else if (typeA == kStringType) {
                NSComparisonResult result = [partA compare:partB];
                if (result != NSOrderedSame) {
                    return result;
                }
            }
        } else {
            // Not the same type? Now we have to do some validity checking
            if (typeA != kStringType && typeB == kStringType) {
                // typeA wins
                return NSOrderedDescending;
            } else if (typeA == kStringType && typeB != kStringType) {
                // typeB wins
                return NSOrderedAscending;
            } else {
                // One is a number and the other is a period. The period is invalid
                if (typeA == kNumberType) {
                    return NSOrderedDescending;
                } else {
                    return NSOrderedAscending;
                }
            }
        }
    }
    // The versions are equal up to the point where they both still have parts
    // Lets check to see if one is larger than the other
    if ([partsA count] != [partsB count]) {
        // Yep. Lets get the next part of the larger
        // n holds the index of the part we want.
        NSString *missingPart;
        SUCharacterType missingType;
        NSComparisonResult shorterResult, largerResult;
        
        if ([partsA count] > [partsB count]) {
            missingPart = [partsA objectAtIndex:n];
            shorterResult = NSOrderedAscending;
            largerResult = NSOrderedDescending;
        } else {
            missingPart = [partsB objectAtIndex:n];
            shorterResult = NSOrderedDescending;
            largerResult = NSOrderedAscending;
        }
        
        missingType = [self typeOfCharacter:missingPart];
        // Check the type
        if (missingType == kStringType) {
            // It's a string. Shorter version wins
            return shorterResult;
        } else {
            // It's a number/period. Larger version wins
            return largerResult;
        }
    }
    
    // The 2 strings are identical
    return NSOrderedSame;
}

@end

@implementation NSObject (AdiumAccess)
- (NSObject<AIAdium> *)adium
{
        return adium;
}
@end