source: trunk/macosx/Torrent.m @ 1093

Last change on this file since 1093 was 1093, checked in by livings124, 15 years ago

Choose a new volume for downloading if the current isn't available. I still need feedback on this.

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