6e4e4ffaf72371d4254e2ec697b771fe7f877358
[openafs.git] / src / platform / DARWIN / AFSPreference / AFSCommanderPref.m
1 //
2 //  AFSCommanderPref.m
3 //  AFSCommander
4 //
5 //  Created by Claudio Bisegni on 10/05/07.
6 //  Copyright (c) 2007 INFN - National Institute of Nuclear Physics. All rights reserved.
7 //
8
9 #import "AFSCommanderPref.h"
10 #import "IpConfiguratorCommander.h"
11 #import "TokenCredentialController.h"
12 #import "InfoController.h"
13 #import "TaskUtil.h"
14 #import "PListManager.h"
15 #import "DialogUtility.h"
16 #import "NSString+search.h"
17 #include <sys/param.h>
18 #include <sys/stat.h>
19 #include <sys/wait.h>
20 #include <sys/types.h>
21 #include <sys/fcntl.h>
22 #include <sys/errno.h>
23 #include <unistd.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #import <CoreServices/CoreServices.h>
27
28
29 #define ADD_CELL_CONTROL_TAG 1
30 #define REMOVE_CELL_CONTROL_TAG 2
31
32 #define TABLE_TOKENS_LIST 1
33 #define TABLE_CELL_LIST 2
34 #define TABLE_LINK_LIST 3
35
36 #define TAB_TOKENS 1
37 #define TAB_CELL_SERV_DB 2
38 #define TAB_CACHE 3
39 #define TAB_LINK 4
40
41 //CellServDB table id
42 #define CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN   0
43 #define CELLSRVDB_TABLE_DFLT_CHECK_COLUMN               1
44 #define CELLSRVDB_TABLE_NAME_COLUMN                             2
45 #define CELLSRVDB_TABLE_DESCRIPTION_COLUMN              3
46
47 //Link Table
48 #define TABLE_COLUMN_LINK_NAME  0
49 #define TABLE_COLUMN_LINK_PATH  1
50
51
52 @implementation AFSCommanderPref
53
54 // -------------------------------------------------------------------------------
55 //  initWithBundle:
56 // -------------------------------------------------------------------------------
57 - (id)initWithBundle:(NSBundle *)bundle
58 {
59     if ( ( self = [super initWithBundle:bundle] ) != nil ) {
60         //appID = kAfsCommanderID;
61                 prefStartUp = 1;
62     }
63     return self;
64 }
65
66 // -------------------------------------------------------------------------------
67 //  mainView:
68 // -------------------------------------------------------------------------------
69 - (NSView *) mainView {
70         if (prefStartUp == 1){
71                 SInt32 osxMJVers = 0;
72                 SInt32 osxMnVers = 0;
73                 if (Gestalt(gestaltSystemVersionMajor, &osxMJVers) == noErr && Gestalt(gestaltSystemVersionMinor, &osxMnVers) == noErr) {
74                         if (osxMJVers == 10 && osxMnVers>= 5) {
75                                 [afsCommanderView  setFrameSize:NSMakeSize(668, [afsCommanderView frame].size.height)];
76                 prefStartUp = 0;
77                         }
78                 }
79         }
80         
81     return afsCommanderView;
82 }
83
84 // -------------------------------------------------------------------------------
85 //  mainViewDidLoad:
86 // -------------------------------------------------------------------------------
87 - (void) mainViewDidLoad
88 {
89         //CellServDB Table
90         [((NSTableView*)cellList) setDelegate:self];
91         [((NSTableView*)cellList) setTarget:self];
92         [((NSTableView*)cellList) setDoubleAction:@selector(tableDoubleAction:)];
93         
94         
95 }
96
97 // -------------------------------------------------------------------------------
98 //  didSelect:
99 // -------------------------------------------------------------------------------
100 - (void) didSelect
101 {
102         //try to install the launchd file for backgrounder
103         //Remove launchd ctrl file
104         @try {
105                 [PListManager installBackgrounderLaunchdFile:YES 
106                                                                                 resourcePath:[[self bundle] resourcePath]];
107         }
108         @catch (NSException * e) {
109                 NSDictionary *excecptDic = [e userInfo];
110                 NSNumber *keyNum = [excecptDic objectForKey:@"agent_folder_error"];
111                 if(keyNum && [keyNum boolValue]) {
112                         // the dir HOME_LAUNCHD_AGENT_FOLDER (PListManager.h) must be created
113                         NSBeginAlertSheet([[NSString stringWithString:kDoYouWantCreateTheDirectory] stringByAppendingString:HOME_LAUNCHD_AGENT_FOLDER],
114                                                           @"Create", @"Cancel", nil,                                                                            
115                                                           [[self mainView] window],     self, @selector(credentialAtLoginTimeEventCreationLaunchAgentDir:returnCode:contextInfo:), NULL, 
116                                                           nil, @"", nil);
117                 }
118         }
119         @finally {
120                 
121         }
122         
123         
124         // Set Developer info
125         [textFieldDevInfoLabel setStringValue:kDevelopInfo];
126         // creating the lock
127         tokensLock = [[NSLock alloc] init];
128         
129         //Initialization cellservdb and token list
130         filteredCellDB = nil;
131         tokenList = nil;
132         
133         [self readPreferenceFile];
134                         
135         // alloc the afs property mananger
136         afsProperty = [[AFSPropertyManager alloc] init];
137         
138         // register preference pane to detect menuextra killed by user
139         [[NSDistributedNotificationCenter defaultCenter] addObserver:self
140                                                                                                                 selector:@selector(refreshTokensNotify:)
141                                                                                                                         name:kAfsCommanderID
142                                                                                                                   object:kMExtraTokenOperation];
143          
144         [[NSDistributedNotificationCenter defaultCenter] addObserver:self 
145                                                                                                                 selector:@selector(refreshGui:) 
146                                                                                                                         name:kAfsCommanderID 
147                                                                                                                   object:kMenuExtraEventOccured];
148         
149         //Register for mount/unmount afs volume
150         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
151                                                                                                                    selector:@selector(afsVolumeMountChange:) 
152                                                                                                                            name:NSWorkspaceDidMountNotification object:nil];
153         
154         [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
155                                                                                                                    selector:@selector(afsVolumeMountChange:) 
156                                                                                                                            name:NSWorkspaceDidUnmountNotification object:nil];
157         
158         // set self as table data source
159         [cellList setDataSource:self];
160         [tokensTable setDataSource:self];
161         //[tableViewLink setDataSource:self];
162         //check the afs state
163         [self setAfsStatus];
164         
165         // let show the configuration after prefpane is open
166         [self refreshConfiguration:nil];
167         
168         // refresh the token list
169         //[self refreshTokens:nil];
170         
171         //refresh table to reflect the NSSearchField contained text
172         [self searchCellTextEvent:nil];
173 }
174
175 // -------------------------------------------------------------------------------
176 //  credentialAtLoginTimeEventCreationLaunchAgentDir:
177 // -------------------------------------------------------------------------------
178 - (void) credentialAtLoginTimeEventCreationLaunchAgentDir:(NSWindow*)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo {
179         [alert close];
180         switch (returnCode) {
181                 case  1:
182                         if([[NSFileManager defaultManager] createDirectoryAtPath:[HOME_LAUNCHD_AGENT_FOLDER stringByExpandingTildeInPath] 
183                                                                                  withIntermediateDirectories:NO
184                                                                                                                   attributes:nil
185                                                                                                                            error:nil]) {
186                                 
187                                 //Create the file
188                                 [PListManager installBackgrounderLaunchdFile:YES
189                                                                                                 resourcePath:[[self bundle] resourcePath]];
190                                 [self showMessage:kDirectoryCreated];
191                         } else {
192                                 [self showMessage:kErrorCreatingDirectory];
193                         }
194                         break;
195                 case 0:
196                         break;
197         }
198 }
199
200
201 // -------------------------------------------------------------------------------
202 //  willUnselect:
203 // -------------------------------------------------------------------------------
204 - (void)willUnselect
205 {
206         // remove self as datasource
207         [((NSTableView*)cellList) setDataSource:nil];
208         [((NSTableView*)tokensTable) setDataSource:nil];
209
210         //release the afs property manager
211         if(afsProperty) [afsProperty release];
212         //release tokens list
213         if(tokenList) [tokenList release];      
214         //Remove the cell temp array
215         if(filteredCellDB) [filteredCellDB release];
216         
217         [self writePreferenceFile];
218         
219         // unregister preference pane to detect menuextra killed by user
220         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
221                                                                                                                            name:kAfsCommanderID
222                                                                                                                          object:kMExtraClosedNotification];
223         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
224                                                                                                                            name:kAfsCommanderID
225                                                                                                                          object:kMExtraTokenOperation];
226         [[NSDistributedNotificationCenter defaultCenter] removeObserver:self
227                                                                                                                            name:kAfsCommanderID
228                                                                                                                          object:kMenuExtraEventOccured];
229         [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self 
230                                                                                                                                   name:NSWorkspaceDidMountNotification object:nil];
231         [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self 
232                                                                                                                                   name:NSWorkspaceDidUnmountNotification object:nil];
233         
234         [self stopTimer];
235         [tokensLock release];
236 }
237
238
239 // -------------------------------------------------------------------------------
240 //  startTimer:
241 // -------------------------------------------------------------------------------
242 - (void)startTimer{
243         //start the time for check tokens validity
244         if(timerForCheckTokensList) return;
245         timerForCheckTokensList = [NSTimer scheduledTimerWithTimeInterval:TOKENS_REFRESH_TIME_IN_SEC 
246                                                                                                                            target:self 
247                                                                                                                          selector:@selector(refreshTokens:) 
248                                                                                                                          userInfo:nil 
249                                                                                                                           repeats:YES];
250         [timerForCheckTokensList fire]; 
251 }
252
253 // -------------------------------------------------------------------------------
254 //  stopTimer:
255 // -------------------------------------------------------------------------------
256 - (void)stopTimer{
257         if(!timerForCheckTokensList) return;
258         [timerForCheckTokensList invalidate];   
259         timerForCheckTokensList = nil;
260 }
261
262
263 // -------------------------------------------------------------------------------
264 //  readPreferenceFile:
265 // -------------------------------------------------------------------------------
266 - (void) readPreferenceFile
267 {
268         // read the preference for aklog use
269         NSNumber *useAklogPrefValue = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_USE_AKLOG, (CFStringRef)kAfsCommanderID,  
270                                                                                                                                         kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
271         NSNumber *aklogTokenAtLogin = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_AKLOG_TOKEN_AT_LOGIN, (CFStringRef)kAfsCommanderID,  
272                                                                                                                                         kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
273         [useAklogCheck setState:[useAklogPrefValue intValue]];
274         [aklogCredentialAtLoginTime setEnabled:useAklogPrefValue && [useAklogPrefValue boolValue]];
275         [aklogCredentialAtLoginTime setState:aklogTokenAtLogin && [aklogTokenAtLogin boolValue]];
276
277         //check krb5 at login time
278         [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
279
280         //check for AFS enable at startup
281         NSNumber *afsEnableStartupTime = (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP,
282                                                                                                                                            (CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
283         if(afsEnableStartupTime)
284                 startAFSAtLogin = [afsEnableStartupTime boolValue];
285         else 
286                 startAFSAtLogin = false;
287         //set the check button state
288         [checkButtonAfsAtBootTime setState:startAFSAtLogin];
289         
290         NSNumber *showStatusMenu =  (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
291         [(NSButton*)afsMenucheckBox setState: [showStatusMenu boolValue]];
292         
293         //backgrounder state
294         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
295         
296         //link enabled status
297         NSNumber *linkEnabledStatus =  (NSNumber*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_USE_LINK,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
298         [checkEnableLink setState:[linkEnabledStatus boolValue]];
299         
300         //link configuration
301         NSData *prefData = (NSData*)CFPreferencesCopyValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,  (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
302         linkConfiguration = (NSMutableDictionary*)[NSPropertyListSerialization propertyListFromData:prefData
303                                                                                                                                                            mutabilityOption:NSPropertyListMutableContainers
304                                                                                                                                                                                  format:nil
305                                                                                                                                                            errorDescription:nil];
306         
307 }
308
309 // -------------------------------------------------------------------------------
310 //  willUnselect:
311 // -------------------------------------------------------------------------------
312 - (void) writePreferenceFile
313 {
314         //Set the preference for afs path
315         /*CFPreferencesSetValue((CFStringRef)PREFERENCE_AFS_SYS_PAT, 
316                                                   (CFStringRef)[((NSTextField*) installationPathTextField ) stringValue], 
317                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);*/
318         
319         //Set the preference for aklog use
320         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_AKLOG, 
321                                                   (CFNumberRef)[NSNumber numberWithInt:[useAklogCheck state]], 
322                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
323
324         //set AFS enable state at startup
325         CFPreferencesSetValue((CFStringRef)PREFERENCE_START_AFS_AT_STARTUP, 
326                                                   (CFNumberRef)[NSNumber numberWithBool:startAFSAtLogin], 
327                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesAnyUser, kCFPreferencesAnyHost);
328         
329         //set aklog at login
330         CFPreferencesSetValue((CFStringRef)PREFERENCE_AKLOG_TOKEN_AT_LOGIN, 
331                                                   (CFNumberRef)[NSNumber numberWithBool:[aklogCredentialAtLoginTime state]], 
332                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
333         
334         //set aklog at login
335         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
336                                                   (CFNumberRef)[NSNumber numberWithBool:[afsMenucheckBox state]], 
337                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
338         
339         //write preference for link
340         CFPreferencesSetValue((CFStringRef)PREFERENCE_USE_LINK,
341                                                   (CFNumberRef)[NSNumber numberWithBool:[checkEnableLink state]], 
342                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
343         
344         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
345         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
346         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kPrefChangeNotification];
347 }
348
349 // -------------------------------------------------------------------------------
350 //  saveConfiguration:
351 // -------------------------------------------------------------------------------
352 - (IBAction) saveConfiguration:(id) sender
353 {
354         @try{
355                 
356                 //[afsProperty setCellName:[cellNameTextEdit stringValue]];
357                 [afsProperty setCellName:[afsProperty getDefaultCellName]];
358                 
359                 //save configurations
360                 [afsProperty saveConfigurationFiles:YES];
361                 
362                 
363                 //Reload all configuration
364                 [self refreshConfiguration:nil];
365                 
366                 //refresh table to reflect the NSSearchField contained text
367                 [self searchCellTextEvent:nil];
368                 
369                 //Show dialog for notifity al saving process ar gone ell
370                 [self showMessage:kConfigurationSaved];
371         }@catch(NSException *e){
372                 [self showMessage:[e reason]];
373         } @finally {
374                 [((NSTableView*)cellList) reloadData];
375         }
376         
377 }
378
379 // -------------------------------------------------------------------------------
380 //  saveCacheManagerParam:
381 // -------------------------------------------------------------------------------
382 - (IBAction) saveCacheManagerParam:(id) sender
383 {
384         @try{
385                 //Update the value form view to afs property manager class
386                 [self updateCacheParamFromView];
387                 [afsProperty saveCacheConfigurationFiles:YES];
388                 [self showMessage:kSavedCacheConfiguration];
389         }@catch(NSException *e){
390                 [self showMessage:[e reason]];
391         } @finally {
392                 [((NSTableView*)cellList) reloadData];
393         }
394 }
395
396 // -------------------------------------------------------------------------------
397 //  refreshConfiguration:
398 // -------------------------------------------------------------------------------
399 - (IBAction) refreshConfiguration:(id) sender
400 {
401         NSString *afsBasePath = PREFERENCE_AFS_SYS_PAT_STATIC;
402         @try{
403                 // set the afs path
404                 [afsProperty setPath:afsBasePath];
405                 
406                 // load configuration
407                 [afsProperty loadConfiguration];
408                 
409                 //set the afs version label
410                 [afsVersionLabel setStringValue:[afsProperty getAfsVersion]];
411                 
412                 //set the current default cell
413                 [afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
414                 
415                 // Update cache view
416                 [self fillCacheParamView];
417                 
418                 //Filter the cellServDb and allocate filtered array
419                 [self filterCellServDB:nil];
420                 
421         }@catch(NSException *e){
422                 [self showMessage:[e reason]];
423         } @finally {
424                 [((NSTableView*)cellList) reloadData];
425         }
426 }
427
428 // -------------------------------------------------------------------------------
429 //  fillCacheParamView:
430 // -------------------------------------------------------------------------------
431 -(void) fillCacheParamView
432 {
433         [dynRoot setState:[afsProperty dynRoot]?NSOnState:NSOffState];
434         [afsDB setState:[afsProperty afsDB]?NSOnState:NSOffState];
435         [statCacheEntry setIntValue:[afsProperty statCacheEntry]];
436         [dCacheDim setIntValue:[afsProperty dCacheDim]];
437         [cacheDimension setIntValue:[afsProperty cacheDimension]];
438         [daemonNumber setIntValue:[afsProperty daemonNumber]];
439         [afsRootMountPoint setStringValue:[afsProperty afsRootMountPoint]];
440         [nVolEntry setIntValue:[afsProperty nVolEntry]];
441         
442         //new version property
443         //[verbose setEnabled:[afsProperty useAfsdConfConfigFile]];
444         [verbose setState:[afsProperty verbose]?NSOnState:NSOffState];
445         
446 }
447
448 // -------------------------------------------------------------------------------
449 //  updateCacheParamFromView:
450 // -------------------------------------------------------------------------------
451 -(void) updateCacheParamFromView
452 {
453         NSString *tmpAfsPath = [afsRootMountPoint stringValue];
454         if(!tmpAfsPath || ([tmpAfsPath length] == 0) || ([tmpAfsPath characterAtIndex:0] != '/')) 
455                 @throw [NSException exceptionWithName:@"updateCacheParamFromView" 
456                                                                            reason:kBadAfsRootMountPoint
457                                                                          userInfo:nil];
458
459         
460         [afsProperty setDynRoot:[dynRoot state]==NSOnState];
461         [afsProperty setAfsDB:[afsDB state]==NSOnState];
462         [afsProperty setStatCacheEntry:[statCacheEntry intValue]];
463         [afsProperty setDCacheDim:[dCacheDim intValue]]; 
464         [afsProperty setCacheDimension:[cacheDimension intValue]]; 
465         [afsProperty setDaemonNumber:[daemonNumber intValue]];
466         [afsProperty setAfsRootMountPoint:tmpAfsPath];
467         [afsProperty setNVolEntry:[nVolEntry intValue]];
468         [afsProperty setVerbose:[verbose state]==NSOnState];
469 }
470
471
472 // -------------------------------------------------------------------------------
473 //  showCellIP:
474 // -------------------------------------------------------------------------------
475 - (IBAction) showCellIP:(id) sender
476 {
477         int rowSelected = [((NSTableView *) cellList) selectedRow];
478         [self modifyCellByIDX:rowSelected];
479 }
480
481 // -------------------------------------------------------------------------------
482 //  modifyCellByIDX:
483 // -------------------------------------------------------------------------------
484 -(void) modifyCellByIDX:(int) idx
485 {
486         [self modifyCell:[self getCellByIDX:idx]];
487 }
488
489 // -------------------------------------------------------------------------------
490 //  modifyCellByIDX:
491 // -------------------------------------------------------------------------------
492 -(void) modifyCell:(DBCellElement*) cellElement
493 {
494         [NSBundle loadNibNamed:@"IpPanel" owner:self];
495         [((IpConfiguratorCommander*) ipConfControllerCommander) setWorkCell:cellElement];
496         [NSApp beginSheet: ipConfigurationSheet
497            modalForWindow: [[self mainView] window]
498                 modalDelegate: self
499            didEndSelector: @selector(didEndSheet:returnCode:contextInfo:)
500                   contextInfo: nil];
501 }
502
503 // -------------------------------------------------------------------------------
504 //  addMoifyCell:
505 // -------------------------------------------------------------------------------
506 - (IBAction) addRemoveCell:(id) sender
507 {
508         switch([((NSControl*) sender) tag]){
509                 case ADD_CELL_CONTROL_TAG:
510                 {
511                         DBCellElement *newCell = [[DBCellElement alloc] init];
512                         if(!newCell) break;
513                         
514                         [newCell setCellName:kNewCellName];
515                         [newCell setCellComment:kNewCellComment];
516                         //cellArray = ;
517                         [[afsProperty getCellList] addObject:newCell];
518                         [newCell release];
519                         
520                         //Modify new cell
521                         [self modifyCell:newCell];
522                 }
523                 break;
524                         
525                 case REMOVE_CELL_CONTROL_TAG:
526                 {
527                         int index = 0;
528                         NSIndexSet *selectedIndex = [(NSTableView*)cellList selectedRowIndexes];
529                         if( [selectedIndex count] > 0) {
530                                 index = [selectedIndex firstIndex]; 
531                                 do {
532                                         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:index];
533                                         [[afsProperty getCellList] removeObject:cellElement];
534                                 } while ((index = [selectedIndex indexGreaterThanIndex:index]) != NSNotFound);
535                         }
536                 }
537                 break;
538         }
539         //Filter the cellServDb and allocate filtered array
540         [self searchCellTextEvent:nil];
541         [(NSTableView*)cellList deselectAll:nil];
542         [(NSTableView*)cellList reloadData];
543 }
544
545 // -------------------------------------------------------------------------------
546 //  repairHelperTool:
547 // -------------------------------------------------------------------------------
548 - (void) repairHelperTool
549 {
550         struct stat st;
551     int fdTool;
552         int status = 0;
553         NSLog(@"repairHelperTool"); 
554         NSString *afshlpPath = [[self bundle] pathForResource:@"afshlp" ofType:nil];
555         
556         
557     
558     // Open tool exclusively, so nobody can change it while we bless it.
559     fdTool = open([afshlpPath UTF8String], O_NONBLOCK | O_RDONLY | O_EXLOCK, 0);
560     
561     if(fdTool == -1)
562     {
563         NSLog(@"Exclusive open while repairing tool failed: %d.", errno);
564         exit(-1);
565     }
566     
567     if(fstat(fdTool, &st))
568     {
569         NSLog(@"fstat failed.");
570         exit(-1);
571     }
572     
573     if(st.st_uid != 0)
574     {
575                 status = [[AuthUtil shared] autorize];
576                 if(status == noErr){
577                         fchown(fdTool, 0, st.st_gid);
578                         
579                         // Disable group and world writability and make setuid root.
580                         fchmod(fdTool, (st.st_mode & (~(S_IWGRP | S_IWOTH)))/* | S_ISUID*/);
581                         const char *args[] = {"root", [afshlpPath UTF8String],0L};
582                         [[AuthUtil shared] execUnixCommand:"/usr/sbin/chown" 
583                                                                                   args:args
584                                                                                 output:nil];
585                         [[AuthUtil shared] deautorize];
586                 }
587     } else  NSLog(@"st_uid = 0");
588     
589         
590     
591     close(fdTool);
592     
593     NSLog(@"Self-repair done.");
594         
595 }
596
597
598 // -------------------------------------------------------------------------------
599 //  startStopAfs:
600 // -------------------------------------------------------------------------------
601 - (IBAction) startStopAfs:(id) sender
602 {
603         BOOL currentAfsState = NO;
604         @try {
605                 currentAfsState = [afsProperty checkAfsStatus];
606                 // make the parameter to call the root helper app
607                 if(currentAfsState){
608                         //shutdown afs
609                         NSLog(@"Shutting down afs");
610                         [afsProperty shutdown];
611                 } else {
612                         //Start afs
613                         NSLog(@"Starting up afs");
614                         [afsProperty startup];
615                 }
616                 [self refreshGui:nil];
617         }
618         @catch (NSException * e) {
619                 [self showMessage:[e reason]];
620         }
621         @finally {
622                 [[AuthUtil shared] deautorize];
623         }
624 }
625
626 // -------------------------------------------------------------------------------
627 //  info:
628 // -------------------------------------------------------------------------------
629 - (void) refreshGui:(NSNotification *)notification{
630         BOOL afsIsUp = [afsProperty checkAfsStatus];
631         [self setAfsStatus];
632         [tokensButton setEnabled:afsIsUp];
633         [unlogButton setEnabled:afsIsUp];
634
635 }
636
637 // -------------------------------------------------------------------------------
638 //  -(void) refreshTokensNotify:(NSNotification*)notification
639 // -------------------------------------------------------------------------------
640 -(void) refreshTokensNotify:(NSNotification*)notification {
641         [self refreshTokens:nil];
642 }
643
644 // -------------------------------------------------------------------------------
645 //  afsVolumeMountChange: Track the afs volume state change
646 // -------------------------------------------------------------------------------
647 - (void) afsVolumeMountChange:(NSNotification *)notification{
648         // Cehck if is mounted or unmounted afs
649         if([[[notification userInfo] objectForKey:@"NSDevicePath"] isEqualToString:@"/afs"]){
650                 [self setAfsStatus];
651                 [self refreshTokens:nil];
652         }
653 }
654
655 // -------------------------------------------------------------------------------
656 //  info:
657 // -------------------------------------------------------------------------------
658 - (IBAction) info:(id) sender
659 {
660         [((InfoController*) infoController) showHtmlResource:[[self bundle] pathForResource:@"license" ofType:@"rtf"]];
661
662         [NSApp beginSheet: infoSheet
663            modalForWindow: [[self mainView] window]
664                 modalDelegate: self
665            didEndSelector:  @selector(didEndInfoSheet:returnCode:contextInfo:)
666                   contextInfo: nil];
667 }
668
669 // -------------------------------------------------------------------------------
670 //  tableDoubleAction:
671 // -------------------------------------------------------------------------------
672 - (IBAction) tableDoubleAction:(id) sender
673 {
674         [self showCellIP:nil];
675 }
676
677 // -------------------------------------------------------------------------------
678 //  getNewToken:
679 // -------------------------------------------------------------------------------
680 - (IBAction) getNewToken:(id) sender
681 {
682         BOOL useAklog = [useAklogCheck state] == NSOnState;
683         if(useAklog){
684                 //[AFSPropertyManager aklog];
685                 [afsProperty getTokens:false 
686                                                    usr:nil 
687                                                    pwd:nil];
688                 [self refreshTokens:nil];
689                 //Inform afs menuextra to updata afs status
690                 [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
691
692         } else {
693                 [NSBundle loadNibNamed:@"CredentialPanel" owner:self];
694                 [NSApp beginSheet: credentialSheet
695                    modalForWindow: [[self mainView] window]
696                         modalDelegate: self
697                    didEndSelector: @selector(didEndCredentialSheet:returnCode:contextInfo:)
698                           contextInfo: nil];
699         }
700 }
701
702
703 // -------------------------------------------------------------------------------
704 //  getCurrentCellInDB:
705 // -------------------------------------------------------------------------------
706 - (IBAction) unlog:(id) sender
707 {
708         int index = -1;
709         NSIndexSet *selectedIndex = [(NSTableView*)tokensTable selectedRowIndexes];
710         if( [selectedIndex count] > 0) {
711                 index = [selectedIndex firstIndex]; 
712                 do {
713                         NSString *tokenDesc = [tokenList objectAtIndex:index];
714                         NSString *cellToUnlog = [tokenDesc estractTokenByDelimiter:@"afs@" 
715                                                                                                                           endToken:@" "];
716                         [afsProperty unlog:cellToUnlog];
717                 } while ((index = [selectedIndex indexGreaterThanIndex: index]) != NSNotFound);
718         } else {
719                 [afsProperty unlog:nil];
720         }
721         [self refreshTokens:nil];
722         //Inform afs menuextra to updata afs status
723         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
724
725 }
726
727
728 // -------------------------------------------------------------------------------
729 //  aklogSwitchEvent:
730 // -------------------------------------------------------------------------------
731 - (IBAction) aklogSwitchEvent:(id) sender
732 {
733         //afs menu extra is loaded inform it to read preference
734         @try {
735                 if(![useAklogCheck state]) {
736                         //deselect the checkbox
737                         [aklogCredentialAtLoginTime setState:NO];
738                 }
739                 
740                 [self writePreferenceFile];
741                 
742                 //Enable disable aklog at login time checkbox according the useAklog checkbox
743                 [aklogCredentialAtLoginTime setEnabled:[useAklogCheck state]];
744                 
745         }
746         @catch (NSException * e) {
747                 [self showMessage:[e reason]];
748         }
749         
750                 
751 }
752
753 // -------------------------------------------------------------------------------
754 //  credentialAtLoginTimeEvent:
755 // -------------------------------------------------------------------------------
756 - (IBAction) credentialAtLoginTimeEvent:(id) sender {
757         [self writePreferenceFile];
758 }
759
760 // -------------------------------------------------------------------------------
761 //  afsStartupSwitchEvent:
762 // -------------------------------------------------------------------------------
763 - (IBAction) afsStartupSwitchEvent:(id) sender {
764         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
765         //get the new state
766         startAFSAtLogin = [checkButtonAfsAtBootTime state];
767         const char *startupConfigureOption[] = {"start_afs_at_startup", startAFSAtLogin?"enable":"disable", 0L};
768         if([[AuthUtil shared] autorize] == noErr) {
769                         //now disable the launchd configuration
770                         [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
771                                                                                   args:startupConfigureOption
772                                                                                 output:nil];
773         }
774 }
775
776
777 // -------------------------------------------------------------------------------
778 //  afsMenuActivationEvent:
779 // -------------------------------------------------------------------------------
780 - (IBAction) krb5KredentialAtLoginTimeEvent:(id) sender {
781         //
782         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
783         const char *args[] = {"enable_krb5_startup", [[installKRB5AuthAtLoginButton stringValue] UTF8String], "", 0L};
784         
785         //Check helper app
786         [self repairHelperTool];
787         if([[AuthUtil shared] autorize] == noErr) {
788                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String] 
789                                                                           args:args
790                                                                         output:nil];
791                 
792                 //check if all is gone well
793                 [installKRB5AuthAtLoginButton setState:[PListManager checkKrb5AtLoginTimeLaunchdEnable]];
794         }
795 }
796
797 // -------------------------------------------------------------------------------
798 //  afsMenuActivationEvent:
799 // -------------------------------------------------------------------------------
800 -(IBAction) afsMenuActivationEvent:(id) sender
801 {
802         CFPreferencesSetValue((CFStringRef)PREFERENCE_SHOW_STATUS_MENU, 
803                                                   (CFNumberRef)[NSNumber numberWithBool:[afsMenucheckBox state]], 
804                                                   (CFStringRef)kAfsCommanderID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
805         
806         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesAnyUser, kCFPreferencesAnyHost);
807         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
808         
809         //notify the backgrounder
810         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSMenuChangeState];
811 }
812
813 // -------------------------------------------------------------------------------
814 //  searchCellTextEvent:
815 //              Fileter the CellServDB list according to NSSearch content
816 // -------------------------------------------------------------------------------
817 - (IBAction) searchCellTextEvent:(id) sender
818 {
819         
820         NSString *searchText = [[textSearchField stringValue] lowercaseString]; //filter string
821         [self filterCellServDB:searchText];
822         [((NSTableView*)cellList) reloadData];
823 }
824
825 // -------------------------------------------------------------------------------
826 //  clearCellServDBFiltering:
827 //              clear the NSSearchField and showw all CellServDB table
828 // -------------------------------------------------------------------------------
829 - (void) clearCellServDBFiltering {
830         //Clear the text search
831         [textSearchField setStringValue:@""];
832         //load the temp array with all cell servdb
833         [self searchCellTextEvent:nil];
834 }
835 // --------------------------------------o-----------------------------------------
836 //  filterCellServDB:
837 //  make the NSMutableArray with all cellservdb or filtered element
838 // -------------------------------------------------------------------------------
839 - (void) filterCellServDB:(NSString*)textToFilter {
840         DBCellElement *cellElement; //Filtered element
841         BOOL doFilter = !(textToFilter == nil || ([textToFilter length] == 0));
842         
843         // We can do filtering and make the temp array
844         if(filteredCellDB){
845                 [filteredCellDB release];
846         }
847         filteredCellDB = [[NSMutableArray alloc] init];
848         NSEnumerator *e = [[afsProperty getCellList] objectEnumerator];
849         while(cellElement = (DBCellElement*)[e nextObject]) {
850                 // check if the element can be get
851                 if(doFilter) {
852                         //Get the CellServDB array enumerator
853                         NSRange rsltRng = [[[cellElement getCellName] lowercaseString] rangeOfString:textToFilter];
854                    if(rsltRng.location != NSNotFound) {
855                         //we can add this cell to filtered
856                         [filteredCellDB addObject:[cellElement retain]];
857                    }
858                 } else {
859                         [filteredCellDB addObject:[cellElement retain]];
860
861                 }
862         }
863 }
864                    
865 // -------------------------------------------------------------------------------
866 //  getCurrentCellInDB:
867 // -------------------------------------------------------------------------------
868 - (DBCellElement*) getCurrentCellInDB
869 {
870         int rowSelected = [((NSTableView *) cellList) selectedRow];
871         return [self getCellByIDX:rowSelected];
872 }
873
874 // -------------------------------------------------------------------------------
875 //  getCurrentCellInDB:
876 // -------------------------------------------------------------------------------
877 - (DBCellElement*) getCellByIDX:(int) idx
878 {
879         //NSMutableArray *cellArray = [afsProperty getCellList];
880         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:idx];
881         return cellElement;
882 }
883
884 // -------------------------------------------------------------------------------
885 //  showMessage:
886 // -------------------------------------------------------------------------------
887 -(void) showMessage:(NSString*) message{
888         NSAlert *alert = [[NSAlert alloc] init];
889         
890         [alert setMessageText:message];
891         [alert beginSheetModalForWindow:[[self mainView] window]
892                                           modalDelegate:nil 
893                                          didEndSelector:nil
894                                                 contextInfo:nil];
895         [alert release];
896 }
897
898 // -------------------------------------------------------------------------------
899 //  setAfsStatus:
900 // -------------------------------------------------------------------------------
901 -(void) setAfsStatus
902 {
903         
904         BOOL afsIsUp = [afsProperty checkAfsStatus];
905         BOOL afsEnabledAtStartup = NO;
906         
907         NSMutableString *commandOutput = [NSMutableString stringWithCapacity:20];
908         NSString *rootHelperApp = [[self bundle] pathForResource:@"afshlp" ofType:@""];
909                 
910 #if 0
911                         // make the parameter to call the root helper app
912         const char *checkAFSDaemonParam[] = {"check_afs_daemon",  0L};
913         if([[AuthUtil shared] autorize] == noErr) {
914                                 //now disable the launchd configuration
915                 [[AuthUtil shared] execUnixCommand:[rootHelperApp UTF8String]
916                                                                           args:checkAFSDaemonParam
917                                                                         output:commandOutput];
918                 afsEnabledAtStartup = [commandOutput rangeOfString:@"afshlp:afs daemon registration result:1"].location!=NSNotFound;
919         }
920 #else
921         afsEnabledAtStartup = 1;
922 #endif
923         
924         
925
926
927         [((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
928         
929         NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
930     NSRange titleRange = NSMakeRange(0, [colorTitle length]);
931         
932     [colorTitle addAttribute:NSForegroundColorAttributeName
933                        value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
934                        range:titleRange];
935         
936     [((NSButton *)startStopButton) setAttributedTitle:colorTitle];
937         [checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
938         if(afsIsUp) {
939                 [self startTimer];
940         } else {
941                 [self stopTimer];
942         }
943 }
944
945 // -------------------------------------------------------------------------------
946 //  refreshToken:
947 // -------------------------------------------------------------------------------
948 - (void) refreshTokens:(NSTimer*)theTimer;
949 {
950         if(![tokensLock tryLock]) return;
951         if(tokenList){
952                 [tokenList release];
953         }
954         
955         tokenList = [afsProperty getTokenList];
956         [((NSTableView*)tokensTable) reloadData];
957         [tokensLock unlock];
958 }
959
960 // -------------------------------------------------------------------------------
961 //  removeExtra:
962 // -------------------------------------------------------------------------------
963 - (IBAction) addLink:(id) sender {
964         [NSBundle loadNibNamed:@"SymLinkEdit" owner:self];
965         
966         [NSApp beginSheet: lyncCreationSheet
967            modalForWindow: [[self mainView] window]
968                 modalDelegate: self
969            didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
970                   contextInfo: nil];
971         
972 }
973
974 // -------------------------------------------------------------------------------
975 //  removeExtra:
976 // -------------------------------------------------------------------------------
977 - (IBAction) removeLink:(id) sender {
978         if(!linkConfiguration) return;
979         int index = 0;
980         NSArray *keys = [linkConfiguration allKeys];
981         NSIndexSet *linkToRemove = [tableViewLink selectedRowIndexes];
982         if( [linkToRemove count] > 0) {
983                 index = [linkToRemove firstIndex];
984                 do {
985                         [linkConfiguration removeObjectForKey:[keys objectAtIndex:index]];
986                 } while ((index = [linkToRemove indexGreaterThanIndex:index]) != -1);
987         }
988         
989         //write the new configuration
990         NSData *prefData = nil;
991         if([linkConfiguration count] > 0) {
992                 prefData = [NSPropertyListSerialization dataWithPropertyList:linkConfiguration
993                                                                                                                           format:NSPropertyListXMLFormat_v1_0
994                                                                                                                          options:0
995                                                                                                                            error:nil];
996         }
997         CFPreferencesSetValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,
998                                                   (CFDataRef)prefData,
999                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1000         
1001         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
1002         
1003         //reload the new data
1004         [tableViewLink reloadData];
1005 }
1006
1007 // -------------------------------------------------------------------------------
1008 //  removeExtra:
1009 // -------------------------------------------------------------------------------
1010 - (IBAction) enableLink:(id) sender {
1011         [self writePreferenceFile];
1012 }
1013
1014 // -------------------------------------------------------------------------------
1015 //  removeExtra:
1016 // -------------------------------------------------------------------------------
1017 - (IBAction) manageBackgrounderActivation:(id)sender {
1018         [PListManager launchctlCommand:[(NSButton*)sender state] 
1019                                                 userDomain:YES 
1020                                                         option:[NSArray arrayWithObjects:@"-S", @"Aqua", nil] 
1021                                                  plistName:[NSString stringWithFormat:@"%@.plist", BACKGROUNDER_P_FILE]];
1022         //re ad the status to check taht all is gone well
1023         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
1024 }
1025
1026 // -------------------------------------------------------------------------------
1027 //  tableViewLinkPerformClick:
1028 // -------------------------------------------------------------------------------
1029 - (IBAction) tableViewLinkPerformClick:(id) sender {
1030         NSLog(@"tableViewLinkPerformClick");
1031 }
1032
1033 // -------------------------------------------------------------------------------
1034 //  - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem
1035 // -------------------------------------------------------------------------------
1036 - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem 
1037 {
1038         //check to see if the cache param tab is the tab that will be selected
1039         if([((NSString*)[tabViewItem identifier]) intValue] == TAB_LINK)
1040         {
1041                 [tableViewLink reloadData];
1042         }
1043 }
1044
1045 @end
1046
1047 @implementation AFSCommanderPref (NSTableDataSource)
1048
1049
1050 // -------------------------------------------------------------------------------
1051 //  tableView:
1052 //              Manage the checkbox of CellServDB Table
1053
1054 // -------------------------------------------------------------------------------
1055 - (void)tableView:(NSTableView *)table 
1056    setObjectValue:(id)data 
1057    forTableColumn:(NSTableColumn *)col 
1058                           row:(int)row
1059 {
1060         NSString *identifier = (NSString*)[col identifier];
1061         switch([table tag]){
1062                 case TABLE_TOKENS_LIST:
1063                         break;
1064                         
1065                 case TABLE_CELL_LIST:
1066                         // we are editing checkbox for cellservdb table
1067                         if([identifier intValue] == CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN) {
1068                                 // set the user default cell
1069                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1070                                 [afsProperty setDefaultCellByName:[cellElement getCellName]];
1071                                 //[afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
1072                                 [((NSTableView*)cellList) reloadData];
1073                         } else if([identifier intValue] == CELLSRVDB_TABLE_DFLT_CHECK_COLUMN) {
1074                                 // set the cell for wich the user want to get token
1075                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1076                                 [cellElement setUserDefaultForToken:![cellElement userDefaultForToken]];
1077                         }  
1078                         break;
1079         }
1080         
1081 }
1082
1083
1084 // -------------------------------------------------------------------------------
1085 //  tableView:
1086 //              refresh delegate method for two AFSCommander table
1087 // -------------------------------------------------------------------------------
1088 - (id)  tableView:(NSTableView *) aTableView
1089         objectValueForTableColumn:(NSTableColumn *) aTableColumn
1090                                                   row:(int) rowIndex
1091 {  
1092         
1093         id result = nil;
1094         NSString *identifier = (NSString*)[aTableColumn identifier];
1095         switch([aTableView tag]){
1096                 case TABLE_TOKENS_LIST:
1097                         //We are refreshing tokens table
1098                         result = [self getTableTokensListValue:[identifier intValue] row:rowIndex];
1099                         break;
1100                         
1101                 case TABLE_CELL_LIST:
1102                         //We are refreshing cell db table
1103                         result = [self getTableCelListValue:[identifier intValue] row:rowIndex];
1104                         break;
1105                         
1106                 case TABLE_LINK_LIST:
1107                         result = [self getTableLinkValue:[identifier intValue] row:rowIndex];
1108                         break;
1109
1110                 
1111         }
1112         return result;  
1113 }
1114
1115
1116 // -------------------------------------------------------------------------------
1117 //  getTableCelListValue:
1118 // -------------------------------------------------------------------------------
1119 - (id)getTableTokensListValue:(int) colId row:(int)row
1120 {
1121         id result = nil;
1122         if(!tokenList) return nil;
1123         switch(colId){
1124                 case 0:
1125                         result = (NSString*)[tokenList objectAtIndex:row];
1126                         break;
1127         }
1128         return result;
1129 }
1130
1131
1132 // -------------------------------------------------------------------------------
1133 //  getTableCelListValue:
1134 // -------------------------------------------------------------------------------
1135 - (id)getTableCelListValue:(int) colId row:(int)row
1136 {
1137         id result = nil;
1138         //NSMutableArray *cellArray = [afsProperty getCellList];
1139         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1140         switch(colId){
1141                 case CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN:
1142                         result = [NSNumber numberWithInt:[cellElement userDefaultForCell]];
1143                         break;
1144                         
1145                 case CELLSRVDB_TABLE_DFLT_CHECK_COLUMN:
1146                         result = [NSNumber numberWithInt:[cellElement userDefaultForToken]];
1147                         break;
1148                 case CELLSRVDB_TABLE_NAME_COLUMN:
1149                         result = [cellElement getCellName];
1150                         break;
1151                         
1152                 case CELLSRVDB_TABLE_DESCRIPTION_COLUMN:
1153                         result = [cellElement getCellComment];
1154                         break;
1155         }
1156         return result;
1157 }
1158
1159 // -------------------------------------------------------------------------------
1160 //  getTableCelListValue:
1161 // -------------------------------------------------------------------------------
1162 - (id)getTableLinkValue:(int) colId row:(int)row
1163 {
1164         id result = nil;
1165         NSArray *allKey = [linkConfiguration allKeys];
1166         switch(colId){
1167                 case TABLE_COLUMN_LINK_NAME:
1168                         result = [allKey objectAtIndex:row];
1169                         break;
1170                         
1171                 case TABLE_COLUMN_LINK_PATH:
1172                         result = [linkConfiguration objectForKey:[allKey objectAtIndex:row]];
1173                         break;
1174         }
1175         return result;
1176 }
1177
1178
1179 // -------------------------------------------------------------------------------
1180 //  numberOfRowsInTableView:
1181 // -------------------------------------------------------------------------------
1182 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
1183 {
1184         int rowCount = 0;
1185         //NSMutableArray *cellArray = nil;
1186         switch([aTableView tag]){
1187                 case TABLE_TOKENS_LIST:
1188                         if(tokenList)  rowCount = [tokenList count];
1189                         break;
1190                         
1191                 case TABLE_CELL_LIST:
1192                         //cellArray = [afsProperty getCellList];
1193                         if(filteredCellDB)  rowCount = [filteredCellDB count];
1194                         break;
1195                         
1196                 case TABLE_LINK_LIST:
1197                         if(linkConfiguration)  rowCount = [linkConfiguration count];
1198                         break;
1199
1200                         
1201         }       
1202         return rowCount;  
1203 }
1204 @end
1205
1206
1207 @implementation AFSCommanderPref (TableDelegate)
1208 // -------------------------------------------------------------------------------
1209 //  selectionShouldChangeInTableView:
1210 // -------------------------------------------------------------------------------
1211 - (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTable
1212 {
1213         switch([aTable tag]){
1214                 case TABLE_TOKENS_LIST:
1215                         
1216                         break;
1217                         
1218                 case TABLE_CELL_LIST:
1219                         [self tableViewCellmanageButtonState:[aTable selectedRow]];
1220                         break;
1221                         
1222                 case TABLE_LINK_LIST:
1223                         break;
1224                         
1225                         
1226         }       
1227         
1228         return YES;
1229 }
1230
1231 // -------------------------------------------------------------------------------
1232 //  tableView:
1233 // -------------------------------------------------------------------------------
1234 - (BOOL)tableView:(NSTableView *)aTable shouldSelectRow:(int)aRow
1235 {
1236         switch([aTable tag]){
1237                 case TABLE_TOKENS_LIST:
1238                         
1239                         break;
1240                         
1241                 case TABLE_CELL_LIST:
1242                         [self tableViewCellmanageButtonState:aRow];
1243                         break;
1244                         
1245                 case TABLE_LINK_LIST:
1246                         break;
1247                         
1248                         
1249         }
1250         
1251         return YES;
1252 }
1253
1254 // -------------------------------------------------------------------------------
1255 //  tableView:
1256 // -------------------------------------------------------------------------------
1257 - (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
1258         NSTableView *aTable = [aNotification object];
1259         switch([aTable tag]){
1260                 case TABLE_TOKENS_LIST:
1261                         break;
1262                         
1263                 case TABLE_CELL_LIST:
1264                         break;
1265                         
1266                 case TABLE_LINK_LIST:
1267                         [self tableViewLinkmanageButtonState:[aTable selectedRowIndexes]];
1268                         break;
1269                         
1270                         
1271         }
1272 }
1273 // -------------------------------------------------------------------------------
1274 //  manageButtonState:
1275 // -------------------------------------------------------------------------------
1276 -(void) tableViewCellmanageButtonState:(int) rowSelected  {
1277         [((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
1278         [((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
1279 }
1280
1281 // -------------------------------------------------------------------------------
1282 //  manageButtonState:
1283 // -------------------------------------------------------------------------------
1284 -(void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex {
1285         [buttonRemoveLink setEnabled:[rowsSelectedIndex count]>0];
1286 }
1287 @end
1288
1289
1290 @implementation AFSCommanderPref (ModalDelegate)
1291 // -------------------------------------------------------------------------------
1292 //  didEndSheet:
1293 // -------------------------------------------------------------------------------
1294 - (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1295 {
1296     [sheet orderOut:self];
1297         //Filter the cellServDb and allocate filtered array
1298         [self searchCellTextEvent:nil];
1299         [((NSTableView*)cellList) reloadData];
1300 }
1301
1302 // -------------------------------------------------------------------------------
1303 //  Klog credential request
1304 // -------------------------------------------------------------------------------
1305 - (void)didEndCredentialSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1306 {
1307         if([((TokenCredentialController*)credentialCommander) takenToken] == YES){
1308                 /*[AFSPropertyManager klog:[((TokenCredentialController*)credentialCommander) uName] 
1309                                                         uPwd:[((TokenCredentialController*)credentialCommander) uPwd] ];*/
1310                 [afsProperty getTokens:true 
1311                                                    usr:[((TokenCredentialController*)credentialCommander) uName] 
1312                                                    pwd:[((TokenCredentialController*)credentialCommander) uPwd]];
1313         }
1314     [sheet orderOut:self];
1315         [self refreshTokens:nil];
1316         //Inform afs menuextra to updata afs status
1317         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
1318
1319 }
1320
1321 // -------------------------------------------------------------------------------
1322 //  Klog credential request
1323 // -------------------------------------------------------------------------------
1324 - (void)didEndInfoSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1325 {
1326         [sheet orderOut:self];
1327 }
1328
1329 // -------------------------------------------------------------------------------
1330 //  symlink edite
1331 // -------------------------------------------------------------------------------
1332 - (void)didEndSymlinkSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1333 {
1334         [lyncCreationSheet orderOut:self];
1335         [self readPreferenceFile];
1336         [tableViewLink reloadData];
1337         
1338 }
1339 @end