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