3 * Christopher Bowns, 2008
5 * Formerly: Memory Monitor, by Bernhard Baehr
7 * Copyright © 2001-2003 Bernhard Baehr
9 * MainController.m - Main Application Controller Class
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.
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.
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
27 #import "MainController.h"
30 #define GRAPH_SIZE 128
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
44 - (void)showHideWindow
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)];
55 [window orderOut:self];
60 // completely redraw graphImage, put graph into displayImage
68 // double interval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
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) {
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));
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;
89 y += cpudata.user * GRAPH_SIZE;
90 [[preferences objectForKey:WIRED_COLOR_KEY] set];
91 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, yy, x, y));
94 [[preferences objectForKey:FREE_COLOR_KEY] set];
95 NSRectFill (NSMakeRect(x - GRAPH_WIDTH, y, x, GRAPH_SIZE));
98 // transfer graph image to icon image
99 [graphImage unlockFocus];
100 [displayImage lockFocus];
101 [graphImage compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
103 [displayImage unlockFocus];
108 // update graphImage (based on previous graphImage), put graph into displayImage
110 // VMData vmdata, vmdata0;
111 CPUData cpudata, cpudata0;
114 // double interval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
116 [graphImage lockFocus];
118 // offset the old graph image
119 [graphImage compositeToPoint:NSMakePoint(-GRAPH_WIDTH, 0) operation:NSCompositeCopy];
121 // [memInfo getLast:&vmdata0];
122 [cpuInfo getLast:&cpudata0];
123 // [memInfo getCurrent:&vmdata];
124 [cpuInfo getCurrent:&cpudata];
126 // draw chronological graph into graph image
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));
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));
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));
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];
171 // get a new sample and refresh the graph
173 // [memInfo refresh];
176 [self setApplicationIcon];
178 if ([[preferences objectForKey:SHOW_GRAPH_WINDOW_KEY] boolValue]) {
179 [window disableFlushWindow];
181 [window enableFlushWindow];
182 [window flushWindow];
188 // completely redraw the graph (to show new preferences settings)
191 [iconImage lockFocus];
192 [[NSColor clearColor] set];
193 NSRectFill (NSMakeRect(0, 0, GRAPH_SIZE, GRAPH_SIZE));
194 [iconImage unlockFocus];
195 [self setApplicationIcon];
197 if ([[preferences objectForKey:SHOW_GRAPH_WINDOW_KEY] boolValue]) {
198 [window disableFlushWindow];
200 [window enableFlushWindow];
201 [window flushWindow];
208 double newInterval = 0.1 * [[preferences objectForKey:UPDATE_FREQUENCY_KEY] floatValue];
211 if (fabs([timer timeInterval] - newInterval) < 0.001)
212 return; /* frequency not changed */
216 timer = [NSTimer scheduledTimerWithTimeInterval:newInterval
217 target:self selector:@selector(refreshGraph) userInfo:nil repeats:YES];
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];
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])
252 - (unsigned)systemVersion
253 // returns the system version normally retrieved with Gestalt(gestaltSystemVersion, &systemVersion)
257 unsigned version = 0;
259 for (p = [[[NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"]
260 objectForKey:@"ProductVersion"] cString]; *p; p++) {
262 version = (version << 4) | (*p - '0');
264 if (version < 0x1000) // for 10.0, 10.1
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
278 NSString *string = @"CHWL"; // CPUHistoryWindowLocation
279 NSEnumerator *enumerator = [[NSScreen screens] objectEnumerator];
281 while ((screen = [enumerator nextObject])) {
282 rect = [screen frame];
284 stringByAppendingString:[NSString stringWithFormat:@"%.0f%.0f%.0f%.0f",
285 rect.origin.x, rect.origin.y, rect.size.width, rect.size.height]];
287 nameDidChange = ! [string isEqualToString:frameName];
291 return (nameDidChange);
295 - (void)applicationDidFinishLaunching:(NSNotification *)notification
297 [NSApp setApplicationIconImage:[NSImage imageNamed:@"CPUHistory.icns"]];
299 preferences = [[Preferences alloc] init];
300 // memInfo = [[MemInfo alloc] initWithCapacity:GRAPH_SIZE];
301 cpuInfo = [[CPUInfo alloc] initWithCapacity:GRAPH_SIZE];
302 if (nil == cpuInfo) //then we need to bomb out. We can't do anything else.
304 NSLog(@"%s failed to create CPUInfo object!", _cmd);
305 NSString *errorStr = [[NSString alloc] initWithFormat:@"There's not enough memory to allocate the CPU data array. Sorry, but I have to quit now."];
306 /* now display error dialog and quit */
307 int choice = NSRunAlertPanel(@"Error", errorStr, @"OK", nil, nil);
309 [preferences release];
310 [NSApp terminate:nil];
313 displayImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
314 graphImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
315 iconImage = [[NSImage allocWithZone:[self zone]] initWithSize:NSMakeSize(GRAPH_SIZE, GRAPH_SIZE)];
318 window = [[TranslucentWindow allocWithZone:[self zone]]
319 initWithContentRect:NSMakeRect(0.0, 0.0, GRAPH_SIZE, GRAPH_SIZE)
320 styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];
321 [window setReleasedWhenClosed:NO];
322 [window setBackgroundColor:[NSColor clearColor]];
323 [self updateFrameName];
324 if (! [window setFrameUsingName:frameName]) {
325 // for compatibility with version 1.1 preferences file
326 [window setFrameUsingName:@"CPUHistoryWindowLocation"];
327 [NSWindow removeFrameUsingName:@"CPUHistoryWindowLocation"];
328 [window saveFrameUsingName:frameName];
330 [window setDelegate:self];
332 view = [[TranslucentView allocWithZone:[self zone]] initWithFrame:NSMakeRect(0.0, 0.0, GRAPH_SIZE, GRAPH_SIZE)];
333 [window setContentView:view];
334 [view setContentDrawer:self method:@selector(drawImageOnWindow)];
335 [view setAutoresizingMask:(NSViewHeightSizable | NSViewWidthSizable)];
336 [view setToolTip:@"CPU History"];
339 [self showHideWindow];
341 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showHideWindow) name:PREFERENCES_CHANGED object:nil];
342 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateGraph) name:PREFERENCES_CHANGED object:nil];
343 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTimer) name:PREFERENCES_CHANGED object:nil];
345 if ([self systemVersion] < 0x1010 && [self isLoginItem])
346 [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(setTimer) userInfo:nil repeats:NO];
352 - (void)applicationWillTerminate:(NSNotification *)aNotification
359 [preferences savePreferences];
360 [NSApp setApplicationIconImage:[NSImage imageNamed:@"CPUHistory.icns"]];
364 - (void)applicationDidChangeScreenParameters:(NSNotification *)aNotification
366 [self updateFrameName];
367 [window setFrameUsingName:frameName];
371 - (void)windowDidMove:(NSNotification *)aNotification
373 if (! [self updateFrameName])
374 [window saveFrameUsingName:frameName];