-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSFBCrashReporterWindowController.m
420 lines (313 loc) · 14.3 KB
/
SFBCrashReporterWindowController.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
/*
* Copyright (C) 2009 - 2020 Stephen F. Booth <[email protected]>
* See https://github.com/sbooth/SFBCrashReporter/blob/master/LICENSE.txt for license information
*/
#import "SFBCrashReporterWindowController.h"
#import "SFBSystemInformation.h"
#import "GenerateFormData.h"
#import <Contacts/Contacts.h>
#define USE_NSTEXTVIEW_PRIVATE_API 1
#if USE_NSTEXTVIEW_PRIVATE_API
@interface NSTextView (ApplePrivate)
- (void)setPlaceholderString:(NSString *)placeholder;
@end
#endif
@interface SFBCrashReporterWindowController ()
{
@private
NSURLConnection *_urlConnection;
NSMutableData *_responseData;
}
// Keep a strong reference to self so ARC doesn't release the window before it's shown
@property (nonatomic, strong) id self_reference;
@end
@interface SFBCrashReporterWindowController (Private)
- (NSString *)applicationName;
- (void)sendCrashReport;
- (void)showSubmissionSucceededSheet;
- (void)showSubmissionFailedSheet:(NSError *)error;
@end
@implementation SFBCrashReporterWindowController
+ (void)initialize
{
// Register reasonable defaults for most preferences
NSMutableDictionary *defaultsDictionary = [NSMutableDictionary dictionary];
[defaultsDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"SFBCrashReporterIncludeAnonymousSystemInformation"];
[defaultsDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"SFBCrashReporterIncludeEmailAddress"];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsDictionary];
}
+ (void)showWindowForCrashLogPath:(NSString *)crashLogPath submissionURL:(NSURL *)submissionURL
{
NSParameterAssert(nil != crashLogPath);
NSParameterAssert(nil != submissionURL);
SFBCrashReporterWindowController *windowController = [[self alloc] init];
windowController.crashLogPath = crashLogPath;
windowController.submissionURL = submissionURL;
[[windowController window] center];
[windowController showWindow:self];
windowController.self_reference = windowController;
}
// Should not be called directly by anyone except this class
- (id)init
{
return [super initWithWindowNibName:@"SFBCrashReporterWindow" owner:self];
}
- (void)windowDidLoad
{
// Set the window's title
NSString *applicationName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
NSString *applicationShortVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *windowTitle;
if(!applicationShortVersion)
windowTitle = [NSString stringWithFormat:NSLocalizedString(@"Crash Reporter: %@", @""), applicationName];
else
windowTitle = [NSString stringWithFormat:NSLocalizedString(@"Crash Reporter: %@ (%@)", @""), applicationName, applicationShortVersion];
[[self window] setTitle:windowTitle];
// Populate the e-mail field with the user's primary e-mail address
CNContactStore *contactStore = [[CNContactStore alloc] init];
[contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError *error) {
#pragma unused(error)
if(granted) {
CNContact *meContact = [contactStore unifiedMeContactWithKeysToFetch:@[CNContactEmailAddressesKey] error:nil];
if(meContact) {
NSString *emailAddress = [[[meContact emailAddresses] firstObject] value];
if(emailAddress) {
dispatch_async(dispatch_get_main_queue(), ^{
self.emailAddress = emailAddress;
});
}
}
}
}];
// Set the font for the comments
[self.commentsTextView setTypingAttributes:[NSDictionary dictionaryWithObject:[NSFont systemFontOfSize:10.0] forKey:NSFontAttributeName]];
#if USE_NSTEXTVIEW_PRIVATE_API
// Private API for placeholder strings in NSTextView
if([self.commentsTextView respondsToSelector:@selector(setPlaceholderString:)])
[self.commentsTextView setPlaceholderString:NSLocalizedString(@"Please enter a description of the actions leading up to the crash.", @"")];
#endif
}
- (void)windowWillClose:(NSNotification *)notification
{
#pragma unused(notification)
// Ensure we don't leak memory
self.self_reference = nil;
}
#pragma mark Action Methods
// Send the report off
- (IBAction)sendReport:(id)sender
{
#pragma unused(sender)
[self sendCrashReport];
}
// Don't do anything except dismiss our window
- (IBAction)ignoreReport:(id)sender
{
#pragma unused(sender)
[[self window] orderOut:self];
}
// Move the crash log to the trash since the user isn't interested in submitting it
- (IBAction)discardReport:(id)sender
{
#pragma unused(sender)
NSError *error = nil;
if(![[NSFileManager defaultManager] trashItemAtURL:[NSURL fileURLWithPath:self.crashLogPath] resultingItemURL:NULL error:&error])
NSLog(@"SFBCrashReporter: Unable to move %@ to trash: %@", self.crashLogPath, error);
[[self window] orderOut:self];
}
@end
@implementation SFBCrashReporterWindowController (Private)
// Convenience method for bindings
- (NSString *)applicationName
{
return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
}
// Do the actual work of building the HTTP POST and submitting it
- (void)sendCrashReport
{
NSMutableDictionary *formValues = [NSMutableDictionary dictionary];
// Append system information, if specified
if([[NSUserDefaults standardUserDefaults] boolForKey:@"SFBCrashReporterIncludeAnonymousSystemInformation"]) {
SFBSystemInformation *systemInformation = [[SFBSystemInformation alloc] init];
id value = nil;
if((value = [systemInformation machine]))
[formValues setObject:value forKey:@"machine"];
if((value = [systemInformation model]))
[formValues setObject:value forKey:@"model"];
if((value = [systemInformation physicalMemory]))
[formValues setObject:value forKey:@"physicalMemory"];
if((value = [systemInformation busFrequency]))
[formValues setObject:value forKey:@"busFrequency"];
if((value = [systemInformation cpuFrequency])) {
[formValues setObject:value forKey:@"cpuFrequency"];
[formValues setObject:value forKey:@"CPUFrequency"];
}
if((value = [systemInformation cpuFamily])) {
[formValues setObject:value forKey:@"cpuFamily"];
[formValues setObject:value forKey:@"CPUFamily"];
}
if((value = [systemInformation cpuType])) {
[formValues setObject:value forKey:@"cpuType"];
[formValues setObject:value forKey:@"CPUType"];
}
if((value = [systemInformation cpuSubtype])) {
[formValues setObject:value forKey:@"cpuSubtype"];
[formValues setObject:value forKey:@"CPUSubtype"];
}
if((value = [systemInformation numberOfCPUs]))
[formValues setObject:value forKey:@"numberOfCPUs"];
if((value = [systemInformation physicalCPUs]))
[formValues setObject:value forKey:@"physicalCPUs"];
if((value = [systemInformation logicalCPUs]))
[formValues setObject:value forKey:@"logicalCPUs"];
if((value = [systemInformation systemVersion]))
[formValues setObject:value forKey:@"systemVersion"];
if((value = [systemInformation systemBuildVersion]))
[formValues setObject:value forKey:@"systemBuildVersion"];
[formValues setObject:[NSNumber numberWithBool:YES] forKey:@"systemInformationIncluded"];
}
else
[formValues setObject:[NSNumber numberWithBool:NO] forKey:@"systemInformationIncluded"];
// Include email address, if permitted
if([[NSUserDefaults standardUserDefaults] boolForKey:@"SFBCrashReporterIncludeEmailAddress"] && self.emailAddress)
[formValues setObject:self.emailAddress forKey:@"emailAddress"];
// Optional comments
NSAttributedString *attributedComments = [self.commentsTextView attributedSubstringForProposedRange:NSMakeRange(0, NSUIntegerMax) actualRange:NULL];
if([[attributedComments string] length])
[formValues setObject:[attributedComments string] forKey:@"comments"];
// The most important item of all
[formValues setObject:[NSURL fileURLWithPath:self.crashLogPath] forKey:@"crashLog"];
// Add the application information
NSString *applicationName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
if(applicationName)
[formValues setObject:applicationName forKey:@"applicationName"];
NSString *applicationIdentifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
if(applicationIdentifier)
[formValues setObject:applicationIdentifier forKey:@"applicationIdentifier"];
NSString *applicationVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
if(applicationVersion)
[formValues setObject:applicationVersion forKey:@"applicationVersion"];
NSString *applicationShortVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if(applicationShortVersion)
[formValues setObject:applicationShortVersion forKey:@"applicationShortVersion"];
// Create a date formatter
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Determine which locale the developer would like dates/times in
NSString *localeName = [[NSUserDefaults standardUserDefaults] stringForKey:@"SFBCrashReporterPreferredReportingLocale"];
if(!localeName) {
localeName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"SFBCrashReporterPreferredReportingLocale"];
// US English is the default
if(!localeName)
localeName = @"en_US";
}
NSLocale *localeToUse = [[NSLocale alloc] initWithLocaleIdentifier:localeName];
[dateFormatter setLocale:localeToUse];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
// Include the date and time
[formValues setObject:[dateFormatter stringFromDate:[NSDate date]] forKey:@"date"];
// Generate the form data
NSString *boundary = @"81e29ba4f957efe5916039f587fe3ed7";
NSData *formData = GenerateFormData(formValues, boundary);
// Set up the HTTP request
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:self.submissionURL];
[urlRequest setHTTPMethod:@"POST"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[urlRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
[urlRequest setValue:@"SFBCrashReporter" forHTTPHeaderField:@"User-Agent"];
[urlRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[formData length]] forHTTPHeaderField:@"Content-Length"];
[urlRequest setHTTPBody:formData];
[self.progressIndicator startAnimation:self];
[self.reportButton setEnabled:NO];
[self.ignoreButton setEnabled:NO];
[self.discardButton setEnabled:NO];
// Submit the URL request
_urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
}
- (void)showSubmissionSucceededSheet
{
[self.progressIndicator stopAnimation:self];
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = NSLocalizedString(@"The crash report was successfully submitted.", @"");
alert.informativeText = [NSString stringWithFormat:NSLocalizedString(@"Thank you for taking the time to help improve %@!", @""), [self applicationName]];
[alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) {
#pragma unused(returnCode)
[[self window] orderOut:self];
}];
}
- (void)showSubmissionFailedSheet:(NSError *)error
{
NSParameterAssert(nil != error);
[self.progressIndicator stopAnimation:self];
NSAlert *alert = [[NSAlert alloc] init];
alert.messageText = NSLocalizedString(@"An error occurred while submitting the crash report.", @"");
alert.informativeText = [NSString stringWithFormat:NSLocalizedString(@"The error was: %@", @""), [error localizedDescription]];
[alert beginSheetModalForWindow:[self window] completionHandler:^(NSModalResponse returnCode) {
#pragma unused(returnCode)
[[self window] orderOut:self];
}];
}
#pragma mark NSTextView delegate methods
- (BOOL)textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector;
{
if(commandSelector == @selector(insertTab:)) {
[[textView window] selectNextKeyView:self];
return YES;
}
else if(commandSelector == @selector(insertBacktab:)) {
[[textView window] selectPreviousKeyView:self];
return YES;
}
return NO;
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
#pragma unused(connection)
#pragma unused(response)
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
#pragma unused(connection)
[_responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
#pragma unused(connection)
// A valid response is simply the string 'ok'
NSString *responseString = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
BOOL responseOK = [responseString isEqualToString:@"ok"];
_urlConnection = nil;
_responseData = nil;
if(responseOK) {
// Create our own instance since this method could be called from a background thread
NSFileManager *fileManager = [[NSFileManager alloc] init];
// Use the file's modification date as the last submitted crash date
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:self.crashLogPath error:nil];
NSDate *fileModificationDate = [fileAttributes fileModificationDate];
if(fileModificationDate)
[[NSUserDefaults standardUserDefaults] setObject:fileModificationDate forKey:@"SFBCrashReporterLastCrashReportDate"];
// Delete the crash log since it is no longer needed
NSError *error = nil;
if(![fileManager removeItemAtPath:self.crashLogPath error:&error])
NSLog(@"SFBCrashReporter error: Unable to delete the submitted crash log (%@): %@", [self.crashLogPath lastPathComponent], [error localizedDescription]);
// Even though the log wasn't deleted, submission was still successful
[self performSelectorOnMainThread: @selector(showSubmissionSucceededSheet) withObject:nil waitUntilDone:NO];
}
// An error occurred on the server
else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:NSLocalizedString(@"Unrecognized response from the server", @""), NSLocalizedDescriptionKey, nil];
NSError *error = [NSError errorWithDomain:NSPOSIXErrorDomain code:EPROTO userInfo:userInfo];
[self performSelectorOnMainThread: @selector(showSubmissionFailedSheet:) withObject:error waitUntilDone:NO];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
#pragma unused(connection)
_urlConnection = nil;
_responseData = nil;
[self performSelectorOnMainThread:@selector(showSubmissionFailedSheet:) withObject:error waitUntilDone:NO];
}
@end