forked from jerrykrinock/ClassesObjC
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSSYAlert.m
executable file
·2176 lines (1848 loc) · 67 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 "SSYAppLSUI.h"
#import "SSYMailto.h"
#import "SSYSheetManager.h"
#import "SSYSystemDescriber.h"
#import "SSYWrappingCheckbox.h"
#import "NSError+SSYAdds.h"
#import "NSInvocation+Quick.h"
#import "NSString+Clipboard.h"
#import "NSString+LocalizeSSY.h"
#import "NSString+Truncate.h"
#import "NSView+Layout.h"
#import "NSWindow+Sizing.h"
NSObject <SSYAlertErrorHideManager> * gSSYAlertErrorHideManager = nil ;
static SSYAlert *sharedAlert = 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]) {
length = MAX(length, [[self performSelector:selector] length]) ;
}
selector = @selector(stringValue) ;
if ([self respondsToSelector:selector]) {
// Because NSImageView has a -stringValue describing each of its sizes...
if (![self isKindOfClass:[NSImageView class]]) {
length = MAX(length, [[self performSelector:selector] length]) ;
}
}
// Recursion into documentView, if any
selector = @selector(documentView) ;
if ([self respondsToSelector:selector]) {
length = [[self performSelector: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 ;
@try {
if (![self respondsToSelector:@selector(encodeWithCoder:)]) {
NSException* ex = [NSException exceptionWithName:@"Can't copy"
reason:@"Can't archive"
userInfo:nil];
[ex raise] ;
}
archive = [NSKeyedArchiver archivedDataWithRootObject:self] ;
copy = [NSKeyedUnarchiver unarchiveObjectWithData:archive] ;
}
@catch (NSException* ex) {
NSLog(@"Error: %@: Exception: %@. Returning self since could not archive/copy %@", NSStringFromSelector(_cmd), ex, self) ;
copy = self ;
}
@finally { }
return [copy retain] ;
}
@end
@interface NSTextView (SSYAlertUsage)
- (void)configureForSSYAlertUsage ;
@end
@implementation NSTextView (SSYAlertUsage)
- (void)configureForSSYAlertUsage {
[self setEditable:NO] ;
[self setDrawsBackground:NO] ;
[self setSelectable:NO] ;
// 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) invoke -setNeedsDisplay: or -display on them.
// 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) NSButton* helpButton ;
@property (retain) NSButton* supportButton ;
@property (retain) SSYWrappingCheckbox* checkbox ;
@property (retain) NSButton* button1 ;
@property (retain) NSButton* button2 ;
@property (retain) NSButton* button3 ;
@property (copy) NSString* helpAnchorString ;
@property (retain) NSError* errorPresenting ;
@property (retain) NSImageView* iconInformational ;
@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 isRetainedForSheet ;
@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
@interface SSYAlertWindow : NSWindow
@end
@implementation SSYAlertWindow
/*!
@brief Override of base class method which does damage control in the
event that the content exceeds the available height on the screen.
@details Damage control is done by moving the critical controls up onto
the screen. Note that they will cover other subviews, but it's more
important that the user see the critical controls. This is what Apple's
alerts do when there is a similar overflow.
This was added in BookMacster 1.9.5 to replace code in -doLayout which
did not work properly.
*/
- (void)setFrameOrigin:(NSPoint)frameOrigin {
[super setFrameOrigin:frameOrigin] ;
SSYAlert* alert = [self windowController] ;
// Defensive Programming
if (![alert isKindOfClass:[SSYAlert class]]) {
NSLog(@"Warning 624-2948 Expected SSYAlert") ;
return ;
}
CGFloat overflowHeight ;
if ([self isSheet]) {
// This branch was added in BookMacster 1.9.8.
// If there is space between the top of the parent window and the menu bar,
// Cocoa will move the window up into that extra height in order to make
// room for the sheet, and unfortunately this has not been done yet. So
// I need to, arghhh, predict what Cocoa is going to do…
NSWindow* parentWindow = [[self windowController] documentWindow] ;
CGFloat useableScreenHeight = [[parentWindow screen] visibleFrame].size.height ;
// useableScreenHeight does not include menu bar and does not include the Dock.
CGFloat tootlebarHeight = [parentWindow tootlebarHeight] ;
CGFloat availableHeight = useableScreenHeight - tootlebarHeight ;
overflowHeight = [self frame].size.height - availableHeight ;
}
else {
overflowHeight = WINDOW_EDGE_SPACING - [self frame].origin.y ;
}
if (overflowHeight > 0.0) {
[[alert button1] deltaY:overflowHeight deltaH:0.0] ;
[[alert button2] deltaY:overflowHeight deltaH:0.0] ;
[[alert button3] deltaY:overflowHeight deltaH:0.0] ;
[[alert helpButton] deltaY:overflowHeight deltaH:0.0] ;
[[alert supportButton] deltaY:overflowHeight deltaH:0.0] ;
[[alert checkbox] deltaY:overflowHeight deltaH:0.0] ;
}
}
#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] == NSKeyDown) {
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**)hdlFirstResponder
previousResponder:(NSView**)hdlPreviousResponder {
if (!*hdlFirstResponder) {
if ([window makeFirstResponder:self]) {
[window setInitialFirstResponder:self] ;
*hdlFirstResponder = self ;
*hdlPreviousResponder = self ;
}
}
else {
[*hdlPreviousResponder setNextKeyView:self] ;
*hdlPreviousResponder = 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
+ (NSString*)supportEmailString {
return [[NSBundle mainBundle] objectForInfoDictionaryKey:SSYAlert_ErrorSupportEmailKey] ;
}
- (id)clickObject {
return [[clickObject retain] autorelease];
}
- (void)setClickObject:(id)value {
if (clickObject != value) {
[clickObject release];
clickObject = [value retain];
}
}
#pragma mark * Accessors
@synthesize icon ;
@synthesize progressBar ;
@synthesize titleTextView ;
@synthesize smallTextView ;
@synthesize helpButton ;
@synthesize supportButton ;
@synthesize checkbox ;
@synthesize button1 ;
@synthesize button2 ;
@synthesize button3 ;
@synthesize helpAnchorString ;
@synthesize errorPresenting ;
@synthesize iconInformational ;
@synthesize iconCritical ;
@synthesize buttonPrototype ;
@synthesize wordAlert ;
@synthesize documentWindow ;
@synthesize isRetainedForSheet ;
@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 shouldStickAround = m_shouldStickAround ;
@synthesize nextProgressUpdate ;
- (CGFloat)rightColumnMaximumWidth {
float 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] autorelease] ; ;
}
return whyDisabled ;
}
- (void)setWhyDisabled:(NSString*)whyDisabled {
[[self button1] setToolTip:whyDisabled] ;
@synchronized(self) {
if (whyDisabled != m_whyDisabled) {
[m_whyDisabled release] ;
m_whyDisabled = [whyDisabled copy] ;
}
}
}
- (NSMutableArray *)otherSubviews {
if (!otherSubviews) {
otherSubviews = [[NSMutableArray alloc] init];
}
return [[otherSubviews retain] autorelease];
}
#pragma mark * Class Methods returning Constants
+ (NSFont*)titleTextFont {
return [NSFont boldSystemFontOfSize:13] ;
}
+ (NSFont*)smallTextFont {
return [NSFont systemFontOfSize:12] ;
}
+ (float)titleTextHeight {
return 17 ;
}
+ (float)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:NSRoundedBezelStyle] ;
return [button autorelease] ;
}
#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:.
@details Cocoa's arrangement allows an unlimited number of error recovery options,
indexed from 0. Our -doLayoutError: method only allows three options, which are
indexed like the buttons in NSAlert. In particular, note that the values
represented by 0 and 1 are reversed.
*/
+ (NSUInteger)recoveryOptionIndexForRecoveryOption:(NSInteger)recoveryOption {
NSUInteger recoveryOptionIndex ;
switch (recoveryOption) {
case NSAlertDefaultReturn /* 1 */ :
recoveryOptionIndex = 0 ;
break;
case NSAlertAlternateReturn /* 0 */ :
recoveryOptionIndex = 1 ;
break;
case NSAlertOtherReturn /* -1 */ :
recoveryOptionIndex = 2 ;
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 ;
NSError* docOpeningError = nil ;
NSError* deepestRecoverableError = [error deepestRecoverableError] ;
id recoveryAttempter = [deepestRecoverableError openRecoveryAttempterForRecoveryOption:recoveryOption
error_p:&docOpeningError] ;
if (recoveryAttempter) {
// 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 retain] autorelease]
recoveryOption:recoveryOption
delegate:delegate
didRecoverSelector:didRecoverSelector
contextInfo:[[infoDictionary retain] autorelease]] ;
// Also, the retain] autorelease] is probably not necessary since I'm invoking attemptRecoveryFromError:::::
// directly, but I'm always fearful of crashes due to invalid contextInfo.
result = SSYAlertRecoveryAttemptedAsynchronously ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:delegate:didRecoverSelector:contextInfo:)]) {
/* This is an error produced by Cocoa.
In particular, in Mac OS X 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 retain] autorelease]
optionIndex:recoveryOptionIndex
delegate:delegate
didRecoverSelector:didRecoverSelector
contextInfo:[[infoDictionary retain] autorelease]] ;
// Also, the retain] autorelease] is probably not necessary since I'm invoking attemptRecoveryFromError:::::
// directly, but I'm always fearful of crashes due to invalid contextInfo.
result = SSYAlertRecoveryAttemptedAsynchronously ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:recoveryOption:)]) {
BOOL ok = [recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
recoveryOption:recoveryOption] ;
result = ok ? SSYAlertRecoverySucceeded : SSYAlertRecoveryFailed ;
}
else if ([recoveryAttempter respondsToSelector:@selector(attemptRecoveryFromError:optionIndex:)]) {
// This is an error produced by Cocoa.
NSInteger recoveryOptionIndex = [self recoveryOptionIndexForRecoveryOption:recoveryOption] ;
BOOL ok = [recoveryAttempter attemptRecoveryFromError:deepestRecoverableError
optionIndex:recoveryOptionIndex] ;
result = ok ? SSYAlertRecoverySucceeded : SSYAlertRecoveryFailed ;
}
else {
NSLog(@"Internal Error 342-5587. Given Recovery Attempter %@ does not respond to any attemptRecoveryFromError:... method", recoveryAttempter) ;
}
}
else if (docOpeningError) {
[self alertError:docOpeningError] ;
}
return result ;
}
- (IBAction)help:(id)sender {
[[NSHelpManager sharedHelpManager] openHelpAnchor:[self helpAnchorString]
inBook:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleHelpBookName"]] ;
}
- (IBAction)support:(id)sender {
[SSYAlert supportError:[self errorPresenting]] ;
}
+ (void)supportError:(NSError*)error {
NSString* appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"] ;
// Note: If you'd prefer the app name to be localized, use "CFBundleName" instead.
NSString* appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] ;
NSString* appVersionString = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"] ;
NSString* systemDescription = [SSYSystemDescriber softwareVersionAndArchitecture] ;
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 performSelector:@selector(longDescription)] ;
NSString* filename = [NSString stringWithFormat:
@"%@-Error-%x.txt",
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"],
(int)[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, bookmarks in particular. Please skim through it before sending. "
@"Delete anything which is too private, add a little note in its place, then save this file.\n\n"
@"To zip this file, select it in Finder, then execute a secondary click. A secondary click "
@"can also be produced by clicking it with the right/secondary mouse button, or holding down "
@"the 'control' key while clicking on it. 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 crew, and thank you for helping us to support",
appName,
appVersion,
appVersionString,
systemDescription,
longDescription] ;
BOOL writeOk = [text writeToFile:filePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&writeError] ;
if (writeOk) {
NSString* msg = [NSString localizeFormat:
@"additionalInfoZipX",
filename] ;
[SSYAlert runModalDialogTitle:nil
message:msg
buttons:nil] ;
mailableDescription = [NSString stringWithFormat:
@"*** Please review, zip and attach file %@. ***",
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%@",
[NSString localize:@"additionalInfoAsk"],
appName,
appVersionString,
appVersion,
systemDescription,
mailableDescription] ;
[SSYMailto emailTo:[SSYAlert supportEmailString]
subject:[NSString stringWithFormat:
@"%@ Error %d",
appName,
[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 {
// In case executing the clickSelector method will remove our last retainer...
[self retain] ;
// Remember:
// Button1 --> tag=NSAlertDefaultReturn = 1
// Button2 --> tag=NSAlertAlternateReturn = 0
// Button3 --> tag=NSAlertOtherReturn = -1
[self setAlertReturn:[sender tag]] ;
if (!m_shouldStickAround) {
[self goAway] ;
}
if ([self clickTarget]) {
[[self clickTarget] performSelector:[self clickSelector]
withObject:self] ;
[self setIsDoingModalDialog:NO] ;
}
if ([self checkboxState] == NSOnState) {
[[self checkboxInvocation] invoke] ;
}
// Balance the -retain, above.
[self release] ;
}
- (void)setTargetActionForButton:(NSButton*)button {
[button setTarget:self] ;
[button setAction:@selector(clickedButton:)] ;
}
- (void)stealObjectsFromAppleAlerts {
NSPanel* panel ;
panel = NSGetAlertPanel(nil, @"dummyInfoText", @"OK", nil, nil) ;
NSArray* subviews = [[panel contentView] subviews] ;
for (NSView* subview in subviews) {
if ([subview isKindOfClass:[NSImageView class]]) {
self.iconInformational = (NSImageView*)subview ;
}
else if ([subview isKindOfClass:[NSTextField class]]) {
NSString* string = [(NSTextField*)subview stringValue] ;
if ([string isEqualToString:@"dummyInfoText"]) {
}
else {
self.wordAlert = string ;
}
}
}
// Now, go back and get the critical-badged icon
panel = NSGetCriticalAlertPanel(@"", @"", @"OK", nil, nil) ;
subviews = [[panel contentView] subviews] ;
for (NSView* subview in subviews) {
if ([subview isKindOfClass:[NSImageView class]]) {
self.iconCritical = (NSImageView*)subview ;
break ;
}
}
}
#pragma mark * Public Methods for Setting views
- (void)setSupportEmail {
if ([SSYAlert supportEmailString] != nil) {
NSButton* button ;
if (!(button = [self supportButton])) {
// 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) ;
NSButton* button = [[NSButton alloc] initWithFrame:frame] ;
[button setBezelStyle:NSRegularSquareBezelStyle] ;
[button setTarget:self] ;
[button setAction:@selector(support:)] ;
NSString* imagePath = [[NSBundle mainBundle] pathForResource:@"support"
ofType:@"tif"] ;
NSImage* image = [[NSImage alloc] initByReferencingFile:imagePath] ;
[button setImage:image] ;
[image release] ;
NSString* toolTip = [[self class] contactSupportToolTip] ;
[button setToolTip:toolTip] ;
[self setSupportButton:button] ;
[[[self window] contentView] addSubview:button] ;
[button release] ;
}
[button setEnabled:YES] ;
}
else {
[[self supportButton] removeFromSuperviewWithoutNeedingDisplay] ;
[self setSupportButton:nil] ;
}
}
//#define DEFAULT_MIN_TEXT_FIELD_WIDTH 250.0
- (void)cleanSlate {
[self setWindowTitle:nil] ; // Defaults to mainBundle's CFBundleName (which should be the localized name of the app)
[self setShowsProgressBar:NO] ;
[self setTitleText:nil] ;
[self setSmallText:nil] ;
[self setIconStyle:SSYAlertIconNoIcon] ;
[self setButton1Title:nil] ;
[self setButton2Title:nil] ;
[self setButton3Title:nil] ;
[self setHelpAnchor:nil] ;
[self setCheckboxTitle:nil] ;
[self setWhyDisabled:nil] ;
[self removeAllOtherSubviews] ;
// The following is a holdover from when SSYAlert support a
// configuration stack, and may no longer be needed...
// Now, there may still be some subviews left in the view...
// The -removeAllOtherSubviews only removed those which are in
// the current self.otherSubviews array. But if the configuration has
// been pushed, self.otherSubviews will be a new, empty array.
// Therefore, we now ask the -contentView if it has any more subviews
// left and if so remove them...
NSView* contentView = [[self window] contentView] ;
// We use a regular C loop since -removeFromSuperviewWithoutNeedingDisplay
// mutates the [contentView subviews] and therefore we cannot
// use an enumeration
NSArray* subviews = [contentView subviews] ;
NSInteger i ;
for (i=[subviews count]-1; i>=0; i--) {
NSView* subview = [subviews objectAtIndex:i] ;
[subview removeFromSuperviewWithoutNeedingDisplay] ;
}
self.allowsShrinking = YES ;
[self setIsEnabled:YES] ;
self.isVisible = YES ;
self.progressBarShouldAnimate = NO ;
[self setRightColumnMinimumWidth:0.0] ;
[self setRightColumnMaximumWidth:FLT_MAX] ;
}
- (void)setWindowTitle:(NSString*)title {
if (!title) {
title = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"] ; // CFBundleName may be localized
}
[[self window] setTitle:title] ;
}
- (void)setShowsProgressBar:(BOOL)showsProgressBar {
NSProgressIndicator* progressBar_ = [self progressBar] ;
if (showsProgressBar) {
if (!progressBar_) {
// Add progress bar
progressBar_ = [[NSProgressIndicator alloc] initWithFrame:NSZeroRect] ;
[progressBar_ setControlSize:NSSmallControlSize] ;
[progressBar_ setStyle:NSProgressIndicatorBarStyle] ;
[progressBar_ sizeToFit] ;
[progressBar_ setUsesThreadedAnimation:YES] ;
[self setProgressBar:progressBar_] ;
[[[self window] contentView] addSubview:progressBar_] ;
[progressBar_ release] ;
}
}
else if (progressBar_) {
[progressBar_ removeFromSuperviewWithoutNeedingDisplay] ;
[self setProgressBar:nil] ;
}
}
- (void)setTitleText:(NSString*)text {
NSTextView* textView = [self titleTextView] ;
if (text) {
if (!textView) {
textView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 100, [SSYAlert titleTextHeight])] ;
[textView setFont:[SSYAlert titleTextFont]] ;
[textView configureForSSYAlertUsage] ;
[self setTitleTextView:textView] ;
[textView release] ;
[[[self window] contentView] addSubview:textView] ;
}
[textView setString:[text stringByTruncatingMiddleToLength:self.titleMaxChars
wholeWords:YES]] ;
}
else {
[textView removeFromSuperviewWithoutNeedingDisplay] ;
[self setTitleTextView:nil] ;
}
}
- (void)setTitleToDefaultAlert {
[self setTitleText:[self wordAlert]] ;
}
- (NSTextView*)smallTextViewPrototype {
NSTextView* textView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, 100, [SSYAlert smallTextHeight])] ;
[textView setFont:[SSYAlert smallTextFont]] ;
[textView configureForSSYAlertUsage] ;
return [textView autorelease] ;
}
- (void)setSmallText:(NSString*)text {
NSTextView* textView = [self smallTextView] ;
if (text) {
if (!textView) {
textView = [self smallTextViewPrototype] ;
[self setSmallTextView:textView] ;
[[[self window] contentView] addSubview:textView] ;
}
[textView setString:text] ;
}
else {
[textView removeFromSuperviewWithoutNeedingDisplay] ;
[self setSmallTextView:nil] ;
}
}
- (void)setIconStyle:(NSInteger)iconStyle {
NSImageView* icon_ ;
switch (iconStyle) {
case SSYAlertIconNoIcon:
icon_ = nil ;
break ;
case SSYAlertIconInformational:
icon_ = [self iconInformational] ;
break ;
case SSYAlertIconCritical:
default:
icon_ = [self iconCritical] ;
break ;
}
if (icon_ != [self icon]) {
// Remove existing icon, if any
[[self icon] removeFromSuperviewWithoutNeedingDisplay] ;
// Set new icon
[self setIcon:icon_] ;
if (icon_) {
[[[self window] contentView] addSubview:icon_] ;
}
}
}
- (void)setButton1Title:(NSString*)title {
if (title) {
NSButton* button ;
if (!(button = [self button1])) {
button = [SSYAlert makeButton] ;
[button setKeyEquivalent:@"\r"] ;
[button setTag:NSAlertDefaultReturn] ;
[self setTargetActionForButton:button] ;
[self setButton1:button] ;
[[[self window] contentView] addSubview:button] ;
}
[button setEnabled:YES] ;
[button setTitle:title] ;
[button sizeToFitIncludingNiceMargins] ;
}
else if (title && ![title length]) {
[[self button1] setEnabled:NO] ;
}
else {