source: trunk/macosx/Torrent.m @ 1006

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

in info show the number of incoming connections next to total connections

  • Property svn:keywords set to Date Rev Author Id
File size: 27.5 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 1006 2006-10-13 18:58:12Z 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: (float *) 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- (int) totalPeersIncoming
687{
688    return fStat->peersIncoming;
689}
690
691- (int) totalPeersOutgoing
692{
693    return [self totalPeers] - [self totalPeersIncoming];
694}
695
696//peers uploading to you
697- (int) peersUploading
698{
699    return fStat->peersUploading;
700}
701
702//peers downloading from you
703- (int) peersDownloading
704{
705    return fStat->peersDownloading;
706}
707
708- (float) downloadRate
709{
710    return fStat->rateDownload;
711}
712
713- (float) uploadRate
714{
715    return fStat->rateUpload;
716}
717
718- (float) downloadedValid
719{
720    return [self progress] * [self size];
721}
722
723- (uint64_t) downloadedTotal
724{
725    return fStat->downloaded;
726}
727
728- (uint64_t) uploadedTotal
729{
730    return fStat->uploaded;
731}
732
733- (float) swarmSpeed
734{
735    return fStat->swarmspeed;
736}
737
738- (NSNumber *) orderValue
739{
740    return [NSNumber numberWithInt: fOrderValue];
741}
742
743- (void) setOrderValue: (int) orderValue
744{
745    fOrderValue = orderValue;
746}
747
748- (NSArray *) fileList
749{
750    int count = fInfo->fileCount, i;
751    tr_file_t file;
752    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
753   
754    for (i = 0; i < count; i++)
755    {
756        file = fInfo->files[i];
757        [files addObject: [NSDictionary dictionaryWithObjectsAndKeys:
758            [[self downloadFolder] stringByAppendingPathComponent: [NSString stringWithUTF8String: file.name]], @"Name",
759            [NSNumber numberWithUnsignedLongLong: file.length], @"Size", nil]];
760    }
761   
762    return files;
763}
764
765- (NSDate *) date
766{
767    return fDate;
768}
769
770- (NSNumber *) stateSortKey
771{
772    if (![self isActive])
773        return [NSNumber numberWithInt: 0];
774    else if ([self isSeeding])
775        return [NSNumber numberWithInt: 1];
776    else
777        return [NSNumber numberWithInt: 2];
778}
779
780- (NSNumber *) progressSortKey
781{
782    //if finished downloading sort by ratio instead of progress
783    float progress = [self progress];
784    return [NSNumber numberWithFloat: progress < 1.0 ? progress : 2.0 + [self ratio]];
785}
786
787@end
788
789
790@implementation Torrent (Private)
791
792//if a hash is given, attempt to load that; otherwise, attempt to open file at path
793- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
794        privateTorrent: (NSNumber *) privateTorrent publicTorrent: (NSNumber *) publicTorrent
795        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
796        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
797        orderValue: (NSNumber *) orderValue
798{
799    if (!(self = [super init]))
800        return nil;
801
802    fLib = lib;
803    fDefaults = [NSUserDefaults standardUserDefaults];
804
805    fPrivateTorrent = privateTorrent ? [privateTorrent boolValue] : [fDefaults boolForKey: @"SavePrivateTorrent"];
806    fPublicTorrent = !fPrivateTorrent || (publicTorrent ? [publicTorrent boolValue]
807                                            : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
808
809    int error;
810    if (fPrivateTorrent && hashString)
811        fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error);
812   
813    if (!fHandle && path)
814        fHandle = tr_torrentInit(fLib, [path UTF8String], fPrivateTorrent ? TR_FSAVEPRIVATE : 0, & error);
815
816    if (!fHandle)
817    {
818        [self release];
819        return nil;
820    }
821   
822    fInfo = tr_torrentInfo( fHandle );
823
824    if (fPublicTorrent)
825        fPublicTorrentLocation = [path retain];
826
827    fDate = date ? [date retain] : [[NSDate alloc] init];
828   
829    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
830    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
831    fFinishedSeeding = NO;
832   
833    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
834    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
835    fError = NO;
836   
837    NSString * fileType = fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
838    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
839    [fIcon retain];
840   
841    fIconFlipped = [fIcon copy];
842    [fIconFlipped setFlipped: YES];
843   
844    fIconSmall = [fIconFlipped copy];
845    [fIconSmall setScalesWhenResized: YES];
846    [fIconSmall setSize: NSMakeSize(16.0, 16.0)];
847
848    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
849    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
850    fShortStatusString = [[NSMutableString alloc] initWithCapacity: 30];
851    fRemainingTimeString = [[NSMutableString alloc] initWithCapacity: 30];
852   
853    //set up advanced bar
854    fBitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
855        pixelsWide: MAX_PIECES pixelsHigh: BAR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
856        isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
857   
858    fPieces = malloc(MAX_PIECES);
859    int i;
860    for (i = 0; i < MAX_PIECES; i++)
861        fPieces[i] = BLANK_PIECE;
862
863    [self update];
864    return self;
865}
866
867- (NSImage *) advancedBar
868{
869    int h, w;
870    uint32_t * p;
871    uint8_t * bitmapData = [fBitmap bitmapData];
872    int bytesPerRow = [fBitmap bytesPerRow];
873
874    int8_t * pieces = malloc(MAX_PIECES);
875    [self getAvailability: pieces size: MAX_PIECES];
876   
877    //lines 2 to 14: blue, green, or gray depending on whether we have the piece or not
878    int have = 0, avail = 0;
879    uint32_t color;
880    BOOL change;
881    for (w = 0; w < MAX_PIECES; w++)
882    {
883        change = NO;
884        if (pieces[w] < 0)
885        {
886            if (fPieces[w] != -1)
887            {
888                color = kBlue;
889                fPieces[w] = -1;
890                change = YES;
891            }
892            have++;
893        }
894        else if (pieces[w] == 0)
895        {
896            if (fPieces[w] != 0)
897            {
898                color = kGray;
899                fPieces[w] = 0;
900                change = YES;
901            }
902        }
903        else
904        {
905            if (pieces[w] == 1)
906            {
907                if (fPieces[w] != 1)
908                {
909                    color = kGreen1;
910                    fPieces[w] = 1;
911                    change = YES;
912                }
913            }
914            else if (pieces[w] == 2)
915            {
916                if (fPieces[w] != 2)
917                {
918                    color = kGreen2;
919                    fPieces[w] = 2;
920                    change = YES;
921                }
922            }
923            else
924            {
925                if (fPieces[w] != 3)
926                {
927                    color = kGreen3;
928                    fPieces[w] = 3;
929                    change = YES;
930                }
931            }
932            avail++;
933        }
934       
935        if (change)
936        {
937            //point to pixel (w, 2) and draw "vertically"
938            p = (uint32_t *)(bitmapData + 2 * bytesPerRow) + w;
939            for (h = 2; h < BAR_HEIGHT; h++)
940            {
941                p[0] = color;
942                p = (uint32_t *)((uint8_t *)p + bytesPerRow);
943            }
944        }
945    }
946   
947    //first two lines: dark blue to show progression, green to show available
948    p = (uint32_t *) bitmapData;
949    for (w = 0; w < have; w++)
950    {
951        p[w] = kBlue2;
952        p[w + bytesPerRow / 4] = kBlue2;
953    }
954    for (; w < avail + have; w++)
955    {
956        p[w] = kGreen3;
957        p[w + bytesPerRow / 4] = kGreen3;
958    }
959    for (; w < MAX_PIECES; w++)
960    {
961        p[w] = kWhite;
962        p[w + bytesPerRow / 4] = kWhite;
963    }
964   
965    free(pieces);
966   
967    //actually draw image
968    NSImage * bar = [[NSImage alloc] initWithSize: [fBitmap size]];
969    [bar addRepresentation: fBitmap];
970    [bar setScalesWhenResized: YES];
971   
972    return [bar autorelease];
973}
974
975- (void) trashFile: (NSString *) path
976{
977    //attempt to move to trash
978    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
979            source: [path stringByDeletingLastPathComponent] destination: @""
980            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
981    {
982        //if cannot trash, just delete it (will work if it is on a remote volume)
983        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
984            NSLog([@"Could not trash " stringByAppendingString: path]);
985    }
986}
987
988@end
Note: See TracBrowser for help on using the repository browser.