summaryrefslogtreecommitdiffstats
path: root/macosx/HBPreset.m
blob: 013e11b9cca73791babadc740e2bbcb497f10fd0 (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
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
/*  HBPreset.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 "HBPreset.h"
#import "HBMutablePreset.h"

#include "handbrake/preset.h"

#import "NSJSONSerialization+HBAdditions.h"
#import "HBLocalizationUtilities.h"

@interface HBPreset ()

///  The actual content of the preset.
@property (nonatomic, strong, nullable) NSMutableDictionary *content;

@end

@implementation HBPreset

- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _name = @"New Preset";
        _presetDescription = @"";
        _content = [[NSMutableDictionary alloc] init];
        self.isLeaf = YES;
    }
    return self;
}

- (instancetype)initWithPreset:(HBPreset *)preset
{
    self = [super init];
    if (self)
    {
        _name = preset.name;
        _presetDescription = preset.presetDescription;
        _content = [preset.content mutableCopy];
        self.isLeaf = preset.isLeaf;

        for (HBPreset *child in preset.children)
        {
            HBPreset *mutableChild = [[[self class] alloc] initWithPreset:child];
            [self insertObject:mutableChild inChildrenAtIndex:0];
        }
    }
    return self;
}

- (instancetype)initWithName:(NSString *)title content:(NSDictionary *)content builtIn:(BOOL)builtIn
{
    self = [self init];
    if (self)
    {
        _name = [title copy];
        _isBuiltIn = builtIn;
        _content = [content mutableCopy];
        if ([content[@"PresetDescription"] isKindOfClass:[NSString class]])
        {
            _presetDescription = [content[@"PresetDescription"] copy];
        }
    }
    return self;
}

- (instancetype)initWithCategoryName:(NSString *)title builtIn:(BOOL)builtIn
{
    self = [self init];
    if (self)
    {
        _name = [title copy];
        _isBuiltIn = builtIn;
        self.isLeaf = NO;
    }
    return self;
}

- (instancetype)initWithDictionary:(NSDictionary *)dict
{
    NSParameterAssert(dict);

    NSString *name = dict[@"PresetName"] ? dict[@"PresetName"] : @"Unnamed preset";
    BOOL builtIn = [dict[@"Type"] boolValue] ? NO : YES;
    BOOL defaultPreset = [dict[@"Default"] boolValue];

    if ([dict[@"Folder"] boolValue])
    {
        self = [self initWithCategoryName:name builtIn:builtIn];

        for (NSDictionary *childDict in [dict[@"ChildrenArray"] reverseObjectEnumerator])
        {
            HBPreset *childPreset = [[HBPreset alloc] initWithDictionary:childDict];
            [self insertObject:childPreset inChildrenAtIndex:0];
        }
    }
    else
    {
        self = [self initWithName:name
                          content:dict
                          builtIn:builtIn];
        self.isDefault = defaultPreset;
    }

    return self;
}

- (nullable instancetype)initWithContentsOfURL:(NSURL *)url error:(NSError * __autoreleasing *)outError
{
    NSParameterAssert(url);

    NSArray *presetsArray;
    NSString *presetsString;

    // Read a json file or the old plists format
    if ([url.pathExtension isEqualToString:@"json"])
    {
        NSData *data = [[NSData alloc] initWithContentsOfURL:url];
        presetsString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    else
    {
        NSArray *array = [[NSArray alloc] initWithContentsOfURL:url];
        if ([NSJSONSerialization isValidJSONObject:array])
        {
            presetsString = [NSJSONSerialization HB_StringWithJSONObject:array options:0 error:NULL];
        }
    }

    // Run the json through the libhb import function
    // to avoid importing unknowns keys.
    if (presetsString.length)
    {
        char *importedJson;
        hb_presets_import_json(presetsString.UTF8String, &importedJson);

        if (importedJson)
        {
            id importedPresets = [NSJSONSerialization HB_JSONObjectWithUTF8String:importedJson options:0 error:NULL];
            free(importedJson);

            if ([importedPresets isKindOfClass:[NSDictionary class]])
            {
                int hb_major, hb_minor, hb_micro;
                int major;

                hb_presets_current_version(&hb_major, &hb_minor, &hb_micro);
                major = [importedPresets[@"VersionMajor"] intValue];

                if (major <= hb_major)
                {
                    presetsArray = importedPresets[@"PresetList"];
                }
                else
                {
                    // Change in major indicates non-backward compatible preset changes.
                    if (outError)
                    {
                        *outError = [self newerPresetErrorForUrl:url];
                    }
                    return nil;
                }
            }
            else if ([importedPresets isKindOfClass:[NSArray class]])
            {
                presetsArray = importedPresets;
            }
        }
    }

    // Convert the array to a HBPreset tree.
    if (presetsArray.count)
    {
        self = [self initWithCategoryName:@"Imported Presets" builtIn:NO];

        if (self)
        {
            for (NSDictionary *dict in presetsArray)
            {
                HBPreset *preset = [[HBPreset alloc] initWithDictionary:dict];
                [self.children addObject:preset];
            }
        }
        return self;
    }
    else if (outError)
    {
        *outError = [self invalidPresetErrorForUrl:url];
    }

    return nil;
}

- (NSError *)invalidPresetErrorForUrl:(NSURL *)url
{
    NSString *description = [NSString stringWithFormat:HBKitLocalizedString(@"The preset \"%@\" could not be imported.", @"Preset -> import error description"),
                             url.lastPathComponent];
    NSString *reason = HBKitLocalizedString(@"The selected preset is invalid.", @"Preset -> import error reason");

    return [NSError errorWithDomain:@"HBPresetDomain" code:1 userInfo:@{NSLocalizedDescriptionKey: description,
                                                                        NSLocalizedRecoverySuggestionErrorKey: reason}];

}

- (NSError *)newerPresetErrorForUrl:(NSURL *)url
{
    NSString *description = [NSString stringWithFormat:HBKitLocalizedString(@"The preset \"%@\" could not be imported.", @"Preset -> import error description"),
                             url.lastPathComponent];
    NSString *reason = HBKitLocalizedString(@"The selected preset was created with a newer version of HandBrake.",  @"Preset -> import error reason");

    return [NSError errorWithDomain:@"HBPresetDomain" code:2 userInfo:@{NSLocalizedDescriptionKey: description,
                                                                        NSLocalizedRecoverySuggestionErrorKey: reason}];

}

/**
 *  A dictionary representation of the preset.
 */
- (NSDictionary *)dictionary
{
    NSMutableDictionary *output = [[NSMutableDictionary alloc] init];
    [output addEntriesFromDictionary:self.content];

    output[@"PresetName"] = self.name;
    output[@"PresetDescription"] = self.presetDescription;
    output[@"Folder"] = [NSNumber numberWithBool:!self.isLeaf];
    output[@"Type"] = @(!self.isBuiltIn);
    output[@"Default"] = @(self.isDefault);

    if (!self.isLeaf)
    {
        NSMutableArray *childArray = [[NSMutableArray alloc] init];
        for (HBPreset *child in self.children)
        {
            [childArray addObject:[child dictionary]];
        }

        output[@"ChildrenArray"] = childArray;
    }

    return output;
}

- (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically format:(HBPresetFormat)format removeRoot:(BOOL)removeRoot
{
    BOOL success = NO;
    NSArray *presetList;

    if (removeRoot)
    {
        presetList = self.dictionary[@"ChildrenArray"];
    }
    else
    {
        presetList = @[self.dictionary];
    }

    int major, minor, micro;
    hb_presets_current_version(&major, &minor, &micro);

    NSDictionary *dict = @{ @"PresetList": presetList,
                            @"VersionMajor": @(major),
                            @"VersionMinor": @(minor),
                            @"VersionMicro": @(micro) };

    if (format == HBPresetFormatPlist)
    {
        success = [dict writeToURL:url atomically:atomically];
    }
    else
    {
        NSUInteger sortKeys = (1UL << 1); // NSJSONWritingSortedKeys in 10.13 sdk;
        NSData *jsonPreset = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted | sortKeys error:NULL];
        success = [jsonPreset writeToURL:url atomically:atomically];
    }

    return success;
}

- (void)cleanUp
{
    // Run the libhb clean function
    NSString *presetJson = [NSJSONSerialization HB_StringWithJSONObject:self.dictionary options:0 error:NULL];

    if (presetJson.length)
    {
        char *cleanedJson = hb_presets_clean_json(presetJson.UTF8String);
        NSDictionary *cleanedDict = [NSJSONSerialization HB_JSONObjectWithUTF8String:cleanedJson options:0 error:NULL];
        free(cleanedJson);

        if ([cleanedDict isKindOfClass:[NSDictionary class]])
        {
            self.content = [cleanedDict mutableCopy];
        }
    }
}

#pragma mark - NSCopying

- (id)copyWithZone:(NSZone *)zone
{
    HBPreset *node = [super copyWithZone:zone];
    node->_name = [self.name copy];
    node->_content = [self.content mutableCopy];
    node->_presetDescription = [self.presetDescription copy];

    return node;
}

- (id)mutableCopyWithZone:(NSZone *)zone
{
    return [[HBMutablePreset allocWithZone:zone] initWithPreset:self];
}

- (NSUInteger)hash
{
    return self.name.hash + self.isBuiltIn + self.isLeaf;
}

#pragma mark - Properties

- (void)setName:(NSString *)name
{
    _name = [name copy];
    [self.delegate nodeDidChange:self];
}

- (void)setIsDefault:(BOOL)isDefault
{
    _isDefault = isDefault;
    [self.delegate nodeDidChange:self];
}

#pragma mark - Keys

- (id)objectForKey:(NSString *)key
{
    return [_content objectForKey:key];
}

- (nullable id)objectForKeyedSubscript:(NSString *)key
{
    return _content[key];
}

#pragma mark - KVC

- (BOOL)validateName:(id *)ioValue error:(NSError * __autoreleasing *)outError
{
    // Return an error is the name is empty
    if (![*ioValue length])
    {
        if (outError)
        {
            *outError = [[NSError alloc] initWithDomain:@"HBErrorDomain"
                                                   code:0
                                               userInfo:@{NSLocalizedDescriptionKey:@"The preset title cannot be empty.",
                                                          NSLocalizedRecoverySuggestionErrorKey:@"Please enter a title."}];
        }
        return NO;
    }

    return YES;
}

@end