source: trunk/macosx/CreatorWindowController.m @ 2266

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

a little code cleanup

File size: 14.4 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];
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            [alert release];
76           
77            [self release];
78            return nil;
79        }
80       
81        fDefaults = [NSUserDefaults standardUserDefaults];
82    }
83    return self;
84}
85
86- (void) awakeFromNib
87{
88    NSString * name = [fPath lastPathComponent];
89   
90    [[self window] setTitle: name];
91   
92    [fNameField setStringValue: name];
93    [fNameField setToolTip: fPath];
94   
95    BOOL multifile = !fInfo->isSingleFile;
96   
97    NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: multifile
98                        ? NSFileTypeForHFSTypeCode('fldr') : [fPath pathExtension]];
99    [icon setSize: [fIconView frame].size];
100    [fIconView setImage: icon];
101   
102    NSString * statusString = [NSString stringForFileSize: fInfo->totalSize];
103    if (multifile)
104    {
105        NSString * fileString;
106        int count = fInfo->fileCount;
107        if (count != 1)
108            fileString = [NSString stringWithFormat: NSLocalizedString(@"%d Files, ", "Create torrent -> info"), count];
109        else
110            fileString = NSLocalizedString(@"1 File, ", "Create torrent -> info");
111        statusString = [fileString stringByAppendingString: statusString];
112    }
113    [fStatusField setStringValue: statusString];
114   
115    NSString * piecesCountString;
116    int piecesCount = fInfo->pieceCount;
117    if (piecesCount == 1)
118        piecesCountString = NSLocalizedString(@"1 piece", "Create torrent -> info");
119    else
120        piecesCountString = [NSString stringWithFormat: NSLocalizedString(@"%d pieces", "Create torrent -> info"),
121                                                                piecesCount];
122    [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@, %@ each", "Create torrent -> info"),
123                                        piecesCountString, [NSString stringForFileSize: fInfo->pieceSize]]];
124   
125    fLocation = [[[[fDefaults stringForKey: @"CreatorLocation"] stringByExpandingTildeInPath] stringByAppendingPathComponent:
126                    [name stringByAppendingPathExtension: @"torrent"]] retain];
127    [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
128    [fLocationField setToolTip: fLocation];
129   
130    //set previously saved values
131    NSString * tracker;
132    if ((tracker = [fDefaults stringForKey: @"CreatorTracker"]))
133        [fTrackerField setStringValue: tracker];
134   
135    if ([fDefaults objectForKey: @"CreatorPrivate"])
136        [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState];
137   
138    if ([fDefaults objectForKey: @"CreatorOpen"])
139        [fOpenCheck setState: [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState];
140}
141
142- (void) dealloc
143{
144    [fPath release];
145    if (fLocation)
146        [fLocation release];
147   
148    if (fInfo)
149        tr_metaInfoBuilderFree(fInfo);
150   
151    if (fTimer)
152        [fTimer invalidate];
153   
154    [super dealloc];
155}
156
157- (void) setLocation: (id) sender
158{
159    NSSavePanel * panel = [NSSavePanel savePanel];
160
161    [panel setPrompt: @"Select"];
162    [panel setRequiredFileType: @"torrent"];
163    [panel setCanSelectHiddenExtension: YES];
164
165    [panel beginSheetForDirectory: nil file: [fLocation lastPathComponent] modalForWindow: [self window] modalDelegate: self
166            didEndSelector: @selector(locationSheetClosed:returnCode:contextInfo:) contextInfo: nil];
167}
168
169- (void) create: (id) sender
170{
171    //parse tracker string
172    NSString * trackerString = [fTrackerField stringValue];
173    if ([trackerString rangeOfString: @"://"].location != NSNotFound)
174    {
175        if (![trackerString hasPrefix: @"http://"])
176        {
177            NSAlert * alert = [[[NSAlert alloc] init] autorelease];
178            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> http warning -> button")];
179            [alert setMessageText: NSLocalizedString(@"The tracker address must begin with \"http://\".",
180                                                    "Create torrent -> http warning -> title")];
181            [alert setInformativeText: NSLocalizedString(@"Change the tracker address to create the torrent.",
182                                                        "Create torrent -> http warning -> warning")];
183            [alert setAlertStyle: NSWarningAlertStyle];
184           
185            [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
186            return;
187        }
188    }
189    else
190        trackerString = [@"http://" stringByAppendingString: trackerString];
191   
192    //don't allow blank addresses
193    if ([trackerString length] <= 7)
194    {
195        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
196        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no url warning -> button")];
197        [alert setMessageText: NSLocalizedString(@"The tracker address cannot be blank.",
198                                                "Create torrent -> no url warning -> title")];
199        [alert setInformativeText: NSLocalizedString(@"Change the tracker address to create the torrent.",
200                                                    "Create torrent -> no url warning -> warning")];
201        [alert setAlertStyle: NSWarningAlertStyle];
202       
203        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
204        return;
205    }
206   
207    //check if a file with the same name and location already exists
208    if ([[NSFileManager defaultManager] fileExistsAtPath: fLocation])
209    {
210        NSArray * pathComponents = [fLocation pathComponents];
211        int count = [pathComponents count];
212       
213        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
214        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")];
215        [alert setMessageText: NSLocalizedString(@"A torrent file with this name and directory cannot be created.",
216                                                "Create torrent -> file already exists warning -> title")];
217        [alert setInformativeText: [NSString stringWithFormat:
218                NSLocalizedString(@"A file with the name \"%@\" already exists in the directory \"%@\". "
219                    "Choose a new name or directory to create the torrent.",
220                    "Create torrent -> file already exists warning -> warning"),
221                    [pathComponents objectAtIndex: count-1], [pathComponents objectAtIndex: count-2]]];
222        [alert setAlertStyle: NSWarningAlertStyle];
223       
224        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
225        return;
226    }
227   
228    fOpenTorrent = [fOpenCheck state] == NSOnState;
229   
230    //store values
231    [fDefaults setObject: trackerString forKey: @"CreatorTracker"];
232    [fDefaults setBool: [fPrivateCheck state] == NSOnState forKey: @"CreatorPrivate"];
233    [fDefaults setBool: fOpenTorrent forKey: @"CreatorOpen"];
234    [fDefaults setObject: [fLocation stringByDeletingLastPathComponent] forKey: @"CreatorLocation"];
235   
236    tr_makeMetaInfo(fInfo, [fLocation UTF8String], [trackerString UTF8String], [[fCommentView string] UTF8String],
237                    [fPrivateCheck state] == NSOnState);
238   
239    fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress)
240                        userInfo: nil repeats: YES];
241}
242
243- (void) cancelCreateWindow: (id) sender
244{
245    [[self window] close];
246}
247
248- (void) windowWillClose: (NSNotification *) notification
249{
250    [self release];
251}
252
253- (void) cancelCreateProgress: (id) sender
254{
255    fInfo->abortFlag = 1;
256    [fTimer fire];
257}
258
259@end
260
261@implementation CreatorWindowController (Private)
262
263+ (NSString *) chooseFile
264{
265    NSOpenPanel * panel = [NSOpenPanel openPanel];
266   
267    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> select file")];
268    [panel setAllowsMultipleSelection: NO];
269    [panel setCanChooseFiles: YES];
270    [panel setCanChooseDirectories: YES];
271    [panel setCanCreateDirectories: NO];
272
273    [panel setMessage: NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file")];
274   
275    BOOL success = [panel runModal] == NSOKButton;
276    return success ? [[panel filenames] objectAtIndex: 0] : nil;
277}
278
279- (void) locationSheetClosed: (NSSavePanel *) panel returnCode: (int) code contextInfo: (void *) info
280{
281    if (code == NSOKButton)
282    {
283        [fLocation release];
284        fLocation = [[panel filename] retain];
285       
286        [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
287        [fLocationField setToolTip: fLocation];
288    }
289}
290
291- (void) checkProgress
292{
293    if (fInfo->isDone)
294    {
295        [fTimer invalidate];
296        fTimer = nil;
297       
298        if (fInfo->failed)
299        {
300            if (!fInfo->abortFlag)
301            {
302                NSAlert * alert = [[[NSAlert alloc] init] autorelease];
303                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")];
304                [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.",
305                                                "Create torrent -> failed -> title"), [fLocation lastPathComponent]]];
306                [alert setInformativeText: NSLocalizedString(@"There was an error parsing the data file. "
307                                            "The torrent file was not created.", "Create torrent -> failed -> warning")];
308                [alert setAlertStyle: NSWarningAlertStyle];
309               
310                [alert beginSheetModalForWindow: [self window] modalDelegate: self
311                        didEndSelector: @selector(failureSheetClosed:returnCode:contextInfo:) contextInfo: nil];
312                return;
313            }
314        }
315        else
316        {
317            if (fOpenTorrent)
318            {
319                NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: fLocation, @"File",
320                                        [fPath stringByDeletingLastPathComponent], @"Path", nil];
321                [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict];
322            }
323        }
324       
325        [[self window] close];
326    }
327    else
328    {
329        [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount];
330       
331        if (!fStarted)
332        {
333            NSWindow * window = [self window];
334           
335            NSRect windowRect = [window frame];
336            float difference = [fProgressView frame].size.height - [[window contentView] frame].size.height;
337            windowRect.origin.y -= difference;
338            windowRect.size.height += difference;
339           
340            //don't allow vertical resizing
341            float height = windowRect.size.height;
342            [window setMinSize: NSMakeSize([window minSize].width, height)];
343            [window setMaxSize: NSMakeSize([window maxSize].width, height)];
344           
345            [window setContentView: fProgressView];
346            [window setFrame: windowRect display: YES animate: YES];
347            [fProgressView setHidden: NO];
348           
349            fStarted = YES;
350        }
351    }
352}
353
354- (void) failureSheetClosed: (NSAlert *) alert returnCode: (int) code contextInfo: (void *) info
355{
356    [[alert window] orderOut: nil];
357    [[self window] close];
358}
359
360@end
Note: See TracBrowser for help on using the repository browser.