source: trunk/macosx/InfoWindowController.m @ 807

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

Message Log window, accessible from the Transmission menu.

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