-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathFileExporter.m
536 lines (483 loc) · 28.7 KB
/
FileExporter.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
//
// FileExporter.m
// iGenomics
//
// Created by Stuckinaboot Inc. on 6/30/14.
//
//
#import "FileExporter.h"
@implementation FileExporter
@synthesize delegate;
- (void)setGenomeFileName:(NSString *)gName andReadsFileName:(NSString *)rName andErrorRate:(float)er andExportDataStr:(NSString *)expDataStr andTotalNumOfReads:(int)numOfReads andTotalNumOfReadsAligned:(int)numOfReadsAligned separateGenomeLensArr:(NSArray *)sepGenLens separateGenomeNamesArr:(NSArray *)sepSegNames {
genomeFileName = [gName substringToIndex:[gName rangeOfString:@"." options:NSBackwardsSearch].location];
readsFileName = [rName substringToIndex:[rName rangeOfString:@"." options:NSBackwardsSearch].location];
errorRate = er;
exportDataStr = [NSString stringWithString:expDataStr];
totalAlignmentRuntime = 0;
// totalAlignmentRuntime = runtime;
totalNumOfReadsAligned = numOfReadsAligned;
totalNumOfReads = numOfReads;
separateGenomeLens = sepGenLens;
separateSegmentNames = sepSegNames;
// [self performSelectorInBackground:@selector(fixExportDataStr) withObject:nil];
}
- (void)fixExportDataStr {
NSArray *lineArr = [exportDataStr componentsSeparatedByString:kLineBreak];
NSMutableString *newDataStr = [[NSMutableString alloc] init];
NSArray *lenArr = [delegate getCumulativeLenArray];
//Add error rate and runtime to beginning
[newDataStr appendFormat:@"#\tER\tRT\tRC\tARC\n#\t%f\t%f\t%d\t%d\n",errorRate,totalAlignmentRuntime, totalNumOfReads, totalNumOfReadsAligned];
int currLenArrIndex = 0;
for (int i = 0; i < [lineArr count]; i++) {
NSArray *compArr = [[lineArr objectAtIndex:i] componentsSeparatedByString:kReadExportDataComponentDivider];
for (int x = 0; x < [compArr count]; x++) {
NSString *obj = [compArr objectAtIndex:x];
if (x == kReadExportDataStrPositionIndex) {
currLenArrIndex = 0;
while ([obj intValue] > [[lenArr objectAtIndex:currLenArrIndex] intValue])
currLenArrIndex++;
int newVal = [obj intValue] - ((currLenArrIndex > 0) ? [[lenArr objectAtIndex:currLenArrIndex-1] intValue] : 0);
obj = [NSString stringWithFormat:@"%i%@%@",newVal, kReadExportDataComponentDivider, [[delegate getSeparateGenomeSegmentNamesArray] objectAtIndex:currLenArrIndex]];
}
[newDataStr appendFormat:@"%@%@",obj,(x < [compArr count]-1) ? kReadExportDataComponentDivider : kLineBreak];
}
}
exportDataStr = newDataStr;
}
- (void)setMutSupportVal:(int)mutSupVal andMutPosArray:(NSArray *)mutPosArr {
mutationSupportVal = mutSupVal;
mutPosArray = mutPosArr;
}
- (void)setTotalAlignmentRuntime:(float)runtime {
totalAlignmentRuntime = runtime;
[self performSelectorInBackground:@selector(fixExportDataStr) withObject:nil];
}
- (void)displayExportOptionsWithSender:(id)sender {
exportActionSheet = [[UIActionSheet alloc] initWithTitle:kExportASTitle delegate:self cancelButtonTitle:nil destructiveButtonTitle:kAlertBtnTitleCancel otherButtonTitles:kExportASExportMutationsHaploid, kExportASExportMutationsDiploid, kExportASEmailData, kExportASDropboxData, kExportASShareData, nil];
if ([sender isKindOfClass:[UIBarButtonItem class]])
[exportActionSheet showFromBarButtonItem:(UIBarButtonItem*)sender animated:YES];
else
[exportActionSheet showFromRect:((UIView*)sender).frame inView:((UIView*)sender).superview animated:YES];
}
- (void)saveFileAtPath:(NSString *)path andContents:(NSString *)contents andFileType:(FileType)fileType completion:(void(^)(BOOL, BOOL))completionBlock {
DBUserClient *client = [DBClientsManager authorizedClient];
// DBFilesystem *sys = [DBFilesystem sharedFilesystem];
if (!client) {
[DBClientsManager authorizeFromController:[UIApplication sharedApplication] controller:[delegate getVC] openURL:^(NSURL *url) {
[[UIApplication sharedApplication] openURL:url];
}];
}
// if (!sys) {
// if ([DBAccountManager sharedManager].linkedAccount == NULL)
// [[DBAccountManager sharedManager] linkFromController:[delegate getVC]];
// else {
// sys = [[DBFilesystem alloc] initWithAccount:[DBAccountManager sharedManager].linkedAccount];
// [DBFilesystem setSharedFilesystem:sys];
// }
// }
path = [self fixChosenExportPathExt:path forFileType:fileType];
// DBPath *dbPath = [[DBPath alloc] initWithString:path];
// DBFileInfo *info = [sys fileInfoForPath:dbPath error:nil];
// DBFile *file;
// DBError *error;
// dispatch_semaphore_t sema = dispatch_semaphore_create(0);
__block BOOL uploadedSuccessfully = FALSE;
NSLog(@"Saving");
[[client.filesRoutes getMetadata:path] setResponseBlock: ^(DBFILESMetadata * _Nullable result, DBFILESGetMetadataError * _Nullable routeError, DBRequestError * _Nullable networkError) {
// Requests metadata to see if the file exists
NSLog(@"Requesting metadata");
if (!result) {
NSLog(@"file DNE");
// File does not exist, so upload the file
[[client.filesRoutes uploadData:path inputData:[contents dataUsingEncoding:NSUTF8StringEncoding]] setResponseBlock:^(DBFILESFileMetadata * _Nullable result, DBFILESUploadError * _Nullable routeError, DBRequestError * _Nullable networkError) {
if (result) {
// File uploaded successfully
uploadedSuccessfully = YES;
[delegate displaySuccessBox];
} else {
// Unknown Error occurred
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyGeneralFailError delegate:nil cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
[alert show];
uploadedSuccessfully = NO;
}
completionBlock(uploadedSuccessfully, FALSE);
NSLog(@"Signaling");
// dispatch_semaphore_signal(sema);
}];
} else {
NSLog(@"File exists");
// File exists
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyGeneralFailError delegate:nil cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
// [alert show];
uploadedSuccessfully = NO;
NSLog(@"Signaling");
completionBlock(uploadedSuccessfully, TRUE);
// dispatch_semaphore_signal(sema);
}
}];
NSLog(@"Waiting");
// dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
NSLog(@"Done waiting");
// return uploadedSuccessfully;
// if (!info)
// file = [sys createFile:dbPath error:&error];
// else
// return NO;
// if (error) {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyGeneralFailError delegate:nil cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
// [alert show];
// return NO;
// } else if ([file writeString:contents error:nil]) {
// [delegate displaySuccessBox];
// return YES;
// } else {
// //Error occurred, file exists is the usual error (if this ever changes, I will need to adapt to it)
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyGeneralFailError delegate:nil cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
// [alert show];
// return NO;
// }
}
- (int)firstAvailableDefaultFileNameForMutsOrData:(int)choice {
DBUserClient *client = [DBClientsManager authorizedClient];
if (!client) {
[DBClientsManager authorizeFromController:[UIApplication sharedApplication] controller:[delegate getVC] openURL:^(NSURL *url) {
[[UIApplication sharedApplication] openURL:url];
}];
}
NSString *formatStr;
if (choice == 0) { // muts
formatStr = kExportDropboxSaveFileFormatMuts;
} else if (choice == 1) {
formatStr = kExportDropboxSaveFileFormatData;
} else {
return -1;
}
NSString *path = [NSString stringWithFormat:formatStr,readsFileName, @""];
return path;
/*
__block BOOL validNameFound = FALSE;
__block int i = 0;
while (!validNameFound) {
NSLog(@"del entered while");
// dispatch_semaphore_t sema = dispatch_semaphore_create(0);
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
runOnMainQueueWithoutDeadlocking(^{
NSLog(@"ran this");
[[client.filesRoutes getMetadata:path] setResponseBlock:^(DBFILESMetadata * _Nullable result, DBFILESGetMetadataError * _Nullable routeError, DBRequestError * _Nullable networkError) {
if (!result) {
NSLog(@"del found valid name");
validNameFound = TRUE;
} else {
NSLog(@"del no invalid name %@", [result description]);
i++;
}
// dispatch_semaphore_signal(sema);
}];
// });
});
if (validNameFound) {
break;
} else {
NSLog(@"del started waiting");
// dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}
}
return i;
// DBFilesystem *sys = [DBFilesystem sharedFilesystem];
// if (choice == 0) {//muts
// DBFile *file = [sys openFile:[[DBPath alloc] initWithString:[NSString stringWithFormat:kExportDropboxSaveFileFormatMuts,readsFileName, @""]] error:nil];
// int i = 0;
// while (file) {
// i++;
// file = [sys openFile:[[DBPath alloc] initWithString:[NSString stringWithFormat:kExportDropboxSaveFileFormatMuts,readsFileName, [NSString stringWithFormat:@"(%i)",i]]] error:nil];
// }
// return i;
// }
// else if (choice == 1) {//data
// DBFile *file = [sys openFile:[[DBPath alloc] initWithString:[NSString stringWithFormat:kExportDropboxSaveFileFormatData,readsFileName, @""]] error:nil];
// int i = 0;
// while (file) {
// i++;
// file = [sys openFile:[[DBPath alloc] initWithString:[NSString stringWithFormat:kExportDropboxSaveFileFormatData,readsFileName, [NSString stringWithFormat:@"(%i)",i]]] error:nil];
// }
// return i;
// }
*/
}
- (void)overwriteFileAtPath:(NSString*)path andContents:(NSString*)contents andFileType:(FileType)fileType {
DBUserClient *client = [DBClientsManager authorizedClient];
// DBFilesystem *sys = [DBFilesystem sharedFilesystem];
path = [self fixChosenExportPathExt:path forFileType:fileType];
// dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[[client.filesRoutes uploadData:path mode:[[DBFILESWriteMode alloc] initWithOverwrite] autorename:NULL clientModified:NULL mute:NULL propertyGroups:NULL strictConflict:NULL inputData:[contents dataUsingEncoding:NSUTF8StringEncoding]] setResponseBlock:^(DBFILESFileMetadata * _Nullable result, DBFILESUploadError * _Nullable routeError, DBRequestError * _Nullable networkError) {
if (result != NULL) {
[delegate displaySuccessBox];
} else {
// Display error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyGeneralFailError delegate:nil cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
[alert show];
}
// dispatch_semaphore_signal(sema);
}];
// dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
// if (uploaded) {
// [delegate displaySuccessBox];
// return YES;
// } else {
// return NO;
// }
// DBFile *file = [sys openFile:[[DBPath alloc] initWithString:path] error:nil];
// if ([file writeString:contents error:nil]) {
// [delegate displaySuccessBox];
// return YES;
// }
// else {
// //Error occurred, file exists is the usual error (if this ever changes, I will need to adapt to it)
// return NO;
// }
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
// Return if no button was selected
if (buttonIndex == -1) {
return;
}
if (![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kAlertBtnTitleCancel] && ![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportMutExportShareMuts] && ![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportASShareData] && ![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportASExportMutationsHaploid] && ![[actionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportASExportMutationsDiploid] && ![GlobalVars internetAvailable]) {
// Only return if no internet available and button other than cancel, share mutations, share alignments, export haploid, export diploid is hit
return;
} else if ([actionSheet isEqual:exportActionSheet]) {
if (buttonIndex == kExportASExportMutationsHaploidIndex) {
exportOptionsMutsActionSheet = [[UIActionSheet alloc] initWithTitle:kExportAlertTitle delegate:self cancelButtonTitle:kAlertBtnTitleCancel destructiveButtonTitle:nil otherButtonTitles:kExportMutExportEmailMuts, kExportMutExportDropboxMuts, kExportMutExportShareMuts, nil];
exportOptionsMutsActionSheet.tag = kExportASExportMutationsHaploidIndex;
UIView *viewToDisplayIn = [actionSheet superview];
if (!viewToDisplayIn) {
viewToDisplayIn = [[delegate getVC] view];
}
[exportOptionsMutsActionSheet showInView:viewToDisplayIn];
// [self emailInfoForOption:EmailInfoOptionMutations];
}
else if (buttonIndex == kExportASExportMutationsDiploidIndex) {
exportOptionsMutsActionSheet = [[UIActionSheet alloc] initWithTitle:kExportAlertTitle delegate:self cancelButtonTitle:kAlertBtnTitleCancel destructiveButtonTitle:nil otherButtonTitles:kExportMutExportEmailMuts, kExportMutExportDropboxMuts, kExportMutExportShareMuts, nil];
exportOptionsMutsActionSheet.tag = kExportASExportMutationsDiploidIndex;
UIView *viewToDisplayIn = [actionSheet superview];
if (!viewToDisplayIn) {
viewToDisplayIn = [[delegate getVC] view];
}
[exportOptionsMutsActionSheet showInView:viewToDisplayIn];
// [self emailInfoForOption:EmailInfoOptionMutations];
}
else if (buttonIndex == kExportASEmailDataIndex) {
[self emailInfoForOption:EmailInfoOptionData isDiploid:NO];
}
else if (buttonIndex == kExportASDropboxDataIndex) {
// if ([DBAccountManager sharedManager].linkedAccount == NULL)
// [[DBAccountManager sharedManager] linkFromController:[delegate getVC]];
DBUserClient *client = [DBClientsManager authorizedClient];
NSLog(@"checking client");
if (!client) {
NSLog(@"authorizing");
[DBClientsManager authorizeFromController:[UIApplication sharedApplication] controller:[delegate getVC] openURL:^(NSURL *url) {
[[UIApplication sharedApplication] openURL:url];
}];
}
else {
exportDataDropboxAlert = [[UIAlertView alloc] initWithTitle:kExportAlertTitle message:kExportAlertBody delegate:self cancelButtonTitle:kAlertBtnTitleCancel otherButtonTitles:kExportAlertBtnExportTitle, nil];
[exportDataDropboxAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField *txtField = [exportDataDropboxAlert textFieldAtIndex:0];
int i = [self firstAvailableDefaultFileNameForMutsOrData:1];
[txtField setText:[NSString stringWithFormat:kExportDropboxSaveFileFormatData, readsFileName, (i>0) ? [NSString stringWithFormat:@"(%i)",i] : @""]];
[exportDataDropboxAlert show];
}
} else if (buttonIndex == kExportASShareDataIndex) {
NSString *safeFilename = [NSString stringWithFormat:kExportMailSaveFileFormatData, readsFileName, @""];
[self presentSharingForFileName:safeFilename fileContents:exportDataStr];
}
} else if ([actionSheet isEqual:exportOptionsMutsActionSheet]) {
if ([[exportOptionsMutsActionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportMutExportEmailMuts]) {
[self emailInfoForOption:EmailInfoOptionMutations isDiploid:exportOptionsMutsActionSheet.tag == kExportASExportMutationsDiploidIndex];
} else if ([[exportOptionsMutsActionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportMutExportDropboxMuts]) {
// if ([DBAccountManager sharedManager].linkedAccount == NULL)
// [[DBAccountManager sharedManager] linkFromController:[delegate getVC]];
DBUserClient *client = [DBClientsManager authorizedClient];
if (!client) {
[DBClientsManager authorizeFromController:[UIApplication sharedApplication] controller:[delegate getVC] openURL:^(NSURL *url) {
[[UIApplication sharedApplication] openURL:url];
}];
}
else {
exportMutsDropboxAlert = [[UIAlertView alloc] initWithTitle:kExportAlertTitle message:kExportAlertBody delegate:self cancelButtonTitle:kAlertBtnTitleCancel otherButtonTitles:kExportAlertBtnExportTitle, nil];
[exportMutsDropboxAlert setAlertViewStyle:UIAlertViewStylePlainTextInput];
UITextField *txtField = [exportMutsDropboxAlert textFieldAtIndex:0];
int i = [self firstAvailableDefaultFileNameForMutsOrData:0];
[txtField setText:[NSString stringWithFormat:kExportDropboxSaveFileFormatMuts, readsFileName, (i>0) ? [NSString stringWithFormat:@"(%i)",i] : @""]];
exportMutsDropboxAlert.tag = actionSheet.tag;
[exportMutsDropboxAlert show];
}
} else if ([[exportOptionsMutsActionSheet buttonTitleAtIndex:buttonIndex] isEqualToString:kExportMutExportShareMuts]) {
NSString *safeFilename = [NSString stringWithFormat:kExportMailSaveFileFormatMuts, readsFileName, @""];
NSString *mutStr = [self getMutationsExportStrForIsDiploid:exportOptionsMutsActionSheet.tag == kExportASExportMutationsDiploidIndex];
[self presentSharingForFileName:safeFilename fileContents:mutStr];
}
}
}
- (void)emailInfoForOption:(EmailInfoOption)option isDiploid:(BOOL)isDiploid {
if (![MFMailComposeViewController canSendMail]) {
// Display alert and return if you can can't send mail
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:kErrorAlertEmailTitle message:kErrorAlertEmailBody delegate:self cancelButtonTitle:kErrorAlertExportBodyGeneralFailErrorBtnTitleClose otherButtonTitles:nil];
[alert show];
return;
}
exportMailController = [[MFMailComposeViewController alloc] init];
exportMailController.mailComposeDelegate = self;
if (option == EmailInfoOptionMutations) {
[exportMailController setSubject:[NSString stringWithFormat:kExportMutsEmailSubject,readsFileName, genomeFileName]];
[exportMailController setMessageBody:[NSString stringWithFormat:kExportMutsEmailMsg, readsFileName, genomeFileName, errorRate] isHTML:NO];
NSMutableString *mutString = [self getMutationsExportStrForIsDiploid:isDiploid];
[exportMailController addAttachmentData:[mutString dataUsingEncoding:NSUTF8StringEncoding] mimeType:@"text/plain" fileName:[NSString stringWithFormat:kExportMailSaveFileFormatMuts,readsFileName,@""]];
[[delegate getVC] presentViewController:exportMailController animated:YES completion:nil];
}
else if (option == EmailInfoOptionData) {
[exportMailController setSubject:[NSString stringWithFormat:kExportDataEmailSubject,readsFileName, genomeFileName]];
[exportMailController setMessageBody:[NSString stringWithFormat:kExportDataEmailMsg, readsFileName, genomeFileName, errorRate] isHTML:NO];
[exportMailController addAttachmentData:[exportDataStr dataUsingEncoding:NSUTF8StringEncoding] mimeType:@"text/plain" fileName:[NSString stringWithFormat:kExportMailSaveFileFormatData,readsFileName,@""]];
[[delegate getVC] presentViewController:exportMailController animated:YES completion:nil];
}
}
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
[exportMailController dismissViewControllerAnimated:YES completion:nil];
}
- (NSMutableString*)getMutationsExportStrForIsDiploid:(BOOL)isDiploid {
NSMutableString *mutString = [[NSMutableString alloc] init];
// [mutString appendFormat:kMutationTotalFormat,(int)[mutPosArray count]];
MutationInfo *inf;
if ([mutPosArray count] > 0)
inf = [mutPosArray objectAtIndex:0];
else
return (NSMutableString*)kNoMutationsFoundStr;
NSString *exportFormat;
if (!inf.genomeName)
exportFormat = kMutationFormat;
else
exportFormat = kMutationExportFormat;
// for (MutationInfo *info in mutPosArray) {
// [mutString appendFormat:exportFormat,info.displayedPos+1,[MutationInfo createMutStrFromOriginalChar:info.refChar andFoundChars:info.foundChars pos:info.pos relevantInsArr:info.relevantInsertionsArr],[MutationInfo createMutCovStrFromFoundChars:info.foundChars andPos:info.pos relevantInsArr:info.relevantInsertionsArr], info.genomeName];//+1 so it doesn't start at 0
// }
NSString *header = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kExportMutsHeaderFileName ofType:kExportMutsHeaderFileExt] encoding:NSUTF8StringEncoding error:nil];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"ddMMyyyy"];
NSString *dateString = [dateFormatter stringFromDate:today];
NSMutableString *contigsStr = [NSMutableString string];
for (int i = 0; i < [separateGenomeLens count]; i++) {
int len = [[separateGenomeLens objectAtIndex:i] intValue];
NSString *name = [separateSegmentNames objectAtIndex:i];
[contigsStr appendFormat:@"##contig=<ID=%@, length=%d>%@", name, len, (i < [separateGenomeLens count] - 1) ? @"\n" : @""];
}
[mutString appendFormat:header, dateString, genomeFileName, contigsStr, readsFileName];
[mutString appendString:[MutationInfo mutationInfosOutputString:mutPosArray isDiploid:isDiploid]];
return mutString;
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if ([alertView isEqual:exportMutsDropboxAlert]) {
if (buttonIndex == 1) {
NSString *txt = [alertView textFieldAtIndex:0].text;
if ([txt isEqualToString:@""]) {
[self actionSheet:exportOptionsMutsActionSheet didDismissWithButtonIndex:kExportMutExportDropboxMutsIndex];
}
else {
[self saveFileAtPath:txt andContents:[self getMutationsExportStrForIsDiploid:alertView.tag == kExportASExportMutationsDiploidIndex] andFileType:FileTypeMutations completion:^(BOOL uploaded, BOOL fileAlreadyExists) {
if (!uploaded && fileAlreadyExists) {
chosenMutsExportPath = txt;
exportMutsDropboxErrorAlert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyFileNameAlreadyInUse delegate:self cancelButtonTitle:kAlertBtnTitleCancel otherButtonTitles:kErrorAlertExportBtnTitleOverwrite, nil];
exportMutsDropboxErrorAlert.tag = exportMutsDropboxAlert.tag;
[exportMutsDropboxErrorAlert show];
}
}];
}
}
}
else if ([alertView isEqual:exportMutsDropboxErrorAlert]) {
if (buttonIndex == 1) {
[self overwriteFileAtPath:chosenMutsExportPath andContents:[self getMutationsExportStrForIsDiploid:alertView.tag == kExportASExportMutationsDiploidIndex] andFileType:FileTypeMutations];
}
}
else if ([alertView isEqual:exportDataDropboxAlert]) {
if (buttonIndex == 1) {
NSString *txt = [alertView textFieldAtIndex:0].text;
if ([txt isEqualToString:@""]) {
[self actionSheet:exportActionSheet didDismissWithButtonIndex:kExportASDropboxDataIndex];
}
else {
[self saveFileAtPath:txt andContents:exportDataStr andFileType:FileTypeData completion:^(BOOL uploaded, BOOL fileAlreadyExists) {
if (!uploaded && fileAlreadyExists) {
chosenDataExportPath = txt;
exportDataDropboxErrorAlert = [[UIAlertView alloc] initWithTitle:kErrorAlertExportTitle message:kErrorAlertExportBodyFileNameAlreadyInUse delegate:self cancelButtonTitle:kAlertBtnTitleCancel otherButtonTitles:kErrorAlertExportBtnTitleOverwrite, nil];
[exportDataDropboxErrorAlert show];
}
}];
}
}
}
else if ([alertView isEqual:exportDataDropboxErrorAlert]) {
if (buttonIndex == 1) {
[self overwriteFileAtPath:chosenDataExportPath andContents:exportDataStr andFileType:FileTypeData];
}
}
}
- (NSString*)fixChosenExportPathExt:(NSString*)path forFileType:(FileType)fileType {
NSString *ext;
switch (fileType) {
case FileTypeData:
ext = kExportDropboxSaveDataFileExt;
break;
case FileTypeMutations:
ext = kExportDropboxSaveMutsFileExt;
break;
default:
ext = kExportDropboxSaveFileExt;
break;
}
int s = ext.length;
// Add forward slash to path if it does not exist (for dropbox)
if ([path characterAtIndex:0] != '/') {
path = [NSString stringWithFormat:@"/%@", path];
}
if ([[path substringFromIndex:path.length-s] caseInsensitiveCompare:ext] != NSOrderedSame)
return [NSString stringWithFormat:@"%@%@",path,ext];
return path;
}
- (void)presentSharingForFileName:(NSString*)fileName fileContents:(NSString*)fileContents {
// For AirDrop, we'll write the URL as a string to a file on disk, name
// the file after the title we want to share as, then return the path
// to that file on disk. The receiving device will see the filename
// in the Airdrop accept dialog, rather than the raw URL.
// Use a dedicated folder so cleanup is easy.
NSURL *cache = [[NSFileManager defaultManager] URLForDirectory:NSCachesDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:nil];
NSURL *scratchFolder = [cache URLByAppendingPathComponent:@"airdrop_scratch"];
[[NSFileManager defaultManager] removeItemAtURL:scratchFolder
error:nil];
[[NSFileManager defaultManager] createDirectoryAtURL:scratchFolder
withIntermediateDirectories:YES
attributes:@{}
error:nil];
// The file on disk has to end with a custom file extension that we have defined.
// Check "Document Types" and "Exported UTIs" in the project settings to see
// where this file extension is defined.
NSURL *tempPath = [scratchFolder URLByAppendingPathComponent:fileName];
// Write the URL into the file, and return the file to be shared.
NSData *data = [fileContents dataUsingEncoding:NSUTF8StringEncoding];
[data writeToURL:tempPath atomically:YES];
NSArray *objsToShare = @[tempPath];
UIActivityViewController *controller = [[UIActivityViewController alloc] initWithActivityItems:objsToShare applicationActivities:nil];
// Exclude all activities except AirDrop.
NSArray *excludedActivities = @[UIActivityTypePostToTwitter, UIActivityTypePostToFacebook,
UIActivityTypePostToWeibo,
UIActivityTypeMessage, UIActivityTypeMail,
UIActivityTypePrint, UIActivityTypeCopyToPasteboard,
UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll,
UIActivityTypeAddToReadingList, UIActivityTypePostToFlickr,
UIActivityTypePostToVimeo, UIActivityTypePostToTencentWeibo];
controller.excludedActivityTypes = excludedActivities;
// Present the controller
[[delegate getVC] presentViewController:controller animated:YES completion:nil];
}
@end