-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppController.m
662 lines (478 loc) · 19.6 KB
/
AppController.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
//
// AppController.m
// SubtitleConverter
//
// Created by Andrew Hughes on 11/7/11.
// -------------------------------------------
//
//
// All code (c)2011 Moksa Media all rights reserved
// Developer: Andrew Hughes
//
// This file is part of SBVConvertor.
//
// SBVConvertor is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SBVConvertor is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with SBVConvertor. If not, see <http://www.gnu.org/licenses/>.
//
//
// -------------------------------------------
//
#import "AppController.h"
@implementation AppController
#pragma mark App Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// APP DELEGATE METHODS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
The following are implented to allow the user to drop files onto the application icon (also had to add file types to the app plist).
*/
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
fileToOpen = nil; // initialize temp string pointer to nil so that we know if it was assigned
}
// this is called after "applicationWillFinishLaunching" and before "applicationDidFinishLaunching"
// we save a copy of the filename to open so that we can open it in "applicationDidFinishLaunching"
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
fileToOpen = [filename retain];
return YES;
}
// if we have a file to open, open it!
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
if (fileToOpen)
{
[self tryLoadFile:fileToOpen];
}
}
// save prefs when user quits app
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
[self loadVarsAndSavePrefs];
}
#pragma mark Initialization
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// WAKE FROM NIB (INITIALIZATION)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// initiailization after object is instantiated and ready from the nib
- (void) awakeFromNib
{
// clear the text views
[[[sourceTextView textStorage] mutableString] setString:@""];
[[[resultTextView textStorage] mutableString] setString:@""];
// set both text views to not editable
[sourceTextView setEditable:NO];
[resultTextView setEditable:NO];
// set the source path text field to not editable
[sourceTextField setEditable:NO];
// create a number character set for testing to see if a given line starts with a timecode
numCharSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] retain];
// convert and save should be disabled until a file is loaded
[convertButton setEnabled:NO];
[saveAsButton setEnabled:NO];
// tool tips, just to be nice
[frameRateTextField setToolTip:@"This value is used to convert miliseconds to frames in the timecodes."];
[newlineCharTextField setToolTip:@"Newlines in the subtitle text of the iSBV are replaced with this character."];
[separatorTextField setToolTip:@"The character used to separate timecodes and subtitle text. Enter \"tab\" to use tabs."];
// default character added between different lines of subtitle text is a space
[newlineCharTextField setStringValue:@" "];
result = nil;
separator = nil;
newLineChar = nil;
[separatorTextField setStringValue:@","];
addQuotes = NO;
frameRate = 30;
//[self setStandardPrefs];
[self loadPrefs];
}
// clean up
- (void) dealloc
{
if (result) [result release];
if (sourceLines) [sourceLines release];
[numCharSet release];
[super dealloc];
}
#pragma mark Prefs
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PREFERENCES
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// loads the saved prefs
// - note that temp string vars are used because we do not retain the separator and newLineChar strings; instead
// they are read from the text fields right before use in the parse function
- (void) loadPrefs
{
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"PrefsSet"])
{
[self setStandardPrefs];
}
addQuotes = [[NSUserDefaults standardUserDefaults] boolForKey:@"AddQuotes"];
if (addQuotes)
{
[addQuotesCheckBox setState:NSOnState];
}
else
{
[addQuotesCheckBox setState:NSOffState];
}
NSString * _separator = [[NSUserDefaults standardUserDefaults] objectForKey:@"Separator"];
if ([_separator isEqualToString:@"\t"]) [separatorTextField setStringValue:@"tab"];
else [separatorTextField setStringValue:_separator];
frameRate = [[NSUserDefaults standardUserDefaults] integerForKey:@"FrameRate"];
[frameRateTextField setIntValue:frameRate];
NSString * _newLineChar = [[NSUserDefaults standardUserDefaults] objectForKey:@"NewLineChar"];
[newlineCharTextField setStringValue:_newLineChar];
}
- (IBAction) resetPrefs:(id)sender
{
[self setStandardPrefs];
[self loadPrefs];
}
// sets the standard prefs
- (void) setStandardPrefs
{
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"PrefsSet"];
[[NSUserDefaults standardUserDefaults] setObject:@"," forKey:@"Separator"];
[[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"AddQuotes"];
[[NSUserDefaults standardUserDefaults] setInteger:30 forKey:@"FrameRate"];
[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"NewLineChar"];
}
// saves the prefs and loads the option vars from the text fields and check box
- (void) loadVarsAndSavePrefs
{
newLineChar = [newlineCharTextField stringValue];
if ([newLineChar isEqualToString:@""]) newLineChar = @" ";
separator = [separatorTextField stringValue];
if ([separator isEqualToString:@"\t"] || [[separator lowercaseString] isEqualToString:@"tab"]) separator = @"\t";
addQuotes = ([addQuotesCheckBox state] == NSOnState);
[[NSUserDefaults standardUserDefaults] setBool:TRUE forKey:@"PrefsSet"];
[[NSUserDefaults standardUserDefaults] setObject:separator forKey:@"Separator"];
[[NSUserDefaults standardUserDefaults] setBool:addQuotes forKey:@"AddQuotes"];
[[NSUserDefaults standardUserDefaults] setInteger:frameRate forKey:@"FrameRate"];
[[NSUserDefaults standardUserDefaults] setObject:newLineChar forKey:@"NewLineChar"];
}
#pragma mark Help
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// HELP
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
- (IBAction) showHelp:(id)sender
{
[helpWindow makeKeyAndOrderFront:self];
}
#pragma mark Frame Rate Validation
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FRAME RATE TEXT FIELD ACTION (validates entry)
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// frame rate text field action
// validate frame rate values entered into the text field
- (IBAction) frameRateTextFieldAction:(id)sender
{
// get the integer value from the text field
int newFrameRate = [sender integerValue];
// reality check the frame rate
if (newFrameRate < 12 || newFrameRate > 100)
{
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:@"Please enter a frame rate between 1 and 100."];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
[alert release];
[frameRateTextField setIntegerValue:frameRate];
}
else
{
frameRate = newFrameRate;
}
}
#pragma mark Save & Load
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// SAVE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// the save button action
- (IBAction) saveAsButtonAction:(id)sender
{
// make a save panel
NSSavePanel * sPanel = [NSSavePanel savePanel];
// set allowed types
[sPanel setAllowedFileTypes:[NSArray arrayWithObjects:@"csv", @"txt", nil]];
[sPanel setAllowsOtherFileTypes:YES];
// show the panel
int sResult = [sPanel runModal];
if (sResult == NSOKButton)
{
NSString * selectedFilename = [sPanel filename];
NSError *error;
BOOL ok = [[[resultTextView textStorage] mutableString] writeToFile:selectedFilename atomically:YES encoding:NSUnicodeStringEncoding error:&error];
// on error
if (!ok)
{
NSAlert * alert = [NSAlert alertWithError:error];
[alert runModal];
[alert release];
NSLog(@"Error writing file at %@\n%@", selectedFilename, [error localizedFailureReason]);
}
// on success
else
{
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:@"File saved successfully!"];
[alert setInformativeText:selectedFilename];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
[alert release];
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// LOAD
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// load source button action
- (IBAction) loadSourceButtonAction:(id)sender
{
// create an open panel
NSOpenPanel * oPanel = [NSOpenPanel openPanel];
// set the allowed file types
NSArray * fileTypes = [NSArray arrayWithObjects:@"txt",@"sbv",nil];
// run the panel and get the result
int panelResult = [oPanel runModalForTypes:fileTypes];
// if we selected a file to open
if (panelResult == NSOKButton)
{
// get the file name
sourceFileName = [oPanel filename];
[self tryLoadFile:sourceFileName];
}
}
- (BOOL) tryLoadFile:(NSString*)file
{
// try and load the file
NSError * error = nil;
sourceText = [[NSString stringWithContentsOfFile:file usedEncoding:nil error:&error] retain];
// if no error
if (error == nil)
{
sourceFileName = file;
// load the text into the source text view
[[[sourceTextView textStorage] mutableString] setString:sourceText];
// load the file name into the source file name text field
[sourceTextField setStringValue:sourceFileName];
// cause the source text view to show the loaded text
[sourceTextView display];
// enable the convert button and allow user to edit the source text
[convertButton setEnabled:YES];
[sourceTextView setEditable:YES];
return TRUE;
}
// on error
else
{
NSAlert * alert = [NSAlert alertWithError:error];
[alert runModal];
[alert release];
return FALSE;
}
}
#pragma mark Parse/Convert
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CONVERT
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// convert button action
- (IBAction) convertButtonAction:(id)sender
{
// split the source text into lines
sourceLines = [[[[sourceTextView textStorage] mutableString] componentsSeparatedByString:@"\n"] retain];
// parse it!
[self parse];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PARSE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// this is where the magic happens - the file is parsed and reformated
- (void) parse
{
[NSApp beginSheet:progressPanel modalForWindow:window modalDelegate:self didEndSelector:NULL contextInfo:NULL];
[progressIndicator setMinValue:0.0];
double max = (double)[sourceLines count];
[progressIndicator setMaxValue:max];
[progressIndicator setUsesThreadedAnimation:YES];
[self loadVarsAndSavePrefs];
// "result" holds the converted file as it is generated
if (result) [result release];
result = [[NSMutableString alloc] init];
// enumerator to iterate through the lines of our source file
NSEnumerator * etr = [sourceLines objectEnumerator];
// iterator variable that holds each new line of source file
NSString * nextLine;
// this is a temp variable that will accrue the different lines of subtitle text for each subtitle
// bc in the SBV a single subtitle can be split across multiple consecutive lines
NSMutableString * subText = nil;
double counter = 0.0;
@try
{
// the main loop
// - here we iterate through every line of the file, createing the translation as we go
while (nextLine = [etr nextObject])
{
// is the current line a timecode line?
if ([self isStartOfTimeCode:nextLine index:0])
{
// if subText is NOT nil, then we have some subtitle text from a previous loop iteration
// that needs to be appended to the results string before we process the timecodes on the
// new current line
if (subText != nil)
{
// this line gets rid of the extraneous new line character that was added below
if (newLineChar != nil && ![newLineChar isEqualToString:@""])
subText = [[[subText substringToIndex:[subText length] - 1] mutableCopy] autorelease];
// close out quotes if necessary
if (addQuotes) [subText appendString:@"\""];
// add the comma, subtitle text, and a newline to the results
[result appendString:separator];
[result appendString:subText];
[result appendString:@"\n"];
// set to nil so that we know we're starting over
subText = nil;
}
// get the timecodes from the line
// - the timecodes are converted from miliseconds to frames by a helper method
NSArray * tcs = [self getTimecodes:nextLine];
// add the timecodes to the results string
[result appendString:[NSString stringWithFormat:@"%@%@%@", [tcs objectAtIndex:0],separator, [tcs objectAtIndex:1]]];
}
// the current line is NOT a timecode line, it must be a subtitle text line
else
{
// if subText is nil, this is the first subtitle text line and we need to initialize the string
if (subText == nil)
{
subText = [[[NSMutableString alloc] init] autorelease];
if (addQuotes) [subText appendString:@"\""];
}
// trim any extra whitespace (which also reduces empty lines to zero length so we can ignore them)
nextLine = [self trimWhite:nextLine];
// only append lines with actual, non-whitespace text
if ([nextLine length] > 0)
{
[subText appendString:nextLine];
[subText appendString:newLineChar];
}
}
}
// force the display to refresh
//[[[resultTextView textStorage] mutableString] setString:result];
// force the results text view to scroll to the last line
//NSRect frame = [resultTextView frame];
//[resultTextView scrollPoint: NSMakePoint(0, frame.origin.y + frame.size.height)];
//[resultTextView display];
[progressIndicator setDoubleValue:counter];
[progressIndicator display];
counter++;
}
@catch ( NSException *e)
{
NSAlert *alert = [[NSAlert alloc] init];
[alert addButtonWithTitle:@"OK"];
[alert setMessageText:[e name]];
[alert setInformativeText:[e reason]];
[alert setAlertStyle:NSWarningAlertStyle];
[alert runModal];
[alert release];
}
@finally
{
[NSApp endSheet:progressPanel returnCode:NSOKButton];
[progressPanel orderOut:nil];
}
// have to process the last bit of subtitle text
if (subText != nil)
{
[result appendString:separator];
[result appendString:subText];
subText = nil;
}
[NSApp endSheet:progressPanel returnCode:NSOKButton];
[progressPanel orderOut:nil];
// refresh the display
[[[resultTextView textStorage] mutableString] setString:result];
[resultTextView display];
[resultTextView setEditable:YES];
// enable the save button
[saveAsButton setEnabled:YES];
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// PARSE/CONVERT HELPERS
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// returns two trimmed and converted timecodes as an array from a string containing two timecodes
- (NSArray*) getTimecodes:(NSString*)string
{
// we assume that the timecodes are separated by a comma
NSArray * timecodes = [string componentsSeparatedByString:@","];
// make sure that we have two well-formed time codes
if ([timecodes count] != 2)
{
[result appendString:[NSString stringWithFormat:@"Timecode appears to be invalid! %@", string]];
// refresh the display
[[[resultTextView textStorage] mutableString] setString:result];
[resultTextView display];
[NSException raise:@"Invalid Timecode" format:@"Timecode appears to be invalid! %@", string];
}
// convert timecodes and trim any whitespace
NSMutableArray * trimmedTimecodes = [NSArray arrayWithObjects:
[self convertTimecode:[self trimWhite:[timecodes objectAtIndex:0]]],
[self convertTimecode:[self trimWhite:[timecodes objectAtIndex:1]]], nil];
return trimmedTimecodes;
}
// converts a timecode from miliseconds to frames
- (NSString*) convertTimecode:(NSString*)timecode
{
// separate timecode by the "."
NSArray * components = [timecode componentsSeparatedByString:@"."];
// make sure that we have a well-formed time code
if ([components count] != 2 || [[components objectAtIndex:1] length] != 3)
{
[result appendString:[NSString stringWithFormat:@"Timecode appears to be invalid! %@", timecode]];
// refresh the display
[[[resultTextView textStorage] mutableString] setString:result];
[resultTextView display];
[NSException raise:@"Invalid Timecode" format:@"Timecode appears to be invalid! %@", timecode];
}
// get miliseconds from timecode
int miliseconds = [[components objectAtIndex:1] integerValue];
// convert to frames
int frames = round((float)miliseconds / 1000 * (float)frameRate);
// create new timecode string
NSString * newTC = [NSString stringWithFormat:@"0%@:%02d", [components objectAtIndex:0], frames];
return newTC;
}
// trims whitespace
- (NSString*)trimWhite:(NSString*) string
{
return [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
// is the character in the string at the index a number between 0-9?
- (BOOL) isNumberInString:(NSString*)string index:(int)index
{
return [numCharSet characterIsMember:[string characterAtIndex:index]];
}
// determines if we are at the start of a timecode by looking for a number and a colon
- (BOOL) isStartOfTimeCode:(NSString*)string index:(int)index
{
[[string retain] autorelease];
if (index + 1 >= [string length]) return NO;
if ([numCharSet characterIsMember:[string characterAtIndex:index]] &&
[string characterAtIndex:index+1] == ':') return YES;
else return NO;
}
@end