source: trunk/macosx/Torrent.m @ 960

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

Determine stats before originally starting torrent from history.

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