Source

CPU Usage / CPUUsageMonitor.m

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//
//  CPUUsageMonitor.m
//  CPU Usage
//
//  Created by Peter Hosey on 2006-06-21.
//  Copyright 2006 Peter Hosey. All rights reserved.
//

#import "CPUUsageMonitor.h"

#import "CPUUsageView.h"
#import "NSString+Percentage.h"

#import "BZGridEnumerator.h"
#import "SnappingWindow.h"

#include <sys/types.h>
//sqrtf, ceilf
#include <math.h>
//sysctl and its parameters
#include <sys/sysctl.h>
//errno, strerror
#include <sys/errno.h>
#include <string.h>

#define DOCK_ICON_SIZE 128.0f

//Pre-0.5 prefs; needed for compatibility.
#define FLOATER_TEXT_COLOR_PREF     @"Floater text color"
#define FLOATER_TEXT_OPACITY_PREF   @"Floater text opacity"
#define DOCK_ICON_TEXT_COLOR_PREF   @"Dock icon text color"
#define DOCK_ICON_TEXT_OPACITY_PREF @"Dock icon text opacity"
#define BACKGROUND_COLOR_PREF       @"Background color"

#define FLOATER_ZERO_USAGE_TEXT_COLOR_PREF         @"Floater zero usage text color"
#define FLOATER_FULL_USAGE_TEXT_COLOR_PREF         @"Floater full usage text color"
#define FLOATER_ZERO_USAGE_BACKGROUND_COLOR_PREF   @"Floater zero usage background color"
#define FLOATER_FULL_USAGE_BACKGROUND_COLOR_PREF   @"Floater full usage background color"
#define DOCK_TILE_ZERO_USAGE_TEXT_COLOR_PREF       @"Dock icon zero usage text color"
#define DOCK_TILE_FULL_USAGE_TEXT_COLOR_PREF       @"Dock icon full usage text color"
#define DOCK_TILE_ZERO_USAGE_BACKGROUND_COLOR_PREF @"Dock icon zero usage background color"
#define DOCK_TILE_FULL_USAGE_BACKGROUND_COLOR_PREF @"Dock icon full usage background color"

#define CELL_WIDTH_PREF             @"Cell width"
#define CELL_HEIGHT_PREF            @"Cell height"
#define FLOATER_ENABLED_PREF        @"Draw CPU usage to window"
#define FLOATER_ORIENTATION_PREF    @"Window orientation"
#define DOCK_ICON_ENABLED_PREF      @"Draw CPU usage to Dock icon"

#define FLOATER_AUTOSAVE_NAME @"CPU usage window"

@interface CPUUsageMonitor ()

- (void)layOutCellsInTarget:(id)target;

//Main thread.
- (void)updateCPUUsageButNotViews:(NSTimer *)timer;
- (void) commenceDispatchTimerForProcessor:(unsigned)processorIndex;
//Threaded.
- (void) threadedUpdateCPUUsageViewForProcessor:(unsigned)processorIndex;

@end

@implementation CPUUsageMonitor {
	SnappingWindow *window;
	NSViewAnimation *windowResizeAnimation; //Also resizes the views. Created in -layOutCellsInWindow:

	//Preferences views.
	IBOutlet NSPanel *preferencesPanel;
	IBOutlet NSTextField *widthField, *heightField;
	IBOutlet NSButton *horizontalButton, *verticalButton, *rectangularButton;
	IBOutlet PRHGradientView *floaterTextColorGradientView, *floaterBackgroundColorGradientView;
	IBOutlet PRHGradientView *dockIconTextColorGradientView, *dockIconBackgroundColorGradientView;

	IBOutlet NSMenu *contextualMenu;

	NSMutableArray *usageViews, *dockIconUsageViews;
	NSView *dockIconUsageViewsContainingView;
	CPUUsageOrientation orientation;
	BOOL shouldDrawToDockIcon, shouldDrawToWindow;

	NSTimer *updateTimer;
	processor_info_array_t processorInfo, lastProcessorInfo;
	mach_msg_type_number_t numProcessorInfo, numLastProcessorInfo;
	unsigned numCPUs;
	float *CPUUsage;
	dispatch_source_t *runningSources;
	NSLock *deathLock;
	NSUInteger threadsRemainingToDie;
	BOOL threadsShouldExit;

	//Saved preferences, for restoration after Cancel.
	NSColor *savedBackgroundColor;
	NSSize   savedCellSize;
	CPUUsageOrientation savedOrientation;
}

@synthesize floaterZeroUsageTextColor;
@synthesize floaterFullUsageTextColor;
@synthesize floaterZeroUsageBackgroundColor;
@synthesize floaterFullUsageBackgroundColor;

@synthesize dockIconZeroUsageTextColor;
@synthesize dockIconFullUsageTextColor;
@synthesize dockIconZeroUsageBackgroundColor;
@synthesize dockIconFullUsageBackgroundColor;

@synthesize floaterTextColorGradient;
@synthesize floaterBackgroundColorGradient;
@synthesize dockIconTextColorGradient;
@synthesize dockIconBackgroundColorGradient;

@synthesize cellWidth;
@synthesize cellHeight;

@synthesize shouldDrawToDockIcon;
@synthesize shouldDrawToWindow;

+ (void)initialize {
	[self exposeBinding:@"floaterZeroUsageTextColor"];
	[self exposeBinding:@"floaterFullUsageTextColor"];
	[self exposeBinding:@"floaterTextColorGradient"];
	[self exposeBinding:@"floaterZeroUsageBackgroundColor"];
	[self exposeBinding:@"floaterFullUsageBackgroundColor"];
	[self exposeBinding:@"floaterBackgroundColorGradient"];
	[self exposeBinding:@"dockTileZeroUsageTextColor"];
	[self exposeBinding:@"dockTileFullUsageTextColor"];
	[self exposeBinding:@"dockTileTextColorGradient"];
	[self exposeBinding:@"dockTileZeroUsageBackgroundColor"];
	[self exposeBinding:@"dockTileFullUsageBackgroundColor"];
	[self exposeBinding:@"cellWidth"];
	[self exposeBinding:@"cellHeight"];
	[self exposeBinding:@"shouldDrawToDockIcon"];
	[self exposeBinding:@"shouldDrawToWindow"];
}

+ (NSSet *) keyPathsForValuesAffectingFloaterTextColorGradient {
	return [NSSet setWithObjects:@"floaterZeroUsageTextColor", @"floaterFullUsageTextColor", nil];
}
+ (NSSet *) keyPathsForValuesAffectingFloaterBackgroundColorGradient {
	return [NSSet setWithObjects:@"floaterZeroUsageBackgroundColor", @"floaterFullUsageBackgroundColor", nil];
}
+ (NSSet *) keyPathsForValuesAffectingDockTileTextColorGradient {
	return [NSSet setWithObjects:@"dockTileZeroUsageTextColor", @"dockTileFullUsageTextColor", nil];
}
+ (NSSet *) keyPathsForValuesAffectingDockTileBackgroundColorGradient {
	return [NSSet setWithObjects:@"dockTileZeroUsageBackgroundColor", @"dockTileFullUsageBackgroundColor", nil];
}

- init {
	if((self = [super init])) {
		NSNumber *thirtyTwo = [NSNumber numberWithFloat:32.0f];

		//I don't know whether there's a significant difference between this and clearColor, so I decided to err on the side of most closely imitating the old separate color and opacity.
		NSData *clearWhiteData = [NSArchiver archivedDataWithRootObject:[[NSColor whiteColor] colorWithAlphaComponent:0.0f]];
		NSData *whiteData = [NSArchiver archivedDataWithRootObject:[NSColor whiteColor]];
		NSData *clearRedData = [NSArchiver archivedDataWithRootObject:[[NSColor redColor] colorWithAlphaComponent:0.0f]];
		NSData *redData = [NSArchiver archivedDataWithRootObject:[NSColor redColor]];

		NSDictionary *defaultPrefs = [NSDictionary dictionaryWithObjectsAndKeys:
			clearWhiteData, FLOATER_ZERO_USAGE_TEXT_COLOR_PREF,
			clearWhiteData, FLOATER_FULL_USAGE_TEXT_COLOR_PREF,
			clearRedData,   FLOATER_ZERO_USAGE_BACKGROUND_COLOR_PREF,
			redData,        FLOATER_FULL_USAGE_BACKGROUND_COLOR_PREF,
			whiteData,      DOCK_TILE_ZERO_USAGE_TEXT_COLOR_PREF,
			whiteData,      DOCK_TILE_FULL_USAGE_TEXT_COLOR_PREF,
			clearRedData,   DOCK_TILE_ZERO_USAGE_BACKGROUND_COLOR_PREF,
			redData,        DOCK_TILE_FULL_USAGE_BACKGROUND_COLOR_PREF,
			thirtyTwo, CELL_WIDTH_PREF,
			thirtyTwo, CELL_HEIGHT_PREF,
			[NSNumber numberWithBool:YES], FLOATER_ENABLED_PREF,
			[NSNumber numberWithInt:CPUUsageOrientationVertical], FLOATER_ORIENTATION_PREF,
			[NSNumber numberWithBool:NO], DOCK_ICON_ENABLED_PREF,
			nil];

		[[NSUserDefaults standardUserDefaults] registerDefaults:defaultPrefs];
	}
	return self;
}

#pragma mark NSApplication delegate conformance

- (void)applicationDidFinishLaunching:(NSNotification *)notification {
	//Set up us the properties of new cells.
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//	NSData *data = [defaults dataForKey:BACKGROUND_COLOR_PREF];
//	NSColor *color = data ? [NSUnarchiver unarchiveObjectWithData:data] : [NSColor redColor];
//	[self setBackgroundColor:color];

	[self setCellWidth:[defaults floatForKey:CELL_WIDTH_PREF]];
	[self setCellHeight:[defaults floatForKey:CELL_HEIGHT_PREF]];

	//Sign up for notifications of pref changes.
	NSUserDefaultsController *udc = [NSUserDefaultsController sharedUserDefaultsController];
	NSDictionary *colorBindingOptions = [NSDictionary dictionaryWithObject:@"NSUnarchiveFromData" forKey:NSValueTransformerNameBindingOption];
	
	[self bind:@"floaterZeroUsageTextColor"        toObject:udc withKeyPath:@"values."FLOATER_ZERO_USAGE_TEXT_COLOR_PREF         options:colorBindingOptions];
	[self bind:@"floaterFullUsageTextColor"        toObject:udc withKeyPath:@"values."FLOATER_FULL_USAGE_TEXT_COLOR_PREF         options:colorBindingOptions];
	[self bind:@"floaterZeroUsageBackgroundColor"  toObject:udc withKeyPath:@"values."FLOATER_ZERO_USAGE_BACKGROUND_COLOR_PREF   options:colorBindingOptions];
	[self bind:@"floaterFullUsageBackgroundColor"  toObject:udc withKeyPath:@"values."FLOATER_FULL_USAGE_BACKGROUND_COLOR_PREF   options:colorBindingOptions];
	[self bind:@"dockIconZeroUsageTextColor"       toObject:udc withKeyPath:@"values."DOCK_TILE_ZERO_USAGE_TEXT_COLOR_PREF       options:colorBindingOptions];
	[self bind:@"dockIconFullUsageTextColor"       toObject:udc withKeyPath:@"values."DOCK_TILE_FULL_USAGE_TEXT_COLOR_PREF       options:colorBindingOptions];
	[self bind:@"dockIconZeroUsageBackgroundColor" toObject:udc withKeyPath:@"values."DOCK_TILE_ZERO_USAGE_BACKGROUND_COLOR_PREF options:colorBindingOptions];
	[self bind:@"dockIconFullUsageBackgroundColor" toObject:udc withKeyPath:@"values."DOCK_TILE_FULL_USAGE_BACKGROUND_COLOR_PREF options:colorBindingOptions];
	[self bind:@"cellWidth"            toObject:udc withKeyPath:@"values.Cell width"                  options:nil];
	[self bind:@"cellHeight"           toObject:udc withKeyPath:@"values.Cell height"                 options:nil];
	[self bind:@"shouldDrawToDockIcon" toObject:udc withKeyPath:@"values.Draw CPU usage to Dock icon" options:nil];
	[self bind:@"shouldDrawToWindow"   toObject:udc withKeyPath:@"values.Draw CPU usage to window"    options:nil];

	[floaterTextColorGradientView bind:@"gradient"
							  toObject:self
						   withKeyPath:@"floaterTextColorGradient"
							   options:nil];
	[floaterBackgroundColorGradientView bind:@"gradient"
									toObject:self
								 withKeyPath:@"floaterBackgroundColorGradient"
									 options:nil];
	[dockIconTextColorGradientView bind:@"gradient"
							   toObject:self
							withKeyPath:@"dockIconTextColorGradient"
								options:nil];
	[dockIconBackgroundColorGradientView bind:@"gradient"
									 toObject:self
								  withKeyPath:@"dockIconBackgroundColorGradient"
									  options:nil];

	//Fetch the orientation from prefs.
	orientation = [defaults integerForKey:FLOATER_ORIENTATION_PREF];

	//Set up the orientation buttons.
	int buttonStates[2] = { NSOffState, NSOnState };
	[horizontalButton  setState:buttonStates[(orientation == CPUUsageOrientationHorizontal )]];
	[verticalButton    setState:buttonStates[(orientation == CPUUsageOrientationVertical   )]];
	[rectangularButton setState:buttonStates[(orientation == CPUUsageOrientationRectangular)]];

	//We could get the number of processors the same way that we get the CPU usage info, but that allocates memory.
	enum { miblen = 2U };
	int mib[miblen] = { CTL_HW, HW_NCPU };
	size_t sizeOfNumCPUs = sizeof(numCPUs);
	int status = sysctl(mib, miblen,
		   &numCPUs, &sizeOfNumCPUs,
		   /*newp*/ NULL, /*newlen*/ 0U);
	if(status != 0)
		numCPUs = 1; //XXX Should probably error out instead…

	//Set up our display destinations.
	//First, the Dock tile.
	NSRect dockIconRect = { NSZeroPoint, { DOCK_ICON_SIZE, DOCK_ICON_SIZE } };
	dockIconUsageViewsContainingView = [[NSView alloc] initWithFrame:dockIconRect];

	dockIconUsageViews = [[NSMutableArray alloc] initWithCapacity:numCPUs];
	[self layOutCellsInTarget:dockIconUsageViewsContainingView];

	//Trigger the assignment of the view we've just created to the Dock tile's content view.
	[self setShouldDrawToDockIcon:[self shouldDrawToDockIcon]];

	//Second, create the floater.
	float numCPUsFloat = numCPUs;
	float numViewsX, numViewsY;
	if(orientation == CPUUsageOrientationHorizontal) {
		numViewsX = numCPUsFloat;
		numViewsY = 1.0f;
	} else if(orientation == CPUUsageOrientationVertical) {
		numViewsX = 1.0f;
		numViewsY = numCPUsFloat;
	} else {
		numViewsX = ceilf(sqrtf(numCPUsFloat));
		numViewsY = ceilf(numCPUsFloat / numViewsX);
	}
	float numCellsMissing = ((numViewsX * numViewsY) - numCPUsFloat);

	//Here, these enumerators are used only to compute the frame of the window. No actual enumeration is done.
	BZGridEnumerator *floaterOddCellsEnum = nil;
	BZGridEnumerator *floaterCellsEnum = [[[BZGridEnumerator alloc] initWithCellSize:(NSSize){ cellWidth, cellHeight }
																	numberOfColumns:numViewsX
																	   numberOfRows:numViewsY] autorelease];
	NSRect frame = [floaterCellsEnum overallRect];
	if(numCellsMissing) {
		float numOddCells = numCellsMissing ? numViewsX - numCellsMissing : 0.0f;
		/*oddCellsWidth is the fraction of the total frame width used by odd cells.
		 *total = X*Y
		 *numEmptySpaces = total - numCPUs
		 *numOddCPUs = X - numEmptySpaces
		 *oddCellsWidth = numOddCPUs / X
		 */
		float oddCellsWidth = numOddCells / numViewsX;
		float oddCellWidth = oddCellsWidth / numOddCells;
			
		floaterOddCellsEnum = [[[BZGridEnumerator alloc] initWithCellSize:(NSSize){ frame.size.width * oddCellWidth, cellHeight }
																  offset:(NSPoint){ 0.0f, cellHeight * numViewsY }
														 numberOfColumns:numOddCells
															numberOfRows:1U] autorelease];
		frame.size.height += [floaterOddCellsEnum overallRect].size.height;
	}

	window = [[SnappingWindow alloc] initWithContentRect:frame
											   styleMask:NSBorderlessWindowMask
												 backing:NSBackingStoreBuffered
												   defer:YES];
	[window setSnapsToEdges:YES];
	[window setSnapTolerance:10.0f];
	[window setTitle:@"CPU Usage"];
	[window setOpaque:NO];
	[window setAcceptsMouseMovedEvents:NO];
	[window setMovableByWindowBackground:YES];
	[window setLevel:NSStatusWindowLevel];
	[window setHasShadow:NO];
	[window setIgnoresMouseEvents:YES];
	[window setReleasedWhenClosed:YES];
	if(orientation != CPUUsageOrientationRectangular) {
		BOOL isHorizontal = (orientation == CPUUsageOrientationHorizontal);
		[window setResizeIncrements:(NSSize){ numCPUs * isHorizontal, numCPUs * !isHorizontal }];
	}
	[window setBackgroundColor:[NSColor clearColor]];

	[window setFrameAutosaveName:FLOATER_AUTOSAVE_NAME];
	if(![window setFrameUsingName:FLOATER_AUTOSAVE_NAME])
		[window center];
	else {
		frame.origin = [window frame].origin;
		[window setFrame:frame display:NO];
	}
	[preferencesPanel center];

	usageViews = [[NSMutableArray alloc] initWithCapacity:numCPUs];
	[self layOutCellsInTarget:window];

	CPUUsage = NSZoneMalloc([self zone], numCPUs * sizeof(float));

	updateTimer = [[NSTimer scheduledTimerWithTimeInterval:0.5
													target:self
												  selector:@selector(updateCPUUsageButNotViews:)
												  userInfo:nil
												   repeats:YES] retain];
	[updateTimer fire];

	runningSources = malloc(sizeof(runningSources[0]) * numCPUs);
	//Launch the threaded (well, queued, now) timers that sweep our CPU usage array looking for views.
	for(unsigned i = 0U; i < numCPUs; ++i) {
		[self commenceDispatchTimerForProcessor:i];
	}

	if(shouldDrawToWindow)
		[window orderFront:nil];
}

- (void)applicationWillTerminate:(NSNotification *)notification {
	//First, wait for our resize animation to finish.
	if (windowResizeAnimation) {
		NSTimeInterval duration = [windowResizeAnimation duration];
		NSTimeInterval progress = [windowResizeAnimation currentProgress];
		NSTimeInterval secondsRemaining = duration * (1.0 - progress);

		NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow:secondsRemaining];
		[[NSRunLoop currentRunLoop] runUntilDate:endDate];

		[windowResizeAnimation release];
		windowResizeAnimation = nil;
	}

	//Fade out the window.
	NSDictionary *animDict = [NSDictionary dictionaryWithObjectsAndKeys:
		window, NSViewAnimationTargetKey,
		NSViewAnimationFadeOutEffect, NSViewAnimationEffectKey,
		nil];
	NSViewAnimation *anim = [[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:animDict]];
	[anim setDuration:0.5];
	[anim setAnimationBlockingMode:NSAnimationNonblockingThreaded];

	//Tell the timers to stop, then wait for them to comply.
//	threadsShouldExit = YES;
	deathLock = [[NSLock alloc] init];
	threadsRemainingToDie = [usageViews count];
	[anim startAnimation];

	unsigned sleepCount = 100U; //Wait no more than this many tenths of a second.
	while(threadsRemainingToDie && sleepCount--)
		[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];

	[deathLock release];
	free(runningSources);

	//Wait for the animation to run out.
	while([anim isAnimating])
		[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];

	[anim release];

	[updateTimer invalidate];
	[updateTimer release];

	[usageViews release];

	[dockIconFullUsageBackgroundColor release];

	[window close];

	NSZoneFree([self zone], CPUUsage);

	vm_map_t target_task = mach_task_self();
	if(lastProcessorInfo) {
		size_t lastProcessorInfoSize = sizeof(integer_t) * numLastProcessorInfo;
		vm_deallocate(target_task, (vm_address_t)lastProcessorInfo, lastProcessorInfoSize);
		lastProcessorInfo = NULL;
	}
	if(processorInfo) {
		size_t processorInfoSize = sizeof(integer_t) * numProcessorInfo;
		vm_deallocate(target_task, (vm_address_t)processorInfo, processorInfoSize);
		processorInfo = NULL;
	}

	[NSApp setApplicationIconImage:[NSImage imageNamed:@"CPUUsageIcon"]];
}

- (void)applicationDidBecomeActive:(NSNotification *)notification {
	NSEnumerator *usageViewsEnum = [usageViews objectEnumerator];
	CPUUsageView *usageView;
	while((usageView = [usageViewsEnum nextObject])) {
		[usageView setDrawsFrame:YES];
		[usageView setNeedsThreadedDisplay:YES];
	}

	[window setIgnoresMouseEvents:NO];
}
- (void)applicationWillResignActive:(NSNotification *)notification {
	NSEnumerator *usageViewsEnum = [usageViews objectEnumerator];
	CPUUsageView *usageView;
	while((usageView = [usageViewsEnum nextObject])) {
		[usageView setDrawsFrame:NO];
		[usageView setNeedsThreadedDisplay:YES];
	}
	
	[window setIgnoresMouseEvents:YES];
}

#pragma mark Timer

- (void) threadedUpdateCPUUsageViewForProcessor:(unsigned)processorIndex {
	CPUUsageView *view = [usageViews objectAtIndex:processorIndex];
	CPUUsageView *viewInDockIcon = [dockIconUsageViews objectAtIndex:processorIndex];

	float currentUsage = CPUUsage[processorIndex];
	[view setCPUUsage:currentUsage];
	[viewInDockIcon setCPUUsage:currentUsage];

	if(shouldDrawToWindow && [view needsThreadedDisplay]) {
		[view threadedDisplay];
	}
	//Don't draw any Dock icon view here anymore—with NSDockTile, that must happen on the main thread.
}
- (void) commenceDispatchTimerForProcessor:(unsigned)processorIndex {
	dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, /*handle*/ 0, /*mask*/ 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, /*flags*/ 0));
	dispatch_source_set_timer(source, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 4), NSEC_PER_SEC / 2, /*leeway*/ NSEC_PER_SEC / 10);

	__block id bself = self;
	dispatch_source_set_event_handler(source, ^{
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

		[bself threadedUpdateCPUUsageViewForProcessor:processorIndex];

		if(threadsRemainingToDie) {
			dispatch_source_cancel(source);

			[deathLock lock];
			--threadsRemainingToDie;
			[deathLock unlock];
		}

		[pool drain];
	});

	dispatch_resume(source);

	runningSources[processorIndex] = source;
}

//Main thread.
- (void)updateCPUUsageButNotViews:(NSTimer *)timer {
	natural_t numProcessors_nobodyCares = 0U;

	kern_return_t err = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &numProcessors_nobodyCares, &processorInfo, &numProcessorInfo);
	if(err == KERN_SUCCESS) {
		for(unsigned i = 0U; i < numCPUs; ++i) {
			unsigned processorOffset = (CPU_STATE_MAX * i);
			//We only want the last $REFRESH_TIME seconds' worth of data, not all time.
			float inUse, total;
			if(lastProcessorInfo) {
				inUse = (
				  (processorInfo[processorOffset + CPU_STATE_USER]   - lastProcessorInfo[processorOffset + CPU_STATE_USER])
				+ (processorInfo[processorOffset + CPU_STATE_SYSTEM] - lastProcessorInfo[processorOffset + CPU_STATE_SYSTEM])
				+ (processorInfo[processorOffset + CPU_STATE_NICE]   - lastProcessorInfo[processorOffset + CPU_STATE_NICE])
				);
				total = inUse + (processorInfo[processorOffset + CPU_STATE_IDLE] - lastProcessorInfo[processorOffset + CPU_STATE_IDLE]);
			} else {
				inUse = processorInfo[processorOffset + CPU_STATE_USER] + processorInfo[processorOffset + CPU_STATE_SYSTEM] + processorInfo[processorOffset + CPU_STATE_NICE];
				total = inUse + processorInfo[processorOffset + CPU_STATE_IDLE];
			}

			CPUUsage[i] = inUse / total;
		}

		if(lastProcessorInfo) {
			size_t lastProcessorInfoSize = sizeof(integer_t) * numLastProcessorInfo;
			vm_deallocate(mach_task_self(), (vm_address_t)lastProcessorInfo, lastProcessorInfoSize);
		}

		lastProcessorInfo = processorInfo;
		numLastProcessorInfo = numProcessorInfo;

		processorInfo = NULL;
		numProcessorInfo = 0U;
	} else {
		NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
			NSLocalizedString(@"Could not get CPU load information", /*comment*/ nil), NSLocalizedDescriptionKey,
			[NSString stringWithFormat:NSLocalizedString(@"Error: %s (please tell the author)", /*comment*/ nil), mach_error_string(err)], NSLocalizedRecoverySuggestionErrorKey,
			nil];
		[NSApp presentError:[NSError errorWithDomain:NSMachErrorDomain code:err userInfo:dict]];
		[NSApp terminate:nil];
	}

	if (shouldDrawToDockIcon) {
		//OK, we actually do update the Dock views here. The selector is now a partial anachronism (only partial because we still don't update the floater views in this method).
		[[NSApp dockTile] display];
	}
}

#pragma mark Accessors

- (void) setFloaterZeroUsageTextColor:(NSColor *)newFloaterZeroUsageTextColor {
	if(floaterZeroUsageTextColor != newFloaterZeroUsageTextColor) {
		[floaterZeroUsageTextColor release];
		floaterZeroUsageTextColor = [newFloaterZeroUsageTextColor retain];

		[self setFloaterTextColorGradient:[[[NSGradient alloc] initWithStartingColor:floaterZeroUsageTextColor endingColor:floaterFullUsageTextColor] autorelease]];
	}
}

- (void) setFloaterFullUsageTextColor:(NSColor *)newFloaterFullUsageTextColor {
	if(floaterFullUsageTextColor != newFloaterFullUsageTextColor) {
		[floaterFullUsageTextColor release];
		floaterFullUsageTextColor = [newFloaterFullUsageTextColor retain];

		[self setFloaterTextColorGradient:[[[NSGradient alloc] initWithStartingColor:floaterZeroUsageTextColor endingColor:floaterFullUsageTextColor] autorelease]];
	}
}

- (void) setFloaterZeroUsageBackgroundColor:(NSColor *)newFloaterZeroUsageBackgroundColor {
	if(floaterZeroUsageBackgroundColor != newFloaterZeroUsageBackgroundColor) {
		[floaterZeroUsageBackgroundColor release];
		floaterZeroUsageBackgroundColor = [newFloaterZeroUsageBackgroundColor retain];

		[self setFloaterBackgroundColorGradient:[[[NSGradient alloc] initWithStartingColor:floaterZeroUsageBackgroundColor endingColor:floaterFullUsageBackgroundColor] autorelease]];
	}
}

- (void) setFloaterFullUsageBackgroundColor:(NSColor *)newFloaterFullUsageBackgroundColor {
	if(floaterFullUsageBackgroundColor != newFloaterFullUsageBackgroundColor) {
		[floaterFullUsageBackgroundColor release];
		floaterFullUsageBackgroundColor = [newFloaterFullUsageBackgroundColor retain];

		[self setFloaterBackgroundColorGradient:[[[NSGradient alloc] initWithStartingColor:floaterZeroUsageBackgroundColor endingColor:floaterFullUsageBackgroundColor] autorelease]];
	}
}

- (void) setDockIconZeroUsageTextColor:(NSColor *)newDockIconZeroUsageTextColor {
	if(dockIconZeroUsageTextColor != newDockIconZeroUsageTextColor) {
		[dockIconZeroUsageTextColor release];
		dockIconZeroUsageTextColor = [newDockIconZeroUsageTextColor retain];

		[self setDockIconTextColorGradient:[[[NSGradient alloc] initWithStartingColor:dockIconZeroUsageTextColor endingColor:dockIconFullUsageTextColor] autorelease]];
	}
}

- (void) setDockIconFullUsageTextColor:(NSColor *)newDockIconFullUsageTextColor {
	if(dockIconFullUsageTextColor != newDockIconFullUsageTextColor) {
		[dockIconFullUsageTextColor release];
		dockIconFullUsageTextColor = [newDockIconFullUsageTextColor retain];

		[self setDockIconTextColorGradient:[[[NSGradient alloc] initWithStartingColor:dockIconZeroUsageTextColor endingColor:dockIconFullUsageTextColor] autorelease]];
	}
}

- (void) setDockIconZeroUsageBackgroundColor:(NSColor *)newDockIconZeroUsageBackgroundColor {
	if(dockIconZeroUsageBackgroundColor != newDockIconZeroUsageBackgroundColor) {
		[dockIconZeroUsageBackgroundColor release];
		dockIconZeroUsageBackgroundColor = [newDockIconZeroUsageBackgroundColor retain];

		[self setDockIconBackgroundColorGradient:[[[NSGradient alloc] initWithStartingColor:dockIconZeroUsageBackgroundColor endingColor:dockIconFullUsageBackgroundColor] autorelease]];
	}
}

- (void) setDockIconFullUsageBackgroundColor:(NSColor *)newDockIconFullUsageBackgroundColor {
	if(dockIconFullUsageBackgroundColor != newDockIconFullUsageBackgroundColor) {
		[dockIconFullUsageBackgroundColor release];
		dockIconFullUsageBackgroundColor = [newDockIconFullUsageBackgroundColor retain];

		[self setDockIconBackgroundColorGradient:[[[NSGradient alloc] initWithStartingColor:dockIconZeroUsageBackgroundColor endingColor:dockIconFullUsageBackgroundColor] autorelease]];
	}
}

- (void) resizeWindow {
	if (window) {
		register float numCPUsFloat = numCPUs;
		float numViewsX, numViewsY;
		if (orientation == CPUUsageOrientationHorizontal) {
			numViewsX = numCPUs;
			numViewsY = 1.0f;
		} else if (orientation == CPUUsageOrientationVertical) {
			numViewsX = 1.0f;
			numViewsY = numCPUs;
		} else {
			numViewsX = ceilf(sqrtf(numCPUsFloat));
			numViewsY = ceilf(numCPUsFloat / numViewsX);
		}

		NSRect oldFrame = [window frame];
		NSRect newFrame = oldFrame;
		newFrame.size.width  = cellWidth  * numViewsX;
		newFrame.size.height = cellHeight * numViewsY;
		newFrame = [window fitProspectiveFrameOnScreen:newFrame];
//		[window setFrame:newFrame display:YES animate:YES]; //For some reason, this blocks dragging the window around. Lucky me — the NSViewAnimation is prettier.
		NSDictionary *animDict = [NSDictionary dictionaryWithObjectsAndKeys:
			window, NSViewAnimationTargetKey,
			[NSValue valueWithRect:oldFrame], NSViewAnimationStartFrameKey,
			[NSValue valueWithRect:newFrame], NSViewAnimationEndFrameKey,
			nil];
		NSViewAnimation *anim = [[[NSViewAnimation alloc] initWithViewAnimations:[NSArray arrayWithObject:animDict]] autorelease];
		[anim startAnimation];
	}
}

- (void)setCellWidth:(CGFloat)newCellWidth {
	cellWidth = newCellWidth;

	[self resizeWindow];
}
- (void)setCellHeight:(CGFloat)newCellHeight {
	cellHeight = newCellHeight;

	[self resizeWindow];
}

- (void)setShouldDrawToDockIcon:(BOOL)flag {
	shouldDrawToDockIcon = flag;

	NSDockTile *tile = [NSApp dockTile];
	[tile setContentView:shouldDrawToDockIcon ? dockIconUsageViewsContainingView : nil];
}

- (void)setShouldDrawToWindow:(BOOL)flag {
	shouldDrawToWindow = flag;

	if(shouldDrawToWindow)
		[window orderFront:nil];
	else
		[window orderOut:nil];
}

#pragma mark Gradient accessors

- (void) setFloaterTextColorGradient:(NSGradient *)newFloaterTextColorGradient {
	if(floaterTextColorGradient != newFloaterTextColorGradient) {
		[floaterTextColorGradient release];
		floaterTextColorGradient = [newFloaterTextColorGradient retain];
	}
}

- (void) setFloaterBackgroundColorGradient:(NSGradient *)newFloaterBackgroundColorGradient {
	if(floaterBackgroundColorGradient != newFloaterBackgroundColorGradient) {
		[floaterBackgroundColorGradient release];
		floaterBackgroundColorGradient = [newFloaterBackgroundColorGradient retain];
	}
}

- (void) setDockIconTextColorGradient:(NSGradient *)newDockIconTextColorGradient {
	if(dockIconTextColorGradient != newDockIconTextColorGradient) {
		[dockIconTextColorGradient release];
		dockIconTextColorGradient = [newDockIconTextColorGradient retain];
	}
}

- (void) setDockIconBackgroundColorGradient:(NSGradient *)newDockIconBackgroundColorGradient {
	if(dockIconBackgroundColorGradient != newDockIconBackgroundColorGradient) {
		[dockIconBackgroundColorGradient release];
		dockIconBackgroundColorGradient = [newDockIconBackgroundColorGradient retain];
	}
}

#pragma mark Actions

- (IBAction)setOrientationToVertical:sender {
	orientation = CPUUsageOrientationVertical;
	[[[NSUserDefaultsController sharedUserDefaultsController] values] setValue:[NSNumber numberWithInteger:orientation] forKey:FLOATER_ORIENTATION_PREF];

	[self layOutCellsInTarget:window];

	[verticalButton    setState:NSOnState];
	[horizontalButton  setState:NSOffState];
	[rectangularButton setState:NSOffState];
}
- (IBAction)setOrientationToHorizontal:sender {
	orientation = CPUUsageOrientationHorizontal;
	[[[NSUserDefaultsController sharedUserDefaultsController] values] setValue:[NSNumber numberWithInteger:orientation] forKey:FLOATER_ORIENTATION_PREF];

	[self layOutCellsInTarget:window];

	[verticalButton    setState:NSOffState];
	[horizontalButton  setState:NSOnState];
	[rectangularButton setState:NSOffState];
}
- (IBAction)setOrientationToRectangular:sender {
	orientation = CPUUsageOrientationRectangular;
	[[[NSUserDefaultsController sharedUserDefaultsController] values] setValue:[NSNumber numberWithInteger:orientation] forKey:FLOATER_ORIENTATION_PREF];

	[self layOutCellsInTarget:window];

	[verticalButton    setState:NSOffState];
	[horizontalButton  setState:NSOffState];
	[rectangularButton setState:NSOnState];
}

#pragma mark NSAnimation delegate conformance

//“Sent to the delegate when the specified animation completes its run.”
//—<http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSAnimation_Class/Reference/Reference.html#//apple_ref/occ/instm/NSObject/animationDidEnd:>
- (void)animationDidEnd:(NSAnimation *)animation {
	if (animation == windowResizeAnimation) {
		[windowResizeAnimation release];
		windowResizeAnimation = nil;
	}
}

#pragma mark Private methods

- (void)layOutCellsInTarget:(id)target {
	[windowResizeAnimation stopAnimation];
	[windowResizeAnimation release];

	//Number of animations = Number of CPU views + the window.
	NSMutableArray *animationDicts = [NSMutableArray arrayWithCapacity:numCPUs + 1U];

	//Each cell in the Dock icon is square, so this rectangle may not be square. Consider a dual-proc machine.
	//And of course, the floater is non-square in most configurations.
	/*numCPUs = 8
	 *+--+--+
	 *|1 | 2|
	 *+-+-+-+
	 *|3|4|5|
	 *+-+-+-+
	 *|6|7|8|
	 *+-+-+-+
	 */
	register float numCPUsFloat = numCPUs;
	float numViewsX, numViewsY;
	if((target == window) && (orientation == CPUUsageOrientationHorizontal)) {
		numViewsX = numCPUsFloat;
		numViewsY = 1.0f;
	} else if((target == window) && (orientation == CPUUsageOrientationVertical)) {
		numViewsX = 1.0f;
		numViewsY = numCPUsFloat;
	} else {
		numViewsX = ceilf(sqrtf(numCPUsFloat));
		numViewsY = ceilf(numCPUsFloat / numViewsX);
	}
	BOOL drawingToDock = (target == dockIconUsageViewsContainingView);

	NSSize cellSize;
	if(drawingToDock) {
		cellSize.width  = DOCK_ICON_SIZE / numViewsX;
		cellSize.height = DOCK_ICON_SIZE / numViewsY;
	} else {
		cellSize.width  = cellWidth;
		cellSize.height = cellHeight;
	}

	//Handle odd cells (1 and 2 above).
	//The number of cells missing from the row with the odd cells (in the example above, this = 1).
	float numCellsMissing = ((numViewsX * numViewsY) - numCPUsFloat);
	float numOddCellsFloat = numCellsMissing ? numViewsX - numCellsMissing : 0.0f;
	unsigned numOddCells = numOddCellsFloat;
	unsigned numNotOddCells = numCPUs - numOddCells;
	
	BZGridEnumerator *floaterOddCellsEnum = nil;
	BZGridEnumerator *floaterCellsEnum = [[BZGridEnumerator alloc] initWithCellSize:cellSize
																	numberOfColumns:numViewsX
																	   numberOfRows:numViewsY];
	NSRect frame = [floaterCellsEnum overallRect];
	if(numCellsMissing) {
		/*oddCellsWidth is the fraction of the total frame width used by odd cells.
		 *total = X*Y
		 *numEmptySpaces = total - numCPUs
		 *numOddCPUs = X - numEmptySpaces
		 *oddCellsWidth = numOddCPUs / X
		 */
		float oddCellsWidth = numOddCellsFloat / numViewsX;
		float oddCellWidth = oddCellsWidth / numOddCellsFloat;
		floaterOddCellsEnum = [[BZGridEnumerator alloc] initWithCellSize:(NSSize){ frame.size.width * oddCellWidth, cellSize.height }
																  offset:(NSPoint){ 0.0f, cellSize.height * numViewsY }
														 numberOfColumns:numOddCells
															numberOfRows:1U];
		frame.size.height += [floaterOddCellsEnum overallRect].size.height;
	}
	if (!drawingToDock) {
		NSAssert([target isKindOfClass:[NSWindow class]], @"Not drawing to dock but target is not a window?! target is: %@", target);
		NSRect origWindowFrame = [target frame];
		frame.origin = origWindowFrame.origin;
		[animationDicts addObject:[NSDictionary dictionaryWithObjectsAndKeys:
			target, NSViewAnimationTargetKey,
			[NSValue valueWithRect:origWindowFrame], NSViewAnimationStartFrameKey,
			[NSValue valueWithRect:frame],           NSViewAnimationEndFrameKey,
			//Only fade the window in if it's not already ordered in.
			([target isVisible] ? nil : NSViewAnimationFadeInEffect), NSViewAnimationEffectKey,
			nil]];
	}
	float offsetY = /*drawingToDock ? ((DOCK_ICON_SIZE - frame.size.height) * 0.5f) :*/ 0.0f;

	NSMutableArray *usageViewsArray = (target == window) ? usageViews : dockIconUsageViews;
	NSUInteger usageViewsArrayCount = [usageViewsArray count];

	//We need this information to set drawsFrame of every view to the correct value.
	//We don't need to retrieve it every time, so we get it once here and cache it in a variable.
	//The Dock icon window never has per-cell frames.
	BOOL shouldDrawFrame = [NSApp isActive] && (target == window);

	//Add CPU usage views.
	unsigned numCols = numViewsX, numRows = numViewsY;
	NSView *contentView = [target isKindOfClass:[NSWindow class]] ? [target contentView] : target;
	unsigned CPUNum = 0U;
	if(numCellsMissing) {
		NSAssert(floaterOddCellsEnum != nil, @"We need to draw %u odd cells (%f cells missing), but did not create an odd-cells enumerator", numOddCells, numCellsMissing);
		while(numOddCells--) {
			NSRect oddCellRect = [floaterOddCellsEnum nextRect];
			oddCellRect.origin.y += offsetY;

			CPUUsageView *usageView;
			if(CPUNum >= usageViewsArrayCount) {
				usageView = [[[CPUUsageView alloc] initWithFrame:oddCellRect] autorelease];
				[contentView addSubview:usageView];
				[usageViewsArray addObject:usageView];
				++usageViewsArrayCount;
			} else {
				usageView = [usageViewsArray objectAtIndex:CPUNum];
				[animationDicts addObject:[NSDictionary dictionaryWithObjectsAndKeys:
					usageView, NSViewAnimationTargetKey,
					[NSValue valueWithRect:[usageView frame]], NSViewAnimationStartFrameKey,
					[NSValue valueWithRect:oddCellRect],       NSViewAnimationEndFrameKey,
					nil]];
			}

			[usageView setDrawsFrame:shouldDrawFrame];
			[usageView setCPUUsage:8.88f]; //XXX TEMP - Should just not update the Dock icon until after all samples anyway
			if(numCPUs > 1)
				[usageView setCPUNumber:++CPUNum];

			[usageView bind:@"textColorGradient"
				   toObject:self
				withKeyPath:(target == window) ? @"floaterTextColorGradient" : @"dockIconTextColorGradient"
					options:nil];
			[usageView bind:@"backgroundColorGradient"
				   toObject:self
				withKeyPath:(target == window) ? @"floaterBackgroundColorGradient" : @"dockIconBackgroundColorGradient"
					options:nil];
			
			oddCellRect.origin.x += oddCellRect.size.width;
		}
	}
	while(numNotOddCells--) {
		frame = [floaterCellsEnum nextRect];
		frame.origin.y += offsetY;

		CPUUsageView *usageView;
		if(CPUNum >= usageViewsArrayCount) {
			usageView = [[[CPUUsageView alloc] initWithFrame:frame] autorelease];
			[contentView addSubview:usageView];
			[usageViewsArray addObject:usageView];
			++usageViewsArrayCount;
		} else {
			usageView = [usageViewsArray objectAtIndex:CPUNum];
			[animationDicts addObject:[NSDictionary dictionaryWithObjectsAndKeys:
				usageView, NSViewAnimationTargetKey,
				[NSValue valueWithRect:[usageView frame]], NSViewAnimationStartFrameKey,
				[NSValue valueWithRect:frame],             NSViewAnimationEndFrameKey,
				nil]];
		}
		NSUInteger mask = NSViewWidthSizable | NSViewHeightSizable
			| (numCols ? NSViewMinXMargin : 0U)
			| (numCols ? NSViewMaxXMargin : 0U)
			| (numRows ? NSViewMaxYMargin : 0U)
			| (numRows ? NSViewMinYMargin : 0U)
			;
		[usageView setAutoresizingMask:mask];
		[usageView setMenu:contextualMenu];

		[usageView setDrawsFrame:shouldDrawFrame];
		if(numCPUs > 1)
			[usageView setCPUNumber:++CPUNum];

		[usageView bind:@"textColorGradient"
			   toObject:self
			withKeyPath:(target == window) ? @"floaterTextColorGradient" : @"dockIconTextColorGradient"
				options:nil];
		[usageView bind:@"backgroundColorGradient"
			   toObject:self
			withKeyPath:(target == window) ? @"floaterBackgroundColorGradient" : @"dockIconBackgroundColorGradient"
				options:nil];
	}

	[floaterOddCellsEnum release];
	[floaterCellsEnum release];

	windowResizeAnimation = [[NSViewAnimation alloc] initWithViewAnimations:animationDicts];
	[windowResizeAnimation setDelegate:self];
	[windowResizeAnimation startAnimation];
}

@end