source: trunk/macosx/TorrentTableView.m @ 9844

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

happy new year!

  • Property svn:keywords set to Date Rev Author Id
File size: 30.7 KB
Line 
1/******************************************************************************
2 * $Id: TorrentTableView.m 9844 2010-01-01 21:12:04Z livings124 $
3 *
4 * Copyright (c) 2005-2010 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 "TorrentTableView.h"
26#import "Controller.h"
27#import "FileListNode.h"
28#import "NSApplicationAdditions.h"
29#import "Torrent.h"
30#import "TorrentCell.h"
31#import "TorrentGroup.h"
32
33#define MAX_GROUP 999999
34
35#define ACTION_MENU_GLOBAL_TAG 101
36#define ACTION_MENU_UNLIMITED_TAG 102
37#define ACTION_MENU_LIMIT_TAG 103
38
39#define ACTION_MENU_PRIORITY_HIGH_TAG 101
40#define ACTION_MENU_PRIORITY_NORMAL_TAG 102
41#define ACTION_MENU_PRIORITY_LOW_TAG 103
42
43#define TOGGLE_PROGRESS_SECONDS 0.175
44
45@interface TorrentTableView (Private)
46
47- (BOOL) pointInGroupStatusRect: (NSPoint) point;
48
49- (void) setGroupStatusColumns;
50
51- (void) createFileMenu: (NSMenu *) menu forFiles: (NSArray *) files;
52
53@end
54
55@implementation TorrentTableView
56
57- (id) initWithCoder: (NSCoder *) decoder
58{
59    if ((self = [super initWithCoder: decoder]))
60    {
61        fDefaults = [NSUserDefaults standardUserDefaults];
62       
63        fTorrentCell = [[TorrentCell alloc] init];
64       
65        NSData * groupData = [fDefaults dataForKey: @"CollapsedGroups"];
66        if (groupData)
67            fCollapsedGroups = [[NSUnarchiver unarchiveObjectWithData: groupData] mutableCopy];
68        else
69            fCollapsedGroups = [[NSMutableIndexSet alloc] init];
70       
71        fMouseControlRow = -1;
72        fMouseRevealRow = -1;
73        fMouseActionRow = -1;
74        fActionPushedRow = -1;
75       
76        [self setDelegate: self];
77       
78        fPiecesBarPercent = [fDefaults boolForKey: @"PiecesBar"] ? 1.0f : 0.0f;
79    }
80   
81    return self;
82}
83
84- (void) dealloc
85{
86    [fCollapsedGroups release];
87   
88    [fPiecesBarAnimation release];
89    [fMenuTorrent release];
90   
91    [fSelectedValues release];
92   
93    [fTorrentCell release];
94   
95    [super dealloc];
96}
97
98- (void) awakeFromNib
99{
100    //set group columns to show ratio, needs to be in awakeFromNib to size columns correctly
101    [self setGroupStatusColumns];
102}
103
104- (BOOL) isGroupCollapsed: (NSInteger) value
105{
106    if (value == -1)
107        value = MAX_GROUP;
108   
109    return [fCollapsedGroups containsIndex: value];
110}
111
112- (void) removeCollapsedGroup: (NSInteger) value
113{
114    if (value == -1)
115        value = MAX_GROUP;
116   
117    [fCollapsedGroups removeIndex: value];
118}
119
120- (void) removeAllCollapsedGroups
121{
122    [fCollapsedGroups removeAllIndexes];
123}
124
125- (void) saveCollapsedGroups
126{
127    [fDefaults setObject: [NSArchiver archivedDataWithRootObject: fCollapsedGroups] forKey: @"CollapsedGroups"];
128}
129
130- (BOOL) outlineView: (NSOutlineView *) outlineView isGroupItem: (id) item
131{
132    return ![item isKindOfClass: [Torrent class]];
133}
134
135- (CGFloat) outlineView: (NSOutlineView *) outlineView heightOfRowByItem: (id) item
136{
137    return [item isKindOfClass: [Torrent class]] ? [self rowHeight] : GROUP_SEPARATOR_HEIGHT;
138}
139
140- (NSCell *) outlineView: (NSOutlineView *) outlineView dataCellForTableColumn: (NSTableColumn *) tableColumn item: (id) item
141{
142    const BOOL group = ![item isKindOfClass: [Torrent class]];
143    if (!tableColumn)
144        return !group ? fTorrentCell : nil;
145    else
146        return group ? [tableColumn dataCellForRow: [self rowForItem: item]] : nil;
147}
148
149- (void) outlineView: (NSOutlineView *) outlineView willDisplayCell: (id) cell forTableColumn: (NSTableColumn *) tableColumn
150    item: (id) item
151{
152    if ([item isKindOfClass: [Torrent class]])
153    {
154        [cell setRepresentedObject: item];
155       
156        const NSInteger row = [self rowForItem: item];
157        [cell setControlHover: row == fMouseControlRow];
158        [cell setRevealHover: row == fMouseRevealRow];
159        [cell setActionHover: row == fMouseActionRow];
160        [cell setActionPushed: row == fActionPushedRow];
161    }
162    else
163    {
164        NSString * ident = [tableColumn identifier];
165        if ([ident isEqualToString: @"UL Image"] || [ident isEqualToString: @"DL Image"])
166        {
167            //ensure arrows are white only when selected
168            if ([NSApp isOnSnowLeopardOrBetter])
169                [[cell image] setTemplate: [cell backgroundStyle] == NSBackgroundStyleLowered];
170            else
171            {
172                NSImage * image = [cell image];
173                const BOOL template = [cell backgroundStyle] == NSBackgroundStyleLowered;
174                if ([image isTemplate] != template)
175                {
176                    [image setTemplate: template];
177                    [cell setImage: nil];
178                    [cell setImage: image];
179                }
180            }
181        }
182    }
183}
184
185- (NSRect) frameOfCellAtColumn: (NSInteger) column row: (NSInteger) row
186{
187    if (column == -1)
188        return [self rectOfRow: row];
189    else
190    {
191        NSRect rect = [super frameOfCellAtColumn: column row: row];
192       
193        //adjust placement for proper vertical alignment
194        if (column == [self columnWithIdentifier: @"Group"])
195            rect.size.height -= 1.0f;
196       
197        return rect;
198    }
199}
200
201- (NSString *) outlineView: (NSOutlineView *) outlineView typeSelectStringForTableColumn: (NSTableColumn *) tableColumn item: (id) item
202{
203    return [item isKindOfClass: [Torrent class]] ? [item name]
204            : [[self preparedCellAtColumn: [self columnWithIdentifier: @"Group"] row: [self rowForItem: item]] stringValue];
205}
206
207- (NSString *) outlineView: (NSOutlineView *) outlineView toolTipForCell: (NSCell *) cell rect: (NSRectPointer) rect
208                tableColumn: (NSTableColumn *) column item: (id) item mouseLocation: (NSPoint) mouseLocation
209{
210    NSString * ident = [column identifier];
211    if ([ident isEqualToString: @"DL"] || [ident isEqualToString: @"DL Image"])
212        return NSLocalizedString(@"Download speed", "Torrent table -> group row -> tooltip");
213    else if ([ident isEqualToString: @"UL"] || [ident isEqualToString: @"UL Image"])
214        return [fDefaults boolForKey: @"DisplayGroupRowRatio"] ? NSLocalizedString(@"Ratio", "Torrent table -> group row -> tooltip")
215                : NSLocalizedString(@"Upload speed", "Torrent table -> group row -> tooltip");
216    else if (ident)
217    {
218        NSInteger count = [[item torrents] count];
219        if (count == 1)
220            return NSLocalizedString(@"1 transfer", "Torrent table -> group row -> tooltip");
221        else
222            return [NSString stringWithFormat: NSLocalizedString(@"%d transfers", "Torrent table -> group row -> tooltip"), count];
223    }
224    else
225        return nil;
226}
227
228- (void) updateTrackingAreas
229{
230    [super updateTrackingAreas];
231    [self removeButtonTrackingAreas];
232   
233    NSRange rows = [self rowsInRect: [self visibleRect]];
234    if (rows.length == 0)
235        return;
236   
237    NSPoint mouseLocation = [self convertPoint: [[self window] convertScreenToBase: [NSEvent mouseLocation]] fromView: nil];
238    for (NSUInteger row = rows.location; row < NSMaxRange(rows); row++)
239    {
240        if (![[self itemAtRow: row] isKindOfClass: [Torrent class]])
241            continue;
242       
243        NSDictionary * userInfo = [NSDictionary dictionaryWithObject: [NSNumber numberWithInteger: row] forKey: @"Row"];
244        TorrentCell * cell = (TorrentCell *)[self preparedCellAtColumn: -1 row: row];
245        [cell addTrackingAreasForView: self inRect: [self rectOfRow: row] withUserInfo: userInfo mouseLocation: mouseLocation];
246    }
247}
248
249- (void) removeButtonTrackingAreas
250{
251    fMouseControlRow = -1;
252    fMouseRevealRow = -1;
253    fMouseActionRow = -1;
254   
255    for (NSTrackingArea * area in [self trackingAreas])
256    {
257        if ([area owner] == self && [[area userInfo] objectForKey: @"Row"])
258            [self removeTrackingArea: area];
259    }
260}
261
262- (void) setControlButtonHover: (NSInteger) row
263{
264    fMouseControlRow = row;
265    if (row >= 0)
266        [self setNeedsDisplayInRect: [self rectOfRow: row]];
267}
268
269- (void) setRevealButtonHover: (NSInteger) row
270{
271    fMouseRevealRow = row;
272    if (row >= 0)
273        [self setNeedsDisplayInRect: [self rectOfRow: row]];
274}
275
276- (void) setActionButtonHover: (NSInteger) row
277{
278    fMouseActionRow = row;
279    if (row >= 0)
280        [self setNeedsDisplayInRect: [self rectOfRow: row]];
281}
282
283- (void) mouseEntered: (NSEvent *) event
284{
285    NSDictionary * dict = (NSDictionary *)[event userData];
286   
287    NSNumber * row;
288    if ((row = [dict objectForKey: @"Row"]))
289    {
290        NSInteger rowVal = [row integerValue];
291        NSString * type = [dict objectForKey: @"Type"];
292        if ([type isEqualToString: @"Action"])
293            fMouseActionRow = rowVal;
294        else if ([type isEqualToString: @"Control"])
295            fMouseControlRow = rowVal;
296        else
297            fMouseRevealRow = rowVal;
298       
299        [self setNeedsDisplayInRect: [self rectOfRow: rowVal]];
300    }
301}
302
303- (void) mouseExited: (NSEvent *) event
304{
305    NSDictionary * dict = (NSDictionary *)[event userData];
306   
307    NSNumber * row;
308    if ((row = [dict objectForKey: @"Row"]))
309    {
310        NSString * type = [dict objectForKey: @"Type"];
311        if ([type isEqualToString: @"Action"])
312            fMouseActionRow = -1;
313        else if ([type isEqualToString: @"Control"])
314            fMouseControlRow = -1;
315        else
316            fMouseRevealRow = -1;
317       
318        [self setNeedsDisplayInRect: [self rectOfRow: [row integerValue]]];
319    }
320}
321
322- (void) outlineViewSelectionIsChanging: (NSNotification *) notification
323{
324    if (fSelectedValues)
325        [self selectValues: fSelectedValues];
326}
327
328- (void) outlineViewItemDidExpand: (NSNotification *) notification
329{
330    NSInteger value = [[[notification userInfo] objectForKey: @"NSObject"] groupIndex];
331    if (value < 0)
332        value = MAX_GROUP;
333   
334    if ([fCollapsedGroups containsIndex: value])
335    {
336        [fCollapsedGroups removeIndex: value];
337        [[NSNotificationCenter defaultCenter] postNotificationName: @"OutlineExpandCollapse" object: self];
338    }
339}
340
341- (void) outlineViewItemDidCollapse: (NSNotification *) notification
342{
343    NSInteger value = [[[notification userInfo] objectForKey: @"NSObject"] groupIndex];
344    if (value < 0)
345        value = MAX_GROUP;
346   
347    [fCollapsedGroups addIndex: value];
348    [[NSNotificationCenter defaultCenter] postNotificationName: @"OutlineExpandCollapse" object: self];
349}
350
351- (void) mouseDown: (NSEvent *) event
352{
353    NSPoint point = [self convertPoint: [event locationInWindow] fromView: nil];
354    const NSInteger row = [self rowAtPoint: point];
355   
356    //check to toggle group status before anything else
357    if ([self pointInGroupStatusRect: point])
358    {
359        [fDefaults setBool: ![fDefaults boolForKey: @"DisplayGroupRowRatio"] forKey: @"DisplayGroupRowRatio"];
360        [self setGroupStatusColumns];
361       
362        return;
363    }
364   
365    const BOOL pushed = row != -1 && (fMouseActionRow == row || fMouseRevealRow == row || fMouseControlRow == row);
366   
367    //if pushing a button, don't change the selected rows
368    if (pushed)
369        fSelectedValues = [[self selectedValues] retain];
370   
371    [super mouseDown: event];
372   
373    [fSelectedValues release];
374    fSelectedValues = nil;
375   
376    //avoid weird behavior when showing menu by doing this after mouse down
377    if (row != -1 && fMouseActionRow == row)
378    {
379        fActionPushedRow = row;
380        [self setNeedsDisplayInRect: [self rectOfRow: row]]; //ensure button is pushed down
381       
382        [self displayTorrentMenuForEvent: event];
383       
384        fActionPushedRow = -1;
385        [self setNeedsDisplayInRect: [self rectOfRow: row]];
386    }
387    else if (!pushed && [event clickCount] == 2) //double click
388    {
389        id item = nil;
390        if (row != -1)
391            item = [self itemAtRow: row];
392       
393        if (!item || [item isKindOfClass: [Torrent class]])
394            [fController showInfo: nil];
395        else
396        {
397            if ([self isItemExpanded: item])
398                [self collapseItem: item];
399            else
400                [self expandItem: item];
401        }
402    }
403    else;
404}
405
406- (void) selectValues: (NSArray *) values
407{
408    NSMutableIndexSet * indexSet = [NSMutableIndexSet indexSet];
409   
410    for (id item in values)
411    {
412        if ([item isKindOfClass: [Torrent class]])
413        {
414            const NSInteger index = [self rowForItem: item];
415            if (index != -1)
416                [indexSet addIndex: index];
417        }
418        else
419        {
420            const NSInteger group = [item groupIndex];
421            for (NSInteger i = 0; i < [self numberOfRows]; i++)
422            {
423                id tableItem = [self itemAtRow: i];
424                if ([tableItem isKindOfClass: [TorrentGroup class]] && group == [tableItem groupIndex])
425                {
426                    [indexSet addIndex: i];
427                    break;
428                }
429            }
430        }
431    }
432   
433    [self selectRowIndexes: indexSet byExtendingSelection: NO];
434}
435
436- (NSArray *) selectedValues
437{
438    NSIndexSet * selectedIndexes = [self selectedRowIndexes];
439    NSMutableArray * values = [NSMutableArray arrayWithCapacity: [selectedIndexes count]];
440   
441    for (NSUInteger i = [selectedIndexes firstIndex]; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex: i])
442        [values addObject: [self itemAtRow: i]];
443   
444    return values;
445}
446
447- (NSArray *) selectedTorrents
448{
449    NSIndexSet * selectedIndexes = [self selectedRowIndexes];
450    NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [selectedIndexes count]]; //take a shot at guessing capacity
451   
452    for (NSUInteger i = [selectedIndexes firstIndex]; i != NSNotFound; i = [selectedIndexes indexGreaterThanIndex: i])
453    {
454        id item = [self itemAtRow: i];
455        if ([item isKindOfClass: [Torrent class]])
456            [torrents addObject: item];
457        else
458        {
459            NSArray * groupTorrents = [item torrents];
460            [torrents addObjectsFromArray: groupTorrents];
461            if ([self isItemExpanded: item])
462                i +=[groupTorrents count];
463        }
464    }
465   
466    return torrents;
467}
468
469- (NSMenu *) menuForEvent: (NSEvent *) event
470{
471    NSInteger row = [self rowAtPoint: [self convertPoint: [event locationInWindow] fromView: nil]];
472    if (row >= 0)
473    {
474        if (![self isRowSelected: row])
475            [self selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO];
476        return fContextRow;
477    }
478    else
479    {
480        [self deselectAll: self];
481        return fContextNoRow;
482    }
483}
484
485//make sure that the pause buttons become orange when holding down the option key
486- (void) flagsChanged: (NSEvent *) event
487{
488    [self display];
489    [super flagsChanged: event];
490}
491
492//option-command-f will focus the filter bar's search field
493- (void) keyDown: (NSEvent *) event
494{
495    const unichar firstChar = [[event charactersIgnoringModifiers] characterAtIndex: 0];
496   
497    if (firstChar == 'f' && [event modifierFlags] & NSAlternateKeyMask && [event modifierFlags] & NSCommandKeyMask)
498        [fController focusFilterField];
499    else if (firstChar == ' ')
500        [fController toggleQuickLook: nil];
501    else
502        [super keyDown: event];
503}
504
505- (NSRect) iconRectForRow: (NSInteger) row
506{
507    return [fTorrentCell iconRectForBounds: [self rectOfRow: row]];
508}
509
510#warning catch string urls?
511- (void) paste: (id) sender
512{
513    NSURL * url;
514    if ((url = [NSURL URLFromPasteboard: [NSPasteboard generalPasteboard]]))
515        [fController openURL: [url absoluteString]];
516}
517
518- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
519{
520    SEL action = [menuItem action];
521   
522    if (action == @selector(paste:))
523        return [[[NSPasteboard generalPasteboard] types] containsObject: NSURLPboardType];
524   
525    return YES;
526}
527
528- (void) toggleControlForTorrent: (Torrent *) torrent
529{
530    if ([torrent isActive])
531        [fController stopTorrents: [NSArray arrayWithObject: torrent]];
532    else
533    {
534        if (([NSApp isOnSnowLeopardOrBetter] ? [NSEvent modifierFlags] : [[NSApp currentEvent] modifierFlags]) & NSAlternateKeyMask)
535            [fController resumeTorrentsNoWait: [NSArray arrayWithObject: torrent]];
536        else if ([torrent waitingToStart])
537            [fController stopTorrents: [NSArray arrayWithObject: torrent]];
538        else
539            [fController resumeTorrents: [NSArray arrayWithObject: torrent]];
540    }
541}
542
543- (void) displayTorrentMenuForEvent: (NSEvent *) event
544{
545    const NSInteger row = [self rowAtPoint: [self convertPoint: [event locationInWindow] fromView: nil]];
546    if (row < 0)
547        return;
548   
549    const NSInteger numberOfNonFileItems = [fActionMenu numberOfItems];
550   
551    //update file action menu
552    fMenuTorrent = [[self itemAtRow: row] retain];
553   
554    //show/hide the file divider
555    const BOOL isFolder = [fMenuTorrent isFolder];
556    [[fActionMenu itemAtIndex: numberOfNonFileItems-1] setHidden: !isFolder];
557   
558    if (isFolder)
559        [self createFileMenu: fActionMenu forFiles: [fMenuTorrent fileList]];
560   
561    //update global limit check
562    [fGlobalLimitItem setState: [fMenuTorrent usesGlobalSpeedLimit] ? NSOnState : NSOffState];
563   
564    //place menu below button
565    NSRect rect = [fTorrentCell iconRectForBounds: [self rectOfRow: row]];
566    NSPoint location = rect.origin;
567    location.y += rect.size.height + 5.0;
568   
569    if ([NSApp isOnSnowLeopardOrBetter])
570    {
571        location = [self convertPoint: location toView: self];
572        [fActionMenu popUpMenuPositioningItem: nil atLocation: location inView: self];
573    }
574    else
575    {
576        location = [self convertPoint: location toView: nil];
577        NSEvent * newEvent = [NSEvent mouseEventWithType: [event type] location: location
578            modifierFlags: [event modifierFlags] timestamp: [event timestamp] windowNumber: [event windowNumber]
579            context: [event context] eventNumber: [event eventNumber] clickCount: [event clickCount] pressure: [event pressure]];
580       
581        [NSMenu popUpContextMenu: fActionMenu withEvent: newEvent forView: self];
582    }
583   
584    for (NSInteger i = [fActionMenu numberOfItems]-1; i >= numberOfNonFileItems; i--)
585        [fActionMenu removeItemAtIndex: i];
586   
587    [fMenuTorrent release];
588    fMenuTorrent = nil;
589}
590
591- (void) menuNeedsUpdate: (NSMenu *) menu
592{
593    //this method seems to be called when it shouldn't be
594    if (!fMenuTorrent || ![menu supermenu])
595        return;
596   
597    if (menu == fUploadMenu || menu == fDownloadMenu)
598    {
599        NSMenuItem * item;
600        if ([menu numberOfItems] == 3)
601        {
602            const NSInteger speedLimitActionValue[] = { 0, 5, 10, 20, 30, 40, 50, 75, 100, 150, 200, 250, 500,
603                                                        750, 1000, 1500, 2000, -1 };
604           
605            for (NSInteger i = 0; speedLimitActionValue[i] != -1; i++)
606            {
607                item = [[NSMenuItem alloc] initWithTitle: [NSString stringWithFormat: NSLocalizedString(@"%d KB/s",
608                        "Action menu -> upload/download limit"), speedLimitActionValue[i]] action: @selector(setQuickLimit:)
609                        keyEquivalent: @""];
610                [item setTarget: self];
611                [item setRepresentedObject: [NSNumber numberWithInt: speedLimitActionValue[i]]];
612                [menu addItem: item];
613                [item release];
614            }
615        }
616       
617        const BOOL upload = menu == fUploadMenu;
618        const BOOL limit = [fMenuTorrent usesSpeedLimit: upload];
619       
620        item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG];
621        [item setState: limit ? NSOnState : NSOffState];
622        [item setTitle: [NSString stringWithFormat: NSLocalizedString(@"Limit (%d KB/s)",
623                            "torrent action menu -> upload/download limit"), [fMenuTorrent speedLimit: upload]]];
624       
625        item = [menu itemWithTag: ACTION_MENU_UNLIMITED_TAG];
626        [item setState: !limit ? NSOnState : NSOffState];
627    }
628    else if (menu == fRatioMenu)
629    {
630        NSMenuItem * item;
631        if ([menu numberOfItems] == 4)
632        {
633            const CGFloat ratioLimitActionValue[] = { 0.25f, 0.5f, 0.75f, 1.0f, 1.5f, 2.0f, 3.0f, -1.0f };
634           
635            for (NSInteger i = 0; ratioLimitActionValue[i] != -1.0f; i++)
636            {
637                item = [[NSMenuItem alloc] initWithTitle: [NSString localizedStringWithFormat: @"%.2f", ratioLimitActionValue[i]]
638                        action: @selector(setQuickRatio:) keyEquivalent: @""];
639                [item setTarget: self];
640                [item setRepresentedObject: [NSNumber numberWithFloat: ratioLimitActionValue[i]]];
641                [menu addItem: item];
642                [item release];
643            }
644        }
645       
646        const tr_ratiolimit mode = [fMenuTorrent ratioSetting];
647       
648        item = [menu itemWithTag: ACTION_MENU_LIMIT_TAG];
649        [item setState: mode == TR_RATIOLIMIT_SINGLE ? NSOnState : NSOffState];
650        [item setTitle: [NSString localizedStringWithFormat: NSLocalizedString(@"Stop at Ratio (%.2f)",
651            "torrent action menu -> ratio stop"), [fMenuTorrent ratioLimit]]];
652       
653        item = [menu itemWithTag: ACTION_MENU_UNLIMITED_TAG];
654        [item setState: mode == TR_RATIOLIMIT_UNLIMITED ? NSOnState : NSOffState];
655       
656        item = [menu itemWithTag: ACTION_MENU_GLOBAL_TAG];
657        [item setState: mode == TR_RATIOLIMIT_GLOBAL ? NSOnState : NSOffState];
658    }
659    else if (menu == fPriorityMenu)
660    {
661        const tr_priority_t priority = [fMenuTorrent priority];
662       
663        NSMenuItem * item = [menu itemWithTag: ACTION_MENU_PRIORITY_HIGH_TAG];
664        [item setState: priority == TR_PRI_HIGH ? NSOnState : NSOffState];
665       
666        item = [menu itemWithTag: ACTION_MENU_PRIORITY_NORMAL_TAG];
667        [item setState: priority == TR_PRI_NORMAL ? NSOnState : NSOffState];
668       
669        item = [menu itemWithTag: ACTION_MENU_PRIORITY_LOW_TAG];
670        [item setState: priority == TR_PRI_LOW ? NSOnState : NSOffState];
671    }
672    else //assume the menu is part of the file list
673    {
674        if ([menu numberOfItems] > 0)
675            return;
676       
677        NSMenu * supermenu = [menu supermenu];
678        [self createFileMenu: menu forFiles: [(FileListNode *)[[supermenu itemAtIndex: [supermenu indexOfItemWithSubmenu: menu]]
679                                                representedObject] children]];
680    }
681}
682
683//alternating rows - first row after group row is white
684- (void) highlightSelectionInClipRect: (NSRect) clipRect
685{
686    NSRect visibleRect = clipRect;
687    NSRange rows = [self rowsInRect: visibleRect];
688    BOOL start = YES;
689   
690    const CGFloat totalRowHeight = [self rowHeight] + [self intercellSpacing].height;
691   
692    NSRect gridRects[(NSInteger)(ceil(visibleRect.size.height / totalRowHeight / 2.0)) + 1]; //add one if partial rows at top and bottom
693    NSInteger rectNum = 0;
694   
695    if (rows.length > 0)
696    {
697        //determine what the first row color should be
698        if ([[self itemAtRow: rows.location] isKindOfClass: [Torrent class]])
699        {
700            for (NSInteger i = rows.location-1; i>=0; i--)
701            {
702                if (![[self itemAtRow: i] isKindOfClass: [Torrent class]])
703                    break;
704                start = !start;
705            }
706        }
707        else
708        {
709            rows.location++;
710            rows.length--;
711        }
712       
713        NSInteger i;
714        for (i = rows.location; i < NSMaxRange(rows); i++)
715        {
716            if (![[self itemAtRow: i] isKindOfClass: [Torrent class]])
717            {
718                start = YES;
719                continue;
720            }
721           
722            if (!start && ![self isRowSelected: i])
723                gridRects[rectNum++] = [self rectOfRow: i];
724           
725            start = !start;
726        }
727       
728        const CGFloat newY = NSMaxY([self rectOfRow: i-1]);
729        visibleRect.size.height -= newY - visibleRect.origin.y;
730        visibleRect.origin.y = newY;
731    }
732   
733    const NSInteger numberBlankRows = ceil(visibleRect.size.height / totalRowHeight);
734   
735    //remaining visible rows continue alternating
736    visibleRect.size.height = totalRowHeight;
737    if (start)
738        visibleRect.origin.y += totalRowHeight;
739   
740    for (NSInteger i = start ? 1 : 0; i < numberBlankRows; i += 2)
741    {
742        gridRects[rectNum++] = visibleRect;
743        visibleRect.origin.y += 2.0 * totalRowHeight;
744    }
745   
746    NSAssert([[NSColor controlAlternatingRowBackgroundColors] count] >= 2, @"There should be 2 alternating row colors");
747   
748    [[[NSColor controlAlternatingRowBackgroundColors] objectAtIndex: 1] set];
749    NSRectFillList(gridRects, rectNum);
750   
751    [super highlightSelectionInClipRect: clipRect];
752}
753
754- (void) setQuickLimitMode: (id) sender
755{
756    const BOOL limit = [sender tag] == ACTION_MENU_LIMIT_TAG;
757    [fMenuTorrent setUseSpeedLimit: limit upload: [sender menu] == fUploadMenu];
758   
759    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil];
760}
761
762- (void) setQuickLimit: (id) sender
763{
764    const BOOL upload = [sender menu] == fUploadMenu;
765    [fMenuTorrent setUseSpeedLimit: YES upload: upload];
766    [fMenuTorrent setSpeedLimit: [[sender representedObject] intValue] upload: upload];
767   
768    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil];
769}
770
771- (void) setGlobalLimit: (id) sender
772{
773    [fMenuTorrent setUseGlobalSpeedLimit: [sender state] != NSOnState];
774   
775    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil];
776}
777
778- (void) setQuickRatioMode: (id) sender
779{
780    tr_ratiolimit mode;
781    switch ([sender tag])
782    {
783        case ACTION_MENU_UNLIMITED_TAG:
784            mode = TR_RATIOLIMIT_UNLIMITED;
785            break;
786        case ACTION_MENU_LIMIT_TAG:
787            mode = TR_RATIOLIMIT_SINGLE;
788            break;
789        case ACTION_MENU_GLOBAL_TAG:
790            mode = TR_RATIOLIMIT_GLOBAL;
791            break;
792        default:
793            return;
794    }
795   
796    [fMenuTorrent setRatioSetting: mode];
797   
798    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil];
799}
800
801- (void) setQuickRatio: (id) sender
802{
803    [fMenuTorrent setRatioSetting: TR_RATIOLIMIT_SINGLE];
804    [fMenuTorrent setRatioLimit: [[sender representedObject] floatValue]];
805   
806    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateOptions" object: nil];
807}
808
809- (void) setPriority: (id) sender
810{
811    tr_priority_t priority;
812    switch ([sender tag])
813    {
814        case ACTION_MENU_PRIORITY_HIGH_TAG:
815            priority = TR_PRI_HIGH;
816            break;
817        case ACTION_MENU_PRIORITY_NORMAL_TAG:
818            priority = TR_PRI_NORMAL;
819            break;
820        case ACTION_MENU_PRIORITY_LOW_TAG:
821            priority = TR_PRI_LOW;
822            break;
823        default:
824            NSAssert1(NO, @"Unknown priority: %d", [sender tag]);
825    }
826   
827    [fMenuTorrent setPriority: priority];
828   
829    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateUI" object: nil];
830}
831
832- (void) checkFile: (id) sender
833{
834    NSIndexSet * indexSet = [(FileListNode *)[sender representedObject] indexes];
835    [fMenuTorrent setFileCheckState: [sender state] != NSOnState ? NSOnState : NSOffState forIndexes: indexSet];
836   
837    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
838}
839
840- (void) togglePiecesBar
841{
842    //stop previous animation
843    if (fPiecesBarAnimation)
844        [fPiecesBarAnimation release];
845   
846    NSMutableArray * progressMarks = [NSMutableArray arrayWithCapacity: 16];
847    for (NSAnimationProgress i = 0.0625f; i <= 1.0f; i += 0.0625f)
848        [progressMarks addObject: [NSNumber numberWithFloat: i]];
849   
850    fPiecesBarAnimation = [[NSAnimation alloc] initWithDuration: TOGGLE_PROGRESS_SECONDS animationCurve: NSAnimationEaseIn];
851    [fPiecesBarAnimation setAnimationBlockingMode: NSAnimationNonblocking];
852    [fPiecesBarAnimation setProgressMarks: progressMarks];
853    [fPiecesBarAnimation setDelegate: self];
854   
855    [fPiecesBarAnimation startAnimation];
856}
857
858- (void) animationDidEnd: (NSAnimation *) animation
859{
860    if (animation == fPiecesBarAnimation)
861    {
862        [fPiecesBarAnimation release];
863        fPiecesBarAnimation = nil;
864    }
865}
866
867- (void) animation: (NSAnimation *) animation didReachProgressMark: (NSAnimationProgress) progress
868{
869    if (animation == fPiecesBarAnimation)
870    {
871        if ([fDefaults boolForKey: @"PiecesBar"])
872            fPiecesBarPercent = progress;
873        else
874            fPiecesBarPercent = 1.0f - progress;
875       
876        [self reloadData];
877    }
878}
879
880- (CGFloat) piecesBarPercent
881{
882    return fPiecesBarPercent;
883}
884
885@end
886
887@implementation TorrentTableView (Private)
888
889- (BOOL) pointInGroupStatusRect: (NSPoint) point
890{
891    NSInteger row = [self rowAtPoint: point];
892    if (row < 0 || [[self itemAtRow: row] isKindOfClass: [Torrent class]])
893        return NO;
894   
895    NSString * ident = [[[self tableColumns] objectAtIndex: [self columnAtPoint: point]] identifier];
896    return [ident isEqualToString: @"UL"] || [ident isEqualToString: @"UL Image"]
897            || [ident isEqualToString: @"DL"] || [ident isEqualToString: @"DL Image"];
898}
899
900- (void) setGroupStatusColumns
901{
902    const BOOL ratio = [fDefaults boolForKey: @"DisplayGroupRowRatio"];
903   
904    [[self tableColumnWithIdentifier: @"DL"] setHidden: ratio];
905    [[self tableColumnWithIdentifier: @"DL Image"] setHidden: ratio];
906}
907
908- (void) createFileMenu: (NSMenu *) menu forFiles: (NSArray *) files
909{
910    for (FileListNode * node in files)
911    {
912        NSString * name = [node name];
913       
914        NSMenuItem * item = [[NSMenuItem alloc] initWithTitle: name action: @selector(checkFile:) keyEquivalent: @""];
915       
916        if ([node isFolder])
917        {
918            NSMenu * itemMenu = [[NSMenu alloc] initWithTitle: name];
919            [itemMenu setAutoenablesItems: NO];
920            [item setSubmenu: itemMenu];
921            [itemMenu setDelegate: self];
922            [itemMenu release];
923        }
924       
925        [item setRepresentedObject: node];
926       
927        NSImage * icon = [node icon];
928        [icon setSize: NSMakeSize(16.0, 16.0)];
929        [item setImage: icon];
930       
931        NSIndexSet * indexSet = [node indexes];
932        [item setState: [fMenuTorrent checkForFiles: indexSet]];
933        [item setEnabled: [fMenuTorrent canChangeDownloadCheckForFiles: indexSet]];
934       
935        [menu addItem: item];
936        [item release];
937    }
938}
939
940@end
Note: See TracBrowser for help on using the repository browser.