source: trunk/macosx/Torrent.m @ 1285

Last change on this file since 1285 was 1285, checked in by livings124, 16 years ago

remove unneeded function

  • Property svn:keywords set to Date Rev Author Id
File size: 38.3 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 1285 2006-12-26 22:33:02Z livings124 $
3 *
4 * Copyright (c) 2006 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 "Torrent.h"
26#import "StringAdditions.h"
27
28#define BAR_HEIGHT 12.0
29
30#define MAX_PIECES 324
31#define BLANK_PIECE -99
32
33@interface Torrent (Private)
34
35- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
36        publicTorrent: (NSNumber *) publicTorrent
37        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
38        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
39        orderValue: (NSNumber *) orderValue;
40
41- (NSImage *) advancedBar;
42
43- (void) trashFile: (NSString *) path;
44
45@end
46
47@implementation Torrent
48
49// Used to optimize drawing. They contain packed RGBA pixels for every color needed.
50#define BE OSSwapBigToHostConstInt32
51
52static uint32_t kRed   = BE(0xFF6450FF), //255, 100, 80
53                kBlue = BE(0x50A0FFFF), //80, 160, 255
54                kBlue2 = BE(0x1E46B4FF), //30, 70, 180
55                kGray  = BE(0x969696FF), //150, 150, 150
56                kGreen1 = BE(0x99FFCCFF), //153, 255, 204
57                kGreen2 = BE(0x66FF99FF), //102, 255, 153
58                kGreen3 = BE(0x00FF66FF), //0, 255, 102
59                kWhite = BE(0xFFFFFFFF); //255, 255, 255
60
61- (id) initWithPath: (NSString *) path forceDeleteTorrent: (BOOL) delete lib: (tr_handle_t *) lib
62{
63    self = [self initWithHash: nil path: path lib: lib
64            publicTorrent: delete ? [NSNumber numberWithBool: NO] : nil
65            date: nil stopRatioSetting: nil ratioLimit: nil waitToStart: nil orderValue: nil];
66   
67    if (self)
68    {
69        fUseIncompleteFolder = [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
70        fIncompleteFolder = [[fDefaults stringForKey: @"IncompleteDownloadFolder"] copy];
71       
72        if (!fPublicTorrent)
73            [self trashFile: path];
74    }
75    return self;
76}
77
78- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle_t *) lib
79{
80    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
81                path: [history objectForKey: @"TorrentPath"] lib: lib
82                publicTorrent: [history objectForKey: @"PublicCopy"]
83                date: [history objectForKey: @"Date"]
84                stopRatioSetting: [history objectForKey: @"StopRatioSetting"]
85                ratioLimit: [history objectForKey: @"RatioLimit"]
86                waitToStart: [history objectForKey: @"WaitToStart"]
87                orderValue: [history objectForKey: @"OrderValue"]];
88   
89    if (self)
90    {
91        //download folders
92        NSString * downloadFolder;
93        if (!(downloadFolder = [history objectForKey: @"DownloadFolder"]))
94            downloadFolder = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
95       
96        NSNumber * useIncompleteFolder;
97        if ((useIncompleteFolder = [history objectForKey: @"UseIncompleteFolder"]))
98        {
99            if ((fUseIncompleteFolder = [useIncompleteFolder boolValue]))
100            {
101                NSString * incompleteFolder;
102                if (incompleteFolder = [history objectForKey: @"IncompleteFolder"])
103                    fIncompleteFolder = [incompleteFolder copy];
104                else
105                    fIncompleteFolder = [[[fDefaults stringForKey: @"IncompleteDownloadFolder"]
106                                            stringByExpandingTildeInPath] copy];
107            }
108        }
109        else
110            fUseIncompleteFolder = NO;
111       
112        [self setDownloadFolder: downloadFolder];
113
114        NSString * paused;
115        if (!(paused = [history objectForKey: @"Paused"]) || [paused isEqualToString: @"NO"])
116        {
117            fStat = tr_torrentStat(fHandle);
118            [self startTransfer];
119        }
120    }
121    return self;
122}
123
124- (NSDictionary *) history
125{
126    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
127                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
128                    [self hashString], @"TorrentHash",
129                    fDownloadFolder, @"DownloadFolder",
130                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
131                    [self isActive] ? @"NO" : @"YES", @"Paused",
132                    [self date], @"Date",
133                    [NSNumber numberWithInt: fStopRatioSetting], @"StopRatioSetting",
134                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
135                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
136                    [self orderValue], @"OrderValue", nil];
137   
138    if (fUseIncompleteFolder)
139        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
140
141    if (fPublicTorrent)
142        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
143   
144    return history;
145}
146
147- (void) dealloc
148{
149    if (fHandle)
150    {
151        tr_torrentClose(fLib, fHandle);
152       
153        if (fDownloadFolder)
154            [fDownloadFolder release];
155        if (fIncompleteFolder)
156            [fIncompleteFolder release];
157       
158        if (fPublicTorrentLocation)
159            [fPublicTorrentLocation release];
160       
161        tr_torrentRemoveSaved(fHandle);
162       
163        [fDate release];
164       
165        if (fAnnounceDate)
166            [fAnnounceDate release];
167       
168        [fIcon release];
169        [fIconFlipped release];
170        [fIconSmall release];
171       
172        [fProgressString release];
173        [fStatusString release];
174        [fShortStatusString release];
175        [fRemainingTimeString release];
176       
177        [fBitmap release];
178        free(fPieces);
179    }
180    [super dealloc];
181}
182
183- (void) setDownloadFolder: (NSString *) path
184{
185    if (path)
186        fDownloadFolder = [path copy];
187   
188    if (!fUseIncompleteFolder || [[NSFileManager defaultManager] fileExistsAtPath:
189                                    [path stringByAppendingPathComponent: [self name]]])
190        tr_torrentSetFolder(fHandle, [path UTF8String]);
191    else
192        tr_torrentSetFolder(fHandle, [fIncompleteFolder UTF8String]);
193}
194
195- (NSString *) downloadFolder
196{
197    return [NSString stringWithUTF8String: tr_torrentGetFolder(fHandle)];
198}
199
200- (void) getAvailability: (int8_t *) tab size: (int) size
201{
202    tr_torrentAvailability(fHandle, tab, size);
203}
204
205- (void) getAmountFinished: (float *) tab size: (int) size
206{
207    tr_torrentAmountFinished(fHandle, tab, size);
208}
209
210- (void) update
211{
212    fStat = tr_torrentStat(fHandle);
213   
214    //notification when downloading finished
215    if ([self justFinished])
216    {
217        BOOL canMove = YES;
218       
219        //move file from incomplete folder to download folder
220        if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
221            && (canMove = [self alertForMoveVolumeAvailable]))
222        {
223            tr_torrentStop(fHandle);
224            if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
225                                    toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
226                tr_torrentSetFolder(fHandle, [fDownloadFolder UTF8String]);
227            tr_torrentStart(fHandle);
228        }
229       
230        if (!canMove)
231        {
232            fUseIncompleteFolder = NO;
233           
234            [fDownloadFolder release];
235            fDownloadFolder = fIncompleteFolder;
236            fIncompleteFolder = nil;
237        }
238       
239        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
240    }
241   
242    //check to stop for ratio
243    if ([self isSeeding] && ((fStopRatioSetting == RATIO_CHECK && [self ratio] >= fRatioLimit)
244            || (fStopRatioSetting == RATIO_GLOBAL && [fDefaults boolForKey: @"RatioCheck"]
245            && [self ratio] >= [fDefaults floatForKey: @"RatioLimit"])))
246    {
247        [self stopTransfer];
248        [self setStopRatioSetting: RATIO_NO_CHECK];
249        fFinishedSeeding = YES;
250       
251        fStat = tr_torrentStat(fHandle);
252       
253        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
254    }
255
256    [fProgressString setString: @""];
257    if ([self progress] < 1.0)
258        [fProgressString appendFormat: NSLocalizedString(@"%@ of %@ (%.2f%%)", "Torrent -> progress string"),
259                            [NSString stringForFileSize: [self downloadedValid]],
260                            [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
261    else
262        [fProgressString appendFormat: NSLocalizedString(@"%@, uploaded %@ (Ratio: %@)", "Torrent -> progress string"),
263                [NSString stringForFileSize: [self size]], [NSString stringForFileSize: [self uploadedTotal]],
264                [NSString stringForRatioWithDownload: [self downloadedTotal] upload: [self uploadedTotal]]];
265
266    switch (fStat->status)
267    {
268        NSString * tempString;
269   
270        case TR_STATUS_PAUSE:
271            if (fFinishedSeeding)
272                tempString = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
273            else if (fWaitToStart)
274                tempString = [NSLocalizedString(@"Waiting to start", "Torrent -> status string") stringByAppendingEllipsis];
275            else
276                tempString = NSLocalizedString(@"Paused", "Torrent -> status string");
277           
278            [fStatusString setString: tempString];
279            [fShortStatusString setString: tempString];
280           
281            break;
282
283        case TR_STATUS_CHECK:
284            tempString = [NSLocalizedString(@"Checking existing files", "Torrent -> status string") stringByAppendingEllipsis];
285           
286            [fStatusString setString: tempString];
287            [fShortStatusString setString: tempString];
288            [fRemainingTimeString setString: tempString];
289           
290            break;
291
292        case TR_STATUS_DOWNLOAD:
293            [fStatusString setString: @""];
294            if ([self totalPeers] > 1)
295                [fStatusString appendFormat: NSLocalizedString(@"Downloading from %d of %d peers",
296                                                "Torrent -> status string"), [self peersUploading], [self totalPeers]];
297            else
298                [fStatusString appendFormat: NSLocalizedString(@"Downloading from %d of %d peer",
299                                                "Torrent -> status string"), [self peersUploading], [self totalPeers]];
300           
301            [fRemainingTimeString setString: @""];
302            int eta = [self eta];
303            if (eta < 0)
304            {
305                [fRemainingTimeString setString: NSLocalizedString(@"Unknown", "Torrent -> remaining time")];
306                [fProgressString appendString: NSLocalizedString(@" - remaining time unknown", "Torrent -> progress string")];
307            }
308            else
309            {
310                if (eta < 60)
311                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d sec", "Torrent -> remaining time"), eta];
312                else if (eta < 3600) //60 * 60
313                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d min %02d sec", "Torrent -> remaining time"),
314                                                            eta / 60, eta % 60];
315                else if (eta < 86400) //24 * 60 * 60
316                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d hr %02d min", "Torrent -> remaining time"),
317                                                            eta / 3600, (eta / 60) % 60];
318                else
319                {
320                    if (eta / 86400 > 1)
321                        [fRemainingTimeString appendFormat: NSLocalizedString(@"%d days %d hr", "Torrent -> remaining time"),
322                                                                eta / 86400, (eta / 3600) % 24];
323                    else
324                        [fRemainingTimeString appendFormat: NSLocalizedString(@"%d day %d hr", "Torrent -> remaining time"),
325                                                                eta / 86400, (eta / 3600) % 24];
326                }
327               
328                [fProgressString appendFormat: NSLocalizedString(@" - %@ remaining", "Torrent -> progress string"),
329                                                                    fRemainingTimeString];
330            }
331           
332            break;
333
334        case TR_STATUS_SEED:
335            [fStatusString setString: @""];
336            if ([self totalPeers] > 1)
337                [fStatusString appendFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
338                                                [self peersDownloading], [self totalPeers]];
339            else
340                [fStatusString appendFormat: NSLocalizedString(@"Seeding to %d of %d peer", "Torrent -> status string"),
341                                                [self peersDownloading], [self totalPeers]];
342           
343            break;
344
345        case TR_STATUS_STOPPING:
346            tempString = [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
347       
348            [fStatusString setString: tempString];
349            [fShortStatusString setString: tempString];
350           
351            break;
352    }
353   
354    if (fStat->error & TR_ETRACKER)
355    {
356        [fStatusString setString: [NSLocalizedString(@"Error: ", "Torrent -> status string") stringByAppendingString:
357                                    [self errorMessage]]];
358    }
359   
360    BOOL wasError = fError;
361    if ((fError = fStat->cannotConnect))
362    {
363        if (!wasError && [self isActive] && ![self isSeeding])
364            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
365    }
366
367    if ([self isActive] && fStat->status != TR_STATUS_CHECK )
368    {
369        NSString * stringToAppend = @"";
370        if ([self progress] < 1.0)
371        {
372            stringToAppend = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, ", "Torrent -> status string"),
373                                [NSString stringForSpeed: [self downloadRate]]];
374            [fShortStatusString setString: @""];
375        }
376        else
377        {
378            NSString * ratioString = [NSString stringForRatioWithDownload: [self downloadedTotal]
379                                                upload: [self uploadedTotal]];
380       
381            [fShortStatusString setString: [NSString stringWithFormat: NSLocalizedString(@"Ratio: %@, ",
382                                            "Torrent -> status string"), ratioString]];
383            [fRemainingTimeString setString: [NSLocalizedString(@"Ratio: ", "Torrent -> status string")
384                                                stringByAppendingString: ratioString]];
385        }
386       
387        stringToAppend = [stringToAppend stringByAppendingString: [NSLocalizedString(@"UL: ", "Torrent -> status string")
388                                            stringByAppendingString: [NSString stringForSpeed: [self uploadRate]]]];
389
390        [fStatusString appendFormat: @" - %@", stringToAppend];
391        [fShortStatusString appendString: stringToAppend];
392    }
393}
394
395- (NSDictionary *) infoForCurrentView
396{
397    NSMutableDictionary * info = [NSMutableDictionary dictionaryWithObjectsAndKeys:
398                                    [self name], @"Name",
399                                    [NSNumber numberWithBool: [self isSeeding]], @"Seeding",
400                                    [NSNumber numberWithFloat: [self progress]], @"Progress",
401                                    [NSNumber numberWithBool: [self isActive]], @"Active",
402                                    [NSNumber numberWithBool: [self isError]], @"Error", nil];
403   
404    if (![fDefaults boolForKey: @"SmallView"])
405    {
406        [info setObject: fIconFlipped forKey: @"Icon"];
407        [info setObject: [self progressString] forKey: @"ProgressString"];
408        [info setObject: [self statusString] forKey: @"StatusString"];
409    }
410    else
411    {
412        [info setObject: fIconSmall forKey: @"Icon"];
413        [info setObject: [self remainingTimeString] forKey: @"RemainingTimeString"];
414        [info setObject: [self shortStatusString] forKey: @"ShortStatusString"];
415    }
416   
417    if ([fDefaults boolForKey: @"UseAdvancedBar"])
418        [info setObject: [self advancedBar] forKey: @"AdvancedBar"];
419   
420    return info;
421}
422
423- (void) startTransfer
424{
425    fWaitToStart = NO;
426    fFinishedSeeding = NO;
427   
428    if (![self isActive] && [self alertForVolumeAvailable] && [self alertForRemainingDiskSpace])
429        tr_torrentStart(fHandle);
430}
431
432- (void) stopTransfer
433{
434    fError = NO;
435   
436    if ([self isActive])
437    {
438        BOOL wasSeeding = [self isSeeding];
439   
440        tr_torrentStop(fHandle);
441
442        if (!wasSeeding)
443            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
444    }
445}
446
447- (void) stopTransferForQuit
448{
449    if ([self isActive])
450        tr_torrentStop(fHandle);
451}
452
453- (void) sleep
454{
455    if ((fResumeOnWake = [self isActive]))
456        tr_torrentStop(fHandle);
457}
458
459- (void) wakeUp
460{
461    if (fResumeOnWake)
462        tr_torrentStart(fHandle);
463}
464
465- (void) announce
466{
467    if (![self isActive])
468        return;
469   
470    tr_manualUpdate(fHandle);
471   
472    if (fAnnounceDate)
473        [fAnnounceDate release];
474    fAnnounceDate = [[NSDate date] retain];
475}
476
477- (NSDate *) announceDate
478{
479    return fAnnounceDate;
480}
481
482- (float) ratio
483{
484    float downloaded = [self downloadedTotal];
485    return downloaded > 0 ? (float)[self uploadedTotal] / downloaded : -1;
486}
487
488- (int) stopRatioSetting
489{
490        return fStopRatioSetting;
491}
492
493- (void) setStopRatioSetting: (int) setting
494{
495    fStopRatioSetting = setting;
496}
497
498- (float) ratioLimit
499{
500    return fRatioLimit;
501}
502
503- (void) setRatioLimit: (float) limit
504{
505    if (limit >= 0)
506        fRatioLimit = limit;
507}
508
509- (void) setWaitToStart: (BOOL) wait
510{
511    fWaitToStart = wait;
512}
513
514- (BOOL) waitingToStart
515{
516    return fWaitToStart;
517}
518
519- (void) revealData
520{
521    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
522}
523
524- (void) revealPublicTorrent
525{
526    if (fPublicTorrent)
527        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
528}
529
530- (void) trashData
531{
532    [self trashFile: [self dataLocation]];
533}
534
535- (void) trashTorrent
536{
537    if (fPublicTorrent)
538        [self trashFile: [self publicTorrentLocation]];
539}
540
541- (BOOL) alertForRemainingDiskSpace
542{
543    if ([self progress] >= 1.0)
544        return YES;
545   
546    NSString * volumeName = [[[NSFileManager defaultManager] componentsToDisplayForPath: [self downloadFolder]]
547                                                                                                objectAtIndex: 0];
548    NSDictionary * fsAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath: [self downloadFolder]];
549    uint64_t remainingSpace = [[fsAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue],
550            torrentRemaining = [self size] - (uint64_t)[self downloadedValid];
551   
552    /*NSLog(@"Volume: %@", volumeName);
553    NSLog(@"Remaining disk space: %qu (%@)", remainingSpace, [NSString stringForFileSize: remainingSpace]);
554    NSLog(@"Torrent remaining size: %qu (%@)", torrentRemaining, [NSString stringForFileSize: torrentRemaining]);*/
555   
556    if (volumeName && remainingSpace <= torrentRemaining)
557    {
558        NSAlert * alert = [[NSAlert alloc] init];
559        [alert setMessageText: [NSString stringWithFormat:
560                                NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
561                                    "Torrent file disk space alert -> title"), [self name]]];
562        [alert setInformativeText: [NSString stringWithFormat:
563                        NSLocalizedString(@"The transfer will be paused. Clear up space on \"%@\" to continue.",
564                                            "Torrent file disk space alert -> message"), volumeName]];
565        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file disk space alert -> button")];
566        [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent file disk space alert -> button")];
567       
568        if ([alert runModal] == NSAlertFirstButtonReturn)
569        {
570            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
571            return NO;
572        }
573        else
574            return YES;
575       
576        [alert release];
577    }
578    return YES;
579}
580
581- (BOOL) alertForVolumeAvailable
582{
583    NSArray * pathComponents = [[self downloadFolder] pathComponents];
584    if ([pathComponents count] < 3)
585        return YES;
586   
587    NSString * volume = [[[pathComponents objectAtIndex: 0] stringByAppendingPathComponent:
588                    [pathComponents objectAtIndex: 1]] stringByAppendingPathComponent: [pathComponents objectAtIndex: 2]];
589   
590    /*NSLog(@"%@", [self downloadFolder]);
591    NSLog(@"Volume: %@", volume);*/
592   
593    if (![[NSFileManager defaultManager] fileExistsAtPath: volume])
594    {
595        NSString * volumeName = [pathComponents objectAtIndex: 2];
596       
597        NSAlert * alert = [[NSAlert alloc] init];
598        [alert setMessageText: [NSString stringWithFormat:
599                                NSLocalizedString(@"The volume for downloading \"%@\" cannot be found.",
600                                    "Volume cannot be found alert -> title"), [self name]]];
601        [alert setInformativeText: [NSString stringWithFormat:
602                        NSLocalizedString(@"The transfer will be paused. Mount the volume \"%@\" to continue.",
603                                            "Volume cannot be found alert -> message"), volumeName]];
604        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Volume cannot be found alert -> button")];
605        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Directory",
606                                    "Volume cannot be found alert -> directory button") stringByAppendingEllipsis]];
607       
608        if ([alert runModal] == NSAlertFirstButtonReturn)
609            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
610        else
611        {
612            NSOpenPanel * panel = [NSOpenPanel openPanel];
613           
614            [panel setPrompt: @"Select"];
615            [panel setAllowsMultipleSelection: NO];
616            [panel setCanChooseFiles: NO];
617            [panel setCanChooseDirectories: YES];
618
619            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
620                                "Open torrent -> select destination folder"), [self name]]];
621           
622            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
623            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
624                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
625        }
626       
627        [alert release];
628       
629        return NO;
630    }
631   
632    return YES;
633}
634
635- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) context
636{
637    NSString * folder = [[openPanel filenames] objectAtIndex: 0];
638    if (code == NSOKButton)
639    {
640        if (fUseIncompleteFolder)
641        {
642            [fIncompleteFolder release];
643            fIncompleteFolder = [folder retain];
644            [self setDownloadFolder: nil];
645        }
646        else
647        {
648            [fDownloadFolder release];
649            fDownloadFolder = folder;
650            [self setDownloadFolder: fDownloadFolder];
651        }
652       
653        [self startTransfer];
654        [self update];
655       
656        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
657    }
658    else
659        [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
660}
661
662- (BOOL) alertForMoveVolumeAvailable
663{
664    NSArray * pathComponents = [fDownloadFolder pathComponents];
665    if ([pathComponents count] < 3)
666        return YES;
667   
668    NSString * volume = [[[pathComponents objectAtIndex: 0] stringByAppendingPathComponent:
669                    [pathComponents objectAtIndex: 1]] stringByAppendingPathComponent: [pathComponents objectAtIndex: 2]];
670   
671    /*NSLog(@"%@", [self downloadFolder]);
672    NSLog(@"Volume: %@", volume);*/
673   
674    if (![[NSFileManager defaultManager] fileExistsAtPath: volume])
675    {
676        NSAlert * alert = [[NSAlert alloc] init];
677        [alert setMessageText: [NSString stringWithFormat:
678                                NSLocalizedString(@"The volume for moving the completed \"%@\" cannot be found.",
679                                    "Move volume cannot be found alert -> title"), [self name]]];
680        [alert setInformativeText: NSLocalizedString(@"The file will remain in its current location",
681                                    "Move volume cannot be found alert -> message")];
682        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move volume cannot be found alert -> button")];
683       
684        [alert runModal];
685        [alert release];
686       
687        return NO;
688    }
689   
690    return YES;
691}
692
693- (NSImage *) icon
694{
695    return fIcon;
696}
697
698- (NSImage *) iconFlipped
699{
700    return fIconFlipped;
701}
702
703- (NSImage *) iconSmall
704{
705    return fIconSmall;
706}
707
708- (NSString *) name
709{
710    return [NSString stringWithUTF8String: fInfo->name];
711}
712
713- (uint64_t) size
714{
715    return fInfo->totalSize;
716}
717
718- (NSString *) trackerAddress
719{
720    return [NSString stringWithFormat: @"http://%s:%d", fStat->trackerAddress, fStat->trackerPort];
721}
722
723- (NSString *) trackerAddressAnnounce
724{
725    return [NSString stringWithUTF8String: fStat->trackerAnnounce];
726}
727
728- (NSString *) comment
729{
730    return [NSString stringWithUTF8String: fInfo->comment];
731}
732
733- (NSString *) creator
734{
735    return [NSString stringWithUTF8String: fInfo->creator];
736}
737
738- (NSDate *) dateCreated
739{
740    int date = fInfo->dateCreated;
741    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
742}
743
744- (int) pieceSize
745{
746    return fInfo->pieceSize;
747}
748
749- (int) pieceCount
750{
751    return fInfo->pieceCount;
752}
753
754- (NSString *) hashString
755{
756    return [NSString stringWithUTF8String: fInfo->hashString];
757}
758
759- (BOOL) privateTorrent
760{
761    return fInfo->privateTorrent;
762}
763
764- (NSString *) torrentLocation
765{
766    return [NSString stringWithUTF8String: fInfo->torrent];
767}
768
769- (NSString *) publicTorrentLocation
770{
771    return fPublicTorrentLocation;
772}
773
774- (NSString *) dataLocation
775{
776    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
777}
778
779- (BOOL) publicTorrent
780{
781    return fPublicTorrent;
782}
783
784- (NSString *) stateString
785{
786    switch( fStat->status )
787    {
788        case TR_STATUS_PAUSE:
789            return NSLocalizedString(@"Paused", "Torrent -> status string");
790            break;
791
792        case TR_STATUS_CHECK:
793            return [NSLocalizedString(@"Checking existing files", "Torrent -> status string") stringByAppendingEllipsis];
794            break;
795
796        case TR_STATUS_DOWNLOAD:
797            return NSLocalizedString(@"Downloading", "Torrent -> status string");
798            break;
799
800        case TR_STATUS_SEED:
801            return NSLocalizedString(@"Seeding", "Torrent -> status string");
802            break;
803
804        case TR_STATUS_STOPPING:
805            return [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
806            break;
807       
808        default:
809            return NSLocalizedString(@"N/A", "Torrent -> status string");
810    }
811}
812
813- (float) progress
814{
815    return fStat->progress;
816}
817
818- (int) eta
819{
820    return fStat->eta;
821}
822
823- (BOOL) isActive
824{
825    return fStat->status & TR_STATUS_ACTIVE;
826}
827
828- (BOOL) isSeeding
829{
830    return fStat->status == TR_STATUS_SEED;
831}
832
833- (BOOL) isPaused
834{
835    return fStat->status == TR_STATUS_PAUSE;
836}
837
838- (BOOL) isError
839{
840    return fStat->error & TR_ETRACKER;
841}
842
843- (NSString *) errorMessage
844{
845    [NSString stringWithUTF8String: fStat->trackerError];
846}
847
848- (BOOL) justFinished
849{
850    return tr_getFinished(fHandle);
851}
852
853- (NSArray *) peers
854{
855    int totalPeers, i;
856    tr_peer_stat_t * peers = tr_torrentPeers(fHandle, & totalPeers);
857   
858    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
859    NSMutableDictionary * dic;
860   
861    tr_peer_stat_t * peer;
862    NSString * client;
863    for (i = 0; i < totalPeers; i++)
864    {
865        peer = &peers[i];
866       
867        dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
868            [NSNumber numberWithBool: peer->isConnected], @"Connected",
869            [NSNumber numberWithBool: peer->isIncoming], @"Incoming",
870            [NSString stringWithCString: (char *) peer->addr encoding: NSUTF8StringEncoding], @"IP",
871            [NSString stringWithCString: (char *) peer->client encoding: NSUTF8StringEncoding], @"Client",
872            [NSNumber numberWithFloat: peer->progress], @"Progress",
873            [NSNumber numberWithBool: peer->isDownloading], @"UL To",
874            [NSNumber numberWithBool: peer->isUploading], @"DL From",
875            [NSNumber numberWithInt: peer->port], @"Port", nil];
876       
877        if (peer->isDownloading)
878            [dic setObject: [NSNumber numberWithFloat: peer->uploadToRate] forKey: @"UL To Rate"];
879        if (peer->isUploading)
880            [dic setObject: [NSNumber numberWithFloat: peer->downloadFromRate] forKey: @"DL From Rate"];
881       
882        [peerDics addObject: dic];
883    }
884   
885    tr_torrentPeersFree(peers, totalPeers);
886   
887    return peerDics;
888}
889
890- (NSString *) progressString
891{
892    return fProgressString;
893}
894
895- (NSString *) statusString
896{
897    return fStatusString;
898}
899
900- (NSString *) shortStatusString
901{
902    return fShortStatusString;
903}
904
905- (NSString *) remainingTimeString
906{
907    return fRemainingTimeString;
908}
909
910- (int) seeders
911{
912    return fStat->seeders;
913}
914
915- (int) leechers
916{
917    return fStat->leechers;
918}
919
920- (int) completedFromTracker
921{
922    return fStat->completedFromTracker;
923}
924
925- (int) totalPeers
926{
927    return fStat->peersTotal;
928}
929
930- (int) totalPeersIncoming
931{
932    return fStat->peersIncoming;
933}
934
935- (int) totalPeersOutgoing
936{
937    return [self totalPeers] - [self totalPeersIncoming];
938}
939
940//peers uploading to you
941- (int) peersUploading
942{
943    return fStat->peersUploading;
944}
945
946//peers downloading from you
947- (int) peersDownloading
948{
949    return fStat->peersDownloading;
950}
951
952- (float) downloadRate
953{
954    return fStat->rateDownload;
955}
956
957- (float) uploadRate
958{
959    return fStat->rateUpload;
960}
961
962- (float) downloadedValid
963{
964    return [self progress] * [self size];
965}
966
967- (uint64_t) downloadedTotal
968{
969    return fStat->downloaded;
970}
971
972- (uint64_t) uploadedTotal
973{
974    return fStat->uploaded;
975}
976
977- (float) swarmSpeed
978{
979    return fStat->swarmspeed;
980}
981
982- (NSNumber *) orderValue
983{
984    return [NSNumber numberWithInt: fOrderValue];
985}
986
987- (void) setOrderValue: (int) orderValue
988{
989    fOrderValue = orderValue;
990}
991
992- (NSArray *) fileList
993{
994    int count = fInfo->fileCount, i;
995    tr_file_t file;
996    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
997   
998    for (i = 0; i < count; i++)
999    {
1000        file = fInfo->files[i];
1001        [files addObject: [NSDictionary dictionaryWithObjectsAndKeys:
1002            [[self downloadFolder] stringByAppendingPathComponent: [NSString stringWithUTF8String: file.name]], @"Name",
1003            [NSNumber numberWithUnsignedLongLong: file.length], @"Size", nil]];
1004    }
1005   
1006    return files;
1007}
1008
1009- (NSDate *) date
1010{
1011    return fDate;
1012}
1013
1014- (NSNumber *) stateSortKey
1015{
1016    if (![self isActive])
1017        return [NSNumber numberWithInt: 0];
1018    else if ([self isSeeding])
1019        return [NSNumber numberWithInt: 1];
1020    else
1021        return [NSNumber numberWithInt: 2];
1022}
1023
1024- (NSNumber *) progressSortKey
1025{
1026    //if finished downloading sort by ratio instead of progress
1027    float progress = [self progress];
1028    return [NSNumber numberWithFloat: progress < 1.0 ? progress : 2.0 + [self ratio]];
1029}
1030
1031@end
1032
1033
1034@implementation Torrent (Private)
1035
1036//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1037- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
1038        publicTorrent: (NSNumber *) publicTorrent
1039        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
1040        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
1041        orderValue: (NSNumber *) orderValue
1042{
1043    if (!(self = [super init]))
1044        return nil;
1045
1046    fLib = lib;
1047    fDefaults = [NSUserDefaults standardUserDefaults];
1048
1049    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1050    if (fPublicTorrent)
1051        fPublicTorrentLocation = [path retain];
1052
1053    int error;
1054    if (hashString)
1055        fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error);
1056   
1057    if (!fHandle && path)
1058        fHandle = tr_torrentInit(fLib, [path UTF8String], TR_FSAVEPRIVATE, & error);
1059
1060    if (!fHandle)
1061    {
1062        [self release];
1063        return nil;
1064    }
1065   
1066    fInfo = tr_torrentInfo( fHandle );
1067
1068    fDate = date ? [date retain] : [[NSDate alloc] init];
1069   
1070    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
1071    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1072    fFinishedSeeding = NO;
1073   
1074    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
1075    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
1076    fError = NO;
1077   
1078    NSString * fileType = fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
1079    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
1080    [fIcon retain];
1081   
1082    fIconFlipped = [fIcon copy];
1083    [fIconFlipped setFlipped: YES];
1084   
1085    fIconSmall = [fIconFlipped copy];
1086    [fIconSmall setScalesWhenResized: YES];
1087    [fIconSmall setSize: NSMakeSize(16.0, 16.0)];
1088
1089    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
1090    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
1091    fShortStatusString = [[NSMutableString alloc] initWithCapacity: 30];
1092    fRemainingTimeString = [[NSMutableString alloc] initWithCapacity: 30];
1093   
1094    //set up advanced bar
1095    fBitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
1096        pixelsWide: MAX_PIECES pixelsHigh: BAR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
1097        isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
1098   
1099    fPieces = malloc(MAX_PIECES);
1100    int i;
1101    for (i = 0; i < MAX_PIECES; i++)
1102        fPieces[i] = BLANK_PIECE;
1103
1104    [self update];
1105    return self;
1106}
1107
1108- (NSImage *) advancedBar
1109{
1110    int h, w;
1111    uint32_t * p;
1112    uint8_t * bitmapData = [fBitmap bitmapData];
1113    int bytesPerRow = [fBitmap bytesPerRow];
1114
1115    int8_t * pieces = malloc(MAX_PIECES);
1116    [self getAvailability: pieces size: MAX_PIECES];
1117   
1118    //lines 2 to 14: blue, green, or gray depending on whether we have the piece or not
1119    int have = 0, avail = 0;
1120    uint32_t color;
1121    BOOL change;
1122    for (w = 0; w < MAX_PIECES; w++)
1123    {
1124        change = NO;
1125        if (pieces[w] < 0)
1126        {
1127            if (fPieces[w] != -1)
1128            {
1129                color = kBlue;
1130                fPieces[w] = -1;
1131                change = YES;
1132            }
1133            have++;
1134        }
1135        else if (pieces[w] == 0)
1136        {
1137            if (fPieces[w] != 0)
1138            {
1139                color = kGray;
1140                fPieces[w] = 0;
1141                change = YES;
1142            }
1143        }
1144        else
1145        {
1146            if (pieces[w] == 1)
1147            {
1148                if (fPieces[w] != 1)
1149                {
1150                    color = kGreen1;
1151                    fPieces[w] = 1;
1152                    change = YES;
1153                }
1154            }
1155            else if (pieces[w] == 2)
1156            {
1157                if (fPieces[w] != 2)
1158                {
1159                    color = kGreen2;
1160                    fPieces[w] = 2;
1161                    change = YES;
1162                }
1163            }
1164            else
1165            {
1166                if (fPieces[w] != 3)
1167                {
1168                    color = kGreen3;
1169                    fPieces[w] = 3;
1170                    change = YES;
1171                }
1172            }
1173            avail++;
1174        }
1175       
1176        if (change)
1177        {
1178            //point to pixel (w, 2) and draw "vertically"
1179            p = (uint32_t *)(bitmapData + 2 * bytesPerRow) + w;
1180            for (h = 2; h < BAR_HEIGHT; h++)
1181            {
1182                p[0] = color;
1183                p = (uint32_t *)((uint8_t *)p + bytesPerRow);
1184            }
1185        }
1186    }
1187   
1188    //first two lines: dark blue to show progression, green to show available
1189    p = (uint32_t *) bitmapData;
1190    for (w = 0; w < have; w++)
1191    {
1192        p[w] = kBlue2;
1193        p[w + bytesPerRow / 4] = kBlue2;
1194    }
1195    for (; w < avail + have; w++)
1196    {
1197        p[w] = kGreen3;
1198        p[w + bytesPerRow / 4] = kGreen3;
1199    }
1200    for (; w < MAX_PIECES; w++)
1201    {
1202        p[w] = kWhite;
1203        p[w + bytesPerRow / 4] = kWhite;
1204    }
1205   
1206    free(pieces);
1207   
1208    //actually draw image
1209    NSImage * bar = [[NSImage alloc] initWithSize: [fBitmap size]];
1210    [bar addRepresentation: fBitmap];
1211    [bar setScalesWhenResized: YES];
1212   
1213    return [bar autorelease];
1214}
1215
1216- (void) trashFile: (NSString *) path
1217{
1218    //attempt to move to trash
1219    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1220            source: [path stringByDeletingLastPathComponent] destination: @""
1221            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1222    {
1223        //if cannot trash, just delete it (will work if it is on a remote volume)
1224        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1225            NSLog(@"Could not trash %@", path);
1226    }
1227}
1228
1229@end
Note: See TracBrowser for help on using the repository browser.