source: trunk/macosx/Controller.m @ 735

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

User can now choose the sound that plays.

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