source: trunk/macosx/Controller.m @ 678

Last change on this file since 678 was 678, checked in by livings124, 16 years ago

simplify rect width and height measurements

  • Property svn:keywords set to Date Rev Author Id
File size: 75.4 KB
Line 
1/******************************************************************************
2 * $Id: Controller.m 678 2006-07-23 19:22:24Z livings124 $
3 *
4 * Copyright (c) 2005-2006 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 <IOKit/IOMessage.h>
26
27#import "Controller.h"
28#import "Torrent.h"
29#import "TorrentCell.h"
30#import "TorrentTableView.h"
31#import "StringAdditions.h"
32
33#import <Sparkle/Sparkle.h>
34
35#define TOOLBAR_OPEN            @"Toolbar Open"
36#define TOOLBAR_REMOVE          @"Toolbar Remove"
37#define TOOLBAR_INFO            @"Toolbar Info"
38#define TOOLBAR_PAUSE_ALL       @"Toolbar Pause All"
39#define TOOLBAR_RESUME_ALL      @"Toolbar Resume All"
40#define TOOLBAR_PAUSE_SELECTED  @"Toolbar Pause Selected"
41#define TOOLBAR_RESUME_SELECTED @"Toolbar Resume Selected"
42#define TOOLBAR_FILTER          @"Toolbar Toggle Filter"
43
44#define GROWL_DOWNLOAD_COMPLETE @"Download Complete"
45#define GROWL_SEEDING_COMPLETE  @"Seeding Complete"
46#define GROWL_AUTO_ADD          @"Torrent Auto Added"
47
48#define TORRENT_TABLE_VIEW_DATA_TYPE    @"TorrentTableViewDataType"
49
50#define ROW_HEIGHT_REGULAR  65.0
51#define ROW_HEIGHT_SMALL    40.0
52#define WINDOW_REGULAR_WIDTH       468.0
53
54#define WEBSITE_URL @"http://transmission.m0k.org/"
55#define FORUM_URL   @"http://transmission.m0k.org/forum/"
56
57static void sleepCallBack(void * controller, io_service_t y, natural_t messageType, void * messageArgument)
58{
59    Controller * c = controller;
60    [c sleepCallBack: messageType argument: messageArgument];
61}
62
63
64@implementation Controller
65
66- (id) init
67{
68    if ((self = [super init]))
69    {
70        fLib = tr_init();
71       
72        fTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
73        fFilteredTorrents = [[NSMutableArray alloc] initWithCapacity: 10];
74       
75        fDefaults = [NSUserDefaults standardUserDefaults];
76        fInfoController = [[InfoWindowController alloc] initWithWindowNibName: @"InfoWindow"];
77        fPrefsController = [[PrefsController alloc] initWithWindowNibName: @"PrefsWindow"];
78        fBadger = [[Badger alloc] init];
79       
80        [GrowlApplicationBridge setGrowlDelegate: self];
81    }
82    return self;
83}
84
85- (void) dealloc
86{
87    [[NSNotificationCenter defaultCenter] removeObserver: self];
88
89    [fTorrents release];
90    [fFilteredTorrents release];
91   
92    [fToolbar release];
93    [fInfoController release];
94    [fPrefsController release];
95    [fBadger release];
96   
97    [fSortType release];
98    [fFilterType release];
99    [fAutoImportedNames release];
100   
101    tr_close(fLib);
102    [super dealloc];
103}
104
105- (void) awakeFromNib
106{
107    [fPrefsController setPrefs: fLib];
108   
109    [fStatusBar setBackgroundImage: [NSImage imageNamed: @"StatusBarBackground.png"]];
110    [fFilterBar setBackgroundImage: [NSImage imageNamed: @"FilterBarBackground.png"]];
111   
112    [fWindow setAcceptsMouseMovedEvents: YES]; //ensure filter buttons display correctly
113   
114    [fAdvancedBarItem setState: [fDefaults boolForKey: @"UseAdvancedBar"]];
115
116    fToolbar = [[NSToolbar alloc] initWithIdentifier: @"Transmission Toolbar"];
117    [fToolbar setDelegate: self];
118    [fToolbar setAllowsUserCustomization: YES];
119    [fToolbar setAutosavesConfiguration: YES];
120    [fWindow setToolbar: fToolbar];
121    [fWindow setDelegate: self];
122   
123    [fWindow makeFirstResponder: fTableView];
124   
125    //set table size
126    if ([fDefaults boolForKey: @"SmallView"])
127    {
128        [fTableView setRowHeight: ROW_HEIGHT_SMALL];
129        [fSmallViewItem setState: NSOnState];
130    }
131   
132    //window min height
133    NSSize contentMinSize = [fWindow contentMinSize];
134    contentMinSize.height = [[fWindow contentView] frame].size.height - [fScrollView frame].size.height
135                                + [fTableView rowHeight] + [fTableView intercellSpacing].height;
136    [fWindow setContentMinSize: contentMinSize];
137   
138    //set info keyboard shortcuts
139    unichar ch = NSRightArrowFunctionKey;
140    [fNextInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
141    ch = NSLeftArrowFunctionKey;
142    [fPrevInfoTabItem setKeyEquivalent: [NSString stringWithCharacters: & ch length: 1]];
143   
144    //set up filter bar
145    NSView * contentView = [fWindow contentView];
146    [fFilterBar setHidden: YES];
147   
148    fFilterBarVisible = NO;
149    NSRect filterBarFrame = [fFilterBar frame];
150    filterBarFrame.size.width = [fWindow frame].size.width;
151    [fFilterBar setFrame: filterBarFrame];
152   
153    [contentView addSubview: fFilterBar];
154    [fFilterBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
155   
156    [self showFilterBar: [fDefaults boolForKey: @"FilterBar"] animate: NO];
157   
158    //set up status bar
159    fStatusBarVisible = NO;
160    [fStatusBar setHidden: YES];
161   
162    NSRect statusBarFrame = [fStatusBar frame];
163    statusBarFrame.size.width = [fWindow frame].size.width;
164    [fStatusBar setFrame: statusBarFrame];
165   
166    [contentView addSubview: fStatusBar];
167    [fStatusBar setFrameOrigin: NSMakePoint(0, NSMaxY([contentView frame]))];
168    [self showStatusBar: [fDefaults boolForKey: @"StatusBar"] animate: NO];
169   
170    //set speed limit
171    fSpeedLimitNormalImage = [fSpeedLimitButton image];
172    fSpeedLimitBlueImage = [NSImage imageNamed: @"SpeedLimitButtonBlue.png"];
173    fSpeedLimitGraphiteImage = [NSImage imageNamed: @"SpeedLimitButtonGraphite.png"];
174   
175    [self updateControlTint: nil];
176   
177    if ((fSpeedLimitEnabled = [fDefaults boolForKey: @"SpeedLimit"]))
178    {
179        [fSpeedLimitItem setState: NSOnState];
180        [fSpeedLimitDockItem setState: NSOnState];
181       
182        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
183                                        ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage];
184    }
185
186    [fActionButton setToolTip: @"Shortcuts for changing global settings."];
187    [fSpeedLimitButton setToolTip: @"Speed Limit overrides the total bandwidth limits with its own limits."];
188
189    [fTableView setTorrents: fFilteredTorrents];
190    [[fTableView tableColumnWithIdentifier: @"Torrent"] setDataCell: [[TorrentCell alloc] init]];
191
192    [fTableView registerForDraggedTypes: [NSArray arrayWithObjects: NSFilenamesPboardType,
193                                                        TORRENT_TABLE_VIEW_DATA_TYPE, nil]];
194
195    //register for sleep notifications
196    IONotificationPortRef notify;
197    io_object_t iterator;
198    if (fRootPort = IORegisterForSystemPower(self, & notify, sleepCallBack, & iterator))
199        CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notify),
200                            kCFRunLoopCommonModes);
201    else
202        NSLog(@"Could not IORegisterForSystemPower");
203
204    //load torrents from history
205    Torrent * torrent;
206    NSDictionary * historyItem;
207    NSEnumerator * enumerator = [[fDefaults arrayForKey: @"History"] objectEnumerator];
208    while ((historyItem = [enumerator nextObject]))
209        if ((torrent = [[Torrent alloc] initWithHistory: historyItem lib: fLib]))
210        {
211            [fTorrents addObject: torrent];
212            [torrent release];
213        }
214   
215    [self torrentNumberChanged];
216   
217    //set sort
218    fSortType = [[fDefaults stringForKey: @"Sort"] retain];
219   
220    NSMenuItem * currentSortItem, * currentSortActionItem;
221    if ([fSortType isEqualToString: @"Name"])
222    {
223        currentSortItem = fNameSortItem;
224        currentSortActionItem = fNameSortActionItem;
225    }
226    else if ([fSortType isEqualToString: @"State"])
227    {
228        currentSortItem = fStateSortItem;
229        currentSortActionItem = fStateSortActionItem;
230    }
231    else if ([fSortType isEqualToString: @"Progress"])
232    {
233        currentSortItem = fProgressSortItem;
234        currentSortActionItem = fProgressSortActionItem;
235    }
236    else if ([fSortType isEqualToString: @"Date"])
237    {
238        currentSortItem = fDateSortItem;
239        currentSortActionItem = fDateSortActionItem;
240    }
241    else
242    {
243        currentSortItem = fOrderSortItem;
244        currentSortActionItem = fOrderSortActionItem;
245    }
246    [currentSortItem setState: NSOnState];
247    [currentSortActionItem setState: NSOnState];
248   
249    //set filter
250    fFilterType = [[fDefaults stringForKey: @"Filter"] retain];
251
252    //button width should be 9 pixels surrounding text length
253    [fNoFilterButton setText: @"All"]; //16.64
254    [fDownloadFilterButton setText: @"Downloading"]; //81.69
255    [fSeedFilterButton setText: @"Seeding"]; //48.57
256    [fPauseFilterButton setText: @"Paused"]; //44.06
257
258    BarButton * currentFilterButton;
259    if ([fFilterType isEqualToString: @"Pause"])
260        currentFilterButton = fPauseFilterButton;
261    else if ([fFilterType isEqualToString: @"Seed"])
262        currentFilterButton = fSeedFilterButton;
263    else if ([fFilterType isEqualToString: @"Download"])
264        currentFilterButton = fDownloadFilterButton;
265    else
266        currentFilterButton = fNoFilterButton;
267
268    [currentFilterButton setEnabled: YES];
269   
270    //set upload limit action button
271    [fUploadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
272                    [fDefaults integerForKey: @"UploadLimit"]]];
273    if ([fDefaults boolForKey: @"CheckUpload"])
274        [fUploadLimitItem setState: NSOnState];
275    else
276        [fUploadNoLimitItem setState: NSOnState];
277
278        //set download limit action menu
279    [fDownloadLimitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
280                    [fDefaults integerForKey: @"DownloadLimit"]]];
281    if ([fDefaults boolForKey: @"CheckDownload"])
282        [fDownloadLimitItem setState: NSOnState];
283    else
284        [fDownloadNoLimitItem setState: NSOnState];
285   
286    //set ratio action menu
287    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
288                                [fDefaults floatForKey: @"RatioLimit"]]];
289    if ([fDefaults boolForKey: @"RatioCheck"])
290        [fRatioSetItem setState: NSOnState];
291    else
292        [fRatioNotSetItem setState: NSOnState];
293   
294    //observe notifications
295    NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
296   
297    [nc addObserver: self selector: @selector(updateControlTint:)
298                    name: NSControlTintDidChangeNotification object: nil];
299   
300    [nc addObserver: self selector: @selector(prepareForUpdate:)
301                    name: SUUpdaterWillRestartNotification object: nil];
302    fUpdateInProgress = NO;
303   
304    [nc addObserver: self selector: @selector(limitGlobalChange:)
305                    name: @"LimitGlobalChange" object: nil];
306   
307    [nc addObserver: self selector: @selector(ratioGlobalChange:)
308                    name: @"RatioGlobalChange" object: nil];
309   
310    [nc addObserver: self selector: @selector(autoImportChange:)
311                    name: @"AutoImportSettingChange" object: nil];
312   
313    [nc addObserver: self selector: @selector(setWindowSizeToFit)
314                    name: @"AutoSizeSettingChange" object: nil];
315   
316    //check to start another because of stopped torrent
317    [nc addObserver: self selector: @selector(checkWaitingForStopped:)
318                    name: @"StoppedDownloading" object: nil];
319   
320    //check all torrents for starting
321    [nc addObserver: self selector: @selector(globalStartSettingChange:)
322                    name: @"GlobalStartSettingChange" object: nil];
323
324    //check if torrent should now start
325    [nc addObserver: self selector: @selector(torrentStartSettingChange:)
326                    name: @"TorrentStartSettingChange" object: nil];
327   
328    //check if torrent should now start
329    [nc addObserver: self selector: @selector(torrentStoppedForRatio:)
330                    name: @"TorrentStoppedForRatio" object: nil];
331   
332    //change that just impacts the inspector
333    [nc addObserver: self selector: @selector(reloadInspectorSettings:)
334                    name: @"TorrentSettingChange" object: nil];
335
336    //timer to update the interface every second
337    fCompleted = 0;
338    [self updateUI: nil];
339    fTimer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target: self
340        selector: @selector(updateUI:) userInfo: nil repeats: YES];
341    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
342    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
343   
344    [self applyFilter: nil];
345   
346    [fWindow makeKeyAndOrderFront: nil];
347
348    if ([fDefaults boolForKey: @"InfoVisible"])
349        [self showInfo: nil];
350   
351    //timer to check for auto import every 15 seconds, must do after everything else is set up
352    fAutoImportedNames = [[NSMutableArray alloc] init];
353   
354    [self checkAutoImportDirectory: nil];
355    fAutoImportTimer = [NSTimer scheduledTimerWithTimeInterval: 15.0 target: self
356        selector: @selector(checkAutoImportDirectory:) userInfo: nil repeats: YES];
357    [[NSRunLoop currentRunLoop] addTimer: fAutoImportTimer forMode: NSDefaultRunLoopMode];
358}
359
360- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) visibleWindows
361{
362    if (![fWindow isVisible] && ![[fPrefsController window] isVisible])
363        [fWindow makeKeyAndOrderFront: nil];
364    return NO;
365}
366
367- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) sender
368{
369    if (!fUpdateInProgress && [fDefaults boolForKey: @"CheckQuit"])
370    {
371        int active = 0, downloading = 0;
372        Torrent * torrent;
373        NSEnumerator * enumerator = [fTorrents objectEnumerator];
374        while ((torrent = [enumerator nextObject]))
375            if ([torrent isActive])
376            {
377                active++;
378                if (![torrent isSeeding])
379                    downloading++;
380            }
381
382        if ([fDefaults boolForKey: @"CheckQuitDownloading"] ? downloading > 0 : active > 0)
383        {
384            NSString * message = active == 1
385                ? @"There is an active transfer. Do you really want to quit?"
386                : [NSString stringWithFormat:
387                    @"There are %d active transfers. Do you really want to quit?", active];
388
389            NSBeginAlertSheet(@"Confirm Quit", @"Quit", @"Cancel", nil, fWindow, self,
390                                @selector(quitSheetDidEnd:returnCode:contextInfo:), nil, nil, message);
391            return NSTerminateLater;
392        }
393    }
394
395    return NSTerminateNow;
396}
397
398- (void) quitSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (void *) contextInfo
399{
400    [NSApp replyToApplicationShouldTerminate: returnCode == NSAlertDefaultReturn];
401}
402
403- (void) applicationWillTerminate: (NSNotification *) notification
404{
405    //stop timers
406    [fAutoImportTimer invalidate];
407    [fTimer invalidate];
408   
409    //save history and stop running torrents
410    [self updateTorrentHistory];
411    [fTorrents makeObjectsPerformSelector: @selector(stopTransferForQuit)];
412   
413    //remember window states and close all windows
414    [fDefaults setBool: [[fInfoController window] isVisible] forKey: @"InfoVisible"];
415    [[NSApp windows] makeObjectsPerformSelector: @selector(close)];
416    [self showStatusBar: NO animate: NO];
417    [self showFilterBar: NO animate: NO];
418   
419    //clear badge
420    [fBadger clearBadge];
421
422    //end quickly if the app is updating
423    if (fUpdateInProgress)
424        return;
425
426    //wait for running transfers to stop (5 second timeout)
427    NSDate * start = [NSDate date];
428    BOOL timeUp = NO;
429   
430    NSEnumerator * enumerator = [fTorrents objectEnumerator];
431    Torrent * torrent;
432    while (!timeUp && (torrent = [enumerator nextObject]))
433        while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
434        {
435            usleep(100000);
436            [torrent update];
437        }
438}
439
440- (void) folderChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code
441    contextInfo: (Torrent *) torrent
442{
443    if (code == NSOKButton)
444    {
445        [torrent setDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
446        [torrent update];
447        [self attemptToStartAuto: torrent];
448       
449        [fTorrents addObject: torrent];
450    }
451   
452    [NSApp stopModal];
453}
454
455- (void) application: (NSApplication *) sender openFiles: (NSArray *) filenames
456{
457    NSString * downloadChoice = [fDefaults stringForKey: @"DownloadChoice"], * torrentPath;
458    Torrent * torrent;
459    NSEnumerator * enumerator = [filenames objectEnumerator];
460    while ((torrentPath = [enumerator nextObject]))
461    {
462        if (!(torrent = [[Torrent alloc] initWithPath: torrentPath lib: fLib]))
463            continue;
464
465        //add it to the "File > Open Recent" menu
466        [[NSDocumentController sharedDocumentController]
467            noteNewRecentDocumentURL: [NSURL fileURLWithPath: torrentPath]];
468
469        if ([downloadChoice isEqualToString: @"Ask"])
470        {
471            NSOpenPanel * panel = [NSOpenPanel openPanel];
472
473            [panel setPrompt: @"Select Download Folder"];
474            [panel setAllowsMultipleSelection: NO];
475            [panel setCanChooseFiles: NO];
476            [panel setCanChooseDirectories: YES];
477
478            [panel setMessage: [NSString stringWithFormat: @"Select the download folder for \"%@\"", [torrent name]]];
479
480            [panel beginSheetForDirectory: nil file: nil types: nil
481                modalForWindow: fWindow modalDelegate: self didEndSelector:
482                @selector( folderChoiceClosed:returnCode:contextInfo: )
483                contextInfo: torrent];
484            [NSApp runModalForWindow: panel];
485        }
486        else
487        {
488            NSString * folder = [downloadChoice isEqualToString: @"Constant"]
489                ? [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath]
490                : [torrentPath stringByDeletingLastPathComponent];
491
492            [torrent setDownloadFolder: folder];
493            [torrent update];
494            [self attemptToStartAuto: torrent];
495           
496            [fTorrents addObject: torrent];
497        }
498       
499        [torrent release];
500    }
501
502    [self torrentNumberChanged];
503
504    [self updateUI: nil];
505    [self applyFilter: nil];
506   
507    [self updateTorrentHistory];
508}
509
510- (NSArray *) torrentsAtIndexes: (NSIndexSet *) indexSet
511{
512    if ([fFilteredTorrents respondsToSelector: @selector(objectsAtIndexes:)])
513        return [fFilteredTorrents objectsAtIndexes: indexSet];
514    else
515    {
516        NSMutableArray * torrents = [NSMutableArray arrayWithCapacity: [indexSet count]];
517        unsigned int i;
518        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
519            [torrents addObject: [fFilteredTorrents objectAtIndex: i]];
520
521        return torrents;
522    }
523}
524
525- (void) torrentNumberChanged
526{
527    int count = [fTorrents count];
528    [fTotalTorrentsField setStringValue: [NSString stringWithFormat:
529        @"%d Transfer%s", count, count == 1 ? "" : "s"]];
530}
531
532//called on by applescript
533- (void) open: (NSArray *) files
534{
535    [self performSelectorOnMainThread: @selector(openFromSheet:) withObject: files waitUntilDone: NO];
536}
537
538- (void) openShowSheet: (id) sender
539{
540    NSOpenPanel * panel = [NSOpenPanel openPanel];
541
542    [panel setAllowsMultipleSelection: YES];
543    [panel setCanChooseFiles: YES];
544    [panel setCanChooseDirectories: NO];
545
546    [panel beginSheetForDirectory: nil file: nil types: [NSArray arrayWithObject: @"torrent"]
547        modalForWindow: fWindow modalDelegate: self didEndSelector:
548        @selector(openSheetClosed:returnCode:contextInfo:) contextInfo: nil];
549}
550
551- (void) openSheetClosed: (NSOpenPanel *) panel returnCode: (int) code contextInfo: (void *) info
552{
553    if (code == NSOKButton)
554        [self performSelectorOnMainThread: @selector(openFromSheet:)
555                    withObject: [panel filenames] waitUntilDone: NO];
556}
557
558- (void) openFromSheet: (NSArray *) filenames
559{
560    [self application: NSApp openFiles: filenames];
561}
562
563- (void) resumeSelectedTorrents: (id) sender
564{
565    [self resumeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
566}
567
568- (void) resumeAllTorrents: (id) sender
569{
570    [self resumeTorrents: fTorrents];
571}
572
573- (void) resumeTorrents: (NSArray *) torrents
574{
575    [torrents makeObjectsPerformSelector: @selector(startTransfer)];
576   
577    [self updateUI: nil];
578    [self applyFilter: nil];
579    [fInfoController updateInfoStatsAndSettings];
580    [self updateTorrentHistory];
581}
582
583- (void) stopSelectedTorrents: (id) sender
584{
585    [self stopTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
586}
587
588- (void) stopAllTorrents: (id) sender
589{
590    [self stopTorrents: fTorrents];
591}
592
593- (void) stopTorrents: (NSArray *) torrents
594{
595    //don't want any of these starting then stopping
596    NSEnumerator * enumerator = [torrents objectEnumerator];
597    Torrent * torrent;
598    while ((torrent = [enumerator nextObject]))
599        [torrent setWaitToStart: NO];
600
601    [torrents makeObjectsPerformSelector: @selector(stopTransfer)];
602   
603    [self updateUI: nil];
604    [self applyFilter: nil];
605    [fInfoController updateInfoStatsAndSettings];
606    [self updateTorrentHistory];
607}
608
609- (void) removeTorrents: (NSArray *) torrents
610        deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
611{
612    [torrents retain];
613    int active = 0, downloading = 0;
614
615    if ([fDefaults boolForKey: @"CheckRemove"])
616    {
617        Torrent * torrent;
618        NSEnumerator * enumerator = [torrents objectEnumerator];
619        while ((torrent = [enumerator nextObject]))
620            if ([torrent isActive])
621            {
622                active++;
623                if (![torrent isSeeding])
624                    downloading++;
625            }
626
627        if ([fDefaults boolForKey: @"CheckRemoveDownloading"] ? downloading > 0 : active > 0)
628        {
629            NSDictionary * dict = [[NSDictionary alloc] initWithObjectsAndKeys:
630                torrents, @"Torrents",
631                [NSNumber numberWithBool: deleteData], @"DeleteData",
632                [NSNumber numberWithBool: deleteTorrent], @"DeleteTorrent", nil];
633
634            NSString * title, * message;
635           
636            int selected = [fTableView numberOfSelectedRows];
637            if (selected == 1)
638            {
639                title = [NSString stringWithFormat: @"Comfirm Removal of \"%@\"",
640                            [[fFilteredTorrents objectAtIndex: [fTableView selectedRow]] name]];
641                message = @"This transfer is active."
642                            " Once removed, continuing the transfer will require the torrent file."
643                            " Do you really want to remove it?";
644            }
645            else
646            {
647                title = [NSString stringWithFormat: @"Comfirm Removal of %d Transfers", selected];
648                if (selected == active)
649                    message = [NSString stringWithFormat:
650                        @"There are %d active transfers.", active];
651                else
652                    message = [NSString stringWithFormat:
653                        @"There are %d transfers (%d active).", selected, active];
654                message = [message stringByAppendingString:
655                    @" Once removed, continuing the transfers will require the torrent files."
656                    " Do you really want to remove them?"];
657            }
658
659            NSBeginAlertSheet(title, @"Remove", @"Cancel", nil, fWindow, self,
660                nil, @selector(removeSheetDidEnd:returnCode:contextInfo:), dict, message);
661            return;
662        }
663    }
664   
665    [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
666}
667
668- (void) removeSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode contextInfo: (NSDictionary *) dict
669{
670    [NSApp stopModal];
671
672    NSArray * torrents = [dict objectForKey: @"Torrents"];
673    BOOL deleteData = [[dict objectForKey: @"DeleteData"] boolValue],
674        deleteTorrent = [[dict objectForKey: @"DeleteTorrent"] boolValue];
675    [dict release];
676   
677    if (returnCode == NSAlertDefaultReturn)
678        [self confirmRemoveTorrents: torrents deleteData: deleteData deleteTorrent: deleteTorrent];
679    else
680        [torrents release];
681}
682
683- (void) confirmRemoveTorrents: (NSArray *) torrents deleteData: (BOOL) deleteData deleteTorrent: (BOOL) deleteTorrent
684{
685    //don't want any of these starting then stopping
686    NSEnumerator * enumerator = [torrents objectEnumerator];
687    Torrent * torrent;
688    while ((torrent = [enumerator nextObject]))
689        [torrent setWaitToStart: NO];
690
691    NSNumber * lowestOrderValue = [NSNumber numberWithInt: [torrents count]], * currentOrderValue;
692
693    enumerator = [torrents objectEnumerator];
694    while ((torrent = [enumerator nextObject]))
695    {
696        [torrent stopTransfer];
697
698        if (deleteData)
699            [torrent trashData];
700        if (deleteTorrent)
701            [torrent trashTorrent];
702       
703        //determine lowest order value
704        currentOrderValue = [torrent orderValue];
705        if ([lowestOrderValue compare: currentOrderValue] == NSOrderedDescending)
706            lowestOrderValue = currentOrderValue;
707
708        [torrent removeForever];
709       
710        [fFilteredTorrents removeObject: torrent];
711        [fTorrents removeObject: torrent];
712    }
713    [torrents release];
714
715    //reset the order values if necessary
716    if ([lowestOrderValue intValue] < [fTorrents count])
717    {
718        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
719                                                @"orderValue" ascending: YES] autorelease];
720        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
721
722        NSArray * tempTorrents = [fTorrents sortedArrayUsingDescriptors: descriptors];
723        [descriptors release];
724
725        int i;
726        for (i = [lowestOrderValue intValue]; i < [tempTorrents count]; i++)
727            [[tempTorrents objectAtIndex: i] setOrderValue: i];
728    }
729   
730    [self torrentNumberChanged];
731   
732    [self updateUI: nil];
733    [self setWindowSizeToFit];
734   
735    [fTableView deselectAll: nil];
736   
737    [self updateTorrentHistory];
738}
739
740- (void) removeNoDelete: (id) sender
741{
742    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
743                deleteData: NO deleteTorrent: NO];
744}
745
746- (void) removeDeleteData: (id) sender
747{
748    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
749                deleteData: YES deleteTorrent: NO];
750}
751
752- (void) removeDeleteTorrent: (id) sender
753{
754    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
755                deleteData: NO deleteTorrent: YES];
756}
757
758- (void) removeDeleteDataAndTorrent: (id) sender
759{
760    [self removeTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]
761                deleteData: YES deleteTorrent: YES];
762}
763
764- (void) copyTorrentFile: (id) sender
765{
766    [self copyTorrentFileForTorrents: [[NSMutableArray alloc] initWithArray:
767            [self torrentsAtIndexes: [fTableView selectedRowIndexes]]]];
768}
769
770- (void) copyTorrentFileForTorrents: (NSMutableArray *) torrents
771{
772    if ([torrents count] == 0)
773    {
774        [torrents release];
775        return;
776    }
777
778    Torrent * torrent = [torrents objectAtIndex: 0];
779
780    //warn user if torrent file can't be found
781    if (![[NSFileManager defaultManager] fileExistsAtPath: [torrent torrentLocation]])
782    {
783        NSAlert * alert = [[NSAlert alloc] init];
784        [alert addButtonWithTitle: @"OK"];
785        [alert setMessageText: [NSString stringWithFormat:
786                @"Copy of \"%@\" Cannot Be Created", [torrent name]]];
787        [alert setInformativeText: [NSString stringWithFormat:
788                @"The torrent file (%@) cannot be found.", [torrent torrentLocation]]];
789        [alert setAlertStyle: NSWarningAlertStyle];
790       
791        [alert runModal];
792       
793        [torrents removeObjectAtIndex: 0];
794        [self copyTorrentFileForTorrents: torrents];
795    }
796    else
797    {
798        NSSavePanel * panel = [NSSavePanel savePanel];
799        [panel setRequiredFileType: @"torrent"];
800        [panel setCanSelectHiddenExtension: YES];
801       
802        [panel beginSheetForDirectory: nil file: [torrent name]
803            modalForWindow: fWindow modalDelegate: self didEndSelector:
804            @selector(saveTorrentCopySheetClosed:returnCode:contextInfo:) contextInfo: torrents];
805    }
806}
807
808- (void) saveTorrentCopySheetClosed: (NSSavePanel *) panel returnCode: (int) code
809    contextInfo: (NSMutableArray *) torrents
810{
811    //if save successful, copy torrent to new location with name of data file
812    if (code == NSOKButton)
813        [[NSFileManager defaultManager] copyPath: [[torrents objectAtIndex: 0] torrentLocation]
814                toPath: [panel filename] handler: nil];
815   
816    [torrents removeObjectAtIndex: 0];
817    [self performSelectorOnMainThread: @selector(copyTorrentFileForTorrents:)
818                withObject: torrents waitUntilDone: NO];
819}
820
821- (void) revealFile: (id) sender
822{
823    NSIndexSet * indexSet = [fTableView selectedRowIndexes];
824    unsigned int i;
825   
826    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
827        [[fFilteredTorrents objectAtIndex: i] revealData];
828}
829
830- (void) showPreferenceWindow: (id) sender
831{
832    NSWindow * window = [fPrefsController window];
833    if (![window isVisible])
834        [window center];
835
836    [window makeKeyAndOrderFront: nil];
837}
838
839- (void) showInfo: (id) sender
840{
841    if ([[fInfoController window] isVisible])
842        [fInfoController close];
843    else
844    {
845        [fInfoController updateInfoStats];
846        [[fInfoController window] orderFront: nil];
847    }
848}
849
850- (void) setInfoTab: (id) sender
851{
852    if (sender == fNextInfoTabItem)
853        [fInfoController setNextTab];
854    else
855        [fInfoController setPreviousTab];
856}
857
858- (void) updateControlTint: (NSNotification *) notification
859{
860    if (fSpeedLimitEnabled)
861        [fSpeedLimitButton setImage: [NSColor currentControlTint] == NSBlueControlTint
862                                        ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage];
863}
864
865- (void) updateUI: (NSTimer *) t
866{
867    NSEnumerator * enumerator = [fTorrents objectEnumerator];
868    Torrent * torrent;
869    while ((torrent = [enumerator nextObject]))
870    {
871        [torrent update];
872
873        if ([torrent justFinished])
874        {
875            [self applyFilter: nil];
876            [self checkToStartWaiting: torrent];
877       
878            [GrowlApplicationBridge notifyWithTitle: @"Download Complete"
879                description: [torrent name] notificationName: GROWL_DOWNLOAD_COMPLETE iconData: nil
880                priority: 0 isSticky: NO clickContext: nil];
881
882            if (![fWindow isKeyWindow])
883                fCompleted++;
884        }
885    }
886
887    if ([fSortType isEqualToString: @"Progress"] || [fSortType isEqualToString: @"State"])
888        [self sortTorrents];
889    else
890        [fTableView reloadData];
891   
892    //update the global DL/UL rates
893    float downloadRate, uploadRate;
894    tr_torrentRates(fLib, & downloadRate, & uploadRate);
895    if (fStatusBarVisible)
896    {
897        [fTotalDLField setStringValue: [@"Total DL: " stringByAppendingString: [NSString stringForSpeed: downloadRate]]];
898        [fTotalULField setStringValue: [@"Total UL: " stringByAppendingString: [NSString stringForSpeed: uploadRate]]];
899    }
900
901    if ([[fInfoController window] isVisible])
902        [fInfoController updateInfoStats];
903
904    //badge dock
905    [fBadger updateBadgeWithCompleted: fCompleted uploadRate: uploadRate downloadRate: downloadRate];
906}
907
908- (void) updateTorrentHistory
909{
910    NSMutableArray * history = [NSMutableArray arrayWithCapacity: [fTorrents count]];
911
912    NSEnumerator * enumerator = [fTorrents objectEnumerator];
913    Torrent * torrent;
914    while ((torrent = [enumerator nextObject]))
915        [history addObject: [torrent history]];
916
917    [fDefaults setObject: history forKey: @"History"];
918    [fDefaults synchronize];
919}
920
921- (void) sortTorrents
922{
923    //remember selected rows if needed
924    NSArray * selectedTorrents = nil;
925    int numSelected = [fTableView numberOfSelectedRows];
926    if (numSelected > 0 && numSelected < [fFilteredTorrents count])
927        selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
928
929    [self sortTorrentsIgnoreSelected]; //actually sort
930   
931    //set selected rows if needed
932    if (selectedTorrents)
933    {
934        Torrent * torrent;
935        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
936        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
937        while ((torrent = [enumerator nextObject]))
938            [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
939       
940        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
941        [indexSet release];
942    }
943}
944
945//doesn't remember selected rows
946- (void) sortTorrentsIgnoreSelected
947{
948    NSSortDescriptor * nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:
949                                            @"name" ascending: YES] autorelease],
950                    * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
951                                            @"orderValue" ascending: YES] autorelease];
952
953    NSArray * descriptors;
954    if ([fSortType isEqualToString: @"Name"])
955        descriptors = [[NSArray alloc] initWithObjects: nameDescriptor, orderDescriptor, nil];
956    else if ([fSortType isEqualToString: @"State"])
957    {
958        NSSortDescriptor * stateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
959                                                @"stateSortKey" ascending: NO] autorelease],
960                        * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
961                                            @"progressSortKey" ascending: NO] autorelease];
962       
963        descriptors = [[NSArray alloc] initWithObjects: stateDescriptor, progressDescriptor,
964                                                            nameDescriptor, orderDescriptor, nil];
965    }
966    else if ([fSortType isEqualToString: @"Progress"])
967    {
968        NSSortDescriptor * progressDescriptor = [[[NSSortDescriptor alloc] initWithKey:
969                                            @"progressSortKey" ascending: YES] autorelease];
970       
971        descriptors = [[NSArray alloc] initWithObjects: progressDescriptor, nameDescriptor, orderDescriptor, nil];
972    }
973    else if ([fSortType isEqualToString: @"Date"])
974    {
975        NSSortDescriptor * dateDescriptor = [[[NSSortDescriptor alloc] initWithKey:
976                                            @"date" ascending: YES] autorelease];
977   
978        descriptors = [[NSArray alloc] initWithObjects: dateDescriptor, orderDescriptor, nil];
979    }
980    else
981        descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
982
983    [fFilteredTorrents sortUsingDescriptors: descriptors];
984    [descriptors release];
985   
986    [fTableView reloadData];
987}
988
989- (void) setSort: (id) sender
990{
991    //get checked items
992    NSMenuItem * prevSortItem, * prevSortActionItem;
993    if ([fSortType isEqualToString: @"Name"])
994    {
995        prevSortItem = fNameSortItem;
996        prevSortActionItem = fNameSortActionItem;
997    }
998    else if ([fSortType isEqualToString: @"State"])
999    {
1000        prevSortItem = fStateSortItem;
1001        prevSortActionItem = fStateSortActionItem;
1002    }
1003    else if ([fSortType isEqualToString: @"Progress"])
1004    {
1005        prevSortItem = fProgressSortItem;
1006        prevSortActionItem = fProgressSortActionItem;
1007    }
1008    else if ([fSortType isEqualToString: @"Date"])
1009    {
1010        prevSortItem = fDateSortItem;
1011        prevSortActionItem = fDateSortActionItem;
1012    }
1013    else
1014    {
1015        prevSortItem = fOrderSortItem;
1016        prevSortActionItem = fOrderSortActionItem;
1017    }
1018   
1019    if (sender != prevSortItem && sender != prevSortActionItem)
1020    {
1021        [fSortType release];
1022       
1023        //get new items to check
1024        NSMenuItem * currentSortItem, * currentSortActionItem;
1025        if (sender == fNameSortItem || sender == fNameSortActionItem)
1026        {
1027            currentSortItem = fNameSortItem;
1028            currentSortActionItem = fNameSortActionItem;
1029            fSortType = [[NSString alloc] initWithString: @"Name"];
1030        }
1031        else if (sender == fStateSortItem || sender == fStateSortActionItem)
1032        {
1033            currentSortItem = fStateSortItem;
1034            currentSortActionItem = fStateSortActionItem;
1035            fSortType = [[NSString alloc] initWithString: @"State"];
1036        }
1037        else if (sender == fProgressSortItem || sender == fProgressSortActionItem)
1038        {
1039            currentSortItem = fProgressSortItem;
1040            currentSortActionItem = fProgressSortActionItem;
1041            fSortType = [[NSString alloc] initWithString: @"Progress"];
1042        }
1043        else if (sender == fDateSortItem || sender == fDateSortActionItem)
1044        {
1045            currentSortItem = fDateSortItem;
1046            currentSortActionItem = fDateSortActionItem;
1047            fSortType = [[NSString alloc] initWithString: @"Date"];
1048        }
1049        else
1050        {
1051            currentSortItem = fOrderSortItem;
1052            currentSortActionItem = fOrderSortActionItem;
1053            fSortType = [[NSString alloc] initWithString: @"Order"];
1054        }
1055   
1056        [prevSortItem setState: NSOffState];
1057        [prevSortActionItem setState: NSOffState];
1058        [currentSortItem setState: NSOnState];
1059        [currentSortActionItem setState: NSOnState];
1060       
1061        [fDefaults setObject: fSortType forKey: @"Sort"];
1062    }
1063
1064    [self sortTorrents];
1065}
1066
1067- (void) applyFilter: (id) sender
1068{
1069    //remember selected rows if needed
1070    NSArray * selectedTorrents = [fTableView numberOfSelectedRows] > 0
1071                ? [self torrentsAtIndexes: [fTableView selectedRowIndexes]] : nil;
1072
1073    NSMutableArray * tempTorrents = [[NSMutableArray alloc] initWithCapacity: [fTorrents count]];
1074
1075    if ([fFilterType isEqualToString: @"Pause"])
1076    {
1077        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1078        Torrent * torrent;
1079        while ((torrent = [enumerator nextObject]))
1080            if (![torrent isActive])
1081                [tempTorrents addObject: torrent];
1082    }
1083    else if ([fFilterType isEqualToString: @"Seed"])
1084    {
1085        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1086        Torrent * torrent;
1087        while ((torrent = [enumerator nextObject]))
1088            if ([torrent isActive] && [torrent progress] >= 1.0)
1089                [tempTorrents addObject: torrent];
1090    }
1091    else if ([fFilterType isEqualToString: @"Download"])
1092    {
1093        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1094        Torrent * torrent;
1095        while ((torrent = [enumerator nextObject]))
1096            if ([torrent isActive] && [torrent progress] < 1.0)
1097                [tempTorrents addObject: torrent];
1098    }
1099    else
1100        [tempTorrents setArray: fTorrents];
1101   
1102    NSString * searchString = [fSearchFilterField stringValue];
1103    if (![searchString isEqualToString: @""])
1104    {
1105        int i;
1106        for (i = [tempTorrents count] - 1; i >= 0; i--)
1107            if ([[[tempTorrents objectAtIndex: i] name] rangeOfString: searchString
1108                                        options: NSCaseInsensitiveSearch].location == NSNotFound)
1109                [tempTorrents removeObjectAtIndex: i];
1110    }
1111   
1112    [fFilteredTorrents setArray: tempTorrents];
1113    [tempTorrents release];
1114   
1115    [self sortTorrentsIgnoreSelected];
1116   
1117    //set selected rows if needed
1118    if (selectedTorrents)
1119    {
1120        Torrent * torrent;
1121        NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1122        NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1123        unsigned index;
1124        while ((torrent = [enumerator nextObject]))
1125            if ((index = [fFilteredTorrents indexOfObject: torrent]) != NSNotFound)
1126                [indexSet addIndex: index];
1127       
1128        [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1129        [indexSet release];
1130    }
1131   
1132    [self setWindowSizeToFit];
1133}
1134
1135//resets filter and sorts torrents
1136- (void) setFilter: (id) sender
1137{
1138    BarButton * prevFilterButton;
1139    if ([fFilterType isEqualToString: @"Pause"])
1140        prevFilterButton = fPauseFilterButton;
1141    else if ([fFilterType isEqualToString: @"Seed"])
1142        prevFilterButton = fSeedFilterButton;
1143    else if ([fFilterType isEqualToString: @"Download"])
1144        prevFilterButton = fDownloadFilterButton;
1145    else
1146        prevFilterButton = fNoFilterButton;
1147   
1148    if (sender != prevFilterButton)
1149    {
1150        [prevFilterButton setEnabled: NO];
1151        [sender setEnabled: YES];
1152
1153        [fFilterType release];
1154        if (sender == fDownloadFilterButton)
1155            fFilterType = [[NSString alloc] initWithString: @"Download"];
1156        else if (sender == fPauseFilterButton)
1157            fFilterType = [[NSString alloc] initWithString: @"Pause"];
1158        else if (sender == fSeedFilterButton)
1159            fFilterType = [[NSString alloc] initWithString: @"Seed"];
1160        else
1161            fFilterType = [[NSString alloc] initWithString: @"None"];
1162
1163        [fDefaults setObject: fFilterType forKey: @"Filter"];
1164    }
1165
1166    [self applyFilter: nil];
1167}
1168
1169- (void) toggleSpeedLimit: (id) sender
1170{
1171    fSpeedLimitEnabled = !fSpeedLimitEnabled;
1172    int state = fSpeedLimitEnabled ? NSOnState : NSOffState;
1173
1174    [fSpeedLimitItem setState: state];
1175    [fSpeedLimitDockItem setState: state];
1176   
1177    [fSpeedLimitButton setImage: !fSpeedLimitEnabled ? fSpeedLimitNormalImage
1178        : ([NSColor currentControlTint] == NSBlueControlTint ? fSpeedLimitBlueImage : fSpeedLimitGraphiteImage)];
1179   
1180    [fPrefsController enableSpeedLimit: fSpeedLimitEnabled];
1181}
1182
1183- (void) setLimitGlobalEnabled: (id) sender
1184{
1185    [fPrefsController setLimitEnabled: (sender == fUploadLimitItem || sender == fDownloadLimitItem)
1186        type: (sender == fUploadLimitItem || sender == fUploadNoLimitItem) ? @"Upload" : @"Download"];
1187}
1188
1189- (void) setQuickLimitGlobal: (id) sender
1190{
1191    [fPrefsController setQuickLimit: [[sender title] intValue]
1192        type: [sender menu] == fUploadMenu ? @"Upload" : @"Download"];
1193}
1194
1195- (void) limitGlobalChange: (NSNotification *) notification
1196{
1197    NSDictionary * dict = [notification object];
1198   
1199    NSMenuItem * limitItem, * noLimitItem;
1200    if ([[dict objectForKey: @"Type"] isEqualToString: @"Upload"])
1201    {
1202        limitItem = fUploadLimitItem;
1203        noLimitItem = fUploadNoLimitItem;
1204    }
1205    else
1206    {
1207        limitItem = fDownloadLimitItem;
1208        noLimitItem = fDownloadNoLimitItem;
1209    }
1210   
1211    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1212    [limitItem setState: enable ? NSOnState : NSOffState];
1213    [noLimitItem setState: !enable ? NSOnState : NSOffState];
1214   
1215    [limitItem setTitle: [NSString stringWithFormat: @"Limit (%d KB/s)",
1216                            [[dict objectForKey: @"Limit"] intValue]]];
1217
1218    [dict release];
1219}
1220
1221- (void) setRatioGlobalEnabled: (id) sender
1222{
1223    [fPrefsController setRatioEnabled: sender == fRatioSetItem];
1224}
1225
1226- (void) setQuickRatioGlobal: (id) sender
1227{
1228    [fPrefsController setQuickRatio: [[sender title] floatValue]];
1229}
1230
1231- (void) ratioGlobalChange: (NSNotification *) notification
1232{
1233    NSDictionary * dict = [notification object];
1234   
1235    BOOL enable = [[dict objectForKey: @"Enable"] boolValue];
1236    [fRatioSetItem setState: enable ? NSOnState : NSOffState];
1237    [fRatioNotSetItem setState: !enable ? NSOnState : NSOffState];
1238   
1239    [fRatioSetItem setTitle: [NSString stringWithFormat: @"Stop at Ratio (%.2f)",
1240                            [[dict objectForKey: @"Ratio"] floatValue]]];
1241
1242    [dict release];
1243}
1244
1245- (void) checkWaitingForStopped: (NSNotification *) notification
1246{
1247    [self checkToStartWaiting: [notification object]];
1248   
1249    [self updateUI: nil];
1250    [self applyFilter: nil];
1251    [fInfoController updateInfoStatsAndSettings];
1252    [self updateTorrentHistory];
1253}
1254
1255- (void) checkToStartWaiting: (Torrent *) finishedTorrent
1256{
1257    //don't try to start a transfer if there should be none waiting
1258    if (![[fDefaults stringForKey: @"StartSetting"] isEqualToString: @"Wait"])
1259        return;
1260
1261    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1262   
1263    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1264    Torrent * torrent, * torrentToStart = nil;
1265    while ((torrent = [enumerator nextObject]))
1266    {
1267        //ignore the torrent just stopped
1268        if (torrent == finishedTorrent)
1269            continue;
1270   
1271        if ([torrent isActive])
1272        {
1273            if (![torrent isSeeding])
1274            {
1275                desiredActive--;
1276                if (desiredActive <= 0)
1277                    return;
1278            }
1279        }
1280        else
1281        {
1282            //use as next if it is waiting to start and either no previous or order value is lower
1283            if ([torrent waitingToStart] && (!torrentToStart
1284                || [[torrentToStart orderValue] compare: [torrent orderValue]] == NSOrderedDescending))
1285                torrentToStart = torrent;
1286        }
1287    }
1288   
1289    //since it hasn't returned, the queue amount has not been met
1290    if (torrentToStart)
1291    {
1292        [torrentToStart startTransfer];
1293       
1294        [self updateUI: nil];
1295        [self applyFilter: nil];
1296        [fInfoController updateInfoStatsAndSettings];
1297        [self updateTorrentHistory];
1298    }
1299}
1300
1301- (void) torrentStartSettingChange: (NSNotification *) notification
1302{
1303    [self attemptToStartMultipleAuto: [notification object]];
1304
1305    [self updateUI: nil];
1306    [self applyFilter: nil];
1307    [fInfoController updateInfoStatsAndSettings];
1308    [self updateTorrentHistory];
1309}
1310
1311- (void) globalStartSettingChange: (NSNotification *) notification
1312{
1313    [self attemptToStartMultipleAuto: fTorrents];
1314   
1315    [self updateUI: nil];
1316    [self applyFilter: nil];
1317    [fInfoController updateInfoStatsAndSettings];
1318    [self updateTorrentHistory];
1319}
1320
1321- (void) torrentStoppedForRatio: (NSNotification *) notification
1322{
1323    [self applyFilter: nil];
1324    [fInfoController updateInfoStatsAndSettings];
1325   
1326    [GrowlApplicationBridge notifyWithTitle: @"Seeding Complete"
1327                description: [[notification object] name] notificationName: GROWL_SEEDING_COMPLETE
1328                iconData: nil priority: 0 isSticky: NO clickContext: nil];
1329}
1330
1331- (void) attemptToStartAuto: (Torrent *) torrent
1332{
1333    [self attemptToStartMultipleAuto: [NSArray arrayWithObject: torrent]];
1334}
1335
1336//will try to start, taking into consideration the start preference
1337- (void) attemptToStartMultipleAuto: (NSArray *) torrents
1338{
1339    NSString * startSetting = [fDefaults stringForKey: @"StartSetting"];
1340    if ([startSetting isEqualToString: @"Start"])
1341    {
1342        NSEnumerator * enumerator = [torrents objectEnumerator];
1343        Torrent * torrent;
1344        while ((torrent = [enumerator nextObject]))
1345            if ([torrent waitingToStart])
1346                [torrent startTransfer];
1347       
1348        return;
1349    }
1350    else if (![startSetting isEqualToString: @"Wait"])
1351        return;
1352    else;
1353   
1354    //determine the number of downloads needed to start
1355    int desiredActive = [fDefaults integerForKey: @"WaitToStartNumber"];
1356           
1357    NSEnumerator * enumerator = [fTorrents objectEnumerator];
1358    Torrent * torrent;
1359    while ((torrent = [enumerator nextObject]))
1360        if ([torrent isActive] && ![torrent isSeeding])
1361        {
1362            desiredActive--;
1363            if (desiredActive <= 0)
1364                break;
1365        }
1366   
1367    //sort torrents by order value
1368    NSArray * sortedTorrents;
1369    if ([torrents count] > 1 && desiredActive > 0)
1370    {
1371        NSSortDescriptor * orderDescriptor = [[[NSSortDescriptor alloc] initWithKey:
1372                                                    @"orderValue" ascending: YES] autorelease];
1373        NSArray * descriptors = [[NSArray alloc] initWithObjects: orderDescriptor, nil];
1374       
1375        sortedTorrents = [torrents sortedArrayUsingDescriptors: descriptors];
1376        [descriptors release];
1377    }
1378    else
1379        sortedTorrents = torrents;
1380
1381    enumerator = [sortedTorrents objectEnumerator];
1382    while ((torrent = [enumerator nextObject]))
1383    {
1384        if ([torrent progress] >= 1.0)
1385            [torrent startTransfer];
1386        else
1387        {
1388            if ([torrent waitingToStart] && desiredActive > 0)
1389            {
1390                [torrent startTransfer];
1391                desiredActive--;
1392            }
1393        }
1394       
1395        [torrent update];
1396    }
1397}
1398
1399- (void) reloadInspectorSettings: (NSNotification *) notification
1400{
1401    [fInfoController updateInfoStatsAndSettings];
1402}
1403
1404- (void) checkAutoImportDirectory: (NSTimer *) timer
1405{
1406    if (![fDefaults boolForKey: @"AutoImport"])
1407        return;
1408       
1409    NSString * path = [[fDefaults stringForKey: @"AutoImportDirectory"] stringByExpandingTildeInPath];
1410   
1411    //if folder cannot be found or the contents hasn't changed simply give up
1412    NSArray * allFileNames;
1413    if (!(allFileNames = [[NSFileManager defaultManager] directoryContentsAtPath: path])
1414            || [allFileNames isEqualToArray: fAutoImportedNames])
1415        return;
1416
1417    //try to add files that haven't already been added
1418    NSMutableArray * newFileNames = [NSMutableArray arrayWithArray: allFileNames];
1419    [newFileNames removeObjectsInArray: fAutoImportedNames];
1420   
1421    //save the current list of files
1422    [fAutoImportedNames setArray: allFileNames];
1423   
1424    NSEnumerator * enumerator = [newFileNames objectEnumerator];
1425    NSString * file;
1426    unsigned oldCount;
1427    while ((file = [enumerator nextObject]))
1428        if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1429        {
1430            oldCount = [fTorrents count];
1431            [self openFromSheet: [NSArray arrayWithObject: [path stringByAppendingPathComponent: file]]];
1432           
1433            //import only actually happened if the torrent array is larger
1434            if (oldCount < [fTorrents count])
1435                [GrowlApplicationBridge notifyWithTitle: @"Torrent File Auto Added"
1436                    description: file notificationName: GROWL_AUTO_ADD iconData: nil
1437                    priority: 0 isSticky: NO clickContext: nil];
1438        }
1439}
1440
1441- (void) autoImportChange: (NSNotification *) notification
1442{
1443    [fAutoImportedNames removeAllObjects];
1444    [self checkAutoImportDirectory: nil];
1445}
1446
1447- (int) numberOfRowsInTableView: (NSTableView *) t
1448{
1449    return [fFilteredTorrents count];
1450}
1451
1452- (void) tableView: (NSTableView *) t willDisplayCell: (id) cell
1453    forTableColumn: (NSTableColumn *) tableColumn row: (int) row
1454{
1455    [cell setTorrent: [fFilteredTorrents objectAtIndex: row]];
1456}
1457
1458- (BOOL) tableView: (NSTableView *) tableView writeRowsWithIndexes: (NSIndexSet *) indexes
1459    toPasteboard: (NSPasteboard *) pasteboard
1460{
1461    //only allow reordering of rows if sorting by order with no filter
1462    if ([fSortType isEqualToString: @"Order"] && [fFilterType isEqualToString: @"None"]
1463            && [[fSearchFilterField stringValue] isEqualToString: @""])
1464    {
1465        [pasteboard declareTypes: [NSArray arrayWithObject: TORRENT_TABLE_VIEW_DATA_TYPE] owner: self];
1466        [pasteboard setData: [NSKeyedArchiver archivedDataWithRootObject: indexes]
1467                                forType: TORRENT_TABLE_VIEW_DATA_TYPE];
1468        return YES;
1469    }
1470    return NO;
1471}
1472
1473- (NSDragOperation) tableView: (NSTableView *) t validateDrop: (id <NSDraggingInfo>) info
1474    proposedRow: (int) row proposedDropOperation: (NSTableViewDropOperation) operation
1475{
1476    NSPasteboard * pasteboard = [info draggingPasteboard];
1477    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1478    {
1479        //check if any files to add have "torrent" as an extension
1480        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1481        NSString * file;
1482        while ((file = [enumerator nextObject]))
1483            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1484            {
1485                [fTableView setDropRow: -1 dropOperation: NSTableViewDropOn];
1486                return NSDragOperationGeneric;
1487            }
1488    }
1489    else if ([[pasteboard types] containsObject: TORRENT_TABLE_VIEW_DATA_TYPE])
1490    {
1491        [fTableView setDropRow: row dropOperation: NSTableViewDropAbove];
1492        return NSDragOperationGeneric;
1493    }
1494    else;
1495   
1496    return NSDragOperationNone;
1497}
1498
1499- (BOOL) tableView: (NSTableView *) t acceptDrop: (id <NSDraggingInfo>) info
1500    row: (int) newRow dropOperation: (NSTableViewDropOperation) operation
1501{
1502    NSPasteboard * pasteboard = [info draggingPasteboard];
1503    if ([[pasteboard types] containsObject: NSFilenamesPboardType])
1504    {
1505        //create an array of files with the "torrent" extension
1506        NSMutableArray * filesToOpen = [[NSMutableArray alloc] init];
1507        NSEnumerator * enumerator = [[pasteboard propertyListForType: NSFilenamesPboardType] objectEnumerator];
1508        NSString * file;
1509        while ((file = [enumerator nextObject]))
1510            if ([[file pathExtension] caseInsensitiveCompare: @"torrent"] == NSOrderedSame)
1511                [filesToOpen addObject: file];
1512   
1513        [self application: NSApp openFiles: filesToOpen];
1514        [filesToOpen release];
1515    }
1516    else
1517    {
1518        //remember selected rows if needed
1519        NSArray * selectedTorrents = nil;
1520        int numSelected = [fTableView numberOfSelectedRows];
1521        if (numSelected > 0 && numSelected < [fFilteredTorrents count])
1522            selectedTorrents = [self torrentsAtIndexes: [fTableView selectedRowIndexes]];
1523   
1524        NSIndexSet * indexes = [NSKeyedUnarchiver unarchiveObjectWithData:
1525                                [pasteboard dataForType: TORRENT_TABLE_VIEW_DATA_TYPE]];
1526       
1527        //move torrent in array
1528        NSArray * movingTorrents = [[self torrentsAtIndexes: indexes] retain];
1529        [fFilteredTorrents removeObjectsInArray: movingTorrents];
1530       
1531        //determine the insertion index now that transfers to move have been removed
1532        int i, decrease = 0;
1533        for (i = [indexes firstIndex]; i < newRow && i != NSNotFound; i = [indexes indexGreaterThanIndex: i])
1534            decrease++;
1535       
1536        //insert objects at new location
1537        for (i = 0; i < [movingTorrents count]; i++)
1538            [fFilteredTorrents insertObject: [movingTorrents objectAtIndex: i] atIndex: newRow - decrease + i];
1539       
1540        [movingTorrents release];
1541       
1542        //redo order values
1543        int low = [indexes firstIndex], high = [indexes lastIndex];
1544        if (newRow < low)
1545            low = newRow;
1546        else if (newRow > high + 1)
1547            high = newRow - 1;
1548        else;
1549       
1550        for (i = low; i <= high; i++)
1551            [[fFilteredTorrents objectAtIndex: i] setOrderValue: i];
1552       
1553        [fTableView reloadData];
1554       
1555        //set selected rows if needed
1556        if (selectedTorrents)
1557        {
1558            Torrent * torrent;
1559            NSEnumerator * enumerator = [selectedTorrents objectEnumerator];
1560            NSMutableIndexSet * indexSet = [[NSMutableIndexSet alloc] init];
1561            while ((torrent = [enumerator nextObject]))
1562                [indexSet addIndex: [fFilteredTorrents indexOfObject: torrent]];
1563           
1564            [fTableView selectRowIndexes: indexSet byExtendingSelection: NO];
1565            [indexSet release];
1566        }
1567    }
1568   
1569    return YES;
1570}
1571
1572- (void) tableViewSelectionDidChange: (NSNotification *) notification
1573{
1574    [fInfoController updateInfoForTorrents: [self torrentsAtIndexes: [fTableView selectedRowIndexes]]];
1575}
1576
1577- (void) toggleSmallView: (id) sender
1578{
1579    BOOL makeSmall = ![fDefaults boolForKey: @"SmallView"];
1580   
1581    [fTableView setRowHeight: makeSmall ? ROW_HEIGHT_SMALL : ROW_HEIGHT_REGULAR];
1582    [fSmallViewItem setState: makeSmall];
1583   
1584    [fDefaults setBool: makeSmall forKey: @"SmallView"];
1585   
1586    //window min height
1587    NSSize contentMinSize = [fWindow contentMinSize],
1588            contentSize = [[fWindow contentView] frame].size;
1589    contentMinSize.height = contentSize.height - [fScrollView frame].size.height
1590                            + [fTableView rowHeight] + [fTableView intercellSpacing].height;
1591    [fWindow setContentMinSize: contentMinSize];
1592   
1593    //resize for larger min height if not set to auto size
1594    if (![fDefaults boolForKey: @"AutoSize"])
1595    {
1596        if (!makeSmall && contentSize.height < contentMinSize.height)
1597        {
1598            NSRect frame = [fWindow frame];
1599            float heightChange = contentMinSize.height - contentSize.height;
1600            frame.size.height += heightChange;
1601            frame.origin.y -= heightChange;
1602           
1603            [fWindow setFrame: frame display: YES];
1604            [fTableView reloadData];
1605        }
1606    }
1607    else
1608        [self setWindowSizeToFit];
1609}
1610
1611- (void) toggleStatusBar: (id) sender
1612{
1613    [self showStatusBar: !fStatusBarVisible animate: YES];
1614    [fDefaults setBool: fStatusBarVisible forKey: @"StatusBar"];
1615}
1616
1617- (void) showStatusBar: (BOOL) show animate: (BOOL) animate
1618{
1619    if (show == fStatusBarVisible)
1620        return;
1621
1622    if (show)
1623        [fStatusBar setHidden: NO];
1624
1625    NSRect frame = [fWindow frame];
1626    float heightChange = [fStatusBar frame].size.height;
1627    if (!show)
1628        heightChange *= -1;
1629
1630    frame.size.height += heightChange;
1631    frame.origin.y -= heightChange;
1632       
1633    fStatusBarVisible = show;
1634   
1635    [self updateUI: nil];
1636   
1637    //set views to not autoresize
1638    unsigned int statsMask = [fStatusBar autoresizingMask];
1639    unsigned int filterMask = [fFilterBar autoresizingMask];
1640    unsigned int scrollMask = [fScrollView autoresizingMask];
1641    [fStatusBar setAutoresizingMask: 0];
1642    [fFilterBar setAutoresizingMask: 0];
1643    [fScrollView setAutoresizingMask: 0];
1644   
1645    [fWindow setFrame: frame display: YES animate: animate];
1646   
1647    //re-enable autoresize
1648    [fStatusBar setAutoresizingMask: statsMask];
1649    [fFilterBar setAutoresizingMask: filterMask];
1650    [fScrollView setAutoresizingMask: scrollMask];
1651   
1652    //change min size
1653    NSSize minSize = [fWindow contentMinSize];
1654    minSize.height += heightChange;
1655    [fWindow setContentMinSize: minSize];
1656   
1657    if (!show)
1658        [fStatusBar setHidden: YES];
1659   
1660    //reset tracking rects for filter buttons
1661    [fNoFilterButton resetBounds: nil];
1662    [fSeedFilterButton resetBounds: nil];
1663    [fDownloadFilterButton resetBounds: nil];
1664    [fPauseFilterButton resetBounds: nil];
1665}
1666
1667- (void) toggleFilterBar: (id) sender
1668{
1669    //disable filtering when hiding
1670    if (fFilterBarVisible)
1671    {
1672        [fSearchFilterField setStringValue: @""];
1673        [self setFilter: fNoFilterButton];
1674    }
1675
1676    [self showFilterBar: !fFilterBarVisible animate: YES];
1677    [fDefaults setBool: fFilterBarVisible forKey: @"FilterBar"];
1678}
1679
1680- (void) showFilterBar: (BOOL) show animate: (BOOL) animate
1681{
1682    if (show == fFilterBarVisible)
1683        return;
1684
1685    if (show)
1686        [fFilterBar setHidden: NO];
1687
1688    NSRect frame = [fWindow frame];
1689    float heightChange = [fFilterBar frame].size.height;
1690    if (!show)
1691        heightChange *= -1;
1692
1693    frame.size.height += heightChange;
1694    frame.origin.y -= heightChange;
1695       
1696    fFilterBarVisible = show;
1697   
1698    //set views to not autoresize
1699    unsigned int filterMask = [fFilterBar autoresizingMask];
1700    unsigned int scrollMask = [fScrollView autoresizingMask];
1701    [fFilterBar setAutoresizingMask: 0];
1702    [fScrollView setAutoresizingMask: 0];
1703   
1704    [fWindow setFrame: frame display: YES animate: animate];
1705   
1706    //re-enable autoresize
1707    [fFilterBar setAutoresizingMask: filterMask];
1708    [fScrollView setAutoresizingMask: scrollMask];
1709   
1710    //change min size
1711    NSSize minSize = [fWindow contentMinSize];
1712    minSize.height += heightChange;
1713    [fWindow setContentMinSize: minSize];
1714   
1715    if (!show)
1716    {
1717        [fFilterBar setHidden: YES];
1718        [fWindow makeFirstResponder: fTableView];
1719    }
1720   
1721    //reset tracking rects for filter buttons
1722    [fNoFilterButton resetBounds: nil];
1723    [fSeedFilterButton resetBounds: nil];
1724    [fDownloadFilterButton resetBounds: nil];
1725    [fPauseFilterButton resetBounds: nil];
1726}
1727
1728- (void) toggleAdvancedBar: (id) sender
1729{
1730    int state = ![fAdvancedBarItem state];
1731    [fAdvancedBarItem setState: state];
1732    [fDefaults setBool: state forKey: @"UseAdvancedBar"];
1733   
1734    [fTableView display];
1735}
1736
1737- (NSToolbarItem *) toolbar: (NSToolbar *) t itemForItemIdentifier:
1738    (NSString *) ident willBeInsertedIntoToolbar: (BOOL) flag
1739{
1740    NSToolbarItem * item = [[NSToolbarItem alloc] initWithItemIdentifier: ident];
1741
1742    if ([ident isEqualToString: TOOLBAR_OPEN])
1743    {
1744        [item setLabel: @"Open"];
1745        [item setPaletteLabel: @"Open Torrent Files"];
1746        [item setToolTip: @"Open torrent files"];
1747        [item setImage: [NSImage imageNamed: @"Open.png"]];
1748        [item setTarget: self];
1749        [item setAction: @selector(openShowSheet:)];
1750    }
1751    else if ([ident isEqualToString: TOOLBAR_REMOVE])
1752    {
1753        [item setLabel: @"Remove"];
1754        [item setPaletteLabel: @"Remove Selected"];
1755        [item setToolTip: @"Remove selected transfers"];
1756        [item setImage: [NSImage imageNamed: @"Remove.png"]];
1757        [item setTarget: self];
1758        [item setAction: @selector(removeNoDelete:)];
1759    }
1760    else if ([ident isEqualToString: TOOLBAR_INFO])
1761    {
1762        [item setLabel: @"Inspector"];
1763        [item setPaletteLabel: @"Toggle Inspector"];
1764        [item setToolTip: @"Toggle the torrent inspector"];
1765        [item setImage: [NSImage imageNamed: @"Info.png"]];
1766        [item setTarget: self];
1767        [item setAction: @selector(showInfo:)];
1768    }
1769    else if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1770    {
1771        [item setLabel: @"Pause All"];
1772        [item setPaletteLabel: [item label]];
1773        [item setToolTip: @"Pause all transfers"];
1774        [item setImage: [NSImage imageNamed: @"PauseAll.png"]];
1775        [item setTarget: self];
1776        [item setAction: @selector(stopAllTorrents:)];
1777    }
1778    else if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1779    {
1780        [item setLabel: @"Resume All"];
1781        [item setPaletteLabel: [item label]];
1782        [item setToolTip: @"Resume all transfers"];
1783        [item setImage: [NSImage imageNamed: @"ResumeAll.png"]];
1784        [item setTarget: self];
1785        [item setAction: @selector(resumeAllTorrents:)];
1786    }
1787    else if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1788    {
1789        [item setLabel: @"Pause"];
1790        [item setPaletteLabel: @"Pause Selected"];
1791        [item setToolTip: @"Pause selected transfers"];
1792        [item setImage: [NSImage imageNamed: @"PauseSelected.png"]];
1793        [item setTarget: self];
1794        [item setAction: @selector(stopSelectedTorrents:)];
1795    }
1796    else if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1797    {
1798        [item setLabel: @"Resume"];
1799        [item setPaletteLabel: @"Resume Selected"];
1800        [item setToolTip: @"Resume selected transfers"];
1801        [item setImage: [NSImage imageNamed: @"ResumeSelected.png"]];
1802        [item setTarget: self];
1803        [item setAction: @selector(resumeSelectedTorrents:)];
1804    }
1805    else if ([ident isEqualToString: TOOLBAR_FILTER])
1806    {
1807        [item setLabel: @"Filter"];
1808        [item setPaletteLabel: @"Toggle Filter"];
1809        [item setToolTip: @"Toggle the filter bar"];
1810        [item setImage: [NSImage imageNamed: @"Filter.png"]];
1811        [item setTarget: self];
1812        [item setAction: @selector(toggleFilterBar:)];
1813    }
1814    else
1815    {
1816        [item release];
1817        return nil;
1818    }
1819
1820    return item;
1821}
1822
1823- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) t
1824{
1825    return [NSArray arrayWithObjects:
1826            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1827            TOOLBAR_PAUSE_SELECTED, TOOLBAR_RESUME_SELECTED,
1828            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL, TOOLBAR_FILTER, TOOLBAR_INFO,
1829            NSToolbarSeparatorItemIdentifier,
1830            NSToolbarSpaceItemIdentifier,
1831            NSToolbarFlexibleSpaceItemIdentifier,
1832            NSToolbarCustomizeToolbarItemIdentifier, nil];
1833}
1834
1835- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) t
1836{
1837    return [NSArray arrayWithObjects:
1838            TOOLBAR_OPEN, TOOLBAR_REMOVE,
1839            NSToolbarSeparatorItemIdentifier,
1840            TOOLBAR_PAUSE_ALL, TOOLBAR_RESUME_ALL,
1841            NSToolbarFlexibleSpaceItemIdentifier,
1842            TOOLBAR_FILTER, TOOLBAR_INFO, nil];
1843}
1844
1845- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
1846{
1847    NSString * ident = [toolbarItem itemIdentifier];
1848
1849    //enable remove item
1850    if ([ident isEqualToString: TOOLBAR_REMOVE])
1851        return [fTableView numberOfSelectedRows] > 0;
1852
1853    //enable pause all item
1854    if ([ident isEqualToString: TOOLBAR_PAUSE_ALL])
1855    {
1856        Torrent * torrent;
1857        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1858        while ((torrent = [enumerator nextObject]))
1859            if ([torrent isActive])
1860                return YES;
1861        return NO;
1862    }
1863
1864    //enable resume all item
1865    if ([ident isEqualToString: TOOLBAR_RESUME_ALL])
1866    {
1867        Torrent * torrent;
1868        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1869        while ((torrent = [enumerator nextObject]))
1870            if ([torrent isPaused])
1871                return YES;
1872        return NO;
1873    }
1874
1875    //enable pause item
1876    if ([ident isEqualToString: TOOLBAR_PAUSE_SELECTED])
1877    {
1878        Torrent * torrent;
1879        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1880        unsigned int i;
1881       
1882        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1883            if ([[fFilteredTorrents objectAtIndex: i] isActive])
1884                return YES;
1885        return NO;
1886    }
1887   
1888    //enable resume item
1889    if ([ident isEqualToString: TOOLBAR_RESUME_SELECTED])
1890    {
1891        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1892        unsigned int i;
1893       
1894        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1895            if ([[fFilteredTorrents objectAtIndex: i] isPaused])
1896                return YES;
1897        return NO;
1898    }
1899
1900    return YES;
1901}
1902
1903- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
1904{
1905    SEL action = [menuItem action];
1906
1907    //only enable some items if it is in a context menu or the window is useable
1908    BOOL canUseMenu = [fWindow isKeyWindow] || [[[menuItem menu] title] isEqualToString: @"Context"];
1909
1910    //enable show info
1911    if (action == @selector(showInfo:))
1912    {
1913        NSString * title = [[fInfoController window] isVisible] ? @"Hide Inspector" : @"Show Inspector";
1914        if (![[menuItem title] isEqualToString: title])
1915                [menuItem setTitle: title];
1916
1917        return YES;
1918    }
1919   
1920    //enable prev/next inspector tab
1921    if (action == @selector(setInfoTab:))
1922        return [[fInfoController window] isVisible];
1923   
1924    //enable toggle status bar
1925    if (action == @selector(toggleStatusBar:))
1926    {
1927        NSString * title = fStatusBarVisible ? @"Hide Status Bar" : @"Show Status Bar";
1928        if (![[menuItem title] isEqualToString: title])
1929                [menuItem setTitle: title];
1930
1931        return canUseMenu;
1932    }
1933   
1934    //enable toggle filter bar
1935    if (action == @selector(toggleFilterBar:))
1936    {
1937        NSString * title = fFilterBarVisible ? @"Hide Filter Bar" : @"Show Filter Bar";
1938        if (![[menuItem title] isEqualToString: title])
1939                [menuItem setTitle: title];
1940
1941        return canUseMenu;
1942    }
1943
1944    //enable resume all item
1945    if (action == @selector(resumeAllTorrents:))
1946    {
1947        Torrent * torrent;
1948        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1949        while ((torrent = [enumerator nextObject]))
1950            if ([torrent isPaused])
1951                return YES;
1952        return NO;
1953    }
1954
1955    //enable pause all item
1956    if (action == @selector(stopAllTorrents:))
1957    {
1958        Torrent * torrent;
1959        NSEnumerator * enumerator = [fTorrents objectEnumerator];
1960        while ((torrent = [enumerator nextObject]))
1961            if ([torrent isActive])
1962                return YES;
1963        return NO;
1964    }
1965
1966    //enable reveal in finder
1967    if (action == @selector(revealFile:))
1968        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
1969
1970    //enable remove items
1971    if (action == @selector(removeNoDelete:) || action == @selector(removeDeleteData:)
1972        || action == @selector(removeDeleteTorrent:) || action == @selector(removeDeleteDataAndTorrent:))
1973    {
1974        BOOL warning = NO,
1975            onlyDownloading = [fDefaults boolForKey: @"CheckRemoveDownloading"],
1976            canDelete = action != @selector(removeDeleteTorrent:) && action != @selector(removeDeleteDataAndTorrent:);
1977        Torrent * torrent;
1978        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
1979        unsigned int i;
1980       
1981        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
1982        {
1983            torrent = [fFilteredTorrents objectAtIndex: i];
1984            if (!warning && [torrent isActive])
1985            {
1986                warning = onlyDownloading ? ![torrent isSeeding] : YES;
1987                if (warning && canDelete)
1988                    break;
1989            }
1990            if (!canDelete && [torrent publicTorrent])
1991            {
1992                canDelete = YES;
1993                if (warning)
1994                    break;
1995            }
1996        }
1997   
1998        //append or remove ellipsis when needed
1999        NSString * title = [menuItem title], * ellipsis = [NSString ellipsis];
2000        if (warning && [fDefaults boolForKey: @"CheckRemove"])
2001        {
2002            if (![title hasSuffix: ellipsis])
2003                [menuItem setTitle: [title stringByAppendingEllipsis]];
2004        }
2005        else
2006        {
2007            if ([title hasSuffix: ellipsis])
2008                [menuItem setTitle: [title substringToIndex: [title rangeOfString: ellipsis].location]];
2009        }
2010       
2011        return canUseMenu && canDelete && [fTableView numberOfSelectedRows] > 0;
2012    }
2013
2014    //enable pause item
2015    if (action == @selector(stopSelectedTorrents:))
2016    {
2017        if (!canUseMenu)
2018            return NO;
2019   
2020        Torrent * torrent;
2021        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2022        unsigned int i;
2023       
2024        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2025        {
2026            torrent = [fFilteredTorrents objectAtIndex: i];
2027            if ([torrent isActive])
2028                return YES;
2029        }
2030        return NO;
2031    }
2032   
2033    //enable resume item
2034    if (action == @selector(resumeSelectedTorrents:))
2035    {
2036        if (!canUseMenu)
2037            return NO;
2038   
2039        Torrent * torrent;
2040        NSIndexSet * indexSet = [fTableView selectedRowIndexes];
2041        unsigned int i;
2042       
2043        for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
2044        {
2045            torrent = [fFilteredTorrents objectAtIndex: i];
2046            if ([torrent isPaused])
2047                return YES;
2048        }
2049        return NO;
2050    }
2051   
2052    //enable sort and advanced bar items
2053    if (action == @selector(setSort:) || action == @selector(toggleAdvancedBar:)
2054            || action == @selector(toggleSmallView:))
2055        return canUseMenu;
2056   
2057    //enable copy torrent file item
2058    if (action == @selector(copyTorrentFile:))
2059    {
2060        return canUseMenu && [fTableView numberOfSelectedRows] > 0;
2061    }
2062
2063    return YES;
2064}
2065
2066- (void) sleepCallBack: (natural_t) messageType argument: (void *) messageArgument
2067{
2068    NSEnumerator * enumerator;
2069    Torrent * torrent;
2070    BOOL active;
2071
2072    switch (messageType)
2073    {
2074        case kIOMessageSystemWillSleep:
2075            //close all connections before going to sleep and remember we should resume when we wake up
2076            [fTorrents makeObjectsPerformSelector: @selector(sleep)];
2077
2078            //wait for running transfers to stop (5 second timeout)
2079            NSDate * start = [NSDate date];
2080            BOOL timeUp = NO;
2081           
2082            NSEnumerator * enumerator = [fTorrents objectEnumerator];
2083            Torrent * torrent;
2084            while (!timeUp && (torrent = [enumerator nextObject]))
2085                while (![torrent isPaused] && !(timeUp = [start timeIntervalSinceNow] < -5.0))
2086                {
2087                    usleep(100000);
2088                    [torrent update];
2089                }
2090
2091            IOAllowPowerChange(fRootPort, (long) messageArgument);
2092            break;
2093
2094        case kIOMessageCanSystemSleep:
2095            //pevent idle sleep unless all paused
2096            active = NO;
2097            enumerator = [fTorrents objectEnumerator];
2098            while ((torrent = [enumerator nextObject]))
2099                if ([torrent isActive])
2100                {
2101                    active = YES;
2102                    break;
2103                }
2104
2105            if (active)
2106                IOCancelPowerChange(fRootPort, (long) messageArgument);
2107            else
2108                IOAllowPowerChange(fRootPort, (long) messageArgument);
2109            break;
2110
2111        case kIOMessageSystemHasPoweredOn:
2112            //resume sleeping transfers after we wake up
2113            [fTorrents makeObjectsPerformSelector: @selector(wakeUp)];
2114            break;
2115    }
2116}
2117
2118- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
2119{
2120    NSRect frame = [fDefaults boolForKey: @"AutoSize"] ? [window frame]
2121                    : [self windowFrameForAmount: [fFilteredTorrents count]];
2122   
2123    frame.size.width = [fDefaults boolForKey: @"SmallView"] ? [fWindow minSize].width : WINDOW_REGULAR_WIDTH;
2124    return frame;
2125}
2126
2127- (void) setWindowSizeToFit
2128{
2129    if ([fDefaults boolForKey: @"AutoSize"])
2130        [fWindow setFrame: [self windowFrameForAmount: [fFilteredTorrents count]] display: YES animate: YES];
2131}
2132
2133- (NSRect) windowFrameForAmount: (int) amount
2134{
2135    NSRect frame = [fWindow frame];
2136    float newHeight = frame.size.height - [fScrollView frame].size.height
2137        + amount * ([fTableView rowHeight] + [fTableView intercellSpacing].height);
2138
2139    float minHeight = [fWindow minSize].height;
2140    if (newHeight < minHeight)
2141        newHeight = minHeight;
2142
2143    frame.origin.y -= (newHeight - frame.size.height);
2144    frame.size.height = newHeight;
2145   
2146    return frame;
2147}
2148
2149- (void) showMainWindow: (id) sender
2150{
2151    [fWindow makeKeyAndOrderFront: nil];
2152}
2153
2154- (void) windowDidBecomeKey: (NSNotification *) notification
2155{
2156    //reset dock badge for completed
2157    if (fCompleted > 0)
2158    {
2159        fCompleted = 0;
2160        [self updateUI: nil];
2161    }
2162   
2163    //set filter images as active
2164    [fNoFilterButton setForActive];
2165    [fSeedFilterButton setForActive];
2166    [fDownloadFilterButton setForActive];
2167    [fPauseFilterButton setForActive];
2168}
2169
2170- (void) windowDidResignKey: (NSNotification *) notification
2171{
2172    //set filter images as inactive
2173    [fNoFilterButton setForInactive];
2174    [fSeedFilterButton setForInactive];
2175    [fDownloadFilterButton setForInactive];
2176    [fPauseFilterButton setForInactive];
2177}
2178
2179- (NSSize) windowWillResize: (NSWindow *) sender toSize: (NSSize) proposedFrameSize
2180{
2181    if ([fDefaults boolForKey: @"AutoSize"])
2182        proposedFrameSize.height = [fWindow frame].size.height;
2183    return proposedFrameSize;
2184}
2185
2186- (void) windowDidResize: (NSNotification *) notification
2187{
2188    //hide search filter if it overlaps filter buttons
2189    NSRect buttonFrame = [fPauseFilterButton frame];
2190    if (NSMaxX(buttonFrame) + 2.0 > [fSearchFilterField frame].origin.x)
2191    {
2192        if (![fSearchFilterField isHidden])
2193            [fSearchFilterField setHidden: YES];
2194    }
2195    else
2196    {
2197        if ([fSearchFilterField isHidden])
2198            [fSearchFilterField setHidden: NO];
2199    }
2200}
2201
2202- (void) linkHomepage: (id) sender
2203{
2204    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: WEBSITE_URL]];
2205}
2206
2207- (void) linkForums: (id) sender
2208{
2209    [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: FORUM_URL]];
2210}
2211
2212- (void) checkUpdate: (id) sender
2213{
2214    [fPrefsController checkUpdate];
2215}
2216
2217- (void) prepareForUpdate: (NSNotification *) notification
2218{
2219    fUpdateInProgress = YES;
2220}
2221
2222- (NSDictionary *) registrationDictionaryForGrowl
2223{
2224    NSArray * notifications = [NSArray arrayWithObjects: GROWL_DOWNLOAD_COMPLETE,
2225                                        GROWL_SEEDING_COMPLETE, GROWL_AUTO_ADD, nil];
2226    return [NSDictionary dictionaryWithObjectsAndKeys: notifications, GROWL_NOTIFICATIONS_ALL,
2227                                notifications, GROWL_NOTIFICATIONS_DEFAULT, nil];
2228}
2229
2230@end
Note: See TracBrowser for help on using the repository browser.