source: trunk/macosx/Controller.m @ 1012

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

Don't auto-import torrents after they have been auto-imported. Useful for removing a transfer without it instantly being re-added.

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