source: trunk/macosx/AddWindowController.m @ 13309

Last change on this file since 13309 was 13309, checked in by livings124, 10 years ago

#4912 Filter and check all/uncheck all in Add Transfer window

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