summaryrefslogtreecommitdiffstats
path: root/macosx/HBChapterTitlesController.m
blob: e029b7244632b6c37c743d1d77fc8dc6dbac6ece (plain)
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
/*  ChapterTitles.m $

   This file is part of the HandBrake source code.
   Homepage: <http://handbrake.fr/>.
   It may be used under the terms of the GNU General Public License. */
   
#import "HBChapterTitlesController.h"
#import "Controller.h"
#include "hb.h"

@interface HBChapterTitlesController () <NSTableViewDataSource, NSTableViewDelegate>
{
    NSMutableArray *fChapterTitlesArray;

    IBOutlet NSTableView         * fChapterTable;
	IBOutlet NSButton            * fLoadChaptersButton;
	IBOutlet NSButton            * fSaveChaptersButton;
    IBOutlet NSButton            * fCreateChaptersMarkers;
	IBOutlet NSTableColumn       * fChapterTableNameColumn;
}

@end

@implementation HBChapterTitlesController

@synthesize enabled = _enabled;

- (instancetype)init
{
    self = [super initWithNibName:@"ChaptersTitles" bundle:nil];
    if (self)
    {
        fChapterTitlesArray = [[[NSMutableArray alloc] init] retain];
        [[NSNotificationCenter defaultCenter]  addObserver: self selector: @selector(titleChanged:) name: HBTitleChangedNotification object: nil];
    }
    return self;
}

- (void)dealloc
{
    [fChapterTitlesArray release];
    [super               dealloc];
}

- (void)titleChanged:(NSNotification *)aNotification
{
    NSDictionary *notDict = [aNotification userInfo];
    NSData *theData = [notDict objectForKey: keyTitleTag];
    hb_title_t *title = NULL;

    [theData getBytes: &title length: sizeof(title)];

    [fChapterTitlesArray removeAllObjects];

    if (title)
    {
        for (int i = 0; i < hb_list_count(title->list_chapter); i++)
        {
            hb_chapter_t *chapter = hb_list_item(title->list_chapter, i);
            if (chapter != NULL)
            {
                if (chapter->title != NULL)
                {
                    [fChapterTitlesArray addObject:[NSString
                                                    stringWithFormat:@"%s",
                                                    chapter->title]];
                }
                else
                {
                    [fChapterTitlesArray addObject:[NSString
                                                    stringWithFormat:@"Chapter %d",
                                                    i + 1]];
                }
            }
        }
    }

    [fChapterTable reloadData];
}

- (void)addChaptersFromQueue:(NSMutableArray *)newChaptersArray
{
    [fChapterTitlesArray removeAllObjects];
    [fChapterTitlesArray addObjectsFromArray:newChaptersArray];
    [fChapterTable reloadData];
}

- (void)setEnabled:(BOOL)enabled
{
    [fCreateChaptersMarkers setEnabled:enabled];
    [fChapterTable setEnabled:enabled];
    [fLoadChaptersButton setEnabled:enabled];
    [fSaveChaptersButton setEnabled:enabled];
}

- (NSArray *)chapterTitlesArray
{
    return [NSArray arrayWithArray:fChapterTitlesArray];
}

- (IBAction)createChapterMarkersChanged:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:HBMixdownChangedNotification object:self];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
    return [fChapterTitlesArray count];
}

- (void)tableView:(NSTableView *)aTableView
        setObjectValue:(id)anObject
        forTableColumn:(NSTableColumn *)aTableColumn
        row:(NSInteger)rowIndex
{
    if (aTableColumn != nil && [[aTableColumn identifier] intValue] == 2)
    {
        [fChapterTitlesArray replaceObjectAtIndex:rowIndex
                                       withObject:[NSString
                                                   stringWithString:anObject]];
    }
}

- (id)tableView:(NSTableView *)aTableView
      objectValueForTableColumn:(NSTableColumn *)aTableColumn
      row:(NSInteger)rowIndex
{
    if ([[aTableColumn identifier] intValue] == 1)
    {
        return [NSString stringWithFormat:@"%ld", rowIndex + 1];
    }
    else
    {
        return [NSString stringWithString:[fChapterTitlesArray
                                           objectAtIndex:rowIndex]];
    }
    return @"__DATA ERROR__";
}

/* Method to edit the next chapter when the user presses Return. We have to use
a timer to avoid interfering with the chain of events that handles the edit. */
- (void)controlTextDidEndEditing: (NSNotification *) notification
{
    NSTableView *chapterTable = [notification object];
    NSInteger column = [chapterTable editedColumn];
    NSInteger row = [chapterTable editedRow];
    NSInteger textMovement;

    // Edit the cell in the next row, same column
    row++;
    textMovement = [[[notification userInfo] objectForKey:@"NSTextMovement"] integerValue];
    if( textMovement == NSReturnTextMovement && row < [chapterTable numberOfRows] )
    {
        NSArray *info = [NSArray arrayWithObjects:chapterTable,
            [NSNumber numberWithInteger:column], [NSNumber numberWithInteger:row], nil];
        /* The delay is unimportant; editNextRow: won't be called until the responder
        chain finishes because the event loop containing the timer is on this thread */
        [self performSelector:@selector(editNextRow:) withObject:info afterDelay:0.0];
    }
}

- (void)editNextRow: (id) objects
{
    NSTableView *chapterTable = [objects objectAtIndex:0];
    NSInteger column = [[objects objectAtIndex:1] integerValue];
    NSInteger row = [[objects objectAtIndex:2] integerValue];

    if( row >= 0 && row < [chapterTable numberOfRows] )
    {
        [chapterTable selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
        [chapterTable editColumn:column row:row withEvent:nil select:YES];
    }
}

#pragma mark -
#pragma mark Chapter Files Import / Export

- (IBAction) browseForChapterFile: (id) sender
{
    /* We get the current file name and path from the destination field here */
    NSString *sourceDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"];

	/* Open a panel to let the user choose the file */
	NSOpenPanel *panel = [NSOpenPanel openPanel];
    [panel setDirectoryURL:[NSURL fileURLWithPath:sourceDirectory]];
    [panel setAllowedFileTypes:@[@"csv"]];

    [panel beginSheetModalForWindow:[[self view] window] completionHandler:^(NSInteger result) {
        NSArray *chaptersArray = nil; /* temp array for chapters */
        NSMutableArray *chaptersMutableArray = nil; /* temp array for chapters */
        NSString *chapterName = nil; 	/* temp string from file */
        NSInteger chapters, i;

        if (result == NSOKButton)  /* if they click OK */
        {
            chapterName = [[NSString alloc] initWithContentsOfURL:[panel URL] encoding:NSUTF8StringEncoding error:NULL];
            chaptersArray = [chapterName componentsSeparatedByString:@"\n"];
            [chapterName release];
            chaptersMutableArray = [[chaptersArray mutableCopy] autorelease];
            chapters = [self numberOfRowsInTableView:fChapterTable];
            if ([chaptersMutableArray count] > 0)
            {
                /* if last item is empty remove it */
                if ([[chaptersMutableArray objectAtIndex:[chaptersArray count]-1] length] == 0)
                {
                    [chaptersMutableArray removeLastObject];
                }
            }
            /* if chapters in table is not equal to array count */
            if ((unsigned int) chapters != [chaptersMutableArray count])
            {
                [panel close];
                [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
                                 defaultButton:NSLocalizedString(@"OK", @"OK")
                               alternateButton:NULL
                                   otherButton:NULL
                     informativeTextWithFormat:NSLocalizedString(@"%d chapters expected, %d chapters found in %@", @"%d chapters expected, %d chapters found in %@"),
                  chapters, [chaptersMutableArray count], [[panel URL] lastPathComponent]] runModal];
                return;
            }
            /* otherwise, go ahead and populate table with array */
            for (i=0; i<chapters; i++)
            {

                if([[chaptersMutableArray objectAtIndex:i] length] > 5)
                {
                    /* avoid a segfault */
                    /* Get the Range.location of the first comma in the line and then put everything after that into chapterTitle */
                    NSRange firstCommaRange = [[chaptersMutableArray objectAtIndex:i] rangeOfString:@","];
                    NSString *chapterTitle = [[chaptersMutableArray objectAtIndex:i] substringFromIndex:firstCommaRange.location + 1];
                    /* Since we store our chapterTitle commas as "\," for the cli, we now need to remove the escaping "\" from the title */
                    chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"\\," withString:@","];
                    [self tableView:fChapterTable
                     setObjectValue:chapterTitle
                     forTableColumn:fChapterTableNameColumn
                                row:i];
                }
                else
                {
                    [panel close];
                    [[NSAlert alertWithMessageText:NSLocalizedString(@"Unable to load chapter file", @"Unable to load chapter file")
                                     defaultButton:NSLocalizedString(@"OK", @"OK")
                                   alternateButton:NULL
                                       otherButton:NULL
                         informativeTextWithFormat:NSLocalizedString(@"%@ was not formatted as expected.", @"%@ was not formatted as expected."), [[panel URL] lastPathComponent]] runModal];
                    [fChapterTable reloadData];
                    return;
                }
            }
            [fChapterTable reloadData];
        }
    }];
}

- (IBAction) browseForChapterFileSave: (id) sender
{
    NSString *destinationDirectory = [[NSUserDefaults standardUserDefaults] stringForKey:@"LastDestinationDirectory"];

    /* Open a panel to let the user save to a file */
    NSSavePanel *panel = [NSSavePanel savePanel];
    [panel setAllowedFileTypes:@[@"csv"]];
    [panel setDirectoryURL:[NSURL fileURLWithPath:destinationDirectory]];
    //[panel setNameFieldStringValue:[[[fDstFile2Field stringValue] lastPathComponent] stringByDeletingPathExtension]];

    [panel beginSheetModalForWindow:[[self view] window] completionHandler:^(NSInteger result) {
        NSString *chapterName;      /* pointer for string for later file-writing */
        NSString *chapterTitle;
        NSError *saveError = nil;
        NSInteger chapters, i;    /* ints for the number of chapters in the table and the loop */

        if( result == NSOKButton )   /* if they clicked OK */
        {
            chapters = [self numberOfRowsInTableView:fChapterTable];
            chapterName = [NSString string];
            for (i=0; i<chapters; i++)
            {
                /* put each chapter title from the table into the array */
                if (i<9)
                { /* if i is from 0 to 8 (chapters 1 to 9) add two leading zeros */
                    chapterName = [chapterName stringByAppendingFormat:@"00%ld,",i+1];
                }
                else if (i<99)
                { /* if i is from 9 to 98 (chapters 10 to 99) add one leading zero */
                    chapterName = [chapterName stringByAppendingFormat:@"0%ld,",i+1];
                }
                else if (i<999)
                { /* in case i is from 99 to 998 (chapters 100 to 999) no leading zeros */
                    chapterName = [chapterName stringByAppendingFormat:@"%ld,",i+1];
                }

                chapterTitle = [self tableView:fChapterTable objectValueForTableColumn:fChapterTableNameColumn row:i];
                /* escape any commas in the chapter name with "\," */
                chapterTitle = [chapterTitle stringByReplacingOccurrencesOfString:@"," withString:@"\\,"];
                chapterName = [chapterName stringByAppendingString:chapterTitle];
                if (i+1 != chapters)
                { /* if not the last chapter */
                    chapterName = [chapterName stringByAppendingString:@ "\n"];
                }


            }
            /* try to write it to where the user wanted */
            if (![chapterName writeToURL:[panel URL]
                              atomically:NO
                                encoding:NSUTF8StringEncoding
                                   error:&saveError])
            {
                [panel close];
                [[NSAlert alertWithError:saveError] runModal];
            }
        }
    }];
}

@end