source: trunk/macosx/TorrentCell.m @ 10318

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

#3017 fix the pieces bar for magnet links

  • Property svn:keywords set to Date Rev Author Id
File size: 30.1 KB
Line 
1/******************************************************************************
2 * $Id: TorrentCell.m 10318 2010-03-07 02:46:49Z livings124 $
3 *
4 * Copyright (c) 2006-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 "TorrentCell.h"
26#import "GroupsController.h"
27#import "NSApplicationAdditions.h"
28#import "NSStringAdditions.h"
29#import "ProgressGradients.h"
30#import "Torrent.h"
31#import "TorrentTableView.h"
32
33#define BAR_HEIGHT 12.0
34
35#define IMAGE_SIZE_REG 32.0
36#define IMAGE_SIZE_MIN 16.0
37#define ERROR_IMAGE_SIZE 20.0
38
39#define NORMAL_BUTTON_WIDTH 14.0
40#define ACTION_BUTTON_WIDTH 16.0
41
42#define PRIORITY_ICON_WIDTH 14.0
43#define PRIORITY_ICON_HEIGHT 14.0
44
45//ends up being larger than font height
46#define HEIGHT_TITLE 16.0
47#define HEIGHT_STATUS 12.0
48
49#define PADDING_HORIZONTAL 3.0
50#define PADDING_BETWEEN_IMAGE_AND_TITLE 5.0
51#define PADDING_BETWEEN_IMAGE_AND_BAR 7.0
52#define PADDING_BETWEEN_TITLE_AND_PRIORITY 4.0
53#define PADDING_ABOVE_TITLE 4.0
54#define PADDING_ABOVE_MIN_STATUS 4.0
55#define PADDING_BETWEEN_TITLE_AND_MIN_STATUS 2.0
56#define PADDING_BETWEEN_TITLE_AND_PROGRESS 1.0
57#define PADDING_BETWEEN_PROGRESS_AND_BAR 2.0
58#define PADDING_BETWEEN_TITLE_AND_BAR_MIN 3.0
59#define PADDING_BETWEEN_BAR_AND_STATUS 2.0
60
61#define PIECES_TOTAL_PERCENT 0.6
62
63#define MAX_PIECES (18*18)
64
65@interface TorrentCell (Private)
66
67- (void) drawBar: (NSRect) barRect;
68- (void) drawRegularBar: (NSRect) barRect;
69- (void) drawPiecesBar: (NSRect) barRect;
70
71- (NSRect) rectForMinimalStatusWithString: (NSAttributedString *) string inBounds: (NSRect) bounds;
72- (NSRect) rectForTitleWithString: (NSAttributedString *) string basedOnMinimalStatusRect: (NSRect) statusRect inBounds: (NSRect) bounds;
73- (NSRect) rectForProgressWithStringInBounds: (NSRect) bounds;
74- (NSRect) rectForStatusWithStringInBounds: (NSRect) bounds;
75- (NSRect) barRectForBounds: (NSRect) bounds;
76
77- (NSRect) controlButtonRectForBounds: (NSRect) bounds;
78- (NSRect) revealButtonRectForBounds: (NSRect) bounds;
79- (NSRect) actionButtonRectForBounds: (NSRect) bounds;
80
81- (NSAttributedString *) attributedTitle;
82- (NSAttributedString *) attributedStatusString: (NSString *) string;
83
84- (NSString *) buttonString;
85- (NSString *) statusString;
86- (NSString *) minimalStatusString;
87
88- (void) drawImage: (NSImage *) image inRect: (NSRect) rect; //use until 10.5 dropped
89
90@end
91
92@implementation TorrentCell
93
94//only called once and the main table is always needed, so don't worry about releasing
95- (id) init
96{
97    if ((self = [super init]))
98        {
99        fDefaults = [NSUserDefaults standardUserDefaults];
100       
101        NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
102        [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingTail];
103       
104        fTitleAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3];
105        [fTitleAttributes setObject: [NSFont messageFontOfSize: 12.0] forKey: NSFontAttributeName];
106        [fTitleAttributes setObject: paragraphStyle forKey: NSParagraphStyleAttributeName];
107       
108        fStatusAttributes = [[NSMutableDictionary alloc] initWithCapacity: 3];
109        [fStatusAttributes setObject: [NSFont messageFontOfSize: 9.0] forKey: NSFontAttributeName];
110        [fStatusAttributes setObject: paragraphStyle forKey: NSParagraphStyleAttributeName];
111       
112        [paragraphStyle release];
113       
114        fBluePieceColor = [[NSColor colorWithCalibratedRed: 0.0 green: 0.4 blue: 0.8 alpha: 1.0] retain];
115        fBarBorderColor = [[NSColor colorWithCalibratedWhite: 0.0 alpha: 0.2] retain];
116    }
117        return self;
118}
119
120- (NSRect) iconRectForBounds: (NSRect) bounds
121{
122    const CGFloat imageSize = [fDefaults boolForKey: @"SmallView"] ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG;
123   
124    return NSMakeRect(NSMinX(bounds) + PADDING_HORIZONTAL, floor(NSMidY(bounds) - imageSize * 0.5),
125                        imageSize, imageSize);
126}
127
128- (NSUInteger) hitTestForEvent: (NSEvent *) event inRect: (NSRect) cellFrame ofView: (NSView *) controlView
129{
130    NSPoint point = [controlView convertPoint: [event locationInWindow] fromView: nil];
131   
132    if (NSMouseInRect(point, [self controlButtonRectForBounds: cellFrame], [controlView isFlipped])
133        || NSMouseInRect(point, [self revealButtonRectForBounds: cellFrame], [controlView isFlipped]))
134        return NSCellHitContentArea | NSCellHitTrackableArea;
135   
136    return NSCellHitContentArea;
137}
138
139+ (BOOL) prefersTrackingUntilMouseUp
140{
141    return YES;
142}
143
144- (BOOL) trackMouse: (NSEvent *) event inRect: (NSRect) cellFrame ofView: (NSView *) controlView untilMouseUp: (BOOL) flag
145{
146    fTracking = YES;
147   
148    [self setControlView: controlView];
149   
150    NSPoint point = [controlView convertPoint: [event locationInWindow] fromView: nil];
151   
152    const NSRect controlRect= [self controlButtonRectForBounds: cellFrame];
153    const BOOL checkControl = NSMouseInRect(point, controlRect, [controlView isFlipped]);
154   
155    const NSRect revealRect = [self revealButtonRectForBounds: cellFrame];
156    const BOOL checkReveal = NSMouseInRect(point, revealRect, [controlView isFlipped]);
157   
158    [(TorrentTableView *)controlView removeButtonTrackingAreas];
159   
160    while ([event type] != NSLeftMouseUp)
161    {
162        point = [controlView convertPoint: [event locationInWindow] fromView: nil];
163       
164        if (checkControl)
165        {
166            const BOOL inControlButton = NSMouseInRect(point, controlRect, [controlView isFlipped]);
167            if (fMouseDownControlButton != inControlButton)
168            {
169                fMouseDownControlButton = inControlButton;
170                [controlView setNeedsDisplayInRect: cellFrame];
171            }
172        }
173        else if (checkReveal)
174        {
175            const BOOL inRevealButton = NSMouseInRect(point, revealRect, [controlView isFlipped]);
176            if (fMouseDownRevealButton != inRevealButton)
177            {
178                fMouseDownRevealButton = inRevealButton;
179                [controlView setNeedsDisplayInRect: cellFrame];
180            }
181        }
182        else;
183       
184        //send events to where necessary
185        if ([event type] == NSMouseEntered || [event type] == NSMouseExited)
186            [NSApp sendEvent: event];
187        event = [[controlView window] nextEventMatchingMask:
188                    (NSLeftMouseUpMask | NSLeftMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask)];
189    }
190   
191    fTracking = NO;
192
193    if (fMouseDownControlButton)
194    {
195        fMouseDownControlButton = NO;
196       
197        [(TorrentTableView *)controlView toggleControlForTorrent: [self representedObject]];
198    }
199    else if (fMouseDownRevealButton)
200    {
201        fMouseDownRevealButton = NO;
202        [controlView setNeedsDisplayInRect: cellFrame];
203       
204        if ([NSApp isOnSnowLeopardOrBetter])
205        {
206            NSString * location = [[self representedObject] dataLocation];
207            if (location)
208            {
209                NSURL * file = [NSURL fileURLWithPath: location];
210                [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs: [NSArray arrayWithObject: file]];
211            }
212        }
213        else
214        {
215            NSString * location = [[self representedObject] dataLocation];
216            if (location)
217                [[NSWorkspace sharedWorkspace] selectFile: location inFileViewerRootedAtPath: nil];
218        }
219    }
220    else;
221   
222    [controlView updateTrackingAreas];
223   
224    return YES;
225}
226
227- (void) addTrackingAreasForView: (NSView *) controlView inRect: (NSRect) cellFrame withUserInfo: (NSDictionary *) userInfo
228            mouseLocation: (NSPoint) mouseLocation
229{
230    NSTrackingAreaOptions options = NSTrackingEnabledDuringMouseDrag | NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways;
231   
232    //control button
233    NSRect controlButtonRect = [self controlButtonRectForBounds: cellFrame];
234    NSTrackingAreaOptions controlOptions = options;
235    if (NSMouseInRect(mouseLocation, controlButtonRect, [controlView isFlipped]))
236    {
237        controlOptions |= NSTrackingAssumeInside;
238        [(TorrentTableView *)controlView setControlButtonHover: [[userInfo objectForKey: @"Row"] integerValue]];
239    }
240   
241    NSMutableDictionary * controlInfo = [userInfo mutableCopy];
242    [controlInfo setObject: @"Control" forKey: @"Type"];
243    NSTrackingArea * area = [[NSTrackingArea alloc] initWithRect: controlButtonRect options: controlOptions owner: controlView
244                                userInfo: controlInfo];
245    [controlView addTrackingArea: area];
246    [controlInfo release];
247    [area release];
248   
249    //reveal button
250    NSRect revealButtonRect = [self revealButtonRectForBounds: cellFrame];
251    NSTrackingAreaOptions revealOptions = options;
252    if (NSMouseInRect(mouseLocation, revealButtonRect, [controlView isFlipped]))
253    {
254        revealOptions |= NSTrackingAssumeInside;
255        [(TorrentTableView *)controlView setRevealButtonHover: [[userInfo objectForKey: @"Row"] integerValue]];
256    }
257   
258    NSMutableDictionary * revealInfo = [userInfo mutableCopy];
259    [revealInfo setObject: @"Reveal" forKey: @"Type"];
260    area = [[NSTrackingArea alloc] initWithRect: revealButtonRect options: revealOptions owner: controlView userInfo: revealInfo];
261    [controlView addTrackingArea: area];
262    [revealInfo release];
263    [area release];
264   
265    //action button
266    NSRect actionButtonRect = [self iconRectForBounds: cellFrame]; //use the whole icon
267    NSTrackingAreaOptions actionOptions = options;
268    if (NSMouseInRect(mouseLocation, actionButtonRect, [controlView isFlipped]))
269    {
270        actionOptions |= NSTrackingAssumeInside;
271        [(TorrentTableView *)controlView setActionButtonHover: [[userInfo objectForKey: @"Row"] integerValue]];
272    }
273   
274    NSMutableDictionary * actionInfo = [userInfo mutableCopy];
275    [actionInfo setObject: @"Action" forKey: @"Type"];
276    area = [[NSTrackingArea alloc] initWithRect: actionButtonRect options: actionOptions owner: controlView userInfo: actionInfo];
277    [controlView addTrackingArea: area];
278    [actionInfo release];
279    [area release];
280}
281
282- (void) setControlHover: (BOOL) hover
283{
284    fHoverControl = hover;
285}
286
287- (void) setRevealHover: (BOOL) hover
288{
289    fHoverReveal = hover;
290}
291
292- (void) setActionHover: (BOOL) hover
293{
294    fHoverAction = hover;
295}
296
297- (void) setActionPushed: (BOOL) pushed
298{
299    fMouseDownActionButton = pushed;
300}
301
302- (void) drawInteriorWithFrame: (NSRect) cellFrame inView: (NSView *) controlView
303{
304    Torrent * torrent = [self representedObject];
305   
306    const BOOL minimal = [fDefaults boolForKey: @"SmallView"];
307   
308    //group coloring
309    const NSRect iconRect = [self iconRectForBounds: cellFrame];
310   
311    const NSInteger groupValue = [torrent groupValue];
312    if (groupValue != -1)
313    {
314        NSRect groupRect = NSInsetRect(iconRect, -1.0, -2.0);
315        if (!minimal)
316        {
317            groupRect.size.height -= 1.0;
318            groupRect.origin.y -= 1.0;
319        }
320        const CGFloat radius = minimal ? 3.0 : 6.0;
321       
322        NSColor * groupColor = [[GroupsController groups] colorForIndex: groupValue],
323                * darkGroupColor = [groupColor blendedColorWithFraction: 0.2 ofColor: [NSColor whiteColor]];
324       
325        //border
326        NSBezierPath * bp = [NSBezierPath bezierPathWithRoundedRect: groupRect xRadius: radius yRadius: radius];
327        [darkGroupColor set];
328        [bp setLineWidth: 2.0];
329        [bp stroke];
330       
331        //inside
332        bp = [NSBezierPath bezierPathWithRoundedRect: groupRect xRadius: radius yRadius: radius];
333        NSGradient * gradient = [[NSGradient alloc] initWithStartingColor: [groupColor blendedColorWithFraction: 0.7
334                                    ofColor: [NSColor whiteColor]] endingColor: darkGroupColor];
335        [gradient drawInBezierPath: bp angle: 90.0];
336        [gradient release];
337    }
338   
339    const BOOL error = [torrent isAnyErrorOrWarning];
340   
341    //icon
342    if (!minimal || !(!fTracking && fHoverAction)) //don't show in minimal mode when hovered over
343    {
344        NSImage * icon = (minimal && error) ? [NSImage imageNamed: [NSApp isOnSnowLeopardOrBetter] ? NSImageNameCaution : @"Error.png"]
345                                            : [torrent icon];
346        [self drawImage: icon inRect: iconRect];
347    }
348   
349    //error badge
350    if (error && !minimal)
351    {
352        NSRect errorRect = NSMakeRect(NSMaxX(iconRect) - ERROR_IMAGE_SIZE, NSMaxY(iconRect) - ERROR_IMAGE_SIZE,
353                                        ERROR_IMAGE_SIZE, ERROR_IMAGE_SIZE);
354        [self drawImage: [NSImage imageNamed: [NSApp isOnSnowLeopardOrBetter] ? NSImageNameCaution : @"Error.png"] inRect: errorRect];
355    }
356   
357    //text color
358    NSColor * titleColor, * statusColor;
359    if ([self backgroundStyle] == NSBackgroundStyleDark)
360        titleColor = statusColor = [NSColor whiteColor];
361    else
362    {
363        titleColor = [NSColor controlTextColor];
364        statusColor = [NSColor darkGrayColor];
365    }
366   
367    [fTitleAttributes setObject: titleColor forKey: NSForegroundColorAttributeName];
368    [fStatusAttributes setObject: statusColor forKey: NSForegroundColorAttributeName];
369   
370    //minimal status
371    NSRect minimalStatusRect;
372    if (minimal)
373    {
374        NSAttributedString * minimalString = [self attributedStatusString: [self minimalStatusString]];
375        minimalStatusRect = [self rectForMinimalStatusWithString: minimalString inBounds: cellFrame];
376       
377        [minimalString drawInRect: minimalStatusRect];
378    }
379   
380    //title
381    NSAttributedString * titleString = [self attributedTitle];
382    NSRect titleRect = [self rectForTitleWithString: titleString basedOnMinimalStatusRect: minimalStatusRect inBounds: cellFrame];
383    [titleString drawInRect: titleRect];
384   
385    //priority icon
386    if ([torrent priority] != TR_PRI_NORMAL)
387    {
388        NSImage * priorityImage = [torrent priority] == TR_PRI_HIGH ? [NSImage imageNamed: @"PriorityHigh.png"]
389                                                                    : [NSImage imageNamed: @"PriorityLow.png"];
390        //take line out completely when 10.6-only
391        priorityImage = [NSApp isOnSnowLeopardOrBetter] ? [priorityImage retain] : [priorityImage copy];
392       
393        NSRect priorityRect = NSMakeRect(NSMaxX(titleRect) + PADDING_BETWEEN_TITLE_AND_PRIORITY,
394                                        NSMidY(titleRect) - PRIORITY_ICON_HEIGHT  * 0.5,
395                                        PRIORITY_ICON_WIDTH, PRIORITY_ICON_HEIGHT);
396       
397        [self drawImage: priorityImage inRect: priorityRect];
398        [priorityImage release];
399    }
400   
401    //progress
402    if (!minimal)
403    {
404        NSAttributedString * progressString = [self attributedStatusString: [torrent progressString]];
405        NSRect progressRect = [self rectForProgressWithStringInBounds: cellFrame];
406       
407        [progressString drawInRect: progressRect];
408    }
409   
410    //bar
411    [self drawBar: [self barRectForBounds: cellFrame]];
412   
413    //control button
414    NSString * controlImageSuffix;
415    if (fMouseDownControlButton)
416        controlImageSuffix = @"On.png";
417    else if (!fTracking && fHoverControl)
418        controlImageSuffix = @"Hover.png";
419    else
420        controlImageSuffix = @"Off.png";
421   
422    NSImage * controlImage;
423    if ([torrent isActive])
424        controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]];
425    else
426    {
427        if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
428            controlImage = [NSImage imageNamed: [@"ResumeNoWait" stringByAppendingString: controlImageSuffix]];
429        else if ([torrent waitingToStart])
430            controlImage = [NSImage imageNamed: [@"Pause" stringByAppendingString: controlImageSuffix]];
431        else
432            controlImage = [NSImage imageNamed: [@"Resume" stringByAppendingString: controlImageSuffix]];
433    }
434   
435    [self drawImage: controlImage inRect: [self controlButtonRectForBounds: cellFrame]];
436   
437    //reveal button
438    NSString * revealImageString;
439    if (fMouseDownRevealButton)
440        revealImageString = @"RevealOn.png";
441    else if (!fTracking && fHoverReveal)
442        revealImageString = @"RevealHover.png";
443    else
444        revealImageString = @"RevealOff.png";
445   
446    NSImage * revealImage = [NSImage imageNamed: revealImageString];
447    [self drawImage: revealImage inRect: [self revealButtonRectForBounds: cellFrame]];
448   
449    //action button
450    NSString * actionImageString;
451    if (fMouseDownActionButton)
452        actionImageString = @"ActionOn.png";
453    else if (!fTracking && fHoverAction)
454        actionImageString = @"ActionHover.png";
455    else
456        actionImageString = nil;
457   
458    if (actionImageString)
459    {
460        NSImage * actionImage = [NSImage imageNamed: actionImageString];
461        [self drawImage: actionImage inRect: [self actionButtonRectForBounds: cellFrame]];
462    }
463   
464    //status
465    if (!minimal)
466    {
467        NSAttributedString * statusString = [self attributedStatusString: [self statusString]];
468        [statusString drawInRect: [self rectForStatusWithStringInBounds: cellFrame]];
469    }
470}
471
472@end
473
474@implementation TorrentCell (Private)
475
476- (void) drawBar: (NSRect) barRect
477{
478    const CGFloat piecesBarPercent = [(TorrentTableView *)[self controlView] piecesBarPercent];
479    if (piecesBarPercent > 0.0)
480    {
481        NSRect piecesBarRect, regularBarRect;
482        NSDivideRect(barRect, &piecesBarRect, &regularBarRect, floor(NSHeight(barRect) * PIECES_TOTAL_PERCENT * piecesBarPercent),
483                    NSMaxYEdge);
484       
485        [self drawRegularBar: regularBarRect];
486        [self drawPiecesBar: piecesBarRect];
487    }
488    else
489    {
490        [[self representedObject] setPreviousFinishedPieces: nil];
491       
492        [self drawRegularBar: barRect];
493    }
494   
495    [fBarBorderColor set];
496    [NSBezierPath strokeRect: NSInsetRect(barRect, 0.5, 0.5)];
497}
498
499- (void) drawRegularBar: (NSRect) barRect
500{
501    Torrent * torrent = [self representedObject];
502   
503    NSRect haveRect, missingRect;
504    NSDivideRect(barRect, &haveRect, &missingRect, round([torrent progress] * NSWidth(barRect)), NSMinXEdge);
505   
506    if (!NSIsEmptyRect(haveRect))
507    {
508        if ([torrent isActive])
509        {
510            if ([torrent isChecking])
511                [[ProgressGradients progressYellowGradient] drawInRect: haveRect angle: 90];
512            else if ([torrent isSeeding])
513            {
514                NSRect ratioHaveRect, ratioRemainingRect;
515                NSDivideRect(haveRect, &ratioHaveRect, &ratioRemainingRect, round([torrent progressStopRatio] * NSWidth(haveRect)),
516                            NSMinXEdge);
517               
518                [[ProgressGradients progressGreenGradient] drawInRect: ratioHaveRect angle: 90];
519                [[ProgressGradients progressLightGreenGradient] drawInRect: ratioRemainingRect angle: 90];
520            }
521            else
522                [[ProgressGradients progressBlueGradient] drawInRect: haveRect angle: 90];
523        }
524        else
525        {
526            if ([torrent waitingToStart])
527            {
528                if ([torrent allDownloaded])
529                    [[ProgressGradients progressDarkGreenGradient] drawInRect: haveRect angle: 90];
530                else
531                    [[ProgressGradients progressDarkBlueGradient] drawInRect: haveRect angle: 90];
532            }
533            else
534                [[ProgressGradients progressGrayGradient] drawInRect: haveRect angle: 90];
535        }
536    }
537   
538    if (![torrent allDownloaded])
539    {
540        const CGFloat widthRemaining = round(NSWidth(barRect) * [torrent progressLeft]);
541       
542        NSRect wantedRect;
543        NSDivideRect(missingRect, &wantedRect, &missingRect, widthRemaining, NSMinXEdge);
544       
545        //not-available section
546        if ([torrent isActive] && ![torrent isChecking] && [torrent availableDesired] < 1.0
547            && [fDefaults boolForKey: @"DisplayProgressBarAvailable"])
548        {
549            NSRect unavailableRect;
550            NSDivideRect(wantedRect, &wantedRect, &unavailableRect, round(NSWidth(wantedRect) * [torrent availableDesired]),
551                        NSMinXEdge);
552           
553            [[ProgressGradients progressRedGradient] drawInRect: unavailableRect angle: 90];
554        }
555       
556        //remaining section
557        [[ProgressGradients progressWhiteGradient] drawInRect: wantedRect angle: 90];
558    }
559   
560    //unwanted section
561    if (!NSIsEmptyRect(missingRect))
562    {
563        if (![torrent isMagnet])
564            [[ProgressGradients progressLightGrayGradient] drawInRect: missingRect angle: 90];
565        else
566            [[ProgressGradients progressRedGradient] drawInRect: missingRect angle: 90];
567    }
568}
569
570- (void) drawPiecesBar: (NSRect) barRect
571{
572    Torrent * torrent = [self representedObject];
573   
574    //fill an all-white bar for magnet links
575    if ([torrent isMagnet])
576    {
577        [[NSColor whiteColor] set];
578        NSRectFill(barRect);
579        return;
580    }
581   
582    NSInteger pieceCount = MIN([torrent pieceCount], MAX_PIECES);
583    float * piecesPercent = malloc(pieceCount * sizeof(float));
584    [torrent getAmountFinished: piecesPercent size: pieceCount];
585   
586    NSBitmapImageRep * bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
587                                    pixelsWide: pieceCount pixelsHigh: 1 bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
588                                    isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
589   
590    NSIndexSet * previousFinishedIndexes = [torrent previousFinishedPieces];
591    NSMutableIndexSet * finishedIndexes = [NSMutableIndexSet indexSet];
592   
593    for (NSInteger i = 0; i < pieceCount; i++)
594    {
595        NSColor * pieceColor;
596        if (piecesPercent[i] == 1.0f)
597        {
598            if (previousFinishedIndexes && ![previousFinishedIndexes containsIndex: i])
599                pieceColor = [NSColor orangeColor];
600            else
601                pieceColor = fBluePieceColor;
602            [finishedIndexes addIndex: i];
603        }
604        else
605            pieceColor = [[NSColor whiteColor] blendedColorWithFraction: piecesPercent[i] ofColor: fBluePieceColor];
606       
607        //it's faster to just set color instead of checking previous color
608        [bitmap setColor: pieceColor atX: i y: 0];
609    }
610   
611    free(piecesPercent);
612   
613    [torrent setPreviousFinishedPieces: [finishedIndexes count] > 0 ? finishedIndexes : nil]; //don't bother saving if none are complete
614   
615    //actually draw image
616    [bitmap drawInRect: barRect];
617    [bitmap release];
618}
619
620- (NSRect) rectForMinimalStatusWithString: (NSAttributedString *) string inBounds: (NSRect) bounds
621{
622    NSRect result;
623    result.size = [string size];
624   
625    result.origin.x = NSMaxX(bounds) - (NSWidth(result) + PADDING_HORIZONTAL);
626    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_MIN_STATUS;
627   
628    return result;
629}
630
631- (NSRect) rectForTitleWithString: (NSAttributedString *) string basedOnMinimalStatusRect: (NSRect) statusRect inBounds: (NSRect) bounds
632{
633    const BOOL minimal = [fDefaults boolForKey: @"SmallView"];
634   
635    NSRect result;
636    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE;
637    result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL
638                        + (minimal ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG) + PADDING_BETWEEN_IMAGE_AND_TITLE;
639   
640    result.size.height = HEIGHT_TITLE;
641    result.size.width = NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL;
642    if (minimal)
643        result.size.width -= PADDING_BETWEEN_TITLE_AND_MIN_STATUS + NSWidth(statusRect);
644    if ([[self representedObject] priority] != TR_PRI_NORMAL)
645    {
646        result.size.width -= PRIORITY_ICON_WIDTH + PADDING_BETWEEN_TITLE_AND_PRIORITY;
647        result.size.width = MIN(NSWidth(result), [string size].width); //only need to force it smaller for the priority icon
648    }
649   
650    return result;
651}
652
653- (NSRect) rectForProgressWithStringInBounds: (NSRect) bounds
654{
655    NSRect result;
656    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS;
657    result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + IMAGE_SIZE_REG + PADDING_BETWEEN_IMAGE_AND_TITLE;
658   
659    result.size.height = HEIGHT_STATUS;
660    result.size.width = NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL;
661   
662    return result;
663}
664
665- (NSRect) rectForStatusWithStringInBounds: (NSRect) bounds
666{
667    NSRect result;
668    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE + PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS
669                        + PADDING_BETWEEN_PROGRESS_AND_BAR + BAR_HEIGHT + PADDING_BETWEEN_BAR_AND_STATUS;
670    result.origin.x = NSMinX(bounds) + PADDING_HORIZONTAL + IMAGE_SIZE_REG + PADDING_BETWEEN_IMAGE_AND_TITLE;
671   
672    result.size.height = HEIGHT_STATUS;
673    result.size.width = NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONTAL;
674   
675    return result;
676}
677
678- (NSRect) barRectForBounds: (NSRect) bounds
679{
680    const BOOL minimal = [fDefaults boolForKey: @"SmallView"];
681   
682    NSRect result;
683    result.size.height = BAR_HEIGHT;
684    result.origin.x = NSMinX(bounds) + (minimal ? IMAGE_SIZE_MIN : IMAGE_SIZE_REG) + PADDING_BETWEEN_IMAGE_AND_BAR;
685   
686    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE;
687    if (minimal)
688        result.origin.y += PADDING_BETWEEN_TITLE_AND_BAR_MIN;
689    else
690        result.origin.y += PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR;
691   
692    result.size.width = floor(NSMaxX(bounds) - result.origin.x - PADDING_HORIZONTAL - 2.0 * (PADDING_HORIZONTAL + NORMAL_BUTTON_WIDTH));
693   
694    return result;
695}
696
697- (NSRect) controlButtonRectForBounds: (NSRect) bounds
698{
699    NSRect result;
700    result.size.height = NORMAL_BUTTON_WIDTH;
701    result.size.width = NORMAL_BUTTON_WIDTH;
702    result.origin.x = NSMaxX(bounds) - 2.0 * (PADDING_HORIZONTAL + NORMAL_BUTTON_WIDTH);
703   
704    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5;
705    if ([fDefaults boolForKey: @"SmallView"])
706        result.origin.y += PADDING_BETWEEN_TITLE_AND_BAR_MIN;
707    else
708        result.origin.y += PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR;
709   
710    return result;
711}
712
713- (NSRect) revealButtonRectForBounds: (NSRect) bounds
714{
715    NSRect result;
716    result.size.height = NORMAL_BUTTON_WIDTH;
717    result.size.width = NORMAL_BUTTON_WIDTH;
718    result.origin.x = NSMaxX(bounds) - (PADDING_HORIZONTAL + NORMAL_BUTTON_WIDTH);
719   
720    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_TITLE + HEIGHT_TITLE - (NORMAL_BUTTON_WIDTH - BAR_HEIGHT) * 0.5;
721    if ([fDefaults boolForKey: @"SmallView"])
722        result.origin.y += PADDING_BETWEEN_TITLE_AND_BAR_MIN;
723    else
724        result.origin.y += PADDING_BETWEEN_TITLE_AND_PROGRESS + HEIGHT_STATUS + PADDING_BETWEEN_PROGRESS_AND_BAR;
725   
726    return result;
727}
728
729- (NSRect) actionButtonRectForBounds: (NSRect) bounds
730{
731    const NSRect iconRect = [self iconRectForBounds: bounds];
732   
733    //in minimal view the rect will be the icon rect, but avoid the extra defaults lookup with some cheap math
734    return NSMakeRect(NSMidX(iconRect) - ACTION_BUTTON_WIDTH * 0.5, NSMidY(iconRect) - ACTION_BUTTON_WIDTH * 0.5,
735                        ACTION_BUTTON_WIDTH, ACTION_BUTTON_WIDTH);
736}
737
738- (NSAttributedString *) attributedTitle
739{
740    NSString * title = [[self representedObject] name];
741    return [[[NSAttributedString alloc] initWithString: title attributes: fTitleAttributes] autorelease];
742}
743
744- (NSAttributedString *) attributedStatusString: (NSString *) string
745{
746    return [[[NSAttributedString alloc] initWithString: string attributes: fStatusAttributes] autorelease];
747}
748
749- (NSString *) buttonString
750{
751    if (fMouseDownRevealButton || (!fTracking && fHoverReveal))
752        return NSLocalizedString(@"Show the data file in Finder", "Torrent cell -> button info");
753    else if (fMouseDownControlButton || (!fTracking && fHoverControl))
754    {
755        Torrent * torrent = [self representedObject];
756        if ([torrent isActive])
757            return NSLocalizedString(@"Pause the transfer", "Torrent Table -> tooltip");
758        else
759        {
760            if ([[NSApp currentEvent] modifierFlags] & NSAlternateKeyMask)
761                return NSLocalizedString(@"Resume the transfer right away", "Torrent cell -> button info");
762            else if ([torrent waitingToStart])
763                return NSLocalizedString(@"Stop waiting to start", "Torrent cell -> button info");
764            else
765                return NSLocalizedString(@"Resume the transfer", "Torrent cell -> button info");
766        }
767    }
768    else if (!fTracking && fHoverAction)
769        return NSLocalizedString(@"Change transfer settings", "Torrent Table -> tooltip");
770    else
771        return nil;
772}
773
774- (NSString *) statusString
775{
776    NSString * buttonString;
777    if ((buttonString = [self buttonString]))
778        return buttonString;
779    else
780        return [[self representedObject] statusString];
781}
782
783- (NSString *) minimalStatusString
784{
785    NSString * buttonString;
786    if ((buttonString = [self buttonString]))
787        return buttonString;
788    else
789    {
790        Torrent * torrent = [self representedObject];
791        return [fDefaults boolForKey: @"DisplaySmallStatusRegular"] ? [torrent shortStatusString] : [torrent remainingTimeString];
792    }
793}
794
795- (void) drawImage: (NSImage *) image inRect: (NSRect) rect
796{
797    if ([NSApp isOnSnowLeopardOrBetter])
798        [image drawInRect: rect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0 respectFlipped: YES hints: nil];
799    else
800    {
801        [image setFlipped: YES];
802        [image drawInRect: rect fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0];
803    }
804}
805
806@end
Note: See TracBrowser for help on using the repository browser.