source: trunk/macosx/TorrentTableView.m @ 13162

Last change on this file since 13162 was 13162, checked in by livings124, 10 years ago

bump Mac copyright to 2012

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