-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcrController.m
executable file
·1416 lines (1133 loc) · 46.6 KB
/
crController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// crController.m
// CronniX
//
// Created by sas on Sat Sep 15 2001.
// Copyright (c) 2001 Sven A. Schmidt. All rights reserved.
//
// abstracture IT-Beratung GmbH
// www.abstracture.de
//
#import "crController.h"
#import "loadCrontabController.h"
#import "BLAuthentication.h"
#import "UserImageRep.h"
#import "RunNowNibController.h"
#import "NewTaskDialogController.h"
#import "EditTaskDialogController.h"
#import "SasString.h"
NSString *cronCommand = @"/usr/bin/crontab";
NSString *suCrontabResource = @"sucrontab";
static NSString *cronnixHomepage = @"http://www.abstracture.de/projects-en/cronnix";
@implementation crController
- (id)init {
if ( self = [ super init ] ) {
[ [ NSNotificationCenter defaultCenter ] addObserver: self selector:@selector(documentModified:)
name: DocumentModifiedNotification object: nil ];
[ [ NSNotificationCenter defaultCenter ] addObserver: self selector:@selector(userSelected:)
name: UserSelectedNotification object: nil ];
[ [ NSNotificationCenter defaultCenter ] addObserver: self selector:@selector(taskCreated:)
name: TaskCreatedNotification object: nil ];
[ [ NSNotificationCenter defaultCenter ] addObserver: self selector:@selector(taskEdited:)
name: TaskEditedNotification object: nil ];
}
return self;
}
- (void)dealloc {
[[ NSNotificationCenter defaultCenter ] removeObserver: self ];
[ toolbar release ];
[ currentCrontab release ];
[ super dealloc];
}
// --------------------------------------------------------------------------------------------------------------
// controls
- (IBAction)loadCrontab:(id)sender {
[ self loadCrontab ];
}
- (IBAction)newLine:(id)sender {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] )
[ self newLine ];
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
[ [ envVariablesNibController sharedInstance ] newLine ];
}
- (IBAction)newLineWithDialog:(id)sender {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] )
[ self newLineWithDialog ];
}
- (IBAction)removeLine:(id)sender {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] ) {
int lastSelectedRow = [ crTable selectedRow ];
[ self removeLinesInList: [ crTable selectedRowEnumerator ] ];
int nRows = [ crTable numberOfRows ];
int rowToSelect = lastSelectedRow < nRows ? lastSelectedRow : nRows -1;
[ crTable selectRow: rowToSelect byExtendingSelection: NO ];
}
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
[ [ envVariablesNibController sharedInstance ] removeLine: sender ];
}
- (IBAction)duplicateLine:(id)sender {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] ) {
[ self duplicateLinesInList: [ crTable selectedRowEnumerator ] ];
if ( [ crTable selectedRow ] == -1 ) {
[ crTable selectRow: [ crTable numberOfRows ] -1 byExtendingSelection: NO ];
}
}
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
[ [ envVariablesNibController sharedInstance ] duplicateLine ];
}
- (IBAction)writeCrontab:(id)sender {
[ self writeCrontab ];
}
- (IBAction)showInfoPanel:(id)sender {
[[NSApplication sharedApplication] orderFrontStandardAboutPanel:sender];
}
- (IBAction)openForUser:(id)sender {
[ self crontabShouldLoad ];
}
- (IBAction)openSystemCrontab:(id)sender {
[ self systemCrontabShouldLoad ];
}
- (void)openForUser {
[ envVariablesNibController hideWindow ];
[ [ loadCrontabController sharedInstance ] beginSheetForWindow: winMain ];
}
- (void)crontabShouldLoad {
if ( [ self isDirty ] ) {
NSBeginAlertSheet(
NSLocalizedString( @"Unsaved Data", @"Unsaved data alert sheet title" ),
NSLocalizedString( @"Save", @"Save in dialog" ),
NSLocalizedString( @"Discard", @"discard in dialog" ),
NSLocalizedString( @"Cancel", @"Cancel in dialog" ),
winMain, self, NULL,
@selector(didEndLoadSheet:returnCode:contextInfo:), nil,
NSLocalizedString( @"You have modified your crontab. Save changes?",
@"unsaved changes warning in alert sheet" ) );
} else {
[ self openForUser ];
}
}
- (void)systemCrontabShouldLoad {
if ( [ self isDirty ] ) {
NSBeginAlertSheet(
NSLocalizedString( @"Unsaved Data", @"Unsaved data alert sheet title" ),
NSLocalizedString( @"Save", @"Save in dialog" ),
NSLocalizedString( @"Discard", @"discard in dialog" ),
NSLocalizedString( @"Cancel", @"Cancel in dialog" ),
winMain, self, NULL,
@selector(didEndLoadSytemCrontabSheet:returnCode:contextInfo:), nil,
NSLocalizedString( @"You have modified your crontab. Save changes?",
@"unsaved changes warning in alert sheet" ) );
} else {
[ self openSystemCrontab ];
}
}
- (void)crontabShouldImport {
if ( [ self isDirty ] ) {
NSBeginAlertSheet(
NSLocalizedString( @"Unsaved Data", @"Unsaved data alert sheet title" ),
NSLocalizedString( @"Save", @"Save in dialog" ),
NSLocalizedString( @"Discard", @"discard in dialog" ),
NSLocalizedString( @"Cancel", @"Cancel in dialog" ),
winMain, self, NULL,
@selector(didEndImportCrontabSheet:returnCode:contextInfo:), nil,
NSLocalizedString( @"You have modified your crontab. Save changes?",
@"unsaved changes warning in alert sheet" ) );
} else {
[ self importCrontab ];
}
}
- (void)didEndLoadSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
switch ( returnCode ) {
case NSAlertDefaultReturn: // yes, save
[ self writeCrontab ];
[ self openForUser ];
break;
case NSAlertAlternateReturn: // no, discard
[ self openForUser ];
break;
case NSAlertOtherReturn: // cancel, go back
break;
}
}
- (void)didEndLoadSytemCrontabSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
switch ( returnCode ) {
case NSAlertDefaultReturn: // yes, save
[ self writeCrontab ];
[ self openSystemCrontab ];
break;
case NSAlertAlternateReturn: // no, discard
[ self openSystemCrontab ];
break;
case NSAlertOtherReturn: // cancel, go back
break;
}
}
- (void)didEndImportCrontabSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
switch ( returnCode ) {
case NSAlertDefaultReturn: // yes, save
[ self writeCrontab ];
[ self importCrontab ];
break;
case NSAlertAlternateReturn: // no, discard
[ self importCrontab ];
break;
case NSAlertOtherReturn: // cancel, go back
break;
}
}
- (BOOL)isSystemCrontab {
return [ [ self crontabForUser ] isEqualToString: @"system" ];
}
- (void)openSystemCrontab {
NSFileHandle *fh = [ NSFileHandle fileHandleForReadingAtPath: @"/etc/crontab" ];
NSData *crondata;
if ( fh ) {
crondata = [ fh readDataToEndOfFile ];
if ( ! crondata ) return; // pop up an error sheet...
[ self clearCrontab ];
// need to set this early, because "system" parsing is slightly different
[ self setCrontabForUser: @"system" ];
[ self parseCrontab: crondata ];
[ self setDirty: NO ];
}
}
- (void)insertProgram:(id)sender {
int result;
//NSArray *fileTypes = [NSArray arrayWithObject:@"app"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[ oPanel setAllowsMultipleSelection: YES ];
[ oPanel setPrompt: NSLocalizedString( @"Insert", @"Insert program std file open dialog: alternative label for open button" ) ];
result = [ oPanel runModalForDirectory: NSHomeDirectory() file: nil types: nil ];
if (result == NSOKButton) {
NSArray *filenames = [oPanel filenames];
NSEnumerator *iter = [ filenames objectEnumerator ];
NSString *fname;
while ( fname = [ iter nextObject ] )
[ self insertProgramWithString: fname ];
}
}
- (void)envVariables:(id)sender {
[ envVariablesNibController showWindow ];
}
- (void)activeButtonToggled {
[ [ NSNotificationCenter defaultCenter ] postNotificationName: DocumentModifiedNotification object: self ];
}
- (IBAction)runSelectedCommand:(id)sender {
[ self runSelectedCommand ];
}
- (void)runSelectedCommand {
NSTextView *tv = [ [ RunNowNibController sharedInstance ] outputTextField ];
NSString *cmd = [ [ self selectedTask ] objectForKey: @"Command" ];
NSData *output;
NSString *outputString;
[ [ RunNowNibController sharedInstance ] showWindow ];
// NSLog( @"Running command %@", cmd );
[ tv setEditable: YES ];
[ tv setString: NSLocalizedString( @"Running command\n", @"Information text displayed in the runNowPanel" ) ];
[ tv insertText: cmd ];
[ tv insertText: NSLocalizedString( @"\nThe output will appear below when the command has finished executing\n", @"Information text displayed in the runNowPanel" ) ];
[ tv setEditable: NO ];
output = [ self runCliCommand: @"/bin/tcsh" WithArgs: [ NSArray arrayWithObjects: @"-c", cmd, nil ] ];
if ( ! output )
outputString = @"- no output from command -";
else
outputString = [ [ [ NSString alloc ] initWithData: output
encoding: [ NSString defaultCStringEncoding ] ] autorelease ];
//NSLog( outputString );
[ tv setEditable: YES ];
[ tv insertText: outputString ];
[ tv setEditable: NO ];
//[ outputString release ];
}
- (void)runSelectedCommandOld {
NSTextView *tv = [ [ RunNowNibController sharedInstance ] outputTextField ];
NSString *cmd = [ [ self selectedTask ] objectForKey: @"Command" ];
NSData *output;
NSString *outputString;
[ [ RunNowNibController sharedInstance ] showWindow ];
// NSLog( @"Running command %@", cmd );
[ tv setEditable: YES ];
[ tv setString: NSLocalizedString( @"Running command\n", @"Information text displayed in the runNowPanel" ) ];
[ tv insertText: cmd ];
[ tv insertText: NSLocalizedString( @"\nThe output will appear below when the command has finished executing\n", @"Information text displayed in the runNowPanel" ) ];
[ tv setEditable: NO ];
output = [ self runCliCommand: @"/bin/tcsh" WithArgs: [ NSArray arrayWithObjects: @"-c", cmd, nil ] ];
if ( ! output )
outputString = @"- no output from command -";
else
outputString = [ [ [ NSString alloc ] initWithData: output
encoding: [ NSString defaultCStringEncoding ] ] autorelease ];
//NSLog( outputString );
[ tv setEditable: YES ];
[ tv insertText: outputString ];
[ tv setEditable: NO ];
//[ outputString release ];
}
- (IBAction)openHomepage:(id)sender {
[[ NSWorkspace sharedWorkspace ] openURL: [ NSURL URLWithString: cronnixHomepage ]];
}
- (IBAction)checkForUpdates:(id)sender {
NSString *currentVersion = [[[ NSBundle bundleForClass: [ self class ]] infoDictionary ]
objectForKey: @"CFBundleVersion" ];
NSString *url = [ NSString stringWithFormat: @"%@/%@", cronnixHomepage, @"version.xml" ];
NSDictionary *dict = [ NSDictionary dictionaryWithContentsOfURL: [ NSURL URLWithString: url ]];
if ( ! dict ) {
NSBeginAlertSheet(
NSLocalizedString( @"Connection failure",
@"Check for update failure sheet title" ),
NSLocalizedString( @"Bummer",
@"Check for update connection failure acknowledgement button title" ),
nil,
nil,
winMain, self, NULL,
nil, nil,
NSLocalizedString( @"Someone tripped over the wire to the internet. Or maybe it's the rain. Wait for clear skies and try again.",
@"update check connection failure dialog text" ) );
}
NSString *latestVersion = [ dict valueForKey: @"Version" ];
if ( ! [ latestVersion isEqualToString: currentVersion ] ) {
id changes = [ dict objectForKey: @"Changes" ];
NSString *msg = [ NSString stringWithFormat: NSLocalizedString( @"There's a new version available at %@.\n\nChanges in version %@:\n", @"new version available dialog text" ),
cronnixHomepage, latestVersion ];
NSString *s = [ changes componentsJoinedByString: @"\n¥ " ];
s = [ NSString stringWithFormat: @"%@\n¥ %@", msg, s ];
NSBeginAlertSheet(
NSLocalizedString( @"Update Available",
@"Update available alert sheet title" ),
NSLocalizedString( @"Go to download page",
@"go to download page button title in 'update available' dialog" ),
nil,
NSLocalizedString( @"Cancel", @"Cancel in dialog" ),
winMain, self, NULL,
@selector(didEndUpdateAvailableSheet:returnCode:contextInfo:), nil,
s );
} else {
NSBeginAlertSheet(
NSLocalizedString( @"No Update Available",
@"No update available alert sheet title" ),
NSLocalizedString( @"Too bad",
@"confirmation button title in 'no update available' dialog" ),
nil,
nil,
winMain, self, NULL,
nil, nil,
NSLocalizedString( @"There's no new version available.",
@"no new version available dialog text" ) );
}
}
// --------------------------------------------------------------------------------------------------------------
// workhorses
- (void)alertForNonExistentUser: (NSString *)user{
NSBeginAlertSheet(
NSLocalizedString( @"User does not exist", @"user doesn't exist warning in open failure alert sheet" ),
NSLocalizedString( @"OK", @"Ok in dialog" ),
nil, nil, winMain, winMain, NULL, NULL, nil,
NSLocalizedString( @"I couldn't find a home directory for '%@' on your system. Maybe you mistyped the name or (god no!) deleted the directory. Better have look...", @"Home directory not found warning in open failure alert sheet" ),
user );
}
- (void)loadCrontab {
[ self loadCrontabForUser: nil ];
}
- (void)loadCrontabForUser: (NSString *)user {
if ( ! user || [ user isEqualToString: NSUserName() ] ) {
[ self loadCrontabForDefaultUser ];
} else if ( [ user isEqualToString: @"system" ] ) {
[ self openSystemCrontab ];
return;
} else {
NSMutableArray *args = [ NSMutableArray array ];
NSString *cronString;
BLAuthentication *authObj = [ BLAuthentication sharedInstance ];
// best solution found to test for user existence
NSString *userHome = NSHomeDirectoryForUser( user );
if ( ! userHome ) {
[ self alertForNonExistentUser: user ];
return;
}
//NSLog( @"Loading for user %@", user );
[ args addObject: @"-u" ];
[ args addObject: user ];
[ args addObject: @"-l" ];
cronString = [ authObj executeCommand: [ self suCronCommand ] withArgs: args ];
//NSLog( @"------- Received cronstring of length: %i", [ cronString length ] );
//NSLog( cronString );
if ( [ cronString length ] != 0 ) {
NSData *cronData = [ NSData dataWithData: [ cronString dataUsingEncoding: [ NSString defaultCStringEncoding ] ] ];
[ self clearCrontab ];
[ self setCrontabForUser: user ]; // setting this before parsing is important!
[ self parseCrontab: cronData ];
[ self setDirty: NO ];
//NSLog( @"Opened for user: %@", user );
} else {
NSBeginAlertSheet(
NSLocalizedString( @"Empty Crontab", @"empty crontab alert sheet" ),
NSLocalizedString( @"OK", @"Ok in dialog" ),
nil, nil, winMain, winMain, NULL, NULL, nil,
NSLocalizedString( @"The system returned an empty crontab for '%s'. This probably just means that there's no crontab for this user yet. Pressing OK will allow you to edit and install a new crontab and you will never see this alert sheet again. If, however, you are sure that '%s' does have a crontab, then you may have encountered an temporal anomaly. Contact the author (see the About box) and complain like there's no tomorrow.", @"descriptive text in empty crontab alert sheet (make sure translations preserve the sarcastic tone ;-)" ),
[ user cString ], [ user cString ] );
[ self clearCrontab ];
[ self setCrontabForUser: user ];
[ self setDirty: NO ];
}
}
}
// new still testing
- (void)loadCrontabForDefaultUser {
int status;
NSTask *task;
NSMutableArray *args = [ NSMutableArray array ];
NSPipe *stdOutPipe = [ NSPipe pipe ];
NSPipe *stdErrPipe = [ NSPipe pipe ];
NSFileHandle *stdOutReadHandle = [ stdOutPipe fileHandleForReading ];
NSFileHandle *stdErrReadHandle = [ stdErrPipe fileHandleForReading ];
NSData *cronData;
NSData *stdErrData;
NSString *stdErrString;
[ args addObject: @"-l" ];
task = [[ NSTask alloc ] init ];
[ task setCurrentDirectoryPath: @"." ];
[ task setLaunchPath: cronCommand ];
[ task setArguments: args ];
[ task setStandardOutput: stdOutPipe ];
[ task setStandardError: stdErrPipe ];
[ task launch ];
[ task waitUntilExit ];
cronData = [ [ NSData alloc ] initWithData :[ stdOutReadHandle readDataToEndOfFile ] ];
stdErrData = [ [ NSData alloc ] initWithData :[ stdErrReadHandle readDataToEndOfFile ] ];
status = [ task terminationStatus ];
[ task release ];
stdErrString = [ [ NSString alloc ] initWithData: stdErrData encoding: [ NSString defaultCStringEncoding ] ];
// Check for "no crontab for" in stderr: If we get this, this user doesn't have a crontab, yet. Not a problem,
// we just parse the empty cronData below.
if ( [ stdErrString isLike: @"*no crontab for*" ] ) {
status = 0; // set status OK
}
switch ( status ) {
case 0: // everything ok
[ self clearCrontab ];
[ self setCrontabForUser: nil ];
[ self parseCrontab: cronData ];
[ self setDirty: NO ];
break;
case 1: // failure (not privileged)
NSBeginAlertSheet(
NSLocalizedString( @"Failure", @"open failure alert sheet" ),
NSLocalizedString( @"OK", @"Ok in dialog" ),
nil, nil, winMain, winMain, NULL, NULL, nil,
NSLocalizedString( @"Something prevented me from reading your crontab - maybe some ion storm in the asteroid belt. See if it's that and fix it or otherwise mail the author (see the About box) and complain like there's no tomorrow.", @"descriptive text in generic failure alert sheet. Try to get fatalism and ignorance across in translation..." ) );
//[ self setCrontabForUser: nil ];
break;
}
[ cronData release ];
[ stdErrData release ];
[ stdErrString release ];
}
- (void)clearCrontab {
[ crTable deselectAll: nil ];
[ currentCrontab clear ];
[ crTable reloadData ];
[[ envVariablesNibController sharedInstance ] clear ];
[ infoTextField setStringValue: @"" ];
[ self setDirty: NO ];
}
- (void)showUserColumn {
int commandColPos = [ crTable columnWithIdentifier: [ commandColumn identifier ]];
if ( [ crTable columnWithIdentifier: [ userColumn identifier ]] == -1 ) {
[ crTable addTableColumn: userColumn ];
}
if ( commandColPos < [ crTable columnWithIdentifier: [ userColumn identifier ]] )
[ crTable moveColumn: [ crTable columnWithIdentifier: [ userColumn identifier ]]
toColumn: commandColPos ];
}
- (void)hideUserColumn {
if ( [ crTable columnWithIdentifier: [ userColumn identifier ]] != -1 )
[ crTable removeTableColumn: userColumn ];
}
- (void)parseCrontab: (NSData *)data {
//[ currentCrontab autorelease ];
[ currentCrontab release ]; // culprit, but why???
currentCrontab = [[ Crontab alloc ] initWithData: data forUser: [ self crontabForUser ] ];
[ crTable reloadData ];
[[ envVariablesNibController sharedInstance ] setCrontab: currentCrontab ];
[ self isSystemCrontab ] ? [ self showUserColumn ] : [ self hideUserColumn ];
}
- (void)openCrontabFromFile: (NSString *)path {
[ currentCrontab release ];
currentCrontab = [[ Crontab alloc ] initWithContentsOfFile: path forUser: NSUserName() ];
[ self setCrontabForUser: nil ];
[ crTable reloadData ];
[[ envVariablesNibController sharedInstance ] setCrontab: currentCrontab ];
[ self setDirty: NO ];
}
- (id)defaultTask {
NSString *string;
NSString *cmd = NSLocalizedString( @"echo \"Happy New Year!\"",
@"default command for new crontab tasks" );
if ( [ self isSystemCrontab ] ) {
string = [NSString stringWithFormat: @"0 0 1 1 * root %@", cmd];
} else {
string = [NSString stringWithFormat: @"0 0 1 1 * %@", cmd];
}
TaskObject *task = [[TaskObject alloc] initWithString: string
forSystem: [self isSystemCrontab]];
return [task autorelease];
}
- (void)newLineWithCommand: (NSString *)cmd {
id task = [self defaultTask];
[task setCommand: cmd];
[self newLineWithTask: task];
}
- (void)newLine {
[self newLineWithTask: [self defaultTask]];
}
- (void)newLineWithDialog {
[ crTable deselectAll: nil ];
id dialog = [[ NewTaskDialogController alloc ] initWithTask: [self defaultTask]];
//[ NewTaskDialogController sharedInstance ];
[ dialog modalForWindow: [ self window ] ];
}
- (void)newLineWithTask: (TaskObject *)aTask {
if ( [ self isSystemCrontab ] )
[ aTask setUser: @"root" ];
[ currentCrontab addTask: aTask ];
[ crTable reloadData ];
[ crTable selectRow: [ currentCrontab indexOfTask: aTask ] byExtendingSelection: NO ];
[ self setDirty: YES ];
}
- (void)editSelectedTask: (id)sender {
[ self editSelectedTask ];
}
- (void)editSelectedTask {
id task = [ self selectedTask ];
id dialog = [[ EditTaskDialogController alloc ] initWithTask: task ];
//[ EditTaskDialogController sharedInstanceWithTask: task ];
[ dialog modalForWindow: [ self window ]];
}
- (void)insertProgramWithString: (NSString *)path {
int row = [ crTable selectedRow ];
NSMutableString *cmd;
//NSLog( @"adding %@", path );
if ( [ path isLike: @"* *" ] )
cmd = [ NSString stringWithFormat: @"/usr/bin/open \"%s\"", [ path cString ] ];
else
cmd = [ NSString stringWithFormat: @"/usr/bin/open %s", [ path cString ] ];
if ( row == -1 ) { // new line
[ self newLineWithCommand: cmd ];
} else { // modify existing line
[ [ currentCrontab taskAtIndex: row ] setObject: cmd forKey: @"Command" ];
}
[ self setDirty: YES ];
}
- (void)removeLine {
[ self removeLinesInList: [ crTable selectedRowEnumerator ]];
}
- (void)removeLinesInList: (NSEnumerator *)list {
id item;
list = [[ list allObjects ] reverseObjectEnumerator ];
while ( item = [ list nextObject ] ) {
[ currentCrontab removeTaskAtIndex: [ item intValue ] ];
}
[ crTable reloadData ];
if ( [crTable selectedRow] != -1 )
[self showInfoForTask: [crTable selectedRow]];
[ self setDirty: YES ];
}
- (void)replaceLineAtRow: (int)row withObject: (id)obj {
if ( row < 0 || row > [ crTable numberOfRows ]-1 ) {
NSBeep();
return;
}
[ currentCrontab replaceTaskAtIndex: row withTask: obj ];
[ crTable reloadData ];
[ self setDirty: YES ];
}
- (void)duplicateLinesInList: (NSEnumerator *)list {
id index;
BOOL firstInList = YES;
int insertionPoint = 0;
int listCount = 0;
list = [[ list allObjects ] reverseObjectEnumerator ];
while ( index = [ list nextObject ] ) {
if ( firstInList ) {
insertionPoint = [ index intValue ] +1;
firstInList = NO;
}
id duplicate = [ TaskObject taskWithTask: [ currentCrontab taskAtIndex: [ index intValue ]]];
[ currentCrontab insertTask: duplicate atIndex: insertionPoint ];
listCount++;
}
[ crTable reloadData ];
[ self setDirty: YES ];
// select the newly created rows
[ crTable selectRow: insertionPoint byExtendingSelection: NO ];
int i;
for ( i = 1; i < listCount; i++ ) {
[ crTable selectRow: insertionPoint +i byExtendingSelection: YES ];
}
}
- (int)writeSystemCrontab {
NSPipe *pipe = [ NSPipe pipe ];
NSFileHandle *writeHandle = [ pipe fileHandleForWriting ];
NSData *cronData = [ currentCrontab data ];
NSMutableArray *args = [ NSMutableArray array ];
BLAuthentication *authObj = [ BLAuthentication sharedInstance ];
[ args addObject: @"/etc/crontab" ];
[ writeHandle writeData: cronData ];
[ writeHandle closeFile ];
[ authObj executeCommand: @"/usr/bin/tee" withArgs: args withPipe: pipe ];
// error handling???
return 0;
}
- (int)writeUserCrontab {
NSPipe *pipe = [ NSPipe pipe ];
NSFileHandle *writeHandle = [ pipe fileHandleForWriting ];
NSData *cronData = [ currentCrontab data ];
NSMutableArray *args = [ NSMutableArray array ];
BLAuthentication *authObj = [ BLAuthentication sharedInstance ];
[ args addObject: [ NSString stringWithFormat: @"-u" ] ];
[ args addObject: [ self crontabForUser ] ];
[ args addObject: @"-" ];
//NSLog( @"Writing for user: %@", [ self loadedForUser ] );
[ writeHandle writeData: cronData ];
[ writeHandle closeFile ];
[ authObj executeCommand: [ self suCronCommand ] withArgs: args withPipe: pipe ];
// error handling???
return 0;
}
- (int)writeStandardCrontab {
NSPipe *pipe = [ NSPipe pipe ];
NSFileHandle *writeHandle = [ pipe fileHandleForWriting ];
NSData *cronData = [ currentCrontab data ];
NSTask *task;
int status;
NSMutableArray *args = [ NSMutableArray array ];
[ args addObject: @"-" ];
task = [[ NSTask alloc ] init ];
[ task setCurrentDirectoryPath: @"." ];
[ task setLaunchPath: cronCommand ];
[ task setArguments: args ];
[ task setStandardInput: pipe ];
[ task launch ];
if ( [ task isRunning ] ) {
[ writeHandle writeData: cronData ];
[ writeHandle closeFile ];
}
[ task waitUntilExit ];
status = [ task terminationStatus ];
[ task release ];
return status;
}
// 2.0
- (void)writeCrontab {
int status;
//NSLog( "write:\n%s", [ [ cronData description ] cString ] );
//return;
if ( [ self isSystemCrontab ] ) {
status = [ self writeSystemCrontab ];
} else if ( [ self crontabForUser ] ) {
status = [ self writeUserCrontab ];
} else {
status = [ self writeStandardCrontab ];
}
//NSLog( @"writeCrontab status: %i", status );
switch ( status ) {
case 0: // everything ok
[ self setDirty: NO ];
break;
case 1: // not privileged to open with username
if ( [ self crontabForUser ] ) {
NSBeginAlertSheet(
NSLocalizedString( @"Failure", @"write failure alert sheet" ),
NSLocalizedString( @"OK", @"Ok in dialog" ),
nil, nil, winMain, winMain, NULL, NULL, nil,
NSLocalizedString( @"Insufficient privileges to write crontab for user \"%s\".", @"descriptive text in write failure alert sheet" ),
[ [ self crontabForUser ] cString ] );
} else {
NSBeginAlertSheet(
NSLocalizedString( @"Failure", @"write failure alert sheet" ),
NSLocalizedString( @"OK", @"Ok in dialog" ),
nil, nil, winMain, winMain, NULL, NULL, nil,
NSLocalizedString( @"Insufficient privileges to write crontab.", @"descriptive text in write failure alert sheet" ) );
}
break;
}
}
- (void)exportCrontab: (id)sender {
NSSavePanel *savePanel = [ NSSavePanel savePanel ];
[ savePanel setPrompt: NSLocalizedString( @"Export", @"Export dialog button title" ) ];
int result = [ savePanel runModalForDirectory: NSHomeDirectory()
file: [ NSString stringWithFormat: @"%@.crontab", NSLocalizedString( @"untitled", @"new crontab file name" ) ]];
if ( result == NSFileHandlingPanelOKButton ) {
NSString *filename = [ savePanel filename ];
BOOL success = [[ self currentCrontab ] writeAtPath: filename ];
if ( ! success ) {
NSBeginAlertSheet(
NSLocalizedString( @"Export failure",
@"Export failure sheet title" ),
NSLocalizedString( @"Darn!",
@"Export failure acknowledgement button title" ),
nil,
nil,
winMain, self, NULL,
nil, nil,
NSLocalizedString( @"Could not export crontab. Are you sure you have a hard drive?",
@"export failure dialog text" ) );
}
}
}
- (void)importCrontab: (id)sender {
[ self crontabShouldImport ];
}
- (void)importCrontab {
NSOpenPanel *openPanel = [ NSOpenPanel openPanel ];
[ openPanel setAllowsMultipleSelection: NO ];
[ openPanel setPrompt: NSLocalizedString( @"Import", @"Import file dialog: alternative label for open button" ) ];
NSArray *fileTypes = [NSArray arrayWithObject:@"crontab"];
int result = [ openPanel runModalForDirectory: NSHomeDirectory() file: nil types: fileTypes ];
if (result == NSOKButton) {
NSString *filename = [ openPanel filename ];
[ self openCrontabFromFile: filename ];
// set the dirty flag after importing
[ self setDirty: YES ];
}
}
- (void)setupUserColumn {
NSLog( @"Setting up userColumn" );
userColumn = [ [ NSTableColumn alloc ] initWithIdentifier: @"User" ];
[ [ userColumn headerCell ] setStringValue: @"User" ];
[ userColumn setWidth: 50 ];
[ [ userColumn headerCell ] setFont: [NSFont systemFontOfSize:[NSFont systemFontSize]] ];
[ [ userColumn headerCell ]
setTitle: NSLocalizedString( @"User", @"Column title for extra column in system crontab. Generated programmatically (i.e. not in a nib) with width: 50" ) ];
// [ crTable addTableColumn: userColumn ];
// [ crTable moveColumn: [ crTable numberOfColumns ] -1 toColumn: [ crTable numberOfColumns ] -2 ];
// [ userColumn release ];
}
// Setting up the "Active" column
- (void)setupActiveColumn {
NSTableColumn *col = [[ crTable tableColumns] objectAtIndex: 0];
NSButtonCell *cell = [[NSButtonCell alloc] init];
//SwitchFormatter *formatter = [ [ SwitchFormatter alloc ] init ];
//[ cell setFormatter: formatter ];
[ cell setButtonType: NSSwitchButton ];
[ cell setAction: @selector(activeButtonToggled) ];
[ cell setTarget: self ];
[ col setDataCell: cell ];
[ cell release ];
//[ formatter release ];
}
// --------------------------------------------------------------------------------------------------------------
// accessors
- (id)mainWindow {
return winMain;
}
- (id)window {
return winMain;
}
- (BOOL)isDirty {
return isDirty;
}
- (void)setDirty: (BOOL)value {
isDirty = value;
}
- (void)documentModified: (NSNotification *)notification {
[ self setDirty: YES ];
}
- (void)userSelected: (NSNotification *)notification {
loadCrontabController *lcc = [ loadCrontabController sharedInstance ];
NSString *username = [ lcc username ];
int returnCode = [ lcc returnCode ];
switch ( returnCode ) {
case 0: // cancel
break; // don't do anything
case 1: // load
if ( username ) [ self loadCrontabForUser: username ];
break;
case 2: // default
[ self loadCrontabForUser: nil ]; // load for default user
break;
}
}
- (void)taskCreated: (NSNotification *)notification {
[ self newLineWithTask: [ notification object ]];
}
- (void)taskEdited: (NSNotification *)notification {
[ self replaceLineAtRow: [ self selectedRow ] withObject: [ notification object ]];
}
- (BOOL)validateMenuItem: (id <NSMenuItem>)menuItem {
if ( [ menuItem isEqual: mSave ] ) {
return [ self isDirty ];
}
if ( [ menuItem isEqual: duplicateMenuItem ] ) {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] )
return [ crTable selectedRow ] != -1; // validate if a row is selected
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
return [ [ envVariablesNibController sharedInstance ] selectedRow ] != -1;
}
if ( [ menuItem isEqual: deleteMenuItem ] ) {
if ( [ [ NSApp keyWindow ] isEqual: winMain ] )
return [ crTable selectedRow ] != -1; // validate if a row is selected
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
return [ [ envVariablesNibController sharedInstance ] selectedRow ] != -1;
}
if ( [ menuItem isEqual: showHideMenuItem ] ) {
BOOL isVisible = YES;
if ( [ [ NSApp keyWindow ] isEqual: winMain ] )
isVisible = [ toolbar isVisible ];
if ( [ [ NSApp keyWindow ] isEqual: [ self envVarWindow ] ] )
isVisible = [ [ [ envVariablesNibController sharedInstance ] toolbar ] isVisible ];
isVisible ? [ menuItem setTitle: NSLocalizedString( @"Hide Toolbar", @"Hide toolbar menu item label" ) ] : [ menuItem setTitle: NSLocalizedString( @"Show Toolbar", @"Show toolbar menu item label" ) ];
}
if ( [ menuItem isEqual: runNowMenuItem ] ) {
return [ crTable selectedRow ] != -1;
}
if ( [ menuItem isEqual: editTaskMenuItem ] ) {
return [ crTable selectedRow ] != -1;
}
if ( [[ menuItem menu ] isEqual: contextMenu ] ) {
return [ crTable selectedRow ] != -1;
}
return YES;
}
- (NSString *)crontabForUser {
return crontabForUser;
}
- (void)setCrontabForUser: (NSString *)user {
[ crontabForUser autorelease ];
if ( user ) {
crontabForUser = [ user copy ];
//[ labelUser setStringValue: crontabForUser ];
[ toolbar setUser: crontabForUser ];
} else {
crontabForUser = nil;
//[ labelUser setStringValue: NSUserName() ];
[ toolbar setUser: NSUserName() ];
}
}
- (NSString *)suCronCommand {
return [ [ NSBundle mainBundle ] pathForResource: suCrontabResource ofType: nil ];
}