source: trunk/macosx/CreatorWindowController.m @ 8227

Last change on this file since 8227 was 8181, checked in by charles, 13 years ago

(trunk) tr_metaInfoBuilderCreate() doesn't need a tr_session* handle anymore

  • Property Id set to /Users/mitchell/Desktop/Transmission/macosx/ActionMenuRatioToDisplayRatioTransformer.h
  • Property svn:keywords set to Date Rev Author Id
File size: 19.9 KB
Line 
1/******************************************************************************
2 * $Id: CreatorWindowController.m 8181 2009-04-08 18:47:48Z livings124 $
3 *
4 * Copyright (c) 2007-2009 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 "NSStringAdditions.h"
27#import "utils.h" //tr_httpIsValidURL
28
29#define TRACKER_ADD_TAG 0
30#define TRACKER_REMOVE_TAG 1
31
32@interface CreatorWindowController (Private)
33
34+ (NSString *) chooseFile;
35- (void) updateEnableOpenCheckForTrackers;
36- (void) locationSheetClosed: (NSSavePanel *) openPanel returnCode: (NSInteger) code contextInfo: (void *) info;
37
38- (void) createBlankAddressAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo;
39- (void) createReal;
40- (void) checkProgress;
41- (void) failureSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info;
42
43@end
44
45@implementation CreatorWindowController
46
47+ (void) createTorrentFile: (tr_session *) handle
48{
49    //get file/folder for torrent
50    NSString * path;
51    if (!(path = [CreatorWindowController chooseFile]))
52        return;
53   
54    CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: path];
55    [creator showWindow: nil];
56}
57
58+ (void) createTorrentFile: (tr_session *) handle forFile: (NSString *) file
59{
60    CreatorWindowController * creator = [[self alloc] initWithHandle: handle path: file];
61    [creator showWindow: nil];
62}
63
64- (id) initWithHandle: (tr_session *) handle path: (NSString *) path
65{
66    if ((self = [super initWithWindowNibName: @"Creator"]))
67    {
68        fStarted = NO;
69       
70        fPath = [path retain];
71        fInfo = tr_metaInfoBuilderCreate([fPath UTF8String]);
72       
73        if (fInfo->fileCount == 0)
74        {
75            NSAlert * alert = [[NSAlert alloc] init];
76            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> no files -> button")];
77            [alert setMessageText: NSLocalizedString(@"This folder contains no files.",
78                                                    "Create torrent -> no files -> title")];
79            [alert setInformativeText: NSLocalizedString(@"There must be at least one file in a folder to create a torrent file.",
80                                                        "Create torrent -> no files -> warning")];
81            [alert setAlertStyle: NSWarningAlertStyle];
82           
83            [alert runModal];
84            [alert release];
85           
86            [self release];
87            return nil;
88        }
89        if (fInfo->totalSize == 0)
90        {
91            NSAlert * alert = [[NSAlert alloc] init];
92            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> zero size -> button")];
93            [alert setMessageText: NSLocalizedString(@"The total file size is zero bytes.",
94                                                    "Create torrent -> zero size -> title")];
95            [alert setInformativeText: NSLocalizedString(@"A torrent file cannot be created for files with no size.",
96                                                        "Create torrent -> zero size -> warning")];
97            [alert setAlertStyle: NSWarningAlertStyle];
98           
99            [alert runModal];
100            [alert release];
101           
102            [self release];
103            return nil;
104        }
105       
106        fDefaults = [NSUserDefaults standardUserDefaults];
107       
108        //get list of trackers
109        if (!(fTrackers = [[fDefaults arrayForKey: @"CreatorTrackers"] mutableCopy]))
110        {
111            fTrackers = [[NSMutableArray alloc] initWithCapacity: 1];
112           
113            //check for single tracker from versions before 1.3
114            NSString * tracker;
115            if ((tracker = [fDefaults stringForKey: @"CreatorTracker"]))
116            {
117                [fDefaults removeObjectForKey: @"CreatorTracker"];
118                if (![tracker isEqualToString: @""])
119                {
120                    [fTrackers addObject: tracker];
121                    [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"];
122                }
123            }
124        }
125       
126        //remove potentially invalid addresses
127        for (NSInteger i = [fTrackers count]-1; i >= 0; i--)
128        {
129            if (!tr_httpIsValidURL([[fTrackers objectAtIndex: i] UTF8String]))
130                [fTrackers removeObjectAtIndex: i];
131        }
132    }
133    return self;
134}
135
136- (void) awakeFromNib
137{
138    NSString * name = [fPath lastPathComponent];
139   
140    [[self window] setTitle: name];
141   
142    [fNameField setStringValue: name];
143    [fNameField setToolTip: fPath];
144   
145    BOOL multifile = !fInfo->isSingleFile;
146   
147    NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: multifile
148                        ? NSFileTypeForHFSTypeCode('fldr') : [fPath pathExtension]];
149    [icon setSize: [fIconView frame].size];
150    [fIconView setImage: icon];
151   
152    NSString * statusString = [NSString stringForFileSize: fInfo->totalSize];
153    if (multifile)
154    {
155        NSString * fileString;
156        NSInteger count = fInfo->fileCount;
157        if (count != 1)
158            fileString = [NSString stringWithFormat: NSLocalizedString(@"%d files", "Create torrent -> info"), count];
159        else
160            fileString = NSLocalizedString(@"1 file", "Create torrent -> info");
161        statusString = [NSString stringWithFormat: @"%@, %@", fileString, statusString];
162    }
163    [fStatusField setStringValue: statusString];
164   
165    NSString * piecesCountString;
166    int piecesCount = fInfo->pieceCount;
167    if (piecesCount == 1)
168        piecesCountString = NSLocalizedString(@"1 piece", "Create torrent -> info");
169    else
170        piecesCountString = [NSString stringWithFormat: NSLocalizedString(@"%d pieces", "Create torrent -> info"),
171                                                                piecesCount];
172    [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@, %@ each", "Create torrent -> info"),
173                                        piecesCountString, [NSString stringForFileSize: fInfo->pieceSize]]];
174   
175    fLocation = [[[[fDefaults stringForKey: @"CreatorLocation"] stringByExpandingTildeInPath] stringByAppendingPathComponent:
176                    [name stringByAppendingPathExtension: @"torrent"]] retain];
177    [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
178    [fLocationField setToolTip: fLocation];
179   
180    //set previously saved values
181    if ([fDefaults objectForKey: @"CreatorPrivate"])
182        [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState];
183   
184    fOpenTorrent = [fDefaults boolForKey: @"CreatorOpen"];
185    [self updateEnableOpenCheckForTrackers];
186}
187
188- (void) dealloc
189{
190    [fPath release];
191    [fLocation release];
192   
193    [fTrackers release];
194   
195    if (fInfo)
196        tr_metaInfoBuilderFree(fInfo);
197   
198    [fTimer invalidate];
199   
200    [super dealloc];
201}
202
203- (void) toggleOpenCheck: (id) sender
204{
205    fOpenTorrent = [fOpenCheck state] == NSOnState;
206}
207
208- (void) setLocation: (id) sender
209{
210    NSSavePanel * panel = [NSSavePanel savePanel];
211
212    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> location sheet -> button")];
213    [panel setMessage: NSLocalizedString(@"Select the name and location for the torrent file.",
214                                        "Create torrent -> location sheet -> message")];
215   
216    [panel setRequiredFileType: @"org.bittorrent.torrent"];
217    [panel setCanSelectHiddenExtension: YES];
218   
219    [panel beginSheetForDirectory: [fLocation stringByDeletingLastPathComponent] file: [fLocation lastPathComponent]
220            modalForWindow: [self window] modalDelegate: self didEndSelector: @selector(locationSheetClosed:returnCode:contextInfo:)
221            contextInfo: nil];
222}
223
224- (void) create: (id) sender
225{
226    if ([fTrackers count] == 0 && [fDefaults boolForKey: @"WarningCreatorBlankAddress"])
227    {
228        NSAlert * alert = [[NSAlert alloc] init];
229        [alert setMessageText: NSLocalizedString(@"There is no tracker address.", "Create torrent -> blank address -> title")];
230        [alert setInformativeText: NSLocalizedString(@"The torrent file will not be able to be opened."
231            " A torrent file with no tracker address is only useful when you plan to upload the file to a tracker website"
232            " that will add the address for you.", "Create torrent -> blank address -> message")];
233        [alert addButtonWithTitle: NSLocalizedString(@"Create", "Create torrent -> blank address -> button")];
234        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")];
235        [alert setShowsSuppressionButton: YES];
236
237        [alert beginSheetModalForWindow: [self window] modalDelegate: self
238            didEndSelector: @selector(createBlankAddressAlertDidEnd:returnCode:contextInfo:) contextInfo: nil];
239    }
240    else
241        [self createReal];
242}
243
244- (void) cancelCreateWindow: (id) sender
245{
246    [[self window] close];
247}
248
249- (void) windowWillClose: (NSNotification *) notification
250{
251    [self release];
252}
253
254- (void) cancelCreateProgress: (id) sender
255{
256    fInfo->abortFlag = 1;
257    [fTimer fire];
258}
259
260- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
261{
262    return [fTrackers count];
263}
264
265- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
266{
267    return [fTrackers objectAtIndex: row];
268}
269
270- (void) addRemoveTracker: (id) sender
271{
272    //don't allow add/remove when currently adding - it leads to weird results
273    if ([fTrackerTable editedRow] != -1)
274        return;
275   
276    if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG)
277    {
278        [fTrackers removeObjectsAtIndexes: [fTrackerTable selectedRowIndexes]];
279       
280        [fTrackerTable deselectAll: self];
281        [fTrackerTable reloadData];
282       
283        [self updateEnableOpenCheckForTrackers];
284    }
285    else
286    {
287        [fTrackers addObject: @""];
288        [fTrackerTable reloadData];
289       
290        NSInteger row = [fTrackers count] - 1;
291        [fTrackerTable selectRow: row byExtendingSelection: NO];
292        [fTrackerTable editColumn: 0 row: row withEvent: nil select: YES];
293    }
294}
295
296- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
297    row: (NSInteger) row
298{
299    NSString * tracker = (NSString *)object;
300   
301    tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
302   
303    if ([tracker rangeOfString: @"://"].location == NSNotFound)
304        tracker = [@"http://" stringByAppendingString: tracker];
305   
306    if (!tr_httpIsValidURL([tracker UTF8String]))
307    {
308        NSBeep();
309        [fTrackers removeObjectAtIndex: row];
310    }
311    else
312    {
313        [fTrackers replaceObjectAtIndex: row withObject: tracker];
314        [self updateEnableOpenCheckForTrackers];
315    }
316   
317    [fTrackerTable deselectAll: self];
318    [fTrackerTable reloadData];
319}
320
321- (void) tableViewSelectionDidChange: (NSNotification *) notification
322{
323    [fTrackerAddRemoveControl setEnabled: [fTrackerTable numberOfSelectedRows] > 0 forSegment: TRACKER_REMOVE_TAG];
324}
325
326@end
327
328@implementation CreatorWindowController (Private)
329
330+ (NSString *) chooseFile
331{
332    NSOpenPanel * panel = [NSOpenPanel openPanel];
333   
334    [panel setTitle: NSLocalizedString(@"Create Torrent File", "Create torrent -> select file")];
335    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> select file")];
336    [panel setAllowsMultipleSelection: NO];
337    [panel setCanChooseFiles: YES];
338    [panel setCanChooseDirectories: YES];
339    [panel setCanCreateDirectories: NO];
340
341    [panel setMessage: NSLocalizedString(@"Select a file or folder for the torrent file.", "Create torrent -> select file")];
342   
343    BOOL success = [panel runModal] == NSOKButton;
344    return success ? [[panel filenames] objectAtIndex: 0] : nil;
345}
346
347- (void) updateEnableOpenCheckForTrackers
348{
349    BOOL hasTracker = [fTrackers count] > 0;
350    [fOpenCheck setEnabled: hasTracker];
351    [fOpenCheck setState: (fOpenTorrent && hasTracker) ? NSOnState : NSOffState];
352}
353
354- (void) locationSheetClosed: (NSSavePanel *) panel returnCode: (NSInteger) code contextInfo: (void *) info
355{
356    if (code == NSOKButton)
357    {
358        [fLocation release];
359        fLocation = [[panel filename] retain];
360       
361        [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
362        [fLocationField setToolTip: fLocation];
363    }
364}
365
366- (void) createBlankAddressAlertDidEnd: (NSAlert *) alert returnCode: (NSInteger) returnCode contextInfo: (void *) contextInfo
367{
368    if ([[alert suppressionButton] state] == NSOnState)
369        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningCreatorBlankAddress"];
370   
371    [alert release];
372   
373    if (returnCode == NSAlertFirstButtonReturn)
374        [self performSelectorOnMainThread: @selector(createReal) withObject: nil waitUntilDone: NO];
375}
376
377- (void) createReal
378{
379    //check if a file with the same name and location already exists
380    if ([[NSFileManager defaultManager] fileExistsAtPath: fLocation])
381    {
382        NSArray * pathComponents = [fLocation pathComponents];
383        NSInteger count = [pathComponents count];
384       
385        NSAlert * alert = [[[NSAlert alloc] init] autorelease];
386        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> file already exists warning -> button")];
387        [alert setMessageText: NSLocalizedString(@"A torrent file with this name and directory cannot be created.",
388                                                "Create torrent -> file already exists warning -> title")];
389        [alert setInformativeText: [NSString stringWithFormat:
390                NSLocalizedString(@"A file with the name \"%@\" already exists in the directory \"%@\". "
391                    "Choose a new name or directory to create the torrent file.",
392                    "Create torrent -> file already exists warning -> warning"),
393                    [pathComponents objectAtIndex: count-1], [pathComponents objectAtIndex: count-2]]];
394        [alert setAlertStyle: NSWarningAlertStyle];
395       
396        [alert beginSheetModalForWindow: [self window] modalDelegate: self didEndSelector: nil contextInfo: nil];
397        return;
398    }
399   
400    //parse non-empty tracker strings
401    tr_tracker_info * trackerInfo = tr_new0(tr_tracker_info, [fTrackers count]);
402   
403    for (NSUInteger i = 0; i < [fTrackers count]; i++)
404        trackerInfo[i].announce = (char *)[[fTrackers objectAtIndex: i] UTF8String];
405   
406    //store values
407    [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"];
408    [fDefaults setBool: [fPrivateCheck state] == NSOnState forKey: @"CreatorPrivate"];
409    [fDefaults setBool: fOpenTorrent forKey: @"CreatorOpen"];
410    [fDefaults setObject: [fLocation stringByDeletingLastPathComponent] forKey: @"CreatorLocation"];
411   
412    [[NSNotificationCenter defaultCenter] postNotificationName: @"BeginCreateTorrentFile" object: fLocation userInfo: nil];
413    tr_makeMetaInfo(fInfo, [fLocation UTF8String], trackerInfo, [fTrackers count], [[fCommentView string] UTF8String],
414                    [fPrivateCheck state] == NSOnState);
415    tr_free(trackerInfo);
416   
417    fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress)
418                userInfo: nil repeats: YES];
419}
420
421- (void) checkProgress
422{
423    if (fInfo->isDone)
424    {
425        [fTimer invalidate];
426        fTimer = nil;
427       
428        NSAlert * alert;
429        switch (fInfo->result)
430        {
431            case TR_MAKEMETA_OK:
432                if (fOpenTorrent && [fTrackers count] > 0)
433                {
434                    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: fLocation, @"File",
435                                            [fPath stringByDeletingLastPathComponent], @"Path", nil];
436                    [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict];
437                }
438               
439                [[self window] close];
440                break;
441           
442            case TR_MAKEMETA_CANCELLED:
443                [[self window] close];
444                break;
445           
446            default:
447                alert = [[[NSAlert alloc] init] autorelease];
448                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")];
449                [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.",
450                                                "Create torrent -> failed -> title"), [fLocation lastPathComponent]]];
451                [alert setAlertStyle: NSWarningAlertStyle];
452               
453                if (fInfo->result == TR_MAKEMETA_IO_READ)
454                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not read \"%s\": %s.",
455                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
456                else if (fInfo->result == TR_MAKEMETA_IO_WRITE)
457                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not write \"%s\": %s.",
458                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
459                else //invalid url should have been caught before creating
460                    [alert setInformativeText: [NSString stringWithFormat: @"%@ (%d)",
461                        NSLocalizedString(@"An unknown error has occurred.", "Create torrent -> failed -> warning"), fInfo->result]];
462               
463                [alert beginSheetModalForWindow: [self window] modalDelegate: self
464                    didEndSelector: @selector(failureSheetClosed:returnCode:contextInfo:) contextInfo: nil];
465        }
466    }
467    else
468    {
469        [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount];
470       
471        if (!fStarted)
472        {
473            fStarted = YES;
474           
475            [fProgressView setHidden: YES];
476           
477            NSWindow * window = [self window];
478           
479            NSRect windowRect = [window frame];
480            CGFloat difference = [fProgressView frame].size.height - [[window contentView] frame].size.height;
481            windowRect.origin.y -= difference;
482            windowRect.size.height += difference;
483           
484            //don't allow vertical resizing
485            CGFloat height = windowRect.size.height;
486            [window setMinSize: NSMakeSize([window minSize].width, height)];
487            [window setMaxSize: NSMakeSize([window maxSize].width, height)];
488           
489            [window setContentView: fProgressView];
490            [window setFrame: windowRect display: YES animate: YES];
491            [fProgressView setHidden: NO];
492           
493            [[window standardWindowButton: NSWindowCloseButton] setEnabled: NO];
494        }
495    }
496}
497
498- (void) failureSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info
499{
500    [[alert window] orderOut: nil];
501    [[self window] close];
502}
503
504@end
Note: See TracBrowser for help on using the repository browser.