source: trunk/macosx/AddWindowController.m @ 13324

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

hide the filter field and check/uncheck all buttons for single-file torrents

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