source: trunk/macosx/Torrent.m @ 861

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

Add Opera to the clients list.

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