Simple RGB LED controller for Mac OS X
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppDelegate.m 48KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. //
  2. // AppDelegate.m
  3. // CaseLights
  4. //
  5. // Created by Thomas Buck on 21.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "Serial.h"
  10. #import "GPUStats.h"
  11. #import "Screenshot.h"
  12. #import "AudioVisualizer.h"
  13. // These are the values stored persistently in the preferences
  14. #define PREF_SERIAL_PORT @"SerialPort"
  15. #define PREF_LIGHTS_STATE @"LightState"
  16. // LED Mode contains the last selected mode as menu item text
  17. #define PREF_LED_MODE @"LEDMode"
  18. #define PREF_BRIGHTNESS @"Brightness"
  19. #define PREF_COLOR @"ManualColor"
  20. #define PREF_SENSITIVITY @"Sensitivity"
  21. #define PREF_COLORED_ICON @"ColorizeIcon"
  22. #define TEXT_MANUAL @"Select..."
  23. #define TEXT_CPU_USAGE @"CPU Usage"
  24. #define TEXT_RAM_USAGE @"RAM Usage"
  25. #define TEXT_GPU_USAGE @"GPU Usage"
  26. #define TEXT_VRAM_USAGE @"VRAM Usage"
  27. #define TEXT_CPU_TEMPERATURE @"CPU Temperature"
  28. #define TEXT_GPU_TEMPERATURE @"GPU Temperature"
  29. #define TEXT_RGB_FADE @"RGB Fade"
  30. #define TEXT_HSV_FADE @"HSV Fade"
  31. #define TEXT_RANDOM @"Random"
  32. #define TEXT_TEMPLATE_AUDIO @"AudioDevice_%@"
  33. // SMC keys are checked for existence and used for reading
  34. #define KEY_CPU_TEMPERATURE @"TC0D"
  35. #define KEY_GPU_TEMPERATURE @"TG0D"
  36. // Temperature in Celsius
  37. #define CPU_TEMP_MIN 20
  38. #define CPU_TEMP_MAX 90
  39. // HSV Color (S = V = 1)
  40. #define CPU_COLOR_MIN 120
  41. #define CPU_COLOR_MAX 0
  42. #define GPU_TEMP_MIN 20
  43. #define GPU_TEMP_MAX 90
  44. #define GPU_COLOR_MIN 120
  45. #define GPU_COLOR_MAX 0
  46. #define RAM_COLOR_MIN 0
  47. #define RAM_COLOR_MAX 120
  48. // You can play around with these values (skipped pixels, display timer delay) to change CPU usage in display mode
  49. #define AVERAGE_COLOR_PERFORMANCE_INC 10
  50. #define DISPLAY_DELAY 0.1
  51. // Used to identify selected menu items
  52. // displays are all tags >= 0
  53. #define MENU_ITEM_TAG_NOTHING -1
  54. #define MENU_ITEM_TAG_AUDIO -2
  55. @interface AppDelegate ()
  56. @property (weak) IBOutlet NSMenu *statusMenu;
  57. @property (weak) IBOutlet NSMenu *menuColors;
  58. @property (weak) IBOutlet NSMenu *menuAnimations;
  59. @property (weak) IBOutlet NSMenu *menuVisualizations;
  60. @property (weak) IBOutlet NSMenuItem *menuItemDisplays;
  61. @property (weak) IBOutlet NSMenu *menuDisplays;
  62. @property (weak) IBOutlet NSMenuItem *menuItemAudio;
  63. @property (weak) IBOutlet NSMenu *menuAudio;
  64. @property (weak) IBOutlet NSMenu *menuPorts;
  65. @property (weak) IBOutlet NSMenuItem *buttonOff;
  66. @property (weak) IBOutlet NSMenuItem *brightnessItem;
  67. @property (weak) IBOutlet NSSlider *brightnessSlider;
  68. @property (weak) IBOutlet NSMenuItem *brightnessLabel;
  69. @property (weak) IBOutlet NSMenuItem *buttonLights;
  70. @property (weak) IBOutlet NSMenuItem *sensitivityItem;
  71. @property (weak) IBOutlet NSSlider *sensitivitySlider;
  72. @property (weak) IBOutlet NSMenuItem *sensitivityLabel;
  73. @property (weak) IBOutlet NSMenuItem *sensitivityMenu;
  74. @property (weak) IBOutlet NSMenuItem *colorizeIconItem;
  75. @property (strong) NSMenuItem *menuItemColor;
  76. @property (strong) NSStatusItem *statusItem;
  77. @property (strong) NSImage *statusImage;
  78. @property (strong) NSDictionary *staticColors;
  79. @property (strong) NSTimer *animation;
  80. @property (strong) Serial *serial;
  81. @property (strong) NSMenuItem *lastLEDMode;
  82. @end
  83. @implementation AppDelegate
  84. @synthesize statusMenu, application;
  85. @synthesize menuColors, menuAnimations, menuVisualizations, menuPorts;
  86. @synthesize menuItemDisplays, menuDisplays;
  87. @synthesize menuItemAudio, menuAudio;
  88. @synthesize buttonOff, buttonLights;
  89. @synthesize brightnessItem, brightnessSlider, brightnessLabel;
  90. @synthesize sensitivityItem, sensitivitySlider, sensitivityLabel, sensitivityMenu;
  91. @synthesize statusItem, statusImage;
  92. @synthesize staticColors, animation;
  93. @synthesize serial, lastLEDMode, microphone;
  94. @synthesize menuItemColor, colorizeIconItem;
  95. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  96. srand((unsigned)time(NULL));
  97. [AudioVisualizer setDelegate:self];
  98. serial = [[Serial alloc] init];
  99. lastLEDMode = nil;
  100. animation = nil;
  101. microphone = nil;
  102. [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(darkModeChanged:) name:@"AppleInterfaceThemeChangedNotification" object:nil];
  103. // Set default configuration values, load existing ones
  104. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  105. NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObject:@"" forKey:PREF_SERIAL_PORT];
  106. [appDefaults setObject:[NSNumber numberWithBool:NO] forKey:PREF_LIGHTS_STATE];
  107. [appDefaults setObject:@"" forKey:PREF_LED_MODE];
  108. [appDefaults setObject:[NSNumber numberWithFloat:50.0] forKey:PREF_BRIGHTNESS];
  109. [appDefaults setObject:[NSNumber numberWithFloat:100.0] forKey:PREF_SENSITIVITY];
  110. [appDefaults setObject:[NSNumber numberWithBool:YES] forKey:PREF_COLORED_ICON];
  111. [store registerDefaults:appDefaults];
  112. [store synchronize];
  113. NSString *savedPort = [store stringForKey:PREF_SERIAL_PORT];
  114. BOOL turnOnLights = [store boolForKey:PREF_LIGHTS_STATE];
  115. NSString *lastMode = [store stringForKey:PREF_LED_MODE];
  116. float brightness = [store floatForKey:PREF_BRIGHTNESS];
  117. NSData *lastColorData = [store dataForKey:PREF_COLOR];
  118. float sensitivity = [store floatForKey:PREF_SENSITIVITY];
  119. NSColor *lastColor = nil;
  120. if (lastColorData != nil) {
  121. lastColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:lastColorData];
  122. }
  123. BOOL coloredIcon = [store boolForKey:PREF_COLORED_ICON];
  124. // Prepare status bar menu
  125. statusImage = [NSImage imageNamed:@"MenuIcon"];
  126. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  127. if (coloredIcon == YES) {
  128. [statusImage setTemplate:NO];
  129. [statusItem setImage:[AppDelegate tintedImage:statusImage WithColor:[NSColor colorWithCalibratedRed:0.0f green:0.0f blue:0.0f alpha:1.0f]]];
  130. [colorizeIconItem setState:NSOnState];
  131. } else {
  132. [statusImage setTemplate:YES];
  133. [statusItem setImage:statusImage];
  134. [colorizeIconItem setState:NSOffState];
  135. }
  136. [statusItem setMenu:statusMenu];
  137. // Prepare brightness menu
  138. brightnessItem.view = brightnessSlider;
  139. [brightnessSlider setFloatValue:brightness];
  140. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", brightness]];
  141. // Prepare serial port menu
  142. NSArray *ports = [Serial listSerialPorts];
  143. if ([ports count] > 0) {
  144. [menuPorts removeAllItems];
  145. for (int i = 0; i < [ports count]; i++) {
  146. // Add Menu Item for this port
  147. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  148. [item setTag:MENU_ITEM_TAG_NOTHING];
  149. [menuPorts addItem:item];
  150. // Set Enabled if it was used the last time
  151. if ((savedPort != nil) && [[ports objectAtIndex:i] isEqualToString:savedPort]) {
  152. [[menuPorts itemAtIndex:i] setState:NSOnState];
  153. // Try to open serial port
  154. [serial setPortName:savedPort];
  155. if ([serial openPort]) {
  156. // Unselect it when an error occured opening the port
  157. [[menuPorts itemAtIndex:i] setState:NSOffState];
  158. }
  159. }
  160. }
  161. }
  162. // Select "Off" button if it was last selected
  163. if ([lastMode isEqualToString:@""]) {
  164. [buttonOff setState:NSOffState];
  165. [self turnLEDsOff:buttonOff];
  166. }
  167. // Prepare static colors menu
  168. staticColors = [NSDictionary dictionaryWithObjectsAndKeys:
  169. [NSColor colorWithCalibratedRed:1.0f green:0.0f blue:0.0f alpha:0.0f], @"Red",
  170. [NSColor colorWithCalibratedRed:0.0f green:1.0f blue:0.0f alpha:0.0f], @"Green",
  171. [NSColor colorWithCalibratedRed:0.0f green:0.0f blue:1.0f alpha:0.0f], @"Blue",
  172. [NSColor colorWithCalibratedRed:0.0f green:1.0f blue:1.0f alpha:0.0f], @"Cyan",
  173. [NSColor colorWithCalibratedRed:1.0f green:0.0f blue:1.0f alpha:0.0f], @"Magenta",
  174. [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:0.0f alpha:0.0f], @"Yellow",
  175. [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:1.0f alpha:0.0f], @"White",
  176. nil];
  177. for (NSString *key in [staticColors allKeys]) {
  178. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:key action:@selector(selectedVisualization:) keyEquivalent:@""];
  179. [item setTag:MENU_ITEM_TAG_NOTHING];
  180. if ([key isEqualToString:lastMode]) {
  181. [self selectedVisualization:item];
  182. }
  183. [menuColors addItem:item];
  184. }
  185. menuItemColor = [[NSMenuItem alloc] initWithTitle:TEXT_MANUAL action:@selector(setColorSelected:) keyEquivalent:@""];
  186. if ([lastMode isEqualToString:TEXT_MANUAL]) {
  187. if (lastColor != nil) {
  188. // Restore previously set RGB color
  189. [self setLightsColor:lastColor];
  190. }
  191. [menuItemColor setState:NSOnState];
  192. }
  193. [menuItemColor setTag:MENU_ITEM_TAG_NOTHING];
  194. [menuColors addItem:menuItemColor];
  195. // Prepare animations menu
  196. NSArray *animationStrings = [NSArray arrayWithObjects:
  197. TEXT_RGB_FADE,
  198. TEXT_HSV_FADE,
  199. TEXT_RANDOM,
  200. nil];
  201. for (NSString *key in animationStrings) {
  202. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:key action:@selector(selectedVisualization:) keyEquivalent:@""];
  203. [item setTag:MENU_ITEM_TAG_NOTHING];
  204. if ([key isEqualToString:lastMode]) {
  205. [self selectedVisualization:item];
  206. }
  207. [menuAnimations addItem:item];
  208. }
  209. // Add CPU Usage menu item
  210. NSMenuItem *cpuUsageItem = [[NSMenuItem alloc] initWithTitle:TEXT_CPU_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  211. [cpuUsageItem setTag:MENU_ITEM_TAG_NOTHING];
  212. if ([lastMode isEqualToString:TEXT_CPU_USAGE]) {
  213. [self selectedVisualization:cpuUsageItem];
  214. }
  215. [menuVisualizations addItem:cpuUsageItem];
  216. // Add Memory Usage item
  217. NSMenuItem *memoryUsageItem = [[NSMenuItem alloc] initWithTitle:TEXT_RAM_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  218. [memoryUsageItem setTag:MENU_ITEM_TAG_NOTHING];
  219. if ([lastMode isEqualToString:TEXT_RAM_USAGE]) {
  220. [self selectedVisualization:memoryUsageItem];
  221. }
  222. [menuVisualizations addItem:memoryUsageItem];
  223. // Check if GPU Stats are available, add menu items if so
  224. NSNumber *usage;
  225. NSNumber *freeVRAM;
  226. NSNumber *usedVRAM;
  227. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  228. NSLog(@"Error reading GPU information\n");
  229. } else {
  230. NSMenuItem *itemUsage = [[NSMenuItem alloc] initWithTitle:TEXT_GPU_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  231. [itemUsage setTag:MENU_ITEM_TAG_NOTHING];
  232. if ([lastMode isEqualToString:TEXT_GPU_USAGE]) {
  233. [self selectedVisualization:itemUsage];
  234. }
  235. [menuVisualizations addItem:itemUsage];
  236. NSMenuItem *itemVRAM = [[NSMenuItem alloc] initWithTitle:TEXT_VRAM_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  237. [itemVRAM setTag:MENU_ITEM_TAG_NOTHING];
  238. if ([lastMode isEqualToString:TEXT_VRAM_USAGE]) {
  239. [self selectedVisualization:itemVRAM];
  240. }
  241. [menuVisualizations addItem:itemVRAM];
  242. }
  243. // Check available temperatures and add menu items
  244. JSKSMC *smc = [JSKSMC smc];
  245. for (int i = 0; i < [[smc workingTempKeys] count]; i++) {
  246. NSString *key = [smc.workingTempKeys objectAtIndex:i];
  247. #ifdef DEBUG
  248. NSString *name = [smc humanReadableNameForKey:key];
  249. NSLog(@"Sensor \"%@\": \"%@\"\n", key, name);
  250. #endif
  251. if ([key isEqualToString:KEY_CPU_TEMPERATURE]) {
  252. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:TEXT_CPU_TEMPERATURE action:@selector(selectedVisualization:) keyEquivalent:@""];
  253. [item setTag:MENU_ITEM_TAG_NOTHING];
  254. if ([lastMode isEqualToString:TEXT_CPU_TEMPERATURE]) {
  255. [self selectedVisualization:item];
  256. }
  257. [menuVisualizations addItem:item];
  258. }
  259. if ([key isEqualToString:KEY_GPU_TEMPERATURE]) {
  260. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:TEXT_GPU_TEMPERATURE action:@selector(selectedVisualization:) keyEquivalent:@""];
  261. [item setTag:MENU_ITEM_TAG_NOTHING];
  262. if ([lastMode isEqualToString:TEXT_GPU_TEMPERATURE]) {
  263. [self selectedVisualization:item];
  264. }
  265. [menuVisualizations addItem:item];
  266. }
  267. }
  268. // Restore previously used lights configuration
  269. if (turnOnLights) {
  270. // Turn on lights
  271. if ([serial isOpen]) {
  272. [serial sendString:@"UV 1\n"];
  273. }
  274. [buttonLights setState:NSOnState];
  275. } else {
  276. // Turn off lights
  277. if ([serial isOpen]) {
  278. [serial sendString:@"UV 0\n"];
  279. }
  280. }
  281. // List available displays and add menu items
  282. [Screenshot init:self];
  283. NSArray *displayIDs = [Screenshot listDisplays];
  284. [self updateDisplayUI:displayIDs];
  285. // List available audio input devices and add menu items
  286. NSArray *inputDevices = [EZAudioDevice inputDevices];
  287. [menuAudio removeAllItems];
  288. for (int i = 0; i < [inputDevices count]; i++) {
  289. EZAudioDevice *dev = [inputDevices objectAtIndex:i];
  290. #ifdef DEBUG
  291. NSLog(@"Audio input device: \"%@\"\n", [dev name]);
  292. #endif
  293. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[dev name] action:@selector(selectedVisualization:) keyEquivalent:@""];
  294. [item setTag:MENU_ITEM_TAG_AUDIO];
  295. NSString *lastModeString = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [dev name]];
  296. if ([lastModeString isEqualToString:lastMode]) {
  297. [self selectedVisualization:item];
  298. }
  299. [menuAudio addItem:item];
  300. }
  301. if ([inputDevices count] > 0) {
  302. [menuItemAudio setHidden:NO];
  303. // Prepare sensitivity menu
  304. sensitivityItem.view = sensitivitySlider;
  305. [sensitivitySlider setFloatValue:sensitivity];
  306. [sensitivityLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", sensitivity]];
  307. [sensitivityMenu setHidden:NO];
  308. [AudioVisualizer setSensitivity:sensitivity];
  309. }
  310. }
  311. - (void)applicationWillTerminate:(NSNotification *)aNotification {
  312. // Stop previous timer setting
  313. if (animation != nil) {
  314. [animation invalidate];
  315. animation = nil;
  316. }
  317. // Stop previous audio data retrieval
  318. if (microphone != nil) {
  319. [microphone setMicrophoneOn:NO];
  320. }
  321. // Remove display callback
  322. [Screenshot close:self];
  323. // Turn off all lights if possible
  324. if ([serial isOpen]) {
  325. [serial sendString:@"RGB 0 0 0\n"];
  326. [serial sendString:@"UV 0\n"];
  327. [serial closePort];
  328. }
  329. }
  330. - (void)clearDisplayUI {
  331. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  332. if ([[menuDisplays itemAtIndex:i] isEnabled] == YES) {
  333. // A display configuration is currently selected. Disable the timer
  334. if (animation != nil) {
  335. [animation invalidate];
  336. animation = nil;
  337. }
  338. }
  339. }
  340. [menuDisplays removeAllItems];
  341. [menuItemDisplays setHidden:YES];
  342. }
  343. - (void)updateDisplayUI:(NSArray *)displayIDs {
  344. if ([displayIDs count] > 0) {
  345. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  346. NSString *lastMode = [store stringForKey:PREF_LED_MODE];
  347. [menuItemDisplays setHidden:NO];
  348. for (int i = 0; i < [displayIDs count]; i++) {
  349. NSString *title = [Screenshot displayNameFromDisplayID:[displayIDs objectAtIndex:i]];
  350. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title
  351. action:@selector(selectedVisualization:)
  352. keyEquivalent:@""];
  353. [item setTag:[[displayIDs objectAtIndex:i] integerValue]];
  354. if ([title isEqualToString:lastMode]) {
  355. [self selectedVisualization:item];
  356. }
  357. [menuDisplays addItem:item];
  358. }
  359. }
  360. }
  361. - (void)setLightsColor:(NSColor *)color {
  362. CGFloat red, green, blue, alpha;
  363. [color getRed:&red green:&green blue:&blue alpha:&alpha];
  364. [self setLightsR:red * 255 G:green * 255 B:blue * 255];
  365. // Stop previous timer setting
  366. if (animation != nil) {
  367. [animation invalidate];
  368. animation = nil;
  369. }
  370. // Stop previous audio data retrieval
  371. if (microphone != nil) {
  372. [microphone setMicrophoneOn:NO];
  373. }
  374. // Turn off all other LED menu items
  375. if (menuColors != nil) {
  376. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  377. [[menuColors itemAtIndex:i] setState:NSOffState];
  378. }
  379. }
  380. if (menuAnimations != nil) {
  381. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  382. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  383. }
  384. }
  385. if (menuVisualizations != nil) {
  386. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  387. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  388. }
  389. }
  390. if (menuAudio != nil) {
  391. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  392. [[menuAudio itemAtIndex:i] setState:NSOffState];
  393. }
  394. }
  395. if (menuDisplays != nil) {
  396. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  397. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  398. }
  399. }
  400. [buttonOff setState:NSOffState];
  401. [menuItemColor setState:NSOnState];
  402. // Store new manually selected color
  403. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  404. NSData *data = [NSArchiver archivedDataWithRootObject:color];
  405. [store setObject:data forKey:PREF_COLOR];
  406. [store setObject:TEXT_MANUAL forKey:PREF_LED_MODE];
  407. [store synchronize];
  408. }
  409. - (void)setLightsR:(unsigned char)r G:(unsigned char)g B:(unsigned char)b {
  410. if ([serial isOpen]) {
  411. unsigned char red = r * ([brightnessSlider floatValue] / 100.0);
  412. unsigned char green = g * ([brightnessSlider floatValue] / 100.0);
  413. unsigned char blue = b * ([brightnessSlider floatValue] / 100.0);
  414. [serial sendString:[NSString stringWithFormat:@"RGB %d %d %d\n", red, green, blue]];
  415. } else {
  416. #ifdef DEBUG
  417. NSLog(@"Trying to send RGB without opened port!\n");
  418. #endif
  419. }
  420. if (colorizeIconItem.state == NSOnState) {
  421. [statusItem setImage:[AppDelegate tintedImage:statusImage WithColor:[NSColor colorWithCalibratedRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f]]];
  422. }
  423. }
  424. - (IBAction)colorizeIconSelected:(NSMenuItem *)sender {
  425. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  426. if ([sender state] == NSOffState) {
  427. // Colorize icon
  428. [statusImage setTemplate:NO];
  429. [statusItem setImage:[AppDelegate tintedImage:statusImage WithColor:[NSColor colorWithCalibratedRed:0.0f green:0.0f blue:0.0f alpha:1.0f]]];
  430. [colorizeIconItem setState:NSOnState];
  431. [store setObject:[NSNumber numberWithBool:YES] forKey:PREF_COLORED_ICON];
  432. } else {
  433. // Don't colorize icon
  434. [statusImage setTemplate:YES];
  435. [statusItem setImage:statusImage];
  436. [colorizeIconItem setState:NSOffState];
  437. [store setObject:[NSNumber numberWithBool:NO] forKey:PREF_COLORED_ICON];
  438. }
  439. [store synchronize];
  440. }
  441. - (IBAction)relistSerialPorts:(id)sender {
  442. // Refill audio device list
  443. NSArray *inputDevices = [EZAudioDevice inputDevices];
  444. [menuAudio removeAllItems];
  445. for (int i = 0; i < [inputDevices count]; i++) {
  446. EZAudioDevice *dev = [inputDevices objectAtIndex:i];
  447. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[dev name] action:@selector(selectedVisualization:) keyEquivalent:@""];
  448. [item setTag:MENU_ITEM_TAG_AUDIO];
  449. NSString *lastModeString = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [dev name]];
  450. if ([lastModeString isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:PREF_LED_MODE]]) {
  451. [self selectedVisualization:item];
  452. }
  453. [menuAudio addItem:item];
  454. }
  455. if ([inputDevices count] > 0) {
  456. [menuItemAudio setHidden:NO];
  457. } else {
  458. [menuItemAudio setHidden:YES];
  459. }
  460. // Refill port list
  461. NSArray *ports = [Serial listSerialPorts];
  462. [menuPorts removeAllItems];
  463. for (int i = 0; i < [ports count]; i++) {
  464. // Add Menu Item for this port
  465. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  466. [item setTag:MENU_ITEM_TAG_NOTHING];
  467. [menuPorts addItem:item];
  468. // Mark it if it is currently open
  469. if ([serial isOpen]) {
  470. if ([[ports objectAtIndex:i] isEqualToString:[serial portName]]) {
  471. [[menuPorts itemAtIndex:i] setState:NSOnState];
  472. }
  473. }
  474. }
  475. }
  476. - (void)setColorSelected:(NSMenuItem *)sender {
  477. NSColorPanel *cp = [NSColorPanel sharedColorPanel];
  478. [cp setTarget:self];
  479. [cp setAction:@selector(colorSelected:)];
  480. [cp setShowsAlpha:NO];
  481. [cp setContinuous:NO];
  482. [cp setMode:NSRGBModeColorPanel];
  483. // Try to restore last manually selected color
  484. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  485. NSData *lastColorData = [store dataForKey:PREF_COLOR];
  486. NSColor *lastColor = nil;
  487. if (lastColorData != nil) {
  488. lastColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:lastColorData];
  489. [cp setColor:lastColor];
  490. }
  491. [NSApp activateIgnoringOtherApps:YES];
  492. [application orderFrontColorPanel:cp];
  493. }
  494. - (void)colorSelected:(NSColorPanel *)sender {
  495. [self setLightsColor:[sender color]];
  496. }
  497. - (IBAction)sensitivityMoved:(NSSlider *)sender {
  498. [sensitivityLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", [sender floatValue]]];
  499. [AudioVisualizer setSensitivity:[sender floatValue]];
  500. // Store changed value in preferences
  501. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  502. [store setObject:[NSNumber numberWithFloat:[sender floatValue]] forKey:PREF_SENSITIVITY];
  503. [store synchronize];
  504. }
  505. - (IBAction)brightnessMoved:(NSSlider *)sender {
  506. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", [sender floatValue]]];
  507. // Restore the current configuration for items where it won't happen automatically
  508. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  509. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  510. [self selectedVisualization:[menuColors itemAtIndex:i]];
  511. }
  512. }
  513. // Store changed value in preferences
  514. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  515. [store setObject:[NSNumber numberWithFloat:[sender floatValue]] forKey:PREF_BRIGHTNESS];
  516. [store synchronize];
  517. }
  518. - (IBAction)turnLEDsOff:(NSMenuItem *)sender {
  519. if ([sender state] == NSOffState) {
  520. lastLEDMode = nil;
  521. // Stop previous timer setting
  522. if (animation != nil) {
  523. [animation invalidate];
  524. animation = nil;
  525. }
  526. // Stop previous audio data retrieval
  527. if (microphone != nil) {
  528. [microphone setMicrophoneOn:NO];
  529. }
  530. // Turn off all other LED menu items
  531. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  532. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  533. lastLEDMode = [menuColors itemAtIndex:i];
  534. }
  535. [[menuColors itemAtIndex:i] setState:NSOffState];
  536. }
  537. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  538. if ([[menuAnimations itemAtIndex:i] state] == NSOnState) {
  539. lastLEDMode = [menuAnimations itemAtIndex:i];
  540. }
  541. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  542. }
  543. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  544. if ([[menuVisualizations itemAtIndex:i] state] == NSOnState) {
  545. lastLEDMode = [menuVisualizations itemAtIndex:i];
  546. }
  547. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  548. }
  549. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  550. if ([[menuAudio itemAtIndex:i] state] == NSOnState) {
  551. lastLEDMode = [menuAudio itemAtIndex:i];
  552. }
  553. [[menuAudio itemAtIndex:i] setState:NSOffState];
  554. }
  555. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  556. if ([[menuDisplays itemAtIndex:i] state] == NSOnState) {
  557. lastLEDMode = [menuDisplays itemAtIndex:i];
  558. }
  559. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  560. }
  561. // Turn on "off" menu item
  562. [sender setState:NSOnState];
  563. // Store changed value in preferences
  564. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  565. [store setObject:@"" forKey:PREF_LED_MODE];
  566. [store synchronize];
  567. #ifdef DEBUG
  568. NSLog(@"Stored new mode: \"off\"!\n");
  569. #endif
  570. // Send command to turn off LEDs
  571. [self setLightsR:0 G:0 B:0];
  572. } else {
  573. // Try to restore last LED setting
  574. if (lastLEDMode != nil) {
  575. [self selectedVisualization:lastLEDMode];
  576. }
  577. }
  578. }
  579. - (IBAction)toggleLights:(NSMenuItem *)sender {
  580. if ([sender state] == NSOffState) {
  581. // Turn on lights
  582. if ([serial isOpen]) {
  583. [serial sendString:@"UV 1\n"];
  584. }
  585. [sender setState:NSOnState];
  586. } else {
  587. // Turn off lights
  588. if ([serial isOpen]) {
  589. [serial sendString:@"UV 0\n"];
  590. }
  591. [sender setState:NSOffState];
  592. }
  593. // Store changed value in preferences
  594. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  595. [store setBool:([sender state] == NSOnState) forKey:PREF_LIGHTS_STATE];
  596. [store synchronize];
  597. }
  598. - (BOOL)timedVisualization:(NSString *)mode {
  599. // Stop previous timer setting
  600. if (animation != nil) {
  601. [animation invalidate];
  602. animation = nil;
  603. }
  604. // Stop previous audio data retrieval
  605. if (microphone != nil) {
  606. [microphone setMicrophoneOn:NO];
  607. }
  608. // Schedule next invocation for this animation...
  609. if ([mode isEqualToString:TEXT_GPU_USAGE]) {
  610. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeGPUUsage:) userInfo:mode repeats:YES];
  611. } else if ([mode isEqualToString:TEXT_VRAM_USAGE]) {
  612. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeVRAMUsage:) userInfo:mode repeats:YES];
  613. } else if ([mode isEqualToString:TEXT_CPU_USAGE]) {
  614. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeCPUUsage:) userInfo:mode repeats:YES];
  615. } else if ([mode isEqualToString:TEXT_RAM_USAGE]) {
  616. animation = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(visualizeRAMUsage:) userInfo:mode repeats:YES];
  617. } else if ([mode isEqualToString:TEXT_CPU_TEMPERATURE]) {
  618. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeCPUTemperature:) userInfo:mode repeats:YES];
  619. } else if ([mode isEqualToString:TEXT_GPU_TEMPERATURE]) {
  620. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeGPUTemperature:) userInfo:mode repeats:YES];
  621. } else if ([mode isEqualToString:TEXT_RGB_FADE]) {
  622. animation = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(visualizeRGBFade:) userInfo:mode repeats:YES];
  623. } else if ([mode isEqualToString:TEXT_HSV_FADE]) {
  624. animation = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(visualizeHSVFade:) userInfo:mode repeats:YES];
  625. } else if ([mode isEqualToString:TEXT_RANDOM]) {
  626. animation = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(visualizeRandom:) userInfo:mode repeats:YES];
  627. } else {
  628. return NO;
  629. }
  630. #ifdef DEBUG
  631. NSLog(@"Scheduled animation for \"%@\"!\n", mode);
  632. #endif
  633. // ...and also execute it right now
  634. [animation fire];
  635. return YES;
  636. }
  637. - (void)displayVisualization:(NSMenuItem *)sender {
  638. // Stop previous timer setting
  639. if (animation != nil) {
  640. [animation invalidate];
  641. animation = nil;
  642. }
  643. // Stop previous audio data retrieval
  644. if (microphone != nil) {
  645. [microphone setMicrophoneOn:NO];
  646. }
  647. // Schedule next invocation for this animation...
  648. animation = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:[NSNumber numberWithInteger:[sender tag]] repeats:YES];
  649. // ...and also execute it right now
  650. [animation fire];
  651. }
  652. - (void)selectedVisualization:(NSMenuItem *)sender {
  653. // Turn off all other LED menu items
  654. if (menuColors != nil) {
  655. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  656. [[menuColors itemAtIndex:i] setState:NSOffState];
  657. }
  658. }
  659. if (menuAnimations != nil) {
  660. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  661. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  662. }
  663. }
  664. if (menuVisualizations != nil) {
  665. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  666. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  667. }
  668. }
  669. if (menuAudio != nil) {
  670. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  671. [[menuAudio itemAtIndex:i] setState:NSOffState];
  672. }
  673. }
  674. if (menuDisplays != nil) {
  675. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  676. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  677. }
  678. }
  679. [buttonOff setState:NSOffState];
  680. [sender setState:NSOnState];
  681. // Check if it is a display
  682. BOOL found = NO;
  683. if ([sender tag] > MENU_ITEM_TAG_NOTHING) {
  684. found = YES;
  685. [self displayVisualization:sender];
  686. }
  687. // Check if it is an audio input device
  688. if ((found == NO) && ([sender tag] == MENU_ITEM_TAG_AUDIO)) {
  689. // Stop previous timer setting
  690. if (animation != nil) {
  691. [animation invalidate];
  692. animation = nil;
  693. }
  694. found = YES;
  695. BOOL foundDev = NO;
  696. NSArray *audioDevices = [EZAudioDevice inputDevices];
  697. for (int i = 0; i < [audioDevices count]; i++) {
  698. EZAudioDevice *dev = [audioDevices objectAtIndex:i];
  699. if ([[dev name] isEqualToString:[sender title]]) {
  700. // Send command to turn off LEDs
  701. [self setLightsR:0 G:0 B:0];
  702. // Found device
  703. foundDev = YES;
  704. if (microphone != nil) {
  705. [microphone setMicrophoneOn:NO];
  706. } else {
  707. microphone = [EZMicrophone microphoneWithDelegate:self];
  708. }
  709. [microphone setDevice:dev];
  710. [microphone setMicrophoneOn:YES];
  711. break;
  712. }
  713. }
  714. if (foundDev == NO) {
  715. NSLog(@"Couldn't find device \"%@\"\n", [sender title]);
  716. [sender setState:NSOffState];
  717. // List available audio input devices and add menu items
  718. NSArray *inputDevices = [EZAudioDevice inputDevices];
  719. [menuAudio removeAllItems];
  720. for (int i = 0; i < [inputDevices count]; i++) {
  721. EZAudioDevice *dev = [inputDevices objectAtIndex:i];
  722. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[dev name] action:@selector(selectedVisualization:) keyEquivalent:@""];
  723. [item setTag:MENU_ITEM_TAG_AUDIO];
  724. if ([[dev name] isEqualToString:[sender title]]) {
  725. // Found the device the user really wanted
  726. [self selectedVisualization:item];
  727. }
  728. [menuAudio addItem:item];
  729. }
  730. return; // Don't store new mode
  731. }
  732. }
  733. // Check if it is the manual color select item
  734. if ((found == NO) && ([sender.title isEqualToString:TEXT_MANUAL])) {
  735. found = YES;
  736. [self colorSelected:[NSColorPanel sharedColorPanel]];
  737. }
  738. // Check if a static color was selected
  739. if ((found == NO) && (staticColors != nil)) {
  740. for (NSString *key in [staticColors allKeys]) {
  741. if ([sender.title isEqualToString:key]) {
  742. found = YES;
  743. // Stop previous timer setting
  744. if (animation != nil) {
  745. [animation invalidate];
  746. animation = nil;
  747. }
  748. // Stop previous audio data retrieval
  749. if (microphone != nil) {
  750. [microphone setMicrophoneOn:NO];
  751. }
  752. NSColor *color = [staticColors valueForKey:key];
  753. unsigned char red = [color redComponent] * 255;
  754. unsigned char green = [color greenComponent] * 255;
  755. unsigned char blue = [color blueComponent] * 255;
  756. [self setLightsR:red G:green B:blue];
  757. break;
  758. }
  759. }
  760. }
  761. if (found == NO) {
  762. // Check if an animated visualization was selected
  763. if ([self timedVisualization:[sender title]] == NO) {
  764. NSLog(@"Unknown LED Visualization selected!\n");
  765. return;
  766. }
  767. }
  768. // Store changed value in preferences
  769. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  770. if ([sender tag] == MENU_ITEM_TAG_AUDIO) {
  771. // Prepend text for audio device names
  772. NSString *tmp = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [sender title]];
  773. [store setObject:tmp forKey:PREF_LED_MODE];
  774. } else {
  775. [store setObject:[sender title] forKey:PREF_LED_MODE];
  776. }
  777. [store synchronize];
  778. #ifdef DEBUG
  779. NSLog(@"Stored new mode: \"%@\"!\n", [sender title]);
  780. #endif
  781. }
  782. - (void)selectedSerialPort:(NSMenuItem *)source {
  783. // Store selection for next start-up
  784. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  785. [store setObject:[source title] forKey:PREF_SERIAL_PORT];
  786. [store synchronize];
  787. // De-select all other ports
  788. for (int i = 0; i < [menuPorts numberOfItems]; i++) {
  789. [[menuPorts itemAtIndex:i] setState:NSOffState];
  790. }
  791. // Select only the current port
  792. [source setState:NSOnState];
  793. // Close previously opened port, if any
  794. if ([serial isOpen]) {
  795. [serial closePort];
  796. }
  797. // Try to open selected port
  798. [serial setPortName:[source title]];
  799. if ([serial openPort] != 0) {
  800. [source setState:NSOffState];
  801. } else {
  802. // Restore the current configuration
  803. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  804. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  805. [self selectedVisualization:[menuColors itemAtIndex:i]];
  806. }
  807. }
  808. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  809. if ([[menuAnimations itemAtIndex:i] state] == NSOnState) {
  810. [self selectedVisualization:[menuAnimations itemAtIndex:i]];
  811. }
  812. }
  813. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  814. if ([[menuVisualizations itemAtIndex:i] state] == NSOnState) {
  815. [self selectedVisualization:[menuVisualizations itemAtIndex:i]];
  816. }
  817. }
  818. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  819. if ([[menuAudio itemAtIndex:i] state] == NSOnState) {
  820. [self selectedVisualization:[menuAudio itemAtIndex:i]];
  821. }
  822. }
  823. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  824. if ([[menuDisplays itemAtIndex:i] state] == NSOnState) {
  825. [self selectedVisualization:[menuDisplays itemAtIndex:i]];
  826. }
  827. }
  828. if ([buttonOff state] == NSOnState) {
  829. [buttonOff setState:NSOffState];
  830. [self turnLEDsOff:buttonOff];
  831. }
  832. if ([buttonLights state] == NSOnState) {
  833. [serial sendString:@"UV 1\n"];
  834. } else {
  835. [serial sendString:@"UV 0\n"];
  836. }
  837. }
  838. }
  839. - (IBAction)showAbout:(id)sender {
  840. [NSApp activateIgnoringOtherApps:YES];
  841. [application orderFrontStandardAboutPanel:self];
  842. }
  843. - (void)darkModeChanged:(NSNotification *)notification {
  844. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  845. BOOL colorize = [store boolForKey:PREF_COLORED_ICON];
  846. if (colorize == YES) {
  847. [statusItem setImage:[AppDelegate tintedImage:statusImage WithColor:nil]];
  848. }
  849. }
  850. // ------------------------------------------------------
  851. // ----------------- Microphone Delegate ----------------
  852. // ------------------------------------------------------
  853. - (void)microphone:(EZMicrophone *)microphone hasAudioReceived:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels {
  854. __weak typeof (self) weakSelf = self;
  855. // Getting audio data as an array of float buffer arrays that can be fed into the
  856. // EZAudioPlot, EZAudioPlotGL, or whatever visualization you would like to do with
  857. // the microphone data.
  858. dispatch_async(dispatch_get_main_queue(),^{
  859. if (weakSelf.microphone.microphoneOn == NO) {
  860. return;
  861. }
  862. // buffer[0] = left channel, buffer[1] = right channel
  863. [AudioVisualizer updateBuffer:buffer[0] withBufferSize:bufferSize];
  864. });
  865. }
  866. - (void)microphone:(EZMicrophone *)microphone changedDevice:(EZAudioDevice *)device {
  867. dispatch_async(dispatch_get_main_queue(), ^{
  868. NSLog(@"Changed audio input device: %@", [device name]);
  869. });
  870. }
  871. // ------------------------------------------------------
  872. // ------------------- Visualizations -------------------
  873. // ------------------------------------------------------
  874. - (void)visualizeDisplay:(NSTimer *)timer {
  875. NSBitmapImageRep *screen = [Screenshot screenshot:[timer userInfo]];
  876. NSInteger spp = [screen samplesPerPixel];
  877. if (((spp != 3) && (spp != 4)) || ([screen isPlanar] == YES) || ([screen numberOfPlanes] != 1)) {
  878. NSLog(@"Unknown image format (%ld, %c, %ld)!\n", (long)spp, ([screen isPlanar] == YES) ? 'p' : 'n', (long)[screen numberOfPlanes]);
  879. return;
  880. }
  881. int redC = 0, greenC = 1, blueC = 2;
  882. if ([screen bitmapFormat] & NSAlphaFirstBitmapFormat) {
  883. redC = 1; greenC = 2; blueC = 3;
  884. }
  885. unsigned char *data = [screen bitmapData];
  886. unsigned long width = [screen pixelsWide];
  887. unsigned long height = [screen pixelsHigh];
  888. unsigned long max = width * height;
  889. unsigned long red = 0, green = 0, blue = 0;
  890. for (unsigned long i = 0; i < max; i += AVERAGE_COLOR_PERFORMANCE_INC) {
  891. unsigned long off = spp * i;
  892. red += data[off + redC];
  893. green += data[off + greenC];
  894. blue += data[off + blueC];
  895. }
  896. max /= AVERAGE_COLOR_PERFORMANCE_INC;
  897. [self setLightsR:(red / max) G:(green / max) B:(blue / max)];
  898. }
  899. - (void)visualizeGPUUsage:(NSTimer *)timer {
  900. NSNumber *usage;
  901. NSNumber *freeVRAM;
  902. NSNumber *usedVRAM;
  903. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  904. NSLog(@"Error reading GPU information\n");
  905. } else {
  906. double h = [AppDelegate map:[usage doubleValue] FromMin:0.0 FromMax:100.0 ToMin:GPU_COLOR_MIN ToMax:GPU_COLOR_MAX];
  907. #ifdef DEBUG
  908. NSLog(@"GPU Usage: %.3f%%\n", [usage doubleValue]);
  909. #endif
  910. unsigned char r, g, b;
  911. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  912. [self setLightsR:r G:g B:b];
  913. }
  914. }
  915. - (void)visualizeVRAMUsage:(NSTimer *)timer {
  916. NSNumber *usage;
  917. NSNumber *freeVRAM;
  918. NSNumber *usedVRAM;
  919. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  920. NSLog(@"Error reading GPU information\n");
  921. } else {
  922. double h = [AppDelegate map:[freeVRAM doubleValue] FromMin:0.0 FromMax:([freeVRAM doubleValue] + [usedVRAM doubleValue]) ToMin:RAM_COLOR_MIN ToMax:RAM_COLOR_MAX];
  923. #ifdef DEBUG
  924. NSLog(@"VRAM %.2fGB Free + %.2fGB Used = %.2fGB mapped to color %.2f!\n", [freeVRAM doubleValue] / (1024.0 * 1024.0 * 1024.0), [usedVRAM doubleValue] / (1024.0 * 1024.0 * 1024.0), ([freeVRAM doubleValue] + [usedVRAM doubleValue]) / (1024.0 * 1024.0 * 1024.0), h);
  925. #endif
  926. unsigned char r, g, b;
  927. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  928. [self setLightsR:r G:g B:b];
  929. }
  930. }
  931. - (void)visualizeCPUUsage:(NSTimer *)timer {
  932. JSKMCPUUsageInfo cpuUsageInfo = [JSKSystemMonitor systemMonitor].cpuUsageInfo;
  933. double h = [AppDelegate map:cpuUsageInfo.usage FromMin:0.0 FromMax:100.0 ToMin:CPU_COLOR_MIN ToMax:CPU_COLOR_MAX];
  934. #ifdef DEBUG
  935. NSLog(@"CPU Usage: %.3f%%\n", cpuUsageInfo.usage);
  936. #endif
  937. unsigned char r, g, b;
  938. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  939. [self setLightsR:r G:g B:b];
  940. }
  941. - (void)visualizeRAMUsage:(NSTimer *)timer {
  942. JSKMMemoryUsageInfo memoryUsageInfo = [JSKSystemMonitor systemMonitor].memoryUsageInfo;
  943. double h = [AppDelegate map:memoryUsageInfo.freeMemory FromMin:0.0 FromMax:(memoryUsageInfo.usedMemory + memoryUsageInfo.freeMemory) ToMin:RAM_COLOR_MIN ToMax:RAM_COLOR_MAX];
  944. #ifdef DEBUG
  945. NSLog(@"RAM %.2fGB Free + %.2fGB Used = %.2fGB mapped to color %.2f!\n", memoryUsageInfo.freeMemory / (1024.0 * 1024.0 * 1024.0), memoryUsageInfo.usedMemory / (1024.0 * 1024.0 * 1024.0), (memoryUsageInfo.freeMemory + memoryUsageInfo.usedMemory) / (1024.0 * 1024.0 * 1024.0), h);
  946. #endif
  947. unsigned char r, g, b;
  948. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  949. [self setLightsR:r G:g B:b];
  950. }
  951. - (void)visualizeGPUTemperature:(NSTimer *)timer {
  952. JSKSMC *smc = [JSKSMC smc];
  953. double temp = [smc temperatureInCelsiusForKey:KEY_GPU_TEMPERATURE];
  954. if (temp > 1000.0) {
  955. temp /= 1000.0;
  956. }
  957. if (temp > GPU_TEMP_MAX) {
  958. temp = GPU_TEMP_MAX;
  959. }
  960. if (temp < GPU_TEMP_MIN) {
  961. temp = GPU_TEMP_MIN;
  962. }
  963. double h = [AppDelegate map:temp FromMin:GPU_TEMP_MIN FromMax:GPU_TEMP_MAX ToMin:GPU_COLOR_MIN ToMax:GPU_COLOR_MAX];
  964. #ifdef DEBUG
  965. NSLog(@"GPU Temp %.2f mapped to color %.2f!\n", temp, h);
  966. #endif
  967. unsigned char r, g, b;
  968. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  969. [self setLightsR:r G:g B:b];
  970. }
  971. - (void)visualizeCPUTemperature:(NSTimer *)timer {
  972. JSKSMC *smc = [JSKSMC smc];
  973. double temp = [smc temperatureInCelsiusForKey:KEY_CPU_TEMPERATURE];
  974. if (temp > 1000.0) {
  975. temp /= 1000.0;
  976. }
  977. if (temp > CPU_TEMP_MAX) {
  978. temp = CPU_TEMP_MAX;
  979. }
  980. if (temp < CPU_TEMP_MIN) {
  981. temp = CPU_TEMP_MIN;
  982. }
  983. double h = [AppDelegate map:temp FromMin:CPU_TEMP_MIN FromMax:CPU_TEMP_MAX ToMin:CPU_COLOR_MIN ToMax:CPU_COLOR_MAX];
  984. #ifdef DEBUG
  985. NSLog(@"CPU Temp %.2f mapped to color %.2f!\n", temp, h);
  986. #endif
  987. unsigned char r, g, b;
  988. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  989. [self setLightsR:r G:g B:b];
  990. }
  991. - (void)visualizeRGBFade:(NSTimer *)timer {
  992. static unsigned char color[3] = { 255, 0, 0 };
  993. static int dec = 0;
  994. static int val = 0;
  995. // Adapted from:
  996. // https://gist.github.com/jamesotron/766994
  997. if (dec < 3) {
  998. int inc = (dec == 2) ? 0 : (dec + 1);
  999. if (val < 255) {
  1000. color[dec] -= 1;
  1001. color[inc] += 1;
  1002. val++;
  1003. } else {
  1004. val = 0;
  1005. dec++;
  1006. }
  1007. } else {
  1008. dec = 0;
  1009. }
  1010. [self setLightsR:color[0] G:color[1] B:color[2]];
  1011. }
  1012. - (void)visualizeHSVFade:(NSTimer *)timer {
  1013. static float h = 0.0;
  1014. if (h < 359.0) {
  1015. h += 0.5;
  1016. } else {
  1017. h = 0.0;
  1018. }
  1019. unsigned char r, g, b;
  1020. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  1021. [self setLightsR:r G:g B:b];
  1022. }
  1023. - (void)visualizeRandom:(NSTimer *)timer {
  1024. [self setLightsR:rand() % 256 G:rand() % 256 B:rand() % 256];
  1025. }
  1026. // -----------------------------------------------------
  1027. // --------------------- Utilities ---------------------
  1028. // -----------------------------------------------------
  1029. + (NSImage *)tintedImage:(NSImage *)image WithColor:(NSColor *)tint {
  1030. NSSize size = [image size];
  1031. NSRect imageBounds = NSMakeRect(0, 0, size.width, size.height);
  1032. NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"];
  1033. BOOL darkMode = ((osxMode != nil) && ([osxMode isEqualToString:@"Dark"])) ? YES : NO;
  1034. NSImage *copiedImage = [image copy];
  1035. static NSColor *lastTint = nil;
  1036. NSColor *copiedTint = nil;
  1037. if (tint != nil) {
  1038. // Just use the provided color
  1039. copiedTint = [tint copy];
  1040. lastTint = copiedTint;
  1041. } else {
  1042. // Try to use the same color as the last time
  1043. if (lastTint != nil) {
  1044. copiedTint = lastTint;
  1045. } else {
  1046. #ifdef DEBUG
  1047. NSLog(@"Trying to set last status bar icon color, but was not set!\n");
  1048. #endif
  1049. if (darkMode == YES) {
  1050. copiedTint = [NSColor whiteColor];
  1051. } else {
  1052. copiedTint = [NSColor blackColor];
  1053. }
  1054. }
  1055. }
  1056. // Fix colors for different interface styles
  1057. CGFloat r, g, b, a;
  1058. [copiedTint getRed:&r green:&g blue:&b alpha:&a];
  1059. if (darkMode == YES) {
  1060. if ((r < 0.001f) && (g < 0.001f) && (b < 0.001f)) {
  1061. copiedTint = [NSColor whiteColor];
  1062. }
  1063. } else {
  1064. if ((r > 0.999f) && (g > 0.999f) && (b > 0.999f)) {
  1065. copiedTint = [NSColor blackColor];
  1066. }
  1067. }
  1068. [copiedImage lockFocus];
  1069. [copiedTint set];
  1070. NSRectFillUsingOperation(imageBounds, NSCompositeSourceAtop);
  1071. [copiedImage unlockFocus];
  1072. return copiedImage;
  1073. }
  1074. + (double)map:(double)val FromMin:(double)fmin FromMax:(double)fmax ToMin:(double)tmin ToMax:(double)tmax {
  1075. double norm = (val - fmin) / (fmax - fmin);
  1076. return (norm * (tmax - tmin)) + tmin;
  1077. }
  1078. + (void)convertH:(double)h S:(double)s V:(double)v toR:(unsigned char *)r G:(unsigned char *)g B:(unsigned char *)b {
  1079. // Adapted from:
  1080. // https://gist.github.com/hdznrrd/656996
  1081. if (s == 0.0) {
  1082. // Achromatic
  1083. *r = *g = *b = (unsigned char)(v * 255);
  1084. return;
  1085. }
  1086. h /= 60; // sector 0 to 5
  1087. int i = floor(h);
  1088. double f = h - i; // factorial part of h
  1089. double p = v * (1 - s);
  1090. double q = v * (1 - s * f);
  1091. double t = v * (1 - s * (1 - f));
  1092. switch (i) {
  1093. case 0:
  1094. *r = (unsigned char)round(255 * v);
  1095. *g = (unsigned char)round(255 * t);
  1096. *b = (unsigned char)round(255 * p);
  1097. break;
  1098. case 1:
  1099. *r = (unsigned char)round(255 * q);
  1100. *g = (unsigned char)round(255 * v);
  1101. *b = (unsigned char)round(255 * p);
  1102. break;
  1103. case 2:
  1104. *r = (unsigned char)round(255 * p);
  1105. *g = (unsigned char)round(255 * v);
  1106. *b = (unsigned char)round(255 * t);
  1107. break;
  1108. case 3:
  1109. *r = (unsigned char)round(255 * p);
  1110. *g = (unsigned char)round(255 * q);
  1111. *b = (unsigned char)round(255 * v);
  1112. break;
  1113. case 4:
  1114. *r = (unsigned char)round(255 * t);
  1115. *g = (unsigned char)round(255 * p);
  1116. *b = (unsigned char)round(255 * v);
  1117. break;
  1118. default: case 5:
  1119. *r = (unsigned char)round(255 * v);
  1120. *g = (unsigned char)round(255 * p);
  1121. *b = (unsigned char)round(255 * q);
  1122. break;
  1123. }
  1124. }
  1125. @end