-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathPEController-2.4.0.m
executable file
·1487 lines (1266 loc) · 51.5 KB
/
PEController-2.4.0.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
// PEController.m
// PermanentEraser
//
// Created by Chad Armstrong on Mon Jun 02 2003.
// Copyright (c) 2003-2007 Edenwaith. All rights reserved.
//
// How to add a badge using Cocoa
// http://www.cocoabuilder.com/archive/message/cocoa/2004/2/3/95988
// How to add a Hot Key using Cocoa
// http://www.unsanity.org/archives/2002_10.php
// Description of the Mac OS X version of statfs
// http://developer.apple.com/documentation/Darwin/Reference/Manpages/man2/statfs.2.html
// Erasing free space examples
// EXAMPLE 1
// nice -n 20 dd bs=50m if=/dev/random of=/tmp/$UID/temp.$$ count=1
// nice -n 20 srm -z /tmp/$UID/temp.$$
//
// EXAMPLE 2
// #!/bin/sh
//
// set +e +u
// dd if=/dev/urandom of=/tmp/_shred_free_space
// sync; sync
// srm /tmp/_shred_free_space
// sync; sync
// Time Machine Utility: http://fernlightning.com/doku.php?id=software:misc:tms
// Erase a CD-RW: hdiutil burn (-erase|-fullerase) -device (something or another...check into this)
// Also check out: drutil erase (quick | full)
// Also: diskutil eraseOptical [quick] device
// diskutil eraseOptical /dev/disk3
// diskutil also has other options, such as zeroDisk, randomDisk, etc.
// diskutil secureErase [freespace] level device
// The diskutil tip taken from the Erase Selected Disc AppleScript
// diskutil list -- lists out available discs & partitions
#import "PEController.h"
#import "NSEvent+ModifierKeys.h"
#import "NSMutableArray+utils.h"
@implementation PEController
// =========================================================================
// (void) init
// -------------------------------------------------------------------------
// Initialize variables and set up notifications.
// -------------------------------------------------------------------------
// Created: 2. June 2003 14:20
// Version: 12 June 2008 22:25
// =========================================================================
- (id) init
{
self = [super init];
fm = [NSFileManager defaultManager];
trash_files = [[NSMutableArray alloc] init];
pEraser = nil; // initialize the NSTask
files_were_dropped = NO;
uid = [[NSString alloc] initWithFormat:@"%d", getuid()];
originalIcon = [NSImage imageNamed:@"PE"];
end_angle = 90.0;
lastPercentageCD = 0;
totalFilesSize = 0;
firstTimeHere = YES;
wasCanceled = NO;
beepBeforeTerminating = YES;
prefs = [[NSUserDefaults standardUserDefaults] retain];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doneErasing:)
name:NSTaskDidTerminateNotification
object:nil];
// If the ALT/Option key is pressed when PE is launched, do not show
// the warning dialog. This is similar to holding down the Option
// key when selecting the Empty Trash menu from Finder.
if ([NSEvent isOptionKeyDown] == YES)
{
warnBeforeErasing = NO;
}
else
{
warnBeforeErasing = YES;
}
return self;
}
// =========================================================================
// (void) dealloc
// -------------------------------------------------------------------------
// Clean up after the program by deallocing space and unnotifying notifications
// -------------------------------------------------------------------------
// Created: 2. June 2003 14:20
// Version: 14. November 2004
// =========================================================================
- (void) dealloc
{
pEraser = nil;
[[NSNotificationCenter defaultCenter] removeObserver: self name: NSTaskDidTerminateNotification object: nil];
[pipe dealloc];
[pEraser dealloc];
[uid dealloc];
[trash_files dealloc];
[super dealloc];
}
// =========================================================================
// (void) appWillTerminateNotification: (NSNotification *)aNotification
// -------------------------------------------------------------------------
// Call this when the application is quitting. Clean up the app icon
// so the badge doesn't remain.
// -------------------------------------------------------------------------
// Created: 24 October 2005 20:57
// Version: 11 March 2007
// =========================================================================
- (void) appWillTerminateNotification: (NSNotification *)aNotification
{
NSImage *icon = [NSImage imageNamed:@"PE"];
[NSApp setApplicationIconImage:icon];
}
// =========================================================================
// (void) awakeFromNib
// -------------------------------------------------------------------------
// Brings focus to the window. Otherwise, it is greyed out when running.
// -------------------------------------------------------------------------
// Created: 2. June 2003 14:20
// Version: 1 November 2008 21:55
// =========================================================================
- (void) awakeFromNib
{
// [theWindow makeKeyAndOrderFront:self];
[theWindow setBackgroundColor:[NSColor colorWithCalibratedRed: 0.909 green: 0.909 blue: 0.909 alpha:1.0]];
// [theWindow setBackgroundColor:[NSColor colorWithCalibratedRed: 0.22 green: 0.22 blue: 0.22 alpha:1.0]];
[theWindow display]; // redraw the window to display the white background.
[theWindow center]; // center the window on the screen
[erasing_msg setStringValue:NSLocalizedString(@"PreparingMessage", nil)];
// Use a spinning indeterminate progress meter when retrieving the list of files
[indicator setIndeterminate: YES];
[indicator setUsesThreadedAnimation:YES];
[indicator startAnimation: self];
// retrieve preference value for warnBeforeErasing
// defaults write com.edenwaith.permanenteraser WarnBeforeErasing -bool NO
// defaults write com.edenwaith.permanenteraser WarnBeforeErasing -bool YES
if (warnBeforeErasing != NO)
{
if ([prefs objectForKey:@"WarnBeforeErasing"] != nil)
{
if ([prefs boolForKey:@"WarnBeforeErasing"] == YES)
{
warnBeforeErasing = YES;
}
else
{
warnBeforeErasing = NO;
}
}
else
{
warnBeforeErasing = YES;
// [prefs setBool:NO forKey: @"WarnBeforeErasing"];
}
}
if ([prefs objectForKey:@"BeepBeforeTerminating"] != nil)
{
if ([prefs boolForKey:@"BeepBeforeTerminating"] == YES)
{
beepBeforeTerminating = YES;
}
else
{
beepBeforeTerminating = NO;
}
}
else
{
beepBeforeTerminating = YES;
}
if ([prefs objectForKey: @"DiscErasingLevel"] != nil)
{
discErasingLevel = [[NSMutableString alloc] initWithString:[prefs objectForKey: @"DiscErasingLevel"]];
}
else
{
discErasingLevel = [[NSMutableString alloc] initWithString:@"Complete"];
}
if ([prefs objectForKey: @"FileErasingLevel"] != nil)
{
fileErasingLevel = [[NSMutableString alloc] initWithString:[prefs objectForKey: @"FileErasingLevel"]];
}
else
{
// Assign a default fileErasingLevel
}
}
// =========================================================================
// (void) applicationDidFinishLaunching: (NSNotification *)
// -------------------------------------------------------------------------
// Need to make the PEController a delegate of the File Owner
// -------------------------------------------------------------------------
// Created: 2. June 2003
// Version: 20 August 2007 22:00
// =========================================================================
- (void) applicationDidFinishLaunching: (NSNotification *) aNotification
{
if (files_were_dropped == YES)
{
[self erase];
}
else // Search for files in .Trash and .Trashes
{
BOOL isDir;
id object = nil;
int j = 0;
NSMutableString *currentDirectory = [[NSMutableString alloc] init];
NSDirectoryEnumerator *enumerator;
NSArray *volumes = [[NSArray alloc] initWithArray: [fm directoryContentsAtPath: @"/Volumes"]];
for (j = 0; j < [volumes count]; j++)
{
// Check to see if the .Trashes exist, and if so, get the contents
// of the .Trashes and add them to trash_files (full path)
[currentDirectory setString: [[[@"/Volumes/" stringByAppendingPathComponent: [volumes objectAtIndex: j]]
stringByAppendingPathComponent: @".Trashes"]
stringByAppendingPathComponent: uid]];
if ( [fm fileExistsAtPath: currentDirectory isDirectory:&isDir] && isDir )
{
enumerator = [fm enumeratorAtPath: currentDirectory];
while (object = [enumerator nextObject])
{
// check for bundled files, i.e. .app, .rtfd, etc.
if ( [fm fileExistsAtPath: [currentDirectory stringByAppendingPathComponent: object] isDirectory:&isDir] && isDir &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: [currentDirectory stringByAppendingPathComponent: object]] )
{
totalFilesSize += [self fileSize: [currentDirectory stringByAppendingPathComponent: object]];
[trash_files insertObject: [currentDirectory stringByAppendingPathComponent: object] atIndex:0];
[enumerator skipDescendents];
}
else
{
totalFilesSize += [self fileSize: [currentDirectory stringByAppendingPathComponent: object]];
// this will reverse the array so a directory will be erased last after it is empty
[trash_files insertObject: [currentDirectory stringByAppendingPathComponent: object] atIndex:0];
}
}
}
}
// Get the files in the home account's Trash
enumerator = [fm enumeratorAtPath:[@"~/.Trash/" stringByExpandingTildeInPath]];
while(object = [enumerator nextObject])
{
// check for bundled files, i.e. .app, .rtfd, etc.
if ( [fm fileExistsAtPath: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object] isDirectory:&isDir] && isDir &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object]] == YES )
{
// Generate a dictionary and insert that into the trash_files array
totalFilesSize += [self fileSize: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object]];
[trash_files insertObject: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object] atIndex:0];
[enumerator skipDescendents];
}
else
{
// Generate a dictionary and insert that into the trash_files array
totalFilesSize += [self fileSize: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object]];
// this will reverse the array so a directory will be erased last after it's empty
[trash_files insertObject: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object] atIndex:0];
}
}
[volumes dealloc];
[currentDirectory dealloc];
[self erase];
}
}
// =========================================================================
// (void) application:(NSApplication*) openFile:
// -------------------------------------------------------------------------
// This method is only called when a file is dragged-n-dropped onto the
// PE icon. The timer is called to add each of the new files.
// -------------------------------------------------------------------------
// Created: 21. April 2004
// Version: 20 August 2007 21:25
// =========================================================================
- (BOOL) application:(NSApplication *)theApplication openFile:(NSString *)filename
{
BOOL isDir;
BOOL isDir2;
id object = nil;
files_were_dropped = YES;
NSMutableDictionary *fileDict = [NSMutableDictionary dictionary];;
// Set this up to identify only burnable discs
if ([self isVolume: filename] == YES && [self isErasableDisc: filename])
{
[trash_files insertObject: filename atIndex: 0];
totalFilesSize += [self fileSize: filename];
}
else if ( [fm fileExistsAtPath: filename isDirectory:&isDir] && isDir &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: filename] == NO )
{
NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath: filename];
[trash_files insertObject: filename atIndex: 0]; // add the directory name
while (object = [enumerator nextObject])
{
if ( [fm fileExistsAtPath: [filename stringByAppendingPathComponent: object] isDirectory:&isDir2] && isDir2 &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: [filename stringByAppendingPathComponent: object]] == YES )
{
// [trash_files insertObject: [filename stringByAppendingPathComponent: object] atIndex:0];
[enumerator skipDescendents];
totalFilesSize += [self fileSize: [filename stringByAppendingPathComponent: object]];
}
else
{
/*
fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
filename, @"path",
[self fileSize:filename], @"size",
nil];
*/
[fileDict setObject: filename forKey: @"path"];
[fileDict setObject: [NSNumber numberWithInt: [self fileSize:filename]] forKey: @"size"];
// this will reverse the array so a directory will be erased last after it's empty
// [trash_files insertObject: [filename stringByAppendingPathComponent: object] atIndex:0];
[trash_files insertObject: fileDict atIndex: 0];
totalFilesSize += [self fileSize: [filename stringByAppendingPathComponent: object]];
}
}
}
else
{
/*
fileDict = [NSDictionary dictionaryWithObjectsAndKeys:
filename, @"path",
[self fileSize: filename], @"size",
nil];
*/
[fileDict setObject: filename forKey: @"path"];
[fileDict setObject: [NSNumber numberWithUnsignedLongLong: [self fileSize:filename]] forKey: @"size"];
unsigned long long fooblat = 3;
NSLog(@"The File size is %llu", [self fileSize: filename]);
[trash_files insertObject: fileDict atIndex: 0];
//totalFilesSize += [self fileSize: [filename stringByAppendingPathComponent: object]]; // No idea why it references "object" here
totalFilesSize += [self fileSize: filename];
}
if (!timer)
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.0
target: self
selector: @selector(addNewFiles:)
userInfo: nil
repeats: YES];
}
return NO;
}
// =========================================================================
// (int) fileSize: (NSString *) path
// -------------------------------------------------------------------------
// Created: 8 August 2007 20:59
// Version: 3 November 2008 20:28
// =========================================================================
- (unsigned long long) fileSize: (NSString *) path
{
// FSRef fsRef;
// FSCatalogInfo fsInfo;
// BOOL isDir;
NSDictionary *fileAttributes = [fm fileAttributesAtPath:[path stringByAppendingPathExtension:@"/..namedfork/rsrc/"] traverseLink:NO];
/*
if(FSPathMakeRef((unsigned char *) [path fileSystemRepresentation], &fsRef, NULL) == noErr)
{
if(FSGetCatalogInfo(&fsRef, kFSCatInfoRsrcSizes, &fsInfo, NULL, NULL, NULL) == noErr)
{
if (fsInfo.rsrcLogicalSize > 0)
{
return (fsInfo.dataLogicalSize + fsInfo.rsrcLogicalSize);
}
else
{
return (fsInfo.dataLogicalSize);
}
}
}
else
{
return (0);
}
*/
return (long long)([[fileAttributes objectForKey:NSFileSize] intValue]);
}
// =========================================================================
// (void) addNewFiles : (NSTimer *) aTimer
// -------------------------------------------------------------------------
// Add new files to the list of files that were dragged-n-dropped on the icon
// -------------------------------------------------------------------------
// Created: 30. March 2004 23:52
// Version: 30. March 2004 23:52
// =========================================================================
- (void) addNewFiles : (NSTimer *) aTimer
{
[aTimer invalidate];
timer = nil;
}
// =========================================================================
// (void) erase:
// -------------------------------------------------------------------------
// NSFileManager: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html
// NSDirectoryEnumerator: http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDirectoryEnumerator_Class/Reference/Reference.html
// -------------------------------------------------------------------------
// Unfortunately, all of the files in the Trash couldn't be erased at once.
// This error occurred: /bin/rm: /Users/admin/.Trash/*: No such file or directory
// [pEraser setArguments: [NSArray arrayWithObjects: @"-P", @"-r", [@"~/.Trash/*" stringByExpandingTildeInPath], nil]];
// -------------------------------------------------------------------------
// Created: 2. June 2003 14:20
// Version: 1 November 2008 22:08
// =========================================================================
- (void) erase
{
int number_of_real_files = 0;
int j = 0;
idx = 0;
num_files = 0;
num_files = [trash_files count];
// If srm already exists, use that version, which will help comply as
// a Universal Binary to use the PPC or Intel version of srm
if ([fm isExecutableFileAtPath: @"/usr/bin/srm"] == YES)
{
util_path = @"/usr/bin/srm";
}
else
{
util_path = [[NSBundle mainBundle] pathForResource:@"srm" ofType:@""];
}
// Count the number of files to delete
for (j = 0; j < num_files; j++)
{
if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath: [trash_files pathAtIndex: j]] == YES ) // if this file is a package, find the number of files contained within
{
// enumerate the package
NSDirectoryEnumerator *package_enumerator;
id object = nil;
BOOL isDir;
package_enumerator = [fm enumeratorAtPath: [trash_files objectAtIndex: j]];
while (object = [package_enumerator nextObject])
{
totalFilesSize += [self fileSize: [[trash_files objectAtIndex: j] stringByAppendingPathComponent: object]];
// Need to check if a file is a directory or not...if so, don't count it!
if ([fm fileExistsAtPath: [ [trash_files objectAtIndex: j] stringByAppendingPathComponent: object] isDirectory:&isDir] && isDir == NO)
{
if ([self containsResourceFork: [trash_files objectAtIndex: j]] == YES)
{
number_of_real_files+=2;
}
else
{
number_of_real_files++;
}
}
}
}
else
{
if ([self containsResourceFork: [trash_files pathAtIndex: j]] == YES)
{
number_of_real_files+=2;
}
else
{
number_of_real_files++;
}
}
}
[indicator setMaxValue: number_of_real_files*100];
[indicator setIndeterminate: NO];
[indicator stopAnimation: self];
[erasing_msg setStringValue:NSLocalizedString(@"ErasingMessage", nil)];
// Throw a warning about erasing files.
// Hold down the Option key when launching PE to prevent this warning from appearing.
if (warnBeforeErasing == YES)
{
int choice = 0;
if (files_were_dropped == YES && num_files == 1) // Erasing one files
{
choice = NSRunAlertPanel(NSLocalizedString(@"ErrorTitle", nil),
NSLocalizedString(@"ErasingFileWarning", nil), NSLocalizedString(@"OK", nil),
NSLocalizedString(@"Quit", nil), nil);
}
else if (files_were_dropped == YES && num_files > 1) // Erasing several files
{
choice = NSRunAlertPanel(NSLocalizedString(@"ErrorTitle", nil),
NSLocalizedString(@"ErasingFilesWarning", nil), NSLocalizedString(@"OK", nil),
NSLocalizedString(@"Quit", nil), nil);
}
else // Erasing files from the Trash
{
choice = NSRunAlertPanel(NSLocalizedString(@"ErrorTitle", nil),
NSLocalizedString(@"ErasingTrashWarning", nil), NSLocalizedString(@"OK", nil),
NSLocalizedString(@"Quit", nil), nil);
}
if (NSCancelButton == choice) // Quit button
{
[NSApp terminate:self];
}
}
if (idx < num_files)
{
[self selectNextFile];
}
else // there are no files
{
[self shutdownPE];
}
}
// =========================================================================
// (void) selectNextFile
// -------------------------------------------------------------------------
// Determine whether to erase a regular file, or to burn an optical disc
// -------------------------------------------------------------------------
// Created: 6 March 2007 20:10
// Version: 28 October 2008 22:38
// =========================================================================
- (void) selectNextFile
{
if ([self isVolume: [trash_files pathAtIndex: idx]] == YES && [self isErasableDisc: [trash_files pathAtIndex: idx]])
{
[self eraseDisc];
}
else
{
[self runTask];
}
}
// =========================================================================
// (void) eraseDisc
// -------------------------------------------------------------------------
// http://developer.apple.com/documentation/MusicAudio/Reference/DiscRecordingFrameworkRef/DRErase/Classes/DRErase/index.html#//apple_ref/occ/cl/DRErase
// NSLog(@"IORegistryEntry: %@", [[device info] objectForKey:DRDeviceIORegistryEntryPathKey]);
// -------------------------------------------------------------------------
// Created: 28 February 2007
// Version: 28 October 2008 22:38
// =========================================================================
- (void) eraseDisc
{
DRDevice* device;
DRErase* erase;
[progress_msg setStringValue: [self fileNameString]];
[fileIcon setImage:[[NSWorkspace sharedWorkspace] iconForFile:[trash_files pathAtIndex: idx]]];
device = [DRDevice deviceForBSDName: [self bsdDevNode: [trash_files pathAtIndex: idx]]];
if (device != nil)
{
erase = [[DRErase alloc] initWithDevice:device];
if ([discErasingLevel isEqualToString:@"Quick"])
{
[erase setEraseType:DREraseTypeQuick];
}
else
{
[erase setEraseType:DREraseTypeComplete];
}
// register to receive notification about the erase status.
[[DRNotificationCenter currentRunLoopCenter] addObserver:self
selector:@selector(eraseNotification:)
name:DREraseStatusChangedNotification
object:erase];
[cancelButton setEnabled:NO];
[cancelMenuItem setEnabled:NO];
[erase start];
}
else
{
NSRunAlertPanel(NSLocalizedString(@"ErrorTitle",nil), NSLocalizedString(@"ErrorDeletingDiscMessage",nil), NSLocalizedString(@"OK",nil), nil, nil);
// Continue on as if this was successful in erasing...
[indicator incrementBy: 100.0];
[self updateApplicationBadge];
[self doneErasing:nil];
}
}
// =========================================================================
// (void) eraseNotification: (NSNotification*) notification
// -------------------------------------------------------------------------
// Receive notifications while the optical disc is being erased
// -------------------------------------------------------------------------
// Created: 28 February 2007
// Version: 10 March 2007 23:12
// =========================================================================
- (void) eraseNotification: (NSNotification*) notification
{
// DRErase* erase = [notification object];
NSDictionary* status = [notification userInfo];
// States: DRStatusStatePreparing, DRStatusStateErasing, DRStatusStateDone, DRStatusStateFailed
if ([[status objectForKey: DRStatusStateKey] isEqualToString: @"DRStatusStateDone"])
{
// kick out of function, reset, clean up, and move onto the next file
[self doneErasing: nil];
}
else
{
int currentPercentageCD = [[status objectForKey: DRStatusPercentCompleteKey] floatValue] * 100;
if (currentPercentageCD < 0)
currentPercentageCD = 0;
else if (currentPercentageCD > 100)
currentPercentageCD = 100;
// Create an updateProgressBar method
if (currentPercentageCD >= lastPercentageCD)
{
[indicator incrementBy: currentPercentageCD - lastPercentageCD];
[indicator displayIfNeeded]; // force indicator to draw itself
}
else
{
[indicator incrementBy: 100 - currentPercentageCD];
[indicator displayIfNeeded]; // force indicator to draw itself
}
[fileSizeMsg setStringValue: [[[self formatFileSize: ([indicator doubleValue] / [indicator maxValue]) *totalFilesSize] stringByAppendingString: NSLocalizedString(@"of", nil)] stringByAppendingString: [self formatFileSize: (double)totalFilesSize]]];
[self updateApplicationBadge];
if (currentPercentageCD >= 100)
{
currentPercentageCD = 0;
lastPercentageCD = 0;
}
else
{
lastPercentageCD = currentPercentageCD;
}
// If the optical disc erasing failed...
if ([[status objectForKey: DRStatusStateKey] isEqualToString: @"DRStatusStateFailed"])
{
NSRunAlertPanel(NSLocalizedString(@"ErrorTitle",nil), NSLocalizedString(@"ErrorDeletingDiscMessage",nil), NSLocalizedString(@"OK",nil), nil, nil);
[self doneErasing: nil];
}
}
}
// =========================================================================
// (void) runTask
// -------------------------------------------------------------------------
// Set the NSTask parameters and launch the task. If a file is symbolic
// link, remove it with rm, because srm will try and remove the original
// file instead of the symbolic link.
// -------------------------------------------------------------------------
// Created: 4. April 2004 23:35
// Version: 6 November 2008 4:57
// =========================================================================
- (void) runTask
{
pEraser = [[NSTask alloc] init];
// If the file is a symbolic/soft link
if ([self isFileSymbolicLink: [trash_files pathAtIndex: idx]] == YES)
{
[pEraser setLaunchPath:@"/bin/rm"];
[pEraser setArguments: [NSArray arrayWithObjects: @"-Pv", [trash_files pathAtIndex: idx], nil] ];
}
else // regular file or directory
{
[pEraser setLaunchPath:util_path];
[pEraser setArguments: [NSArray arrayWithObjects: @"-fvrz", [trash_files pathAtIndex: idx], nil] ];
}
// Throw a warning if a file cannot be erased
if ([fm isDeletableFileAtPath:[trash_files pathAtIndex: idx]] == NO ||
[self checkPermissions: [trash_files pathAtIndex: idx]] == NO)
{
int choice = NSRunAlertPanel(NSLocalizedString(@"ErrorTitle", nil),
NSLocalizedString(@"ErrorDeletingMessage", nil), NSLocalizedString(@"OK", nil),
NSLocalizedString(@"Quit", nil), nil, [self currentFileName]);
if (choice == 0) // Quit button
{
[[NSApplication sharedApplication] terminate:self];
}
else
{
// Act like the file was erased and move on to the next file
[indicator incrementBy:100.0];
[indicator displayIfNeeded];
[ [NSNotificationCenter defaultCenter] postNotificationName: @"NSTaskDidTerminateNotification" object: self];
}
}
else
{
// NSFileHandle *handle;
BOOL isDir;
pipe = [[NSPipe alloc] init];
[progress_msg setStringValue: [self fileNameString]];
[fileIcon setImage:[[NSWorkspace sharedWorkspace] iconForFile:[trash_files pathAtIndex: idx]]];
[pEraser setStandardOutput:pipe];
[pEraser setStandardError:pipe];
handle = [pipe fileHandleForReading];
NSDictionary *fileAttributes = [fm fileAttributesAtPath:[trash_files pathAtIndex: idx] traverseLink:NO];
// If the file is locked by the Finder, unlock it before deleting.
if ([[fileAttributes objectForKey:NSFileImmutable] boolValue] == YES)
{
[fm changeFileAttributes: [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSFileImmutable] atPath:[trash_files pathAtIndex: idx]];
}
// If it is a directory or empty file, add 100 since it doesn't delete like normal files
if (([fm fileExistsAtPath: [trash_files pathAtIndex: idx] isDirectory:&isDir] && isDir &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: [trash_files pathAtIndex: idx]] == NO) )
{
[indicator incrementBy: 100.0]; // This was originally set to 99
}
else if ([[fileAttributes objectForKey:NSFileSize] intValue] == 0) // file is 0K in size
{
[indicator incrementBy: 100.0];
}
[pEraser launch];
[NSThread detachNewThreadSelector: @selector(outputData:) toTarget: self withObject: handle];
}
}
// =========================================================================
// (void) outputData: (NSFileHandle *) current_handle
// -------------------------------------------------------------------------
// Direct the output data sent from the task to be read by the program
// -------------------------------------------------------------------------
// Created: 25 October 2005 19:14
// Version: 13 November 2008 21:45
// =========================================================================
- (void) outputData: (NSFileHandle *) current_handle
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSData *data;
// unsigned int index = 0;
int lastPercentage = 0;
int currentPercentage = 0;
while ([data=[current_handle availableData] length])
{
NSString *string = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
NSString *modifiedString = [[NSString alloc] initWithString: [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
// What is setting index used for? Old, unused code, perhaps?
// if ([modifiedString length] < 4)
// {
// index = [modifiedString length];
// }
// else
// {
// index = 4;
// }
// stringByTrimmingCharactersInSet is a 10.2+ feature.
NSArray *splitString = [modifiedString componentsSeparatedByString: @"%"];
currentPercentage = [[splitString objectAtIndex: 0] intValue];
[string release];
if (currentPercentage >= lastPercentage)
{
[indicator incrementBy: currentPercentage - lastPercentage];
[indicator displayIfNeeded]; // force indicator to draw itself
}
else
{
[indicator incrementBy: 100 - currentPercentage];
[indicator displayIfNeeded]; // force indicator to draw itself
}
[fileSizeMsg setStringValue: [[[self formatFileSize: ([indicator doubleValue] / [indicator maxValue]) *totalFilesSize] stringByAppendingString: @" of "] stringByAppendingString: [self formatFileSize: (double)totalFilesSize]]];
[self updateApplicationBadge];
if (currentPercentage >= 100)
{
currentPercentage = 0;
lastPercentage = 0;
}
else
{
lastPercentage = currentPercentage;
}
}
[pool release];
}
// =========================================================================
// (NSString *) formatFileSize: (double) file_size
// -------------------------------------------------------------------------
//
// -------------------------------------------------------------------------
// Created: 8 August 2007 22:09
// Version: 16 July 2008 21:06
// =========================================================================
- (NSString *) formatFileSize: (double) file_size
{
NSString *file_size_label;
if ( (file_size / 1024) < 1.0)
file_size_label = @" bytes";
else if ((file_size / 1048576) < 1.0)
{
file_size = file_size / 1024;
file_size_label = @" KB";
}
else if ((file_size / 1073741824) < 1.0)
{
file_size = file_size / 1048576;
file_size_label = @" MB";
}
else
{
file_size = file_size / 1073741824;
file_size_label = @" GB";
}
return ([[NSString stringWithFormat: @"%.2f", file_size] stringByAppendingString:file_size_label]);
}
// =========================================================================
// - (void) updateApplicationBadge
// -------------------------------------------------------------------------
// http://www.macdevcenter.com/pub/a/mac/2001/10/19/cocoa.html?page=3
// [[NSColor colorWithCalibratedRed: 0.6 green: 0.6 blue: 0.8 alpha:1.0] set]; // create a custom color
// [[[NSColor orangeColor] colorWithAlphaComponent:0.7] set];
// -------------------------------------------------------------------------
// Created: November 2005
// Version: 19 November 2006 16:27
// =========================================================================
- (void) updateApplicationBadge
{
NSImage *icon = [NSImage imageNamed:@"NSApplicationIcon"];
NSRect r = NSMakeRect(90.0, 10.0, 32.0, 32.0);
NSRect r2 = NSMakeRect(88.0, 5.0, 36.0, 35.0);
[icon lockFocus];
// Draw the badge image
end_angle = 90.0 - ([indicator doubleValue] / [indicator maxValue]) * 360;
NSBezierPath *bp = [NSBezierPath bezierPathWithOvalInRect:r];
NSBezierPath *bp2 = [NSBezierPath bezierPath];
if (firstTimeHere == YES)
{
firstTimeHere = NO;
// Draw the shadow behind the progress badge
NSBezierPath *bp3 = [NSBezierPath bezierPathWithOvalInRect:r2];
[[[NSColor blackColor] colorWithAlphaComponent:0.3] set];
[bp3 fill];
// If the background orange and white circle is drawn only once at
// this point, the outside edges are smoother, but the progress
// meter inside becomes very jagged.
}
// Draw the background circle (white background with an orange edge)
[bp setLineWidth: 5.0];
[bp setFlatness:0.1]; // This smooths the edges by a bit
[[NSColor orangeColor] set];
[bp stroke];
[[NSColor whiteColor] set];
[bp fill];
// Draw the progress meter
[bp2 moveToPoint:NSMakePoint(106.0, 26.0)];
[bp2 lineToPoint:NSMakePoint(106.0, 43.0)];
[bp2 appendBezierPathWithArcWithCenter: NSMakePoint(106.0, 26.0) radius: 17.0 startAngle: 90.0 endAngle: end_angle clockwise: YES];
[[NSColor orangeColor] set];
[bp2 fill];
[icon unlockFocus];
[NSApp setApplicationIconImage:icon];
// Clean up the icon before the application quits
if (!registeredForTerminate)
{
registeredForTerminate = YES;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appWillTerminateNotification:)
name:NSApplicationWillTerminateNotification
object:NSApp];
}
}
// =========================================================================
// (NSString *) currentFileName
// -------------------------------------------------------------------------
// Retrieve the short version of the current file (i.e. "foo.txt") being
// deleted (so no full path).
// -------------------------------------------------------------------------
// Created: 9 October 2005 17:30
// Version: 9 October 2005 17:30
// =========================================================================
- (NSString *) currentFileName
{
return ([[trash_files pathAtIndex: idx] lastPathComponent]);
}