source: trunk/macosx/Torrent.m @ 2255

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

get rid of a warning

  • Property svn:keywords set to Date Rev Author Id
File size: 60.3 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 2255 2007-06-30 21:53:45Z livings124 $
3 *
4 * Copyright (c) 2006-2007 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
33static int static_lastid = 0;
34
35@interface Torrent (Private)
36
37- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
38        publicTorrent: (NSNumber *) publicTorrent
39        downloadFolder: (NSString *) downloadFolder
40        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
41        dateAdded: (NSDate *) dateAdded dateCompleted: (NSDate *) dateCompleted
42        dateActivity: (NSDate *) dateActivity
43        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
44        limitSpeedCustom: (NSNumber *) limitCustom
45        checkUpload: (NSNumber *) checkUpload uploadLimit: (NSNumber *) uploadLimit
46        checkDownload: (NSNumber *) checkDownload downloadLimit: (NSNumber *) downloadLimit
47                pex: (NSNumber *) pex
48        waitToStart: (NSNumber *) waitToStart orderValue: (NSNumber *) orderValue
49        filesShouldDownload: (NSArray *) filesShouldDownload filePriorities: (NSArray *) filePriorities;
50- (void) historyFilePriorities: (NSMutableArray *) history forItems: (NSArray *) items;
51
52- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name;
53- (void) updateDownloadFolder;
54
55- (void) createFileListShouldDownload: (NSArray *) filesShouldDownload priorities: (NSArray *) filePriorities;
56- (void) insertPath: (NSMutableArray *) components forSiblings: (NSMutableArray *) siblings
57            withParent: (NSMutableDictionary *) parent previousPath: (NSString *) previousPath
58            flatList: (NSMutableArray *) flatList fileSize: (uint64_t) size index: (int) index priority: (int) priority;
59- (NSImage *) advancedBar;
60- (void) trashFile: (NSString *) path;
61
62@end
63
64@implementation Torrent
65
66// Used to optimize drawing. They contain packed RGBA pixels for every color needed.
67#define BE OSSwapBigToHostConstInt32
68
69static uint32_t kRed   = BE(0xFF6450FF), //255, 100, 80
70                kBlue = BE(0x50A0FFFF), //80, 160, 255
71                kBlue2 = BE(0x1E46B4FF), //30, 70, 180
72                kGray  = BE(0x969696FF), //150, 150, 150
73                kGreen1 = BE(0x99FFCCFF), //153, 255, 204
74                kGreen2 = BE(0x66FF99FF), //102, 255, 153
75                kGreen3 = BE(0x00FF66FF), //0, 255, 102
76                kWhite = BE(0xFFFFFFFF); //255, 255, 255
77
78- (id) initWithPath: (NSString *) path location: (NSString *) location forceDeleteTorrent: (BOOL) delete lib: (tr_handle_t *) lib
79{
80    self = [self initWithHash: nil path: path lib: lib
81            publicTorrent: delete ? [NSNumber numberWithBool: NO] : nil
82            downloadFolder: location
83            useIncompleteFolder: nil incompleteFolder: nil
84            dateAdded: nil dateCompleted: nil
85            dateActivity: nil
86            ratioSetting: nil ratioLimit: nil
87            limitSpeedCustom: nil
88            checkUpload: nil uploadLimit: nil
89            checkDownload: nil downloadLimit: nil
90                        pex: nil
91            waitToStart: nil orderValue: nil
92            filesShouldDownload: nil filePriorities: nil];
93   
94    if (self)
95    {
96        if (!fPublicTorrent)
97            [self trashFile: path];
98    }
99    return self;
100}
101
102- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle_t *) lib
103{
104    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
105                path: [history objectForKey: @"TorrentPath"] lib: lib
106                publicTorrent: [history objectForKey: @"PublicCopy"]
107                downloadFolder: [history objectForKey: @"DownloadFolder"]
108                useIncompleteFolder: [history objectForKey: @"UseIncompleteFolder"]
109                incompleteFolder: [history objectForKey: @"IncompleteFolder"]
110                dateAdded: [history objectForKey: @"Date"]
111                                dateCompleted: [history objectForKey: @"DateCompleted"]
112                dateActivity: [history objectForKey: @"DateActivity"]
113                ratioSetting: [history objectForKey: @"RatioSetting"]
114                ratioLimit: [history objectForKey: @"RatioLimit"]
115                limitSpeedCustom: [history objectForKey: @"LimitSpeedCustom"]
116                checkUpload: [history objectForKey: @"CheckUpload"]
117                uploadLimit: [history objectForKey: @"UploadLimit"]
118                checkDownload: [history objectForKey: @"CheckDownload"]
119                downloadLimit: [history objectForKey: @"DownloadLimit"]
120                                pex: [history objectForKey: @"Pex"]
121                waitToStart: [history objectForKey: @"WaitToStart"]
122                orderValue: [history objectForKey: @"OrderValue"]
123                filesShouldDownload: [history objectForKey: @"FilesShouldDownload"]
124                filePriorities: [history objectForKey: @"FilePriorities"]];
125   
126    if (self)
127    {
128        //start transfer
129        NSNumber * active;
130        if ((active = [history objectForKey: @"Active"]) && [active boolValue])
131        {
132            fStat = tr_torrentStat(fHandle);
133            [self startTransfer];
134        }
135    }
136    return self;
137}
138
139- (NSDictionary *) history
140{
141    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
142                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
143                    [self hashString], @"TorrentHash",
144                    fDownloadFolder, @"DownloadFolder",
145                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
146                    [NSNumber numberWithBool: [self isActive]], @"Active",
147                    fDateAdded, @"Date",
148                    [NSNumber numberWithInt: fRatioSetting], @"RatioSetting",
149                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
150                    [NSNumber numberWithInt: fCheckUpload], @"CheckUpload",
151                    [NSNumber numberWithInt: fUploadLimit], @"UploadLimit",
152                    [NSNumber numberWithInt: fCheckDownload], @"CheckDownload",
153                    [NSNumber numberWithInt: fDownloadLimit], @"DownloadLimit",
154                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
155                    [self orderValue], @"OrderValue",
156                    nil];
157   
158    if (fIncompleteFolder)
159        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
160   
161    //set file should download
162    int fileCount = [self fileCount];
163    NSMutableArray * filesShouldDownload = [NSMutableArray arrayWithCapacity: fileCount];
164   
165    tr_priority_t * priorities = tr_torrentGetFilePriorities(fHandle);
166    int i;
167    for (i = 0; i < fileCount; i++)
168        [filesShouldDownload addObject: [NSNumber numberWithBool: priorities[i] != TR_PRI_DND]];
169    free(priorities);
170    [history setObject: filesShouldDownload forKey: @"FilesShouldDownload"];
171   
172    //set file priorities
173    NSMutableArray * filePriorities = [NSMutableArray arrayWithCapacity: fileCount];
174    [self historyFilePriorities: filePriorities forItems: fFileList];
175    [history setObject: filePriorities forKey: @"FilePriorities"];
176
177    if (fPublicTorrent)
178        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
179       
180        if (![self privateTorrent])
181                [history setObject: [NSNumber numberWithBool: fPex] forKey: @"Pex"];
182       
183        if (fDateCompleted)
184                [history setObject: fDateCompleted forKey: @"DateCompleted"];
185   
186    NSDate * dateActivity = [self dateActivity];
187    if (dateActivity)
188                [history setObject: dateActivity forKey: @"DateActivity"];
189       
190    return history;
191}
192
193- (void) dealloc
194{
195    if (fHandle)
196    {
197        tr_torrentClose(fHandle);
198       
199        if (fDownloadFolder)
200            [fDownloadFolder release];
201        if (fIncompleteFolder)
202            [fIncompleteFolder release];
203       
204        if (fPublicTorrentLocation)
205            [fPublicTorrentLocation release];
206       
207        [fDateAdded release];
208                if (fDateCompleted)
209                        [fDateCompleted release];
210        if (fDateActivity)
211                        [fDateActivity release];
212       
213        if (fAnnounceDate)
214            [fAnnounceDate release];
215       
216        [fIcon release];
217        [fIconFlipped release];
218        [fIconSmall release];
219       
220        [fProgressString release];
221        [fStatusString release];
222        [fShortStatusString release];
223        [fRemainingTimeString release];
224       
225        [fFileList release];
226        [fFlatFileList release];
227       
228        [fBitmap release];
229        free(fPieces);
230    }
231    [super dealloc];
232}
233
234- (void) removeTorrent
235{
236    tr_torrentRemoveSaved(fHandle);
237}
238
239- (void) changeIncompleteDownloadFolder: (NSString *) folder
240{
241    fUseIncompleteFolder = folder != nil;
242    if (fIncompleteFolder)
243    {
244        [fIncompleteFolder release];
245        fIncompleteFolder = nil;
246    }
247   
248    if (folder)
249        fIncompleteFolder = [folder retain];
250   
251    [self updateDownloadFolder];
252}
253
254- (void) changeDownloadFolder: (NSString *) folder
255{
256    if (fDownloadFolder)
257        [fDownloadFolder release];
258    fDownloadFolder = [folder retain];
259   
260    [self updateDownloadFolder];
261}
262
263- (NSString *) downloadFolder
264{
265    return [NSString stringWithUTF8String: tr_torrentGetFolder(fHandle)];
266}
267
268- (void) getAvailability: (int8_t *) tab size: (int) size
269{
270    tr_torrentAvailability(fHandle, tab, size);
271}
272
273- (void) getAmountFinished: (float *) tab size: (int) size
274{
275    tr_torrentAmountFinished(fHandle, tab, size);
276}
277
278- (void) update
279{
280    fStat = tr_torrentStat(fHandle);
281   
282    //notification when downloading finished
283    if (tr_getComplete(fHandle) || tr_getDone(fHandle))
284    {
285        BOOL canMove = YES;
286       
287        //move file from incomplete folder to download folder
288        if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
289            && (canMove = [self alertForMoveFolderAvailable]))
290        {
291            //pause without actually stopping
292            tr_setUseCustomUpload(fHandle, 1);
293            tr_setUploadLimit(fHandle, 0);
294           
295            tr_setUseCustomDownload(fHandle, 1);
296            tr_setDownloadLimit(fHandle, 0);
297           
298            if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
299                                    toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
300                [self updateDownloadFolder];
301           
302            [self updateSpeedSetting];
303        }
304       
305        if (!canMove)
306        {
307            fUseIncompleteFolder = NO;
308           
309            [fDownloadFolder release];
310            fDownloadFolder = fIncompleteFolder;
311            fIncompleteFolder = nil;
312        }
313               
314                if (fDateCompleted)
315                        [fDateCompleted release];
316                fDateCompleted = [[NSDate alloc] init];
317       
318        fStat = tr_torrentStat(fHandle);
319        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
320    }
321    else if (tr_getIncomplete(fHandle))
322        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
323    else;
324   
325    //check to stop for ratio
326    float stopRatio;
327    if ([self isSeeding] && (stopRatio = [self actualStopRatio]) != INVALID && [self ratio] >= stopRatio)
328    {
329        [self stopTransfer];
330        fStat = tr_torrentStat(fHandle);
331       
332        fFinishedSeeding = YES;
333       
334        [self setRatioSetting: NSOffState];
335        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
336    }
337       
338        NSMutableString * progressString = [NSMutableString stringWithString: @""],
339                                        * remainingTimeString = [NSMutableString stringWithString: @""],
340                                        * statusString = [NSMutableString string],
341                                        * shortStatusString = [NSMutableString string];
342
343    if (![self allDownloaded])
344        [progressString appendFormat: NSLocalizedString(@"%@ of %@ (%.2f%%)", "Torrent -> progress string"),
345                            [NSString stringForFileSize: [self downloadedValid]],
346                            [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
347    else if ([self progress] < 1.0)
348        [progressString appendFormat: NSLocalizedString(@"%@ of %@ (%.2f%%), uploaded %@ (Ratio: %@)",
349                "Torrent -> progress string"),
350                [NSString stringForFileSize: [self downloadedValid]], [NSString stringForFileSize: [self size]],
351                100.0 * [self progress], [NSString stringForFileSize: [self uploadedTotal]],
352                [NSString stringForRatio: [self ratio]]];
353    else
354        [progressString appendFormat: NSLocalizedString(@"%@, uploaded %@ (Ratio: %@)", "Torrent -> progress string"),
355                [NSString stringForFileSize: [self size]], [NSString stringForFileSize: [self uploadedTotal]],
356                [NSString stringForRatio: [self ratio]]];
357
358    BOOL wasChecking = fChecking;
359    fChecking = NO;
360    switch (fStat->status)
361    {
362        NSString * tempString;
363       
364        case TR_STATUS_STOPPED:
365            if (fWaitToStart)
366            {
367                tempString = ![self allDownloaded]
368                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
369                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
370            }
371            else if (fFinishedSeeding)
372                tempString = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
373            else
374                tempString = NSLocalizedString(@"Paused", "Torrent -> status string");
375           
376            [statusString setString: tempString];
377            [shortStatusString setString: tempString];
378           
379            break;
380
381        case TR_STATUS_CHECK_WAIT:
382            tempString = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string")
383                            stringByAppendingEllipsis];
384           
385            [statusString setString: tempString];
386            [shortStatusString setString: tempString];
387            [remainingTimeString setString: tempString];
388           
389            fChecking = YES;
390           
391            break;
392
393        case TR_STATUS_CHECK:
394            tempString = [NSLocalizedString(@"Checking existing data", "Torrent -> status string") stringByAppendingEllipsis];
395           
396            [statusString setString: tempString];
397            [shortStatusString setString: tempString];
398            [remainingTimeString setString: tempString];
399           
400            fChecking = YES;
401           
402            break;
403
404        case TR_STATUS_DOWNLOAD:
405            [statusString setString: @""];
406            if ([self totalPeers] != 1)
407                [statusString appendFormat: NSLocalizedString(@"Downloading from %d of %d peers",
408                                                "Torrent -> status string"), [self peersUploading], [self totalPeers]];
409            else
410                [statusString appendFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
411                                                "Torrent -> status string"), [self peersUploading]];
412           
413            int eta = [self eta];
414            if (eta < 0)
415            {
416                [remainingTimeString setString: NSLocalizedString(@"Unknown", "Torrent -> remaining time")];
417                [progressString appendString: NSLocalizedString(@" - remaining time unknown", "Torrent -> progress string")];
418            }
419            else
420            {
421                if (eta < 60)
422                    [remainingTimeString appendFormat: NSLocalizedString(@"%d sec", "Torrent -> remaining time"), eta];
423                else if (eta < 3600) //60 * 60
424                    [remainingTimeString appendFormat: NSLocalizedString(@"%d min %d sec", "Torrent -> remaining time"),
425                                                            eta / 60, eta % 60];
426                else if (eta < 86400) //24 * 60 * 60
427                    [remainingTimeString appendFormat: NSLocalizedString(@"%d hr %d min", "Torrent -> remaining time"),
428                                                            eta / 3600, (eta / 60) % 60];
429                else
430                {
431                                        int days = eta / 86400;
432                    if (days > 1)
433                        [remainingTimeString appendFormat: NSLocalizedString(@"%d days %d hr", "Torrent -> remaining time"),
434                                                                days, (eta / 3600) % 24];
435                    else
436                        [remainingTimeString appendFormat: NSLocalizedString(@"1 day %d hr", "Torrent -> remaining time"),
437                                                                (eta / 3600) % 24];
438                }
439               
440                [progressString appendFormat: NSLocalizedString(@" - %@ remaining", "Torrent -> progress string"),
441                                                                    remainingTimeString];
442            }
443           
444            break;
445
446        case TR_STATUS_SEED:
447        case TR_STATUS_DONE:
448            [statusString setString: @""];
449            if ([self totalPeers] != 1)
450                [statusString appendFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
451                                                [self peersDownloading], [self totalPeers]];
452            else
453                [statusString appendFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
454                                                [self peersDownloading]];
455           
456            break;
457
458        case TR_STATUS_STOPPING:
459            tempString = [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
460       
461            [statusString setString: tempString];
462            [shortStatusString setString: tempString];
463           
464            break;
465    }
466   
467    //check for error
468    BOOL wasError = fError;
469    fError = [self isError];
470   
471    //check if stalled
472    BOOL wasStalled = fStalled;
473    fStalled = [self isActive] && [fDefaults boolForKey: @"CheckStalled"]
474                && [fDefaults integerForKey: @"StalledMinutes"] < [self stalledMinutes];
475   
476    //create strings for error or stalled
477    if (fError)
478        [statusString setString: [NSLocalizedString(@"Error: ", "Torrent -> status string")
479                                    stringByAppendingString: [self errorMessage]]];
480    else if (fStalled)
481        [statusString setString: [NSLocalizedString(@"Stalled, ", "Torrent -> status string")
482                                    stringByAppendingString: statusString]];
483    else;
484   
485    //update queue for checking (from downloading to seeding), stalled, or error
486    if ((wasChecking && !fChecking) || (!wasStalled && fStalled) || (!wasError && fError && [self isActive]))
487        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
488
489    if ([self isActive] && ![self isChecking])
490    {
491        NSString * stringToAppend = @"";
492        if (![self allDownloaded])
493        {
494            stringToAppend = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, ", "Torrent -> status string"),
495                                [NSString stringForSpeed: [self downloadRate]]];
496            [shortStatusString setString: @""];
497        }
498        else
499        {
500            NSString * ratioString = [NSString stringForRatio: [self ratio]];
501       
502            [shortStatusString setString: [NSString stringWithFormat: NSLocalizedString(@"Ratio: %@, ",
503                                            "Torrent -> status string"), ratioString]];
504            [remainingTimeString setString: [NSLocalizedString(@"Ratio: ", "Torrent -> status string")
505                                                stringByAppendingString: ratioString]];
506        }
507       
508        stringToAppend = [stringToAppend stringByAppendingString: [NSLocalizedString(@"UL: ", "Torrent -> status string")
509                                            stringByAppendingString: [NSString stringForSpeed: [self uploadRate]]]];
510
511        [statusString appendFormat: @" - %@", stringToAppend];
512        [shortStatusString appendString: stringToAppend];
513    }
514       
515        [fProgressString setString: progressString];
516        [fStatusString setString: statusString];
517        [fShortStatusString setString: shortStatusString];
518        [fRemainingTimeString setString: remainingTimeString];
519}
520
521- (NSDictionary *) infoForCurrentView
522{
523    NSMutableDictionary * info = [NSMutableDictionary dictionaryWithObjectsAndKeys:
524                                    [self name], @"Name",
525                                    [NSNumber numberWithBool: [self isSeeding]], @"Seeding",
526                                    [NSNumber numberWithFloat: [self progress]], @"Progress",
527                                    [NSNumber numberWithFloat: (float)fStat->left/[self size]], @"Left",
528                                    [NSNumber numberWithBool: [self isActive]], @"Active",
529                                    [NSNumber numberWithBool: [self isError]], @"Error", nil];
530   
531    if ([self isSeeding])
532        [info setObject: [NSNumber numberWithFloat: [self progressStopRatio]] forKey: @"ProgressStopRatio"];
533   
534    if (![fDefaults boolForKey: @"SmallView"])
535    {
536        [info setObject: fIconFlipped forKey: @"Icon"];
537        [info setObject: [self progressString] forKey: @"ProgressString"];
538        [info setObject: [self statusString] forKey: @"StatusString"];
539    }
540    else
541    {
542        [info setObject: fIconSmall forKey: @"Icon"];
543        [info setObject: [self remainingTimeString] forKey: @"RemainingTimeString"];
544        [info setObject: [self shortStatusString] forKey: @"ShortStatusString"];
545    }
546   
547    if ([fDefaults boolForKey: @"UseAdvancedBar"])
548        [info setObject: [self advancedBar] forKey: @"AdvancedBar"];
549   
550    return info;
551}
552
553- (void) startTransfer
554{
555    fWaitToStart = NO;
556    fFinishedSeeding = NO;
557   
558    if (![self isActive] && [self alertForFolderAvailable] && [self alertForRemainingDiskSpace])
559    {
560        tr_torrentStart(fHandle);
561        [self update];
562    }
563}
564
565- (void) stopTransfer
566{
567    fError = NO;
568    fWaitToStart = NO;
569   
570    if ([self isActive])
571    {
572        tr_torrentStop(fHandle);
573        [self update];
574
575        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
576    }
577}
578
579- (void) sleep
580{
581    if ((fResumeOnWake = [self isActive]))
582        tr_torrentStop(fHandle);
583}
584
585- (void) wakeUp
586{
587    if (fResumeOnWake)
588        tr_torrentStart(fHandle);
589}
590
591- (void) announce
592{
593    if (![self isActive])
594        return;
595   
596    tr_manualUpdate(fHandle);
597   
598    if (fAnnounceDate)
599        [fAnnounceDate release];
600    fAnnounceDate = [[NSDate date] retain];
601}
602
603- (NSDate *) announceDate
604{
605    return fAnnounceDate;
606}
607
608- (void) resetCache
609{
610    tr_torrentRecheck(fHandle);
611}
612
613- (float) ratio
614{
615    return fStat->ratio;
616}
617
618- (int) ratioSetting
619{
620    return fRatioSetting;
621}
622
623- (void) setRatioSetting: (int) setting
624{
625    fRatioSetting = setting;
626}
627
628- (float) ratioLimit
629{
630    return fRatioLimit;
631}
632
633- (void) setRatioLimit: (float) limit
634{
635    if (limit >= 0)
636        fRatioLimit = limit;
637}
638
639- (float) actualStopRatio
640{
641    if (fRatioSetting == NSOnState)
642        return fRatioLimit;
643    else if (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"])
644        return [fDefaults floatForKey: @"RatioLimit"];
645    else
646        return INVALID;
647}
648
649- (float) progressStopRatio
650{
651    float stopRatio, ratio;
652    if ((stopRatio = [self actualStopRatio]) == INVALID || (ratio = [self ratio]) >= stopRatio)
653        return 1.0;
654    else if (ratio > 0 && stopRatio > 0)
655        return ratio / stopRatio;
656    else
657        return 0;
658}
659
660- (int) checkUpload
661{
662    return fCheckUpload;
663}
664
665- (void) setCheckUpload: (int) setting
666{
667    fCheckUpload = setting;
668    [self updateSpeedSetting];
669}
670
671- (int) uploadLimit
672{
673    return fUploadLimit;
674}
675
676- (void) setUploadLimit: (int) limit
677{
678    fUploadLimit = limit;
679    [self updateSpeedSetting];
680}
681
682- (int) checkDownload
683{
684    return fCheckDownload;
685}
686
687- (void) setCheckDownload: (int) setting
688{
689    fCheckDownload = setting;
690    [self updateSpeedSetting];
691}
692
693- (int) downloadLimit
694{
695    return fDownloadLimit;
696}
697
698- (void) setDownloadLimit: (int) limit
699{
700    fDownloadLimit = limit;
701    [self updateSpeedSetting];
702}
703
704- (void) updateSpeedSetting
705{
706    tr_setUseCustomUpload(fHandle, fCheckUpload != NSMixedState);
707    tr_setUploadLimit(fHandle, fCheckUpload == NSOnState ? fUploadLimit : -1);
708   
709    tr_setUseCustomDownload(fHandle, fCheckDownload != NSMixedState);
710    tr_setDownloadLimit(fHandle, fCheckDownload == NSOnState ? fDownloadLimit : -1);
711}
712
713- (void) setWaitToStart: (BOOL) wait
714{
715    fWaitToStart = wait;
716}
717
718- (BOOL) waitingToStart
719{
720    return fWaitToStart;
721}
722
723- (void) revealData
724{
725    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
726}
727
728- (void) revealPublicTorrent
729{
730    if (fPublicTorrent)
731        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
732}
733
734- (void) trashData
735{
736    [self trashFile: [self dataLocation]];
737}
738
739- (void) trashTorrent
740{
741    if (fPublicTorrent)
742        [self trashFile: [self publicTorrentLocation]];
743}
744
745- (void) moveTorrentDataFileTo: (NSString *) folder
746{
747    NSString * oldFolder = [self downloadFolder];
748    if (![oldFolder isEqualToString: folder] || ![fDownloadFolder isEqualToString: folder])
749    {
750        //check if moving inside itself
751        NSArray * oldComponents = [oldFolder pathComponents],
752                * newComponents = [folder pathComponents];
753        int count;
754       
755        if ((count = [oldComponents count]) < [newComponents count]
756                && [[newComponents objectAtIndex: count] isEqualToString: [self name]]
757                && [oldComponents isEqualToArray:
758                        [newComponents objectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, count)]]])
759        {
760            NSAlert * alert = [[NSAlert alloc] init];
761            [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.",
762                                                        "Move inside itself alert -> title")];
763            [alert setInformativeText: [NSString stringWithFormat:
764                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
765                                                "Move inside itself alert -> message"), [self name]]];
766            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")];
767           
768            [alert runModal];
769            [alert release];
770           
771            return;
772        }
773       
774        //pause without actually stopping
775        tr_setDownloadLimit(fHandle, 0);
776        tr_setUploadLimit(fHandle, 0);
777       
778        if ([[NSFileManager defaultManager] movePath: [oldFolder stringByAppendingPathComponent: [self name]]
779                            toPath: [folder stringByAppendingPathComponent: [self name]] handler: nil])
780        {
781            //get rid of both incomplete folder and old download folder, even if move failed
782            fUseIncompleteFolder = NO;
783            if (fIncompleteFolder)
784            {
785                [fIncompleteFolder release];
786                fIncompleteFolder = nil;
787            }
788            [self changeDownloadFolder: folder];
789           
790            [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
791           
792            [self updateSpeedSetting];
793        }
794        else
795        {
796            [self updateSpeedSetting]; //restart before showing the alert
797       
798            NSAlert * alert = [[NSAlert alloc] init];
799            [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")];
800            [alert setInformativeText: [NSString stringWithFormat:
801                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
802                                                "Move error alert -> message"), [self name]]];
803            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")];
804           
805            [alert runModal];
806            [alert release];
807        }
808    }
809}
810
811- (void) copyTorrentFileTo: (NSString *) path
812{
813    [[NSFileManager defaultManager] copyPath: [self torrentLocation] toPath: path handler: nil];
814}
815
816- (BOOL) alertForRemainingDiskSpace
817{
818    if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"])
819        return YES;
820   
821    NSString * volumeName;
822    if ((volumeName = [[[NSFileManager defaultManager] componentsToDisplayForPath: [self downloadFolder]] objectAtIndex: 0]))
823    {
824        NSDictionary * fsAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath: [self downloadFolder]];
825        uint64_t remainingSpace = [[fsAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue];
826       
827        if (remainingSpace <= fStat->left)
828        {
829            NSAlert * alert = [[NSAlert alloc] init];
830            [alert setMessageText: [NSString stringWithFormat:
831                                    NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
832                                        "Torrent file disk space alert -> title"), [self name]]];
833            [alert setInformativeText: [NSString stringWithFormat:
834                            NSLocalizedString(@"The transfer will be paused. Clear up space on \"%@\" to continue.",
835                                                "Torrent file disk space alert -> message"), volumeName]];
836            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file disk space alert -> button")];
837            [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent file disk space alert -> button")];
838            [alert addButtonWithTitle: NSLocalizedString(@"Always Download", "Torrent file disk space alert -> button")];
839           
840            int result = [alert runModal];
841            [alert release];
842           
843            if (result == NSAlertThirdButtonReturn)
844                [fDefaults setBool: NO forKey: @"WarningRemainingSpace"];
845           
846            return result != NSAlertFirstButtonReturn;
847        }
848    }
849    return YES;
850}
851
852- (BOOL) alertForFolderAvailable
853{
854    if (access(tr_torrentGetFolder(fHandle), 0))
855    {
856        NSAlert * alert = [[NSAlert alloc] init];
857        [alert setMessageText: [NSString stringWithFormat:
858                                NSLocalizedString(@"The folder for downloading \"%@\" cannot be found.",
859                                    "Folder cannot be found alert -> title"), [self name]]];
860        [alert setInformativeText: [NSString stringWithFormat:
861                        NSLocalizedString(@"\"%@\" cannot be found. The transfer will be paused.",
862                                            "Folder cannot be found alert -> message"), [self downloadFolder]]];
863        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Folder cannot be found alert -> button")];
864        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Location",
865                                    "Folder cannot be found alert -> location button") stringByAppendingEllipsis]];
866       
867        if ([alert runModal] != NSAlertFirstButtonReturn)
868        {
869            NSOpenPanel * panel = [NSOpenPanel openPanel];
870           
871            [panel setPrompt: NSLocalizedString(@"Select", "Folder cannot be found alert -> prompt")];
872            [panel setAllowsMultipleSelection: NO];
873            [panel setCanChooseFiles: NO];
874            [panel setCanChooseDirectories: YES];
875            [panel setCanCreateDirectories: YES];
876
877            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
878                                "Folder cannot be found alert -> select destination folder"), [self name]]];
879           
880            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
881            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
882                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
883        }
884       
885        [alert release];
886       
887        return NO;
888    }
889   
890    return YES;
891}
892
893- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) context
894{
895    if (code != NSOKButton)
896        return;
897   
898    NSString * folder = [[openPanel filenames] objectAtIndex: 0];
899    if (fUseIncompleteFolder)
900        [self changeDownloadFolder: folder];
901    else
902        [self changeDownloadFolder: folder];
903   
904    [self startTransfer];
905    [self update];
906   
907    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
908}
909
910- (BOOL) alertForMoveFolderAvailable
911{
912    if (access([fDownloadFolder UTF8String], 0))
913    {
914        NSAlert * alert = [[NSAlert alloc] init];
915        [alert setMessageText: [NSString stringWithFormat:
916                                NSLocalizedString(@"The folder for moving the completed \"%@\" cannot be found.",
917                                    "Move folder cannot be found alert -> title"), [self name]]];
918        [alert setInformativeText: [NSString stringWithFormat:
919                                NSLocalizedString(@"\"%@\" cannot be found. The file will remain in its current location.",
920                                    "Move folder cannot be found alert -> message"), fDownloadFolder]];
921        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move folder cannot be found alert -> button")];
922       
923        [alert runModal];
924        [alert release];
925       
926        return NO;
927    }
928   
929    return YES;
930}
931
932- (NSImage *) icon
933{
934    return fIcon;
935}
936
937- (NSImage *) iconFlipped
938{
939    return fIconFlipped;
940}
941
942- (NSImage *) iconSmall
943{
944    return fIconSmall;
945}
946
947- (NSString *) name
948{
949    return [NSString stringWithUTF8String: fInfo->name];
950}
951
952- (uint64_t) size
953{
954    return fInfo->totalSize;
955}
956
957- (NSString *) trackerAddress
958{
959    return [NSString stringWithFormat: @"http://%s:%d", fStat->tracker->address, fStat->tracker->port];
960}
961
962- (NSString *) trackerAddressAnnounce
963{
964    return [NSString stringWithUTF8String: fStat->tracker->announce];
965}
966
967- (NSString *) comment
968{
969    return [NSString stringWithUTF8String: fInfo->comment];
970}
971
972- (NSString *) creator
973{
974    return [NSString stringWithUTF8String: fInfo->creator];
975}
976
977- (NSDate *) dateCreated
978{
979    int date = fInfo->dateCreated;
980    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
981}
982
983- (int) pieceSize
984{
985    return fInfo->pieceSize;
986}
987
988- (int) pieceCount
989{
990    return fInfo->pieceCount;
991}
992
993- (NSString *) hashString
994{
995    return [NSString stringWithUTF8String: fInfo->hashString];
996}
997
998- (BOOL) privateTorrent
999{
1000    return TR_FLAG_PRIVATE & fInfo->flags;
1001}
1002
1003- (NSString *) torrentLocation
1004{
1005    return [NSString stringWithUTF8String: fInfo->torrent];
1006}
1007
1008- (NSString *) publicTorrentLocation
1009{
1010    return fPublicTorrentLocation;
1011}
1012
1013- (NSString *) dataLocation
1014{
1015    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
1016}
1017
1018- (BOOL) publicTorrent
1019{
1020    return fPublicTorrent;
1021}
1022
1023- (NSString *) stateString
1024{
1025    switch( fStat->status )
1026    {
1027        case TR_STATUS_STOPPED:
1028            return NSLocalizedString(@"Paused", "Torrent -> status string");
1029            break;
1030
1031        case TR_STATUS_CHECK:
1032            return [NSLocalizedString(@"Checking existing data", "Torrent -> status string") stringByAppendingEllipsis];
1033            break;
1034
1035        case TR_STATUS_DOWNLOAD:
1036            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1037            break;
1038
1039        case TR_STATUS_SEED:
1040        case TR_STATUS_DONE:
1041            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1042            break;
1043
1044        case TR_STATUS_STOPPING:
1045            return [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
1046            break;
1047       
1048        default:
1049            return NSLocalizedString(@"N/A", "Torrent -> status string");
1050    }
1051}
1052
1053- (float) progress
1054{
1055    return fStat->percentComplete;
1056}
1057
1058- (float) progressDone
1059{
1060    return fStat->percentDone;
1061}
1062
1063- (int) eta
1064{
1065    return fStat->eta;
1066}
1067
1068- (BOOL) isActive
1069{
1070    return fStat->status & TR_STATUS_ACTIVE;
1071}
1072
1073- (BOOL) isSeeding
1074{
1075    return fStat->status == TR_STATUS_SEED || fStat->status == TR_STATUS_DONE;
1076}
1077
1078- (BOOL) isPaused
1079{
1080    return fStat->status == TR_STATUS_STOPPED;
1081}
1082
1083- (BOOL) isChecking
1084{
1085    return fStat->status == TR_STATUS_CHECK || fStat->status == TR_STATUS_CHECK_WAIT;
1086}
1087
1088- (BOOL) allDownloaded
1089{
1090    return fStat->cpStatus != TR_CP_INCOMPLETE;
1091}
1092
1093- (BOOL) isError
1094{
1095    return fStat->error != 0;
1096}
1097
1098- (NSString *) errorMessage
1099{
1100    if (![self isError])
1101        return @"";
1102   
1103    NSString * error;
1104    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
1105        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
1106        error = NSLocalizedString(@"(unreadable error)", "Torrent -> error string unreadable");
1107   
1108    return error;
1109}
1110
1111- (NSArray *) peers
1112{
1113    int totalPeers, i;
1114    tr_peer_stat_t * peers = tr_torrentPeers(fHandle, & totalPeers);
1115   
1116    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
1117    NSMutableDictionary * dic;
1118   
1119    tr_peer_stat_t * peer;
1120    for (i = 0; i < totalPeers; i++)
1121    {
1122        peer = &peers[i];
1123       
1124        dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
1125            [NSNumber numberWithBool: peer->isConnected], @"Connected",
1126            [NSNumber numberWithInt: peer->from], @"From",
1127            [NSString stringWithCString: (char *) peer->addr encoding: NSUTF8StringEncoding], @"IP",
1128            [NSNumber numberWithInt: peer->port], @"Port", nil];
1129       
1130        if (peer->isConnected)
1131        {
1132            [dic setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
1133           
1134            if (peer->isDownloading)
1135                [dic setObject: [NSNumber numberWithFloat: peer->uploadToRate] forKey: @"UL To Rate"];
1136            if (peer->isUploading)
1137                [dic setObject: [NSNumber numberWithFloat: peer->downloadFromRate] forKey: @"DL From Rate"];
1138           
1139            [dic setObject: [NSString stringWithCString: (char *) peer->client encoding: NSUTF8StringEncoding] forKey: @"Client"];
1140        }
1141        else
1142            [dic setObject: @"" forKey: @"Client"];
1143       
1144        [peerDics addObject: dic];
1145    }
1146   
1147    tr_torrentPeersFree(peers, totalPeers);
1148   
1149    return peerDics;
1150}
1151
1152- (NSString *) progressString
1153{
1154    return fProgressString;
1155}
1156
1157- (NSString *) statusString
1158{
1159    return fStatusString;
1160}
1161
1162- (NSString *) shortStatusString
1163{
1164    return fShortStatusString;
1165}
1166
1167- (NSString *) remainingTimeString
1168{
1169    return fRemainingTimeString;
1170}
1171
1172- (int) seeders
1173{
1174    return fStat->seeders;
1175}
1176
1177- (int) leechers
1178{
1179    return fStat->leechers;
1180}
1181
1182- (int) completedFromTracker
1183{
1184    return fStat->completedFromTracker;
1185}
1186
1187- (int) totalPeers
1188{
1189    return fStat->peersTotal;
1190}
1191
1192- (int) totalPeersTracker
1193{
1194    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1195}
1196
1197- (int) totalPeersIncoming
1198{
1199    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1200}
1201
1202- (int) totalPeersCache
1203{
1204    return fStat->peersFrom[TR_PEER_FROM_CACHE];
1205}
1206
1207- (int) totalPeersPex
1208{
1209    return fStat->peersFrom[TR_PEER_FROM_PEX];
1210}
1211
1212//peers uploading to you
1213- (int) peersUploading
1214{
1215    return fStat->peersUploading;
1216}
1217
1218//peers downloading from you
1219- (int) peersDownloading
1220{
1221    return fStat->peersDownloading;
1222}
1223
1224- (float) downloadRate
1225{
1226    return fStat->rateDownload;
1227}
1228
1229- (float) uploadRate
1230{
1231    return fStat->rateUpload;
1232}
1233
1234- (uint64_t) downloadedValid
1235{
1236    return fStat->downloadedValid;
1237}
1238
1239- (uint64_t) downloadedTotal
1240{
1241    return fStat->downloaded;
1242}
1243
1244- (uint64_t) uploadedTotal
1245{
1246    return fStat->uploaded;
1247}
1248
1249- (float) swarmSpeed
1250{
1251    return fStat->swarmspeed;
1252}
1253
1254- (BOOL) pex
1255{
1256        return fPex;
1257}
1258
1259- (void) setPex: (BOOL) setting
1260{
1261        if (![self privateTorrent])
1262        {
1263                fPex = setting;
1264                tr_torrentDisablePex(fHandle, !setting);
1265        }
1266}
1267
1268- (NSNumber *) orderValue
1269{
1270    return [NSNumber numberWithInt: fOrderValue];
1271}
1272
1273- (void) setOrderValue: (int) orderValue
1274{
1275    fOrderValue = orderValue;
1276}
1277
1278- (NSArray *) fileList
1279{
1280    return fFileList;
1281}
1282
1283- (int) fileCount
1284{
1285    return fInfo->fileCount;
1286}
1287
1288- (float) fileProgress: (int) index
1289{
1290    return tr_torrentFileCompletion(fHandle, index);
1291}
1292
1293- (int) checkForFiles: (NSIndexSet *) indexSet
1294{
1295    BOOL onState = NO, offState = NO;
1296    int index;
1297    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1298    {
1299        if (tr_torrentGetFilePriority(fHandle, index) != TR_PRI_DND
1300                || ![self canChangeDownloadCheckForFiles: [NSIndexSet indexSetWithIndex: index]])
1301            onState = YES;
1302        else
1303            offState = YES;
1304       
1305        if (onState == offState)
1306            return NSMixedState;
1307    }
1308    return onState ? NSOnState : NSOffState;
1309}
1310
1311- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1312{
1313    if ([self fileCount] <= 1)
1314        return NO;
1315   
1316    int index;
1317    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1318        if ([self fileProgress: index] < 1.0)
1319            return YES;
1320    return NO;
1321}
1322
1323- (void) setFileCheckState: (int) state forIndexes: (NSIndexSet *) indexSet
1324{
1325    int index;
1326    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1327    {
1328        tr_priority_t actualPriority;
1329        if (state == NSOnState)
1330        {
1331            int priority = [[[fFlatFileList objectAtIndex: index] objectForKey: @"Priority"] intValue];
1332            if (priority == PRIORITY_HIGH)
1333                actualPriority = TR_PRI_HIGH;
1334            else if (priority == PRIORITY_LOW)
1335                actualPriority = TR_PRI_LOW;
1336            else
1337                actualPriority = TR_PRI_NORMAL;
1338        }
1339        else
1340            actualPriority = TR_PRI_DND;
1341       
1342        tr_torrentSetFilePriority(fHandle, index, actualPriority);
1343    }
1344   
1345    [self update];
1346    if ([self isPaused])
1347        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self]; //for paused torrents
1348}
1349
1350- (void) setFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1351{
1352    NSNumber * priorityValue = [NSNumber numberWithInt: priority];
1353   
1354    int index;
1355    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1356    {
1357        [[fFlatFileList objectAtIndex: index] setObject: priorityValue forKey: @"Priority"];
1358       
1359        if ([self checkForFiles: [NSIndexSet indexSetWithIndex: index]] == NSOnState)
1360        {
1361            tr_priority_t actualPriority;
1362            if (priority == PRIORITY_HIGH)
1363                actualPriority = TR_PRI_HIGH;
1364            else if (priority == PRIORITY_LOW)
1365                actualPriority = TR_PRI_LOW;
1366            else
1367                actualPriority = TR_PRI_NORMAL;
1368            tr_torrentSetFilePriority(fHandle, index, actualPriority);
1369        }
1370    }
1371}
1372
1373- (BOOL) hasFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1374{
1375    int index;
1376    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1377        if (priority == [[[fFlatFileList objectAtIndex: index] objectForKey: @"Priority"] intValue]
1378                && [self canChangeDownloadCheckForFiles: [NSIndexSet indexSetWithIndex: index]])
1379            return YES;
1380    return NO;
1381}
1382
1383- (NSDate *) dateAdded
1384{
1385    return fDateAdded;
1386}
1387
1388- (NSDate *) dateCompleted
1389{
1390    return fDateCompleted;
1391}
1392
1393- (NSDate *) dateActivity
1394{
1395    uint64_t date = fStat->activityDate / 1000;
1396    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : fDateActivity;
1397}
1398
1399- (int) stalledMinutes
1400{
1401    uint64_t start;
1402    if ((start = fStat->startDate) == 0)
1403        return -1;
1404   
1405    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start / 1000],
1406            * activity = [self dateActivity];
1407    if (!activity || [started compare: activity] == NSOrderedDescending)
1408        return -1 * [started timeIntervalSinceNow] / 60;
1409    else
1410        return -1 * [activity timeIntervalSinceNow] / 60;
1411}
1412
1413- (BOOL) isStalled
1414{
1415    return fStalled;
1416}
1417
1418- (NSNumber *) stateSortKey
1419{
1420    if (![self isActive])
1421        return [NSNumber numberWithInt: 0];
1422    else if ([self isSeeding])
1423        return [NSNumber numberWithInt: 1];
1424    else
1425        return [NSNumber numberWithInt: 2];
1426}
1427
1428- (NSNumber *) progressSortKey
1429{
1430    float progress;
1431    if ((progress = [self progress]) >= 1.0)
1432       progress += [self progressStopRatio];
1433   
1434    return [NSNumber numberWithFloat: progress];
1435}
1436
1437- (NSNumber *) ratioSortKey
1438{
1439    return [NSNumber numberWithFloat: [self ratio]];
1440}
1441
1442- (int) torrentID
1443{
1444    return fID;
1445}
1446
1447- (const tr_info_t *) torrentInfo
1448{
1449    return fInfo;
1450}
1451
1452- (tr_stat_t *) torrentStat
1453{
1454    return fStat;
1455}
1456
1457@end
1458
1459@implementation Torrent (Private)
1460
1461//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1462- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
1463        publicTorrent: (NSNumber *) publicTorrent
1464        downloadFolder: (NSString *) downloadFolder
1465        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
1466        dateAdded: (NSDate *) dateAdded dateCompleted: (NSDate *) dateCompleted
1467        dateActivity: (NSDate *) dateActivity
1468        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
1469        limitSpeedCustom: (NSNumber *) limitCustom
1470        checkUpload: (NSNumber *) checkUpload uploadLimit: (NSNumber *) uploadLimit
1471        checkDownload: (NSNumber *) checkDownload downloadLimit: (NSNumber *) downloadLimit
1472                pex: (NSNumber *) pex
1473        waitToStart: (NSNumber *) waitToStart orderValue: (NSNumber *) orderValue
1474        filesShouldDownload: (NSArray *) filesShouldDownload filePriorities: (NSArray *) filePriorities;
1475{
1476    if (!(self = [super init]))
1477        return nil;
1478   
1479    static_lastid++;
1480    fID = static_lastid;
1481   
1482    fLib = lib;
1483    fDefaults = [NSUserDefaults standardUserDefaults];
1484
1485    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1486    if (fPublicTorrent)
1487        fPublicTorrentLocation = [path retain];
1488   
1489    fDownloadFolder = downloadFolder ? downloadFolder : [fDefaults stringForKey: @"DownloadFolder"];
1490    fDownloadFolder = [[fDownloadFolder stringByExpandingTildeInPath] retain];
1491   
1492    fUseIncompleteFolder = useIncompleteFolder ? [useIncompleteFolder boolValue]
1493                                : [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
1494    if (fUseIncompleteFolder)
1495    {
1496        fIncompleteFolder = incompleteFolder ? incompleteFolder : [fDefaults stringForKey: @"IncompleteDownloadFolder"];
1497        fIncompleteFolder = [[fIncompleteFolder stringByExpandingTildeInPath] retain];
1498    }
1499   
1500    #warning duplicate warning?
1501    NSString * currentDownloadFolder;
1502    tr_info_t info;
1503    int error;
1504    if (hashString)
1505    {
1506        if (tr_torrentParseHash(fLib, [hashString UTF8String], NULL, &info) == TR_OK)
1507        {
1508            currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1509                                        ? fIncompleteFolder : fDownloadFolder;
1510            fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], [currentDownloadFolder UTF8String],
1511                                            TR_FLAG_SAVE | TR_FLAG_PAUSED, &error);
1512        }
1513        tr_metainfoFree(&info);
1514    }
1515    if (!fHandle && path)
1516    {
1517        if (tr_torrentParse(fLib, [path UTF8String], NULL, &info) == TR_OK)
1518        {
1519            currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1520                                        ? fIncompleteFolder : fDownloadFolder;
1521            fHandle = tr_torrentInit(fLib, [path UTF8String], [currentDownloadFolder UTF8String],
1522                                        TR_FLAG_SAVE | TR_FLAG_PAUSED, &error);
1523        }
1524        tr_metainfoFree(&info);
1525    }
1526    if (!fHandle)
1527    {
1528        [self release];
1529        return nil;
1530    }
1531   
1532    fInfo = tr_torrentInfo(fHandle);
1533   
1534    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
1535    [nc addObserver: self selector: @selector(updateSpeedSetting:)
1536                name: @"UpdateSpeedSetting" object: nil];
1537
1538    fDateAdded = dateAdded ? [dateAdded retain] : [[NSDate alloc] init];
1539        if (dateCompleted)
1540                fDateCompleted = [dateCompleted retain];
1541    if (dateActivity)
1542                fDateActivity = [dateActivity retain];
1543       
1544    fRatioSetting = ratioSetting ? [ratioSetting intValue] : NSMixedState;
1545    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1546    fFinishedSeeding = NO;
1547   
1548    fCheckUpload = checkUpload ? [checkUpload intValue] : NSMixedState;
1549    fUploadLimit = uploadLimit ? [uploadLimit intValue] : [fDefaults integerForKey: @"UploadLimit"];
1550    fCheckDownload = checkDownload ? [checkDownload intValue] : NSMixedState;
1551    fDownloadLimit = downloadLimit ? [downloadLimit intValue] : [fDefaults integerForKey: @"DownloadLimit"];
1552    [self updateSpeedSetting];
1553       
1554        if ([self privateTorrent])
1555                fPex = NO;
1556        else
1557                fPex = pex ? [pex boolValue] : YES;
1558        tr_torrentDisablePex(fHandle, !fPex);
1559   
1560    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
1561    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
1562    fError = NO;
1563   
1564    fIcon = [[[NSWorkspace sharedWorkspace] iconForFileType: fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr')
1565                                                : [[self name] pathExtension]] retain];
1566   
1567    fIconFlipped = [fIcon copy];
1568    [fIconFlipped setFlipped: YES];
1569   
1570    fIconSmall = [fIconFlipped copy];
1571    [fIconSmall setScalesWhenResized: YES];
1572    [fIconSmall setSize: NSMakeSize(16.0, 16.0)];
1573
1574    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
1575    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
1576    fShortStatusString = [[NSMutableString alloc] initWithCapacity: 30];
1577    fRemainingTimeString = [[NSMutableString alloc] initWithCapacity: 30];
1578   
1579    [self createFileListShouldDownload: filesShouldDownload priorities: filePriorities];
1580   
1581    //set up advanced bar
1582    fBitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
1583        pixelsWide: MAX_PIECES pixelsHigh: BAR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
1584        isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
1585   
1586    fPieces = malloc(MAX_PIECES);
1587    int i;
1588    for (i = 0; i < MAX_PIECES; i++)
1589        fPieces[i] = BLANK_PIECE;
1590   
1591    [self update];
1592    return self;
1593}
1594
1595- (void) createFileListShouldDownload: (NSArray *) filesShouldDownload priorities: (NSArray *) filePriorities
1596{
1597    int count = [self fileCount], i;
1598    tr_file_t * file;
1599    NSMutableArray * pathComponents;
1600    NSString * path;
1601    int priority;
1602    tr_priority_t actualPriority;
1603   
1604    NSMutableArray * fileList = [[NSMutableArray alloc] init],
1605                    * flatFileList = [[NSMutableArray alloc] initWithCapacity: count];
1606   
1607    for (i = 0; i < count; i++)
1608    {
1609        file = &fInfo->files[i];
1610       
1611        pathComponents = [[[NSString stringWithUTF8String: file->name] pathComponents] mutableCopy];
1612        if (fInfo->multifile)
1613        {
1614            path = [pathComponents objectAtIndex: 0];
1615            [pathComponents removeObjectAtIndex: 0];
1616        }
1617        else
1618            path = @"";
1619       
1620        priority = filePriorities ? [[filePriorities objectAtIndex: i] intValue] : PRIORITY_NORMAL;
1621        [self insertPath: pathComponents forSiblings: fileList withParent: nil previousPath: path
1622                flatList: flatFileList fileSize: file->length index: i priority: priority];
1623        [pathComponents autorelease];
1624       
1625        if (!filesShouldDownload || [[filesShouldDownload objectAtIndex: i] boolValue])
1626        {
1627            if (priority == PRIORITY_HIGH)
1628                actualPriority = TR_PRI_HIGH;
1629            else if (priority == PRIORITY_LOW)
1630                actualPriority = TR_PRI_LOW;
1631            else
1632                actualPriority = TR_PRI_NORMAL;
1633        }
1634        else
1635            actualPriority = TR_PRI_DND;
1636       
1637        tr_torrentSetFilePriority(fHandle, i, actualPriority);
1638    }
1639   
1640    fFileList = [[NSArray alloc] initWithArray: fileList];
1641    [fileList release];
1642    fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1643    [flatFileList release];
1644}
1645
1646- (void) insertPath: (NSMutableArray *) components forSiblings: (NSMutableArray *) siblings
1647        withParent: (NSMutableDictionary *) parent previousPath: (NSString *) previousPath
1648        flatList: (NSMutableArray *) flatList fileSize: (uint64_t) size index: (int) index priority: (int) priority
1649{
1650    NSString * name = [components objectAtIndex: 0];
1651    BOOL isFolder = [components count] > 1;
1652   
1653    NSMutableDictionary * dict = nil;
1654    if (isFolder)
1655    {
1656        NSEnumerator * enumerator = [siblings objectEnumerator];
1657        while ((dict = [enumerator nextObject]))
1658            if ([[dict objectForKey: @"Name"] isEqualToString: name] && [[dict objectForKey: @"IsFolder"] boolValue])
1659                break;
1660    }
1661   
1662    NSString * currentPath = [previousPath stringByAppendingPathComponent: name];
1663   
1664    //create new folder or item if it doesn't already exist
1665    if (!dict)
1666    {
1667        dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: name, @"Name",
1668                [NSNumber numberWithBool: isFolder], @"IsFolder", currentPath, @"Path", nil];
1669        [siblings addObject: dict];
1670       
1671        if (isFolder)
1672        {
1673            [dict setObject: [NSMutableArray array] forKey: @"Children"];
1674            [dict setObject: [NSMutableIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1675        }
1676        else
1677        {
1678            [dict setObject: [NSIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1679            [dict setObject: [NSNumber numberWithUnsignedLongLong: size] forKey: @"Size"];
1680            [dict setObject: [[NSWorkspace sharedWorkspace] iconForFileType: [name pathExtension]] forKey: @"Icon"];
1681            [dict setObject: [NSNumber numberWithInt: priority] forKey: @"Priority"];
1682           
1683            [flatList addObject: dict];
1684        }
1685       
1686        if (parent)
1687            [dict setObject: parent forKey: @"Parent"];
1688    }
1689    else
1690        [[dict objectForKey: @"Indexes"] addIndex: index];
1691   
1692    if (isFolder)
1693    {
1694        [components removeObjectAtIndex: 0];
1695        [self insertPath: components forSiblings: [dict objectForKey: @"Children"]
1696            withParent: dict previousPath: currentPath flatList: flatList fileSize: size index: index priority: priority];
1697    }
1698}
1699
1700- (void) historyFilePriorities: (NSMutableArray *) history forItems: (NSArray *) items
1701{
1702    NSEnumerator * enumerator = [items objectEnumerator];
1703    NSDictionary * item;
1704    while ((item = [enumerator nextObject]))
1705    {
1706        if (![[item objectForKey: @"IsFolder"] boolValue])
1707            [history addObject: [item objectForKey: @"Priority"]];
1708        else
1709            [self historyFilePriorities: history forItems: [item objectForKey: @"Children"]];
1710    }
1711}
1712
1713- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name
1714{
1715    return fUseIncompleteFolder &&
1716        ![[NSFileManager defaultManager] fileExistsAtPath: [fDownloadFolder stringByAppendingPathComponent: name]];
1717}
1718
1719- (void) updateDownloadFolder
1720{
1721    NSString * folder = [self shouldUseIncompleteFolderForName: [self name]] ? fIncompleteFolder : fDownloadFolder;
1722    tr_torrentSetFolder(fHandle, [folder UTF8String]);
1723}
1724
1725#warning move?
1726- (NSImage *) advancedBar
1727{
1728    uint32_t * p;
1729    uint8_t * bitmapData = [fBitmap bitmapData];
1730    int bytesPerRow = [fBitmap bytesPerRow];
1731   
1732    int pieceCount = [self pieceCount];
1733    int8_t * piecesAvailablity = malloc(pieceCount);
1734    [self getAvailability: piecesAvailablity size: pieceCount];
1735   
1736    //lines 2 to 14: blue, green, or gray depending on piece availability
1737    int i, h, index = 0;
1738    float increment = (float)pieceCount / (float)MAX_PIECES, indexValue = 0;
1739    uint32_t color;
1740    BOOL change;
1741    for (i = 0; i < MAX_PIECES; i++)
1742    {
1743        change = NO;
1744        if (piecesAvailablity[index] < 0)
1745        {
1746            if (fPieces[i] != -1)
1747            {
1748                color = kBlue;
1749                fPieces[i] = -1;
1750                change = YES;
1751            }
1752        }
1753        else if (piecesAvailablity[index] == 0)
1754        {
1755            if (fPieces[i] != 0)
1756            {
1757                color = kGray;
1758                fPieces[i] = 0;
1759                change = YES;
1760            }
1761        }
1762        else if (piecesAvailablity[index] <= 4)
1763        {
1764            if (fPieces[i] != 1)
1765            {
1766                color = kGreen1;
1767                fPieces[i] = 1;
1768                change = YES;
1769            }
1770        }
1771        else if (piecesAvailablity[index] <= 8)
1772        {
1773            if (fPieces[i] != 2)
1774            {
1775                color = kGreen2;
1776                fPieces[i] = 2;
1777                change = YES;
1778            }
1779        }
1780        else
1781        {
1782            if (fPieces[i] != 3)
1783            {
1784                color = kGreen3;
1785                fPieces[i] = 3;
1786                change = YES;
1787            }
1788        }
1789       
1790        if (change)
1791        {
1792            //point to pixel (i, 2) and draw "vertically"
1793            p = (uint32_t *)(bitmapData + 2 * bytesPerRow) + i;
1794            for (h = 2; h < BAR_HEIGHT; h++)
1795            {
1796                p[0] = color;
1797                p = (uint32_t *)((uint8_t *)p + bytesPerRow);
1798            }
1799        }
1800       
1801        indexValue += increment;
1802        index = (int)indexValue;
1803    }
1804   
1805    //determine percentage finished and available
1806    int have = rintf((float)MAX_PIECES * [self progress]), avail;
1807    if ([self progress] >= 1.0 || ![self isActive] || [self totalPeers] <= 0)
1808        avail = 0;
1809    else
1810    {
1811        float * piecesFinished = malloc(pieceCount * sizeof(float));
1812        [self getAmountFinished: piecesFinished size: pieceCount];
1813       
1814        float available = 0;
1815        for (i = 0; i < pieceCount; i++)
1816            if (piecesAvailablity[i] > 0)
1817                available += 1.0 - piecesFinished[i];
1818       
1819        avail = rintf((float)MAX_PIECES * available / (float)pieceCount);
1820        if (have + avail > MAX_PIECES) //case if both end in .5 and all pieces are available
1821            avail--;
1822       
1823        free(piecesFinished);
1824    }
1825   
1826    free(piecesAvailablity);
1827   
1828    //first two lines: dark blue to show progression, green to show available
1829    p = (uint32_t *)bitmapData;
1830    for (i = 0; i < have; i++)
1831    {
1832        p[i] = kBlue2;
1833        p[i + bytesPerRow / 4] = kBlue2;
1834    }
1835    for (; i < avail + have; i++)
1836    {
1837        p[i] = kGreen3;
1838        p[i + bytesPerRow / 4] = kGreen3;
1839    }
1840    for (; i < MAX_PIECES; i++)
1841    {
1842        p[i] = kWhite;
1843        p[i + bytesPerRow / 4] = kWhite;
1844    }
1845   
1846    //actually draw image
1847    NSImage * bar = [[NSImage alloc] initWithSize: [fBitmap size]];
1848    [bar addRepresentation: fBitmap];
1849    [bar setScalesWhenResized: YES];
1850   
1851    return [bar autorelease];
1852}
1853
1854- (void) trashFile: (NSString *) path
1855{
1856    //attempt to move to trash
1857    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1858            source: [path stringByDeletingLastPathComponent] destination: @""
1859            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1860    {
1861        //if cannot trash, just delete it (will work if it is on a remote volume)
1862        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1863            NSLog(@"Could not trash %@", path);
1864    }
1865}
1866
1867@end
Note: See TracBrowser for help on using the repository browser.