source: trunk/macosx/GroupsController.m @ 7388

Last change on this file since 7388 was 7388, checked in by livings124, 12 years ago

skip bad rules instead of asserting - this might help down the road if rules are removed/changed

  • Property svn:keywords set to Date Rev Author Id
File size: 17.5 KB
Line 
1/******************************************************************************
2 * $Id: GroupsController.m 7388 2008-12-14 16:16:37Z livings124 $
3 *
4 * Copyright (c) 2007-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "GroupsController.h"
26#import "CTGradient.h"
27#import "NSBezierPathAdditions.h"
28
29#define ICON_WIDTH 16.0
30#define ICON_WIDTH_SMALL 12.0
31
32@interface GroupsController (Private)
33
34- (void) saveGroups;
35
36- (NSImage *) imageForGroup: (NSMutableDictionary *) dict;
37
38- (BOOL) torrent: (Torrent *) torrent doesMatchRulesForGroupAtIndex: (NSInteger) index;
39
40@end
41
42@implementation GroupsController
43
44GroupsController * fGroupsInstance = nil;
45+ (GroupsController *) groups
46{
47    if (!fGroupsInstance)
48        fGroupsInstance = [[GroupsController alloc] init];
49    return fGroupsInstance;
50}
51
52- (id) init
53{
54    if ((self = [super init]))
55    {
56        NSData * data;
57        if ((data = [[NSUserDefaults standardUserDefaults] dataForKey: @"Groups"]))
58            fGroups = [[NSUnarchiver unarchiveObjectWithData: data] retain];
59        else
60        {
61            //default groups
62            NSMutableDictionary * red = [NSMutableDictionary dictionaryWithObjectsAndKeys:
63                                            [NSColor redColor], @"Color",
64                                            NSLocalizedString(@"Red", "Groups -> Name"), @"Name",
65                                            [NSNumber numberWithInt: 0], @"Index", nil];
66           
67            NSMutableDictionary * orange = [NSMutableDictionary dictionaryWithObjectsAndKeys:
68                                            [NSColor orangeColor], @"Color",
69                                            NSLocalizedString(@"Orange", "Groups -> Name"), @"Name",
70                                            [NSNumber numberWithInt: 1], @"Index", nil];
71           
72            NSMutableDictionary * yellow = [NSMutableDictionary dictionaryWithObjectsAndKeys:
73                                            [NSColor yellowColor], @"Color",
74                                            NSLocalizedString(@"Yellow", "Groups -> Name"), @"Name",
75                                            [NSNumber numberWithInt: 2], @"Index", nil];
76           
77            NSMutableDictionary * green = [NSMutableDictionary dictionaryWithObjectsAndKeys:
78                                            [NSColor greenColor], @"Color",
79                                            NSLocalizedString(@"Green", "Groups -> Name"), @"Name",
80                                            [NSNumber numberWithInt: 3], @"Index", nil];
81           
82            NSMutableDictionary * blue = [NSMutableDictionary dictionaryWithObjectsAndKeys:
83                                            [NSColor blueColor], @"Color",
84                                            NSLocalizedString(@"Blue", "Groups -> Name"), @"Name",
85                                            [NSNumber numberWithInt: 4], @"Index", nil];
86           
87            NSMutableDictionary * purple = [NSMutableDictionary dictionaryWithObjectsAndKeys:
88                                            [NSColor purpleColor], @"Color",
89                                            NSLocalizedString(@"Purple", "Groups -> Name"), @"Name",
90                                            [NSNumber numberWithInt: 5], @"Index", nil];
91           
92            NSMutableDictionary * gray = [NSMutableDictionary dictionaryWithObjectsAndKeys:
93                                            [NSColor grayColor], @"Color",
94                                            NSLocalizedString(@"Gray", "Groups -> Name"), @"Name",
95                                            [NSNumber numberWithInt: 6], @"Index", nil];
96           
97            fGroups = [[NSMutableArray alloc] initWithObjects: red, orange, yellow, green, blue, purple, gray, nil];
98            [self saveGroups]; //make sure this is saved right away
99        }
100    }
101   
102    return self;
103}
104
105- (void) dealloc
106{
107    [fGroups release];
108    [super dealloc];
109}
110
111- (NSInteger) numberOfGroups
112{
113    return [fGroups count];
114}
115
116- (NSInteger) rowValueForIndex: (NSInteger) index
117{
118    if (index != -1)
119    {
120        for (NSInteger i = 0; i < [fGroups count]; i++)
121            if (index == [[[fGroups objectAtIndex: i] objectForKey: @"Index"] intValue])
122                return i;
123    }
124    return -1;
125}
126
127- (NSInteger) indexForRow: (NSInteger) row
128{
129    return [[[fGroups objectAtIndex: row] objectForKey: @"Index"] intValue];
130}
131
132- (NSString *) nameForIndex: (NSInteger) index
133{
134    NSInteger orderIndex = [self rowValueForIndex: index];
135    return orderIndex != -1 ? [[fGroups objectAtIndex: orderIndex] objectForKey: @"Name"] : nil;
136}
137
138- (void) setName: (NSString *) name forIndex: (NSInteger) index
139{
140    NSInteger orderIndex = [self rowValueForIndex: index];
141    [[fGroups objectAtIndex: orderIndex] setObject: name forKey: @"Name"];
142    [self saveGroups];
143   
144    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self];
145}
146
147- (NSImage *) imageForIndex: (NSInteger) index
148{
149    NSInteger orderIndex = [self rowValueForIndex: index];
150    return orderIndex != -1 ? [self imageForGroup: [fGroups objectAtIndex: orderIndex]]
151                            : [NSImage imageNamed: @"GroupsNoneTemplate.png"];
152}
153
154- (NSColor *) colorForIndex: (NSInteger) index
155{
156    NSInteger orderIndex = [self rowValueForIndex: index];
157    return orderIndex != -1 ? [[fGroups objectAtIndex: orderIndex] objectForKey: @"Color"] : nil;
158}
159
160- (void) setColor: (NSColor *) color forIndex: (NSInteger) index
161{
162    NSMutableDictionary * dict = [fGroups objectAtIndex: [self rowValueForIndex: index]];
163    [dict removeObjectForKey: @"Icon"];
164   
165    [dict setObject: color forKey: @"Color"];
166   
167    [[GroupsController groups] saveGroups];
168    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self];
169}
170
171- (BOOL) usesCustomDownloadLocationForIndex: (NSInteger) index
172{
173    if (![self customDownloadLocationForIndex: index])
174        return NO;
175
176    NSInteger orderIndex = [self rowValueForIndex: index];
177    return [[[fGroups objectAtIndex: orderIndex] objectForKey: @"UsesCustomDownloadLocation"] boolValue];
178}
179
180- (void) setUsesCustomDownloadLocation: (BOOL) useCustomLocation forIndex: (NSInteger) index
181{
182    NSMutableDictionary * dict = [fGroups objectAtIndex: [self rowValueForIndex: index]];
183   
184    [dict setObject: [NSNumber numberWithBool: useCustomLocation] forKey: @"UsesCustomDownloadLocation"];
185   
186    [[GroupsController groups] saveGroups];
187}
188
189- (NSString *) customDownloadLocationForIndex: (NSInteger) index
190{
191    NSInteger orderIndex = [self rowValueForIndex: index];
192    return orderIndex != -1 ? [[fGroups objectAtIndex: orderIndex] objectForKey: @"CustomDownloadLocation"] : nil;
193}
194
195- (void) setCustomDownloadLocation: (NSString *) location forIndex: (NSInteger) index
196{
197    NSMutableDictionary * dict = [fGroups objectAtIndex: [self rowValueForIndex: index]];
198    [dict setObject: location forKey: @"CustomDownloadLocation"];
199   
200    [[GroupsController groups] saveGroups];
201}
202
203- (BOOL) usesAutoAssignRulesForIndex: (NSInteger) index
204{
205    NSInteger orderIndex = [self rowValueForIndex: index];
206    if (orderIndex == -1)
207        return NO;
208   
209    NSNumber * assignRules = [[fGroups objectAtIndex: orderIndex] objectForKey: @"UsesAutoAssignRules"];
210    return assignRules && [assignRules boolValue];
211}
212
213- (void) setUsesAutoAssignRules: (BOOL) useAutoAssignRules forIndex: (NSInteger) index
214{
215    NSMutableDictionary * dict = [fGroups objectAtIndex: [self rowValueForIndex: index]];
216   
217    [dict setObject: [NSNumber numberWithBool: useAutoAssignRules] forKey: @"UsesAutoAssignRules"];
218   
219    [[GroupsController groups] saveGroups];
220}
221
222- (NSArray *) autoAssignRulesForIndex: (NSInteger) index
223{
224    NSInteger orderIndex = [self rowValueForIndex: index];
225    return orderIndex != -1 ? [[fGroups objectAtIndex: orderIndex] objectForKey: @"AutoAssignRules"] : nil;
226}
227
228- (void) setAutoAssignRules: (NSArray *) rules forIndex: (NSInteger) index
229{
230    NSMutableDictionary * dict = [fGroups objectAtIndex: [self rowValueForIndex: index]];
231   
232    if (rules && [rules count] > 0)
233    {
234        [dict setObject: rules forKey: @"AutoAssignRules"];
235       
236        [[GroupsController groups] saveGroups];
237    }
238    else
239    {
240        [dict removeObjectForKey: @"AutoAssignRules"];
241        [self setUsesAutoAssignRules: NO forIndex: index];
242    }
243}
244
245- (BOOL) rulesNeedAllForIndex: (NSInteger) index
246{
247    NSInteger orderIndex = [self rowValueForIndex: index];
248    if (orderIndex == -1)
249        return YES;
250   
251    NSNumber * enforceAll = [[fGroups objectAtIndex: orderIndex] objectForKey: @"AssignRulesNeedAll"];
252    return !enforceAll || [enforceAll boolValue];
253}
254
255- (void) setRulesNeedAllForIndex: (BOOL) all forIndex: (NSInteger) index
256{
257    NSMutableDictionary * group = [fGroups objectAtIndex: [self rowValueForIndex: index]];
258   
259    [group setObject: [NSNumber numberWithBool: all] forKey: @"AssignRulesNeedAll"];
260   
261    [[GroupsController groups] saveGroups];
262}
263
264- (void) addNewGroup
265{
266    //find the lowest index
267    NSInteger index;
268    for (index = 0; index < [fGroups count]; index++)
269    {
270        BOOL found = NO;
271        NSEnumerator * enumerator = [fGroups objectEnumerator];
272        NSDictionary * dict;
273        while ((dict = [enumerator nextObject]))
274            if ([[dict objectForKey: @"Index"] intValue] == index)
275            {
276                found = YES;
277                break;
278            }
279       
280        if (!found)
281            break;
282    }
283   
284    [fGroups addObject: [NSMutableDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt: index], @"Index",
285                            [NSColor cyanColor], @"Color", @"", @"Name", nil]];
286   
287    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self];
288    [self saveGroups];
289}
290
291- (void) removeGroupWithRowIndex: (NSInteger) row
292{
293    NSInteger index = [[[fGroups objectAtIndex: row] objectForKey: @"Index"] intValue];
294    [fGroups removeObjectAtIndex: row];
295   
296    [[NSNotificationCenter defaultCenter] postNotificationName: @"GroupValueRemoved" object: self userInfo:
297        [NSDictionary dictionaryWithObject: [NSNumber numberWithInt: index] forKey: @"Index"]];
298   
299    if (index == [[NSUserDefaults standardUserDefaults] integerForKey: @"FilterGroup"])
300        [[NSUserDefaults standardUserDefaults] setInteger: -2 forKey: @"FilterGroup"];
301   
302    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self];
303    [self saveGroups];
304}
305
306- (void) moveGroupAtRow: (NSInteger) oldRow toRow: (NSInteger) newRow
307{
308    if (oldRow < newRow)
309        newRow--;
310   
311    //remove objects to reinsert
312    id movingGroup = [[fGroups objectAtIndex: oldRow] retain];
313    [fGroups removeObjectAtIndex: oldRow];
314   
315    //insert objects at new location
316    [fGroups insertObject: movingGroup atIndex: newRow];
317   
318    [movingGroup release];
319   
320    [self saveGroups];
321    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateGroups" object: self];
322}
323
324- (NSMenu *) groupMenuWithTarget: (id) target action: (SEL) action isSmall: (BOOL) small
325{
326    NSMenu * menu = [[NSMenu alloc] initWithTitle: @"Groups"];
327   
328    NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString(@"None", "Groups -> Menu") action: action
329                            keyEquivalent: @""];
330    [item setTarget: target];
331    [item setTag: -1];
332   
333    NSImage * icon = [NSImage imageNamed: @"GroupsNoneTemplate.png"];
334    if (small)
335    {
336        icon = [icon copy];
337        [icon setScalesWhenResized: YES];
338        [icon setSize: NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL)];
339       
340        [item setImage: icon];
341        [icon release];
342    }
343    else
344        [item setImage: icon];
345   
346    [menu addItem: item];
347    [item release];
348   
349    NSEnumerator * enumerator = [fGroups objectEnumerator];
350    NSMutableDictionary * dict;
351    while ((dict = [enumerator nextObject]))
352    {
353        item = [[NSMenuItem alloc] initWithTitle: [dict objectForKey: @"Name"] action: action keyEquivalent: @""];
354        [item setTarget: target];
355       
356        [item setTag: [[dict objectForKey: @"Index"] intValue]];
357       
358        NSImage * icon = [self imageForGroup: dict];
359        if (small)
360        {
361            icon = [icon copy];
362            [icon setScalesWhenResized: YES];
363            [icon setSize: NSMakeSize(ICON_WIDTH_SMALL, ICON_WIDTH_SMALL)];
364           
365            [item setImage: icon];
366            [icon release];
367        }
368        else
369            [item setImage: icon];
370       
371        [menu addItem: item];
372        [item release];
373    }
374   
375    return [menu autorelease];
376}
377
378- (NSInteger) groupIndexForTorrent: (Torrent *) torrent;
379{
380    NSEnumerator * enumerator = [fGroups objectEnumerator];
381    NSMutableDictionary * group;
382    while ((group = [enumerator nextObject]))
383    {
384        NSInteger row = [[group objectForKey: @"Index"] intValue];
385        if ([self torrent: torrent doesMatchRulesForGroupAtIndex: row])
386            return row;
387    }
388    return -1; // Default to no group
389}
390
391@end
392
393@implementation GroupsController (Private)
394
395- (void) saveGroups
396{
397    //don't archive the icon
398    NSMutableArray * groups = [NSMutableArray arrayWithCapacity: [fGroups count]];
399    NSEnumerator * enumerator = [fGroups objectEnumerator];
400    NSDictionary * dict;
401    while ((dict = [enumerator nextObject]))
402    {
403        NSMutableDictionary * tempDict = [dict mutableCopy];
404        [tempDict removeObjectForKey: @"Icon"];
405        [groups addObject: tempDict];
406        [tempDict release];
407    }
408   
409    [[NSUserDefaults standardUserDefaults] setObject: [NSArchiver archivedDataWithRootObject: groups] forKey: @"Groups"];
410}
411
412- (NSImage *) imageForGroup: (NSMutableDictionary *) dict
413{
414    NSImage * image;
415    if ((image = [dict objectForKey: @"Icon"]))
416        return image;
417   
418    NSRect rect = NSMakeRect(0.0, 0.0, ICON_WIDTH, ICON_WIDTH);
419   
420    NSBezierPath * bp = [NSBezierPath bezierPathWithRoundedRect: rect radius: 3.0];
421    NSImage * icon = [[NSImage alloc] initWithSize: rect.size];
422   
423    NSColor * color = [dict objectForKey: @"Color"];
424   
425    [icon lockFocus];
426   
427    //border
428    CTGradient * gradient = [CTGradient gradientWithBeginningColor: [color blendedColorWithFraction: 0.45 ofColor:
429                                [NSColor whiteColor]] endingColor: color];
430    [gradient fillBezierPath: bp angle: 270.0];
431   
432    //inside
433    bp = [NSBezierPath bezierPathWithRoundedRect: NSInsetRect(rect, 1.0, 1.0) radius: 3.0];
434    gradient = [CTGradient gradientWithBeginningColor: [color blendedColorWithFraction: 0.75 ofColor: [NSColor whiteColor]]
435                endingColor: [color blendedColorWithFraction: 0.2 ofColor: [NSColor whiteColor]]];
436    [gradient fillBezierPath: bp angle: 270.0];
437   
438    [icon unlockFocus];
439   
440    [dict setObject: icon forKey: @"Icon"];
441    [icon release];
442   
443    return icon;
444}
445
446- (BOOL) torrent: (Torrent *) torrent doesMatchRulesForGroupAtIndex: (NSInteger) index
447{
448    if (![self usesAutoAssignRulesForIndex: index])
449        return NO;
450   
451    const BOOL needAll = [self rulesNeedAllForIndex: index];
452    BOOL anyPassed = NO;
453   
454    NSEnumerator * iterator = [[self autoAssignRulesForIndex: index] objectEnumerator];
455    NSArray * rule = nil;
456    while ((rule = [iterator nextObject]))
457    {
458        NSString * type = [rule objectAtIndex: 0], * place = [rule objectAtIndex: 1], * givenValue = [rule objectAtIndex: 2];
459        NSArray * values;
460        if ([type isEqualToString: @"title"])
461            values = [NSArray arrayWithObject: [torrent name]];
462        else if ([type isEqualToString: @"tracker"])
463            values = [torrent allTrackers: NO];
464        else
465            continue;
466       
467        NSStringCompareOptions options;
468        if ([place isEqualToString: @"begins"])
469            options = NSCaseInsensitiveSearch + NSAnchoredSearch;
470        else if ([place isEqualToString: @"ends"])
471            options = NSCaseInsensitiveSearch + NSBackwardsSearch + NSAnchoredSearch;
472        else if ([place isEqualToString: @"contains"])
473            options = NSCaseInsensitiveSearch;
474        else
475            continue;
476       
477        BOOL match = NO;
478       
479        NSEnumerator * enumerator = [values objectEnumerator];
480        NSString * value;
481        while ((value = [enumerator nextObject]))
482        {
483            NSRange result = [value rangeOfString: givenValue options: options];
484            if (result.location != NSNotFound)
485            {
486                match = YES;
487                anyPassed = YES;
488                break;
489            }
490        }
491       
492        if (match && !needAll)
493            return YES;
494        else if (!match && needAll)
495            return NO;
496        else;
497    }
498   
499    return anyPassed && needAll;
500}
501
502@end
Note: See TracBrowser for help on using the repository browser.