source: trunk/macosx/InfoWindowController.m @ 841

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

Only update peer table when it's visible

  • Property svn:keywords set to Date Rev Author Id
File size: 21.0 KB
Line 
1/******************************************************************************
2 * $Id: InfoWindowController.m 841 2006-09-03 16:16:35Z livings124 $
3 *
4 * Copyright (c) 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 "InfoWindowController.h"
26#import "StringAdditions.h"
27
28#define RATIO_NO_CHECK_TAG 0
29#define RATIO_GLOBAL_TAG 1
30#define RATIO_CHECK_TAG 2
31
32#define MIN_WINDOW_WIDTH 270
33#define MAX_WINDOW_WIDTH 2000
34
35#define TAB_INFO_IDENT @"Info"
36#define TAB_ACTIVITY_IDENT @"Activity"
37#define TAB_PEERS_IDENT @"Peers"
38#define TAB_FILES_IDENT @"Files"
39#define TAB_OPTIONS_IDENT @"Options"
40
41//15 spacing at the bottom of each tab
42#define TAB_INFO_HEIGHT 182.0
43#define TAB_ACTIVITY_HEIGHT 230.0
44#define TAB_PEERS_HEIGHT 255.0
45#define TAB_FILES_HEIGHT 255.0
46#define TAB_OPTIONS_HEIGHT 116.0
47
48@interface InfoWindowController (Private)
49
50- (void) reloadPeerTable;
51- (void) setWindowForTab: (NSString *) identifier animate: (BOOL) animate;
52- (NSArray *) peerSortDescriptors;
53
54@end
55
56@implementation InfoWindowController
57
58- (void) awakeFromNib
59{
60    fAppIcon = [[NSApp applicationIconImage] copy];
61    fDotGreen = [NSImage imageNamed: @"GreenDot.tiff"];
62    fDotRed = [NSImage imageNamed: @"RedDot.tiff"];
63    fCheckImage = [NSImage imageNamed: @"NSMenuCheckmark"];
64   
65    fTorrents = [[NSArray alloc] init];
66    fPeers = [[NSMutableArray alloc] initWithCapacity: 6];
67    fFiles = [[NSMutableArray alloc] initWithCapacity: 6];
68    [fFileTable setDoubleAction: @selector(revealFile:)];
69   
70    //window location and size
71    NSPanel * window = (NSPanel *)[self window];
72   
73    [window setBecomesKeyOnlyIfNeeded: YES];
74   
75    [window setFrameAutosaveName: @"InspectorWindowFrame"];
76    [window setFrameUsingName: @"InspectorWindowFrame"];
77   
78    //select tab
79    NSString * identifier = [[NSUserDefaults standardUserDefaults] stringForKey: @"InfoTab"];
80    if ([fTabView indexOfTabViewItemWithIdentifier: identifier] == NSNotFound)
81        identifier = TAB_INFO_IDENT;
82   
83    [fTabView selectTabViewItemWithIdentifier: identifier];
84    [self setWindowForTab: identifier animate: NO];
85   
86    //initially sort peer table by IP
87    if ([[fPeerTable sortDescriptors] count] == 0)
88        [fPeerTable setSortDescriptors: [NSArray arrayWithObject: [[fPeerTable tableColumnWithIdentifier: @"IP"]
89                                            sortDescriptorPrototype]]];
90   
91    [self updateInfoForTorrents: [NSArray array]];
92}
93
94- (void) dealloc
95{
96    [fTorrents release];
97    [fPeers release];
98    [fFiles release];
99
100    [fAppIcon release];
101    [super dealloc];
102}
103
104- (void) updateInfoForTorrents: (NSArray *) torrents
105{
106    [fTorrents release];
107    fTorrents = [torrents retain];
108
109    int numberSelected = [fTorrents count];
110    if (numberSelected != 1)
111    {
112        if (numberSelected > 0)
113        {
114            [fNameField setStringValue: [NSString stringWithFormat: @"%d Torrents Selected", numberSelected]];
115       
116            uint64_t size = 0;
117            NSEnumerator * enumerator = [torrents objectEnumerator];
118            Torrent * torrent;
119            while ((torrent = [enumerator nextObject]))
120                size += [torrent size];
121           
122            [fSizeField setStringValue: [[NSString stringForFileSize: size] stringByAppendingString: @" Total"]];
123        }
124        else
125        {
126            [fNameField setStringValue: @"No Torrents Selected"];
127            [fSizeField setStringValue: @""];
128
129            [fDownloadedValidField setStringValue: @""];
130            [fDownloadedTotalField setStringValue: @""];
131            [fUploadedTotalField setStringValue: @""];
132        }
133       
134        [fImageView setImage: fAppIcon];
135       
136        [fNameField setToolTip: nil];
137
138        [fTrackerField setStringValue: @""];
139        [fTrackerField setToolTip: nil];
140        [fAnnounceField setStringValue: @""];
141        [fAnnounceField setToolTip: nil];
142        [fPieceSizeField setStringValue: @""];
143        [fPiecesField setStringValue: @""];
144        [fHashField setStringValue: @""];
145        [fHashField setToolTip: nil];
146       
147        [fTorrentLocationField setStringValue: @""];
148        [fTorrentLocationField setToolTip: nil];
149        [fDataLocationField setStringValue: @""];
150        [fDataLocationField setToolTip: nil];
151        [fDateStartedField setStringValue: @""];
152       
153        //don't allow empty fields to be selected
154        [fTrackerField setSelectable: NO];
155        [fAnnounceField setSelectable: NO];
156        [fHashField setSelectable: NO];
157        [fTorrentLocationField setSelectable: NO];
158        [fDataLocationField setSelectable: NO];
159       
160        [fStateField setStringValue: @""];
161        [fRatioField setStringValue: @""];
162       
163        [fSeedersField setStringValue: @""];
164        [fLeechersField setStringValue: @""];
165        [fConnectedPeersField setStringValue: @""];
166        [fDownloadingFromField setStringValue: @""];
167        [fUploadingToField setStringValue: @""];
168        [fSwarmSpeedField setStringValue: @""];
169       
170        [fPeers removeAllObjects];
171        [fPeerTable reloadData];
172        [fPeerTableStatusField setStringValue: @"info not available"];
173    }
174    else
175    {   
176        Torrent * torrent = [fTorrents objectAtIndex: 0];
177       
178        [fImageView setImage: [torrent icon]];
179       
180        NSString * name = [torrent name];
181        [fNameField setStringValue: name];
182        [fNameField setToolTip: name];
183        [fSizeField setStringValue: [NSString stringForFileSize: [torrent size]]];
184       
185        NSString * tracker = [torrent tracker],
186                * announce = [torrent announce],
187                * hashString = [torrent hashString];
188        [fTrackerField setStringValue: tracker];
189        [fTrackerField setToolTip: tracker];
190        [fAnnounceField setStringValue: announce];
191        [fAnnounceField setToolTip: announce];
192        [fPieceSizeField setStringValue: [NSString stringForFileSize: [torrent pieceSize]]];
193        [fPiecesField setIntValue: [torrent pieceCount]];
194        [fHashField setStringValue: hashString];
195        [fHashField setToolTip: hashString];
196       
197        [fTorrentLocationField setStringValue: [torrent torrentLocationString]];
198        [fTorrentLocationField setToolTip: [torrent torrentLocation]];
199        [fDataLocationField setStringValue: [[torrent dataLocation] stringByAbbreviatingWithTildeInPath]];
200        [fDataLocationField setToolTip: [torrent dataLocation]];
201        [fDateStartedField setObjectValue: [torrent date]];
202       
203        //allow these fields to be selected
204        [fTrackerField setSelectable: YES];
205        [fAnnounceField setSelectable: YES];
206        [fHashField setSelectable: YES];
207        [fTorrentLocationField setSelectable: YES];
208        [fDataLocationField setSelectable: YES];
209    }
210   
211    //update stats and settings
212    [self updateInfoStatsAndSettings];
213
214    //set file table
215    [fFiles removeAllObjects];
216   
217    if (numberSelected > 0)
218    {
219        Torrent * torrent;
220        NSEnumerator * enumerator = [fTorrents objectEnumerator];
221        while ((torrent = [enumerator nextObject]))
222            [fFiles addObjectsFromArray: [torrent fileList]];
223   
224        [fFileTableStatusField setStringValue: [NSString stringWithFormat: @"%d file%s", [fFiles count],
225                                                [fFiles count] == 1 ? "" : "s"]];
226    }
227    else
228        [fFileTableStatusField setStringValue: @"info not available"];
229   
230    [fFileTable deselectAll: nil];
231    [fFileTable reloadData];
232}
233
234- (void) updateInfoStats
235{
236    int numberSelected = [fTorrents count];
237    if (numberSelected == 0)
238        return;
239   
240    float downloadedValid = 0;
241    uint64_t downloadedTotal = 0, uploadedTotal = 0;
242    Torrent * torrent;
243    NSEnumerator * enumerator = [fTorrents objectEnumerator];
244    while ((torrent = [enumerator nextObject]))
245    {
246        downloadedValid += [torrent downloadedValid];
247        downloadedTotal += [torrent downloadedTotal];
248        uploadedTotal += [torrent uploadedTotal];
249    }
250
251    [fDownloadedValidField setStringValue: [NSString stringForFileSize: downloadedValid]];
252    [fDownloadedTotalField setStringValue: [NSString stringForFileSize: downloadedTotal]];
253    [fUploadedTotalField setStringValue: [NSString stringForFileSize: uploadedTotal]];
254
255    if (numberSelected == 1)
256    {
257        torrent = [fTorrents objectAtIndex: 0];
258       
259        //append percentage to amount downloaded if 1 torrent
260        [fDownloadedValidField setStringValue: [[fDownloadedValidField stringValue]
261                                        stringByAppendingFormat: @" (%.2f%%)", 100.0 * [torrent progress]]];
262       
263        [fStateField setStringValue: [torrent stateString]];
264       
265        int seeders = [torrent seeders], leechers = [torrent leechers];
266        [fSeedersField setStringValue: seeders < 0 ? @"" : [NSString stringWithInt: seeders]];
267        [fLeechersField setStringValue: leechers < 0 ? @"" : [NSString stringWithInt: leechers]];
268       
269        BOOL active = [torrent isActive];
270       
271        [fConnectedPeersField setStringValue: active ? [NSString stringWithInt: [torrent totalPeers]] : @""];
272        [fDownloadingFromField setStringValue: active ? [NSString stringWithInt: [torrent peersUploading]] : @""];
273        [fUploadingToField setStringValue: active ? [NSString stringWithInt: [torrent peersDownloading]] : @""];
274       
275        [fRatioField setStringValue: [NSString stringForRatioWithDownload: downloadedTotal upload: uploadedTotal]];
276       
277        [fSwarmSpeedField setStringValue: [torrent isActive] ? [NSString stringForSpeed: [torrent swarmSpeed]] : @""];
278       
279        //set peers table if visible
280        if ([[[fTabView selectedTabViewItem] identifier] isEqualToString: TAB_PEERS_IDENT])
281            [self reloadPeerTable];
282    }
283}
284
285- (void) updateInfoStatsAndSettings
286{
287    int numberSelected = [fTorrents count];
288
289    //set wait to start
290    BOOL waiting = NO, notWaiting = NO, canEnableWaiting = numberSelected > 0,
291        waitingSettingOn = [[[NSUserDefaults standardUserDefaults] stringForKey: @"StartSetting"]
292                                isEqualToString: @"Wait"];
293   
294    NSEnumerator * enumerator = [fTorrents objectEnumerator];
295    Torrent * torrent;
296    while ((torrent = [enumerator nextObject]))
297    {
298        if ([torrent waitingToStart])
299            waiting = YES;
300        else
301            notWaiting = YES;
302       
303        if (canEnableWaiting && !(![torrent isActive] && [torrent progress] < 1.0 && waitingSettingOn))
304            canEnableWaiting = NO;
305    }
306   
307    [fWaitToStartButton setState: waiting && notWaiting ? NSMixedState : (waiting ? NSOnState : NSOffState)];
308    [fWaitToStartButton setEnabled: canEnableWaiting];
309
310    //set ratio settings
311    if (numberSelected > 0)
312    {
313        enumerator = [fTorrents objectEnumerator];
314        torrent = [enumerator nextObject]; //first torrent
315        const int INVALID = -99;
316        int ratioSetting = [torrent stopRatioSetting];
317        float ratioLimit = [torrent ratioLimit];
318       
319        while ((ratioSetting != INVALID || ratioLimit != INVALID)
320                && (torrent = [enumerator nextObject]))
321        {
322            if (ratioSetting != INVALID && ratioSetting != [torrent stopRatioSetting])
323                ratioSetting = INVALID;
324           
325            if (ratioLimit != INVALID && ratioLimit != [torrent ratioLimit])
326                ratioLimit = INVALID;
327        }
328       
329        [fRatioMatrix setEnabled: YES];
330       
331        if (ratioSetting == RATIO_CHECK)
332        {
333            [fRatioMatrix selectCellWithTag: RATIO_CHECK_TAG];
334            [fRatioLimitField setEnabled: YES];
335        }
336        else
337        {
338            if (ratioSetting == RATIO_NO_CHECK)
339                [fRatioMatrix selectCellWithTag: RATIO_NO_CHECK_TAG];
340            else if (ratioSetting == RATIO_GLOBAL)
341                [fRatioMatrix selectCellWithTag: RATIO_GLOBAL_TAG];
342            else
343                [fRatioMatrix deselectAllCells];
344           
345            [fRatioLimitField setEnabled: NO];
346        }
347       
348        if (ratioLimit != INVALID)
349            [fRatioLimitField setFloatValue: ratioLimit];
350        else
351            [fRatioLimitField setStringValue: @""];
352    }
353    else
354    {
355        [fRatioMatrix deselectAllCells];
356        [fRatioMatrix setEnabled: NO];
357       
358        [fRatioLimitField setEnabled: NO];
359        [fRatioLimitField setStringValue: @""];
360    }
361   
362    [self updateInfoStats];
363}
364
365//requires a non-empty torrent array
366- (void) reloadPeerTable
367{
368    Torrent * torrent = [fTorrents objectAtIndex: 0];
369   
370    [fPeers setArray: [torrent peers]];
371    [fPeers sortUsingDescriptors: [self peerSortDescriptors]];
372   
373    [fPeerTable reloadData];
374    [fPeerTableStatusField setStringValue: [NSString stringWithFormat: @"%d of %d connected",
375                                            [torrent totalPeers], [fPeers count]]];
376}
377
378- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
379{
380    SEL action = [menuItem action];
381   
382    if (action == @selector(revealFile:))
383        return [fFileTable numberOfSelectedRows] > 0 &&
384            [[[fTabView selectedTabViewItem] identifier] isEqualToString: TAB_FILES_IDENT];
385       
386    return YES;
387}
388
389- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
390{
391    NSRect windowRect = [window frame];
392    windowRect.size.width = [window minSize].width;   
393    return windowRect;
394}
395
396- (void) tabView: (NSTabView *) tabView didSelectTabViewItem: (NSTabViewItem *) tabViewItem
397{
398    NSString * identifier = [tabViewItem identifier];
399    [self setWindowForTab: identifier animate: YES];
400    [[NSUserDefaults standardUserDefaults] setObject: identifier forKey: @"InfoTab"];
401}
402
403- (void) setWindowForTab: (NSString *) identifier animate: (BOOL) animate
404{
405    float height;
406    if ([identifier isEqualToString: TAB_ACTIVITY_IDENT])
407        height = TAB_ACTIVITY_HEIGHT;
408    else if ([identifier isEqualToString: TAB_PEERS_IDENT])
409    {
410        height = TAB_PEERS_HEIGHT;
411       
412        if ([fTorrents count] == 1)
413            [self reloadPeerTable]; //initial update of peer table
414    }
415    else if ([identifier isEqualToString: TAB_FILES_IDENT])
416        height = TAB_FILES_HEIGHT;
417    else if ([identifier isEqualToString: TAB_OPTIONS_IDENT])
418        height = TAB_OPTIONS_HEIGHT;
419    else
420        height = TAB_INFO_HEIGHT;
421   
422    NSWindow * window = [self window];
423    NSRect frame = [window frame];
424    NSView * view = [[fTabView selectedTabViewItem] view];
425   
426    float difference = height - [view frame].size.height;
427    frame.origin.y -= difference;
428    frame.size.height += difference;
429   
430    if (animate)
431    {
432        [view setHidden: YES];
433        [window setFrame: frame display: YES animate: YES];
434        [view setHidden: NO];
435    }
436    else
437        [window setFrame: frame display: YES];
438   
439    [window setMinSize: NSMakeSize(MIN_WINDOW_WIDTH, frame.size.height)];
440    [window setMaxSize: NSMakeSize(MAX_WINDOW_WIDTH, frame.size.height)];
441}
442
443- (void) setNextTab
444{
445    if ([fTabView indexOfTabViewItem: [fTabView selectedTabViewItem]] == [fTabView numberOfTabViewItems] - 1)
446        [fTabView selectFirstTabViewItem: nil];
447    else
448        [fTabView selectNextTabViewItem: nil];
449}
450
451- (void) setPreviousTab
452{
453    if ([fTabView indexOfTabViewItem: [fTabView selectedTabViewItem]] == 0)
454        [fTabView selectLastTabViewItem: nil];
455    else
456        [fTabView selectPreviousTabViewItem: nil];
457}
458
459- (int) numberOfRowsInTableView: (NSTableView *) tableView
460{
461    if (tableView == fPeerTable)
462        return [fPeers count];
463    else
464        return [fFiles count];
465}
466
467- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (int) row
468{
469    NSString * ident = [column identifier];
470    if (tableView == fPeerTable)
471    {
472        NSDictionary * peer = [fPeers objectAtIndex: row];
473       
474        if ([ident isEqualToString: @"Connected"])
475            return [[peer objectForKey: @"Connected"] boolValue] ? fDotGreen : fDotRed;
476        else if ([ident isEqualToString: @"UL To"])
477            return [[peer objectForKey: @"UL To"] boolValue] ? fCheckImage : nil;
478        else if ([ident isEqualToString: @"DL From"])
479            return [[peer objectForKey: @"DL From"] boolValue] ? fCheckImage : nil;
480        else if ([ident isEqualToString: @"Client"])
481            return [peer objectForKey: @"Client"];
482        else
483            return [peer objectForKey: @"IP"];
484    }
485    else
486    {
487        NSDictionary * file = [fFiles objectAtIndex: row];
488        if ([ident isEqualToString: @"Icon"])
489            return [[NSWorkspace sharedWorkspace] iconForFileType: [[file objectForKey: @"Name"] pathExtension]];
490        else if ([ident isEqualToString: @"Size"])
491            return [NSString stringForFileSize: [[file objectForKey: @"Size"] unsignedLongLongValue]];
492        else
493            return [[file objectForKey: @"Name"] lastPathComponent];
494    }
495}
496
497- (void) tableView: (NSTableView *) tableView didClickTableColumn: (NSTableColumn *) tableColumn
498{
499    if (tableView == fPeerTable)
500    {
501        [fPeers sortUsingDescriptors: [self peerSortDescriptors]];
502        [tableView reloadData];
503    }
504}
505
506- (BOOL) tableView: (NSTableView *) tableView shouldSelectRow:(int) row
507{
508    return tableView != fPeerTable;
509}
510
511//only called on >= 10.4
512- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell
513        rect: (NSRectPointer) rect tableColumn: (NSTableColumn *) column
514        row: (int) row mouseLocation: (NSPoint) mouseLocation
515{
516    if (tableView == fFileTable)
517    {
518        NSDictionary * file = [fFiles objectAtIndex: row];
519        if ([[column identifier] isEqualToString: @"Size"])
520            return [[[file objectForKey: @"Size"] stringValue] stringByAppendingString: @" bytes"];
521        else
522            return [file objectForKey: @"Name"];
523    }
524    else
525        return nil;
526}
527
528- (NSArray *) peerSortDescriptors
529{
530    NSMutableArray * descriptors = [NSMutableArray array];
531   
532    NSArray * oldDescriptors = [fPeerTable sortDescriptors];
533    if ([oldDescriptors count] > 0)
534        [descriptors addObject: [oldDescriptors objectAtIndex: 0]];
535   
536    [descriptors addObject: [[fPeerTable tableColumnWithIdentifier: @"IP"] sortDescriptorPrototype]];
537   
538    return descriptors;
539}
540
541- (void) revealFile: (id) sender
542{
543    NSIndexSet * indexSet = [fFileTable selectedRowIndexes];
544    unsigned int i;
545    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
546        [[NSWorkspace sharedWorkspace] selectFile: [[fFiles objectAtIndex: i] objectForKey: @"Name"]
547                                        inFileViewerRootedAtPath: nil];
548}
549
550- (void) setRatioCheck: (id) sender
551{
552    int ratioSetting, tag = [[fRatioMatrix selectedCell] tag];
553    if (tag == RATIO_CHECK_TAG)
554        ratioSetting = RATIO_CHECK;
555    else if (tag == RATIO_NO_CHECK_TAG)
556        ratioSetting = RATIO_NO_CHECK;
557    else
558        ratioSetting = RATIO_GLOBAL;
559
560    Torrent * torrent;
561    NSEnumerator * enumerator = [fTorrents objectEnumerator];
562    while ((torrent = [enumerator nextObject]))
563        [torrent setStopRatioSetting: ratioSetting];
564   
565    [self setRatioLimit: fRatioLimitField];
566    [fRatioLimitField setEnabled: tag == RATIO_CHECK_TAG];
567}
568
569- (void) setRatioLimit: (id) sender
570{
571    Torrent * torrent;
572    NSEnumerator * enumerator = [fTorrents objectEnumerator];
573
574    float ratioLimit = [sender floatValue];
575    if (![[sender stringValue] isEqualToString: [NSString stringWithFormat: @"%.2f", ratioLimit]] || ratioLimit < 0)
576    {
577        NSBeep();
578        float ratioLimit = [[enumerator nextObject] ratioLimit]; //use first torrent
579        while ((torrent = [enumerator nextObject]))
580            if (ratioLimit != [torrent ratioLimit])
581            {
582                [sender setStringValue: @""];
583                return;
584            }
585       
586        [sender setFloatValue: ratioLimit];
587    }
588    else
589    {
590        while ((torrent = [enumerator nextObject]))
591            [torrent setRatioLimit: ratioLimit];
592    }
593}
594
595- (void) setWaitToStart: (id) sender
596{
597    int state = [sender state];
598
599    NSEnumerator * enumerator = [fTorrents objectEnumerator];
600    Torrent * torrent;
601    while ((torrent = [enumerator nextObject]))
602        [torrent setWaitToStart: state];
603   
604    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStartSettingChange" object: fTorrents];
605}
606
607@end
Note: See TracBrowser for help on using the repository browser.