-
Notifications
You must be signed in to change notification settings - Fork 5
/
PEController.m
executable file
·2216 lines (1898 loc) · 78.4 KB
/
PEController.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-2015 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 "PreferencesController.h"
@implementation PEController
// =========================================================================
// (id) init
// -------------------------------------------------------------------------
// Initialize variables and set up notifications.
// -------------------------------------------------------------------------
// Created: 2. June 2003 14:20
// Version: September 2009
// =========================================================================
- (id) init
{
self = [super init];
fm = [NSFileManager defaultManager];
trash_files = [[NSMutableArray alloc] init];
badge = [[CTProgressBadge alloc] init];
pEraser = nil; // initialize the NSTask
preparationThread = nil;
filesWereDropped = NO;
uid = [[NSString alloc] initWithFormat:@"%d", getuid()];
// uid = [NSString stringWithFormat: @"%d", getuid()]; // This has issues and doesn't save properly on Mac OS 10.3 and 10.4
// uid = [[NSNumber numberWithInt: getuid()] stringValue];
originalIcon = [NSImage imageNamed:@"PE"];
end_angle = 90.0;
lastPercentageCD = 0;
totalFilesSize = 0;
firstTimeHere = YES;
wasCanceled = NO;
beepBeforeTerminating = YES;
suppressCannotEraseWarning = NO;
isCurrentlyErasingDisc = NO;
prefs = [[NSUserDefaults standardUserDefaults] retain];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(doneErasing:)
name:NSTaskDidTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(privilegedTaskFinished:)
name:STPrivilegedTaskDidTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appWillTerminateNotification:)
name:NSApplicationWillTerminateNotification
object:NSApp];
// 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;
suppressCannotEraseWarning = YES;
}
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: 26 March 2018 21:50
// =========================================================================
- (void) dealloc
{
// Remove all observed notifications, such as NSTaskDidTerminateNotification, STPrivilegedTaskDidTerminateNotification,
// NSApplicationWillTerminateNotification, etc.
[[NSNotificationCenter defaultCenter] removeObserver: self];
[badge release];
[pipe release];
[pEraser release];
pEraser = nil;
[uid release];
[trash_files release];
if (privilegedTask != nil)
{
[privilegedTask release];
privilegedTask = nil;
}
if (preparationThread != nil)
{
[preparationThread release];
preparationThread = nil;
}
[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: 10 December 2016 22:00
// =========================================================================
- (void) awakeFromNib
{
[NSApp activateIgnoringOtherApps:YES]; // Bring app to foreground
[theWindow setBackgroundColor:[NSColor colorWithCalibratedRed: 0.909 green: 0.909 blue: 0.909 alpha:1.0]];
[theWindow display]; // redraw the window to display the light grey background.
[theWindow center]; // center the window on the screen
[erasingMsg 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];
// Since the indicator has different heights, depending on the version of Mac OS X,
// Adjust the y coordinate for cancelButton to align with the indicator
NSRect cancelButtonFrame = [cancelButton frame];
float updatedCancelButtonY = cancelButtonFrame.origin.y;
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 10, 0}] == YES)
{ // Yosemite and later
cancelButtonFrame.origin.y = updatedCancelButtonY-2.0;
[cancelButton setFrame: cancelButtonFrame];
}
else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 7, 0}] == YES)
{ // Lion through Mavericks
cancelButtonFrame.origin.y = updatedCancelButtonY-2.5;
[cancelButton setFrame: cancelButtonFrame];
}
// 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;
}
}
if ([prefs objectForKey:@"BeepBeforeTerminating"] != nil)
{
if ([prefs boolForKey:@"BeepBeforeTerminating"] == YES)
{
beepBeforeTerminating = YES;
}
else
{
beepBeforeTerminating = NO;
}
}
else
{
beepBeforeTerminating = YES;
}
if ([prefs objectForKey: @"OpticalDiscErasingLevel"] != nil)
{
discErasingLevel = [[NSMutableString alloc] initWithString:[prefs objectForKey: @"OpticalDiscErasingLevel"]];
}
else
{
discErasingLevel = [[NSMutableString alloc] initWithString:@"Complete"];
}
if ([prefs objectForKey: @"FileErasingLevel"] != nil)
{
fileErasingLevel = [[NSMutableString alloc] initWithString:[prefs objectForKey: @"FileErasingLevel"]];
}
else
{
// Assign a default fileErasingLevel
}
[self checkInstalledPlugins];
}
// =========================================================================
// (void) applicationDidFinishLaunching: (NSNotification *)
// -------------------------------------------------------------------------
// Need to make the PEController a delegate of the File Owner
// -------------------------------------------------------------------------
// Created: 2. June 2003
// Version: 30 November 2014 20:39
// =========================================================================
- (void) applicationDidFinishLaunching: (NSNotification *) aNotification
{
if (filesWereDropped != YES) // Search for files in .Trash and .Trashes
{
NSBundle *dockBundle = [NSBundle bundleWithPath:@"/System/Library/CoreServices/Dock.app"];
if (dockBundle != nil)
{
NSString *trashFullPath = [dockBundle pathForResource:@"trashfull" ofType:@"png"];
if (trashFullPath != nil)
{
NSImage *trashFullImage = [[NSImage alloc] initWithContentsOfFile:trashFullPath];
[fileIcon setImage: trashFullImage];
[trashFullImage release];
}
}
// Use the enumerator to try and read from the local Trash, which will hopefully pre-populate
// this app in the Full Disk Access list.
NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath:[@"~/.Trash/" stringByExpandingTildeInPath]];
// Need to check if the ap can read from the user's local ~/.Trash. If it is not possible to see the files
// in the user's local Trash, the app probably requires Full Disk Access to be enabled (in macOS Catalina and later)
// Instruct the user to enable Full Disk Access and then quit the app.
if ([[enumerator allObjects] count] == 0 && [fm isReadableFileAtPath:[@"~/.Trash" stringByExpandingTildeInPath]] == NO)
{
NSAlert *alert = [NSAlert alertWithMessageText: NSLocalizedString(@"ErrorTitle", nil)
defaultButton: NSLocalizedString(@"OpenSecurityPreferences", nil)
alternateButton: NSLocalizedString(@"Quit", nil)
otherButton: nil
informativeTextWithFormat: NSLocalizedString(@"CannotAccessTrash", nil)];
// This takes the user to the Enable Full Disk Access section in the Help files
[alert setHelpAnchor:@"full-disk-access-help"];
[alert setShowsHelp: YES];
[alert setAlertStyle: NSCriticalAlertStyle];
[alert beginSheetModalForWindow: theWindow modalDelegate:self didEndSelector:@selector(fullDiskAccessAlertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
else
{
// Perhaps consider naming the thread...
preparationThread = [[NSThread alloc] initWithTarget:self selector:@selector(prepareFiles) object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(preparationFinished:)
name:NSThreadWillExitNotification
object:preparationThread];
[preparationThread start];
}
}
}
// =========================================================================
// (void) prepareFiles
// -------------------------------------------------------------------------
// Prepare the files in the Trash(es) to be erased
// -------------------------------------------------------------------------
// Crreated: 10 December 2014 22:22
// =========================================================================
- (void) prepareFiles
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BOOL isDir;
id object = nil;
int j = 0;
NSDirectoryEnumerator *enumerator;
NSArray *volumes = [[NSWorkspace sharedWorkspace] mountedLocalVolumePaths];
// Note: It seems that it thinks that .DS_Store is also a volume. Avoid this.
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)
NSString *currentDirectory = [NSString stringWithString: [[[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]] )
{
[self addFileToArray: [currentDirectory stringByAppendingPathComponent: object]];
[enumerator skipDescendents];
}
else
{
totalFilesSize += [fm fileSize: [currentDirectory stringByAppendingPathComponent: object]];
// this will reverse the array so a directory will be erased last after it is empty
[self addFileToArray: [currentDirectory stringByAppendingPathComponent: object]];
}
}
}
}
// 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
[self addFileToArray: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object]];
[enumerator skipDescendents];
}
else
{
// Generate a dictionary and insert that into the trash_files array
// this will reverse the array so a directory will be erased last after it's empty
[self addFileToArray: [[@"~/.Trash/" stringByExpandingTildeInPath] stringByAppendingPathComponent: object]];
}
}
[pool release];
[NSThread exit];
}
// =========================================================================
// (void)preparationFinished: (NSNotification *)aNotification
// -------------------------------------------------------------------------
// Call back method when the preparation thread is finished
// -------------------------------------------------------------------------
// Crreated: 10 December 2014
// Version: 13 September 2015
// =========================================================================
- (void)preparationFinished: (NSNotification *)aNotification
{
if (preparationThread != nil && wasCanceled == NO)
{
[[NSNotificationCenter defaultCenter] removeObserver: self name: NSThreadWillExitNotification object: preparationThread];
[preparationThread release], preparationThread = nil;
[self performSelectorOnMainThread:@selector(erase) withObject:nil waitUntilDone:NO];
}
}
// Method for debugging
- (void)checkRunningThreadFromMethod: (NSString *)methodName {
BOOL isRunningOnMainThread = [[NSThread currentThread] isMainThread];
NSLog(@"Running on main thread from %@ : %@", methodName, isRunningOnMainThread ? @"Yes" : @"No");
}
// =========================================================================
// (void) application:(NSApplication*) openFiles:
// -------------------------------------------------------------------------
// 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.
// This method is initially called after applicationWillFinishLaunching, but
// before applicationDidFinishLaunching. Subsequent calls to this method
// can be called after applicationDidFinishLaunching, which was often
// seen in Yosemite with a large batch of files.
// -------------------------------------------------------------------------
// Created: 2009 or 2010
// Version: 21 March 2015 17:25
// =========================================================================
- (void) application:(NSApplication *)sender openFiles:(NSArray *)filenames
{
BOOL isDir;
BOOL isDir2;
id object = nil;
int fn_idx = 0;
if ([filenames count] > 0)
{
filesWereDropped = YES;
}
for (fn_idx = 0; fn_idx < [filenames count]; fn_idx++)
{
NSString *filename = [filenames objectAtIndex: fn_idx];
// Set this up to identify only burnable discs
if ([self isVolume: filename] == YES && [self isErasableDisc: filename])
{
[self addFileToArray: filename];
}
else if ([fm fileExistsAtPath: filename isDirectory:&isDir] && isDir &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: filename] == NO &&
[fm isFileSymbolicLink: filename] == NO)
{
NSDirectoryEnumerator *enumerator = [fm enumeratorAtPath: filename];
[self addFileToArray: filename];
while (object = [enumerator nextObject])
{
// if an item within the folder is a package
if ( [fm fileExistsAtPath: [filename stringByAppendingPathComponent: object] isDirectory:&isDir2] && isDir2 &&
[[NSWorkspace sharedWorkspace] isFilePackageAtPath: [filename stringByAppendingPathComponent: object]] == YES )
{
[self addFileToArray: [filename stringByAppendingPathComponent: object]];
[enumerator skipDescendents];
}
else
{
[self addFileToArray: [filename stringByAppendingPathComponent: object]];
}
}
}
else
{
[self addFileToArray: filename];
}
}
// Fire timer at some later time. A timeInterval of 0.0 tells the run loop
// to process this right away, but first it has to get through all the pending
// open file messages.
if (!timer)
{
timer = [NSTimer scheduledTimerWithTimeInterval:0.0
target: self
selector: @selector(addNewFiles:)
userInfo: nil
repeats: YES];
}
}
// =========================================================================
// (void) addNewFiles : (NSTimer *) aTimer
// -------------------------------------------------------------------------
// Add new files to the list of files that were dragged-n-dropped on the icon
// This method is called by the timer that is set-up in the application:openFile:
// method.
// -------------------------------------------------------------------------
// Created: 30 March 2004 23:52
// Version: 21 March 2015 20:27
// =========================================================================
- (void) addNewFiles: (NSTimer *) aTimer
{
[aTimer invalidate];
timer = nil;
[self erase];
}
// =========================================================================
// (void) addFileToArray: (NSString *) filename
// -------------------------------------------------------------------------
//
// -------------------------------------------------------------------------
// Created: 29 June 2009 22:30
// Version: 30 March 2018 22:43
// =========================================================================
- (void) addFileToArray: (NSString *) filePath
{
PEFile *tempPEFile = [[PEFile alloc] initWithPath: filePath];
BOOL isDir3;
// Symbolic link
[tempPEFile setIsSymbolicLink: [fm isFileSymbolicLink: filePath]];
// File size
if ([fm fileExistsAtPath: filePath isDirectory:&isDir3] && isDir3 &&
[tempPEFile isSymbolicLink] == NO )
{
[tempPEFile setIsDirectory: YES];
if ([[NSWorkspace sharedWorkspace] isFilePackageAtPath: filePath] == YES)
{
[tempPEFile setIsPackage: YES];
[tempPEFile setFilesize: [fm fileSize: filePath]];
}
else if ([self isVolume: filePath] == YES && [self isErasableDisc: filePath]) // erasable disc
{
[tempPEFile setIsPackage: NO];
[tempPEFile setFilesize: [fm fileSize: filePath]];
}
else // otherwise, just a directory
{
[tempPEFile setIsPackage: NO];
[tempPEFile setFilesize: 1];
}
}
else
{
[tempPEFile setFilesize: [fm fileSize: filePath]];
[tempPEFile setIsDirectory: NO];
[tempPEFile setIsPackage: NO];
}
// Is Volume + Is Erasable Disc
if ([self isVolume: filePath] == YES)
{
[tempPEFile setIsVolume: NO];
if ([self isErasableDisc: filePath] == YES)
{
[tempPEFile setIsErasableDisc: YES];
}
else
{
[tempPEFile setIsErasableDisc: NO];
}
}
else
{
[tempPEFile setIsVolume: NO];
[tempPEFile setIsErasableDisc: NO];
}
// This check can only be done on Mac OS 10.6+
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 6, 0}] == YES)
{
[tempPEFile setIsOnSSD: [fm isSolidState: [filePath fileSystemRepresentation]]];
}
else
{
[tempPEFile setIsOnSSD: NO];
}
// Resource Fork
[tempPEFile setHasResourceFork: [fm containsResourceFork: filePath]];
// Calculate total file size
if ( ([tempPEFile isErasableDisc] == YES) || ([tempPEFile isDirectory] == NO) )
{
totalFilesSize += [tempPEFile filesize];
}
// Packages are treated as one file so it looks like just the bundle is being erased
if ([tempPEFile isPackage] == YES)
{
totalFilesSize += [tempPEFile filesize];
[tempPEFile setNumberOfFiles: [self countNumberOfFiles: [tempPEFile path]]];
}
else
{
if ([tempPEFile hasResourcefork] == YES)
{
[tempPEFile setNumberOfFiles: 2];
}
else
{
[tempPEFile setNumberOfFiles: 1]; // For all other files, folders, and non-bundles, set to 1
}
}
// Check if a file can be deleted, and if not, if it can be deleted by using
// escalated permissions. In most cases, a file is deletable. But if it
// returns back 'no', then perform additional checks to determine if it is
// a write issue or if the file is on a read-only disk.
BOOL requiresAuthorization = NO; // Check if admin rights are needed to delete
BOOL isWritable = YES; // Can the file be written over
BOOL isPathDeletable = YES; // Is the enclosing path writable
BOOL isFileDeletable = YES; // By default, assume the file can be deleted
int deleteErrno = 0;
NSDictionary *fileAttributes = [fm fileAttributesAtPath:filePath traverseLink:NO];
// If the file is locked by the Finder, unlock it before checking if it can be deleted.
if ([[fileAttributes objectForKey:NSFileImmutable] boolValue] == YES)
{
NSError *error = nil;
if ([fm setAttributes: [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:NSFileImmutable] ofItemAtPath:filePath error: &error] == NO) {
NSLog(@"Error trying to set the NSFileImmutable attribute: %@", [error localizedDescription]);
}
}
// Check if the file can be overwritten and deleted. If there is an error,
// save the value of the system errno, since it can easily be changed by
// the system if another error occurs.
// Check if the enclosing path is writable so the file can be deleted
isPathDeletable = [fm isDeletableFileAtPath: filePath];
if (isPathDeletable == NO) {
deleteErrno = errno;
perror("isPathDeletable error");
}
// Check if the file can be overwritten and deleted
isWritable = [fm isWritableFileAtPath: filePath];
if (isWritable == NO) {
deleteErrno = errno;
perror("isWritable error");
}
if (isPathDeletable == NO || isWritable == NO)
{
NSNumber *originalPermissions = [fileAttributes objectForKey: NSFilePosixPermissions];
mode_t permissionsMask = 0700;
mode_t updatedPermissions = [originalPermissions shortValue] | permissionsMask; // Updated set of permissions
NSDictionary *attribs = [NSDictionary dictionaryWithObject:[NSNumber numberWithShort:updatedPermissions] forKey:NSFilePosixPermissions];
NSError *error = nil;
#ifdef MAC_APP_STORE
// In most cases, this should be set to NO, but perfom one check to see if the current
// user can update the file's permissions so it can be deleted.
if (([fm setAttributes: attribs ofItemAtPath: filePath error: &error] == YES) && (isPathDeletable == YES))
{
isFileDeletable = YES;
}
else
{
// Since admin rights cannot be granted for MAS apps, set this to NO
isFileDeletable = NO;
}
#else
if (deleteErrno == EPERM) // Error 1 - Operation not permitted
{
requiresAuthorization = YES;
}
else if (deleteErrno == EACCES) // Error 13 - Permissions error
{
// Try and update the permissions. If possible, authorization is not necessary
if ([fm setAttributes: attribs ofItemAtPath: filePath error: &error] == YES)
{
// As long as an enclosing folder(s) are writable, the file can be deleted
// Otherwise, if the enclosing folder is read-only, then the file may be
// modified and overwritten, but the original file cannot be deleted, so
// authorization is needed to fully delete the file.
if (isPathDeletable == YES) {
// Was able to modify the permissions
requiresAuthorization = NO;
} else {
requiresAuthorization = YES;
}
}
else
{ // Was not able to modify the permissions, will need authorization
if ([STPrivilegedTask authorizationFunctionAvailable] == YES)
{
requiresAuthorization = YES;
}
else
{
// If AuthorizationExecuteWithPrivileges no longer works, then this
// file cannot be deleted.
isFileDeletable = NO;
}
}
}
else if (deleteErrno == EROFS) // Error 30 - Read-only file system
{
isFileDeletable = NO;
}
else
{
char *errorMsg = strerror(deleteErrno);
NSLog(@"Other error detecting deletability: %s (%d)", errorMsg, deleteErrno);
}
#endif
}
[tempPEFile setIsDeletable: isFileDeletable requiresAuthorizationToDelete: requiresAuthorization];
[trash_files insertObject: tempPEFile atIndex: 0];
[tempPEFile release];
}
// =========================================================================
// (unsigned long long) countNumberOfFiles: (NSString *) path
// -------------------------------------------------------------------------
//
// -------------------------------------------------------------------------
// Created: 23 August 2009
// Version: 23 August 2009
// =========================================================================
- (unsigned long long) countNumberOfFiles: (NSString *) path
{
unsigned long long numFiles = 0;
NSDirectoryEnumerator *package_enumerator;
id object = nil;
BOOL isDir;
package_enumerator = [fm enumeratorAtPath: path];
while (object = [package_enumerator nextObject])
{
if ([fm fileExistsAtPath: [path stringByAppendingPathComponent: object] isDirectory:&isDir] && isDir == NO)
{
if ([fm containsResourceFork: [path stringByAppendingPathComponent: object]] == YES)
{
numFiles+=2;
}
else
{
numFiles++;
}
}
}
return (numFiles);
}
// =========================================================================
// (void) checkInstalledPlugins
// -------------------------------------------------------------------------
// Check if a plug-in is installed, and if so, update to the most up-to-date
// version, if necessary
// -------------------------------------------------------------------------
// Created: 2 January 2012 14:11
// Version: 10 December 2016 23:30
// =========================================================================
- (void) checkInstalledPlugins
{
NSString *oldPluginPath = nil;
NSString *newPluginPath = nil;
// Get installed plugin path and app's plugin path
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 6, 0}] == YES) // Mac OS 10.6 or later
{
oldPluginPath = [@"~/Library/Services/Erase.workflow" stringByExpandingTildeInPath];
newPluginPath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent: @"Erase.workflow"];
}
// Check if plugin is installed
if ([fm fileExistsAtPath: oldPluginPath] == YES && [fm fileExistsAtPath: newPluginPath] == YES)
{
// Check if installed plugin is older than app's version
NSDictionary *oldPluginAttr = [fm fileAttributesAtPath:oldPluginPath traverseLink:NO];
NSDictionary *newPluginAttr = [fm fileAttributesAtPath:newPluginPath traverseLink:NO];
NSDate *oldPluginDate = [oldPluginAttr objectForKey: NSFileModificationDate];
NSDate *newPluginDate = [newPluginAttr objectForKey: NSFileModificationDate];
if (oldPluginDate != nil && newPluginDate != nil)
{
if ([newPluginDate compare: oldPluginDate] == NSOrderedDescending)
{
if ([fm removeFileAtPath: oldPluginPath handler: nil] == NO)
{
NSLog(@"Failed to remove old plugin at %@", oldPluginPath);
}
// Install new version of plugin
if ([fm copyPath: newPluginPath toPath: oldPluginPath handler:nil] == NO)
{
NSLog(@"Failed installing the new plugin at %@", oldPluginPath);
}
}
}
}
}
#pragma mark -
// =========================================================================
// (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: 30 November 2014 21:03
// =========================================================================
- (void) erase
{
// [self checkRunningThreadFromMethod: @"erase"];
idx = 0;
num_files = 0;
num_files = [trash_files count];
[indicator setMaxValue: totalFilesSize*100];
[indicator setIndeterminate: NO];
[indicator stopAnimation: self];
[erasingMsg 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)
{
if (filesWereDropped == YES && num_files == 1) // Erasing one file
{
NSAlert *alert = [NSAlert alertWithMessageText: NSLocalizedString(@"ErrorTitle", nil)
defaultButton: NSLocalizedString(@"OK", nil)
alternateButton: NSLocalizedString(@"Quit", nil)
otherButton: nil
informativeTextWithFormat: [NSString stringWithFormat: NSLocalizedString(@"ErasingFileWarning", nil), [[trash_files objectAtIndex: idx] fileName]] ];
[alert setShowsSuppressionButton: YES];
[[alert suppressionButton] setTitle:NSLocalizedString(@"DoNotShowMessage", nil)];
[[alert suppressionButton] setState:NSOffState];
[alert beginSheetModalForWindow: theWindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
else if (filesWereDropped == YES && num_files > 1) // Erasing several files
{
NSAlert *alert = [NSAlert alertWithMessageText: NSLocalizedString(@"ErrorTitle", nil)
defaultButton: NSLocalizedString(@"OK", nil)
alternateButton: NSLocalizedString(@"Quit", nil)
otherButton: nil
informativeTextWithFormat: NSLocalizedString(@"ErasingFilesWarning", nil)];
[alert setShowsSuppressionButton: YES];
[[alert suppressionButton] setTitle: NSLocalizedString(@"DoNotShowMessage", nil)];
[[alert suppressionButton] setState: NSOffState];
[alert beginSheetModalForWindow: theWindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
else // Erasing files from the Trash
{
NSAlert *alert = [NSAlert alertWithMessageText: NSLocalizedString(@"ErrorTitle", nil)
defaultButton: NSLocalizedString(@"OK", nil)
alternateButton: NSLocalizedString(@"Quit", nil)
otherButton: nil
informativeTextWithFormat: NSLocalizedString(@"ErasingTrashWarning", nil)];
[alert setShowsSuppressionButton: YES];
[[alert suppressionButton] setTitle: NSLocalizedString(@"DoNotShowMessage", nil)];
[[alert suppressionButton] setState: NSOffState];
[alert beginSheetModalForWindow: theWindow modalDelegate:self didEndSelector:@selector(alertDidEnd:returnCode:contextInfo:) contextInfo:nil];
}
}
else // no warning displayed, start erasing
{
if (idx < num_files)
{
[self selectNextFile];
}
else // there are no files
{
[self shutdownPE];
}
}
}
// =========================================================================
// (void) alertDidEnd: (NSAlertCheckbox *) alert returnCode: (int) returnCode contextInfo: (void *) contextInfo
// -------------------------------------------------------------------------
// Instead of using a modal alert, run as a sheet so the Preferences can
// be accessed easily.
// -------------------------------------------------------------------------
// Created: 29 December 2010 20:30
// Version: 29 December 2010 20:30
// =========================================================================
- (void) alertDidEnd: (NSAlert *) alert returnCode: (int) returnCode contextInfo: (void *) contextInfo
{
if ([[alert suppressionButton] state] == NSOnState)
{
[prefs setBool:NO forKey: @"WarnBeforeErasing"];
}
if (NSAlertSecondButtonReturn == returnCode || NSCancelButton == returnCode) // Quit
{
[NSApp terminate:self];
}
else
{
if (idx < num_files)
{
[self selectNextFile];
}
else // there are no files
{
[self shutdownPE];
}
}
}
// =========================================================================
// (void) fullDiskAccessAlertDidEnd
// -------------------------------------------------------------------------
// Call back method from the NSAlert which checks if Full Disk Access needs
// to be enabled.
// -------------------------------------------------------------------------
// Crreated: Mid-May 2020
// =========================================================================
- (void) fullDiskAccessAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo
{
if (NSAlertSecondButtonReturn == returnCode || NSCancelButton == returnCode) // Quit
{
[NSApp terminate:self];
}
else
{
// macOS Mojave and later have Full Disk Access in the Security & Privacy pane
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion){10, 14, 0}] == YES)
{
// Reference for all of the preference anchors: https://apple.stackexchange.com/questions/361045/open-system-preferences-privacy-full-disk-access-with-url
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"x-apple.systempreferences:com.apple.preference.security?Privacy_AllFiles"]];
[NSApp terminate:self];
}
else
{
// For pre-Mojave versions of macOS/Mac OS X, have NSWorkspace directly open the Security pane
NSURL *url = [NSURL fileURLWithPath:@"/System/Library/PreferencePanes/Security.prefPane"];
if (url != NULL)
{
[[NSWorkspace sharedWorkspace] openURL:url];
}
[NSApp terminate:self];
}