ecaacfbd2640447e99263819c9075f3558ee716c
[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         BOOL afsIsUp = [afsProperty checkAfsStatus];
904         BOOL afsEnabledAtStartup = [afsProperty checkAfsStatusForStartup];
905
906
907         [((NSButton *)startStopButton) setTitle: (afsIsUp?kAfsButtonShutdown:kAfsButtonStartup)];
908         
909         NSMutableAttributedString *colorTitle =[[NSMutableAttributedString alloc] initWithAttributedString:[((NSButton *)startStopButton) attributedTitle]];
910     NSRange titleRange = NSMakeRange(0, [colorTitle length]);
911         
912     [colorTitle addAttribute:NSForegroundColorAttributeName
913                        value:(afsIsUp?[NSColor redColor]:[NSColor blackColor])
914                        range:titleRange];
915         
916     [((NSButton *)startStopButton) setAttributedTitle:colorTitle];
917         [checkButtonAfsAtBootTime setState:afsEnabledAtStartup];
918         if(afsIsUp) {
919                 [self startTimer];
920         } else {
921                 [self stopTimer];
922         }
923 }
924
925 // -------------------------------------------------------------------------------
926 //  refreshToken:
927 // -------------------------------------------------------------------------------
928 - (void) refreshTokens:(NSTimer*)theTimer;
929 {
930         if(![tokensLock tryLock]) return;
931         if(tokenList){
932                 [tokenList release];
933         }
934         
935         tokenList = [afsProperty getTokenList];
936         [((NSTableView*)tokensTable) reloadData];
937         [tokensLock unlock];
938 }
939
940 // -------------------------------------------------------------------------------
941 //  removeExtra:
942 // -------------------------------------------------------------------------------
943 - (IBAction) addLink:(id) sender {
944         [NSBundle loadNibNamed:@"SymLinkEdit" owner:self];
945         
946         [NSApp beginSheet: lyncCreationSheet
947            modalForWindow: [[self mainView] window]
948                 modalDelegate: self
949            didEndSelector: @selector(didEndSymlinkSheet:returnCode:contextInfo:)
950                   contextInfo: nil];
951         
952 }
953
954 // -------------------------------------------------------------------------------
955 //  removeExtra:
956 // -------------------------------------------------------------------------------
957 - (IBAction) removeLink:(id) sender {
958         if(!linkConfiguration) return;
959         int index = 0;
960         NSArray *keys = [linkConfiguration allKeys];
961         NSIndexSet *linkToRemove = [tableViewLink selectedRowIndexes];
962         if( [linkToRemove count] > 0) {
963                 index = [linkToRemove firstIndex];
964                 do {
965                         [linkConfiguration removeObjectForKey:[keys objectAtIndex:index]];
966                 } while ((index = [linkToRemove indexGreaterThanIndex:index]) != -1);
967         }
968         
969         //write the new configuration
970         NSData *prefData = nil;
971         if([linkConfiguration count] > 0) {
972                 prefData = [NSPropertyListSerialization dataWithPropertyList:linkConfiguration
973                                                                                                                           format:NSPropertyListXMLFormat_v1_0
974                                                                                                                          options:0
975                                                                                                                            error:nil];
976         }
977         CFPreferencesSetValue((CFStringRef)PREFERENCE_LINK_CONFIGURATION,
978                                                   (CFDataRef)prefData,
979                                                   (CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
980         
981         CFPreferencesSynchronize((CFStringRef)kAfsCommanderID,  kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
982         
983         //reload the new data
984         [tableViewLink reloadData];
985 }
986
987 // -------------------------------------------------------------------------------
988 //  removeExtra:
989 // -------------------------------------------------------------------------------
990 - (IBAction) enableLink:(id) sender {
991         [self writePreferenceFile];
992 }
993
994 // -------------------------------------------------------------------------------
995 //  removeExtra:
996 // -------------------------------------------------------------------------------
997 - (IBAction) manageBackgrounderActivation:(id)sender {
998         [PListManager launchctlCommand:[(NSButton*)sender state] 
999                                                 userDomain:YES 
1000                                                         option:[NSArray arrayWithObjects:@"-S", @"Aqua", nil] 
1001                                                  plistName:[NSString stringWithFormat:@"%@.plist", BACKGROUNDER_P_FILE]];
1002         //re ad the status to check taht all is gone well
1003         [backgrounderActivationCheck setState:[PListManager launchdJobState:BACKGROUNDER_P_FILE]];
1004 }
1005
1006 // -------------------------------------------------------------------------------
1007 //  tableViewLinkPerformClick:
1008 // -------------------------------------------------------------------------------
1009 - (IBAction) tableViewLinkPerformClick:(id) sender {
1010         NSLog(@"tableViewLinkPerformClick");
1011 }
1012
1013 // -------------------------------------------------------------------------------
1014 //  - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem
1015 // -------------------------------------------------------------------------------
1016 - (void)tabView:(NSTabView *)tabView willSelectTabViewItem: (NSTabViewItem *)tabViewItem 
1017 {
1018         //check to see if the cache param tab is the tab that will be selected
1019         if([((NSString*)[tabViewItem identifier]) intValue] == TAB_LINK)
1020         {
1021                 [tableViewLink reloadData];
1022         }
1023 }
1024
1025 @end
1026
1027 @implementation AFSCommanderPref (NSTableDataSource)
1028
1029
1030 // -------------------------------------------------------------------------------
1031 //  tableView:
1032 //              Manage the checkbox of CellServDB Table
1033
1034 // -------------------------------------------------------------------------------
1035 - (void)tableView:(NSTableView *)table 
1036    setObjectValue:(id)data 
1037    forTableColumn:(NSTableColumn *)col 
1038                           row:(int)row
1039 {
1040         NSString *identifier = (NSString*)[col identifier];
1041         switch([table tag]){
1042                 case TABLE_TOKENS_LIST:
1043                         break;
1044                         
1045                 case TABLE_CELL_LIST:
1046                         // we are editing checkbox for cellservdb table
1047                         if([identifier intValue] == CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN) {
1048                                 // set the user default cell
1049                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1050                                 [afsProperty setDefaultCellByName:[cellElement getCellName]];
1051                                 //[afsDefaultCellLabel setStringValue:[afsProperty getDefaultCellName]];
1052                                 [((NSTableView*)cellList) reloadData];
1053                         } else if([identifier intValue] == CELLSRVDB_TABLE_DFLT_CHECK_COLUMN) {
1054                                 // set the cell for wich the user want to get token
1055                                 DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1056                                 [cellElement setUserDefaultForToken:![cellElement userDefaultForToken]];
1057                         }  
1058                         break;
1059         }
1060         
1061 }
1062
1063
1064 // -------------------------------------------------------------------------------
1065 //  tableView:
1066 //              refresh delegate method for two AFSCommander table
1067 // -------------------------------------------------------------------------------
1068 - (id)  tableView:(NSTableView *) aTableView
1069         objectValueForTableColumn:(NSTableColumn *) aTableColumn
1070                                                   row:(int) rowIndex
1071 {  
1072         
1073         id result = nil;
1074         NSString *identifier = (NSString*)[aTableColumn identifier];
1075         switch([aTableView tag]){
1076                 case TABLE_TOKENS_LIST:
1077                         //We are refreshing tokens table
1078                         result = [self getTableTokensListValue:[identifier intValue] row:rowIndex];
1079                         break;
1080                         
1081                 case TABLE_CELL_LIST:
1082                         //We are refreshing cell db table
1083                         result = [self getTableCelListValue:[identifier intValue] row:rowIndex];
1084                         break;
1085                         
1086                 case TABLE_LINK_LIST:
1087                         result = [self getTableLinkValue:[identifier intValue] row:rowIndex];
1088                         break;
1089
1090                 
1091         }
1092         return result;  
1093 }
1094
1095
1096 // -------------------------------------------------------------------------------
1097 //  getTableCelListValue:
1098 // -------------------------------------------------------------------------------
1099 - (id)getTableTokensListValue:(int) colId row:(int)row
1100 {
1101         id result = nil;
1102         if(!tokenList) return nil;
1103         switch(colId){
1104                 case 0:
1105                         result = (NSString*)[tokenList objectAtIndex:row];
1106                         break;
1107         }
1108         return result;
1109 }
1110
1111
1112 // -------------------------------------------------------------------------------
1113 //  getTableCelListValue:
1114 // -------------------------------------------------------------------------------
1115 - (id)getTableCelListValue:(int) colId row:(int)row
1116 {
1117         id result = nil;
1118         //NSMutableArray *cellArray = [afsProperty getCellList];
1119         DBCellElement *cellElement =  (DBCellElement*)[filteredCellDB objectAtIndex:row];
1120         switch(colId){
1121                 case CELLSRVDB_TABLE_USR_DFLT_CHECK_COLUMN:
1122                         result = [NSNumber numberWithInt:[cellElement userDefaultForCell]];
1123                         break;
1124                         
1125                 case CELLSRVDB_TABLE_DFLT_CHECK_COLUMN:
1126                         result = [NSNumber numberWithInt:[cellElement userDefaultForToken]];
1127                         break;
1128                 case CELLSRVDB_TABLE_NAME_COLUMN:
1129                         result = [cellElement getCellName];
1130                         break;
1131                         
1132                 case CELLSRVDB_TABLE_DESCRIPTION_COLUMN:
1133                         result = [cellElement getCellComment];
1134                         break;
1135         }
1136         return result;
1137 }
1138
1139 // -------------------------------------------------------------------------------
1140 //  getTableCelListValue:
1141 // -------------------------------------------------------------------------------
1142 - (id)getTableLinkValue:(int) colId row:(int)row
1143 {
1144         id result = nil;
1145         NSArray *allKey = [linkConfiguration allKeys];
1146         switch(colId){
1147                 case TABLE_COLUMN_LINK_NAME:
1148                         result = [allKey objectAtIndex:row];
1149                         break;
1150                         
1151                 case TABLE_COLUMN_LINK_PATH:
1152                         result = [linkConfiguration objectForKey:[allKey objectAtIndex:row]];
1153                         break;
1154         }
1155         return result;
1156 }
1157
1158
1159 // -------------------------------------------------------------------------------
1160 //  numberOfRowsInTableView:
1161 // -------------------------------------------------------------------------------
1162 - (int)numberOfRowsInTableView:(NSTableView *)aTableView
1163 {
1164         int rowCount = 0;
1165         //NSMutableArray *cellArray = nil;
1166         switch([aTableView tag]){
1167                 case TABLE_TOKENS_LIST:
1168                         if(tokenList)  rowCount = [tokenList count];
1169                         break;
1170                         
1171                 case TABLE_CELL_LIST:
1172                         //cellArray = [afsProperty getCellList];
1173                         if(filteredCellDB)  rowCount = [filteredCellDB count];
1174                         break;
1175                         
1176                 case TABLE_LINK_LIST:
1177                         if(linkConfiguration)  rowCount = [linkConfiguration count];
1178                         break;
1179
1180                         
1181         }       
1182         return rowCount;  
1183 }
1184 @end
1185
1186
1187 @implementation AFSCommanderPref (TableDelegate)
1188 // -------------------------------------------------------------------------------
1189 //  selectionShouldChangeInTableView:
1190 // -------------------------------------------------------------------------------
1191 - (BOOL)selectionShouldChangeInTableView:(NSTableView *)aTable
1192 {
1193         switch([aTable tag]){
1194                 case TABLE_TOKENS_LIST:
1195                         
1196                         break;
1197                         
1198                 case TABLE_CELL_LIST:
1199                         [self tableViewCellmanageButtonState:[aTable selectedRow]];
1200                         break;
1201                         
1202                 case TABLE_LINK_LIST:
1203                         break;
1204                         
1205                         
1206         }       
1207         
1208         return YES;
1209 }
1210
1211 // -------------------------------------------------------------------------------
1212 //  tableView:
1213 // -------------------------------------------------------------------------------
1214 - (BOOL)tableView:(NSTableView *)aTable shouldSelectRow:(int)aRow
1215 {
1216         switch([aTable tag]){
1217                 case TABLE_TOKENS_LIST:
1218                         
1219                         break;
1220                         
1221                 case TABLE_CELL_LIST:
1222                         [self tableViewCellmanageButtonState:aRow];
1223                         break;
1224                         
1225                 case TABLE_LINK_LIST:
1226                         break;
1227                         
1228                         
1229         }
1230         
1231         return YES;
1232 }
1233
1234 // -------------------------------------------------------------------------------
1235 //  tableView:
1236 // -------------------------------------------------------------------------------
1237 - (void)tableViewSelectionDidChange:(NSNotification *)aNotification {
1238         NSTableView *aTable = [aNotification object];
1239         switch([aTable tag]){
1240                 case TABLE_TOKENS_LIST:
1241                         break;
1242                         
1243                 case TABLE_CELL_LIST:
1244                         break;
1245                         
1246                 case TABLE_LINK_LIST:
1247                         [self tableViewLinkmanageButtonState:[aTable selectedRowIndexes]];
1248                         break;
1249                         
1250                         
1251         }
1252 }
1253 // -------------------------------------------------------------------------------
1254 //  manageButtonState:
1255 // -------------------------------------------------------------------------------
1256 -(void) tableViewCellmanageButtonState:(int) rowSelected  {
1257         [((NSControl*) cellIpButton) setEnabled:rowSelected >= 0];
1258         [((NSControl*) removeCellButton) setEnabled:rowSelected >= 0];
1259 }
1260
1261 // -------------------------------------------------------------------------------
1262 //  manageButtonState:
1263 // -------------------------------------------------------------------------------
1264 -(void) tableViewLinkmanageButtonState:(NSIndexSet *) rowsSelectedIndex {
1265         [buttonRemoveLink setEnabled:[rowsSelectedIndex count]>0];
1266 }
1267 @end
1268
1269
1270 @implementation AFSCommanderPref (ModalDelegate)
1271 // -------------------------------------------------------------------------------
1272 //  didEndSheet:
1273 // -------------------------------------------------------------------------------
1274 - (void)didEndSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1275 {
1276     [sheet orderOut:self];
1277         //Filter the cellServDb and allocate filtered array
1278         [self searchCellTextEvent:nil];
1279         [((NSTableView*)cellList) reloadData];
1280 }
1281
1282 // -------------------------------------------------------------------------------
1283 //  Klog credential request
1284 // -------------------------------------------------------------------------------
1285 - (void)didEndCredentialSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1286 {
1287         if([((TokenCredentialController*)credentialCommander) takenToken] == YES){
1288                 /*[AFSPropertyManager klog:[((TokenCredentialController*)credentialCommander) uName] 
1289                                                         uPwd:[((TokenCredentialController*)credentialCommander) uPwd] ];*/
1290                 [afsProperty getTokens:true 
1291                                                    usr:[((TokenCredentialController*)credentialCommander) uName] 
1292                                                    pwd:[((TokenCredentialController*)credentialCommander) uPwd]];
1293         }
1294     [sheet orderOut:self];
1295         [self refreshTokens:nil];
1296         //Inform afs menuextra to updata afs status
1297         [[NSDistributedNotificationCenter defaultCenter] postNotificationName:kAFSMenuExtraID object:kMExtraAFSStateChange];
1298
1299 }
1300
1301 // -------------------------------------------------------------------------------
1302 //  Klog credential request
1303 // -------------------------------------------------------------------------------
1304 - (void)didEndInfoSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1305 {
1306         [sheet orderOut:self];
1307 }
1308
1309 // -------------------------------------------------------------------------------
1310 //  symlink edite
1311 // -------------------------------------------------------------------------------
1312 - (void)didEndSymlinkSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo
1313 {
1314         [lyncCreationSheet orderOut:self];
1315         [self readPreferenceFile];
1316         [tableViewLink reloadData];
1317         
1318 }
1319 @end