source: trunk/macosx/CreatorWindowController.m @ 6569

Last change on this file since 6569 was 6569, checked in by livings124, 13 years ago

when checking the previous tracker address for the torrent creator, don't use a blank address

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