source: trunk/macosx/Torrent.m @ 993

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

if a transfer does not start because of not enough disk space, start next in queue

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