source: trunk/macosx/Torrent.m @ 7514

Last change on this file since 7514 was 7514, checked in by livings124, 12 years ago

eliminate some more enumerator objects

  • Property svn:keywords set to Date Rev Author Id
File size: 63.8 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 7514 2008-12-26 07:25:17Z livings124 $
3 *
4 * Copyright (c) 2006-2008 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 "GroupsController.h"
27#import "FileListNode.h"
28#import "NSStringAdditions.h"
29#import "utils.h" //tr_httpIsValidURL
30
31@interface Torrent (Private)
32
33- (id) initWithHash: (NSString *) hashString path: (NSString *) path torrentStruct: (tr_torrent *) torrentStruct lib: (tr_session *) lib
34        publicTorrent: (NSNumber *) publicTorrent
35        downloadFolder: (NSString *) downloadFolder
36        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
37        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
38        waitToStart: (NSNumber *) waitToStart
39        orderValue: (NSNumber *) orderValue groupValue: (NSNumber *) groupValue addedTrackers: (NSNumber *) addedTrackers;
40
41- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name;
42- (void) updateDownloadFolder;
43
44- (void) createFileList;
45- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
46    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList;
47
48- (void) completenessChange: (NSNumber *) status;
49
50- (void) quickPause;
51- (void) endQuickPause;
52
53- (NSString *) etaString: (NSInteger) eta;
54
55- (void) updateAllTrackers: (NSMutableArray *) trackers;
56
57+ (void) trashFile: (NSString *) path;
58
59- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path;
60
61@end
62
63void completenessChangeCallback(tr_torrent * torrent, tr_completeness status, void * torrentData)
64{
65    [(Torrent *)torrentData performSelectorOnMainThread: @selector(completenessChange:)
66                withObject: [[NSNumber alloc] initWithInt: status] waitUntilDone: NO];
67}
68
69int trashDataFile(const char * filename)
70{
71    [Torrent trashFile: [NSString stringWithUTF8String: filename]];
72    return 0;
73}
74
75@implementation Torrent
76
77- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (torrentFileState) torrentDelete
78        lib: (tr_session *) lib
79{
80    self = [self initWithHash: nil path: path torrentStruct: NULL lib: lib
81            publicTorrent: torrentDelete != TORRENT_FILE_DEFAULT ? [NSNumber numberWithBool: torrentDelete == TORRENT_FILE_SAVE] : nil
82            downloadFolder: location
83            useIncompleteFolder: nil incompleteFolder: nil
84            ratioSetting: nil ratioLimit: nil
85            waitToStart: nil orderValue: nil groupValue: nil addedTrackers: nil];
86   
87    if (self)
88    {
89        //if the public and private torrent files are the same, then there is no public torrent
90        if ([[self torrentLocation] isEqualToString: path])
91        {
92            fPublicTorrent = NO;
93            [fPublicTorrentLocation release];
94            fPublicTorrentLocation = nil;
95        }
96        else if (!fPublicTorrent)
97            [Torrent trashFile: path];
98        else;
99    }
100    return self;
101}
102
103- (id) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib
104{
105    self = [self initWithHash: nil path: nil torrentStruct: torrentStruct lib: lib
106            publicTorrent: [NSNumber numberWithBool: NO]
107            downloadFolder: location
108            useIncompleteFolder: nil incompleteFolder: nil
109            ratioSetting: nil ratioLimit: nil
110            waitToStart: nil orderValue: nil groupValue: nil addedTrackers: nil];
111   
112    return self;
113}
114
115- (id) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib
116{
117    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
118                path: [history objectForKey: @"TorrentPath"] torrentStruct: NULL lib: lib
119                publicTorrent: [history objectForKey: @"PublicCopy"]
120                downloadFolder: [history objectForKey: @"DownloadFolder"]
121                useIncompleteFolder: [history objectForKey: @"UseIncompleteFolder"]
122                incompleteFolder: [history objectForKey: @"IncompleteFolder"]
123                ratioSetting: [history objectForKey: @"RatioSetting"]
124                ratioLimit: [history objectForKey: @"RatioLimit"]
125                waitToStart: [history objectForKey: @"WaitToStart"]
126                orderValue: [history objectForKey: @"OrderValue"]
127                groupValue: [history objectForKey: @"GroupValue"]
128                addedTrackers: [history objectForKey: @"AddedTrackers"]];
129   
130    if (self)
131    {
132        //start transfer
133        NSNumber * active;
134        if ((active = [history objectForKey: @"Active"]) && [active boolValue])
135        {
136            fStat = tr_torrentStat(fHandle);
137            [self startTransfer];
138        }
139       
140        //upgrading from versions < 1.30: get old added, activity, and done dates
141        NSDate * date;
142        if ((date = [history objectForKey: @"Date"]))
143            tr_torrentSetAddedDate(fHandle, [date timeIntervalSince1970]);
144        if ((date = [history objectForKey: @"DateActivity"]))
145            tr_torrentSetActivityDate(fHandle, [date timeIntervalSince1970]);
146        if ((date = [history objectForKey: @"DateCompleted"]))
147            tr_torrentSetDoneDate(fHandle, [date timeIntervalSince1970]);
148    }
149    return self;
150}
151
152- (NSDictionary *) history
153{
154    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
155                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
156                    [self hashString], @"TorrentHash",
157                    fDownloadFolder, @"DownloadFolder",
158                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
159                    [NSNumber numberWithBool: [self isActive]], @"Active",
160                    [NSNumber numberWithInt: fRatioSetting], @"RatioSetting",
161                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
162                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
163                    [NSNumber numberWithInt: fOrderValue], @"OrderValue",
164                    [NSNumber numberWithInt: fGroupValue], @"GroupValue",
165                    [NSNumber numberWithBool: fAddedTrackers], @"AddedTrackers", nil];
166   
167    if (fIncompleteFolder)
168        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
169
170    if (fPublicTorrent)
171        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
172       
173    return history;
174}
175
176- (void) dealloc
177{
178    [[NSNotificationCenter defaultCenter] removeObserver: self];
179   
180    if (fFileStat)
181        tr_torrentFilesFree(fFileStat, [self fileCount]);
182   
183    [fPreviousFinishedIndexes release];
184    [fPreviousFinishedIndexesDate release];
185   
186    [fNameString release];
187    [fHashString release];
188   
189    [fDownloadFolder release];
190    [fIncompleteFolder release];
191   
192    [fPublicTorrentLocation release];
193   
194    [fIcon release];
195   
196    [fFileList release];
197    [fFlatFileList release];
198   
199    [fQuickPauseDict release];
200   
201    [super dealloc];
202}
203
204- (NSString *) description
205{
206    return [@"Torrent: " stringByAppendingString: [self name]];
207}
208
209- (void) closeRemoveTorrent
210{
211    //allow the file to be index by Time Machine
212    [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
213   
214    tr_torrentRemove(fHandle);
215}
216
217- (void) changeIncompleteDownloadFolder: (NSString *) folder
218{
219    fUseIncompleteFolder = folder != nil;
220   
221    [fIncompleteFolder release];
222    fIncompleteFolder = fUseIncompleteFolder ? [folder retain] : nil;
223   
224    [self updateDownloadFolder];
225}
226
227- (void) changeDownloadFolder: (NSString *) folder
228{
229    if (fDownloadFolder && [folder isEqualToString: fDownloadFolder])
230        return;
231   
232    [fDownloadFolder release];
233    fDownloadFolder = [folder retain];
234   
235    [self updateDownloadFolder];
236}
237
238- (NSString *) downloadFolder
239{
240    return [NSString stringWithUTF8String: tr_torrentGetDownloadDir(fHandle)];
241}
242
243- (void) getAvailability: (int8_t *) tab size: (NSInteger) size
244{
245    tr_torrentAvailability(fHandle, tab, size);
246}
247
248- (void) getAmountFinished: (float *) tab size: (NSInteger) size
249{
250    tr_torrentAmountFinished(fHandle, tab, size);
251}
252
253- (NSIndexSet *) previousFinishedPieces
254{
255    //if the torrent hasn't been seen in a bit, and therefore hasn't been refreshed, return nil
256    if (fPreviousFinishedIndexesDate && [fPreviousFinishedIndexesDate timeIntervalSinceNow] > -2.0)
257        return fPreviousFinishedIndexes;
258    else
259        return nil;
260}
261
262-(void) setPreviousFinishedPieces: (NSIndexSet *) indexes
263{
264    [fPreviousFinishedIndexes release];
265    fPreviousFinishedIndexes = [indexes retain];
266   
267    [fPreviousFinishedIndexesDate release];
268    fPreviousFinishedIndexesDate = indexes != nil ? [[NSDate alloc] init] : nil;
269}
270
271- (void) update
272{
273    //get previous status values before update
274    BOOL wasChecking = NO, wasError = NO, wasStalled = NO;
275    if (fStat != NULL)
276    {
277        wasChecking = [self isChecking];
278        wasError = [self isError];
279        wasStalled = fStalled;
280    }
281   
282    fStat = tr_torrentStat(fHandle);
283   
284    //check to stop for ratio
285    CGFloat stopRatio;
286    if ([self isSeeding] && (stopRatio = [self actualStopRatio]) != INVALID && [self ratio] >= stopRatio)
287    {
288        [self setRatioSetting: NSOffState];
289        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
290       
291        [self stopTransfer];
292        fStat = tr_torrentStat(fHandle);
293       
294        fFinishedSeeding = YES;
295    }
296   
297    //check if stalled (stored because based on time and needs to check if it was previously stalled)
298    fStalled = [self isActive] && [fDefaults boolForKey: @"CheckStalled"]
299                && [self stalledMinutes] > [fDefaults integerForKey: @"StalledMinutes"];
300   
301    //update queue for checking (from downloading to seeding), stalled, or error
302    if ((wasChecking && ![self isChecking]) || (wasStalled != fStalled) || (!wasError && [self isError] && [self isActive]))
303        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
304}
305
306- (void) startTransfer
307{
308    fWaitToStart = NO;
309    fFinishedSeeding = NO;
310   
311    if (![self isActive] && [self alertForFolderAvailable] && [self alertForRemainingDiskSpace])
312    {
313        tr_torrentStart(fHandle);
314        [self update];
315    }
316}
317
318- (void) stopTransfer
319{
320    fWaitToStart = NO;
321   
322    if ([self isActive])
323    {
324        tr_torrentStop(fHandle);
325        [self update];
326       
327        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
328    }
329}
330
331- (void) sleep
332{
333    if ((fResumeOnWake = [self isActive]))
334        tr_torrentStop(fHandle);
335}
336
337- (void) wakeUp
338{
339    if (fResumeOnWake)
340        tr_torrentStart(fHandle);
341}
342
343- (void) manualAnnounce
344{
345    tr_torrentManualUpdate(fHandle);
346}
347
348- (BOOL) canManualAnnounce
349{
350    return tr_torrentCanManualUpdate(fHandle);
351}
352
353- (void) resetCache
354{
355    tr_torrentVerify(fHandle);
356    [self update];
357}
358
359- (CGFloat) ratio
360{
361    return fStat->ratio;
362}
363
364- (NSInteger) ratioSetting
365{
366    return fRatioSetting;
367}
368
369- (void) setRatioSetting: (NSInteger) setting
370{
371    fRatioSetting = setting;
372}
373
374- (CGFloat) ratioLimit
375{
376    return fRatioLimit;
377}
378
379- (void) setRatioLimit: (CGFloat) limit
380{
381    if (limit >= 0)
382        fRatioLimit = limit;
383}
384
385- (CGFloat) actualStopRatio
386{
387    if (fRatioSetting == NSOnState)
388        return fRatioLimit;
389    else if (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"])
390        return [fDefaults floatForKey: @"RatioLimit"];
391    else
392        return INVALID;
393}
394
395- (CGFloat) progressStopRatio
396{
397    CGFloat stopRatio, ratio;
398    if ((stopRatio = [self actualStopRatio]) == INVALID || (ratio = [self ratio]) >= stopRatio)
399        return 1.0;
400    else if (stopRatio > 0.0)
401        return ratio / stopRatio;
402    else
403        return 0.0;
404}
405
406- (tr_speedlimit) speedMode: (BOOL) upload
407{
408    return tr_torrentGetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN);
409}
410
411- (void) setSpeedMode: (tr_speedlimit) mode upload: (BOOL) upload
412{
413    tr_torrentSetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN, mode);
414}
415
416- (NSInteger) speedLimit: (BOOL) upload
417{
418    return tr_torrentGetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN);
419}
420
421- (void) setSpeedLimit: (NSInteger) limit upload: (BOOL) upload
422{
423    tr_torrentSetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, limit);
424}
425
426- (void) setMaxPeerConnect: (uint16_t) count
427{
428    NSAssert(count > 0, @"max peer count must be greater than 0");
429   
430    tr_torrentSetPeerLimit(fHandle, count);
431}
432
433- (uint16_t) maxPeerConnect
434{
435    return tr_torrentGetPeerLimit(fHandle);
436}
437
438- (void) setWaitToStart: (BOOL) wait
439{
440    fWaitToStart = wait;
441}
442
443- (BOOL) waitingToStart
444{
445    return fWaitToStart;
446}
447
448- (void) revealData
449{
450    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
451}
452
453- (void) revealPublicTorrent
454{
455    if (fPublicTorrent)
456        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
457}
458
459- (void) trashData
460{
461    tr_torrentDeleteLocalData(fHandle, trashDataFile);
462}
463
464- (void) trashTorrent
465{
466    if (fPublicTorrent)
467    {
468        [Torrent trashFile: fPublicTorrentLocation];
469        [fPublicTorrentLocation release];
470        fPublicTorrentLocation = nil;
471       
472        fPublicTorrent = NO;
473    }
474}
475
476- (void) moveTorrentDataFileTo: (NSString *) folder
477{
478    NSString * oldFolder = [self downloadFolder];
479    if (![oldFolder isEqualToString: folder] || ![fDownloadFolder isEqualToString: folder])
480    {
481        //check if moving inside itself
482        NSArray * oldComponents = [oldFolder pathComponents],
483                * newComponents = [folder pathComponents];
484        NSInteger count;
485       
486        if ((count = [oldComponents count]) < [newComponents count]
487                && [[newComponents objectAtIndex: count] isEqualToString: [self name]]
488                && [oldComponents isEqualToArray:
489                        [newComponents objectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, count)]]])
490        {
491            NSAlert * alert = [[NSAlert alloc] init];
492            [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.",
493                                                        "Move inside itself alert -> title")];
494            [alert setInformativeText: [NSString stringWithFormat:
495                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
496                                                "Move inside itself alert -> message"), [self name]]];
497            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")];
498           
499            [alert runModal];
500            [alert release];
501           
502            return;
503        }
504       
505        [self quickPause];
506       
507        //allow if file can be moved or does not exist
508        if ([[NSFileManager defaultManager] movePath: [oldFolder stringByAppendingPathComponent: [self name]]
509                            toPath: [folder stringByAppendingPathComponent: [self name]] handler: nil]
510            || ![[NSFileManager defaultManager] fileExistsAtPath: [oldFolder stringByAppendingPathComponent: [self name]]])
511        {
512            //get rid of both incomplete folder and old download folder, even if move failed
513            fUseIncompleteFolder = NO;
514            if (fIncompleteFolder)
515            {
516                [fIncompleteFolder release];
517                fIncompleteFolder = nil;
518            }
519            [self changeDownloadFolder: folder];
520           
521            [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
522           
523            [self endQuickPause];
524        }
525        else
526        {
527            [self endQuickPause];
528       
529            NSAlert * alert = [[NSAlert alloc] init];
530            [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")];
531            [alert setInformativeText: [NSString stringWithFormat:
532                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
533                                                "Move error alert -> message"), [self name]]];
534            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")];
535           
536            [alert runModal];
537            [alert release];
538        }
539    }
540}
541
542- (void) copyTorrentFileTo: (NSString *) path
543{
544    [[NSFileManager defaultManager] copyPath: [self torrentLocation] toPath: path handler: nil];
545}
546
547- (BOOL) alertForRemainingDiskSpace
548{
549    if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"])
550        return YES;
551   
552    NSFileManager * fileManager = [NSFileManager defaultManager];
553    NSString * downloadFolder = [self downloadFolder];
554   
555    NSString * volumeName;
556    if ((volumeName = [[fileManager componentsToDisplayForPath: downloadFolder] objectAtIndex: 0]))
557    {
558        NSDictionary * systemAttributes = [fileManager attributesOfFileSystemForPath: downloadFolder error: NULL];
559        uint64_t remainingSpace = [[systemAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue];
560       
561        //if the remaining space is greater than the size left, then there is enough space regardless of preallocation
562        if (remainingSpace < [self sizeLeft] && remainingSpace < tr_torrentGetBytesLeftToAllocate(fHandle))
563        {
564            NSAlert * alert = [[NSAlert alloc] init];
565            [alert setMessageText: [NSString stringWithFormat:
566                                    NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
567                                        "Torrent disk space alert -> title"), [self name]]];
568            [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused."
569                                        " Clear up space on %@ or deselect files in the torrent inspector to continue.",
570                                        "Torrent disk space alert -> message"), volumeName]];
571            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent disk space alert -> button")];
572            [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent disk space alert -> button")];
573           
574            [alert setShowsSuppressionButton: YES];
575            [[alert suppressionButton] setTitle: NSLocalizedString(@"Do not check disk space again",
576                                                    "Torrent disk space alert -> button")];
577
578            NSInteger result = [alert runModal];
579            if ([[alert suppressionButton] state] == NSOnState)
580                [fDefaults setBool: NO forKey: @"WarningRemainingSpace"];
581            [alert release];
582           
583            return result != NSAlertFirstButtonReturn;
584        }
585    }
586    return YES;
587}
588
589- (BOOL) alertForFolderAvailable
590{
591    #warning check for change from incomplete to download folder first
592    if (access(tr_torrentGetDownloadDir(fHandle), 0))
593    {
594        NSAlert * alert = [[NSAlert alloc] init];
595        [alert setMessageText: [NSString stringWithFormat:
596                                NSLocalizedString(@"The folder for downloading \"%@\" cannot be used.",
597                                    "Folder cannot be used alert -> title"), [self name]]];
598        [alert setInformativeText: [NSString stringWithFormat:
599                        NSLocalizedString(@"\"%@\" cannot be used. The transfer will be paused.",
600                                            "Folder cannot be used alert -> message"), [self downloadFolder]]];
601        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Folder cannot be used alert -> button")];
602        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Location",
603                                    "Folder cannot be used alert -> location button") stringByAppendingEllipsis]];
604       
605        if ([alert runModal] != NSAlertFirstButtonReturn)
606        {
607            NSOpenPanel * panel = [NSOpenPanel openPanel];
608           
609            [panel setPrompt: NSLocalizedString(@"Select", "Folder cannot be used alert -> prompt")];
610            [panel setAllowsMultipleSelection: NO];
611            [panel setCanChooseFiles: NO];
612            [panel setCanChooseDirectories: YES];
613            [panel setCanCreateDirectories: YES];
614
615            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
616                                "Folder cannot be used alert -> select destination folder"), [self name]]];
617           
618            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
619            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
620                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
621        }
622       
623        [alert release];
624       
625        return NO;
626    }
627    return YES;
628}
629
630- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (void *) context
631{
632    if (code != NSOKButton)
633        return;
634   
635    [self changeDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
636   
637    [self startTransfer];
638    [self update];
639   
640    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
641}
642
643- (BOOL) alertForMoveFolderAvailable
644{
645    if (access([fDownloadFolder UTF8String], 0))
646    {
647        NSAlert * alert = [[NSAlert alloc] init];
648        [alert setMessageText: [NSString stringWithFormat:
649                                NSLocalizedString(@"The folder for moving the completed \"%@\" cannot be used.",
650                                    "Move folder cannot be used alert -> title"), [self name]]];
651        [alert setInformativeText: [NSString stringWithFormat:
652                                NSLocalizedString(@"\"%@\" cannot be used. The file will remain in its current location.",
653                                    "Move folder cannot be used alert -> message"), fDownloadFolder]];
654        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move folder cannot be used alert -> button")];
655       
656        [alert runModal];
657        [alert release];
658       
659        return NO;
660    }
661   
662    return YES;
663}
664
665- (NSImage *) icon
666{
667    if (!fIcon)
668    {
669        fIcon = [[[NSWorkspace sharedWorkspace] iconForFileType: [self isFolder] ? NSFileTypeForHFSTypeCode('fldr')
670                                                : [[self name] pathExtension]] retain];
671        [fIcon setFlipped: YES];
672    }
673    return fIcon;
674}
675
676- (NSString *) name
677{
678    return fNameString;
679}
680
681- (BOOL) isFolder
682{
683    return fInfo->isMultifile;
684}
685
686- (uint64_t) size
687{
688    return fInfo->totalSize;
689}
690
691- (uint64_t) sizeLeft
692{
693    return fStat->leftUntilDone;
694}
695
696- (NSString *) trackerAddressAnnounce
697{
698    return fStat->announceURL ? [NSString stringWithUTF8String: fStat->announceURL] : nil;
699}
700
701- (NSDate *) lastAnnounceTime
702{
703    NSInteger date = fStat->lastAnnounceTime;
704    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
705}
706
707- (NSInteger) nextAnnounceTime
708{
709    NSInteger date = fStat->nextAnnounceTime;
710    NSTimeInterval difference;
711    switch (date)
712    {
713        case 0:
714            return STAT_TIME_NONE;
715        case 1:
716            return STAT_TIME_NOW;
717        default:
718            difference = [[NSDate dateWithTimeIntervalSince1970: date] timeIntervalSinceNow];
719            return difference > 0 ? (NSInteger)difference : STAT_TIME_NONE;
720    }
721}
722
723- (NSString *) announceResponse
724{
725    return [NSString stringWithUTF8String: fStat->announceResponse];
726}
727
728- (NSString *) trackerAddressScrape
729{
730    return fStat->scrapeURL ? [NSString stringWithUTF8String: fStat->scrapeURL] : nil;
731}
732
733- (NSDate *) lastScrapeTime
734{
735    NSInteger date = fStat->lastScrapeTime;
736    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
737}
738
739- (NSInteger) nextScrapeTime
740{
741    NSInteger date = fStat->nextScrapeTime;
742    NSTimeInterval difference;
743    switch (date)
744    {
745        case 0:
746            return STAT_TIME_NONE;
747        case 1:
748            return STAT_TIME_NOW;
749        default:
750            difference = [[NSDate dateWithTimeIntervalSince1970: date] timeIntervalSinceNow];
751            return difference > 0 ? (NSInteger)difference : STAT_TIME_NONE;
752    }
753}
754
755- (NSString *) scrapeResponse
756{
757    return [NSString stringWithUTF8String: fStat->scrapeResponse];
758}
759
760- (NSMutableArray *) allTrackers: (BOOL) separators
761{
762    NSInteger count = fInfo->trackerCount, capacity = count;
763    if (separators)
764        capacity += fInfo->trackers[count-1].tier + 1;
765    NSMutableArray * allTrackers = [NSMutableArray arrayWithCapacity: capacity];
766   
767    for (NSInteger i = 0, tier = -1; i < count; i++)
768    {
769        if (separators && tier != fInfo->trackers[i].tier)
770        {
771            tier = fInfo->trackers[i].tier;
772            [allTrackers addObject: [NSNumber numberWithInt: fAddedTrackers ? tier : tier + 1]];
773        }
774       
775        [allTrackers addObject: [NSString stringWithUTF8String: fInfo->trackers[i].announce]];
776    }
777   
778    return allTrackers;
779}
780
781- (NSString *) trackerList
782{
783    return [[self allTrackers: NO] componentsJoinedByString: @"\n"];
784}
785
786- (BOOL) updateAllTrackersForAdd: (NSMutableArray *) trackers
787{
788    //find added tracker at end of first tier
789    NSInteger i;
790    for (i = 1; i < [trackers count]; i++)
791        if ([[trackers objectAtIndex: i] isKindOfClass: [NSNumber class]])
792            break;
793    i--;
794   
795    NSString * tracker = [trackers objectAtIndex: i];
796   
797    tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
798   
799    if ([tracker rangeOfString: @"://"].location == NSNotFound)
800    {
801        tracker = [@"http://" stringByAppendingString: tracker];
802        [trackers replaceObjectAtIndex: i withObject: tracker];
803    }
804   
805    if (!tr_httpIsValidURL([tracker UTF8String]))
806        return NO;
807   
808    [self updateAllTrackers: trackers];
809   
810    fAddedTrackers = YES;
811    return YES;
812}
813
814- (void) updateAllTrackersForRemove: (NSMutableArray *) trackers
815{
816    //check if no user-added groups
817    if ([[trackers objectAtIndex: 0] intValue] != 0)
818        fAddedTrackers = NO;
819   
820    [self updateAllTrackers: trackers];
821}
822
823- (BOOL) hasAddedTrackers
824{
825    return fAddedTrackers;
826}
827
828- (NSString *) comment
829{
830    return [NSString stringWithUTF8String: fInfo->comment];
831}
832
833- (NSString *) creator
834{
835    return [NSString stringWithUTF8String: fInfo->creator];
836}
837
838- (NSDate *) dateCreated
839{
840    NSInteger date = fInfo->dateCreated;
841    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
842}
843
844- (NSInteger) pieceSize
845{
846    return fInfo->pieceSize;
847}
848
849- (NSInteger) pieceCount
850{
851    return fInfo->pieceCount;
852}
853
854- (NSString *) hashString
855{
856    return fHashString;
857}
858
859- (BOOL) privateTorrent
860{
861    return fInfo->isPrivate;
862}
863
864- (NSString *) torrentLocation
865{
866    return [NSString stringWithUTF8String: fInfo->torrent];
867}
868
869- (NSString *) publicTorrentLocation
870{
871    return fPublicTorrentLocation;
872}
873
874- (NSString *) dataLocation
875{
876    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
877}
878
879- (BOOL) publicTorrent
880{
881    return fPublicTorrent;
882}
883
884- (CGFloat) progress
885{
886    return fStat->percentComplete;
887}
888
889- (CGFloat) progressDone
890{
891    return fStat->percentDone;
892}
893
894- (CGFloat) progressLeft
895{
896    return (CGFloat)[self sizeLeft] / [self size];
897}
898
899- (CGFloat) checkingProgress
900{
901    return fStat->recheckProgress;
902}
903
904- (NSInteger) eta
905{
906    return fStat->eta;
907}
908
909- (NSInteger) etaRatio
910{
911    if (![self isSeeding])
912        return TR_ETA_UNKNOWN;
913   
914    CGFloat uploadRate = [self uploadRate];
915    if (uploadRate < 0.1)
916        return TR_ETA_UNKNOWN;
917   
918    CGFloat stopRatio = [self actualStopRatio], ratio = [self ratio];
919    if (stopRatio == INVALID || ratio >= stopRatio)
920        return TR_ETA_UNKNOWN;
921   
922    CGFloat haveDownloaded = (CGFloat)([self downloadedTotal] > 0 ? [self downloadedTotal] : [self haveVerified]);
923    CGFloat needUploaded = haveDownloaded * (stopRatio - ratio);
924    return needUploaded / uploadRate / 1024.0;
925}
926
927- (CGFloat) notAvailableDesired
928{
929    return 1.0 - (CGFloat)fStat->desiredAvailable / [self sizeLeft];
930}
931
932- (BOOL) isActive
933{
934    return fStat->activity != TR_STATUS_STOPPED;
935}
936
937- (BOOL) isSeeding
938{
939    return fStat->activity == TR_STATUS_SEED;
940}
941
942- (BOOL) isChecking
943{
944    return fStat->activity == TR_STATUS_CHECK || fStat->activity == TR_STATUS_CHECK_WAIT;
945}
946
947- (BOOL) isCheckingWaiting
948{
949    return fStat->activity == TR_STATUS_CHECK_WAIT;
950}
951
952- (BOOL) allDownloaded
953{
954    return [self progressDone] >= 1.0;
955}
956
957- (BOOL) isComplete
958{
959    return [self progress] >= 1.0;
960}
961
962- (BOOL) isError
963{
964    return fStat->error != TR_OK;
965}
966
967- (NSString *) errorMessage
968{
969    if (![self isError])
970        return @"";
971   
972    NSString * error;
973    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
974        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
975        error = [NSString stringWithFormat: @"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")];
976   
977    return error;
978}
979
980- (NSArray *) peers
981{
982    int totalPeers;
983    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
984   
985    NSMutableArray * peerDicts = [NSMutableArray arrayWithCapacity: totalPeers];
986   
987    for (int i = 0; i < totalPeers; i++)
988    {
989        tr_peer_stat * peer = &peers[i];
990        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 10];
991       
992        [dict setObject: [NSNumber numberWithInt: peer->from] forKey: @"From"];
993        [dict setObject: [NSString stringWithUTF8String: peer->addr] forKey: @"IP"];
994        [dict setObject: [NSNumber numberWithInt: peer->port] forKey: @"Port"];
995        [dict setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
996        [dict setObject: [NSNumber numberWithBool: peer->isSeed] forKey: @"Seed"];
997        [dict setObject: [NSNumber numberWithBool: peer->isEncrypted] forKey: @"Encryption"];
998        [dict setObject: [NSString stringWithUTF8String: peer->client] forKey: @"Client"];
999        [dict setObject: [NSString stringWithUTF8String: peer->flagStr] forKey: @"Flags"];
1000       
1001        if (peer->isUploadingTo)
1002            [dict setObject: [NSNumber numberWithFloat: peer->rateToPeer] forKey: @"UL To Rate"];
1003        if (peer->isDownloadingFrom)
1004            [dict setObject: [NSNumber numberWithFloat: peer->rateToClient] forKey: @"DL From Rate"];
1005       
1006        [peerDicts addObject: dict];
1007    }
1008   
1009    tr_torrentPeersFree(peers, totalPeers);
1010   
1011    return peerDicts;
1012}
1013
1014- (NSUInteger) webSeedCount
1015{
1016    return fInfo->webseedCount;
1017}
1018
1019- (NSArray *) webSeeds
1020{
1021    const NSInteger webSeedCount = fInfo->webseedCount;
1022    NSMutableArray * webSeeds = [NSMutableArray arrayWithCapacity: webSeedCount];
1023   
1024    float * dlSpeeds = tr_torrentWebSpeeds(fHandle);
1025   
1026    for (NSInteger i = 0; i < webSeedCount; i++)
1027    {
1028        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 2];
1029       
1030        [dict setObject: [NSString stringWithUTF8String: fInfo->webseeds[i]] forKey: @"Address"];
1031       
1032        if (dlSpeeds[i] != -1.0)
1033            [dict setObject: [NSNumber numberWithFloat: dlSpeeds[i]] forKey: @"DL From Rate"];
1034       
1035        [webSeeds addObject: dict];
1036    }
1037   
1038    tr_free(dlSpeeds);
1039   
1040    return webSeeds;
1041}
1042
1043- (NSString *) progressString
1044{
1045    NSString * string;
1046   
1047    if (![self allDownloaded])
1048    {
1049        CGFloat progress;
1050        if ([self isFolder] && [fDefaults boolForKey: @"DisplayStatusProgressSelected"])
1051        {
1052            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected", "Torrent -> progress string"),
1053                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self totalSizeSelected]]];
1054            progress = 100.0 * [self progressDone];
1055        }
1056        else
1057        {
1058            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
1059                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
1060            progress = 100.0 * [self progress];
1061        }
1062       
1063        string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", string, progress];
1064    }
1065    else
1066    {
1067        NSString * downloadString;
1068        if (![self isComplete]) //only multifile possible
1069        {
1070            if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
1071                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"),
1072                                    [NSString stringForFileSize: [self haveTotal]]];
1073            else
1074            {
1075                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
1076                                    [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
1077               
1078                downloadString = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", downloadString, 100.0 * [self progress]];
1079            }
1080        }
1081        else
1082            downloadString = [NSString stringForFileSize: [self size]];
1083       
1084        NSString * uploadString = [NSString stringWithFormat: NSLocalizedString(@"uploaded %@ (Ratio: %@)",
1085                                    "Torrent -> progress string"), [NSString stringForFileSize: [self uploadedTotal]],
1086                                    [NSString stringForRatio: [self ratio]]];
1087       
1088        string = [downloadString stringByAppendingFormat: @", %@", uploadString];
1089    }
1090   
1091    //add time when downloading
1092    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding]
1093        && (fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
1094    {
1095        NSInteger eta = fStat->activity == TR_STATUS_DOWNLOAD ? [self eta] : [self etaRatio];
1096        string = [string stringByAppendingFormat: @" - %@", [self etaString: eta]];
1097    }
1098   
1099    return string;
1100}
1101
1102- (NSString *) statusString
1103{
1104    NSString * string;
1105   
1106    if ([self isError])
1107    {
1108        string = NSLocalizedString(@"Error", "Torrent -> status string");
1109        NSString * errorString = [self errorMessage];
1110        if (errorString && ![errorString isEqualToString: @""])
1111            string = [string stringByAppendingFormat: @": %@", errorString];
1112    }
1113    else
1114    {
1115        switch (fStat->activity)
1116        {
1117            case TR_STATUS_STOPPED:
1118                if (fWaitToStart)
1119                {
1120                    string = ![self allDownloaded]
1121                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1122                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1123                }
1124                else if (fFinishedSeeding)
1125                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1126                else
1127                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
1128                break;
1129
1130            case TR_STATUS_CHECK_WAIT:
1131                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1132                break;
1133
1134            case TR_STATUS_CHECK:
1135                string = [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1136                                        "Torrent -> status string"), 100.0 * [self checkingProgress]];
1137                break;
1138
1139            case TR_STATUS_DOWNLOAD:
1140                if ([self totalPeersConnected] != 1)
1141                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
1142                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
1143                else
1144                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
1145                                                    "Torrent -> status string"), [self peersSendingToUs]];
1146               
1147                NSInteger webSeedCount = fStat->webseedsSendingToUs;
1148                if (webSeedCount > 0)
1149                {
1150                    NSString * webSeedString;
1151                    if (webSeedCount == 1)
1152                        webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string");
1153                    else
1154                        webSeedString = [NSString stringWithFormat: NSLocalizedString(@"%d web seeds", "Torrent -> status string"),
1155                                                                    webSeedCount];
1156                   
1157                    string = [string stringByAppendingFormat: @" + %@", webSeedString];
1158                }
1159               
1160                break;
1161
1162            case TR_STATUS_SEED:
1163                if ([self totalPeersConnected] != 1)
1164                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
1165                                                    [self peersGettingFromUs], [self totalPeersConnected]];
1166                else
1167                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
1168                                                    [self peersGettingFromUs]];
1169        }
1170       
1171        if (fStalled)
1172            string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string];
1173    }
1174   
1175    //append even if error
1176    if ([self isActive] && ![self isChecking])
1177    {
1178        if (fStat->activity == TR_STATUS_DOWNLOAD)
1179            string = [string stringByAppendingFormat: @" - %@: %@, %@: %@",
1180                        NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1181                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1182        else
1183            string = [string stringByAppendingFormat: @" - %@: %@",
1184                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1185    }
1186   
1187    return string;
1188}
1189
1190- (NSString *) shortStatusString
1191{
1192    NSString * string;
1193   
1194    switch (fStat->activity)
1195    {
1196        case TR_STATUS_STOPPED:
1197            if (fWaitToStart)
1198            {
1199                string = ![self allDownloaded]
1200                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1201                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1202            }
1203            else if (fFinishedSeeding)
1204                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1205            else
1206                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1207            break;
1208
1209        case TR_STATUS_CHECK_WAIT:
1210            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1211            break;
1212
1213        case TR_STATUS_CHECK:
1214            string = [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1215                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1216            break;
1217       
1218        case TR_STATUS_DOWNLOAD:
1219            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1220                            NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1221                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1222            break;
1223       
1224        case TR_STATUS_SEED:
1225            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1226                            NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: [self ratio]],
1227                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1228    }
1229   
1230    return string;
1231}
1232
1233- (NSString *) remainingTimeString
1234{
1235    if (![self isActive] || ([self isSeeding]
1236        && !(fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
1237        return [self shortStatusString];
1238   
1239    return [self etaString: [self isSeeding] ? [self etaRatio] : [self eta]];
1240}
1241
1242- (NSString *) stateString
1243{
1244    switch (fStat->activity)
1245    {
1246        case TR_STATUS_STOPPED:
1247            return NSLocalizedString(@"Paused", "Torrent -> status string");
1248
1249        case TR_STATUS_CHECK:
1250            return [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1251                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1252       
1253        case TR_STATUS_CHECK_WAIT:
1254            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1255
1256        case TR_STATUS_DOWNLOAD:
1257            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1258
1259        case TR_STATUS_SEED:
1260            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1261    }
1262}
1263
1264- (NSInteger) seeders
1265{
1266    return fStat->seeders;
1267}
1268
1269- (NSInteger) leechers
1270{
1271    return fStat->leechers;
1272}
1273
1274- (NSInteger) completedFromTracker
1275{
1276    return fStat->timesCompleted;
1277}
1278
1279- (NSInteger) totalPeersConnected
1280{
1281    return fStat->peersConnected;
1282}
1283
1284- (NSInteger) totalPeersTracker
1285{
1286    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1287}
1288
1289- (NSInteger) totalPeersIncoming
1290{
1291    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1292}
1293
1294- (NSInteger) totalPeersCache
1295{
1296    return fStat->peersFrom[TR_PEER_FROM_CACHE];
1297}
1298
1299- (NSInteger) totalPeersPex
1300{
1301    return fStat->peersFrom[TR_PEER_FROM_PEX];
1302}
1303
1304- (NSInteger) totalPeersKnown
1305{
1306    return fStat->peersKnown;
1307}
1308
1309- (NSInteger) peersSendingToUs
1310{
1311    return fStat->peersSendingToUs;
1312}
1313
1314- (NSInteger) peersGettingFromUs
1315{
1316    return fStat->peersGettingFromUs;
1317}
1318
1319- (CGFloat) downloadRate
1320{
1321    return fStat->pieceDownloadSpeed;
1322}
1323
1324- (CGFloat) uploadRate
1325{
1326    return fStat->pieceUploadSpeed;
1327}
1328
1329- (CGFloat) totalRate
1330{
1331    return [self downloadRate] + [self uploadRate];
1332}
1333
1334- (uint64_t) haveVerified
1335{
1336    return fStat->haveValid;
1337}
1338
1339- (uint64_t) haveTotal
1340{
1341    return [self haveVerified] + fStat->haveUnchecked;
1342}
1343
1344- (uint64_t) totalSizeSelected
1345{
1346    return fStat->sizeWhenDone;
1347}
1348
1349- (uint64_t) downloadedTotal
1350{
1351    return fStat->downloadedEver;
1352}
1353
1354- (uint64_t) uploadedTotal
1355{
1356    return fStat->uploadedEver;
1357}
1358
1359- (uint64_t) failedHash
1360{
1361    return fStat->corruptEver;
1362}
1363
1364- (CGFloat) swarmSpeed
1365{
1366    return fStat->swarmSpeed;
1367}
1368
1369- (NSInteger) orderValue
1370{
1371    return fOrderValue;
1372}
1373
1374- (void) setOrderValue: (NSInteger) orderValue
1375{
1376    fOrderValue = orderValue;
1377}
1378
1379- (NSInteger) groupValue
1380{
1381    return fGroupValue;
1382}
1383
1384- (void) setGroupValue: (NSInteger) goupValue
1385{
1386    fGroupValue = goupValue;
1387}
1388
1389- (NSInteger) groupOrderValue
1390{
1391    return [[GroupsController groups] rowValueForIndex: fGroupValue];
1392}
1393
1394- (void) checkGroupValueForRemoval: (NSNotification *) notification
1395{
1396    if (fGroupValue != -1 && [[[notification userInfo] objectForKey: @"Index"] intValue] == fGroupValue)
1397        fGroupValue = -1;
1398}
1399
1400- (NSArray *) fileList
1401{
1402    return fFileList;
1403}
1404
1405- (NSInteger) fileCount
1406{
1407    return fInfo->fileCount;
1408}
1409
1410- (void) updateFileStat
1411{
1412    if (fFileStat)
1413        tr_torrentFilesFree(fFileStat, [self fileCount]);
1414   
1415    fFileStat = tr_torrentFiles(fHandle, NULL);
1416}
1417
1418- (CGFloat) fileProgress: (FileListNode *) node
1419{
1420    if ([self isComplete])
1421        return 1.0;
1422   
1423    if (!fFileStat)
1424        [self updateFileStat];
1425   
1426    NSIndexSet * indexSet = [node indexes];
1427   
1428    if ([indexSet count] == 1)
1429        return fFileStat[[indexSet firstIndex]].progress;
1430   
1431    uint64_t have = 0;
1432    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1433        have += fFileStat[index].bytesCompleted;
1434   
1435    NSAssert([node size], @"director in torrent file has size 0");
1436    return (CGFloat)have / [node size];
1437}
1438
1439- (NSArray *) flatFileList
1440{
1441    return fFlatFileList;
1442}
1443
1444- (BOOL) canChangeDownloadCheckForFile: (NSInteger) index
1445{
1446    if (!fFileStat)
1447        [self updateFileStat];
1448   
1449    return [self fileCount] > 1 && fFileStat[index].progress < 1.0;
1450}
1451
1452- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1453{
1454    if ([self fileCount] <= 1 || [self isComplete])
1455        return NO;
1456   
1457    if (!fFileStat)
1458        [self updateFileStat];
1459   
1460    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1461        if (fFileStat[index].progress < 1.0)
1462            return YES;
1463    return NO;
1464}
1465
1466- (NSInteger) checkForFiles: (NSIndexSet *) indexSet
1467{
1468    BOOL onState = NO, offState = NO;
1469    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1470    {
1471        if (tr_torrentGetFileDL(fHandle, index) || ![self canChangeDownloadCheckForFile: index])
1472            onState = YES;
1473        else
1474            offState = YES;
1475       
1476        if (onState && offState)
1477            return NSMixedState;
1478    }
1479    return onState ? NSOnState : NSOffState;
1480}
1481
1482- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet
1483{
1484    NSUInteger count = [indexSet count];
1485    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1486    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1487        files[i] = index;
1488   
1489    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1490    free(files);
1491   
1492    [self update];
1493    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFileCheckChange" object: self];
1494}
1495
1496- (void) setFilePriority: (NSInteger) priority forIndexes: (NSIndexSet *) indexSet
1497{
1498    const NSUInteger count = [indexSet count];
1499    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1500    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1501        files[i] = index;
1502   
1503    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1504    free(files);
1505}
1506
1507- (BOOL) hasFilePriority: (NSInteger) priority forIndexes: (NSIndexSet *) indexSet
1508{
1509    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1510        if (priority == tr_torrentGetFilePriority(fHandle, index) && [self canChangeDownloadCheckForFile: index])
1511            return YES;
1512    return NO;
1513}
1514
1515- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1516{
1517    BOOL low = NO, normal = NO, high = NO;
1518    NSMutableSet * priorities = [NSMutableSet setWithCapacity: 3];
1519   
1520    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1521    {
1522        if (![self canChangeDownloadCheckForFile: index])
1523            continue;
1524       
1525        NSInteger priority = tr_torrentGetFilePriority(fHandle, index);
1526        if (priority == TR_PRI_LOW)
1527        {
1528            if (low)
1529                continue;
1530            low = YES;
1531        }
1532        else if (priority == TR_PRI_HIGH)
1533        {
1534            if (high)
1535                continue;
1536            high = YES;
1537        }
1538        else
1539        {
1540            if (normal)
1541                continue;
1542            normal = YES;
1543        }
1544       
1545        [priorities addObject: [NSNumber numberWithInt: priority]];
1546        if (low && normal && high)
1547            break;
1548    }
1549    return priorities;
1550}
1551
1552- (NSDate *) dateAdded
1553{
1554    time_t date = fStat->addedDate;
1555    return [NSDate dateWithTimeIntervalSince1970: date];
1556}
1557
1558- (NSDate *) dateCompleted
1559{
1560    time_t date = fStat->doneDate;
1561    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1562}
1563
1564- (NSDate *) dateActivity
1565{
1566    time_t date = fStat->activityDate;
1567    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1568}
1569
1570- (NSDate *) dateActivityOrAdd
1571{
1572    NSDate * date = [self dateActivity];
1573    return date ? date : [self dateAdded];
1574}
1575
1576- (NSInteger) stalledMinutes
1577{
1578    time_t start = fStat->startDate;
1579    if (start == 0)
1580        return -1;
1581   
1582    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start],
1583            * activity = [self dateActivity];
1584   
1585    NSDate * laterDate = activity ? [started laterDate: activity] : started;
1586    return -1 * [laterDate timeIntervalSinceNow] / 60;
1587}
1588
1589- (BOOL) isStalled
1590{
1591    return fStalled;
1592}
1593
1594- (NSInteger) stateSortKey
1595{
1596    if (![self isActive]) //paused
1597        return 0;
1598    else if ([self isSeeding]) //seeding
1599        return 1;
1600    else //downloading
1601        return 2;
1602}
1603
1604- (tr_torrent *) torrentStruct
1605{
1606    return fHandle;
1607}
1608
1609@end
1610
1611@implementation Torrent (Private)
1612
1613//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1614- (id) initWithHash: (NSString *) hashString path: (NSString *) path torrentStruct: (tr_torrent *) torrentStruct lib: (tr_session *) lib
1615        publicTorrent: (NSNumber *) publicTorrent
1616        downloadFolder: (NSString *) downloadFolder
1617        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
1618        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
1619        waitToStart: (NSNumber *) waitToStart
1620        orderValue: (NSNumber *) orderValue groupValue: (NSNumber *) groupValue addedTrackers: (NSNumber *) addedTrackers
1621{
1622    if (!(self = [super init]))
1623        return nil;
1624   
1625    fDefaults = [NSUserDefaults standardUserDefaults];
1626
1627    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1628    if (fPublicTorrent)
1629        fPublicTorrentLocation = [path retain];
1630   
1631    fDownloadFolder = downloadFolder ? downloadFolder : [fDefaults stringForKey: @"DownloadFolder"];
1632    fDownloadFolder = [[fDownloadFolder stringByExpandingTildeInPath] retain];
1633   
1634    fUseIncompleteFolder = useIncompleteFolder ? [useIncompleteFolder boolValue]
1635                                : [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
1636    if (fUseIncompleteFolder)
1637    {
1638        fIncompleteFolder = incompleteFolder ? incompleteFolder : [fDefaults stringForKey: @"IncompleteDownloadFolder"];
1639        fIncompleteFolder = [[fIncompleteFolder stringByExpandingTildeInPath] retain];
1640    }
1641   
1642    if (torrentStruct)
1643    {
1644        fHandle = torrentStruct;
1645        fInfo = tr_torrentInfo(fHandle);
1646       
1647        NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: fInfo->name]]
1648                                                ? fIncompleteFolder : fDownloadFolder;
1649        tr_torrentSetDownloadDir(fHandle, [currentDownloadFolder UTF8String]);
1650    }
1651    else
1652    {
1653        //set libtransmission settings for initialization
1654        tr_ctor * ctor = tr_ctorNew(lib);
1655        tr_ctorSetPaused(ctor, TR_FORCE, YES);
1656        tr_ctorSetPeerLimit(ctor, TR_FALLBACK, [fDefaults integerForKey: @"PeersTorrent"]);
1657       
1658        tr_info info;
1659        if (hashString)
1660        {
1661            tr_ctorSetMetainfoFromHash(ctor, [hashString UTF8String]);
1662            if (tr_torrentParse(lib, ctor, &info) == TR_OK)
1663            {
1664                NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1665                                                    ? fIncompleteFolder : fDownloadFolder;
1666                tr_ctorSetDownloadDir(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1667               
1668                fHandle = tr_torrentNew(lib, ctor, NULL);
1669            }
1670            tr_metainfoFree(&info);
1671        }
1672        if (!fHandle && path)
1673        {
1674            tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]);
1675            if (tr_torrentParse(lib, ctor, &info) == TR_OK)
1676            {
1677                NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1678                                                    ? fIncompleteFolder : fDownloadFolder;
1679                tr_ctorSetDownloadDir(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1680               
1681                fHandle = tr_torrentNew(lib, ctor, NULL);
1682            }
1683            tr_metainfoFree(&info);
1684        }
1685       
1686        tr_ctorFree(ctor);
1687       
1688        if (!fHandle)
1689        {
1690            [self release];
1691            return nil;
1692        }
1693       
1694        fInfo = tr_torrentInfo(fHandle);
1695    }
1696   
1697    tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, self);
1698   
1699    fNameString = [[NSString alloc] initWithUTF8String: fInfo->name];
1700    fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString];
1701       
1702    fRatioSetting = ratioSetting ? [ratioSetting intValue] : NSMixedState;
1703    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1704    fFinishedSeeding = NO;
1705   
1706    fWaitToStart = waitToStart && [waitToStart boolValue];
1707    fResumeOnWake = NO;
1708   
1709    fOrderValue = orderValue ? [orderValue intValue] : tr_sessionCountTorrents(lib) - 1;
1710    fGroupValue = groupValue ? [groupValue intValue] : [[GroupsController groups] groupIndexForTorrent: self];
1711   
1712    fAddedTrackers = addedTrackers ? [addedTrackers boolValue] : NO;
1713   
1714    [self createFileList];
1715   
1716    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(checkGroupValueForRemoval:)
1717        name: @"GroupValueRemoved" object: nil];
1718   
1719    [self update];
1720   
1721    //mark incomplete files to be ignored by Time Machine
1722    [self setTimeMachineExclude: ![self allDownloaded] forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1723   
1724    return self;
1725}
1726
1727- (void) createFileList
1728{
1729    if ([self isFolder])
1730    {
1731        NSInteger count = [self fileCount];
1732        NSMutableArray * fileList = [[NSMutableArray alloc] initWithCapacity: count],
1733                    * flatFileList = [[NSMutableArray alloc] initWithCapacity: count];
1734       
1735        for (NSInteger i = 0; i < count; i++)
1736        {
1737            tr_file * file = &fInfo->files[i];
1738           
1739            NSMutableArray * pathComponents = [[[NSString stringWithUTF8String: file->name] pathComponents] mutableCopy];
1740            NSString * path = [pathComponents objectAtIndex: 0];
1741            NSString * name = [pathComponents objectAtIndex: 1];
1742            [pathComponents removeObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, 2)]];
1743           
1744            if ([pathComponents count] > 0)
1745            {
1746                //determine if folder node already exists
1747                FileListNode * node = nil;
1748                for (node in fileList)
1749                    if ([[node name] isEqualToString: name] && [node isFolder])
1750                        break;
1751               
1752                if (!node)
1753                {
1754                    node = [[FileListNode alloc] initWithFolderName: name path: path];
1755                    [fileList addObject: node];
1756                    [node release];
1757                }
1758               
1759                [node insertIndex: i withSize: file->length];
1760                [self insertPath: pathComponents forParent: node fileSize: file->length index: i flatList: flatFileList];
1761            }
1762            else
1763            {
1764                FileListNode * node = [[FileListNode alloc] initWithFileName: name path: path size: file->length index: i];
1765                [fileList addObject: node];
1766                [flatFileList addObject: node];
1767                [node release];
1768            }
1769           
1770            [pathComponents release];
1771        }
1772       
1773        fFileList = [[NSArray alloc] initWithArray: fileList];
1774        [fileList release];
1775       
1776        fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1777        [flatFileList release];
1778    }
1779    else
1780    {
1781        FileListNode * node = [[FileListNode alloc] initWithFileName: [self name] path: @"" size: [self size] index: 0];
1782        fFileList = [[NSArray arrayWithObject: node] retain];
1783        fFlatFileList = [fFileList copy];
1784        [node release];
1785    }
1786}
1787
1788- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
1789    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList
1790{
1791    NSString * name = [components objectAtIndex: 0];
1792    BOOL isFolder = [components count] > 1;
1793   
1794    FileListNode * node = nil;
1795    if (isFolder)
1796    {
1797        for (node in [parent children])
1798            if ([[node name] isEqualToString: name] && [node isFolder])
1799                break;
1800    }
1801   
1802    //create new folder or file if it doesn't already exist
1803    if (!node)
1804    {
1805        if (isFolder)
1806            node = [[FileListNode alloc] initWithFolderName: name path: [parent fullPath]];
1807        else
1808        {
1809            node = [[FileListNode alloc] initWithFileName: name path: [parent fullPath] size: size index: index];
1810            [flatFileList addObject: node];
1811        }
1812       
1813        [parent insertChild: node];
1814        [node release];
1815    }
1816   
1817    if (isFolder)
1818    {
1819        [node insertIndex: index withSize: size];
1820       
1821        [components removeObjectAtIndex: 0];
1822        [self insertPath: components forParent: node fileSize: size index: index flatList: flatFileList];
1823    }
1824}
1825
1826- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name
1827{
1828    return fUseIncompleteFolder &&
1829        ![[NSFileManager defaultManager] fileExistsAtPath: [fDownloadFolder stringByAppendingPathComponent: name]];
1830}
1831
1832- (void) updateDownloadFolder
1833{
1834    //remove old Time Machine location
1835    [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1836   
1837    NSString * folder = [self shouldUseIncompleteFolderForName: [self name]] ? fIncompleteFolder : fDownloadFolder;
1838    tr_torrentSetDownloadDir(fHandle, [folder UTF8String]);
1839   
1840    [self setTimeMachineExclude: ![self allDownloaded] forPath: [folder stringByAppendingPathComponent: [self name]]];
1841}
1842
1843//status has been retained
1844- (void) completenessChange: (NSNumber *) status
1845{
1846    fStat = tr_torrentStat(fHandle); //don't call update yet to avoid auto-stop
1847   
1848    BOOL canMove;
1849    switch ([status intValue])
1850    {
1851        case TR_SEED:
1852        case TR_PARTIAL_SEED:
1853            canMove = YES;
1854           
1855            //move file from incomplete folder to download folder
1856            if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
1857                && (canMove = [self alertForMoveFolderAvailable]))
1858            {
1859                [self quickPause];
1860               
1861                if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
1862                                        toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
1863                    [self updateDownloadFolder];
1864                else
1865                    canMove = NO;
1866               
1867                [self endQuickPause];
1868            }
1869           
1870            if (!canMove)
1871            {
1872                fUseIncompleteFolder = NO;
1873               
1874                [fDownloadFolder release];
1875                fDownloadFolder = fIncompleteFolder;
1876                fIncompleteFolder = nil;
1877            }
1878           
1879            //allow to be backed up by Time Machine
1880            [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1881           
1882            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
1883            break;
1884       
1885        case TR_LEECH:
1886            //do not allow to be backed up by Time Machine
1887            [self setTimeMachineExclude: YES forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1888           
1889            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
1890            break;
1891    }
1892    [status release];
1893   
1894    [self update];
1895}
1896
1897- (void) quickPause
1898{
1899    if (fQuickPauseDict)
1900        return;
1901
1902    fQuickPauseDict = [[NSDictionary alloc] initWithObjectsAndKeys:
1903                    [NSNumber numberWithInt: [self speedMode: YES]], @"UploadSpeedMode",
1904                    [NSNumber numberWithInt: [self speedLimit: YES]], @"UploadSpeedLimit",
1905                    [NSNumber numberWithInt: [self speedMode: NO]], @"DownloadSpeedMode",
1906                    [NSNumber numberWithInt: [self speedLimit: NO]], @"DownloadSpeedLimit", nil];
1907   
1908    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: YES];
1909    [self setSpeedLimit: 0 upload: YES];
1910    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: NO];
1911    [self setSpeedLimit: 0 upload: NO];
1912}
1913
1914- (void) endQuickPause
1915{
1916    if (!fQuickPauseDict)
1917        return;
1918   
1919    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"UploadSpeedMode"] intValue] upload: YES];
1920    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"UploadSpeedLimit"] intValue] upload: YES];
1921    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"DownloadSpeedMode"] intValue] upload: NO];
1922    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"DownloadSpeedLimit"] intValue] upload: NO];
1923   
1924    [fQuickPauseDict release];
1925    fQuickPauseDict = nil;
1926}
1927
1928- (NSString *) etaString: (NSInteger) eta
1929{
1930    switch (eta)
1931    {
1932        case TR_ETA_NOT_AVAIL:
1933        case TR_ETA_UNKNOWN:
1934            return NSLocalizedString(@"remaining time unknown", "Torrent -> eta string");
1935        default:
1936            return [NSString stringWithFormat: NSLocalizedString(@"%@ remaining", "Torrent -> eta string"),
1937                        [NSString timeString: eta showSeconds: YES maxFields: 2]];
1938    }
1939}
1940
1941- (void) updateAllTrackers: (NSMutableArray *) trackers
1942{
1943    //get count
1944    NSInteger count = 0;
1945    for (id object in trackers)
1946        if (![object isKindOfClass: [NSNumber class]])
1947            count++;
1948   
1949    //recreate the tracker structure
1950    tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, count);
1951    NSInteger tier = 0, i = 0;
1952    for (id object in trackers)
1953    {
1954        if (![object isKindOfClass: [NSNumber class]])
1955        {
1956            trackerStructs[i].tier = tier;
1957            trackerStructs[i].announce = (char *)[object UTF8String];
1958            i++;
1959        }
1960        else
1961            tier++;
1962    }
1963   
1964    tr_torrentSetAnnounceList(fHandle, trackerStructs, count);
1965    tr_free(trackerStructs);
1966}
1967
1968+ (void) trashFile: (NSString *) path
1969{
1970    //attempt to move to trash
1971    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1972        source: [path stringByDeletingLastPathComponent] destination: @""
1973        files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1974    {
1975        //if cannot trash, just delete it (will work if it's on a remote volume)
1976        NSError * error;
1977        if (![[NSFileManager defaultManager] removeItemAtPath: path error: &error])
1978            NSLog(@"Could not trash %@: %@", path, [error localizedDescription]);
1979    }
1980}
1981
1982- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path
1983{
1984    CSBackupSetItemExcluded((CFURLRef)[NSURL fileURLWithPath: path], exclude, true);
1985}
1986
1987@end
Note: See TracBrowser for help on using the repository browser.