source: trunk/macosx/CreatorWindowController.m @ 6526

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

remove potentially invalid tracker url's in the creator window

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