source: trunk/macosx/InfoWindowController.m @ 920

Last change on this file since 920 was 920, checked in by joshe, 15 years ago

Merge nat-traversal branch to trunk.

  • Property svn:keywords set to Date Rev Author Id
File size: 19.9 KB
Line 
1/******************************************************************************
2 * $Id: InfoWindowController.m 920 2006-09-25 18:37:45Z joshe $
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 83.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: 30];
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 updateInfoStats];
213    [self updateInfoSettings];
214
215    //set file table
216    [fFiles removeAllObjects];
217   
218    if (numberSelected > 0)
219    {
220        Torrent * torrent;
221        NSEnumerator * enumerator = [fTorrents objectEnumerator];
222        while ((torrent = [enumerator nextObject]))
223            [fFiles addObjectsFromArray: [torrent fileList]];
224   
225        [fFileTableStatusField setStringValue: [NSString stringWithFormat: @"%d file%s", [fFiles count],
226                                                [fFiles count] == 1 ? "" : "s"]];
227    }
228    else
229        [fFileTableStatusField setStringValue: @"info not available"];
230   
231    [fFileTable deselectAll: nil];
232    [fFileTable reloadData];
233}
234
235- (void) updateInfoStats
236{
237    int numberSelected = [fTorrents count];
238    if (numberSelected == 0)
239        return;
240   
241    float downloadedValid = 0;
242    uint64_t downloadedTotal = 0, uploadedTotal = 0;
243    Torrent * torrent;
244    NSEnumerator * enumerator = [fTorrents objectEnumerator];
245    while ((torrent = [enumerator nextObject]))
246    {
247        downloadedValid += [torrent downloadedValid];
248        downloadedTotal += [torrent downloadedTotal];
249        uploadedTotal += [torrent uploadedTotal];
250    }
251
252    [fDownloadedValidField setStringValue: [NSString stringForFileSize: downloadedValid]];
253    [fDownloadedTotalField setStringValue: [NSString stringForFileSize: downloadedTotal]];
254    [fUploadedTotalField setStringValue: [NSString stringForFileSize: uploadedTotal]];
255
256    if (numberSelected == 1)
257    {
258        torrent = [fTorrents objectAtIndex: 0];
259       
260        //append percentage to amount downloaded if 1 torrent
261        [fDownloadedValidField setStringValue: [[fDownloadedValidField stringValue]
262                                        stringByAppendingFormat: @" (%.2f%%)", 100.0 * [torrent progress]]];
263       
264        [fStateField setStringValue: [torrent stateString]];
265       
266        int seeders = [torrent seeders], leechers = [torrent leechers];
267        [fSeedersField setStringValue: seeders < 0 ? @"" : [NSString stringWithInt: seeders]];
268        [fLeechersField setStringValue: leechers < 0 ? @"" : [NSString stringWithInt: leechers]];
269       
270        BOOL active = [torrent isActive];
271       
272        [fConnectedPeersField setStringValue: active ? [NSString stringWithInt: [torrent totalPeers]] : @""];
273        [fDownloadingFromField setStringValue: active ? [NSString stringWithInt: [torrent peersUploading]] : @""];
274        [fUploadingToField setStringValue: active ? [NSString stringWithInt: [torrent peersDownloading]] : @""];
275       
276        [fRatioField setStringValue: [NSString stringForRatioWithDownload: downloadedTotal upload: uploadedTotal]];
277       
278        [fSwarmSpeedField setStringValue: [torrent isActive] ? [NSString stringForSpeed: [torrent swarmSpeed]] : @""];
279       
280        //set peers table if visible
281        if ([[[fTabView selectedTabViewItem] identifier] isEqualToString: TAB_PEERS_IDENT])
282            [self reloadPeerTable];
283    }
284}
285
286- (void) updateInfoSettings
287{
288    int numberSelected = [fTorrents count];
289
290    //set ratio settings
291    if (numberSelected > 0)
292    {
293        NSEnumerator * enumerator = [fTorrents objectEnumerator];
294        Torrent * torrent = [enumerator nextObject]; //first torrent
295        const int INVALID = -99;
296        int ratioSetting = [torrent stopRatioSetting];
297        float ratioLimit = [torrent ratioLimit];
298       
299        while ((ratioSetting != INVALID || ratioLimit != INVALID)
300                && (torrent = [enumerator nextObject]))
301        {
302            if (ratioSetting != INVALID && ratioSetting != [torrent stopRatioSetting])
303                ratioSetting = INVALID;
304           
305            if (ratioLimit != INVALID && ratioLimit != [torrent ratioLimit])
306                ratioLimit = INVALID;
307        }
308       
309        [fRatioMatrix setEnabled: YES];
310       
311        if (ratioSetting == RATIO_CHECK)
312        {
313            [fRatioMatrix selectCellWithTag: RATIO_CHECK_TAG];
314            [fRatioLimitField setEnabled: YES];
315        }
316        else
317        {
318            if (ratioSetting == RATIO_NO_CHECK)
319                [fRatioMatrix selectCellWithTag: RATIO_NO_CHECK_TAG];
320            else if (ratioSetting == RATIO_GLOBAL)
321                [fRatioMatrix selectCellWithTag: RATIO_GLOBAL_TAG];
322            else
323                [fRatioMatrix deselectAllCells];
324           
325            [fRatioLimitField setEnabled: NO];
326        }
327       
328        if (ratioLimit != INVALID)
329            [fRatioLimitField setFloatValue: ratioLimit];
330        else
331            [fRatioLimitField setStringValue: @""];
332    }
333    else
334    {
335        [fRatioMatrix deselectAllCells];
336        [fRatioMatrix setEnabled: NO];
337       
338        [fRatioLimitField setEnabled: NO];
339        [fRatioLimitField setStringValue: @""];
340    }
341   
342    [self updateInfoStats];
343}
344
345//requires a non-empty torrent array
346- (void) reloadPeerTable
347{
348    Torrent * torrent = [fTorrents objectAtIndex: 0];
349   
350    [fPeers setArray: [torrent peers]];
351    [fPeers sortUsingDescriptors: [self peerSortDescriptors]];
352   
353    [fPeerTable reloadData];
354    [fPeerTableStatusField setStringValue: [NSString stringWithFormat: @"%d of %d connected",
355                                            [torrent totalPeers], [fPeers count]]];
356}
357
358- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
359{
360    SEL action = [menuItem action];
361   
362    if (action == @selector(revealFile:))
363        return [fFileTable numberOfSelectedRows] > 0 &&
364            [[[fTabView selectedTabViewItem] identifier] isEqualToString: TAB_FILES_IDENT];
365       
366    return YES;
367}
368
369- (NSRect) windowWillUseStandardFrame: (NSWindow *) window defaultFrame: (NSRect) defaultFrame
370{
371    NSRect windowRect = [window frame];
372    windowRect.size.width = [window minSize].width;   
373    return windowRect;
374}
375
376- (void) tabView: (NSTabView *) tabView didSelectTabViewItem: (NSTabViewItem *) tabViewItem
377{
378    NSString * identifier = [tabViewItem identifier];
379    [self setWindowForTab: identifier animate: YES];
380    [[NSUserDefaults standardUserDefaults] setObject: identifier forKey: @"InfoTab"];
381}
382
383- (void) setWindowForTab: (NSString *) identifier animate: (BOOL) animate
384{
385    float height;
386    if ([identifier isEqualToString: TAB_ACTIVITY_IDENT])
387        height = TAB_ACTIVITY_HEIGHT;
388    else if ([identifier isEqualToString: TAB_PEERS_IDENT])
389    {
390        height = TAB_PEERS_HEIGHT;
391       
392        if ([fTorrents count] == 1)
393            [self reloadPeerTable]; //initial update of peer table
394    }
395    else if ([identifier isEqualToString: TAB_FILES_IDENT])
396        height = TAB_FILES_HEIGHT;
397    else if ([identifier isEqualToString: TAB_OPTIONS_IDENT])
398        height = TAB_OPTIONS_HEIGHT;
399    else
400        height = TAB_INFO_HEIGHT;
401   
402    NSWindow * window = [self window];
403    NSRect frame = [window frame];
404    NSView * view = [[fTabView selectedTabViewItem] view];
405   
406    float difference = height - [view frame].size.height;
407    frame.origin.y -= difference;
408    frame.size.height += difference;
409   
410    if (animate)
411    {
412        [view setHidden: YES];
413        [window setFrame: frame display: YES animate: YES];
414        [view setHidden: NO];
415    }
416    else
417        [window setFrame: frame display: YES];
418   
419    [window setMinSize: NSMakeSize(MIN_WINDOW_WIDTH, frame.size.height)];
420    [window setMaxSize: NSMakeSize(MAX_WINDOW_WIDTH, frame.size.height)];
421}
422
423- (void) setNextTab
424{
425    if ([fTabView indexOfTabViewItem: [fTabView selectedTabViewItem]] == [fTabView numberOfTabViewItems] - 1)
426        [fTabView selectFirstTabViewItem: nil];
427    else
428        [fTabView selectNextTabViewItem: nil];
429}
430
431- (void) setPreviousTab
432{
433    if ([fTabView indexOfTabViewItem: [fTabView selectedTabViewItem]] == 0)
434        [fTabView selectLastTabViewItem: nil];
435    else
436        [fTabView selectPreviousTabViewItem: nil];
437}
438
439- (int) numberOfRowsInTableView: (NSTableView *) tableView
440{
441    if (tableView == fPeerTable)
442        return [fPeers count];
443    else
444        return [fFiles count];
445}
446
447- (id) tableView: (NSTableView *) tableView objectValueForTableColumn: (NSTableColumn *) column row: (int) row
448{
449    NSString * ident = [column identifier];
450    if (tableView == fPeerTable)
451    {
452        NSDictionary * peer = [fPeers objectAtIndex: row];
453       
454        if ([ident isEqualToString: @"Connected"])
455            return [[peer objectForKey: @"Connected"] boolValue] ? fDotGreen : fDotRed;
456        else if ([ident isEqualToString: @"UL To"])
457            return [[peer objectForKey: @"UL To"] boolValue] ? fCheckImage : nil;
458        else if ([ident isEqualToString: @"DL From"])
459            return [[peer objectForKey: @"DL From"] boolValue] ? fCheckImage : nil;
460        else if ([ident isEqualToString: @"Client"])
461            return [peer objectForKey: @"Client"];
462        else
463            return [peer objectForKey: @"IP"];
464    }
465    else
466    {
467        NSDictionary * file = [fFiles objectAtIndex: row];
468        if ([ident isEqualToString: @"Icon"])
469            return [[NSWorkspace sharedWorkspace] iconForFileType: [[file objectForKey: @"Name"] pathExtension]];
470        else if ([ident isEqualToString: @"Size"])
471            return [NSString stringForFileSize: [[file objectForKey: @"Size"] unsignedLongLongValue]];
472        else
473            return [[file objectForKey: @"Name"] lastPathComponent];
474    }
475}
476
477- (void) tableView: (NSTableView *) tableView didClickTableColumn: (NSTableColumn *) tableColumn
478{
479    if (tableView == fPeerTable)
480    {
481        [fPeers sortUsingDescriptors: [self peerSortDescriptors]];
482        [tableView reloadData];
483    }
484}
485
486- (BOOL) tableView: (NSTableView *) tableView shouldSelectRow:(int) row
487{
488    return tableView != fPeerTable;
489}
490
491//only called on >= 10.4
492- (NSString *) tableView: (NSTableView *) tableView toolTipForCell: (NSCell *) cell
493        rect: (NSRectPointer) rect tableColumn: (NSTableColumn *) column
494        row: (int) row mouseLocation: (NSPoint) mouseLocation
495{
496    if (tableView == fFileTable)
497    {
498        NSDictionary * file = [fFiles objectAtIndex: row];
499        if ([[column identifier] isEqualToString: @"Size"])
500            return [[[file objectForKey: @"Size"] stringValue] stringByAppendingString: @" bytes"];
501        else
502            return [file objectForKey: @"Name"];
503    }
504    else
505        return nil;
506}
507
508- (NSArray *) peerSortDescriptors
509{
510    NSMutableArray * descriptors = [NSMutableArray array];
511   
512    NSArray * oldDescriptors = [fPeerTable sortDescriptors];
513    if ([oldDescriptors count] > 0)
514        [descriptors addObject: [oldDescriptors objectAtIndex: 0]];
515   
516    [descriptors addObject: [[fPeerTable tableColumnWithIdentifier: @"IP"] sortDescriptorPrototype]];
517   
518    return descriptors;
519}
520
521- (void) revealFile: (id) sender
522{
523    NSIndexSet * indexSet = [fFileTable selectedRowIndexes];
524    unsigned int i;
525    for (i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex: i])
526        [[NSWorkspace sharedWorkspace] selectFile: [[fFiles objectAtIndex: i] objectForKey: @"Name"]
527                                        inFileViewerRootedAtPath: nil];
528}
529
530- (void) setRatioCheck: (id) sender
531{
532    int ratioSetting, tag = [[fRatioMatrix selectedCell] tag];
533    if (tag == RATIO_CHECK_TAG)
534        ratioSetting = RATIO_CHECK;
535    else if (tag == RATIO_NO_CHECK_TAG)
536        ratioSetting = RATIO_NO_CHECK;
537    else
538        ratioSetting = RATIO_GLOBAL;
539
540    Torrent * torrent;
541    NSEnumerator * enumerator = [fTorrents objectEnumerator];
542    while ((torrent = [enumerator nextObject]))
543        [torrent setStopRatioSetting: ratioSetting];
544   
545    [self setRatioLimit: fRatioLimitField];
546    [fRatioLimitField setEnabled: tag == RATIO_CHECK_TAG];
547}
548
549- (void) setRatioLimit: (id) sender
550{
551    Torrent * torrent;
552    NSEnumerator * enumerator = [fTorrents objectEnumerator];
553
554    float ratioLimit = [sender floatValue];
555    if (![[sender stringValue] isEqualToString: [NSString stringWithFormat: @"%.2f", ratioLimit]] || ratioLimit < 0)
556    {
557        NSBeep();
558        float ratioLimit = [[enumerator nextObject] ratioLimit]; //use first torrent
559        while ((torrent = [enumerator nextObject]))
560            if (ratioLimit != [torrent ratioLimit])
561            {
562                [sender setStringValue: @""];
563                return;
564            }
565       
566        [sender setFloatValue: ratioLimit];
567    }
568    else
569    {
570        while ((torrent = [enumerator nextObject]))
571            [torrent setRatioLimit: ratioLimit];
572    }
573}
574
575@end
Note: See TracBrowser for help on using the repository browser.