source: trunk/macosx/StatsWindowController.m @ 13318

Last change on this file since 13318 was 13318, checked in by livings124, 9 years ago

#4920 On Lion, use window restoration on the message log and stats window

  • Property svn:keywords set to Date Rev Author Id
File size: 9.8 KB
Line 
1/******************************************************************************
2 * $Id: StatsWindowController.m 13318 2012-05-27 22:31:58Z livings124 $
3 *
4 * Copyright (c) 2007-2012 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 "StatsWindowController.h"
26#import "Controller.h"
27#import "NSStringAdditions.h"
28
29#define UPDATE_SECONDS 1.0
30
31@interface StatsWindowController (Private)
32
33- (void) updateStats;
34
35- (void) performResetStats;
36- (void) resetSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info;
37
38@end
39
40@implementation StatsWindowController
41
42StatsWindowController * fStatsWindowInstance = nil;
43tr_session * fLib = NULL;
44+ (StatsWindowController *) statsWindow
45{
46    if (!fStatsWindowInstance)
47    {
48        if ((fStatsWindowInstance = [[self alloc] init]))
49        {
50            fLib = [(Controller *)[NSApp delegate] sessionHandle];
51        }
52    }
53    return fStatsWindowInstance;
54}
55
56- (id) init
57{
58    return [super initWithWindowNibName: @"StatsWindow"];
59}
60
61- (void) awakeFromNib
62{
63    [self updateStats];
64   
65    fTimer = [NSTimer scheduledTimerWithTimeInterval: UPDATE_SECONDS target: self selector: @selector(updateStats) userInfo: nil repeats: YES];
66    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSModalPanelRunLoopMode];
67    [[NSRunLoop currentRunLoop] addTimer: fTimer forMode: NSEventTrackingRunLoopMode];
68   
69    [[self window] setRestorationClass: [self class]];
70   
71    [[self window] setTitle: NSLocalizedString(@"Statistics", "Stats window -> title")];
72   
73    //set label text
74    [fUploadedLabelField setStringValue: [NSLocalizedString(@"Uploaded", "Stats window -> label") stringByAppendingString: @":"]];
75    [fDownloadedLabelField setStringValue: [NSLocalizedString(@"Downloaded", "Stats window -> label") stringByAppendingString: @":"]];
76    [fRatioLabelField setStringValue: [NSLocalizedString(@"Ratio", "Stats window -> label") stringByAppendingString: @":"]];
77    [fTimeLabelField setStringValue: [NSLocalizedString(@"Running Time", "Stats window -> label") stringByAppendingString: @":"]];
78    [fNumOpenedLabelField setStringValue: [NSLocalizedString(@"Program Started", "Stats window -> label") stringByAppendingString: @":"]];
79   
80    //size all elements
81    const CGFloat oldWidth = [fUploadedLabelField frame].size.width;
82   
83    [fUploadedLabelField sizeToFit];
84    [fDownloadedLabelField sizeToFit];
85    [fRatioLabelField sizeToFit];
86    [fTimeLabelField sizeToFit];
87    [fNumOpenedLabelField sizeToFit];
88   
89    CGFloat maxWidth = MAX([fUploadedLabelField frame].size.width, [fDownloadedLabelField frame].size.width);
90    maxWidth = MAX(maxWidth, [fRatioLabelField frame].size.width);
91    maxWidth = MAX(maxWidth, [fTimeLabelField frame].size.width);
92    maxWidth = MAX(maxWidth, [fNumOpenedLabelField frame].size.width);
93   
94    NSRect frame = [fUploadedLabelField frame];
95    frame.size.width = maxWidth;
96    [fUploadedLabelField setFrame: frame];
97   
98    frame = [fDownloadedLabelField frame];
99    frame.size.width = maxWidth;
100    [fDownloadedLabelField setFrame: frame];
101   
102    frame = [fRatioLabelField frame];
103    frame.size.width = maxWidth;
104    [fRatioLabelField setFrame: frame];
105   
106    frame = [fTimeLabelField frame];
107    frame.size.width = maxWidth;
108    [fTimeLabelField setFrame: frame];
109   
110    frame = [fNumOpenedLabelField frame];
111    frame.size.width = maxWidth;
112    [fNumOpenedLabelField setFrame: frame];
113   
114    //resize window for new label width - fields are set in nib to adjust correctly
115    NSRect windowRect = [[self window] frame];
116    windowRect.size.width += maxWidth - oldWidth;
117    [[self window] setFrame: windowRect display: YES];
118   
119    //resize reset button
120    const CGFloat oldButtonWidth = [fResetButton frame].size.width;
121   
122    [fResetButton setTitle: NSLocalizedString(@"Reset", "Stats window -> reset button")];
123    [fResetButton sizeToFit];
124   
125    NSRect buttonFrame = [fResetButton frame];
126    buttonFrame.size.width += 10.0;
127    buttonFrame.origin.x -= buttonFrame.size.width - oldButtonWidth;
128    [fResetButton setFrame: buttonFrame];
129}
130
131- (void) windowWillClose: (id) sender
132{
133    [fTimer invalidate];
134   
135    [fStatsWindowInstance autorelease];
136    fStatsWindowInstance = nil;
137}
138
139+ (void) restoreWindowWithIdentifier: (NSString *) identifier state: (NSCoder *) state completionHandler: (void (^)(NSWindow *, NSError *)) completionHandler
140{
141    NSAssert1([identifier isEqualToString: @"StatsWindow"], @"Trying to restore unexpected identifier %@", identifier);
142   
143    completionHandler([[StatsWindowController statsWindow] window], nil);
144}
145
146- (void) resetStats: (id) sender
147{
148    if (![[NSUserDefaults standardUserDefaults] boolForKey: @"WarningResetStats"])
149    {
150        [self performResetStats];
151        return;
152    }
153   
154    NSAlert * alert = [[NSAlert alloc] init];
155    [alert setMessageText: NSLocalizedString(@"Are you sure you want to reset usage statistics?", "Stats reset -> title")];
156    [alert setInformativeText: NSLocalizedString(@"This will clear the global statistics displayed by Transmission."
157                                " Individual transfer statistics will not be affected.", "Stats reset -> message")];
158    [alert setAlertStyle: NSWarningAlertStyle];
159    [alert addButtonWithTitle: NSLocalizedString(@"Reset", "Stats reset -> button")];
160    [alert addButtonWithTitle: NSLocalizedString(@"Cancel", "Stats reset -> button")];
161    [alert setShowsSuppressionButton: YES];
162   
163    [alert beginSheetModalForWindow: [self window] modalDelegate: self
164        didEndSelector: @selector(resetSheetClosed:returnCode:contextInfo:) contextInfo: nil];
165}
166
167- (NSString *) windowFrameAutosaveName
168{
169    return @"StatsWindow";
170}
171
172@end
173
174@implementation StatsWindowController (Private)
175
176- (void) updateStats
177{
178    tr_session_stats statsAll, statsSession;
179    tr_sessionGetCumulativeStats(fLib, &statsAll);
180    tr_sessionGetStats(fLib, &statsSession);
181   
182    [fUploadedField setStringValue: [NSString stringForFileSize: statsSession.uploadedBytes]];
183    [fUploadedField setToolTip: [NSString stringWithFormat: NSLocalizedString(@"%@ bytes", "stats -> bytes"),
184                                    [NSString formattedUInteger: statsSession.uploadedBytes]]];
185    [fUploadedAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"),
186                                        [NSString stringForFileSize: statsAll.uploadedBytes]]];
187    [fUploadedAllField setToolTip: [NSString stringWithFormat: NSLocalizedString(@"%@ bytes", "stats -> bytes"),
188                                    [NSString formattedUInteger: statsAll.uploadedBytes]]];
189   
190    [fDownloadedField setStringValue: [NSString stringForFileSize: statsSession.downloadedBytes]];
191    [fDownloadedField setToolTip: [NSString stringWithFormat: NSLocalizedString(@"%@ bytes", "stats -> bytes"),
192                                    [NSString formattedUInteger: statsSession.downloadedBytes]]];
193    [fDownloadedAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"),
194                                        [NSString stringForFileSize: statsAll.downloadedBytes]]];
195    [fDownloadedAllField setToolTip: [NSString stringWithFormat: NSLocalizedString(@"%@ bytes", "stats -> bytes"),
196                                        [NSString formattedUInteger: statsAll.downloadedBytes]]];
197   
198    [fRatioField setStringValue: [NSString stringForRatio: statsSession.ratio]];
199   
200    NSString * totalRatioString = statsAll.ratio != TR_RATIO_NA
201        ? [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"), [NSString stringForRatio: statsAll.ratio]]
202        : NSLocalizedString(@"Total N/A", "stats total");
203    [fRatioAllField setStringValue: totalRatioString];
204   
205    [fTimeField setStringValue: [NSString timeString: statsSession.secondsActive showSeconds: NO]];
206    [fTimeAllField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ total", "stats total"),
207                                        [NSString timeString: statsAll.secondsActive showSeconds: NO]]];
208   
209    if (statsAll.sessionCount == 1)
210        [fNumOpenedField setStringValue: NSLocalizedString(@"1 time", "stats window -> times opened")];
211    else
212        [fNumOpenedField setStringValue: [NSString stringWithFormat: NSLocalizedString(@"%@ times", "stats window -> times opened"),
213                                            [NSString formattedUInteger: statsAll.sessionCount]]];
214}
215
216- (void) performResetStats
217{
218    tr_sessionClearStats(fLib);
219    [self updateStats];
220}
221
222- (void) resetSheetClosed: (NSAlert *) alert returnCode: (NSInteger) code contextInfo: (void *) info
223{
224    [[alert window] orderOut: nil];
225   
226    if ([[alert suppressionButton] state] == NSOnState)
227        [[NSUserDefaults standardUserDefaults] setBool: NO forKey: @"WarningResetStats"];
228   
229    if (code == NSAlertFirstButtonReturn)
230        [self performResetStats];
231}
232
233@end
Note: See TracBrowser for help on using the repository browser.