source: trunk/macosx/TrackerCell.m @ 12336

Last change on this file since 12336 was 12336, checked in by livings124, 11 years ago

catch invalid addresses when loading tracker favicons

  • Property svn:keywords set to Date Rev Author Id
File size: 13.8 KB
Line 
1/******************************************************************************
2 * $Id: TrackerCell.m 12336 2011-04-07 23:29:05Z livings124 $
3 *
4 * Copyright (c) 2009-2011 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 "TrackerCell.h"
26#import "NSApplicationAdditions.h"
27#import "TrackerNode.h"
28
29#import "transmission.h" // required by utils.h
30#import "utils.h" //tr_addressIsIP()
31
32#define PADDING_HORIZONAL 3.0
33#define PADDING_STATUS_HORIZONAL 3.0
34#define ICON_SIZE 16.0
35#define PADDING_BETWEEN_ICON_AND_NAME 4.0
36#define PADDING_ABOVE_ICON 1.0
37#define PADDING_ABOVE_NAME 1.0
38#define PADDING_BETWEEN_LINES 1.0
39#define PADDING_BETWEEN_LINES_ON_SAME_LINE 4.0
40#define COUNT_WIDTH 40.0
41
42@interface TrackerCell (Private)
43
44- (NSImage *) favIcon;
45- (void) loadTrackerIcon: (NSString *) baseAddress;
46
47- (NSRect) imageRectForBounds: (NSRect) bounds;
48- (NSRect) rectForNameWithString: (NSAttributedString *) string inBounds: (NSRect) bounds;
49- (NSRect) rectForCountWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect inBounds: (NSRect) bounds;
50- (NSRect) rectForCountLabelWithString: (NSAttributedString *) string withRightRect: (NSRect) rightRect inBounds: (NSRect) bounds;
51- (NSRect) rectForStatusWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect withRightRect: (NSRect) rightRect
52            inBounds: (NSRect) bounds;
53
54- (NSAttributedString *) attributedName;
55- (NSAttributedString *) attributedStatusWithString: (NSString *) statusString;
56- (NSAttributedString *) attributedCount: (NSInteger) count;
57
58@end
59
60@implementation TrackerCell
61
62//make the favicons accessible to all tracker cells
63#warning make NSCache when 10.6-only
64NSMutableDictionary * fTrackerIconCache;
65NSMutableSet * fTrackerIconLoading;
66
67+ (void) initialize
68{
69    fTrackerIconCache = [[NSMutableDictionary alloc] init];
70    fTrackerIconLoading = [[NSMutableSet alloc] init];
71}
72
73- (id) init
74{
75    if ((self = [super init]))
76    {
77        NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
78        [paragraphStyle setLineBreakMode: NSLineBreakByTruncatingTail];
79       
80        fNameAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
81                            [NSFont messageFontOfSize: 12.0], NSFontAttributeName,
82                            paragraphStyle, NSParagraphStyleAttributeName, nil];
83       
84        fStatusAttributes = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
85                                [NSFont messageFontOfSize: 9.0], NSFontAttributeName,
86                                paragraphStyle, NSParagraphStyleAttributeName, nil];
87       
88        [paragraphStyle release];
89    }
90    return self;
91}
92
93- (void) dealloc
94{
95    [fNameAttributes release];
96    [fStatusAttributes release];
97   
98    [super dealloc];
99}
100
101- (id) copyWithZone: (NSZone *) zone
102{
103    TrackerCell * copy = [super copyWithZone: zone];
104   
105    copy->fNameAttributes = [fNameAttributes retain];
106    copy->fStatusAttributes = [fStatusAttributes retain];
107   
108    return copy;
109}
110
111- (void) drawWithFrame: (NSRect) cellFrame inView: (NSView *) controlView
112{
113    //icon
114    if ([NSApp isOnSnowLeopardOrBetter])
115        [[self favIcon] drawInRect: [self imageRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver
116                        fraction: 1.0 respectFlipped: YES hints: nil];
117    else
118    {
119        NSImage * icon = [self favIcon];
120        [icon setFlipped: YES];
121        [icon drawInRect: [self imageRectForBounds: cellFrame] fromRect: NSZeroRect operation: NSCompositeSourceOver fraction: 1.0];
122    }
123
124    //set table colors
125    NSColor * nameColor, * statusColor;
126    if ([self backgroundStyle] == NSBackgroundStyleDark)
127        nameColor = statusColor = [NSColor whiteColor];
128    else
129    {
130        nameColor = [NSColor controlTextColor];
131        statusColor = [NSColor darkGrayColor];
132    }
133   
134    [fNameAttributes setObject: nameColor forKey: NSForegroundColorAttributeName];
135    [fStatusAttributes setObject: statusColor forKey: NSForegroundColorAttributeName];
136   
137    TrackerNode * node = (TrackerNode *)[self objectValue];
138   
139    //name
140    NSAttributedString * nameString = [self attributedName];
141    const NSRect nameRect = [self rectForNameWithString: nameString inBounds: cellFrame];
142    [nameString drawInRect: nameRect];
143   
144    //count strings
145    NSAttributedString * seederString = [self attributedCount: [node totalSeeders]];
146    const NSRect seederRect = [self rectForCountWithString: seederString withAboveRect: nameRect inBounds: cellFrame];
147    [seederString drawInRect: seederRect];
148   
149    NSAttributedString * leecherString = [self attributedCount: [node totalLeechers]];
150    const NSRect leecherRect = [self rectForCountWithString: leecherString withAboveRect: seederRect inBounds: cellFrame];
151    [leecherString drawInRect: leecherRect];
152   
153    NSAttributedString * downloadedString = [self attributedCount: [node totalDownloaded]];
154    const NSRect downloadedRect = [self rectForCountWithString: downloadedString withAboveRect: leecherRect inBounds: cellFrame];
155    [downloadedString drawInRect: downloadedRect];
156   
157    //count label strings
158    NSString * seederLabelBaseString = [NSLocalizedString(@"Seeders", "tracker peer stat") stringByAppendingFormat: @": "];
159    NSAttributedString * seederLabelString = [self attributedStatusWithString: seederLabelBaseString];
160    const NSRect seederLabelRect = [self rectForCountLabelWithString: seederLabelString withRightRect: seederRect
161                                        inBounds: cellFrame];
162    [seederLabelString drawInRect: seederLabelRect];
163   
164    NSString * leecherLabelBaseString = [NSLocalizedString(@"Leechers", "tracker peer stat") stringByAppendingFormat: @": "];
165    NSAttributedString * leecherLabelString = [self attributedStatusWithString: leecherLabelBaseString];
166    const NSRect leecherLabelRect = [self rectForCountLabelWithString: leecherLabelString withRightRect: leecherRect
167                                        inBounds: cellFrame];
168    [leecherLabelString drawInRect: leecherLabelRect];
169   
170    NSString * downloadedLabelBaseString = [NSLocalizedString(@"Downloaded", "tracker peer stat") stringByAppendingFormat: @": "];
171    NSAttributedString * downloadedLabelString = [self attributedStatusWithString: downloadedLabelBaseString];
172    const NSRect downloadedLabelRect = [self rectForCountLabelWithString: downloadedLabelString withRightRect: downloadedRect
173                                        inBounds: cellFrame];
174    [downloadedLabelString drawInRect: downloadedLabelRect];
175   
176    //status strings
177    NSAttributedString * lastAnnounceString = [self attributedStatusWithString: [node lastAnnounceStatusString]];
178    const NSRect lastAnnounceRect = [self rectForStatusWithString: lastAnnounceString withAboveRect: nameRect
179                                        withRightRect: seederLabelRect inBounds: cellFrame];
180    [lastAnnounceString drawInRect: lastAnnounceRect];
181   
182    NSAttributedString * nextAnnounceString = [self attributedStatusWithString: [node nextAnnounceStatusString]];
183    const NSRect nextAnnounceRect = [self rectForStatusWithString: nextAnnounceString withAboveRect: lastAnnounceRect
184                                        withRightRect: leecherLabelRect inBounds: cellFrame];
185    [nextAnnounceString drawInRect: nextAnnounceRect];
186   
187    NSAttributedString * lastScrapeString = [self attributedStatusWithString: [node lastScrapeStatusString]];
188    const NSRect lastScrapeRect = [self rectForStatusWithString: lastScrapeString withAboveRect: nextAnnounceRect
189                                    withRightRect: downloadedLabelRect inBounds: cellFrame];
190    [lastScrapeString drawInRect: lastScrapeRect];
191}
192
193@end
194
195@implementation TrackerCell (Private)
196
197- (NSImage *) favIcon
198{
199    id icon = nil;
200    NSURL * address = [NSURL URLWithString: [(TrackerNode *)[self objectValue] fullAnnounceAddress]];
201    NSString * host;
202    if ((host = [address host]))
203    {
204        //don't try to parse ip address
205        const BOOL separable = !tr_addressIsIP([host UTF8String]);
206       
207        NSArray * hostComponents = separable ? [host componentsSeparatedByString: @"."] : nil;
208       
209        //let's try getting the tracker address without using any subdomains
210        NSString * baseAddress;
211        if (separable && [hostComponents count] > 1)
212            baseAddress = [NSString stringWithFormat: @"http://%@.%@",
213                            [hostComponents objectAtIndex: [hostComponents count]-2], [hostComponents lastObject]];
214        else
215            baseAddress = [NSString stringWithFormat: @"http://%@", host];
216       
217        icon = [fTrackerIconCache objectForKey: baseAddress];
218        if (!icon && ![fTrackerIconLoading containsObject: baseAddress])
219        {
220            [fTrackerIconLoading addObject: baseAddress];
221            [NSThread detachNewThreadSelector: @selector(loadTrackerIcon:) toTarget: self withObject: baseAddress];
222        }
223    }
224       
225    return (icon && icon != [NSNull null]) ? icon : [NSImage imageNamed: @"FavIcon.png"];
226}
227
228- (void) loadTrackerIcon: (NSString *) baseAddress
229{
230    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
231   
232    //try favicon.png
233    NSURL * favIconUrl = [NSURL URLWithString: [baseAddress stringByAppendingPathComponent: @"favicon.png"]];
234   
235    NSURLRequest * request = [NSURLRequest requestWithURL: favIconUrl cachePolicy: NSURLRequestUseProtocolCachePolicy
236                                timeoutInterval: 30.0];
237    NSData * iconData = [NSURLConnection sendSynchronousRequest: request returningResponse: NULL error: NULL];
238    NSImage * icon = [[NSImage alloc] initWithData: iconData];
239   
240    //try favicon.ico
241    if (!icon)
242    {
243        favIconUrl = [NSURL URLWithString: [baseAddress stringByAppendingPathComponent: @"favicon.ico"]];
244       
245        request = [NSURLRequest requestWithURL: favIconUrl cachePolicy: NSURLRequestUseProtocolCachePolicy
246                    timeoutInterval: 30.0];
247        iconData = [NSURLConnection sendSynchronousRequest: request returningResponse: NULL error: NULL];
248        icon = [[NSImage alloc] initWithData: iconData];
249    }
250   
251    if (icon)
252    {
253        [fTrackerIconCache setObject: icon forKey: baseAddress];
254        [icon release];
255       
256        [[self controlView] setNeedsDisplay: YES];
257    }
258    else
259        [fTrackerIconCache setObject: [NSNull null] forKey: baseAddress];
260   
261    [fTrackerIconLoading removeObject: baseAddress];
262
263    [pool drain];
264}
265
266- (NSRect) imageRectForBounds: (NSRect) bounds
267{
268    return NSMakeRect(NSMinX(bounds) + PADDING_HORIZONAL, NSMinY(bounds) + PADDING_ABOVE_ICON, ICON_SIZE, ICON_SIZE);
269}
270
271- (NSRect) rectForNameWithString: (NSAttributedString *) string inBounds: (NSRect) bounds
272{
273    NSRect result;
274    result.origin.x = NSMinX(bounds) + PADDING_HORIZONAL + ICON_SIZE + PADDING_BETWEEN_ICON_AND_NAME;
275    result.origin.y = NSMinY(bounds) + PADDING_ABOVE_NAME;
276       
277    result.size.height = [string size].height;
278    result.size.width = NSMaxX(bounds) - NSMinX(result) - PADDING_HORIZONAL;
279   
280    return result;
281}
282
283- (NSRect) rectForCountWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect inBounds: (NSRect) bounds
284{
285    return NSMakeRect(NSMaxX(bounds) - PADDING_HORIZONAL - COUNT_WIDTH,
286                        NSMaxY(aboveRect) + PADDING_BETWEEN_LINES,
287                        COUNT_WIDTH, [string size].height);
288}
289
290- (NSRect) rectForCountLabelWithString: (NSAttributedString *) string withRightRect: (NSRect) rightRect inBounds: (NSRect) bounds
291{
292    NSRect result = rightRect;
293    result.size.width = [string size].width;
294    result.origin.x -= NSWidth(result);
295   
296    return result;
297}
298
299- (NSRect) rectForStatusWithString: (NSAttributedString *) string withAboveRect: (NSRect) aboveRect withRightRect: (NSRect) rightRect
300            inBounds: (NSRect) bounds
301{
302    NSRect result;
303    result.origin.x = NSMinX(bounds) + PADDING_STATUS_HORIZONAL;
304    result.origin.y = NSMaxY(aboveRect) + PADDING_BETWEEN_LINES;
305   
306    result.size.height = [string size].height;
307    result.size.width = NSMinX(rightRect) - PADDING_BETWEEN_LINES_ON_SAME_LINE - NSMinX(result);
308   
309    return result;
310}
311
312- (NSAttributedString *) attributedName
313{
314    NSString * name = [(TrackerNode *)[self objectValue] host];
315    return [[[NSAttributedString alloc] initWithString: name attributes: fNameAttributes] autorelease];
316}
317
318- (NSAttributedString *) attributedStatusWithString: (NSString *) statusString
319{
320    return [[[NSAttributedString alloc] initWithString: statusString attributes: fStatusAttributes] autorelease];
321}
322
323- (NSAttributedString *) attributedCount: (NSInteger) count
324{
325    NSString * countString = count != -1 ? [NSString stringWithFormat: @"%d", count] : NSLocalizedString(@"N/A", "tracker peer stat");
326    return [[[NSAttributedString alloc] initWithString: countString attributes: fStatusAttributes] autorelease];
327}
328
329@end
Note: See TracBrowser for help on using the repository browser.