updating taskpaper.
[cpuHistory.git] / MainController.m
blobad6a71fa59da00a85ef09b82dfaf83f846290116
1 /*
2  *      CPU History
3  *      Christopher Bowns, 2008
4  *      
5  *      Formerly: Memory Monitor, by Bernhard Baehr
6  *
7  *      Copyright © 2001-2003 Bernhard Baehr
8  *
9  *      MainController.m - Main Application Controller Class
10  *
11  *      This program is free software; you can redistribute it and/or modify
12  *      it under the terms of the GNU General Public License as published by
13  *      the Free Software Foundation; either version 2 of the License, or
14  *      (at your option) any later version.
15  *
16  *      This program is distributed in the hope that it will be useful,
17  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *      GNU General Public License for more details.
20  *
21  *      You should have received a copy of the GNU General Public License
22  *      along with this program; if not, write to the Free Software
23  *      Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
27 #import "MainController.h"
30 #define GRAPH_SIZE      128
31 #define GRAPH_WIDTH     8
33 @implementation MainController
36 - (void)drawImageOnWindow
38         [displayImage drawInRect:NSMakeRect(0, 0, NSWidth([window frame]), NSHeight([window frame]))
39                 fromRect:NSMakeRect(0, 0, GRAPH_SIZE, GRAPH_SIZE) operation:NSCompositeCopy
40                 fraction:1.0];
44 - (void)showHideWindow
46         float   size;
47         
48         if ([[preferences objectForKey:SHOW_GRAPH_WINDOW_KEY] boolValue]) {
49                 size = [[preferences objectForKey:GRAPH_WINDOW_SIZE_KEY] floatValue];
50                 [window setContentSize:NSMakeSize(size, size)];
51                 [window orderWindow:NSWindowBelow relativeTo:[preferences windowNumber]];
52                 [window setLevel:([[preferences objectForKey:GRAPH_WINDOW_ON_TOP_KEY] boolValue] ?
53                         NSFloatingWindowLevel : NSNormalWindowLevel)];
54         } else
55                 [window orderOut:self];
59 - (void)drawComplete
60 // completely redraw graphImage, put graph into displayImage
61 {       
62         CPUData                 cpudata;
63         
64         
65         int                             x;
66         float                   y, yy;
67         
68         // double interval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
69         
70         [graphImage lockFocus];
72         // draw the cpu usage graph
73         [cpuInfo startIterate];
74         // for (x = 0; [memInfo getNext:&vmdata]; x++) {
75         for (x = 0; [cpuInfo getNext:&cpudata]; x+=GRAPH_WIDTH) {
76                 
77                 // y += vmdata.active * GRAPH_SIZE;
78                 y = cpudata.sys * GRAPH_SIZE;
79                 [[preferences objectForKey:ACTIVE_COLOR_KEY] set];
80                 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, 0.0, x, y));
81                 yy = y;
82                 // y += vmdata.inactive * GRAPH_SIZE;
83                 y += cpudata.nice * GRAPH_SIZE;
84                 [[preferences objectForKey:INACTIVE_COLOR_KEY] set];
85                 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, yy, x, y));
86                 // y = vmdata.wired * GRAPH_SIZE;
87                 yy = y;
88                 
89                 y += cpudata.user * GRAPH_SIZE;
90                 [[preferences objectForKey:WIRED_COLOR_KEY] set];
91                 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, yy, x, y));
92                 
93                 // free data here
94                 [[preferences objectForKey:FREE_COLOR_KEY] set];
95                 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, y, x, GRAPH_SIZE));
96         }
97         
98         // transfer graph image to icon image
99         [graphImage unlockFocus];
100         [displayImage lockFocus];       
101         [graphImage compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
102                 
103         [displayImage unlockFocus];
107 - (void)drawDelta
108 // update graphImage (based on previous graphImage), put graph into displayImage
109 {       
110         // VMData                       vmdata, vmdata0;
111         CPUData                 cpudata, cpudata0;
112         float                   y, yy;
113         
114         // double interval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
115         
116         [graphImage lockFocus];
118         // offset the old graph image
119         [graphImage compositeToPoint:NSMakePoint(-GRAPH_WIDTH, 0) operation:NSCompositeCopy];
120                 
121         // [memInfo getLast:&vmdata0];
122         [cpuInfo getLast:&cpudata0];
123         // [memInfo getCurrent:&vmdata];
124         [cpuInfo getCurrent:&cpudata];
125         
126         // draw chronological graph into graph image
127         
128         // y += vmdata.active * GRAPH_SIZE;
129         y = cpudata.sys * GRAPH_SIZE;
130         [[preferences objectForKey:ACTIVE_COLOR_KEY] set];
131         NSRectFill (NSMakeRect(GRAPH_SIZE - GRAPH_WIDTH, 0.0, GRAPH_SIZE - GRAPH_WIDTH, y));
132         yy = y;
133         
134         // y += vmdata.inactive * GRAPH_SIZE;
135         y += cpudata.nice * GRAPH_SIZE;
136         [[preferences objectForKey:INACTIVE_COLOR_KEY] set];
137         NSRectFill (NSMakeRect(GRAPH_SIZE - GRAPH_WIDTH, yy, GRAPH_SIZE - GRAPH_WIDTH, y));
138         yy = y;
139         
140         // y = vmdata.wired * GRAPH_SIZE;
141         y += cpudata.user * GRAPH_SIZE;
142         [[preferences objectForKey:WIRED_COLOR_KEY] set];
143         NSRectFill (NSMakeRect(GRAPH_SIZE - GRAPH_WIDTH, yy, GRAPH_SIZE - GRAPH_WIDTH, y));
145         // free data here
146         [[preferences objectForKey:FREE_COLOR_KEY] set];
147         NSRectFill (NSMakeRect(GRAPH_SIZE - GRAPH_WIDTH, y, GRAPH_SIZE - GRAPH_WIDTH, GRAPH_SIZE));
150         // transfer graph image to icon image
151         [graphImage unlockFocus];
152         [displayImage lockFocus];
153         [graphImage compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
155         [displayImage unlockFocus];
159 - (void)setApplicationIcon
160 // set the (scaled) application icon
162         float inc = GRAPH_SIZE * (1.0 - [[preferences objectForKey:DOCK_ICON_SIZE_KEY] floatValue]); // icon scaling
163         [iconImage lockFocus];
164         [displayImage drawInRect:NSMakeRect(inc, inc, GRAPH_SIZE - 2 * inc, GRAPH_SIZE - 2 * inc) fromRect:NSMakeRect(0, 0, GRAPH_SIZE, GRAPH_SIZE) operation:NSCompositeCopy fraction:1.0];
165         [iconImage unlockFocus];
166         [NSApp setApplicationIconImage:iconImage];
170 - (void)refreshGraph
171 // get a new sample and refresh the graph
173         // [memInfo refresh];
174         [cpuInfo refresh];
175         [self drawDelta];
176         [self setApplicationIcon];
177         
178         if ([[preferences objectForKey:SHOW_GRAPH_WINDOW_KEY] boolValue]) {
179                 [window disableFlushWindow];
180                 [view display];
181                 [window enableFlushWindow];
182                 [window flushWindow];
183         }
187 - (void)updateGraph
188 // completely redraw the graph (to show new preferences settings)
190         [self drawComplete];
191         [iconImage lockFocus];
192         [[NSColor clearColor] set];
193         NSRectFill (NSMakeRect(0, 0, GRAPH_SIZE, GRAPH_SIZE));
194         [iconImage unlockFocus];
195         [self setApplicationIcon];
196         
197         if ([[preferences objectForKey:SHOW_GRAPH_WINDOW_KEY] boolValue]) {
198                 [window disableFlushWindow];
199                 [view display];
200                 [window enableFlushWindow];
201                 [window flushWindow];
202         }
206 - (void)setTimer
208         double newInterval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
210         if (timer) {
211                 if (fabs([timer timeInterval] - newInterval) < 0.001)
212                         return;         /* frequency not changed */
213                 [timer invalidate];
214                 [timer release];
215         }
216         timer = [NSTimer scheduledTimerWithTimeInterval:newInterval
217                 target:self selector:@selector(refreshGraph) userInfo:nil repeats:YES];
218         [timer retain];
222 - (void)showPreferences:(id)sender
224         [NSApp activateIgnoringOtherApps:YES];  /* activate application when called from Dock menu */
225         [preferences showPreferences:self];
229 - (void)showAboutBox:(id)sender
231         [NSApp activateIgnoringOtherApps:YES];  /* activate application when called from Dock menu */
232         [NSApp orderFrontStandardAboutPanel:sender];
236 - (BOOL)isLoginItem
238         id      obj;
239         
240         NSString *cpuHistoryPath = [[NSBundle mainBundle] bundlePath];
241         NSDictionary *loginItemDict = [NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/loginwindow.plist", NSHomeDirectory()]];
242         NSEnumerator *loginItemEnumerator = [[loginItemDict objectForKey:@"AutoLaunchedApplicationDictionary"] objectEnumerator];
244         while ((obj = [loginItemEnumerator nextObject])) {
245                 if ([[obj objectForKey:@"Path"] isEqualTo:cpuHistoryPath])
246                         return (YES);
247         }
248         return (NO);
252 - (unsigned)systemVersion
253 // returns the system version normally retrieved with Gestalt(gestaltSystemVersion, &systemVersion)
255         const char      *p;
256         
257         unsigned version = 0;
258         
259         for (p = [[[NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]
260                 objectForKey:@"ProductVersion"] cString]; *p; p++) {
261                 if (*p != '.')
262                         version = (version << 4) | (*p - '0');
263         }
264         if (version < 0x1000)   // for 10.0, 10.1
265                 version <<= 4;
266         return (version);
270 - (BOOL)updateFrameName
271 // calculate the frameName used to save the window position; return TRUE iff the name changed,
272 // i. e. the display configuration changed since last call of this method
274         NSRect          rect;
275         NSScreen        *screen;
276         BOOL            nameDidChange;
277         
278         NSString *string = @"CHWL";     // CPUHistoryWindowLocation
279         NSEnumerator *enumerator = [[NSScreen screens] objectEnumerator];
281         while ((screen = [enumerator nextObject])) {
282                 rect = [screen frame];
283                 string = [string
284                         stringByAppendingString:[NSString stringWithFormat:@"%.0f%.0f%.0f%.0f",
285                         rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]];
286         }
287         nameDidChange = ! [string isEqualToString:frameName];
288         [frameName release];
289         frameName = string;
290         [frameName retain];
291         return (nameDidChange);
295 - (void)applicationDidFinishLaunching:(NSNotification *)notification
297         preferences = [[Preferences alloc] init];
298         // memInfo = [[MemInfo alloc] initWithCapacity:GRAPH_SIZE];
299         cpuInfo = [[CPUInfo alloc] initWithCapacity:GRAPH_SIZE];
300         if (nil == cpuInfo) //then we need to bomb out. We can't go anywhere from here.
301         {
302                 NSLog(@"%s failed to create CPUInfo object! App will crash in a minute. This is unavoidable until we learn how to gracefully exit.", _cmd);
303                 /*
304                         TODO appDidFinishLaunching: error on creating cpuInfo obj: shut down the app gracefully. Display error message?
305                 */
306         }
307         
308         displayImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
309         graphImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
310         iconImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
311         [self drawComplete];
313         window = [[TranslucentWindow allocWithZone:[self zone]]
314                 initWithContentRect:NSMakeRect(0.0, 0.0, GRAPH_SIZE, GRAPH_SIZE)
315                 styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
316         [window setReleasedWhenClosed:NO];
317         [window setBackgroundColor:[NSColor clearColor]];
318         [self updateFrameName];
319         if (! [window setFrameUsingName:frameName]) {
320                 // for compatibility with version 1.1 preferences file
321                 [window setFrameUsingName:@"CPUHistoryWindowLocation"];
322                 [NSWindow removeFrameUsingName:@"CPUHistoryWindowLocation"];
323                 [window saveFrameUsingName:frameName];
324         }
325         [window setDelegate:self];
327         view = [[TranslucentView allocWithZone:[self zone]] initWithFrame:NSMakeRect(0.0, 0.0, GRAPH_SIZE, GRAPH_SIZE)];
328         [window setContentView:view];
329         [view setContentDrawer:self method:@selector(drawImageOnWindow)];
330         [view setAutoresizingMask:(NSViewHeightSizable | NSViewWidthSizable)];
331         [view setToolTip:@"CPU History"];
332         
333         
334         [self showHideWindow];
336         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showHideWindow) name:PREFERENCES_CHANGED object:nil];
337         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGraph) name:PREFERENCES_CHANGED object:nil];
338         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTimer) name:PREFERENCES_CHANGED object:nil];
340         if ([self systemVersion] < 0x1010 && [self isLoginItem])
341                 [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(setTimer) userInfo:nil repeats:NO];
342         else
343                 [self setTimer];
347 - (void)applicationWillTerminate:(NSNotification *)aNotification 
349         if (timer) {
350                 [timer invalidate];
351                 [timer release];
352                 timer = nil;
353         }
354         [preferences savePreferences];
355         [NSApp setApplicationIconImage:[NSImage imageNamed:@"CPUHistory.icns"]];
359 - (void)applicationDidChangeScreenParameters:(NSNotification *)aNotification
361         [self updateFrameName];
362         [window setFrameUsingName:frameName];
366 - (void)windowDidMove:(NSNotification *)aNotification
368         if (! [self updateFrameName])
369                 [window saveFrameUsingName:frameName];
373 @end