source: trunk/macosx/Torrent.m @ 857

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

Change the advanced bar width a bit.

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