source: trunk/macosx/Torrent.m @ 994

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

Initial attempt at against the completeness of a specific piece.

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