source: trunk/macosx/CreatorWindowController.m @ 13323

Last change on this file since 13323 was 13323, checked in by livings124, 9 years ago

#4923 "Open when created" might not be respected

  • Property Id set to /Users/mitchell/Desktop/Transmission/macosx/ActionMenuRatioToDisplayRatioTransformer.h
  • Property svn:keywords set to Date Rev Author Id
File size: 25.8 KB
Line 
1/******************************************************************************
2 * $Id: CreatorWindowController.m 13323 2012-05-28 19:43:53Z livings124 $
3 *
4 * Copyright (c) 2007-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 "CreatorWindowController.h"
26#import "Controller.h"
27#import "NSStringAdditions.h"
28
29#import "transmission.h" // required by utils.h
30#import "utils.h" // tr_urlIsValidTracker()
31
32#define TRACKER_ADD_TAG 0
33#define TRACKER_REMOVE_TAG 1
34
35@interface CreatorWindowController (Private)
36
37+ (NSURL *) chooseFile;
38
39- (void) updateLocationField;
40- (void) createBlankAddressAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo;
41- (void) createReal;
42- (void) checkProgress;
43- (void) failureSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info;
44
45@end
46
47@implementation CreatorWindowController
48
49+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle
50{
51    //get file/folder for torrent
52    NSURL * path;
53    if (!(path = [CreatorWindowController chooseFile]))
54        return nil;
55   
56    CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: path];
57    [creator showWindow: nil];
58    return creator;
59}
60
61+ (CreatorWindowController *) createTorrentFile: (tr_session *) handle forFile: (NSURL *) file
62{
63    CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: file];
64    [creator showWindow: nil];
65    return creator;
66}
67
68- (id) initWithHandle: (tr_session *) handle path: (NSURL *) path
69{
70    if ((self = [super initWithWindowNibName: @"Creator"]))
71    {
72        fStarted = NO;
73       
74        fPath = [path retain];
75        fInfo = tr_metaInfoBuilderCreate([[fPath path] UTF8String]);
76       
77        if (fInfo->fileCount == 0)
78        {
79            NSAlert * alert = [[NSAlert alloc] init];
80            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no files -> button")];
81            [alert setMessageText: NSLocalizedString(@"This folder contains no files.",
82                                                    "Create torrent -> no files -> title")];
83            [alert setInformativeText: NSLocalizedString(@"There must be at least one file in a folder to create a torrent file.",
84                                                        "Create torrent -> no files -> warning")];
85            [alert setAlertStyle: NSWarningAlertStyle];
86           
87            [alert runModal];
88            [alert release];
89           
90            [self release];
91            return nil;
92        }
93        if (fInfo->totalSize == 0)
94        {
95            NSAlert * alert = [[NSAlert alloc] init];
96            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> zero size -> button")];
97            [alert setMessageText: NSLocalizedString(@"The total file size is zero bytes.",
98                                                    "Create torrent -> zero size -> title")];
99            [alert setInformativeText: NSLocalizedString(@"A torrent file cannot be created for files with no size.",
100                                                        "Create torrent -> zero size -> warning")];
101            [alert setAlertStyle: NSWarningAlertStyle];
102           
103            [alert runModal];
104            [alert release];
105           
106            [self release];
107            return nil;
108        }
109       
110        fDefaults = [NSUserDefaults standardUserDefaults];
111       
112        //get list of trackers
113        if (!(fTrackers = [[fDefaults arrayForKey: @"CreatorTrackers"] mutableCopy]))
114        {
115            fTrackers = [[NSMutableArray alloc] init];
116           
117            //check for single tracker from versions before 1.3
118            NSString * tracker;
119            if ((tracker = [fDefaults stringForKey: @"CreatorTracker"]))
120            {
121                [fDefaults removeObjectForKey: @"CreatorTracker"];
122                if (![tracker isEqualToString: @""])
123                {
124                    [fTrackers addObject: tracker];
125                    [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"];
126                }
127            }
128        }
129       
130        //remove potentially invalid addresses
131        for (NSInteger i = [fTrackers count]-1; i >= 0; i--)
132        {
133            if (!tr_urlIsValidTracker([[fTrackers objectAtIndex: i] UTF8String]))
134                [fTrackers removeObjectAtIndex: i];
135        }
136    }
137    return self;
138}
139
140- (void) awakeFromNib
141{
142    [[self window] setRestorationClass: [self class]];
143   
144    NSString * name = [fPath lastPathComponent];
145   
146    [[self window] setTitle: name];
147   
148    [fNameField setStringValue: name];
149    [fNameField setToolTip: [fPath path]];
150   
151    const BOOL multifile = !fInfo->isSingleFile;
152   
153    NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: multifile
154                        ? NSFileTypeForHFSTypeCode(kGenericFolderIcon) : [fPath pathExtension]];
155    [icon setSize: [fIconView frame].size];
156    [fIconView setImage: icon];
157   
158    NSString * statusString = [NSString stringForFileSize: fInfo->totalSize];
159    if (multifile)
160    {
161        NSString * fileString;
162        NSInteger count = fInfo->fileCount;
163        if (count != 1)
164            fileString = [NSString stringWithFormat: NSLocalizedString(@"%@ files", "Create torrent -> info"),
165                            [NSString formattedUInteger: count]];
166        else
167            fileString = NSLocalizedString(@"1 file", "Create torrent -> info");
168        statusString = [NSString stringWithFormat: @"%@, %@", fileString, statusString];
169    }
170    [fStatusField setStringValue: statusString];
171   
172    if (fInfo->pieceCount == 1)
173        [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"1 piece, %@", "Create torrent -> info"),
174                                                            [NSString stringForFileSize: fInfo->pieceSize]]];
175    else
176        [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%d pieces, %@ each", "Create torrent -> info"),
177                                                            fInfo->pieceCount, [NSString stringForFileSize: fInfo->pieceSize]]];
178   
179    fLocation = [[[fDefaults URLForKey: @"CreatorLocationURL"] URLByAppendingPathComponent: [name stringByAppendingPathExtension: @"torrent"]] retain];
180    if (!fLocation)
181    {
182        //for 2.5 and earlier
183        #warning we still store "CreatorLocation" in Defaults.plist, and not "CreatorLocationURL"
184        NSString * location = [fDefaults stringForKey: @"CreatorLocation"];
185        fLocation = [[NSURL alloc] initFileURLWithPath: [[location stringByExpandingTildeInPath] stringByAppendingPathComponent: [name stringByAppendingPathExtension: @"torrent"]]];
186    }
187    [self updateLocationField];
188   
189    //set previously saved values
190    if ([fDefaults objectForKey: @"CreatorPrivate"])
191        [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState];
192   
193    [fOpenCheck setState: [fDefaults boolForKey: @"CreatorOpen"] ? NSOnState : NSOffState];
194}
195
196- (void) dealloc
197{
198    [fPath release];
199    [fLocation release];
200   
201    [fTrackers release];
202   
203    if (fInfo)
204        tr_metaInfoBuilderFree(fInfo);
205   
206    [fTimer invalidate];
207   
208    [super dealloc];
209}
210
211+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler
212{
213    NSURL * path = [state decodeObjectForKey: @"TRCreatorPath"];
214    if (!path || ![path checkResourceIsReachableAndReturnError: nil])
215    {
216        completionHandler(nil, [NSError errorWithDomain: NSURLErrorDomain code: NSURLErrorCannotOpenFile userInfo: nil]);
217        return;
218    }
219   
220    NSWindow * window = [[self createTorrentFile: [(Controller *)[NSApp delegate] sessionHandle] forFile: path] window];
221    completionHandler(window, nil);
222}
223
224- (void) window: (NSWindow *) window willEncodeRestorableState: (NSCoder *) state
225{
226    [state encodeObject: fPath forKey: @"TRCreatorPath"];
227    [state encodeObject: fLocation forKey: @"TRCreatorLocation"];
228    [state encodeObject: fTrackers forKey: @"TRCreatorTrackers"];
229    [state encodeInteger: [fOpenCheck state] forKey: @"TRCreatorOpenCheck"];
230    [state encodeInteger: [fPrivateCheck state] forKey: @"TRCreatorPrivateCheck"];
231    [state encodeObject: [fCommentView string] forKey: @"TRCreatorPrivateComment"];
232}
233
234- (void) window: (NSWindow *) window didDecodeRestorableState: (NSCoder *) coder
235{
236    [fLocation release];
237    fLocation = [[coder decodeObjectForKey: @"TRCreatorLocation"] retain];
238    [self updateLocationField];
239   
240    [fTrackers release];
241    fTrackers = [[coder decodeObjectForKey: @"TRCreatorTrackers"] retain];
242    [fTrackerTable reloadData];
243   
244    [fOpenCheck setState: [coder decodeIntegerForKey: @"TRCreatorOpenCheck"]];
245    [fPrivateCheck setState: [coder decodeIntegerForKey: @"TRCreatorPrivateCheck"]];
246    [fCommentView setString: [coder decodeObjectForKey: @"TRCreatorPrivateComment"]];
247}
248
249- (IBAction) setLocation: (id) sender
250{
251    NSSavePanel * panel = [NSSavePanel savePanel];
252
253    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> location sheet -> button")];
254    [panel setMessage: NSLocalizedString(@"Select the name and location for the torrent file.",
255                                        "Create torrent -> location sheet -> message")];
256   
257    [panel setAllowedFileTypes: [NSArray arrayWithObjects: @"org.bittorrent.torrent", @"torrent", nil]];
258    [panel setCanSelectHiddenExtension: YES];
259   
260    [panel setDirectoryURL: [fLocation URLByDeletingLastPathComponent]];
261    [panel setNameFieldStringValue: [fLocation lastPathComponent]];
262   
263    [panel beginSheetModalForWindow: [self window] completionHandler: ^(NSInteger result) {
264        if (result == NSFileHandlingPanelOKButton)
265        {
266            [fLocation release];
267            fLocation = [[panel URL] retain];
268            [self updateLocationField];
269        }
270    }];
271}
272
273- (IBAction) create: (id) sender
274{
275    //make sure the trackers are no longer being verified
276    if ([fTrackerTable editedRow] != -1)
277        [[self window] endEditingFor: fTrackerTable];
278   
279    const BOOL isPrivate = [fPrivateCheck state] == NSOnState;
280    if ([fTrackers count] == 0
281        && [fDefaults boolForKey: isPrivate ? @"WarningCreatorPrivateBlankAddress" : @"WarningCreatorBlankAddress"])
282    {
283        NSAlert * alert = [[NSAlert alloc] init];
284        [alert setMessageText: NSLocalizedString(@"There are no tracker addresses.", "Create torrent -> blank address -> title")];
285       
286        NSString * infoString = isPrivate
287                    ? NSLocalizedString(@"A transfer marked as private with no tracker addresses will be unable to connect to peers."
288                        " The torrent file will only be useful if you plan to upload the file to a tracker website"
289                        " that will add the addresses for you.", "Create torrent -> blank address -> message")
290                    : NSLocalizedString(@"The transfer will not contact trackers for peers, and will have to rely solely on"
291                        " non-tracker peer discovery methods such as PEX and DHT to download and seed.",
292                        "Create torrent -> blank address -> message");
293       
294        [alert setInformativeText: infoString];
295        [alert addButtonWithTitle: NSLocalizedString(@"Create", "Create torrent -> blank address -> button")];
296        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")];
297        [alert setShowsSuppressionButton: YES];
298
299        [alert beginSheetModalForWindow: [self window] modalDelegate: self
300            didEndSelector: @selector(createBlankAddressAlertDidEnd:returnCode:contextInfo:) contextInfo: nil];
301    }
302    else
303        [self createReal];
304}
305
306- (IBAction) cancelCreateWindow: (id) sender
307{
308    [[self window] close];
309}
310
311- (void) windowWillClose: (NSNotification *) notification
312{
313    [self autorelease];
314}
315
316- (IBAction) cancelCreateProgress: (id) sender
317{
318    fInfo->abortFlag = 1;
319    [fTimer fire];
320}
321
322- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
323{
324    return [fTrackers count];
325}
326
327- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
328{
329    return [fTrackers objectAtIndex: row];
330}
331
332- (IBAction) addRemoveTracker: (id) sender
333{
334    //don't allow add/remove when currently adding - it leads to weird results
335    if ([fTrackerTable editedRow] != -1)
336        return;
337   
338    if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG)
339    {
340        [fTrackers removeObjectsAtIndexes: [fTrackerTable selectedRowIndexes]];
341       
342        [fTrackerTable deselectAll: self];
343        [fTrackerTable reloadData];
344    }
345    else
346    {
347        [fTrackers addObject: @""];
348        [fTrackerTable reloadData];
349       
350        const NSInteger row = [fTrackers count] - 1;
351        [fTrackerTable selectRowIndexes: [NSIndexSet indexSetWithIndex: row] byExtendingSelection: NO];
352        [fTrackerTable editColumn: 0 row: row withEvent: nil select: YES];
353    }
354}
355
356- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
357    row: (NSInteger) row
358{
359    NSString * tracker = (NSString *)object;
360   
361    tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
362   
363    if ([tracker rangeOfString: @"://"].location == NSNotFound)
364        tracker = [@"http://" stringByAppendingString: tracker];
365   
366    if (!tr_urlIsValidTracker([tracker UTF8String]))
367    {
368        NSBeep();
369        [fTrackers removeObjectAtIndex: row];
370    }
371    else
372        [fTrackers replaceObjectAtIndex: row withObject: tracker];
373   
374    [fTrackerTable deselectAll: self];
375    [fTrackerTable reloadData];
376}
377
378- (void) tableViewSelectionDidChange: (NSNotification *) notification
379{
380    [fTrackerAddRemoveControl setEnabled: [fTrackerTable numberOfSelectedRows] > 0 forSegment: TRACKER_REMOVE_TAG];
381}
382
383- (void) copy: (id) sender
384{
385    NSArray * addresses = [fTrackers objectsAtIndexes: [fTrackerTable selectedRowIndexes]];
386    NSString * text = [addresses componentsJoinedByString: @"\n"];
387   
388    NSPasteboard * pb = [NSPasteboard generalPasteboard];
389    [pb clearContents];
390    [pb writeObjects: [NSArray arrayWithObject: text]];
391}
392
393- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
394{
395    const SEL action = [menuItem action];
396   
397    if (action == @selector(copy:))
398        return [[self window] firstResponder] == fTrackerTable && [fTrackerTable numberOfSelectedRows] > 0;
399   
400    if (action == @selector(paste:))
401        return [[self window] firstResponder] == fTrackerTable
402            && [[NSPasteboard generalPasteboard] canReadObjectForClasses: [NSArray arrayWithObject: [NSString class]] options: nil];
403   
404    return YES;
405}
406
407- (void) paste: (id) sender
408{
409    NSMutableArray * tempTrackers = [NSMutableArray array];
410   
411    NSArray * items = [[NSPasteboard generalPasteboard] readObjectsForClasses: [NSArray arrayWithObject: [NSString class]] options: nil];
412    NSAssert(items != nil, @"no string items to paste; should not be able to call this method");
413   
414    for (NSString * pbItem in items)
415    {
416        for (NSString * tracker in [pbItem componentsSeparatedByString: @"\n"])
417            [tempTrackers addObject: tracker];
418    }
419   
420    BOOL added = NO;
421   
422    for (NSString * tracker in tempTrackers)
423    {
424        tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
425       
426        if ([tracker rangeOfString: @"://"].location == NSNotFound)
427            tracker = [@"http://" stringByAppendingString: tracker];
428       
429        if (tr_urlIsValidTracker([tracker UTF8String]))
430        {
431            [fTrackers addObject: tracker];
432            added = YES;
433        }
434    }
435   
436    if (added)
437    {
438        [fTrackerTable deselectAll: self];
439        [fTrackerTable reloadData];
440    }
441    else
442        NSBeep();
443}
444
445@end
446
447@implementation CreatorWindowController (Private)
448
449- (void) updateLocationField
450{
451    NSString * pathString = [fLocation path];
452    [fLocationField setStringValue: [pathString stringByAbbreviatingWithTildeInPath]];
453    [fLocationField setToolTip: pathString];
454}
455
456+ (NSURL *) chooseFile
457{
458    NSOpenPanel * panel = [NSOpenPanel openPanel];
459   
460    [panel setTitle: NSLocalizedString(@"Create Torrent File", "Create torrent -> select file")];
461    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> select file")];
462    [panel setAllowsMultipleSelection: NO];
463    [panel setCanChooseFiles: YES];
464    [panel setCanChooseDirectories: YES];
465    [panel setCanCreateDirectories: NO];
466
467    [panel setMessage: NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file")];
468   
469    BOOL success = [panel runModal] == NSOKButton;
470    return success ? [[panel URLs] objectAtIndex: 0] : nil;
471}
472
473- (void) createBlankAddressAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
474{
475    if ([[alert suppressionButton] state] == NSOnState)
476    {
477        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningCreatorBlankAddress"]; //set regardless of private/public
478        if ([fPrivateCheck state] == NSOnState)
479            [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningCreatorPrivateBlankAddress"];
480    }
481   
482    [alert release];
483   
484    if (returnCode == NSAlertFirstButtonReturn)
485        [self performSelectorOnMainThread: @selector(createReal) withObject: nil waitUntilDone: NO];
486}
487
488- (void) createReal
489{
490    //check if the location currently exists
491    if (![[fLocation URLByDeletingLastPathComponent] checkResourceIsReachableAndReturnError: NULL])
492    {
493        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
494        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> directory doesn't exist warning -> button")];
495        [alert setMessageText: NSLocalizedString(@"The chosen torrent file location does not exist.",
496                                                "Create torrent -> directory doesn't exist warning -> title")];
497        [alert setInformativeText: [NSString stringWithFormat:
498                NSLocalizedString(@"The directory \"%@\" does not currently exist. "
499                    "Create this directory or choose a different one to create the torrent file.",
500                    "Create torrent -> directory doesn't exist warning -> warning"),
501                    [[fLocation URLByDeletingLastPathComponent] path]]];
502        [alert setAlertStyle: NSWarningAlertStyle];
503       
504        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
505        return;
506    }
507   
508    //check if a file with the same name and location already exists
509    if ([fLocation checkResourceIsReachableAndReturnError: NULL])
510    {
511        NSArray * pathComponents = [fLocation pathComponents];
512        NSInteger count = [pathComponents count];
513       
514        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
515        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")];
516        [alert setMessageText: NSLocalizedString(@"A torrent file with this name and directory cannot be created.",
517                                                "Create torrent -> file already exists warning -> title")];
518        [alert setInformativeText: [NSString stringWithFormat:
519                NSLocalizedString(@"A file with the name \"%@\" already exists in the directory \"%@\". "
520                    "Choose a new name or directory to create the torrent file.",
521                    "Create torrent -> file already exists warning -> warning"),
522                    [pathComponents objectAtIndex: count-1], [pathComponents objectAtIndex: count-2]]];
523        [alert setAlertStyle: NSWarningAlertStyle];
524       
525        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
526        return;
527    }
528   
529    //parse non-empty tracker strings
530    tr_tracker_info * trackerInfo = tr_new0(tr_tracker_info, [fTrackers count]);
531   
532    for (NSUInteger i = 0; i < [fTrackers count]; i++)
533    {
534        trackerInfo[i].announce = (char *)[[fTrackers objectAtIndex: i] UTF8String];
535        trackerInfo[i].tier = i;
536    }
537   
538    //store values
539    [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"];
540    [fDefaults setBool: [fPrivateCheck state] == NSOnState forKey: @"CreatorPrivate"];
541    [fDefaults setBool: [fOpenCheck state] == NSOnState forKey: @"CreatorOpen"];
542    fOpenWhenCreated = [fOpenCheck state] == NSOnState; //need this since the check box might not exist, and value in prefs might have changed from another creator window
543    [fDefaults setURL: [fLocation URLByDeletingLastPathComponent] forKey: @"CreatorLocationURL"];
544   
545    [[NSNotificationCenter defaultCenter] postNotificationName: @"BeginCreateTorrentFile" object: fLocation userInfo: nil];
546    tr_makeMetaInfo(fInfo, [[fLocation path] UTF8String], trackerInfo, [fTrackers count], [[fCommentView string] UTF8String], [fPrivateCheck state] == NSOnState);
547    tr_free(trackerInfo);
548   
549    fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress)
550                userInfo: nil repeats: YES];
551}
552
553- (void) checkProgress
554{
555    if (fInfo->isDone)
556    {
557        [fTimer invalidate];
558        fTimer = nil;
559       
560        NSAlert * alert;
561        switch (fInfo->result)
562        {
563            case TR_MAKEMETA_OK:
564                if (fOpenWhenCreated)
565                {
566                    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: [fLocation path], @"File",
567                                            [[fPath URLByDeletingLastPathComponent] path], @"Path", nil];
568                    [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict];
569                }
570               
571                [[self window] close];
572                break;
573           
574            case TR_MAKEMETA_CANCELLED:
575                [[self window] close];
576                break;
577           
578            default:
579                alert = [[[NSAlert alloc] init] autorelease];
580                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")];
581                [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.",
582                                                "Create torrent -> failed -> title"), [fLocation lastPathComponent]]];
583                [alert setAlertStyle: NSWarningAlertStyle];
584               
585                if (fInfo->result == TR_MAKEMETA_IO_READ)
586                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not read \"%s\": %s.",
587                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
588                else if (fInfo->result == TR_MAKEMETA_IO_WRITE)
589                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not write \"%s\": %s.",
590                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
591                else //invalid url should have been caught before creating
592                    [alert setInformativeText: [NSString stringWithFormat: @"%@ (%d)",
593                        NSLocalizedString(@"An unknown error has occurred.", "Create torrent -> failed -> warning"), fInfo->result]];
594               
595                [alert beginSheetModalForWindow: [self window] modalDelegate: self
596                    didEndSelector: @selector(failureSheetClosed:returnCode:contextInfo:) contextInfo: nil];
597        }
598    }
599    else
600    {
601        [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount];
602       
603        if (!fStarted)
604        {
605            fStarted = YES;
606           
607            [fProgressView setHidden: YES];
608           
609            NSWindow * window = [self window];
610            [window setFrameAutosaveName: @""];
611           
612            NSRect windowRect = [window frame];
613            CGFloat difference = [fProgressView frame].size.height - [[window contentView] frame].size.height;
614            windowRect.origin.y -= difference;
615            windowRect.size.height += difference;
616           
617            //don't allow vertical resizing
618            CGFloat height = windowRect.size.height;
619            [window setMinSize: NSMakeSize([window minSize].width, height)];
620            [window setMaxSize: NSMakeSize([window maxSize].width, height)];
621           
622            [window setContentView: fProgressView];
623            [window setFrame: windowRect display: YES animate: YES];
624            [fProgressView setHidden: NO];
625           
626            [[window standardWindowButton: NSWindowCloseButton] setEnabled: NO];
627        }
628    }
629}
630
631- (void) failureSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info
632{
633    [[alert window] orderOut: nil];
634    [[self window] close];
635}
636
637@end
Note: See TracBrowser for help on using the repository browser.