-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSSYAlert.m
2753 lines (2381 loc) · 92.5 KB
/
SSYAlert.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
#import "SSYAlert.h"
#import "SSYMailto.h"
#import "SSYSystemDescriber.h"
#import "SSYWrappingCheckbox.h"
#import "NSError+InfoAccess.h"
#import "NSString+Truncate.h"
#import "NSView+Layout.h"
#import "NSWindow+Sizing.h"
#import "NSError+MoreDescriptions.h"
#import "NSError+Recovery.h"
#import "NSError+SSYInfo.h"
#import "NSBundle+MainApp.h"
#import "NSObject+RecklessPerformSelector.h"
#import "SSYVectorImages.h"
#import "NSString+LocalizeSSY.h"
#import "NSInvocation+Quick.h"
#import "NS(Attributed)String+Geometrics.h"
NSObject <SSYAlertErrorHideManager> * gSSYAlertErrorHideManager = nil ;
NSMutableSet* static_alertHangout = nil ;
NSString* const SSYAlertDidRecoverInvocationKey = @"SSYAlertDidRecoverInvocationKey" ;
NSString* const SSYAlert_ErrorSupportEmailKey = @"SSYAlert_ErrorSupportEmail" ;
NSString* const SSYAlertDidProcessErrorNotification = @"SSYAlertDidProcessErrorNotification" ;
#pragma mark > How to Add a Feature
/*
Most new features will require an instance variable.
Use the following checklist when adding a feature:
- In .h, add an instance variable.
- In .h, or in .m SSYAlert Class Extension, add ivar declaration.
- In .m, add a @synthesize or getter/setter implementation.
- In .m, if an object, -[SSYAlert dealloc], release it.
- In .m, -[SSYAlert cleanSlate], set to a default value.
- In .m, -[SSAlert display], read the ivar value and affect the content accordingly.
*/
@interface NSView (StringsInSubviews)
- (NSInteger)longestStringLengthInAnySubview ;
@end
@implementation NSView (StringsInSubviews)
- (NSInteger)stringLengthInAnySubviewLongerThan:(NSInteger)length {
SEL selector ;
selector = @selector(string) ;
if ([self respondsToSelector:selector]) {
NSInteger minLength = [[self recklessPerformSelector:selector] length] ;
if (length < minLength) {
length = minLength ;
}
}
selector = @selector(stringValue) ;
if ([self respondsToSelector:selector]) {
// Because NSImageView has a -stringValue describing each of its sizes...
if (![self isKindOfClass:[NSImageView class]]) {
NSInteger minLength = [[self recklessPerformSelector:selector] length] ;
if (length < minLength) {
length = minLength ;
}
}
}
// Recursion into documentView, if any
selector = @selector(documentView) ;
if ([self respondsToSelector:selector]) {
length = [[self recklessPerformSelector:selector] stringLengthInAnySubviewLongerThan:length] ;
}
// Recursion into subviews, if any:
for (NSView* subview in [self subviews]) {
length = [subview stringLengthInAnySubviewLongerThan:length] ;
}
return length ;
}
- (NSInteger)longestStringLengthInAnySubview {
return [self stringLengthInAnySubviewLongerThan:0] ;
}
@end
@interface NSArray (SimpleDeepCopy)
- (id <NSCoding>)simpleDeepCopy ;
@end
@implementation NSArray (SimpleDeepCopy)
- (id <NSCoding>)simpleDeepCopy {
NSData* archive ;
id copy = nil;
@try {
if (![self respondsToSelector:@selector(encodeWithCoder:)]) {
NSException* ex = [NSException exceptionWithName:@"Can't copy"
reason:@"Can't archive"
userInfo:nil];
[ex raise] ;
}
NSError* error = nil;
archive = [NSKeyedArchiver archivedDataWithRootObject:self
requiringSecureCoding:YES
error:&error];
if (error) {
NSLog(@"Internal Error 243-5742: %@: Returning self since could not archive %@", NSStringFromSelector(_cmd), self) ;
copy = self;
}
if (archive && !error) {
copy = [NSKeyedUnarchiver unarchivedObjectOfClass:[SSYAlert class]
fromData:archive
error:&error];
if (!copy || error) {
NSLog(@"Internal Error 243-5743: %@: Returning self since could not unarchive %@", NSStringFromSelector(_cmd), self) ;
copy = self;
}
}
}
@catch (NSException* ex) {
NSLog(@"Internal Error 243-5741]: %@: Exception: %@. Returning self since could not un/archive %@", NSStringFromSelector(_cmd), ex, self) ;
copy = self ;
}
@finally { }
#if !__has_feature(objc_arc)
[copy retain] ;
#endif
return copy ;
}
@end
@interface NSTextView (SSYAlertUsage)
- (void)configureForSSYAlertUsage ;
@end
@implementation NSTextView (SSYAlertUsage)
- (void)configureForSSYAlertUsage {
[self setEditable:NO] ;
[self setDrawsBackground:NO] ;
// Changed in BookMacster 1.21. Why not allow text to be copied?
[self setSelectable:YES] ;
// The next two lines are very important. Took me many months to learn that,
// by default, NSTextViews will resize themselves automatically to accomodate
// a changed text size, and what's even more confusing is that they do so
// when you (or a superview) sets their `needsDisplay` property to YES.
// When used in SSYAlert, SSYAlert wants to set their size manually, in its
// -display method. In particular, if SSYAlert's ivar allowsShrinking is set
// to NO, in fact we want them to maintain their height when automatic resizing
// would tell them to shrink.
[self setVerticallyResizable:NO] ;
[self setHorizontallyResizable:NO] ;
}
@end
#define WINDOW_EDGE_SPACING 17.0
#pragma mark * Class Extension of SSYAlert
@interface SSYAlert ()
@property (retain) NSImageView* icon ;
@property (retain) NSProgressIndicator* progressBar ; // readonly in public @interface
@property (retain) NSTextView* titleTextView ; // readonly in public @interface
@property (retain) NSTextView* smallTextView ; // readonly in public @interface
@property (retain) NSScrollView* smallTextScrollView ;
@property (retain) NSButton* helpButton ;
@property (retain) NSButton* supportButton ;
@property (retain) SSYWrappingCheckbox* checkbox ;
@property (retain) NSButton* button1 ;
@property (retain) NSButton* button2 ;
@property (retain) NSButton* button3 ;
@property (retain) NSButton* button4 ;
@property (retain) NSError* errorPresenting ;
@property (retain) NSImageView* iconInformational ;
@property (retain) NSImageView* iconWarning ;
@property (retain) NSImageView* iconCritical ;
@property (retain) NSButton* buttonPrototype ;
@property (copy) NSString* wordAlert ;
// @property (copy) NSString* whyDisabled ; // in public @interface
// @property (assign) isEnabled ; // in public @interface
@property (assign) BOOL isVisible ;
@property (assign) NSInteger nDone ;
// @property (assign) float rightColumnMinimumWidth ; // in public @interface
// @property (assign) float rightColumnMaximumWidth ; // in public @interface
// @property (assign) BOOL allowsShrinking ; // in public @interface
// @property (assign) NSInteger titleMaxChars ; // in public @interface
// @property (assign) NSInteger smallTextMaxChars ; // in public @interface
// @property (assign) BOOL progressBarShouldAnimate ; // in public @interface
@property (assign) BOOL isDoingModalDialog ;
@property (assign) NSModalSession modalSession ;
@property (assign) NSPoint windowTopCenter ;
@property (assign) NSTimeInterval nextProgressUpdate ;
// @property (retain, readonly) NSMutableArray* otherSubviews ; // in public @interface
@end
@implementation SSYAlertWindow
- (NSInteger)checkboxState {
NSInteger state = NSControlStateValueMixed ; // default answer in case we can't find checkbox
BOOL didFindCheckbox = NO ;
for (NSView* view in [[self contentView] subviews]) {
if ([view isKindOfClass:[SSYWrappingCheckbox class]]) {
SSYWrappingCheckbox* checkbox = (SSYWrappingCheckbox*)view ;
state = [checkbox state] ;
didFindCheckbox = YES ;
break ;
}
}
if (!didFindCheckbox) {
// Until BookMacster 1.22.4, logged Internal Error 624-9382
state = NSControlStateValueOff ;
}
return state ;
}
#pragma mark *
// At one time, I thought that NSWindow's keyboard loop was
// broken in a programmatically-created window.
/* - (void)sendEvent:(NSEvent *)event {
int tab = 0 ;
if ([event type] == NSEventTypeKeyDown) {
unichar character = [[event characters] characterAtIndex:0] ;
if (character == 9) {
tab = 1 ;
}
else if (character == 25) {
tab = -1 ;
}
}
if (YES) {///if (!tab) {
[super sendEvent:event] ;
}
else {
NSView* firstResponder = (NSView*)[self firstResponder] ;
if (![[[self contentView] subviews] containsObject:firstResponder]) {
// Aha! Must be a sneaky field editor!!
// In this case, we replace it with the delegate of the
// field editor, which is the "actual" field (i.e., NSTextField)
// being edited by the field editor
if ([firstResponder respondsToSelector:@selector(delegate)]) {
// The above if() is just for safety; it should always
// be true as far as far as I can imagine, but my
// imagination is limited.
firstResponder = [(NSTextView*)firstResponder delegate] ;
}
}
// Now, we want the next responder in the chain. However, the
// "actual" object being edited may not itself be in the responder
// chain, because it may be a subview of a higher level view
// (for example, SSYLabelledTextField) which is in the chain.
// In this case, its -nextKeyView and -previousKeyView
// will be nil. If it is, we recursively try its superview.
NSView* nextResponder = nil ;
while (!nextResponder && firstResponder) {
nextResponder = (tab > 0)
? [firstResponder nextKeyView]
: [firstResponder previousKeyView] ;
firstResponder = [firstResponder superview] ;
}
[self makeFirstResponder:nextResponder] ;
}
}
*/
@end
@interface NSView (KeyboardLooping)
- (void)makeNextKeyViewOfWindow:(NSWindow*)window
firstResponder:(NSView**)hdlFirstResponder
previousResponder:(NSView**)hdlPreviousResponder ;
@end
@implementation NSView (KeyboardLooping)
- (void)makeNextKeyViewOfWindow:(NSWindow*)window
firstResponder:(NSView**)firstResponder_p
previousResponder:(NSView**)previousResponder_p {
if ([self acceptsFirstResponder]) {
if (!*firstResponder_p) {
// No first responder yet
if ([window makeFirstResponder:self]) {
[window setInitialFirstResponder:self] ;
*firstResponder_p = self ;
*previousResponder_p = self ;
}
}
else {
[*previousResponder_p setNextKeyView:self] ;
*previousResponder_p = self ;
}
}
}
@end
@interface NSButton (SSYAlertStuff)
- (void)sizeToFitIncludingNiceMargins ;
// Stupid -sizeToFit does not look good for NSButtons, so I add more margin
@end
@implementation NSButton (SSYAlertStuff)
- (void)sizeToFitIncludingNiceMargins {
[self sizeToFit] ;
[self deltaX:0.0
deltaW:6.0] ;
}
@end
@implementation SSYAlert : NSWindowController
+ (void)load {
static_alertHangout = [[NSMutableSet alloc] init] ;
}
+ (NSString*)supportEmailString {
return [[NSBundle mainAppBundle] objectForInfoDictionaryKey:SSYAlert_ErrorSupportEmailKey] ;
}
- (id)clickObject {
#if !__has_feature(objc_arc)
[[clickObject retain] autorelease] ;
#endif
return clickObject ;
}
- (void)setClickObject:(id)value {
if (clickObject != value) {
#if !__has_feature(objc_arc)
[clickObject release] ;
[value retain] ;
#endif
clickObject = value ;
}
}
#pragma mark * Accessors
@synthesize icon ;
@synthesize progressBar ;
@synthesize titleTextView ;
@synthesize smallTextView ;
@synthesize smallTextScrollView ;
@synthesize helpButton ;
@synthesize supportButton ;
@synthesize checkbox ;
@synthesize button1 ;
@synthesize button2 ;
@synthesize button3 ;
@synthesize button4 ;
@synthesize errorPresenting ;
@synthesize iconInformational ;
@synthesize iconWarning;
@synthesize iconCritical ;
@synthesize buttonPrototype ;
@synthesize wordAlert ;
@synthesize isVisible ;
@synthesize nDone ;
@synthesize rightColumnMinimumWidth = m_rightColumnMinimumWidth ;
@synthesize allowsShrinking ;
@synthesize titleMaxChars ;
@synthesize smallTextMaxChars ;
@synthesize clickTarget ;
@synthesize clickSelector ;
@synthesize clickObject ;
@synthesize checkboxInvocation = m_checkboxInvocation ;
@synthesize isDoingModalDialog ;
@synthesize modalSession ;
@synthesize windowTopCenter ;
@synthesize progressBarShouldAnimate ;
@synthesize dontGoAwayUponButtonClicked = m_dontGoAwayUponButtonClicked ;
@synthesize nextProgressUpdate ;
- (CGFloat)rightColumnMaximumWidth {
CGFloat rightColumnMaximumWidth ;
@synchronized(self) {
rightColumnMaximumWidth = m_rightColumnMaximumWidth ; ;
}
return rightColumnMaximumWidth ;
}
- (void)setRightColumnMaximumWidth:(CGFloat)width {
@synchronized(self) {
m_rightColumnMaximumWidth = width ;
}
[[self checkbox] setMaxWidth:width] ;
for (NSView* view in [self otherSubviews]) {
if ([view respondsToSelector:@selector(setMaxWidth:)]) {
// Sleazy, lying typecast to avoid compiler warning
[(SSYWrappingCheckbox*)view setMaxWidth:width] ;
}
}
}
- (void)setRightColumnWidth:(CGFloat)width {
[self setRightColumnMinimumWidth:width] ;
[self setRightColumnMaximumWidth:width] ;
}
@synthesize alertReturn = m_alertReturn ;
- (BOOL)isEnabled {
BOOL isEnabled ;
@synchronized(self) {
isEnabled = m_isEnabled ; ;
}
return isEnabled ;
}
- (void)setIsEnabled:(BOOL)isEnabled {
[[self button1] setEnabled:isEnabled] ;
[[self button1] display] ;
@synchronized(self) {
m_isEnabled = isEnabled ;
}
}
- (NSString*)whyDisabled {
NSString* whyDisabled ;
@synchronized(self) {
whyDisabled = [m_whyDisabled copy] ;
#if !__has_feature(objc_arc)
[whyDisabled autorelease] ;
#endif
}
return whyDisabled ;
}
- (void)setWhyDisabled:(NSString*)whyDisabled {
[[self button1] setToolTip:whyDisabled] ;
@synchronized(self) {
if (whyDisabled != m_whyDisabled) {
#if !__has_feature(objc_arc)
[m_whyDisabled release] ;
#endif
m_whyDisabled = [whyDisabled copy] ;
}
}
}
- (NSMutableArray *)otherSubviews {
if (!otherSubviews) {
otherSubviews = [[NSMutableArray alloc] init];
}
#if !__has_feature(objc_arc)
[[otherSubviews retain] autorelease] ;
#endif
return otherSubviews ;
}
#pragma mark * Class Methods returning Constants
+ (NSFont*)titleTextFont {
return [NSFont boldSystemFontOfSize:13] ;
}
+ (NSFont*)smallTextFont {
return [NSFont systemFontOfSize:12] ;
}
+ (CGFloat)titleTextHeight {
return 17 ;
}
+ (CGFloat)smallTextHeight {
return 14 ;
}
+ (NSString*)contactSupportToolTip {
return [NSString stringWithFormat:@"%@ | %@",
[NSString localize:@"supportContact"],
[[NSString localize:@"email"] capitalizedString]] ;
}
+ (NSButton*)makeButton {
NSButton* button = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 49, 49)] ;
[button setFont:[NSFont systemFontOfSize:13]] ;
[button setBezelStyle:NSBezelStyleRounded] ;
#if !__has_feature(objc_arc)
[button autorelease] ;
#endif
return button ;
}
#pragma mark * Private Methods
/*!
@brief Translates from the 'recovery option' as expressed in our
-doLayoutError: method to the 'recovery option index' expressed in Cocoa's
error presentation method, -presentError:
*/
+ (NSUInteger)recoveryOptionIndexForRecoveryOption:(NSInteger)recoveryOption {
NSUInteger recoveryOptionIndex ;
switch (recoveryOption) {
case NSAlertFirstButtonReturn : // 1000
recoveryOptionIndex = 0 ;
break;
case NSAlertSecondButtonReturn :
recoveryOptionIndex = 1 ; // 1001
break;
case NSAlertThirdButtonReturn : // 1002
recoveryOptionIndex = 2 ;
break;
case SSYAlertFourthButtonReturn : // 1003
recoveryOptionIndex = 3 ;
break;
default:
// This should never happen since we only have 3 buttons and return
// one of the above three values like NSAlert.
NSLog(@"Warning 520-3840 %ld", (long)recoveryOption) ;
recoveryOptionIndex = recoveryOption ;
break;
}
return recoveryOptionIndex ;
}
+ (NSInteger)tryRecoveryAttempterForError:(NSError*)error
recoveryOption:(NSUInteger)recoveryOption
contextInfo:(NSMutableDictionary*)infoDictionary {
NSUInteger result = SSYAlertRecoveryNotAttempted ;
id recoveryAttempter ;
if ([[[error userInfo] objectForKey:SSYRecoveryAttempterIsAppDelegateErrorKey] boolValue]) {
recoveryAttempter = [NSApp delegate] ;
}
else {
recoveryAttempter = [error recoveryAttempter] ;
}
if (recoveryAttempter) {
[self attemptRecoveryFromError:error
infoDictionary:infoDictionary
recoveryOption:recoveryOption
recoveryAttempter:recoveryAttempter] ;
}
else {
NSURL* recoveryAttempterUrl = [[error userInfo] objectForKey:SSYRecoveryAttempterUrlErrorKey] ;
if (recoveryAttempterUrl) {
// recoveryOption NSAlertSecondButtonReturn is assumed to mean "Cancel".
if (recoveryOption == NSAlertFirstButtonReturn) {
result = SSYAlertRecoveryAttemptedAsynchronously ;
[[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:recoveryAttempterUrl
display:YES
completionHandler:^void(
NSDocument* newDocument,
BOOL documentWasAlreadyOpen,
NSError* documentOpeningError) {
if (newDocument) {
[self attemptRecoveryFromError:error
infoDictionary:infoDictionary
recoveryOption:recoveryOption
recoveryAttempter:newDocument] ;
}
else if (documentOpeningError) {
[self alertError:documentOpeningError] ;
}
}] ;
}
}
}
return result ;
}
+ (void)attemptRecoveryFromError:(NSError*)error
infoDictionary:(NSMutableDictionary*)infoDictionary
recoveryOption:(NSUInteger)recoveryOption
recoveryAttempter:(id)recoveryAttempter {
NSError* deepestRecoverableError = [error deepestRecoverableError] ;
// Try the sheet method, attemptRecoveryFromError::::: first, since, in my
// opinion, it gives a better user experience. If the recoveryAttempter
// does not respond to that, try the window method, attemptRecoveryFromError::
if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:recoveryOption:delegate:didRecoverSelector:contextInfo:)]) {
NSInvocation* invocation = [error didRecoverInvocation] ;
id delegate = [invocation target] ;
SEL didRecoverSelector = [invocation selector] ;
// I put the whole invocation into the context info, believing it to be alot cleaner.
if (invocation) {
// Before we invoke the didRecoverInvocation, we also put it into the
// current infoDictionary in case an error occurs again and we need
// to re-recover.
[infoDictionary setObject:invocation
forKey:SSYAlertDidRecoverInvocationKey] ;
}
[recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
recoveryOption:recoveryOption
delegate:delegate
didRecoverSelector:didRecoverSelector
contextInfo:(__bridge void *)(infoDictionary)] ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)]) {
/* This is an error produced by Cocoa.
In particular, in macOS 10.7, it might be one like this:
Error Domain = NSCocoaErrorDomain
Code = 67000
UserInfo = {
• NSLocalizedRecoverySuggestion=Click Save Anyway to keep your changes and save the
changes made by the other application as a version, or click Revert to keep the changes from the other
application and save your changes as a version.
• NSLocalizedFailureReason=The file has been changed by another application.
• NSLocalizedDescription=This document’s file has been changed by another application.
• NSLocalizedRecoveryOptions = ("Save Anyway", "Revert")
}
*/
NSInvocation* invocation = [error didRecoverInvocation] ;
id delegate = [invocation target] ;
SEL didRecoverSelector = [invocation selector] ;
// I put the whole invocation into the context info, believing it to be alot cleaner.
if (invocation) {
// Before we invoke the didRecoverInvocation, we also put it into the
// current infoDictionary in case an error occurs again and we need
// to re-recover.
[infoDictionary setObject:invocation
forKey:SSYAlertDidRecoverInvocationKey] ;
}
NSInteger recoveryOptionIndex = [self recoveryOptionIndexForRecoveryOption:recoveryOption] ;
[recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
optionIndex:recoveryOptionIndex
delegate:delegate
didRecoverSelector:didRecoverSelector
contextInfo:(__bridge void *)(infoDictionary)] ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:recoveryOption:)]) {
[recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
recoveryOption:recoveryOption] ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:)]) {
// This is an error produced by Cocoa.
NSInteger recoveryOptionIndex = [self recoveryOptionIndexForRecoveryOption:recoveryOption] ;
[recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
optionIndex:recoveryOptionIndex] ;
}
else if (recoveryAttempter != nil) {
NSLog(@"Internal Error 342-5587. Given Recovery Attempter %@ does not respond to any attemptRecoveryFromError:... method", recoveryAttempter) ;
}
}
- (IBAction)help:(id)sender {
NSURL* url = [NSURL URLWithString:self.helpAddress];
if ([[url scheme] hasPrefix:@"http"]) {
[[NSWorkspace sharedWorkspace] openURLs:@[url]
withAppBundleIdentifier:nil
options:NSWorkspaceLaunchAsync
additionalEventParamDescriptor:nil
launchIdentifiers:NULL];
} else {
/* Help Anchors are broken in macOS 10.14, at least, as they are formed
in my app's Help Book. Until I get a workaround that works, I
implement in my app delegate displayHelpBookAnchor: which displays
the given help anchor in the Help Book on my web page.
*/
SEL selector = NSSelectorFromString(@"displayHelpBookAnchor:");
if ((NSAppKitVersionNumber >= 1600.0) && [[NSApp delegate] respondsToSelector:selector]) {
[[NSApp delegate] performSelector:selector
withObject:self.helpAddress];
} else {
[[NSHelpManager sharedHelpManager] openHelpAnchor:self.helpAddress
inBook:[[NSBundle mainAppBundle] objectForInfoDictionaryKey:@"CFBundleHelpBookName"]];
}
}
}
- (IBAction)support:(id)sender {
[SSYAlert supportError:[self errorPresenting]] ;
}
+ (void)supportError:(NSError*)error {
NSString* presenterExecutableName = [[NSBundle mainAppBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"] ;
// Note: If you'd prefer the app name to be localized, use "CFBundleName" instead.
NSString* appVersion = [[NSBundle mainAppBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] ;
NSString* appVersionString = [[NSBundle mainAppBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ;
NSString* systemDescription = [SSYSystemDescriber softwareVersionString] ;
NSString* mailableDescription ;
if (
([error respondsToSelector:@selector(longDescription)])
&&
([error respondsToSelector:@selector(mailableLongDescription)])
) {
mailableDescription = [error performSelector:@selector(mailableLongDescription)] ;
if ([mailableDescription hasSuffix:SSYDidTruncateErrorDescriptionTrailer]) {
// We'll write a file to package the error's longDescription which was too long to
// fit in the email, and ask the user to zip and attach it.
NSString* longDescription = [error longDescription] ;
NSString* filename = [NSString stringWithFormat:
@"%@-Error-%lx.txt",
[[NSBundle mainAppBundle] objectForInfoDictionaryKey:@"CFBundleName"],
(long)[NSDate timeIntervalSinceReferenceDate]] ;
NSString* filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] stringByAppendingPathComponent:filename] ;
NSError* writeError = nil ;
NSString* text = [NSString stringWithFormat:
@"%@ %@.\n\n%@\n%@\n%@\n\n%@",
@"*** Note to user*** It is possible that this file may have some of your private "
@"information in it. Please skim through it before sending. "
@"Replace any text you don't want to send with the word 'REDACTED', then save this file.\n\n"
@"To zip this file, select it in Finder, then execute a secondary click. (A secondary click "
@"means to click it while holding down the 'control' key, or to tap with two fingers if you "
@"have a trackpad, or to use the secondary button if you have a multi-button mouse.) "
@"From the contextual menu which appears, click 'Compress...' "
@"A new file with a name ending in .zip will appear.\n\n"
@"Please send the .zip file to our support team. Thank you for helping us to support",
presenterExecutableName,
appVersion,
appVersionString,
systemDescription,
longDescription] ;
BOOL writeOk = [text writeToFile:filePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&writeError] ;
if (writeOk) {
NSString* msg = [[NSString alloc] initWithFormat:
NSLocalizedString(@"A file named \"%@\" has just been written to your desktop.\n\nThe extended error information in this file may help our Support crew to solve the problem.\n\nPlease review this file for any too-sensitive information, zip it, and then attach the .zip to your email.", nil),
filename] ;
[SSYAlert runModalDialogTitle:nil
message:msg
buttons:nil] ;
#if !__has_feature(objc_arc)
[msg release] ;
#endif
mailableDescription = [NSString stringWithFormat:
@"****** I M P O R T A N T I N S T R U C T I O N S ******\n\n"
@"*** Please look on your Desktop and find the file named %@ ***\n"
@"Review for your privacy, zip and ATTACH it before sending this.\n"
@"To zip a file, perform a secondary click (right-click or control-click)\n"
@"on it, then from the contextual menu which appears, click 'Compress ...'.\n"
@"Attach the .zip file which appears. Thank you.\n",
filename] ;
}
else {
mailableDescription = [mailableDescription stringByAppendingString:
@"\n\n*** The above description was truncated to fit in an email, but writing it to a file failed."] ;
}
}
}
else {
mailableDescription = [error description] ;
}
NSMutableString* body = [NSMutableString stringWithFormat:@"%@\n\n\n\n%@ %@ (%@)\n%@\n\n%@",
NSLocalizedString(@"Please insert any additional information regarding what happened that might help us to investigate this problem:", nil),
presenterExecutableName,
appVersionString,
appVersion,
systemDescription,
mailableDescription] ;
[SSYMailto emailTo:[SSYAlert supportEmailString]
subject:[NSString stringWithFormat:
@"%@ Error %ld",
presenterExecutableName,
(long)[error code]]
body:body] ;
}
/*!
@brief This method will *always* run when a button is clicked
@details -sheetDidEnd::: *may* also run when a button is clicked,
and if it does, it will run a little prior to this one, in the same
run loop cycle.
*/
- (IBAction)clickedButton:(id)sender {
#if !__has_feature(objc_arc)
[self retain]; // Needed for macOS 10.11
#endif
// For classic button layout
// Button1 --> tag=NSAlertFirstButtonReturn
// Button2 --> tag=NSAlertSecondButtonReturn
// Button3 --> tag=NSAlertThirdButtonReturn
[self setAlertReturn:[sender tag]] ;
if (m_dontGoAwayUponButtonClicked) {
if ([self isDoingModalDialog]) {
[NSApp stopModal] ;
[self setIsDoingModalDialog:NO] ;
}
}
if ([self clickTarget]) {
[[self clickTarget] recklessPerformSelector:[self clickSelector]
object:self] ;
}
if ([self checkboxState] == NSControlStateValueOn) {
[[self checkboxInvocation] invoke] ;
}
if (!m_dontGoAwayUponButtonClicked) {
[self goAway] ;
}
#if !__has_feature(objc_arc)
[self release]; // Needed for macOS 10.11
#endif
}
- (void)setTargetActionForButton:(NSButton*)button {
[button setTarget:self] ;
[button setAction:@selector(clickedButton:)] ;
}
- (void)stealObjectsFromAppleAlerts {
NSAlert* nsAlert = [[NSAlert alloc] init] ;
NSImageView* iconView ;
NSRect frame = NSMakeRect(0.0, 0.0, 64.0, 64.0) ;
NSImage* badge ;
// Steal localized word for "alert"
[self setWordAlert:[nsAlert messageText]] ;
// Steal the icon. (Could also get this from NSBundle I suppose.)
NSImage* rawIcon = [nsAlert icon] ;
/* The next line was added to fix a crash during subsequent app quitting
which started in macOS 12:
* Assertion failed: (![[NSApp _openWindows] NS_containsObjectIdenticalTo:self]), function -[NSWindow dealloc], file NSWindow.m, line 1579
I only noticed this if I quit after licensing. After licensing, there
are two SSYAlert objects created and destroyed in succession. The first
one shows the downloaded License Information and the second one I forgot
what it shows. Anyhow, I noticted that if I quit the app immediately
after dismissing those two SSYAlerts in succession, the array returned by
[NSApplication windows] included two _NSAlertPanel which I found were
attached to the `nsAlert` created here. Even after the fix, these two
_NSAlertPanel objects remain in [NSApplication windows] for some time, but
will be found to be gone later if you do not quit immediately. Although
sending either -close or -performClose: fixed the assertion+crash, I
decided on the former since the latter calls NSBeep, probably because
the "window doesn’t have a close button", as explained in documentation
of -[NSWindow performClose:]. */
[nsAlert.window close];
#if !__has_feature(objc_arc)
[nsAlert release] ;
#endif
NSImage* image = [[NSImage alloc] initWithSize:(NSMakeSize(64.0, 64.0))] ;
[image lockFocus] ;
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
CGFloat borderWength = 8.0 ;
[rawIcon drawInRect:NSMakeRect(
borderWength,
borderWength,
[image size].width - 2 * borderWength,
[image size].height - 2 * borderWength)
fromRect:NSZeroRect
operation:NSCompositingOperationSourceOver
fraction:1.0] ;
[image unlockFocus] ;
// Set raw icon as "informational"
iconView = [[NSImageView alloc] initWithFrame:frame] ;
NSImage* imageCopy = [image copy] ;
iconView.image = imageCopy ;
[self setIconInformational:iconView] ;
#if !__has_feature(objc_arc)
[iconView release] ;
[imageCopy release] ;
#endif
// Badge with yellow and set as "warning"
badge = [SSYVectorImages imageStyle:SSYVectorImageStyleHexagon
wength:64.0
color:[NSColor yellowColor]
darkModeView:nil // Ignored since we passed in a constant `color`
rotateDegrees:90.0
inset:12.0] ;
[image lockFocus] ;
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[badge drawInRect:NSMakeRect(
[image size].width / 2,
0,
[image size].width / 2,
[image size].height / 2)
fromRect:NSZeroRect
operation:NSCompositingOperationSourceOver
fraction:0.75] ;
[image unlockFocus] ;
iconView = [[NSImageView alloc] initWithFrame:frame] ;
imageCopy = [image copy] ;
iconView.image = imageCopy ;
[self setIconWarning:iconView] ;
#if !__has_feature(objc_arc)
[iconView release] ;
[imageCopy release] ;
#endif
// Badge with red and set as "critical"
badge = [SSYVectorImages imageStyle:SSYVectorImageStyleHexagon
wength:64.0
color:[NSColor redColor]
darkModeView:nil // Ignored since we passed in a constant `color`
rotateDegrees:90.0
inset:12.0] ;
[image lockFocus] ;
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[badge drawInRect:NSMakeRect(
[image size].width / 2,
0,
[image size].width / 2,
[image size].height / 2)
fromRect:NSZeroRect
operation:NSCompositingOperationSourceOver
fraction:0.75] ;
[image unlockFocus] ;
iconView = [[NSImageView alloc] initWithFrame:frame] ;
imageCopy = [image copy] ;
iconView.image = imageCopy ;
[self setIconCritical:iconView] ;
#if !__has_feature(objc_arc)
[iconView release] ;
[image release] ;
[imageCopy release] ;
#endif
/* Thanks to Brian Dunagan for the few lines of compositing code used above.
http://bdunagan.com/2010/01/25/cocoa-tip-nsimage-composites/ */
}
#pragma mark * Public Methods for Setting views
- (void)setSupportEmail {
if ([SSYAlert supportEmailString] != nil) {
NSButton* button = [self supportButton] ;
if (!button) {
// The image is 32 and the bezel border on each side is 2*2=4.
// However, testing shows that we need 38. Oh, well.
NSRect frame = NSMakeRect(0, 0, 38.0, 38.0) ;
button = [[NSButton alloc] initWithFrame:frame] ;
[button setBezelStyle:NSBezelStyleRegularSquare] ;
[button setTarget:self] ;
[button setAction:@selector(support:)] ;
NSString* imagePath = [[NSBundle mainAppBundle] pathForResource:@"support"
ofType:@"tif"] ;
NSImage* image = [[NSImage alloc] initByReferencingFile:imagePath] ;
[button setImage:image] ;
NSString* toolTip = [[self class] contactSupportToolTip] ;
[button setToolTip:toolTip] ;
[self setSupportButton:button] ;
[[[self window] contentView] addSubview:button] ;
#if !__has_feature(objc_arc)
[image release] ;
[button release] ;
#endif
}
[button setEnabled:YES] ;
}
else {
[[self supportButton] removeFromSuperviewWithoutNeedingDisplay] ;
[self setSupportButton:nil] ;
}
}