source: trunk/macosx/AddWindowController.m

Last change on this file was 14587, checked in by mikedld, 6 years ago

Use tr_sys_path_remove instead of remove

  • Property svn:keywords set to Date Rev Author Id
File size: 14.2 KB
Line 
1/******************************************************************************
2 * $Id: AddWindowController.m 14587 2015-10-23 04:09:40Z mikedld $
3 *
4 * Copyright (c) 2008-2012 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 "AddWindowController.h"
26#import "Controller.h"
27#import "ExpandedPathToIconTransformer.h"
28#import "FileOutlineController.h"
29#import "GroupsController.h"
30#import "NSStringAdditions.h"
31#import "Torrent.h"
32
33#define UPDATE_SECONDS 1.0
34
35#define POPUP_PRIORITY_HIGH 0
36#define POPUP_PRIORITY_NORMAL 1
37#define POPUP_PRIORITY_LOW 2
38
39@interface AddWindowController (Private)
40
41- (void) updateFiles;
42
43- (void) confirmAdd;
44
45- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType;
46
47- (void) setGroupsMenu;
48- (void) changeGroupValue: (id) sender;
49
50- (void) sameNameAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo;
51
52@end
53
54@implementation AddWindowController
55
56- (id) initWithTorrent: (Torrent *) torrent destination: (NSString *) path lockDestination: (BOOL) lockDestination
57    controller: (Controller *) controller torrentFile: (NSString *) torrentFile
58    deleteTorrentCheckEnableInitially: (BOOL) deleteTorrent canToggleDelete: (BOOL) canToggleDelete
59{
60    if ((self = [super initWithWindowNibName: @"AddWindow"]))
61    {
62        fTorrent = torrent;
63        fDestination = [[path stringByExpandingTildeInPath] retain];
64        fLockDestination = lockDestination;
65       
66        fController = controller;
67       
68        fTorrentFile = [[torrentFile stringByExpandingTildeInPath] retain];
69       
70        fDeleteTorrentEnableInitially = deleteTorrent;
71        fCanToggleDelete = canToggleDelete;
72       
73        fGroupValue = [torrent groupValue];
74        fGroupValueDetermination = TorrentDeterminationAutomatic;
75
76        [fVerifyIndicator setUsesThreadedAnimation: YES];
77    }
78    return self;
79}
80
81- (void) awakeFromNib
82{
83    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateCheckButtons:) name: @"TorrentFileCheckChange" object: fTorrent];
84   
85    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(updateGroupMenu:) name: @"UpdateGroups" object: nil];
86   
87    [fFileController setTorrent: fTorrent];
88   
89    NSString * name = [fTorrent name];
90    [[self window] setTitle: name];
91    [fNameField setStringValue: name];
92    [fNameField setToolTip: name];
93   
94    [fIconView setImage: [fTorrent icon]];
95   
96    if (![fTorrent isFolder])
97    {
98        [fFileFilterField setHidden: YES];
99        [fCheckAllButton setHidden: YES];
100        [fUncheckAllButton setHidden: YES];
101       
102        NSRect scrollFrame = [fFileScrollView frame];
103        const CGFloat diff = NSMinY([fFileScrollView frame]) - NSMinY([fFileFilterField frame]);
104        scrollFrame.origin.y -= diff;
105        scrollFrame.size.height += diff;
106        [fFileScrollView setFrame: scrollFrame];
107    }
108    else
109        [self updateCheckButtons: nil];
110   
111    [self setGroupsMenu];
112    [fGroupPopUp selectItemWithTag: fGroupValue];
113   
114    NSInteger priorityIndex;
115    switch ([fTorrent priority])
116    {
117        case TR_PRI_HIGH: priorityIndex = POPUP_PRIORITY_HIGH; break;
118        case TR_PRI_NORMAL: priorityIndex = POPUP_PRIORITY_NORMAL; break;
119        case TR_PRI_LOW: priorityIndex = POPUP_PRIORITY_LOW; break;
120        default: NSAssert1(NO, @"Unknown priority for adding torrent: %d", [fTorrent priority]);
121    }
122    [fPriorityPopUp selectItemAtIndex: priorityIndex];
123   
124    [fStartCheck setState: [[NSUserDefaults standardUserDefaults] boolForKey: @"AutoStartDownload"] ? NSOnState : NSOffState];
125   
126    [fDeleteCheck setState: fDeleteTorrentEnableInitially ? NSOnState : NSOffState];
127    [fDeleteCheck setEnabled: fCanToggleDelete];
128   
129    if (fDestination)
130        [self setDestinationPath: fDestination determinationType: (fLockDestination ? TorrentDeterminationUserSpecified : TorrentDeterminationAutomatic)];
131    else
132    {
133        [fLocationField setStringValue: @""];
134        [fLocationImageView setImage: nil];
135    }
136   
137    fTimer = [[NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self
138                selector: @selector(updateFiles) userInfo: nil repeats: YES] retain];
139    [self updateFiles];
140}
141
142- (void) windowDidLoad
143{
144    //if there is no destination, prompt for one right away
145    if (!fDestination)
146        [self setDestination: nil];
147}
148
149- (void) dealloc
150{
151    [[NSNotificationCenter defaultCenter] removeObserver: self];
152   
153    [fTimer invalidate];
154    [fTimer release];
155   
156    [fDestination release];
157    [fTorrentFile release];
158   
159    [super dealloc];
160}
161
162- (Torrent *) torrent
163{
164    return fTorrent;
165}
166
167- (void) setDestination: (id) sender
168{
169    NSOpenPanel * panel = [NSOpenPanel openPanel];
170
171    [panel setPrompt: NSLocalizedString(@"Select", "Open torrent -> prompt")];
172    [panel setAllowsMultipleSelection: NO];
173    [panel setCanChooseFiles: NO];
174    [panel setCanChooseDirectories: YES];
175    [panel setCanCreateDirectories: YES];
176   
177    [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
178                        "Add -> select destination folder"), [fTorrent name]]];
179   
180    [panel beginSheetModalForWindow: [self window] completionHandler: ^(NSInteger result) {
181        if (result == NSFileHandlingPanelOKButton)
182        {
183            fLockDestination = YES;
184            [self setDestinationPath: [[[panel URLs] objectAtIndex: 0] path] determinationType: TorrentDeterminationUserSpecified];
185        }
186        else
187        {
188            if (!fDestination)
189                [self performSelectorOnMainThread: @selector(cancelAdd:) withObject: nil waitUntilDone: NO];
190        }
191    }];
192}
193
194- (void) add: (id) sender
195{
196    if ([[fDestination lastPathComponent] isEqualToString: [fTorrent name]]
197        && [[NSUserDefaults standardUserDefaults] boolForKey: @"WarningFolderDataSameName"])
198    {
199        NSAlert * alert = [[NSAlert alloc] init];
200        [alert setMessageText: NSLocalizedString(@"The destination directory and root data directory have the same name.",
201                                "Add torrent -> same name -> title")];
202        [alert setInformativeText: NSLocalizedString(@"If you are attempting to use already existing data,"
203            " the root data directory should be inside the destination directory.", "Add torrent -> same name -> message")];
204        [alert setAlertStyle: NSWarningAlertStyle];
205        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Add torrent -> same name -> button")];
206        [alert addButtonWithTitle: NSLocalizedString(@"Add", "Add torrent -> same name -> button")];
207        [alert setShowsSuppressionButton: YES];
208       
209        [alert beginSheetModalForWindow: [self window] modalDelegate: self
210            didEndSelector: @selector(sameNameAlertDidEnd:returnCode:contextInfo:) contextInfo: nil];
211    }
212    else
213        [self confirmAdd];
214}
215
216- (void) cancelAdd: (id) sender
217{
218    [[self window] performClose: sender];
219}
220
221//only called on cancel
222- (BOOL) windowShouldClose: (id) window
223{
224    [fTimer invalidate];
225    [fTimer release];
226    fTimer = nil;
227   
228    [fFileController setTorrent: nil]; //avoid a crash when window tries to update
229   
230    [fController askOpenConfirmed: self add: NO];
231    return YES;
232}
233
234- (void) setFileFilterText: (id) sender
235{
236    [fFileController setFilterText: [sender stringValue]];
237}
238
239- (IBAction) checkAll: (id) sender
240{
241    [fFileController checkAll];
242}
243
244- (IBAction) uncheckAll: (id) sender
245{
246    [fFileController uncheckAll];
247}
248
249- (void) verifyLocalData: (id) sender
250{
251    [fTorrent resetCache];
252    [self updateFiles];
253}
254
255- (void) changePriority: (id) sender
256{
257    tr_priority_t priority;
258    switch ([sender indexOfSelectedItem])
259    {
260        case POPUP_PRIORITY_HIGH: priority = TR_PRI_HIGH; break;
261        case POPUP_PRIORITY_NORMAL: priority = TR_PRI_NORMAL; break;
262        case POPUP_PRIORITY_LOW: priority = TR_PRI_LOW; break;
263        default: NSAssert1(NO, @"Unknown priority tag for adding torrent: %ld", [sender tag]);
264    }
265    [fTorrent setPriority: priority];
266}
267
268- (void) updateCheckButtons: (NSNotification *) notification
269{
270    NSString * statusString = [NSString stringForFileSize: [fTorrent size]];
271    if ([fTorrent isFolder])
272    {
273        //check buttons
274        //keep synced with identical code in InfoFileViewController.m
275        const NSInteger filesCheckState = [fTorrent checkForFiles: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, [fTorrent fileCount])]];
276        [fCheckAllButton setEnabled: filesCheckState != NSOnState]; //if anything is unchecked
277        [fUncheckAllButton setEnabled: ![fTorrent allDownloaded]]; //if there are any checked files that aren't finished
278       
279        //status field
280        NSString * fileString;
281        NSInteger count = [fTorrent fileCount];
282        if (count != 1)
283            fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Add torrent -> info"),
284                            [NSString formattedUInteger: count]];
285        else
286            fileString = NSLocalizedString(@"1 file", "Add torrent -> info");
287       
288        NSString * selectedString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Add torrent -> info"),
289                                        [NSString stringForFileSize: [fTorrent totalSizeSelected]]];
290       
291        statusString = [NSString stringWithFormat: @"%@, %@ (%@)", fileString, statusString, selectedString];
292    }
293   
294    [fStatusField setStringValue: statusString];
295}
296
297- (void) updateGroupMenu: (NSNotification *) notification
298{
299    [self setGroupsMenu];
300    if (![fGroupPopUp selectItemWithTag: fGroupValue])
301    {
302        fGroupValue = -1;
303                fGroupValueDetermination = TorrentDeterminationAutomatic;
304        [fGroupPopUp selectItemWithTag: fGroupValue];
305    }
306}
307
308@end
309
310@implementation AddWindowController (Private)
311
312- (void) updateFiles
313{
314    [fTorrent update];
315   
316    [fFileController refresh];
317   
318    [self updateCheckButtons: nil]; //call in case button state changed by checking
319   
320    if ([fTorrent isChecking])
321    {
322        const BOOL waiting = [fTorrent isCheckingWaiting];
323        [fVerifyIndicator setIndeterminate: waiting];
324        if (waiting)
325            [fVerifyIndicator startAnimation: self];
326        else
327            [fVerifyIndicator setDoubleValue: [fTorrent checkingProgress]];
328    }
329    else {
330        [fVerifyIndicator setIndeterminate: YES]; //we want to hide when stopped, which only applies when indeterminate
331        [fVerifyIndicator stopAnimation: self];
332    }
333}
334
335- (void) confirmAdd
336{
337    [fTimer invalidate];
338    [fTimer release];
339    fTimer = nil;
340    [fTorrent setGroupValue: fGroupValue  determinationType: fGroupValueDetermination];
341
342    if (fTorrentFile && fCanToggleDelete && [fDeleteCheck state] == NSOnState)
343        [Torrent trashFile: fTorrentFile error: nil];
344   
345    if ([fStartCheck state] == NSOnState)
346        [fTorrent startTransfer];
347   
348    [fFileController setTorrent: nil]; //avoid a crash when window tries to update
349   
350    [self close];
351    [fController askOpenConfirmed: self add: YES]; //ensure last, since it releases this controller
352}
353
354- (void) setDestinationPath: (NSString *) destination determinationType: (TorrentDeterminationType) determinationType
355{
356    destination = [destination stringByExpandingTildeInPath];
357    if (!fDestination || ![fDestination isEqualToString: destination])
358    {
359        [fDestination release];
360        fDestination = [destination retain];
361       
362        [fTorrent changeDownloadFolderBeforeUsing: fDestination determinationType: determinationType];
363    }
364   
365    [fLocationField setStringValue: [fDestination stringByAbbreviatingWithTildeInPath]];
366    [fLocationField setToolTip: fDestination];
367   
368    ExpandedPathToIconTransformer * iconTransformer = [[ExpandedPathToIconTransformer alloc] init];
369    [fLocationImageView setImage: [iconTransformer transformedValue: fDestination]];
370    [iconTransformer release];
371}
372
373- (void) setGroupsMenu
374{
375    NSMenu * groupMenu = [[GroupsController groups] groupMenuWithTarget: self action: @selector(changeGroupValue:) isSmall: NO];
376    [fGroupPopUp setMenu: groupMenu];
377}
378
379- (void) changeGroupValue: (id) sender
380{
381    NSInteger previousGroup = fGroupValue;
382    fGroupValue = [sender tag];
383    fGroupValueDetermination = TorrentDeterminationUserSpecified;
384
385    if (!fLockDestination)
386    {
387        if ([[GroupsController groups] usesCustomDownloadLocationForIndex: fGroupValue])
388            [self setDestinationPath: [[GroupsController groups] customDownloadLocationForIndex: fGroupValue] determinationType: TorrentDeterminationAutomatic];
389        else if ([fDestination isEqualToString: [[GroupsController groups] customDownloadLocationForIndex: previousGroup]])
390            [self setDestinationPath: [[NSUserDefaults standardUserDefaults] stringForKey: @"DownloadFolder"] determinationType: TorrentDeterminationAutomatic];
391        else;
392    }
393}
394
395- (void) sameNameAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
396{
397    if ([[alert suppressionButton] state] == NSOnState)
398        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningFolderDataSameName"];
399   
400    [alert release];
401   
402    if (returnCode == NSAlertSecondButtonReturn)
403        [self performSelectorOnMainThread: @selector(confirmAdd) withObject: nil waitUntilDone: NO];
404}
405
406@end
Note: See TracBrowser for help on using the repository browser.