source: trunk/macosx/CreatorWindowController.m @ 2175

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

save the download location

File size: 14.3 KB
Line 
1/******************************************************************************
2 * $Id$
3 *
4 * Copyright (c) 2007 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "CreatorWindowController.h"
26#import "StringAdditions.h"
27
28@interface CreatorWindowController (Private)
29
30+ (NSString *) chooseFile;
31- (void) locationSheetClosed: (NSSavePanel *) openPanel returnCode: (int) code contextInfo: (void *) info;
32- (void) checkProgress;
33- (void) failureSheetClosed: (NSAlert *) alert returnCode: (int) code contextInfo: (void *) info;
34
35@end
36
37@implementation CreatorWindowController
38
39+ (void) createTorrentFile: (tr_handle_t *) handle
40{
41    //get file/folder for torrent
42    NSString * path;
43    if (!(path = [CreatorWindowController chooseFile]))
44        return;
45   
46    CreatorWindowController * creator = [[self alloc] initWithWindowNibName: @"Creator" handle: handle path: path];
47    [creator showWindow: nil];
48}
49
50+ (void) createTorrentFile: (tr_handle_t *) handle forFile: (NSString *) file
51{
52    CreatorWindowController * creator = [[self alloc] initWithWindowNibName: @"Creator" handle: handle path: file];
53    [creator showWindow: nil];
54}
55
56- (id) initWithWindowNibName: (NSString *) name handle: (tr_handle_t *) handle path: (NSString *) path
57{
58    if ((self = [super initWithWindowNibName: name]))
59    {
60        fStarted = NO;
61       
62        fPath = [path retain];
63        fInfo = tr_metaInfoBuilderCreate(handle, [fPath UTF8String]);
64        if (fInfo->fileCount == 0)
65        {
66            NSAlert * alert = [[[NSAlert alloc] init] autorelease];
67            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no files -> button")];
68            [alert setMessageText: NSLocalizedString(@"This folder contains no files.",
69                                                    "Create torrent -> no files -> title")];
70            [alert setInformativeText: NSLocalizedString(@"There must be at least one file in a folder to create a torrent file.",
71                                                        "Create torrent -> no files -> warning")];
72            [alert setAlertStyle: NSWarningAlertStyle];
73           
74            [alert runModal];
75           
76            [self release];
77            return nil;
78        }
79       
80        fDefaults = [NSUserDefaults standardUserDefaults];
81    }
82    return self;
83}
84
85- (void) awakeFromNib
86{
87    NSString * name = [fPath lastPathComponent];
88   
89    [[self window] setTitle: name];
90   
91    [fNameField setStringValue: name];
92    [fNameField setToolTip: fPath];
93   
94    BOOL multifile = !fInfo->isSingleFile;
95   
96    #warning fix when resizing window
97    [fIcon setImage: [[NSWorkspace sharedWorkspace] iconForFileType: multifile
98                        ? NSFileTypeForHFSTypeCode('fldr') : [fPath pathExtension]]];
99   
100    NSString * statusString = [NSString stringForFileSize: fInfo->totalSize];
101    if (multifile)
102    {
103        NSString * fileString;
104        int count = fInfo->fileCount;
105        if (count != 1)
106            fileString = [NSString stringWithFormat: NSLocalizedString(@"%d Files, ", "Create torrent -> info"), count];
107        else
108            fileString = NSLocalizedString(@"1 File, ", "Create torrent -> info");
109        statusString = [fileString stringByAppendingString: statusString];
110    }
111    [fStatusField setStringValue: statusString];
112   
113    NSString * piecesCountString;
114    int piecesCount = fInfo->pieceCount;
115    if (piecesCount == 1)
116        piecesCountString = NSLocalizedString(@"1 piece", "Create torrent -> info");
117    else
118        piecesCountString = [NSString stringWithFormat: NSLocalizedString(@"%d pieces", "Create torrent -> info"),
119                                                                piecesCount];
120    [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@, %@ each", "Create torrent -> info"),
121                                        piecesCountString, [NSString stringForFileSize: fInfo->pieceSize]]];
122   
123    fLocation = [[[[fDefaults stringForKey: @"CreatorLocation"] stringByExpandingTildeInPath] stringByAppendingPathComponent:
124                    [name stringByAppendingPathExtension: @"torrent"]] retain];
125    [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
126    [fLocationField setToolTip: fLocation];
127   
128    //set previously saved values
129    NSString * tracker;
130    if ((tracker = [fDefaults stringForKey: @"CreatorTracker"]))
131        [fTrackerField setStringValue: tracker];
132   
133    if ([fDefaults objectForKey: @"CreatorPrivate"])
134        [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState];
135   
136    if ([fDefaults objectForKey: @"CreatorOpen"])
137        [fOpenCheck setState: [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState];
138}
139
140- (void) dealloc
141{
142    [fPath release];
143    if (fLocation)
144        [fLocation release];
145   
146    if (fInfo)
147        tr_metaInfoBuilderFree(fInfo);
148   
149    if (fTimer)
150        [fTimer invalidate];
151   
152    [super dealloc];
153}
154
155- (void) setLocation: (id) sender
156{
157    NSSavePanel * panel = [NSSavePanel savePanel];
158
159    [panel setPrompt: @"Select"];
160    [panel setRequiredFileType: @"torrent"];
161    [panel setCanSelectHiddenExtension: YES];
162
163    [panel beginSheetForDirectory: nil file: [fLocation lastPathComponent] modalForWindow: [self window] modalDelegate: self
164            didEndSelector: @selector(locationSheetClosed:returnCode:contextInfo:) contextInfo: nil];
165}
166
167- (void) create: (id) sender
168{
169    //parse tracker string
170    NSString * trackerString = [fTrackerField stringValue];
171    if ([trackerString rangeOfString: @"://"].location != NSNotFound)
172    {
173        if (![trackerString hasPrefix: @"http://"])
174        {
175            NSAlert * alert = [[[NSAlert alloc] init] autorelease];
176            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> http warning -> button")];
177            [alert setMessageText: NSLocalizedString(@"The tracker address must begin with \"http://\".",
178                                                    "Create torrent -> http warning -> title")];
179            [alert setInformativeText: NSLocalizedString(@"Change the tracker address to create the torrent.",
180                                                        "Create torrent -> http warning -> warning")];
181            [alert setAlertStyle: NSWarningAlertStyle];
182           
183            [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
184            return;
185        }
186    }
187    else
188        trackerString = [@"http://" stringByAppendingString: trackerString];
189   
190    //don't allow blank addresses
191    if ([trackerString length] <= 7)
192    {
193        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
194        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no url warning -> button")];
195        [alert setMessageText: NSLocalizedString(@"The tracker address cannot be blank.",
196                                                "Create torrent -> no url warning -> title")];
197        [alert setInformativeText: NSLocalizedString(@"Change the tracker address to create the torrent.",
198                                                    "Create torrent -> no url warning -> warning")];
199        [alert setAlertStyle: NSWarningAlertStyle];
200       
201        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
202        return;
203    }
204   
205    //check if a file with the same name and location already exists
206    if ([[NSFileManager defaultManager] fileExistsAtPath: fLocation])
207    {
208        NSArray * pathComponents = [fLocation pathComponents];
209        int count = [pathComponents count];
210       
211        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
212        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")];
213        [alert setMessageText: NSLocalizedString(@"A torrent file with this name and directory cannot be created.",
214                                                "Create torrent -> file already exists warning -> title")];
215        [alert setInformativeText: [NSString stringWithFormat:
216                NSLocalizedString(@"A file with the name \"%@\" already exists in the directory \"%@\". "
217                    "Choose a new name or directory to create the torrent.",
218                    "Create torrent -> file already exists warning -> warning"),
219                    [pathComponents objectAtIndex: count-1], [pathComponents objectAtIndex: count-2]]];
220        [alert setAlertStyle: NSWarningAlertStyle];
221       
222        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
223        return;
224    }
225   
226    fOpenTorrent = [fOpenCheck state] == NSOnState;
227   
228    //store values
229    [fDefaults setObject: trackerString forKey: @"CreatorTracker"];
230    [fDefaults setBool: [fPrivateCheck state] == NSOnState forKey: @"CreatorPrivate"];
231    [fDefaults setBool: fOpenTorrent forKey: @"CreatorOpen"];
232    [fDefaults setObject: [fLocation stringByDeletingLastPathComponent] forKey: @"CreatorLocation"];
233   
234    tr_makeMetaInfo(fInfo, [fLocation UTF8String], [trackerString UTF8String], [[fCommentView string] UTF8String],
235                    [fPrivateCheck state] == NSOnState);
236   
237    fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress)
238                        userInfo: nil repeats: YES];
239}
240
241- (void) cancelCreateWindow: (id) sender
242{
243    [[self window] close];
244}
245
246- (void) windowWillClose: (NSNotification *) notification
247{
248    [self release];
249}
250
251- (void) cancelCreateProgress: (id) sender
252{
253    fInfo->abortFlag = 1;
254    [fTimer fire];
255}
256
257@end
258
259@implementation CreatorWindowController (Private)
260
261+ (NSString *) chooseFile
262{
263    NSOpenPanel * panel = [NSOpenPanel openPanel];
264   
265    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> select file")];
266    [panel setAllowsMultipleSelection: NO];
267    [panel setCanChooseFiles: YES];
268    [panel setCanChooseDirectories: YES];
269    [panel setCanCreateDirectories: NO];
270
271    [panel setMessage: NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file")];
272   
273    BOOL success = [panel runModal] == NSOKButton;
274    return success ? [[panel filenames] objectAtIndex: 0] : nil;
275}
276
277- (void) locationSheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (void *) info
278{
279    if (code == NSOKButton)
280    {
281        [fLocation release];
282        fLocation = [[panel filename] retain];
283       
284        [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
285        [fLocationField setToolTip: fLocation];
286    }
287}
288
289- (void) checkProgress
290{
291    if (fInfo->isDone)
292    {
293        [fTimer invalidate];
294        fTimer = nil;
295       
296        if (fInfo->failed)
297        {
298            if (!fInfo->abortFlag)
299            {
300                NSAlert * alert = [[[NSAlert alloc] init] autorelease];
301                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")];
302                [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.",
303                                                "Create torrent -> failed -> title"), [fLocation lastPathComponent]]];
304                [alert setInformativeText: NSLocalizedString(@"There was an error parsing the data file. "
305                                            "The torrent file was not created.", "Create torrent -> failed -> warning")];
306                [alert setAlertStyle: NSWarningAlertStyle];
307               
308                [alert beginSheetModalForWindow: [self window] modalDelegate: self
309                        didEndSelector: @selector(failureSheetClosed:returnCode:contextInfo:) contextInfo: nil];
310                return;
311            }
312        }
313        else
314        {
315            if (fOpenTorrent)
316            {
317                NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: fLocation, @"File",
318                                        [fPath stringByDeletingLastPathComponent], @"Path", nil];
319                [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict];
320            }
321        }
322       
323        [[self window] close];
324    }
325    else
326    {
327        [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount];
328       
329        if (!fStarted)
330        {
331            NSWindow * window = [self window];
332           
333            NSRect windowRect = [window frame];
334            float difference = [fProgressView frame].size.height - [[window contentView] frame].size.height;
335            windowRect.origin.y -= difference;
336            windowRect.size.height += difference;
337           
338            //don't allow vertical resizing
339            float height = windowRect.size.height;
340            [window setMinSize: NSMakeSize([window minSize].width, height)];
341            [window setMaxSize: NSMakeSize([window maxSize].width, height)];
342           
343            [window setContentView: fProgressView];
344            [window setFrame: windowRect display: YES animate: YES];
345            [fProgressView setHidden: NO];
346           
347            fStarted = YES;
348        }
349    }
350}
351
352- (void) failureSheetClosed: (NSAlert *) alert returnCode: (int) code contextInfo: (void *) info
353{
354    [[alert window] orderOut: nil];
355    [[self window] close];
356}
357
358@end
Note: See TracBrowser for help on using the repository browser.