source: trunk/macosx/Torrent.m @ 2226

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

remove some nslogs

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