summaryrefslogtreecommitdiffstats
path: root/macosx/HBTreeNode.m
blob: a2a69f406d4621dc370aa500842d1a1f080f02ac (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
/*  HBTreeNode.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 "HBTreeNode.h"

@implementation HBTreeNode

- (instancetype)init
{
    self = [super init];
    if (self) {
        _children = [[NSMutableArray alloc] init];
        _isLeaf = YES;
    }
    return self;
}

- (NSUInteger)countOfChildren
{
    return self.children.count;
}

- (id)objectInChildrenAtIndex:(NSUInteger)index
{
    return [self.children objectAtIndex:index];
}

- (void)insertObject:(HBTreeNode *)presetObject inChildrenAtIndex:(NSUInteger)index
{
    [self.children insertObject:presetObject atIndex:index];
    [presetObject setDelegate:self.delegate];

    [self.delegate nodeDidChange];
}

- (void)removeObjectFromChildrenAtIndex:(NSUInteger)index
{
    [self.children removeObjectAtIndex:index];
    [self.delegate nodeDidChange];
}

#pragma mark - Enumeration

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSIndexPath *idx, BOOL *stop))block
{
    BOOL stop = NO;
    NSMutableArray *queue = [[NSMutableArray alloc] init];
    NSMutableArray *indexesQueue = [[NSMutableArray alloc] init];

    [queue addObject:self];
    [indexesQueue addObject:[[NSIndexPath alloc] init]];

    HBTreeNode *node = nil;
    while ((node = [queue lastObject]) != nil)
    {
        // Get the index path of the current object
        NSIndexPath *indexPath = [indexesQueue lastObject];

        // Call the block
        block(node, indexPath, &stop);

        if (stop)
        {
            break;
        }

        [indexesQueue removeLastObject];

        for (NSInteger i = node.children.count - 1; i >= 0; i--)
        {
            [indexesQueue addObject:[indexPath indexPathByAddingIndex:i]];
        }

        [queue removeLastObject];

        for (id childNode in [node.children reverseObjectEnumerator])
        {
            [queue addObject:childNode];
        }
    }
}

@end