source: trunk/macosx/CreatorWindowController.m @ 6246

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

the progress bar color gradients are now all generated by a single color fed into a method to generate the gradient (more consistent gradient between colors and easier to adjust the gradient look in the future)

  • Property Id set to /Users/mitchell/Desktop/Transmission/macosx/ActionMenuRatioToDisplayRatioTransformer.h
  • Property svn:keywords set to Date Rev Author Id
File size: 19.6 KB
Line 
1/******************************************************************************
2 * $Id: CreatorWindowController.m 6246 2008-06-24 03:59:34Z 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 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    return self;
125}
126
127- (void) awakeFromNib
128{
129    NSString * name = [fPath lastPathComponent];
130   
131    [[self window] setTitle: name];
132   
133    [fNameField setStringValue: name];
134    [fNameField setToolTip: fPath];
135   
136    BOOL multifile = !fInfo->isSingleFile;
137   
138    NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: multifile
139                        ? NSFileTypeForHFSTypeCode('fldr') : [fPath pathExtension]];
140    [icon setSize: [fIconView frame].size];
141    [fIconView setImage: icon];
142   
143    NSString * statusString = [NSString stringForFileSize: fInfo->totalSize];
144    if (multifile)
145    {
146        NSString * fileString;
147        int count = fInfo->fileCount;
148        if (count != 1)
149            fileString = [NSString stringWithFormat: NSLocalizedString(@"%d files", "Create torrent -> info"), count];
150        else
151            fileString = NSLocalizedString(@"1 file", "Create torrent -> info");
152        statusString = [NSString stringWithFormat: @"%@, %@", fileString, statusString];
153    }
154    [fStatusField setStringValue: statusString];
155   
156    NSString * piecesCountString;
157    int piecesCount = fInfo->pieceCount;
158    if (piecesCount == 1)
159        piecesCountString = NSLocalizedString(@"1 piece", "Create torrent -> info");
160    else
161        piecesCountString = [NSString stringWithFormat: NSLocalizedString(@"%d pieces", "Create torrent -> info"),
162                                                                piecesCount];
163    [fPiecesField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@, %@ each", "Create torrent -> info"),
164                                        piecesCountString, [NSString stringForFileSize: fInfo->pieceSize]]];
165   
166    fLocation = [[[[fDefaults stringForKey: @"CreatorLocation"] stringByExpandingTildeInPath] stringByAppendingPathComponent:
167                    [name stringByAppendingPathExtension: @"torrent"]] retain];
168    [fLocationField setStringValue: [fLocation stringByAbbreviatingWithTildeInPath]];
169    [fLocationField setToolTip: fLocation];
170   
171    //set previously saved values
172    if ([fDefaults objectForKey: @"CreatorPrivate"])
173        [fPrivateCheck setState: [fDefaults boolForKey: @"CreatorPrivate"] ? NSOnState : NSOffState];
174   
175    fOpenTorrent = [fDefaults boolForKey: @"CreatorOpen"];
176    [self updateEnableOpenCheckForTrackers];
177   
178    if (![NSApp isOnLeopardOrBetter])
179    {
180        [fTrackerAddRemoveControl sizeToFit];
181        [fTrackerAddRemoveControl setLabel: @"+" forSegment: TRACKER_ADD_TAG];
182        [fTrackerAddRemoveControl setLabel: @"-" forSegment: TRACKER_REMOVE_TAG];
183    }
184}
185
186- (void) dealloc
187{
188    [fPath release];
189    [fLocation release];
190   
191    [fTrackers release];
192   
193    if (fInfo)
194        tr_metaInfoBuilderFree(fInfo);
195   
196    [fTimer invalidate];
197   
198    [super dealloc];
199}
200
201- (void) toggleOpenCheck: (id) sender
202{
203    fOpenTorrent = [fOpenCheck state] == NSOnState;
204}
205
206- (void) setLocation: (id) sender
207{
208    NSSavePanel * panel = [NSSavePanel savePanel];
209
210    [panel setPrompt: NSLocalizedString(@"Select", "Create torrent -> location sheet -> button")];
211    [panel setMessage: NSLocalizedString(@"Select the name and location for the torrent file.",
212                                        "Create torrent -> location sheet -> message")];
213   
214    [panel setRequiredFileType: @"torrent"];
215    [panel setCanSelectHiddenExtension: YES];
216   
217    [panel beginSheetForDirectory: [fLocation stringByDeletingLastPathComponent] file: [fLocation lastPathComponent]
218            modalForWindow: [self window] modalDelegate: self didEndSelector: @selector(locationSheetClosed:returnCode:contextInfo:)
219            contextInfo: nil];
220}
221
222- (void) create: (id) sender
223{
224    if ([fTrackers count] == 0 && [fDefaults boolForKey: @"WarningCreatorBlankAddress"])
225    {
226        NSAlert * alert = [[NSAlert alloc] init];
227        [alert setMessageText: NSLocalizedString(@"There is no tracker address.", "Create torrent -> blank address -> title")];
228        [alert setInformativeText: NSLocalizedString(@"The torrent file will not be able to be opened."
229            " A torrent file with no tracker address is only useful when you plan to upload the file to a tracker website"
230            " that will add the address for you.", "Create torrent -> blank address -> message")];
231        [alert addButtonWithTitle: NSLocalizedString(@"Create", "Create torrent -> blank address -> button")];
232        [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Create torrent -> blank address -> button")];
233       
234        if ([NSApp isOnLeopardOrBetter])
235            [alert setShowsSuppressionButton: YES];
236        else
237            [alert addButtonWithTitle: NSLocalizedString(@"Don't Alert Again", "Create torrent -> blank address -> button")];
238
239        [alert beginSheetModalForWindow: [self window] modalDelegate: self
240            didEndSelector: @selector(createBlankAddressAlertDidEnd:returnCode:contextInfo:) contextInfo: nil];
241    }
242    else
243        [self createReal];
244}
245
246- (void) cancelCreateWindow: (id) sender
247{
248    [[self window] close];
249}
250
251- (void) windowWillClose: (NSNotification *) notification
252{
253    [self release];
254}
255
256- (void) cancelCreateProgress: (id) sender
257{
258    fInfo->abortFlag = 1;
259    [fTimer fire];
260}
261
262- (NSInteger) numberOfRowsInTableView: (NSTableView *) tableView
263{
264    return [fTrackers count];
265}
266
267- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) tableColumn row: (NSInteger) row
268{
269    return [fTrackers objectAtIndex: row];
270}
271
272- (void) addRemoveTracker: (id) sender
273{
274    //don't allow add/remove when currently adding - it leads to weird results
275    if ([fTrackerTable editedRow] != -1)
276        return;
277   
278    if ([[sender cell] tagForSegment: [sender selectedSegment]] == TRACKER_REMOVE_TAG)
279    {
280        [fTrackers removeObjectsAtIndexes: [fTrackerTable selectedRowIndexes]];
281       
282        [fTrackerTable deselectAll: self];
283        [fTrackerTable reloadData];
284       
285        [self updateEnableOpenCheckForTrackers];
286    }
287    else
288    {
289        [fTrackers addObject: @""];
290        [fTrackerTable reloadData];
291       
292        int row = [fTrackers count] - 1;
293        [fTrackerTable selectRow: row byExtendingSelection: NO];
294        [fTrackerTable editColumn: 0 row: row withEvent: nil select: YES];
295    }
296}
297
298- (void) tableView: (NSTableView *) tableView setObjectValue: (id) object forTableColumn: (NSTableColumn *) tableColumn
299    row: (NSInteger) row
300{
301    NSString * tracker = (NSString *)object;
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: (int) 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: (int) returnCode contextInfo: (void *) contextInfo
367{
368    if (([NSApp isOnLeopardOrBetter] ? [[alert suppressionButton] state] == NSOnState : returnCode == NSAlertThirdButtonReturn))
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        int 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    NSUInteger i;
404    for (i = 0; i < [fTrackers count]; i++)
405        trackerInfo[i].announce = (char *)[[fTrackers objectAtIndex: i] UTF8String];
406   
407    //store values
408    [fDefaults setObject: fTrackers forKey: @"CreatorTrackers"];
409    [fDefaults setBool: [fPrivateCheck state] == NSOnState forKey: @"CreatorPrivate"];
410    [fDefaults setBool: fOpenTorrent forKey: @"CreatorOpen"];
411    [fDefaults setObject: [fLocation stringByDeletingLastPathComponent] forKey: @"CreatorLocation"];
412   
413    [[NSNotificationCenter defaultCenter] postNotificationName: @"BeginCreateTorrentFile" object: fLocation userInfo: nil];
414    tr_makeMetaInfo(fInfo, [fLocation UTF8String], trackerInfo, [fTrackers count], [[fCommentView string] UTF8String],
415                    [fPrivateCheck state] == NSOnState);
416    tr_free(trackerInfo);
417   
418    fTimer = [NSTimer scheduledTimerWithTimeInterval: 0.1 target: self selector: @selector(checkProgress)
419                userInfo: nil repeats: YES];
420}
421
422- (void) checkProgress
423{
424    if (fInfo->isDone)
425    {
426        [fTimer invalidate];
427        fTimer = nil;
428       
429        NSAlert * alert;
430        switch (fInfo->result)
431        {
432            case TR_MAKEMETA_OK:
433                if (fOpenTorrent && [fTrackers count] > 0)
434                {
435                    NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys: fLocation, @"File",
436                                            [fPath stringByDeletingLastPathComponent], @"Path", nil];
437                    [[NSNotificationCenter defaultCenter] postNotificationName: @"OpenCreatedTorrentFile" object: self userInfo: dict];
438                }
439               
440                [[self window] close];
441                break;
442           
443            case TR_MAKEMETA_CANCELLED:
444                [[self window] close];
445                break;
446           
447            default:
448                alert = [[[NSAlert alloc] init] autorelease];
449                [alert addButtonWithTitle: NSLocalizedString(@"OK", "Create torrent -> failed -> button")];
450                [alert setMessageText: [NSString stringWithFormat: NSLocalizedString(@"Creation of \"%@\" failed.",
451                                                "Create torrent -> failed -> title"), [fLocation lastPathComponent]]];
452                [alert setAlertStyle: NSWarningAlertStyle];
453               
454                if (fInfo->result == TR_MAKEMETA_IO_READ)
455                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not read \"%s\": %s.",
456                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
457                else if (fInfo->result == TR_MAKEMETA_IO_WRITE)
458                    [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"Could not write \"%s\": %s.",
459                        "Create torrent -> failed -> warning"), fInfo->errfile, strerror(fInfo->my_errno)]];
460                else; //invalid url should have been caught before creating
461               
462                [alert beginSheetModalForWindow: [self window] modalDelegate: self
463                        didEndSelector: @selector(failureSheetClosed:returnCode:contextInfo:) contextInfo: nil];
464        }
465    }
466    else
467    {
468        [fProgressIndicator setDoubleValue: (double)fInfo->pieceIndex / fInfo->pieceCount];
469       
470        if (!fStarted)
471        {
472            fStarted = YES;
473           
474            NSWindow * window = [self window];
475           
476            NSRect windowRect = [window frame];
477            float difference = [fProgressView frame].size.height - [[window contentView] frame].size.height;
478            windowRect.origin.y -= difference;
479            windowRect.size.height += difference;
480           
481            //don't allow vertical resizing
482            float height = windowRect.size.height;
483            [window setMinSize: NSMakeSize([window minSize].width, height)];
484            [window setMaxSize: NSMakeSize([window maxSize].width, height)];
485           
486            [window setContentView: fProgressView];
487            [window setFrame: windowRect display: YES animate: YES];
488            [fProgressView setHidden: NO];
489           
490            [[window standardWindowButton: NSWindowCloseButton] setEnabled: NO];
491        }
492    }
493}
494
495- (void) failureSheetClosed: (NSAlert *) alert returnCode: (int) code contextInfo: (void *) info
496{
497    [[alert window] orderOut: nil];
498    [[self window] close];
499}
500
501@end
Note: See TracBrowser for help on using the repository browser.