source: trunk/macosx/Controller.m @ 701

Last change on this file since 701 was 701, checked in by livings124, 15 years ago

This shouldn't have been committed.

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