source: trunk/macosx/TorrentTableView.m

Last change on this file was 14705, checked in by mikedld, 6 years ago

#6078: Show main window and scroll to torrent on notification click

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