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 / RAFBlockEditorWindowController.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
//
//  RAFBlockEditorWindow.m
//  Adium
//
//  Created by Augie Fackler on 5/26/05.
//  Copyright 2006 The Adium Team. All rights reserved.
//

#import "RAFBlockEditorWindowController.h"
#import <Adium/AIAccountControllerProtocol.h>
#import <Adium/AIContactControllerProtocol.h>
#import <AIUtilities/AICompletingTextField.h>
#import <AIUtilities/AIPopUpButtonAdditions.h>
#import <AIUtilities/AIMenuAdditions.h>
#import <Adium/AIAccount.h>
#import <Adium/AIListContact.h>
#import <Adium/AIMetaContact.h>
#import <Adium/AIListGroup.h>
#import <Adium/AIService.h>

@interface RAFBlockEditorWindowController ()
- (NSMenu *)privacyOptionsMenu;
- (AIAccount<AIAccount_Privacy> *)selectedAccount;
- (void)configureTextField;
- (NSSet *)contactsFromTextField;
- (AIPrivacyOption)selectedPrivacyOption;
@end

@implementation RAFBlockEditorWindowController

static RAFBlockEditorWindowController *sharedInstance = nil;

+ (void)showWindow
{       
        if (!sharedInstance) {
                sharedInstance = [[self alloc] initWithWindowNibName:@"BlockEditorWindow"];
        }

        [sharedInstance showWindow:nil];
        [[sharedInstance window] makeKeyAndOrderFront:nil];
}

- (void)windowDidLoad
{
        [[self window] setTitle:AILocalizedString(@"Privacy Settings", nil)];
        [cancelButton setLocalizedString:AILocalizedString(@"Cancel","Cancel button for Privacy Settings")];
        [blockButton setLocalizedString:AILocalizedString(@"Add","Add button for Privacy Settings")];
        [[buddyCol headerCell] setTitle:AILocalizedString(@"Contact","Title of column containing user IDs of blocked contacts")];
        [[accountCol headerCell] setTitle:AILocalizedString(@"Account","Title of column containing blocking accounts")];
        [accountText setLocalizedString:AILocalizedString(@"Account:",nil)];

        {
                //Let the min X margin be resizeable while label_account and label_privacyLevel localize in case the window moves
                [stateChooser setAutoresizingMask:(NSViewMinYMargin | NSViewMinXMargin)];
                [popUp_accounts setAutoresizingMask:(NSViewMinYMargin | NSViewMinXMargin)];

                //Keep label_privacyLevel in place, too, while label_account potentially resizes the window
                [label_privacyLevel setAutoresizingMask:(NSViewMinYMargin | NSViewMinXMargin)];
                [label_account setLocalizedString:AILocalizedString(@"Account:",nil)];
                [label_privacyLevel setAutoresizingMask:(NSViewMinYMargin | NSViewMaxXMargin)];
                //Account is in place; popUp_accounts can width-resize again
                [popUp_accounts setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];

                [label_privacyLevel setLocalizedString:AILocalizedString(@"Privacy level:", nil)];              
                [stateChooser setAutoresizingMask:(NSViewWidthSizable | NSViewMinYMargin)];
        }

        accountColumnsVisible = YES;
        [accountCol retain];

        listContents = [[NSMutableArray alloc] init];

        [stateChooser setMenu:[self privacyOptionsMenu]];

        [[table tableColumnWithIdentifier:@"icon"] setDataCell:[[[NSImageCell alloc] init] autorelease]];
        
        accountMenu = [[AIAccountMenu accountMenuWithDelegate:self
                                                                                          submenuType:AIAccountNoSubmenu
                                                                                   showTitleVerbs:NO] retain];
        [table registerForDraggedTypes:[NSArray arrayWithObjects:@"AIListObject", @"AIListObjectUniqueIDs",nil]];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                                   selector:@selector(privacySettingsChangedExternally:)
                                                                           name:@"AIPrivacySettingsChangedOutsideOfPrivacyWindow"
                                                                         object:nil];
        
        [[AIContactObserverManager sharedManager] registerListObjectObserver:self];

        [super windowDidLoad];
}

- (void)windowWillClose:(id)sender
{
        [super windowWillClose:sender];

        [[AIContactObserverManager sharedManager] unregisterListObjectObserver:self];

        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [sharedInstance release]; sharedInstance = nil;
}

- (NSString *)adiumFrameAutosaveName
{
        return @"PrivacyWindow";
}

- (void)dealloc
{
        [accountCol release];
        [accountMenu release];
        [listContents release];
        [listContentsAllAccounts release];
        
        [super dealloc];
}

- (NSMutableArray*)listContents
{
        return listContents;
}

- (void)setListContents:(NSArray*)newList
{
        if (newList != listContents) {
                [listContents release];
                listContents = [newList mutableCopy];
        }
}

#pragma mark Adding a contact to the list

- (void)selectAccountInSheet:(AIAccount *)inAccount
{
        [popUp_sheetAccounts selectItemWithRepresentedObject:inAccount];
        [self configureTextField];
        
        NSString        *userNameLabel = [inAccount.service userNameLabel];
        
        [accountText setAutoresizingMask:NSViewMinXMargin];
        [buddyText setLocalizedString:[(userNameLabel ?
                                                                        userNameLabel : AILocalizedString(@"Contact ID",nil)) stringByAppendingString:AILocalizedString(@":", "Colon which will be appended after a label such as 'User Name', before an input field")]];
        [accountText setAutoresizingMask:NSViewMaxXMargin];
}

- (IBAction)runBlockSheet:(id)sender
{
        [field setStringValue:@""];
        
        sheetAccountMenu = [[AIAccountMenu accountMenuWithDelegate:self
                                                                                                   submenuType:AIAccountNoSubmenu
                                                                                                showTitleVerbs:NO] retain];
        [self selectAccountInSheet:[[popUp_sheetAccounts selectedItem] representedObject]];
        
        [NSApp beginSheet:sheet 
           modalForWindow:[self window]
                modalDelegate:self 
           didEndSelector:@selector(didEndSheet:returnCode:contextInfo:)
                  contextInfo:nil];
}


- (IBAction)cancelBlockSheet:(id)sender
{
    [NSApp endSheet:sheet];
}

- (void)addObject:(AIListContact *)inContact
{
        if (inContact) {
                if (![listContents containsObject:inContact]) {
                        [listContents addObject:inContact];
                }
                
                [inContact setIsOnPrivacyList:YES updateList:YES privacyType:(([self selectedPrivacyOption] == AIPrivacyOptionAllowUsers) ?
                                                                                                                                          AIPrivacyTypePermit :
                                                                                                                                          AIPrivacyTypeDeny)];  
        }
}

- (IBAction)didBlockSheet:(id)sender
{
        NSSet *contactArray = [self contactsFromTextField];

        //Add the contact immediately
        if (contactArray && [contactArray count]) {
                AIListContact *contact;
                
                for (contact in contactArray) {
                        [self addObject:contact];
                }
                
                [table reloadData];
        }

    [NSApp endSheet:sheet];
}


- (void)didEndSheet:(NSWindow *)theSheet returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
        [sheetAccountMenu release]; sheetAccountMenu = nil;
    [theSheet orderOut:self];
}

/*!
 * @brief Get a set of all contacts which are represented by the currently selected account and UID field
 *
 * @result A set of AIListContact objects
 */
- (NSSet *)contactsFromTextField
{
        AIListContact   *contact = nil;
        NSString                *UID = nil;
        AIAccount               *account = [[popUp_sheetAccounts selectedItem] representedObject];;
        NSArray                 *accountArray;
        NSMutableSet    *contactsSet = [NSMutableSet set];
        NSEnumerator    *enumerator;
        id                              impliedValue = [field impliedValue];

        if (account) {
                accountArray = [NSArray arrayWithObject:account];
        } else {
                //All accounts
                NSMutableArray  *tempArray = [NSMutableArray array];
                NSMenuItem              *menuItem;
                
                enumerator = [[[popUp_sheetAccounts menu] itemArray] objectEnumerator];
                while ((menuItem = [enumerator nextObject])) {
                        AIAccount *anAccount;
                        
                        if ((anAccount = [menuItem representedObject])) {
                                [tempArray addObject:anAccount];
                        }
                }
                
                accountArray = tempArray;
        }

        for (account in accountArray) {
                if ([impliedValue isKindOfClass:[AIMetaContact class]]) {
                        AIListContact *containedContact;
                        NSEnumerator *contactEnumerator = [[(AIMetaContact *)impliedValue listContactsIncludingOfflineAccounts] objectEnumerator];
                        
                        while ((containedContact = [contactEnumerator nextObject])) {
                                /* For each contact contained my the metacontact, check if its service class matches the current account's.
                                 * If it does, add that contact to our list, using the contactController to get an AIListContact specific for the account.
                                 */
                                if ([containedContact.service.serviceClass isEqualToString:account.service.serviceClass]) {
                                        if ((contact = [adium.contactController contactWithService:account.service
                                                                                                                                                 account:account
                                                                                                                                                         UID:containedContact.UID])) {
                                                [contactsSet addObject:contact];
                                        }
                                }
                        }
                        
                } else {
                        if ([impliedValue isKindOfClass:[AIListContact class]]) {
                                UID = [(AIListContact *)impliedValue UID];
                        
                        } else  if ([impliedValue isKindOfClass:[NSString class]]) {
                                UID = [account.service normalizeUID:impliedValue removeIgnoredCharacters:YES];
                        }
                        
                        if (UID) {
                                //Get a contact with this UID on the current account
                                if ((contact = [adium.contactController contactWithService:account.service
                                                                                                                                         account:account 
                                                                                                                                                 UID:UID])) {
                                        [contactsSet addObject:contact];
                                }
                        }
                }
                        
        }
        
        return contactsSet;
}

- (void)configureTextField
{
        AIAccount *account = [[popUp_sheetAccounts selectedItem] representedObject];
        NSEnumerator            *enumerator;
    AIListContact               *contact;
        
        //Clear the completing strings
        [field setCompletingStrings:nil];
        
        //Configure the auto-complete view to autocomplete for contacts matching the selected account's service
    enumerator = [adium.contactController.allContacts objectEnumerator];
    while ((contact = [enumerator nextObject])) {
                if (!account ||
                        contact.service == account.service) {
                        NSString *UID = contact.UID;
                        [field addCompletionString:contact.formattedUID withImpliedCompletion:UID];
                        [field addCompletionString:contact.displayName withImpliedCompletion:UID];
                        [field addCompletionString:UID];
                }
    }
}

#pragma mark Removing a contact from the  list

- (IBAction)removeSelection:(id)sender
{
        NSIndexSet              *selectedItems = [table selectedRowIndexes];
        
        // If there's anything selected..
        if ([selectedItems count]) {
                AIListContact   *contact;
                
                // Iterate through the selected rows (backwards)
                for (NSInteger selection = [selectedItems lastIndex]; selection != NSNotFound; selection = [selectedItems indexLessThanIndex:selection]) {
                        contact = [listContents objectAtIndex:selection];
                        // Remove from the serverside list
                        [contact setIsOnPrivacyList:NO updateList:YES privacyType:(([self selectedPrivacyOption] == AIPrivacyOptionAllowUsers) ?
                                                                                                                                           AIPrivacyTypePermit :
                                                                                                                                           AIPrivacyTypeDeny)];
                        [listContents removeObject:contact];
                }
                
                [table reloadData];
                [table deselectAll:nil];
        }

}

- (void)tableViewDeleteSelectedRows:(NSTableView *)tableView
{
        [self removeSelection:tableView];
}

- (void)setAccountColumnsVisible:(BOOL)visible
{
        if (accountColumnsVisible != visible) {
                if (visible) {
                        [table addTableColumn:accountCol];
                } else {
                        [table removeTableColumn:accountCol];                   
                }

                [table sizeToFit];
                accountColumnsVisible = visible;
        }
}
#pragma mark Privacy options menu

- (NSMenu *)privacyOptionsMenu
{
        //build the menu of states
        NSMenu *stateMenu = [[NSMenu alloc] init];

        NSMenuItem *menuItem;
        
        menuItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Allow anyone", nil) 
                                                                                  action:NULL
                                                                   keyEquivalent:@""];
        [menuItem setTag:AIPrivacyOptionAllowAll];
        [stateMenu addItem:menuItem];
        [menuItem release];

        menuItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Allow only contacts on my contact list", nil) 
                                                                                  action:NULL
                                                                   keyEquivalent:@""];
        [menuItem setTag:AIPrivacyOptionAllowContactList];
        [stateMenu addItem:menuItem];
        [menuItem release];

        menuItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Allow only certain contacts", nil) 
                                                                                  action:NULL
                                                                   keyEquivalent:@""];
        [menuItem setTag:AIPrivacyOptionAllowUsers];
        [stateMenu addItem:menuItem];
        [menuItem release];

        menuItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Block certain contacts", nil) 
                                                                                  action:NULL
                                                                   keyEquivalent:@""];
        [menuItem setTag:AIPrivacyOptionDenyUsers];
        [stateMenu addItem:menuItem];
        [menuItem release];

        /*
        tmpItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"Custom settings for each account", nil) action:NULL keyEquivalent:@""];
        [tmpItem setRepresentedObject:[NSNumber numberWithInt:AIPrivacyOptionCustom]];
        [stateMenu addItem:[tmpItem autorelease]];
        */

        return [stateMenu autorelease];
}

- (AIPrivacyOption)selectedPrivacyOption
{
        return [[stateChooser selectedItem] tag];
}

/*!
 * @brief Set a privacy option and update our view for it
 *
 * @param sender If nil, we update our display without attempting to change anything on our account
 */
- (IBAction)setPrivacyOption:(id)sender
{
        AIAccount<AIAccount_Privacy> *account = [self selectedAccount];
        AIPrivacyOption privacyOption = [self selectedPrivacyOption];

        //First, let's get the right tab view selected
        switch (privacyOption) {
                case AIPrivacyOptionAllowAll:
                case AIPrivacyOptionAllowContactList:
                case AIPrivacyOptionCustom:
                        if (![[[tabView_contactList selectedTabViewItem] identifier] isEqualToString:@"empty"]) {
                                [tabView_contactList selectTabViewItemWithIdentifier:@"empty"];
                                [tabView_contactList setHidden:YES];

                                NSRect frame = [[self window] frame];
                                CGFloat tabViewHeight = [tabView_contactList frame].size.height;
                                frame.size.height -= tabViewHeight;
                                frame.origin.y += tabViewHeight;
                                
                                //Don't resize vertically now...
                                [tabView_contactList setAutoresizingMask:NSViewWidthSizable];

                                [[self window] setMinSize:NSMakeSize(250, frame.size.height)];
                                [[self window] setMaxSize:NSMakeSize(CGFLOAT_MAX, frame.size.height)];
                                
                                AILog(@"Because of privacy option %i, resizing from %@ to %@",privacyOption,
                                          NSStringFromRect([[self window] frame]),NSStringFromRect(frame));
                                [[self window] setFrame:frame display:YES animate:YES];
                        }
                        break;
                        
                case AIPrivacyOptionAllowUsers:
                case AIPrivacyOptionDenyUsers:
                        if (![[[tabView_contactList selectedTabViewItem] identifier] isEqualToString:@"list"]) {
                                [tabView_contactList selectTabViewItemWithIdentifier:@"list"];

                                NSRect frame = [[self window] frame];
                                CGFloat tabViewHeight = [tabView_contactList frame].size.height;
                                frame.size.height += tabViewHeight;
                                frame.origin.y -= tabViewHeight;
                                
                                [[self window] setMinSize:NSMakeSize(250, 320)];
                                [[self window] setMaxSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX)];
                                
                                //Set frame after fixing our min/max size so the resize won't fail
                                AILog(@"Because of privacy option %i, resizing from %@ to %@",privacyOption,
                                          NSStringFromRect([[self window] frame]),NSStringFromRect(frame));
                                [[self window] setFrame:frame display:YES animate:YES];

                                [tabView_contactList setHidden:NO];

                                //Allow resizing vertically again
                                [tabView_contactList setAutoresizingMask:(NSViewWidthSizable | NSViewHeightSizable)];
                        }
                        break;
                case AIPrivacyOptionDenyAll:
                case AIPrivacyOptionUnknown:
                        NSLog(@"We should never see these...");
                        break;
        }
        
        if (sender) {
                if (account) {
                        [account setPrivacyOptions:privacyOption];
                        
                } else {
                        NSEnumerator    *enumerator = [[[popUp_accounts menu] itemArray] objectEnumerator];
                        NSMenuItem                                              *menuItem;
                        AIAccount<AIAccount_Privacy>    *representedAccount;

                        while ((menuItem = [enumerator nextObject])) {
                                if ((representedAccount = [menuItem representedObject])) {
                                        [representedAccount setPrivacyOptions:privacyOption];
                                }
                        }
                }
        }
        
        //Now make our listContents array match the serverside arrays for the selected account(s)
        [listContents removeAllObjects];
        if ((privacyOption == AIPrivacyOptionAllowUsers) ||
                (privacyOption == AIPrivacyOptionDenyUsers)) {
                if (account) {
                        [listContents addObjectsFromArray:[account listObjectsOnPrivacyList:((privacyOption == AIPrivacyOptionAllowUsers) ?
                                                                                                                                                                 AIPrivacyTypePermit :
                                                                                                                                                                 AIPrivacyTypeDeny)]];          
                } else {
                        NSEnumerator                                    *enumerator = [[[popUp_accounts menu] itemArray] objectEnumerator];
                        NSMenuItem                                              *menuItem;
                        AIAccount<AIAccount_Privacy>    *representedAccount;

                        while ((menuItem = [enumerator nextObject])) {
                                if ((representedAccount = [menuItem representedObject])) {
                                        [listContents addObjectsFromArray:[representedAccount listObjectsOnPrivacyList:((privacyOption == AIPrivacyOptionAllowUsers) ?
                                                                                                                                                                                                        AIPrivacyTypePermit :
                                                                                                                                                                                                        AIPrivacyTypeDeny)]];           
                                }
                        }
                }
        }

        [table reloadData];
}

- (void)selectPrivacyOption:(AIPrivacyOption)privacyOption
{
        BOOL success = [stateChooser selectItemWithTag:privacyOption];
        if (privacyOption == AIPrivacyOptionCustom) {
                if (!success) {
                        NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:AILocalizedString(@"(Multiple privacy levels are active)", nil) 
                                                                                                                          action:NULL
                                                                                                           keyEquivalent:@""];
                        [menuItem setTag:AIPrivacyOptionCustom];
                        [[stateChooser menu] addItem:menuItem];
                        [menuItem release];
                        
                        success = [stateChooser selectItemWithTag:privacyOption];
                }

        } else {
                //Not on custom; make sure custom isn't still in the menu
                NSInteger customItemIndex = [stateChooser indexOfItemWithTag:AIPrivacyOptionCustom];
                if (customItemIndex != -1) {
                        [[stateChooser menu] removeItemAtIndex:customItemIndex];
                }
        }

        //Now update our view for this privacy option
        [self setPrivacyOption:nil];
}

#pragma mark Account menu
/*!
 * @brief Return the currently selected account, or nil if the 'All' item is selected
 */
- (AIAccount<AIAccount_Privacy> *)selectedAccount
{
        return [[popUp_accounts selectedItem] representedObject];
}

/*!
 * @brief Action called when the account selection changes
 *
 * Update our view and the privacy option menu to be appropriate for the newly selected account.
 * This may be called with a sender of nil by code elsewhere to force an update
 */
- (void)accountMenu:(AIAccountMenu *)inAccountMenu didSelectAccount:(AIAccount *)inAccount
{
        if (inAccountMenu == accountMenu) {
                AIAccount<AIAccount_Privacy> *account = [self selectedAccount];
                if (account) {
                        //Selected an account
                        AIPrivacyOption privacyOption = [account privacyOptions];
                        
                        //Don't need the account column when we're showing for just one account
                        [self setAccountColumnsVisible:NO];

                        [self selectPrivacyOption:privacyOption];                       

                } else {
                        //Selected 'All'. We need to determine what privacy option to display for the set of all accounts.
                        AIPrivacyOption currentState = AIPrivacyOptionUnknown;
                        NSEnumerator    *enumerator = [[[popUp_accounts menu] itemArray] objectEnumerator];
                        NSMenuItem              *menuItem;
                        
                        while ((menuItem = [enumerator nextObject])) {
                                if ((account = [menuItem representedObject])) {
                                        AIPrivacyOption accountState = [account privacyOptions];
                                        
                                        if (currentState == AIPrivacyOptionUnknown) {
                                                //We don't know the state of an account yet
                                                currentState = accountState;
                                        } else if (accountState != currentState) {
                                                currentState = AIPrivacyOptionCustom;
                                        }                               
                                }
                        }
                        
                        [self setAccountColumnsVisible:YES];

                        [self selectPrivacyOption:currentState];
                }

        } else if (inAccountMenu == sheetAccountMenu) {
                //Update our sheet for the current account
                [self selectAccountInSheet:inAccount];
        }
}

/*!
 * @brief The 'All' menu item for accounts was selected
 *
 * We simulate an AIAccountMenu delegate call, since the All item was added by RAFBLockEditorWindowController.
 */
- (IBAction)selectedAllAccountItem:(id)sender
{
        AIAccountMenu *relevantAccountMenu = (([sender menu] == [popUp_accounts menu]) ?
                                                                                  accountMenu :
                                                                                  sheetAccountMenu);

        [self accountMenu:relevantAccountMenu didSelectAccount:nil];
}

/*!
 * @brief Select an account in our account menu, then update everything else to be appropriate for it
 */
- (void)selectAccount:(AIAccount *)inAccount
{
        [popUp_accounts selectItemWithRepresentedObject:inAccount];
        
        [self accountMenu:accountMenu didSelectAccount:inAccount];
}

/*!
 * @brief Add account menu items to our location
 *
 * Implemented as required by the AccountMenuPlugin protocol.
 *
 * @param menuItemArray An <tt>NSArray</tt> of <tt>NSMenuItem</tt> objects to be added to the menu
 */
- (void)accountMenu:(AIAccountMenu *)inAccountMenu didRebuildMenuItems:(NSArray *)menuItems
{
        AIAccount        *previouslySelectedAccount = nil;
        NSMenuItem       *menuItem;
        NSMenu           *menu = [[NSMenu alloc] init];

        /*
         * accountMenu isn't set the first time we get here as the accountMenu is created. Similarly, sheetAccountMenu isn't created its first time.
         * This code makes the (true) assumption that accountMenu is _always_ created before sheetAccountMenu.
         */     
        BOOL isPrimaryAccountMenu = (!accountMenu || (inAccountMenu == accountMenu));

        if (isPrimaryAccountMenu) {
                if ([popUp_accounts menu]) {
                        previouslySelectedAccount = [[popUp_accounts selectedItem] representedObject];
                }
        } else if (inAccountMenu == sheetAccountMenu) {
                if ([popUp_sheetAccounts menu]) {
                        previouslySelectedAccount = [[popUp_sheetAccounts selectedItem] representedObject];
                }               
        }

        //Add the All menu item first if we have more than one account listed
        if ([menuItems count] > 1) {
                [menu addItemWithTitle:AILocalizedString(@"All", nll)
                                                target:self
                                                action:@selector(selectedAllAccountItem:)
                                 keyEquivalent:@""];
        }

        /*
         * As we enumerate, we:
         *      1) Determine what state the accounts within the menu are in
         *  2) Add the menu items to our menu
         */
        for (menuItem in menuItems) {           
                [menu addItem:menuItem];
        }

        if (isPrimaryAccountMenu) {
                [popUp_accounts setMenu:menu];

                /* Restore the previous account selection if there was one.
                 * Whether there was one or not, this will cause the rest of our view update to match the new/current selection
                 */
                [self selectAccount:previouslySelectedAccount];

        } else {
                [popUp_sheetAccounts setMenu:menu];
                
                [self selectAccountInSheet:previouslySelectedAccount];
        }

        [menu release];
}

- (BOOL)accountMenu:(AIAccountMenu *)inAccountMenu shouldIncludeAccount:(AIAccount *)inAccount
{
        BOOL isPrimaryAccountMenu = (!accountMenu || (inAccountMenu == accountMenu));

        if (isPrimaryAccountMenu) {
                return (inAccount.online &&
                                [inAccount conformsToProtocol:@protocol(AIAccount_Privacy)]);
        } else {
                AIAccount *selectedPrimaryAccount = self.selectedAccount;
                if (selectedPrimaryAccount) {
                        //An account is selected in the main window; only incldue that account in our sheet
                        return (inAccount == selectedPrimaryAccount);

                } else {
                        //'All' is selected in the main window; include all accounts which are online and support privacy
                        return (inAccount.online &&
                                        [inAccount conformsToProtocol:@protocol(AIAccount_Privacy)]);                   
                }
        }
}

- (void)privacySettingsChangedExternally:(NSNotification *)inNotification
{
        [self accountMenu:accountMenu didSelectAccount:[self selectedAccount]]; 
}

- (NSSet *)updateListObject:(AIListObject *)inObject keys:(NSSet *)inModifiedKeys silent:(BOOL)silent
{
        if ([inModifiedKeys containsObject:KEY_IS_BLOCKED]) {
                [self privacySettingsChangedExternally:nil];
        }
        
        return nil;
}

#pragma mark Table view

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
        return [listContents count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
        NSString                *identifier = [aTableColumn identifier];
        AIListContact   *contact = [listContents objectAtIndex:rowIndex];

        if ([identifier isEqualToString:@"icon"]) {
                return [contact menuIcon];
                
        } else if ([identifier isEqualToString:@"contact"]) {
                return contact.formattedUID;

        } else if ([identifier isEqualToString:@"account"]) {
                return contact.account.formattedUID;
        }
        
        return nil;
}

- (BOOL)writeListObjects:(NSArray *)inArray toPasteboard:(NSPasteboard*)pboard
{
        [pboard declareTypes:[NSArray arrayWithObjects:@"AIListObject",@"AIListObjectUniqueIDs",nil] owner:self];
        [pboard setString:@"Private" forType:@"AIListObject"];

        if (dragItems != inArray) {
                [dragItems release];
                dragItems = [inArray retain];
        }
        
        return YES;
}

- (BOOL)tableView:(NSTableView *)tv writeRows:(NSArray*)rows toPasteboard:(NSPasteboard*)pboard
{       
        NSMutableArray  *itemArray = [NSMutableArray array];
        NSNumber                *rowNumber;
        for (rowNumber in rows) {
                [itemArray addObject:[listContents objectAtIndex:[rowNumber integerValue]]];
        }

        return [self writeListObjects:itemArray toPasteboard:pboard];
}

- (BOOL)tableView:(NSTableView *)aTableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard
{
        NSMutableArray  *itemArray = [NSMutableArray array];
        id                              item;
        
        NSUInteger bufSize = [rowIndexes count];
        NSUInteger *buf = malloc(bufSize * sizeof(NSUInteger));
        NSUInteger i;
        
        NSRange range = NSMakeRange([rowIndexes firstIndex], ([rowIndexes lastIndex]-[rowIndexes firstIndex]) + 1);
        [rowIndexes getIndexes:buf maxCount:bufSize inIndexRange:&range];
        
        for (i = 0; i != bufSize; i++) {
                if ((item = [listContents objectAtIndex:buf[i]])) {
                        [itemArray addObject:item];
                }
        }
        
        free(buf);
        
        return [self writeListObjects:itemArray toPasteboard:pboard];
}

- (void)pasteboard:(NSPasteboard *)sender provideDataForType:(NSString *)type
{
        //Provide an array of internalObjectIDs which can be used to reference all the dragged contacts
        if ([type isEqualToString:@"AIListObjectUniqueIDs"]) {
                
                if (dragItems) {
                        NSMutableArray  *dragItemsArray = [NSMutableArray array];
                        AIListObject    *listObject;
                        
                        for (listObject in dragItems) {
                                [dragItemsArray addObject:listObject.internalObjectID];
                        }
                        
                        [sender setPropertyList:dragItemsArray forType:@"AIListObjectUniqueIDs"];
                }
        }
}

- (NSDragOperation)tableView:(NSTableView*)tv
                                validateDrop:(id <NSDraggingInfo>)info
                                 proposedRow:(NSInteger)row
           proposedDropOperation:(NSTableViewDropOperation)op
{
    
    NSDragOperation dragOp = NSDragOperationCopy;
        
    if ([info draggingSource] == table) {
                dragOp =  NSDragOperationMove;
    }
    [tv setDropRow:row dropOperation:NSTableViewDropAbove];
        
    return dragOp;
}

- (void)addListObjectToList:(AIListObject *)listObject
{
        AIListObject *containedObject;
        NSEnumerator *enumerator;

        if ([listObject isKindOfClass:[AIListGroup class]]) {
                enumerator = [[(AIListGroup *)listObject uniqueContainedObjects] objectEnumerator];
                while ((containedObject = [enumerator nextObject])) {
                        [self addListObjectToList:containedObject];
                }

        } else if ([listObject isKindOfClass:[AIMetaContact class]]) {
                enumerator = [[(AIMetaContact *)listObject uniqueContainedObjects] objectEnumerator];
                while ((containedObject = [enumerator nextObject])) {
                        [self addListObjectToList:containedObject];
                }

        } else if ([listObject isKindOfClass:[AIListContact class]]) {
                //if the account for this contact is connected...
                if ([(AIListContact *)listObject account].online) {
                        [self addObject:(AIListContact *)listObject];
                }
        }
}

- (BOOL)tableView:(NSTableView*)tv acceptDrop:(id <NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)op
{
        BOOL accept = NO;
    if (row < 0)
                row = 0;
        
        if ([info.draggingPasteboard.types containsObject:@"AIListObjectUniqueIDs"]) {
                for (NSString *uniqueUID in [info.draggingPasteboard propertyListForType:@"AIListObjectUniqueIDs"])
                        [self addListObjectToList:[adium.contactController existingListObjectWithUniqueID:uniqueUID]];
                accept = YES;
        }
        
    return accept;
}

@end