source: trunk/macosx/Controller.m @ 756

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

More improvements to the way speed limit scheduling works.

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