source: trunk/macosx/Torrent.m @ 961

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

Torrents that have errors aren't counted in the queue, and when a torrent encounters an error the next torrent in the queue will start (even though that torrent might still be active).

  • Property svn:keywords set to Date Rev Author Id
File size: 25.8 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 961 2006-09-29 05:30:36Z 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@interface Torrent (Private)
31
32- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
33        privateTorrent: (NSNumber *) privateTorrent publicTorrent: (NSNumber *) publicTorrent
34        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
35        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
36        orderValue: (NSNumber *) orderValue;
37
38- (NSImage *) advancedBar;
39
40- (void) trashFile: (NSString *) path;
41
42@end
43
44@implementation Torrent
45
46// Used to optimize drawing. They contain packed RGBA pixels for every color needed.
47#define BE OSSwapBigToHostConstInt32
48
49static uint32_t kRed   = BE(0xFF6450FF), //255, 100, 80
50                kBlue1 = BE(0xA0DCFFFF), //160, 220, 255
51                kBlue2 = BE(0x78BEFFFF), //120, 190, 255
52                kBlue3 = BE(0x50A0FFFF), //80, 160, 255
53                kBlue4 = BE(0x1E46B4FF), //30, 70, 180
54                kGray  = BE(0x969696FF), //150, 150, 150
55                kGreen = BE(0x00FF00FF), //0, 255, 0
56                kWhite = BE(0xFFFFFFFF); //255, 255, 255
57
58- (id) initWithPath: (NSString *) path lib: (tr_handle_t *) lib
59{
60    self = [self initWithHash: nil path: path lib: lib privateTorrent: nil publicTorrent: nil
61            date: nil stopRatioSetting: nil ratioLimit: nil waitToStart: nil orderValue: nil];
62   
63    if (self)
64    {
65        if (!fPublicTorrent)
66            [self trashFile: path];
67    }
68    return self;
69}
70
71- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle_t *) lib
72{
73    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
74                path: [history objectForKey: @"TorrentPath"] lib: lib
75                privateTorrent: [history objectForKey: @"PrivateCopy"]
76                publicTorrent: [history objectForKey: @"PublicCopy"]
77                date: [history objectForKey: @"Date"]
78                stopRatioSetting: [history objectForKey: @"StopRatioSetting"]
79                ratioLimit: [history objectForKey: @"RatioLimit"]
80                waitToStart: [history objectForKey: @"WaitToStart"]
81                orderValue: [history objectForKey: @"OrderValue"]];
82   
83    if (self)
84    {
85        NSString * downloadFolder;
86        if (!(downloadFolder = [history objectForKey: @"DownloadFolder"]))
87            downloadFolder = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
88        [self setDownloadFolder: downloadFolder];
89
90        NSString * paused;
91        if (!(paused = [history objectForKey: @"Paused"]) || [paused isEqualToString: @"NO"])
92        {
93            fStat = tr_torrentStat(fHandle);
94            [self startTransfer];
95        }
96    }
97    return self;
98}
99
100- (NSDictionary *) history
101{
102    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
103                    [NSNumber numberWithBool: fPrivateTorrent], @"PrivateCopy",
104                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
105                    [self downloadFolder], @"DownloadFolder",
106                    [self isActive] ? @"NO" : @"YES", @"Paused",
107                    [self date], @"Date",
108                    [NSNumber numberWithInt: fStopRatioSetting], @"StopRatioSetting",
109                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
110                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
111                    [self orderValue], @"OrderValue", nil];
112           
113    if (fPrivateTorrent)
114        [history setObject: [self hashString] forKey: @"TorrentHash"];
115
116    if (fPublicTorrent)
117        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
118   
119    return history;
120}
121
122- (void) dealloc
123{
124    if (fHandle)
125    {
126        tr_torrentClose(fLib, fHandle);
127       
128        if (fPublicTorrentLocation)
129            [fPublicTorrentLocation release];
130       
131        [fDate release];
132       
133        [fIcon release];
134        [fIconFlipped release];
135        [fIconSmall release];
136       
137        [fProgressString release];
138        [fStatusString release];
139        [fShortStatusString release];
140        [fRemainingTimeString release];
141    }
142    [super dealloc];
143}
144
145- (void) setDownloadFolder: (NSString *) path
146{
147    tr_torrentSetFolder(fHandle, [path UTF8String]);
148}
149
150- (NSString *) downloadFolder
151{
152    return [NSString stringWithUTF8String: tr_torrentGetFolder(fHandle)];
153}
154
155- (void) getAvailability: (int8_t *) tab size: (int) size
156{
157    tr_torrentAvailability(fHandle, tab, size);
158}
159
160- (void) update
161{
162    fStat = tr_torrentStat(fHandle);
163   
164    //notification when downloading finished
165    if ([self justFinished])
166        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
167   
168    //check to stop for ratio
169    if ([self isSeeding] && ((fStopRatioSetting == RATIO_CHECK && [self ratio] >= fRatioLimit)
170            || (fStopRatioSetting == RATIO_GLOBAL && [fDefaults boolForKey: @"RatioCheck"]
171            && [self ratio] >= [fDefaults floatForKey: @"RatioLimit"])))
172    {
173        [self stopTransfer];
174        [self setStopRatioSetting: RATIO_NO_CHECK];
175        fFinishedSeeding = YES;
176       
177        fStat = tr_torrentStat(fHandle);
178       
179        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
180    }
181
182    [fProgressString setString: @""];
183    if ([self progress] < 1.0)
184        [fProgressString appendFormat: @"%@ of %@ (%.2f%%)", [NSString stringForFileSize:
185                [self downloadedValid]], [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
186    else
187        [fProgressString appendFormat: @"%@, uploaded %@ (Ratio: %@)", [NSString stringForFileSize:
188                [self size]], [NSString stringForFileSize: [self uploadedTotal]],
189                [NSString stringForRatioWithDownload: [self downloadedTotal] upload: [self uploadedTotal]]];
190
191    switch (fStat->status)
192    {
193        NSString * tempString;
194   
195        case TR_STATUS_PAUSE:
196            if (fFinishedSeeding)
197                tempString = @"Seeding complete";
198            else if (fWaitToStart)
199                tempString = [@"Waiting to start" stringByAppendingEllipsis];
200            else
201                tempString = @"Paused";
202           
203            [fStatusString setString: tempString];
204            [fShortStatusString setString: tempString];
205           
206            break;
207
208        case TR_STATUS_CHECK:
209            tempString = [@"Checking existing files" stringByAppendingEllipsis];
210           
211            [fStatusString setString: tempString];
212            [fShortStatusString setString: tempString];
213            [fRemainingTimeString setString: tempString];
214           
215            break;
216
217        case TR_STATUS_DOWNLOAD:
218            [fStatusString setString: @""];
219            [fStatusString appendFormat:
220                @"Downloading from %d of %d peer%s", [self peersUploading], [self totalPeers],
221                [self totalPeers] == 1 ? "" : "s"];
222           
223            [fRemainingTimeString setString: @""];
224            int eta = [self eta];
225            if (eta < 0)
226            {
227                [fRemainingTimeString setString: @"Unknown"];
228                [fProgressString appendString: @" - remaining time unknown"];
229            }
230            else
231            {
232                if (eta < 60)
233                    [fRemainingTimeString appendFormat: @"%d sec", eta];
234                else if (eta < 3600) //60 * 60
235                    [fRemainingTimeString appendFormat: @"%d min %02d sec", eta / 60, eta % 60];
236                else if (eta < 86400) //24 * 60 * 60
237                    [fRemainingTimeString appendFormat: @"%d hr %02d min", eta / 3600, (eta / 60) % 60];
238                else
239                    [fRemainingTimeString appendFormat: @"%d day%s %d hr",
240                                                eta / 86400, eta / 86400 == 1 ? "" : "s", (eta / 3600) % 24];
241               
242                [fProgressString appendFormat: @" - %@ remaining", fRemainingTimeString];
243            }
244           
245            break;
246
247        case TR_STATUS_SEED:
248            [fStatusString setString: @""];
249            [fStatusString appendFormat:
250                @"Seeding to %d of %d peer%s",
251                [self peersDownloading], [self totalPeers], [self totalPeers] == 1 ? "" : "s"];
252           
253            break;
254
255        case TR_STATUS_STOPPING:
256            tempString = [@"Stopping" stringByAppendingEllipsis];
257       
258            [fStatusString setString: tempString];
259            [fShortStatusString setString: tempString];
260           
261            break;
262    }
263   
264    if (fStat->error & TR_ETRACKER)
265    {
266        [fStatusString setString: [@"Error: " stringByAppendingString: [NSString stringWithUTF8String: fStat->trackerError]]];
267        if (!fError && [self isActive])
268        {
269            fError = YES;
270            if (![self isSeeding])
271                [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
272        }
273    }
274    else
275    {
276        if (fError)
277            fError = NO;
278    }
279
280    if ([self isActive])
281    {
282        NSString * stringToAppend = @"";
283        if ([self progress] < 1.0)
284        {
285            stringToAppend = [NSString stringWithFormat: @"DL: %@, ", [NSString stringForSpeed: [self downloadRate]]];
286            [fShortStatusString setString: @""];
287        }
288        else
289        {
290            NSString * ratioString = [NSString stringForRatioWithDownload: [self downloadedTotal]
291                                                upload: [self uploadedTotal]];
292       
293            [fShortStatusString setString: [NSString stringWithFormat: @"Ratio: %@, ", ratioString]];
294            [fRemainingTimeString setString: [@"Ratio: " stringByAppendingString: ratioString]];
295        }
296       
297        stringToAppend = [stringToAppend stringByAppendingString: [@"UL: " stringByAppendingString:
298                                                [NSString stringForSpeed: [self uploadRate]]]];
299
300        [fStatusString appendFormat: @" - %@", stringToAppend];
301        [fShortStatusString appendString: stringToAppend];
302    }
303}
304
305- (NSDictionary *) infoForCurrentView
306{
307    NSMutableDictionary * info = [NSMutableDictionary dictionaryWithObjectsAndKeys:
308                                    [self name], @"Name",
309                                    [NSNumber numberWithBool: [self isSeeding]], @"Seeding",
310                                    [NSNumber numberWithFloat: [self progress]], @"Progress",
311                                    [NSNumber numberWithBool: [self isActive]], @"Active",
312                                    [NSNumber numberWithBool: [self isError]], @"Error", nil];
313   
314    if (![fDefaults boolForKey: @"SmallView"])
315    {
316        [info setObject: fIconFlipped forKey: @"Icon"];
317        [info setObject: [self progressString] forKey: @"ProgressString"];
318        [info setObject: [self statusString] forKey: @"StatusString"];
319    }
320    else
321    {
322        [info setObject: fIconSmall forKey: @"Icon"];
323        [info setObject: [self remainingTimeString] forKey: @"RemainingTimeString"];
324        [info setObject: [self shortStatusString] forKey: @"ShortStatusString"];
325    }
326   
327    if ([fDefaults boolForKey: @"UseAdvancedBar"])
328        [info setObject: [self advancedBar] forKey: @"AdvancedBar"];
329   
330    return info;
331}
332
333- (void) startTransfer
334{
335    fWaitToStart = NO;
336    fFinishedSeeding = NO;
337   
338    if (![self isActive] && [self remainingDiskSpaceForTorrent])
339        tr_torrentStart(fHandle);
340}
341
342- (void) stopTransfer
343{
344    fError = NO;
345   
346    if ([self isActive])
347    {
348        BOOL wasSeeding = [self isSeeding];
349   
350        tr_torrentStop(fHandle);
351
352        if (!wasSeeding)
353            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
354    }
355}
356
357- (void) stopTransferForQuit
358{
359    if ([self isActive])
360        tr_torrentStop(fHandle);
361}
362
363- (void) removeForever
364{
365    if (fPrivateTorrent)
366        tr_torrentRemoveSaved(fHandle);
367}
368
369- (void) sleep
370{
371    if ((fResumeOnWake = [self isActive]))
372        tr_torrentStop(fHandle);
373}
374
375- (void) wakeUp
376{
377    if (fResumeOnWake)
378        tr_torrentStart(fHandle);
379}
380
381- (float) ratio
382{
383    float downloaded = [self downloadedTotal];
384    return downloaded > 0 ? (float)[self uploadedTotal] / downloaded : -1;
385}
386
387- (int) stopRatioSetting
388{
389        return fStopRatioSetting;
390}
391
392- (void) setStopRatioSetting: (int) setting
393{
394    fStopRatioSetting = setting;
395}
396
397- (float) ratioLimit
398{
399    return fRatioLimit;
400}
401
402- (void) setRatioLimit: (float) limit
403{
404    if (limit >= 0)
405        fRatioLimit = limit;
406}
407
408- (void) setWaitToStart: (BOOL) wait
409{
410    fWaitToStart = wait;
411}
412
413- (BOOL) waitingToStart
414{
415    return fWaitToStart;
416}
417
418- (void) revealData
419{
420    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
421}
422
423- (void) trashData
424{
425    [self trashFile: [self dataLocation]];
426}
427
428- (void) trashTorrent
429{
430    if (fPublicTorrent)
431        [self trashFile: [self publicTorrentLocation]];
432}
433
434- (BOOL) remainingDiskSpaceForTorrent
435{
436    if ([self progress] >= 1.0)
437        return YES;
438   
439    NSString * location = [self dataLocation],
440                * volume = [[[NSFileManager defaultManager] componentsToDisplayForPath: location] objectAtIndex: 0];
441    NSDictionary * fsAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath: location];
442    uint64_t remainingSpace = [[fsAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue],
443            torrentRemaining = [self size] - (uint64_t)[self downloadedValid];
444   
445    NSLog(@"Volume: %@", volume);
446    NSLog(@"Remaining disk space: %qu (%@)", remainingSpace, [NSString stringForFileSize: remainingSpace]);
447    NSLog(@"Torrent remaining size: %qu (%@)", torrentRemaining, [NSString stringForFileSize: torrentRemaining]);
448   
449    if (volume && remainingSpace <= torrentRemaining)
450    {
451        NSAlert * alert = [[NSAlert alloc] init];
452        [alert setMessageText: [NSString stringWithFormat: @"Not enough remaining disk space to download \"%@\" completely.",
453                                    [self name]]];
454        [alert setInformativeText: [NSString stringWithFormat:
455                        @"The transfer has been paused. Clear up space on %@ to continue.", volume]];
456        [alert runModal];
457       
458        return NO;
459    }
460    return YES;
461}
462
463- (NSImage *) icon
464{
465    return fIcon;
466}
467
468- (NSImage *) iconFlipped
469{
470    return fIconFlipped;
471}
472
473- (NSImage *) iconSmall
474{
475    return fIconSmall;
476}
477
478- (NSString *) name
479{
480    return [NSString stringWithUTF8String: fInfo->name];
481}
482
483- (uint64_t) size
484{
485    return fInfo->totalSize;
486}
487
488- (NSString *) tracker
489{
490    return [NSString stringWithFormat: @"%s:%d", fInfo->trackerAddress, fInfo->trackerPort];
491}
492
493- (NSString *) announce
494{
495    return [NSString stringWithUTF8String: fInfo->trackerAnnounce];
496}
497
498- (int) pieceSize
499{
500    return fInfo->pieceSize;
501}
502
503- (int) pieceCount
504{
505    return fInfo->pieceCount;
506}
507
508- (NSString *) hashString
509{
510    return [NSString stringWithUTF8String: fInfo->hashString];
511}
512
513- (NSString *) torrentLocation
514{
515    return [NSString stringWithUTF8String: fInfo->torrent];
516}
517
518- (NSString *) publicTorrentLocation
519{
520    return fPublicTorrentLocation;
521}
522
523- (NSString *) torrentLocationString
524{
525    return fPrivateTorrent ? @"Transmission Support Folder" : [fPublicTorrentLocation stringByAbbreviatingWithTildeInPath];
526}
527
528- (NSString *) dataLocation
529{
530    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
531}
532
533- (BOOL) publicTorrent
534{
535    return fPublicTorrent;
536}
537
538- (BOOL) privateTorrent
539{
540    return fPrivateTorrent;
541}
542
543- (NSString *) stateString
544{
545    switch( fStat->status )
546    {
547        case TR_STATUS_PAUSE:
548            return @"Paused";
549            break;
550
551        case TR_STATUS_CHECK:
552            return [@"Checking existing files" stringByAppendingEllipsis];
553            break;
554
555        case TR_STATUS_DOWNLOAD:
556            return @"Downloading";
557            break;
558
559        case TR_STATUS_SEED:
560            return @"Seeding";
561            break;
562
563        case TR_STATUS_STOPPING:
564            return [@"Stopping" stringByAppendingEllipsis];
565            break;
566       
567        default:
568            return @"N/A";
569    }
570}
571
572- (float) progress
573{
574    return fStat->progress;
575}
576
577- (int) eta
578{
579    return fStat->eta;
580}
581
582- (BOOL) isActive
583{
584    return fStat->status & TR_STATUS_ACTIVE;
585}
586
587- (BOOL) isSeeding
588{
589    return fStat->status == TR_STATUS_SEED;
590}
591
592- (BOOL) isPaused
593{
594    return fStat->status == TR_STATUS_PAUSE;
595}
596
597- (BOOL) isError
598{
599    return fStat->error & TR_ETRACKER;
600}
601
602- (BOOL) justFinished
603{
604    return tr_getFinished(fHandle);
605}
606
607- (NSArray *) peers
608{
609    int totalPeers, i;
610    tr_peer_stat_t * peers = tr_torrentPeers(fHandle, & totalPeers);
611   
612    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
613    tr_peer_stat_t peer;
614    NSString * client;
615    for (i = 0; i < totalPeers; i++)
616    {
617        peer = peers[i];
618        [peerDics addObject: [NSDictionary dictionaryWithObjectsAndKeys:
619            [NSNumber numberWithBool: peer.isConnected], @"Connected",
620            [NSString stringWithCString: (char *) peer.addr encoding: NSUTF8StringEncoding], @"IP",
621            [NSString stringWithCString: (char *) peer.client encoding: NSUTF8StringEncoding], @"Client",
622            [NSNumber numberWithBool: peer.isDownloading], @"UL To",
623            [NSNumber numberWithBool: peer.isUploading], @"DL From", nil]];
624    }
625   
626    tr_torrentPeersFree(peers, totalPeers);
627   
628    return peerDics;
629}
630
631- (NSString *) progressString
632{
633    return fProgressString;
634}
635
636- (NSString *) statusString
637{
638    return fStatusString;
639}
640
641- (NSString *) shortStatusString
642{
643    return fShortStatusString;
644}
645
646- (NSString *) remainingTimeString
647{
648    return fRemainingTimeString;
649}
650
651- (int) seeders
652{
653    return fStat->seeders;
654}
655
656- (int) leechers
657{
658    return fStat->leechers;
659}
660
661- (int) totalPeers
662{
663    return fStat->peersTotal;
664}
665
666//peers uploading to you
667- (int) peersUploading
668{
669    return fStat->peersUploading;
670}
671
672//peers downloading from you
673- (int) peersDownloading
674{
675    return fStat->peersDownloading;
676}
677
678- (float) downloadRate
679{
680    return fStat->rateDownload;
681}
682
683- (float) uploadRate
684{
685    return fStat->rateUpload;
686}
687
688- (float) downloadedValid
689{
690    return [self progress] * [self size];
691}
692
693- (uint64_t) downloadedTotal
694{
695    return fStat->downloaded;
696}
697
698- (uint64_t) uploadedTotal
699{
700    return fStat->uploaded;
701}
702
703- (float) swarmSpeed
704{
705    return fStat->swarmspeed;
706}
707
708- (NSNumber *) orderValue
709{
710    return [NSNumber numberWithInt: fOrderValue];
711}
712
713- (void) setOrderValue: (int) orderValue
714{
715    fOrderValue = orderValue;
716}
717
718- (NSArray *) fileList
719{
720    int count = fInfo->fileCount, i;
721    tr_file_t file;
722    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
723   
724    for (i = 0; i < count; i++)
725    {
726        file = fInfo->files[i];
727        [files addObject: [NSDictionary dictionaryWithObjectsAndKeys:
728            [[self downloadFolder] stringByAppendingPathComponent: [NSString stringWithUTF8String: file.name]], @"Name",
729            [NSNumber numberWithUnsignedLongLong: file.length], @"Size", nil]];
730    }
731   
732    return files;
733}
734
735- (NSDate *) date
736{
737    return fDate;
738}
739
740- (NSNumber *) stateSortKey
741{
742    if (![self isActive])
743        return [NSNumber numberWithInt: 0];
744    else if ([self isSeeding])
745        return [NSNumber numberWithInt: 1];
746    else
747        return [NSNumber numberWithInt: 2];
748}
749
750- (NSNumber *) progressSortKey
751{
752    //if finished downloading sort by ratio instead of progress
753    float progress = [self progress];
754    return [NSNumber numberWithFloat: progress < 1.0 ? progress : 2.0 + [self ratio]];
755}
756
757@end
758
759
760@implementation Torrent (Private)
761
762//if a hash is given, attempt to load that; otherwise, attempt to open file at path
763- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
764        privateTorrent: (NSNumber *) privateTorrent publicTorrent: (NSNumber *) publicTorrent
765        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
766        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
767        orderValue: (NSNumber *) orderValue
768{
769    if (!(self = [super init]))
770        return nil;
771
772    fLib = lib;
773    fDefaults = [NSUserDefaults standardUserDefaults];
774
775    fPrivateTorrent = privateTorrent ? [privateTorrent boolValue] : [fDefaults boolForKey: @"SavePrivateTorrent"];
776    fPublicTorrent = !fPrivateTorrent || (publicTorrent ? [publicTorrent boolValue]
777                                            : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
778
779    int error;
780    if (fPrivateTorrent && hashString)
781        fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error);
782   
783    if (!fHandle && path)
784        fHandle = tr_torrentInit(fLib, [path UTF8String], fPrivateTorrent ? TR_FSAVEPRIVATE : 0, & error);
785
786    if (!fHandle)
787    {
788        [self release];
789        return nil;
790    }
791   
792    fInfo = tr_torrentInfo( fHandle );
793
794    if (fPublicTorrent)
795        fPublicTorrentLocation = [path retain];
796
797    fDate = date ? [date retain] : [[NSDate alloc] init];
798   
799    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
800    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
801    fFinishedSeeding = NO;
802   
803    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
804    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
805    fError = NO;
806   
807    NSString * fileType = fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
808    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
809    [fIcon retain];
810   
811    fIconFlipped = [fIcon copy];
812    [fIconFlipped setFlipped: YES];
813   
814    fIconSmall = [fIconFlipped copy];
815    [fIconSmall setScalesWhenResized: YES];
816    [fIconSmall setSize: NSMakeSize(16.0, 16.0)];
817
818    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
819    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
820    fShortStatusString = [[NSMutableString alloc] initWithCapacity: 30];
821    fRemainingTimeString = [[NSMutableString alloc] initWithCapacity: 30];
822
823    [self update];
824    return self;
825}
826
827- (NSImage *) advancedBar
828{
829    int width = 324; //integers for bars
830   
831    NSBitmapImageRep * bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
832        pixelsWide: width pixelsHigh: BAR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
833        isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
834
835    int h, w;
836    uint32_t * p;
837    uint8_t * bitmapData = [bitmap bitmapData];
838    int bytesPerRow = [bitmap bytesPerRow];
839
840    int8_t * pieces = malloc(width);
841    [self getAvailability: pieces size: width];
842    int avail = 0;
843    for (w = 0; w < width; w++)
844        if (pieces[w] != 0)
845            avail++;
846
847    //first two lines: dark blue to show progression, green to show available
848    int end = lrintf(floor([self progress] * width));
849    p = (uint32_t *) bitmapData;
850
851    for (w = 0; w < end; w++)
852    {
853        p[w] = kBlue4;
854        p[w + bytesPerRow / 4] = kBlue4;
855    }
856    for (; w < avail; w++)
857    {
858        p[w] = kGreen;
859        p[w + bytesPerRow / 4] = kGreen;
860    }
861    for (; w < width; w++)
862    {
863        p[w] = kWhite;
864        p[w + bytesPerRow / 4] = kWhite;
865    }
866   
867    //lines 2 to 14: blue or grey depending on whether we have the piece or not
868    uint32_t color;
869    for( w = 0; w < width; w++ )
870    {
871        if (pieces[w] < 0)
872            color = kGreen;
873        else if (pieces[w] == 0)
874            color = kGray;
875        else if (pieces[w] == 1)
876            color = kBlue1;
877        else if (pieces[w] == 2)
878            color = kBlue2;
879        else
880            color = kBlue3;
881       
882        //point to pixel (w, 2) and draw "vertically"
883        p = (uint32_t *) ( bitmapData + 2 * bytesPerRow ) + w;
884        for( h = 2; h < BAR_HEIGHT; h++ )
885        {
886            p[0] = color;
887            p = (uint32_t *) ( (uint8_t *) p + bytesPerRow );
888        }
889    }
890
891    free(pieces);
892   
893    //actually draw image
894    NSImage * bar = [[NSImage alloc] initWithSize: [bitmap size]];
895    [bar addRepresentation: bitmap];
896    [bitmap release];
897   
898    [bar setScalesWhenResized: YES];
899   
900    return [bar autorelease];
901}
902
903- (void) trashFile: (NSString *) path
904{
905    //attempt to move to trash
906    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
907            source: [path stringByDeletingLastPathComponent] destination: @""
908            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
909    {
910        //if cannot trash, just delete it (will work if it is on a remote volume)
911        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
912            NSLog([@"Could not trash " stringByAppendingString: path]);
913    }
914}
915
916@end
Note: See TracBrowser for help on using the repository browser.