From 544d551c5d1f7ffaa9113e07d9b264d90edffb49 Mon Sep 17 00:00:00 2001 From: tinkernels Date: Mon, 25 May 2020 15:29:51 +0800 Subject: [PATCH 1/8] Add Turbo Boost control feature. --- Classes/FanControl.m | 826 +++++++++--------- Classes/Privilege.h | 18 + Classes/Privilege.m | 56 ++ Classes/smcWrapper.m | 101 +-- Info.plist | 6 +- .../Contents/Info.plist | 53 ++ .../Contents/MacOS/DisableTurboBoost | Bin 0 -> 2028 bytes .../Contents/Info.plist | 53 ++ .../Contents/MacOS/DisableTurboBoost | Bin 0 -> 8840 bytes smcFanControl.xcodeproj/project.pbxproj | 55 +- .../xcshareddata/xcschemes/smc.xcscheme | 78 ++ .../xcschemes/smcFanControl.xcscheme | 78 ++ 12 files changed, 849 insertions(+), 475 deletions(-) create mode 100644 Classes/Privilege.h create mode 100644 Classes/Privilege.m create mode 100755 Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist create mode 100644 Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost create mode 100755 Ressources/DisableTurboBoost.64bits.kext/Contents/Info.plist create mode 100755 Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost create mode 100644 smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme create mode 100644 smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme diff --git a/Classes/FanControl.m b/Classes/FanControl.m index e1e3b44..0a5df0f 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -20,7 +20,7 @@ * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ - + #import "FanControl.h" #import "MachineDefaults.h" @@ -29,12 +29,12 @@ #import #import #import "SystemVersion.h" +#import "Privilege.h" @interface FanControl () + (void)copyMachinesIfNecessary; @property (NS_NONATOMIC_IOSONLY, getter=isInAutoStart, readonly) BOOL inAutoStart; - (void)setStartAtLogin:(BOOL)enabled; -+ (void)checkRightStatus:(OSStatus)status; @end @implementation FanControl @@ -42,6 +42,7 @@ @implementation FanControl // Number of fans reported by the hardware. int g_numFans = 0; +NSString *moduleDstPath = @"/Library/Extensions/DisableTurboBoost.64bits.kext"; NSUserDefaults *defaults; @@ -49,19 +50,19 @@ @implementation FanControl +(void) initialize { - //avoid Zombies when starting external app - signal(SIGCHLD, SIG_IGN); + //avoid Zombies when starting external app + signal(SIGCHLD, SIG_IGN); [FanControl copyMachinesIfNecessary]; - //check owner and suid rights - [FanControl setRights]; - - //talk to smc - [smcWrapper init]; - - //app in foreground for update notifications - [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; - + //check owner and suid rights + [FanControl setRights]; + + //talk to smc + [smcWrapper init]; + + //app in foreground for update notifications + [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; + } +(void)copyMachinesIfNecessary @@ -74,164 +75,164 @@ +(void)copyMachinesIfNecessary -(void)upgradeFavorites { - //upgrade favorites - NSArray *rfavorites = [FavoritesController arrangedObjects]; - int j; - int i; - for (i=0;i<[rfavorites count];i++) - { - BOOL selected = NO; - NSArray *fans = rfavorites[i][PREF_FAN_ARRAY]; - for (j=0;j<[fans count];j++) { - if ([fans[j][PREF_FAN_SHOWMENU] boolValue] == YES ) { - selected = YES; - } - } - if (selected==NO) { - rfavorites[i][PREF_FAN_ARRAY][0][PREF_FAN_SHOWMENU] = @YES; - } - } - + //upgrade favorites + NSArray *rfavorites = [FavoritesController arrangedObjects]; + int j; + int i; + for (i=0;i<[rfavorites count];i++) + { + BOOL selected = NO; + NSArray *fans = rfavorites[i][PREF_FAN_ARRAY]; + for (j=0;j<[fans count];j++) { + if ([fans[j][PREF_FAN_SHOWMENU] boolValue] == YES ) { + selected = YES; + } + } + if (selected==NO) { + rfavorites[i][PREF_FAN_ARRAY][0][PREF_FAN_SHOWMENU] = @YES; + } + } + } -(void) awakeFromNib { - pw=[[Power alloc] init]; - [pw setDelegate:self]; - [pw registerForSleepWakeNotification]; - [pw registerForPowerChange]; - - + pw=[[Power alloc] init]; + [pw setDelegate:self]; + [pw registerForSleepWakeNotification]; + [pw registerForPowerChange]; + + //load defaults [DefaultsController setAppliesImmediately:NO]; - - mdefaults=[[MachineDefaults alloc] init:nil]; - + + mdefaults=[[MachineDefaults alloc] init:nil]; + self.machineDefaultsDict=[[NSMutableDictionary alloc] initWithDictionary:[mdefaults get_machine_defaults]]; - + NSMutableArray *favorites = [[NSMutableArray alloc] init]; NSMutableDictionary *defaultFav = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Default", PREF_FAN_TITLE, - [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY,nil]; - + [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY,nil]; + [favorites addObject:defaultFav]; - NSRange range=[[MachineDefaults computerModel] rangeOfString:@"MacBook"]; - if (range.length>0) { - //for macbooks add a second default - NSMutableDictionary *higherFav=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Higher RPM", PREF_FAN_TITLE, + NSRange range=[[MachineDefaults computerModel] rangeOfString:@"MacBook"]; + if (range.length>0) { + //for macbooks add a second default + NSMutableDictionary *higherFav=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Higher RPM", PREF_FAN_TITLE, [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY,nil]; - for (NSUInteger i=0;i<[_machineDefaultsDict[@"Fans"] count];i++) { + for (NSUInteger i=0;i<[_machineDefaultsDict[@"Fans"] count];i++) { int min_value=([[[[_machineDefaultsDict objectForKey:@"Fans"] objectAtIndex:i] objectForKey:PREF_FAN_MINSPEED] intValue])*2; [[[higherFav objectForKey:PREF_FAN_ARRAY] objectAtIndex:i] setObject:[NSNumber numberWithInt:min_value] forKey:PREF_FAN_SELSPEED]; - } + } [favorites addObject:higherFav]; - - } - - //sync option for Macbook Pro's - NSRange range_mbp=[[MachineDefaults computerModel] rangeOfString:@"MacBookPro"]; - if (range_mbp.length>0 && [_machineDefaultsDict[@"Fans"] count] == 2) { - [sync setHidden:NO]; - } - - //load user defaults - defaults = [NSUserDefaults standardUserDefaults]; - [defaults registerDefaults: - [NSMutableDictionary dictionaryWithObjectsAndKeys: - @0, PREF_TEMP_UNIT, - @0, PREF_SELECTION_DEFAULT, - @NO,PREF_AUTOSTART_ENABLED, - @NO,PREF_AUTOMATIC_CHANGE, - @0, PREF_BATTERY_SELECTION, - @0, PREF_AC_SELECTION, - @0, PREF_CHARGING_SELECTION, - @0, PREF_MENU_DISPLAYMODE, - @"TC0D",PREF_TEMPERATURE_SENSOR, - @0, PREF_NUMBEROF_LAUNCHES, - @NO,PREF_DONATIONMESSAGE_DISPLAY, - [NSArchiver archivedDataWithRootObject:[NSColor blackColor]],PREF_MENU_TEXTCOLOR, - favorites,PREF_FAVORITES_ARRAY, - nil]]; - - - - g_numFans = [smcWrapper get_fan_num]; - s_menus=[[NSMutableArray alloc] init]; - int i; - for(i=0;i0) { - [autochange setEnabled:true]; - } else { - [autochange setEnabled:false]; - } - [faqText replaceCharactersInRange:NSMakeRange(0,0) withRTF: [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"F.A.Q" ofType:@"rtf"]]]; - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; - [[[[theMenu itemWithTag:1] submenu] itemAtIndex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]] setState:NSOnState]; - [[sliderCell dataCell] setControlSize:NSSmallControlSize]; - [self changeMenu:nil]; - - //seting toolbar image + + } + + //sync option for Macbook Pro's + NSRange range_mbp=[[MachineDefaults computerModel] rangeOfString:@"MacBookPro"]; + if (range_mbp.length>0 && [_machineDefaultsDict[@"Fans"] count] == 2) { + [sync setHidden:NO]; + } + + //load user defaults + defaults = [NSUserDefaults standardUserDefaults]; + [defaults registerDefaults: + [NSMutableDictionary dictionaryWithObjectsAndKeys: + @0, PREF_TEMP_UNIT, + @0, PREF_SELECTION_DEFAULT, + @NO,PREF_AUTOSTART_ENABLED, + @NO,PREF_AUTOMATIC_CHANGE, + @0, PREF_BATTERY_SELECTION, + @0, PREF_AC_SELECTION, + @0, PREF_CHARGING_SELECTION, + @0, PREF_MENU_DISPLAYMODE, + @"TC0D",PREF_TEMPERATURE_SENSOR, + @0, PREF_NUMBEROF_LAUNCHES, + @NO,PREF_DONATIONMESSAGE_DISPLAY, + [NSArchiver archivedDataWithRootObject:[NSColor blackColor]],PREF_MENU_TEXTCOLOR, + favorites,PREF_FAVORITES_ARRAY, + nil]]; + + + + g_numFans = [smcWrapper get_fan_num]; + s_menus=[[NSMutableArray alloc] init]; + int i; + for(i=0;i0) { + [autochange setEnabled:true]; + } else { + [autochange setEnabled:false]; + } + [faqText replaceCharactersInRange:NSMakeRange(0,0) withRTF: [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"F.A.Q" ofType:@"rtf"]]]; + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; + [[[[theMenu itemWithTag:1] submenu] itemAtIndex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]] setState:NSOnState]; + [[sliderCell dataCell] setControlSize:NSSmallControlSize]; + [self changeMenu:nil]; + + //seting toolbar image menu_image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"smc" ofType:@"png"]]; menu_image_alt = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"smcover" ofType:@"png"]]; if ([menu_image respondsToSelector:@selector(setTemplate:)]) { [menu_image setTemplate:YES]; [menu_image_alt setTemplate:YES]; } - - //add timer for reading to RunLoop - _readTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(readFanData:) userInfo:nil repeats:YES]; + + //add timer for reading to RunLoop + _readTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(readFanData:) userInfo:nil repeats:YES]; if ([_readTimer respondsToSelector:@selector(setTolerance:)]) { [_readTimer setTolerance:2.0]; } - [_readTimer fire]; + [_readTimer fire]; - //autoapply settings if valid - [self upgradeFavorites]; + //autoapply settings if valid + [self upgradeFavorites]; //autostart [[NSUserDefaults standardUserDefaults] setValue:@([self isInAutoStart]) forKey:PREF_AUTOSTART_ENABLED]; - NSUInteger numLaunches = [[[NSUserDefaults standardUserDefaults] objectForKey:PREF_NUMBEROF_LAUNCHES] integerValue]; + NSUInteger numLaunches = [[[NSUserDefaults standardUserDefaults] objectForKey:PREF_NUMBEROF_LAUNCHES] integerValue]; [[NSUserDefaults standardUserDefaults] setObject:@(numLaunches+1) forKey:PREF_NUMBEROF_LAUNCHES]; if (numLaunches != 0 && (numLaunches % 3 == 0) && ![[[NSUserDefaults standardUserDefaults] objectForKey:PREF_DONATIONMESSAGE_DISPLAY] boolValue]) { [self displayDonationMessage]; } [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(readFanData:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; - + } -(void)displayDonationMessage @@ -248,10 +249,29 @@ -(void)displayDonationMessage } } +-(void) enableTurboBoost{ + [Privilege runTaskAsAdmin:@"/sbin/kextunload" andArgs:@[moduleDstPath]]; +} + +-(void) disableTurboBoost{ + NSArray *argsArrayLoadKext = @[@"-v",moduleDstPath]; + [Privilege runTaskAsAdmin:@"/usr/bin/kextutil" andArgs:argsArrayLoadKext]; +} + +-(void)applyTurboBoost:(id)sender{ + NSControlStateValue state = [sender state]; + if (state == NSOffState){ + [sender setState:NSOnState]; + [self enableTurboBoost]; + }else{ + [sender setState:NSOffState]; + [self disableTurboBoost]; + } +} -(void)init_statusitem{ - statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength]; - [statusItem setMenu: theMenu]; + statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength]; + [statusItem setMenu: theMenu]; if ([statusItem respondsToSelector:@selector(button)]) { [statusItem.button setTitle:@"smc..."]; @@ -260,10 +280,22 @@ -(void)init_statusitem{ [statusItem setHighlightMode:YES]; [statusItem setTitle:@"smc..."]; } - int i; - for(i=0;i<[s_menus count];i++) { - [theMenu insertItem:s_menus[i] atIndex:i]; - }; + int i; + for(i=0;i<[s_menus count];i++) { + [theMenu insertItem:s_menus[i] atIndex:i]; + }; + + [self disableTurboBoost]; + NSMenuItem *fan1Item = [theMenu itemWithTitle:@"Fan: 1"]; + int fan1ItemIdx = [theMenu indexOfItem:fan1Item]; + NSMenuItem *turboBoostItem = [[NSMenuItem alloc] + initWithTitle:@"Turbo Boost" + action:@selector(applyTurboBoost:) + keyEquivalent:@""]; + [turboBoostItem setState:NSOffState]; + [turboBoostItem setEnabled:true]; + [turboBoostItem setTarget:self]; + [theMenu insertItem:turboBoostItem atIndex:fan1ItemIdx + 1]; // Sign up for menuNeedsUpdate call // so that the fan speeds in the menu can be updated @@ -272,62 +304,61 @@ -(void)init_statusitem{ } + #pragma mark **Action-Methods** - (IBAction)loginItem:(id)sender{ - if ([sender state]==NSOnState) { - [self setStartAtLogin:YES]; - } else { + if ([sender state]==NSOnState) { + [self setStartAtLogin:YES]; + } else { [self setStartAtLogin:NO]; - } + } } - (IBAction)add_favorite:(id)sender{ - [[NSApplication sharedApplication] beginSheet:newfavoritewindow - modalForWindow: mainwindow - modalDelegate: nil - didEndSelector: nil - contextInfo: nil]; + [[NSApplication sharedApplication] beginSheet:newfavoritewindow + modalForWindow: mainwindow + modalDelegate: nil + didEndSelector: nil + contextInfo: nil]; } - (IBAction)close_favorite:(id)sender{ - [newfavoritewindow close]; - [[NSApplication sharedApplication] endSheet:newfavoritewindow]; + [newfavoritewindow close]; + [[NSApplication sharedApplication] endSheet:newfavoritewindow]; } - (IBAction)save_favorite:(id)sender{ - MachineDefaults *msdefaults=[[MachineDefaults alloc] init:nil]; - if ([[newfavorite_title stringValue] length]>0) { - NSMutableDictionary *toinsert=[[NSMutableDictionary alloc] initWithObjectsAndKeys:[newfavorite_title stringValue],@"Title",[msdefaults get_machine_defaults][@"Fans"],PREF_FAN_ARRAY,nil]; //default as template - [toinsert setValue:@0 forKey:@"Standard"]; - [FavoritesController addObject:toinsert]; - [newfavoritewindow close]; - [[NSApplication sharedApplication] endSheet:newfavoritewindow]; - } - [self upgradeFavorites]; + MachineDefaults *msdefaults=[[MachineDefaults alloc] init:nil]; + if ([[newfavorite_title stringValue] length]>0) { + NSMutableDictionary *toinsert=[[NSMutableDictionary alloc] initWithObjectsAndKeys:[newfavorite_title stringValue],@"Title",[msdefaults get_machine_defaults][@"Fans"],PREF_FAN_ARRAY,nil]; //default as template + [toinsert setValue:@0 forKey:@"Standard"]; + [FavoritesController addObject:toinsert]; + [newfavoritewindow close]; + [[NSApplication sharedApplication] endSheet:newfavoritewindow]; + } + [self upgradeFavorites]; } -(void) check_deletion:(id)combo{ - if ([FavoritesController selectionIndex]==[[defaults objectForKey:combo] intValue]) { - [defaults setObject:@0 forKey:combo]; - } + if ([FavoritesController selectionIndex]==[[defaults objectForKey:combo] intValue]) { + [defaults setObject:@0 forKey:combo]; + } } - - - (void) deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; { if (returnCode==0) { - //delete favorite, but resets presets before - [self check_deletion:PREF_BATTERY_SELECTION]; - [self check_deletion:PREF_AC_SELECTION]; - [self check_deletion:PREF_CHARGING_SELECTION]; + //delete favorite, but resets presets before + [self check_deletion:PREF_BATTERY_SELECTION]; + [self check_deletion:PREF_AC_SELECTION]; + [self check_deletion:PREF_CHARGING_SELECTION]; [FavoritesController removeObjects:[FavoritesController selectedObjects]]; - } + } } - (IBAction)delete_favorite:(id)sender{ - + NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Delete favorite",nil) defaultButton:NSLocalizedString(@"No",nil) alternateButton:NSLocalizedString(@"Yes",nil) otherButton:nil informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"Do you really want to delete the favorite %@?",nil), [FavoritesController arrangedObjects][[FavoritesController selectionIndex]][@"Title"] ]]; [alert beginSheetModalForWindow:mainwindow modalDelegate:self didEndSelector:@selector(deleteAlertDidEnd:returnCode:contextInfo:) contextInfo:NULL]; @@ -338,13 +369,13 @@ - (IBAction)delete_favorite:(id)sender{ // Called via a timer mechanism. This is where all the temp / RPM reading is done. //reads fan data and updates the gui -(void) readFanData:(id)caller{ - + int i = 0; - - //on init handling - if (_machineDefaultsDict==nil) { - return; - } + + //on init handling + if (_machineDefaultsDict==nil) { + return; + } // Determine what data is actually needed to keep the energy impact // as low as possible. @@ -373,9 +404,9 @@ -(void) readFanData:(id)caller{ bNeedRpm = true; break; } - + NSString *temp = nil; - NSString *fan = nil; + NSString *fan = nil; float c_temp = 0.0f; int selectedRpm = 0; @@ -417,7 +448,7 @@ -(void) readFanData:(id)caller{ NSColor *menuColor = (NSColor*)[NSUnarchiver unarchiveObjectWithData:[defaults objectForKey:PREF_MENU_TEXTCOLOR]]; BOOL setColor = NO; if (!([[menuColor colorUsingColorSpaceName: - NSCalibratedWhiteColorSpace] whiteComponent] == 0.0) || ![statusItem respondsToSelector:@selector(button)]) setColor = YES; + NSCalibratedWhiteColorSpace] whiteComponent] == 0.0) || ![statusItem respondsToSelector:@selector(button)]) setColor = YES; NSString *osxMode = [[NSUserDefaults standardUserDefaults] stringForKey:@"AppleInterfaceStyle"]; @@ -447,10 +478,10 @@ -(void) readFanData:(id)caller{ [paragraphStyle setAlignment:NSLeftTextAlignment]; [s_status addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Lucida Grande" size:fsize] range:NSMakeRange(0,[s_status length])]; [s_status addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0,[s_status length])]; - + if (setColor) [s_status addAttribute:NSForegroundColorAttributeName value:menuColor range:NSMakeRange(0,[s_status length])]; - + if ([statusItem respondsToSelector:@selector(button)]) { [statusItem.button setAttributedTitle:s_status]; [statusItem.button setImage:nil]; @@ -517,28 +548,28 @@ -(void) readFanData:(id)caller{ - (IBAction)savePreferences:(id)sender{ - [(NSUserDefaultsController *)DefaultsController save:sender]; - [defaults setValue:[FavoritesController content] forKey:PREF_FAVORITES_ARRAY]; - [defaults synchronize]; - [mainwindow close]; - [self apply_settings:sender controllerindex:[FavoritesController selectionIndex]]; - undo_dic=[NSDictionary dictionaryWithDictionary:[defaults dictionaryRepresentation]]; + [(NSUserDefaultsController *)DefaultsController save:sender]; + [defaults setValue:[FavoritesController content] forKey:PREF_FAVORITES_ARRAY]; + [defaults synchronize]; + [mainwindow close]; + [self apply_settings:sender controllerindex:[FavoritesController selectionIndex]]; + undo_dic=[NSDictionary dictionaryWithDictionary:[defaults dictionaryRepresentation]]; } - (IBAction)closePreferences:(id)sender{ - [mainwindow close]; - [DefaultsController revert:sender]; + [mainwindow close]; + [DefaultsController revert:sender]; } //set the new fan settings -(void)apply_settings:(id)sender controllerindex:(int)cIndex{ - int i; - [FanControl setRights]; - [FavoritesController setSelectionIndex:cIndex]; + int i; + [FanControl setRights]; + [FavoritesController setSelectionIndex:cIndex]; if ([[MachineDefaults computerModel] rangeOfString:@"MacBookPro15"].location != NSNotFound) { for (i=0;i<[[FavoritesController arrangedObjects][cIndex][PREF_FAN_ARRAY] count];i++) { @@ -555,80 +586,79 @@ -(void)apply_settings:(id)sender controllerindex:(int)cIndex{ } } - NSMenu *submenu = [[NSMenu alloc] init]; - - for(i=0;i<[[FavoritesController arrangedObjects] count];i++){ - NSMenuItem *submenuItem = [[NSMenuItem alloc] initWithTitle:[FavoritesController arrangedObjects][i][@"Title"] action:@selector(apply_quickselect:) keyEquivalent:@""]; - [submenuItem setTag:i*100]; //for later manipulation - [submenuItem setEnabled:YES]; - [submenuItem setTarget:self]; - [submenuItem setRepresentedObject:[FavoritesController arrangedObjects][i]]; - [submenu addItem:submenuItem]; - } - - [[theMenu itemWithTag:1] setSubmenu:submenu]; - for (i=0;i<[[[theMenu itemWithTag:1] submenu] numberOfItems];i++) { - [[[[theMenu itemWithTag:1] submenu] itemAtIndex:i] setState:NSOffState]; - } - [[[[theMenu itemWithTag:1] submenu] itemAtIndex:cIndex] setState:NSOnState]; - [defaults setObject:@(cIndex) forKey:PREF_SELECTION_DEFAULT]; - //change active setting display - [[theMenu itemWithTag:1] setTitle:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"Active Setting",nil),[FavoritesController arrangedObjects][[FavoritesController selectionIndex]][PREF_FAN_TITLE] ]]; + NSMenu *submenu = [[NSMenu alloc] init]; + + for(i=0;i<[[FavoritesController arrangedObjects] count];i++){ + NSMenuItem *submenuItem = [[NSMenuItem alloc] initWithTitle:[FavoritesController arrangedObjects][i][@"Title"] action:@selector(apply_quickselect:) keyEquivalent:@""]; + [submenuItem setTag:i*100]; //for later manipulation + [submenuItem setEnabled:YES]; + [submenuItem setTarget:self]; + [submenuItem setRepresentedObject:[FavoritesController arrangedObjects][i]]; + [submenu addItem:submenuItem]; + } + + [[theMenu itemWithTag:1] setSubmenu:submenu]; + for (i=0;i<[[[theMenu itemWithTag:1] submenu] numberOfItems];i++) { + [[[[theMenu itemWithTag:1] submenu] itemAtIndex:i] setState:NSOffState]; + } + [[[[theMenu itemWithTag:1] submenu] itemAtIndex:cIndex] setState:NSOnState]; + [defaults setObject:@(cIndex) forKey:PREF_SELECTION_DEFAULT]; + //change active setting display + [[theMenu itemWithTag:1] setTitle:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"Active Setting",nil),[FavoritesController arrangedObjects][[FavoritesController selectionIndex]][PREF_FAN_TITLE] ]]; } -(void)apply_quickselect:(id)sender{ - int i; - [FanControl setRights]; - //set all others items to off - for (i=0;i<[[[theMenu itemWithTag:1] submenu] numberOfItems];i++) { - [[[[theMenu itemWithTag:1] submenu] itemAtIndex:i] setState:NSOffState]; - } - [sender setState:NSOnState]; - [[theMenu itemWithTag:1] setTitle:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"Active Setting",nil),[sender title]]]; - [self apply_settings:sender controllerindex:[[[theMenu itemWithTag:1] submenu] indexOfItem:sender]]; + int i; + [FanControl setRights]; + //set all others items to off + for (i=0;i<[[[theMenu itemWithTag:1] submenu] numberOfItems];i++) { + [[[[theMenu itemWithTag:1] submenu] itemAtIndex:i] setState:NSOffState]; + } + [sender setState:NSOnState]; + [[theMenu itemWithTag:1] setTitle:[NSString stringWithFormat:@"%@: %@",NSLocalizedString(@"Active Setting",nil),[sender title]]]; + [self apply_settings:sender controllerindex:[[[theMenu itemWithTag:1] submenu] indexOfItem:sender]]; } -(void)terminate:(id)sender{ - //get last active selection - [defaults synchronize]; - [smcWrapper cleanUp]; - [_readTimer invalidate]; - [pw deregisterForSleepWakeNotification]; - [pw deregisterForPowerChange]; - [[NSApplication sharedApplication] terminate:self]; + //get last active selection + [defaults synchronize]; + [smcWrapper cleanUp]; + [_readTimer invalidate]; + [pw deregisterForSleepWakeNotification]; + [pw deregisterForPowerChange]; + [self enableTurboBoost]; + [[NSApplication sharedApplication] terminate:self]; } - - - (IBAction)syncSliders:(id)sender{ - if ([sender state]) { - [self syncBinder:YES]; - } else { - [self syncBinder:NO]; - } + if ([sender state]) { + [self syncBinder:YES]; + } else { + [self syncBinder:NO]; + } } - (IBAction) changeMenu:(id)sender{ - if ([[[[NSUserDefaultsController sharedUserDefaultsController] values] valueForKey:PREF_MENU_DISPLAYMODE] intValue]==2) { - [colorSelector setEnabled:NO]; - } else { - [colorSelector setEnabled:YES]; - } - + if ([[[[NSUserDefaultsController sharedUserDefaultsController] values] valueForKey:PREF_MENU_DISPLAYMODE] intValue]==2) { + [colorSelector setEnabled:NO]; + } else { + [colorSelector setEnabled:YES]; + } + } - (IBAction)menuSelect:(id)sender{ - //deactivate all other radio buttons - int i; - for (i=0;i<[[FanController arrangedObjects] count];i++) { - if (i!=[sender selectedRow]) { - [[FanController arrangedObjects][i] setValue:@NO forKey:PREF_FAN_SHOWMENU]; - } - } + //deactivate all other radio buttons + int i; + for (i=0;i<[[FanController arrangedObjects] count];i++) { + if (i!=[sender selectedRow]) { + [[FanController arrangedObjects][i] setValue:@NO forKey:PREF_FAN_SHOWMENU]; + } + } } // Called when user clicks on smcFanControl status bar item @@ -657,15 +687,15 @@ - (void)menuNeedsUpdate:(NSMenu*)menu { //just a helper to bringt update-info-window to the front - (IBAction)updateCheck:(id)sender{ SUUpdater *updater = [[SUUpdater alloc] init]; - [updater checkForUpdates:sender]; - [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; + [updater checkForUpdates:sender]; + [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; } -(void)performReset { NSFileManager *fileManager = [NSFileManager defaultManager]; - + NSError *error; NSString *machinesPath = [[fileManager applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]; [fileManager removeItemAtPath:machinesPath error:&error]; @@ -678,7 +708,7 @@ -(void)performReset [smcWrapper setKey_external:[NSString stringWithFormat:@"F%dMd",i] value:@"00"]; } } - + NSString *domainName = [[NSBundle mainBundle] bundleIdentifier]; [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:domainName]; @@ -701,60 +731,60 @@ - (IBAction)resetSettings:(id)sender if (code == NSAlertDefaultReturn) { [self performReset]; } else if (code == NSAlertAlternateReturn) { - + } - + } - (IBAction)visitHomepage:(id)sender{ - [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.eidac.de/products"]]; + [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.eidac.de/products"]]; } - (IBAction)paypal:(id)sender{ - [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=holtmann%40campus%2dvirtuell%2ede&no_shipping=0&no_note=1&tax=0¤cy_code=EUR&bn=PP%2dDonationsBF&charset=UTF%2d8&country=US"]]; + [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=holtmann%40campus%2dvirtuell%2ede&no_shipping=0&no_note=1&tax=0¤cy_code=EUR&bn=PP%2dDonationsBF&charset=UTF%2d8&country=US"]]; } -(void) syncBinder:(Boolean)bind{ - //in case plist is corrupt, don't bind - if ([[FanController arrangedObjects] count]>1 ) { - if (bind==YES) { - [[FanController arrangedObjects][1] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][0] withKeyPath:PREF_FAN_SELSPEED options:nil]; - [[FanController arrangedObjects][0] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][1] withKeyPath:PREF_FAN_SELSPEED options:nil]; - } else { - [[FanController arrangedObjects][1] unbind:PREF_FAN_SELSPEED]; - [[FanController arrangedObjects][0] unbind:PREF_FAN_SELSPEED]; - } - } + //in case plist is corrupt, don't bind + if ([[FanController arrangedObjects] count]>1 ) { + if (bind==YES) { + [[FanController arrangedObjects][1] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][0] withKeyPath:PREF_FAN_SELSPEED options:nil]; + [[FanController arrangedObjects][0] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][1] withKeyPath:PREF_FAN_SELSPEED options:nil]; + } else { + [[FanController arrangedObjects][1] unbind:PREF_FAN_SELSPEED]; + [[FanController arrangedObjects][0] unbind:PREF_FAN_SELSPEED]; + } + } } #pragma mark **Power Watchdog-Methods** - (void)systemDidWakeFromSleep:(id)sender{ - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; } - (void)powerChangeToBattery:(id)sender{ - - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_BATTERY_SELECTION] intValue]]; - } + + if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_BATTERY_SELECTION] intValue]]; + } } - (void)powerChangeToAC:(id)sender{ - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_AC_SELECTION] intValue]]; - - } + if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_AC_SELECTION] intValue]]; + + } } - (void)powerChangeToACLoading:(id)sender{ - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_CHARGING_SELECTION] intValue]]; - - } + if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_CHARGING_SELECTION] intValue]]; + + } } @@ -763,144 +793,131 @@ - (void)powerChangeToACLoading:(id)sender{ - (BOOL)isInAutoStart { - BOOL found = NO; - LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); - NSString *path = [[NSBundle mainBundle] bundlePath]; - CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; - //LSSharedFileListItemRef existingItem = NULL; - - UInt32 seed = 0U; + BOOL found = NO; + LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); + NSString *path = [[NSBundle mainBundle] bundlePath]; + CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; + //LSSharedFileListItemRef existingItem = NULL; + + UInt32 seed = 0U; NSArray *currentLoginItems = CFBridgingRelease(LSSharedFileListCopySnapshot(loginItems, &seed)); - - for (id itemObject in currentLoginItems) { - LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; - - UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; - CFURLRef URL = NULL; - OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); - if (err == noErr) { - Boolean foundIt = CFEqual(URL, URLToToggle); - CFRelease(URL); - - if (foundIt) { - //existingItem = item; - found = YES; - break; - } - } - } - return found; + + for (id itemObject in currentLoginItems) { + LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; + + UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; + CFURLRef URL = NULL; + OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); + if (err == noErr) { + Boolean foundIt = CFEqual(URL, URLToToggle); + CFRelease(URL); + + if (foundIt) { + //existingItem = item; + found = YES; + break; + } + } + } + return found; } - (void) setStartAtLogin:(BOOL)enabled { - LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); + LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); + - - NSString *path = [[NSBundle mainBundle] bundlePath]; - - OSStatus status; - CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; - LSSharedFileListItemRef existingItem = NULL; - - UInt32 seed = 0U; + NSString *path = [[NSBundle mainBundle] bundlePath]; + + OSStatus status; + CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; + LSSharedFileListItemRef existingItem = NULL; + + UInt32 seed = 0U; NSArray *currentLoginItems = CFBridgingRelease(LSSharedFileListCopySnapshot(loginItems, &seed)); - - for (id itemObject in currentLoginItems) { - LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; - - UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; - CFURLRef URL = NULL; - OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); - if (err == noErr) { - Boolean foundIt = CFEqual(URL, URLToToggle); - CFRelease(URL); - - if (foundIt) { - existingItem = item; - break; - } - } - } - - if (enabled && (existingItem == NULL)) { - NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:path]; - IconRef icon = NULL; - FSRef ref; - Boolean gotRef = CFURLGetFSRef(URLToToggle, &ref); - if (gotRef) { - status = GetIconRefFromFileInfo(&ref, - /*fileNameLength*/ 0, /*fileName*/ NULL, - kFSCatInfoNone, /*catalogInfo*/ NULL, - kIconServicesNormalUsageFlag, - &icon, - /*outLabel*/ NULL); - if (status != noErr) - icon = NULL; - } - - LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, (__bridge CFStringRef)displayName, icon, URLToToggle, /*propertiesToSet*/ NULL, /*propertiesToClear*/ NULL); - } else if (!enabled && (existingItem != NULL)) - LSSharedFileListItemRemove(loginItems, existingItem); -} - - -+(void) checkRightStatus:(OSStatus) status -{ - if (status != errAuthorizationSuccess) { - NSAlert *alert = [NSAlert alertWithMessageText:@"Authorization failed" defaultButton:@"Quit" alternateButton:nil otherButton:nil informativeTextWithFormat:[NSString stringWithFormat:@"Authorization failed with code %d",status]]; - [alert setAlertStyle:2]; - NSInteger result = [alert runModal]; + + for (id itemObject in currentLoginItems) { + LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; - if (result == NSAlertDefaultReturn) { - [[NSApplication sharedApplication] terminate:self]; + UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; + CFURLRef URL = NULL; + OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); + if (err == noErr) { + Boolean foundIt = CFEqual(URL, URLToToggle); + CFRelease(URL); + + if (foundIt) { + existingItem = item; + break; + } } } + + if (enabled && (existingItem == NULL)) { + NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:path]; + IconRef icon = NULL; + FSRef ref; + Boolean gotRef = CFURLGetFSRef(URLToToggle, &ref); + if (gotRef) { + status = GetIconRefFromFileInfo(&ref, + /*fileNameLength*/ 0, /*fileName*/ NULL, + kFSCatInfoNone, /*catalogInfo*/ NULL, + kIconServicesNormalUsageFlag, + &icon, + /*outLabel*/ NULL); + if (status != noErr) + icon = NULL; + } + + LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, (__bridge CFStringRef)displayName, icon, URLToToggle, /*propertiesToSet*/ NULL, /*propertiesToClear*/ NULL); + } else if (!enabled && (existingItem != NULL)) + LSSharedFileListItemRemove(loginItems, existingItem); } #pragma mark **SMC-Binary Owner/Right Check** //TODO: It looks like this function is called inefficiently. //call smc binary with sudo rights and apply +(void)setRights{ - NSString *smcpath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; - NSFileManager *fmanage=[NSFileManager defaultManager]; + NSString *smcpath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; + NSFileManager *fmanage=[NSFileManager defaultManager]; NSDictionary *fdic = [fmanage attributesOfItemAtPath:smcpath error:nil]; - if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue]==3437)) { - // If the SMC binary has already been modified to run as root, then do nothing. - return; - } - //TODO: Is the usage of commPipe safe? - FILE *commPipe; - AuthorizationRef authorizationRef; - AuthorizationItem gencitem = { "system.privilege.admin", 0, NULL, 0 }; - AuthorizationRights gencright = { 1, &gencitem }; - int flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed; - OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, flags, &authorizationRef); - - [self checkRightStatus:status]; - - NSString *tool=@"/usr/sbin/chown"; - NSArray *argsArray = @[@"root:admin",smcpath]; - int i; - char *args[255]; - for(i = 0;i < [argsArray count];i++){ - args[i] = (char *)[argsArray[i]cString]; - } - args[i] = NULL; - status=AuthorizationExecuteWithPrivileges(authorizationRef,[tool UTF8String],0,args,&commPipe); - - [self checkRightStatus:status]; - - //second call for suid-bit - tool=@"/bin/chmod"; - argsArray = @[@"6555",smcpath]; - for(i = 0;i < [argsArray count];i++){ - args[i] = (char *)[argsArray[i]cString]; - } - args[i] = NULL; - status=AuthorizationExecuteWithPrivileges(authorizationRef,[tool UTF8String],0,args,&commPipe); - - [self checkRightStatus:status]; + if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue]==3437)) { + // If the SMC binary has already been modified to run as root, then do nothing. + + }else{ + NSString *tool=@"/usr/sbin/chown"; + NSArray *argsArray = @[@"root:admin",smcpath]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + + //second call for suid-bit + tool=@"/bin/chmod"; + argsArray = @[@"6555",smcpath]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + } + + + NSString *modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.64bits" ofType:@"kext"]; + NSString *moduleDstPath = @"/Library/Extensions/DisableTurboBoost.64bits.kext"; + NSFileManager *fileManager = [NSFileManager defaultManager]; + if (![fileManager fileExistsAtPath:moduleDstPath]){ + NSString *tool=@"/bin/sh"; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"cp -R \"%@\" \"%@\"", modulePath, moduleDstPath]]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + } + NSDictionary *fdicKext = [fmanage attributesOfItemAtPath:moduleDstPath error:nil]; + if ([[fdicKext valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdicKext valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"wheel"]) { + // If the SMC binary has already been modified to run as root, then do nothing. + + }else{ + NSString *tool=@"/usr/sbin/chown"; + NSArray *argsArray = @[@"-R", @"root:wheel",moduleDstPath]; + + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + + tool=@"/bin/chmod"; + argsArray = @[@"-Rf", @"755",moduleDstPath]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + } } @@ -911,20 +928,17 @@ -(void)dealloc @end - - - @implementation NSNumber (NumberAdditions) - (NSString*) tohex{ - return [NSString stringWithFormat:@"%0.4x",[self intValue]<<2]; + return [NSString stringWithFormat:@"%0.4x",[self intValue]<<2]; } - (NSNumber*) celsius_fahrenheit{ - float celsius=[self floatValue]; - float fahrenheit=(celsius*9)/5+32; - return @(fahrenheit); + float celsius=[self floatValue]; + float fahrenheit=(celsius*9)/5+32; + return @(fahrenheit); } @end diff --git a/Classes/Privilege.h b/Classes/Privilege.h new file mode 100644 index 0000000..aa520c9 --- /dev/null +++ b/Classes/Privilege.h @@ -0,0 +1,18 @@ +// +// Privilege.h +// smcFanControl +// +// Created by Don Johnny on 2020/5/25. +// + +#ifndef Privilege_h +#define Privilege_h + +#import + +@interface Privilege:NSObject ++(AuthorizationRef) Get; ++(BOOL) runTaskAsAdmin:(NSString *) path andArgs:(NSArray *) args; +@end + +#endif /* Privilege_h */ diff --git a/Classes/Privilege.m b/Classes/Privilege.m new file mode 100644 index 0000000..b89003c --- /dev/null +++ b/Classes/Privilege.m @@ -0,0 +1,56 @@ +// +// Privilege.m +// smcFanControl +// +// Created by Don Johnny on 2020/5/25. +// + +#import +#import "Privilege.h" +#import + +static AuthorizationRef authorizationRef = nil; + +@implementation Privilege ++(AuthorizationRef) Get{ + if (authorizationRef == nil){ + AuthorizationItem gencitem = { "system.privilege.admin", 0, NULL, 0 }; + AuthorizationRights gencright = { 1, &gencitem }; + int flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed; + OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, flags, &authorizationRef); + + if (status != errAuthorizationSuccess){ + NSLog(@"Copy Rights Unsuccessful: %d", status); + authorizationRef = nil; + } + } + return authorizationRef; +} + ++(BOOL) runTaskAsAdmin:(NSString *) path andArgs:(NSArray *) args { + + if ([self Get] == nil) { + return NO; + } + + FILE *myCommunicationsPipe = NULL; + + int count = (int)[args count]; + + char *myArguments[count+1]; + + for (int i=0; i<[args count]; i++) { + myArguments[i] = (char *)[(NSString *)[args objectAtIndex:i] UTF8String]; + } + myArguments[count] = NULL; + + OSStatus resultStatus = AuthorizationExecuteWithPrivileges ([self Get], + [path UTF8String], kAuthorizationFlagDefaults, myArguments, + &myCommunicationsPipe); + + if (resultStatus != errAuthorizationSuccess) + NSLog(@"Error: %d", resultStatus); + + return YES; +} +@end diff --git a/Classes/smcWrapper.m b/Classes/smcWrapper.m index b1fd4eb..a0c67f5 100755 --- a/Classes/smcWrapper.m +++ b/Classes/smcWrapper.m @@ -23,15 +23,17 @@ #import "smcWrapper.h" #import -NSString * const smc_checksum=@"4fc00a0979970ee8b55f078a0c793c4d"; +#import "Privilege.h" + +NSString * const smc_checksum=@"8ab515dbd0f83731306041d96eaff0ac"; NSArray *allSensors; @implementation smcWrapper - io_connect_t conn; +io_connect_t conn; +(void)init{ - SMCOpen(&conn); + SMCOpen(&conn); } +(void)cleanUp{ SMCClose(conn); @@ -40,7 +42,7 @@ +(void)cleanUp{ +(int)convertToNumber:(SMCVal_t) val { float fval = -1.0f; - + if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) { memcpy(&fval,val.bytes,sizeof(float)); } @@ -59,7 +61,7 @@ +(int)convertToNumber:(SMCVal_t) val else { NSLog(@"%@", [NSString stringWithFormat:@"Unknown val:%s size-%d",val.dataType,val.dataSize]); } - + return (int)fval; } @@ -106,12 +108,12 @@ +(float) get_mptemp{ UInt32Char_t keyB; SMCVal_t valA; SMCVal_t valB; - // kern_return_t resultA; - // kern_return_t resultB; + // kern_return_t resultA; + // kern_return_t resultB; sprintf(keyA, "TCAH"); - SMCReadKey2(keyA, &valA,conn); + SMCReadKey2(keyA, &valA,conn); sprintf(keyB, "TCBH"); - SMCReadKey2(keyB, &valB,conn); + SMCReadKey2(keyB, &valB,conn); float c_tempA= [self convertToNumber:valA]; float c_tempB= [self convertToNumber:valB]; int i_tempA, i_tempB; @@ -128,34 +130,34 @@ +(float) get_mptemp{ } +(int) get_fan_rpm:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; - //kern_return_t result; - sprintf(key, "F%dAc", fan_number); - SMCReadKey2(key, &val,conn); - int running= [self convertToNumber:val]; - return running; + UInt32Char_t key; + SMCVal_t val; + //kern_return_t result; + sprintf(key, "F%dAc", fan_number); + SMCReadKey2(key, &val,conn); + int running= [self convertToNumber:val]; + return running; } +(int) get_fan_num{ -// kern_return_t result; + // kern_return_t result; SMCVal_t val; int totalFans; - SMCReadKey2("FNum", &val,conn); + SMCReadKey2("FNum", &val,conn); totalFans = [self convertToNumber:val]; - return totalFans; + return totalFans; } +(NSString*) get_fan_descr:(int)fan_number{ - UInt32Char_t key; - char temp; - SMCVal_t val; - //kern_return_t result; - NSMutableString *desc; - + UInt32Char_t key; + char temp; + SMCVal_t val; + //kern_return_t result; + NSMutableString *desc; + sprintf(key, "F%dID", fan_number); SMCReadKey2(key, &val,conn); - + if(val.dataSize>0){ desc=[[NSMutableString alloc]init]; int i; @@ -170,28 +172,28 @@ +(NSString*) get_fan_descr:(int)fan_number{ //On MacBookPro 15.1 descriptions aren't available desc=[[NSMutableString alloc] initWithFormat:@"Fan #%d: ",fan_number+1]; } - return desc; + return desc; } +(int) get_min_speed:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; - //kern_return_t result; - sprintf(key, "F%dMn", fan_number); - SMCReadKey2(key, &val,conn); - int min= [self convertToNumber:val]; - return min; + UInt32Char_t key; + SMCVal_t val; + //kern_return_t result; + sprintf(key, "F%dMn", fan_number); + SMCReadKey2(key, &val,conn); + int min= [self convertToNumber:val]; + return min; } +(int) get_max_speed:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; - //kern_return_t result; - sprintf(key, "F%dMx", fan_number); - SMCReadKey2(key, &val,conn); - int max= [self convertToNumber:val]; - return max; + UInt32Char_t key; + SMCVal_t val; + //kern_return_t result; + sprintf(key, "F%dMx", fan_number); + SMCReadKey2(key, &val,conn); + int max= [self convertToNumber:val]; + return max; } @@ -237,22 +239,23 @@ + (NSString*)createCheckSum:(NSString*)path { return ret; } -//call smc binary with setuid rights and apply +// call smc binary with setuid rights and apply // The smc binary is given root permissions in FanControl.m with the setRights method. +(void)setKey_external:(NSString *)key value:(NSString *)value{ - NSString *launchPath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; + NSString *launchPath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; - NSString *checksum=[smcWrapper createCheckSum:launchPath]; + NSString *checksum=[smcWrapper createCheckSum:launchPath]; if (![checksum isEqualToString:smc_checksum]) { NSLog(@"smcFanControl: Security Error: smc-binary is not the distributed one"); +#ifdef RELEASE return; +#endif } NSArray *argsArray = @[@"-k",key,@"-w",value]; - NSTask *task; + NSTask *task; task = [[NSTask alloc] init]; - [task setLaunchPath: launchPath]; - [task setArguments: argsArray]; - [task launch]; + [task setLaunchPath: launchPath]; + [task setArguments: argsArray]; + [task launch]; } - @end diff --git a/Info.plist b/Info.plist index 6980b07..41d0213 100644 --- a/Info.plist +++ b/Info.plist @@ -19,11 +19,13 @@ CFBundlePackageType APPL CFBundleShortVersionString - 2.6.1 + $(MARKETING_VERSION) CFBundleSignature ???? CFBundleVersion - 2.6.1 + $(CURRENT_PROJECT_VERSION) + LSApplicationCategoryType + public.app-category.utilities LSUIElement 1 NSHumanReadableCopyright diff --git a/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist b/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist new file mode 100755 index 0000000..909af40 --- /dev/null +++ b/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist @@ -0,0 +1,53 @@ + + + + + BuildMachineOSBuild + 11D17a + CFBundleDevelopmentRegion + English + CFBundleExecutable + DisableTurboBoost + CFBundleIdentifier + com.rugarciap.DisableTurboBoost + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + DisableTurboBoost + CFBundlePackageType + KEXT + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + 0.0.1 + DTCompiler + + DTPlatformBuild + 11D17a + DTPlatformVersion + GM + DTSDKBuild + 11D17a + DTSDKName + + DTXcode + 0410 + DTXcodeBuild + 11D17a + OSBundleAllowUserLoad + + OSBundleLibraries + + com.apple.kpi.bsd + 9.0.0 + com.apple.kpi.libkern + 9.0.0 + com.apple.kpi.mach + 9.0.0 + com.apple.kpi.unsupported + 9.0.0 + + + diff --git a/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost b/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost new file mode 100644 index 0000000000000000000000000000000000000000..ce72c29860989736ac9e0e85c5d593067f76221c GIT binary patch literal 2028 zcma)7Plyv&7=P+$Q`v1&t-6OrbFhaVOxHgM7PMK-to`FqtVs~s_3dnCb~iQ23^Nm5 zgi0ZLcn)3^dXCUT57JW)T1vHSAX2C(c(5Q6MP&{VJgj9YtMT{Eyxp~N)qUj6_xt|; z=9|fz>;FA|{tjbo1@B7UCp5A= z%BP(Em5gm5qr!e5L5uT(RdE-Jbl0H#1mb#7fVeNVP{Z|{Vr5)9yKC5}@dbSSbHrsF z%=3$LL-+J~6}&Qo*}(<CQa6YG5Dj?>G*2kYwf18 zISf}@Lc0?@LhG}=KZ3k?B=QL{)Z?pn#8Ax7wM1TNt_nTc?cgNxFB46n-V)bpjm(kZ zsWDoq_@+}K{iX1mqypXiMu^|W*YF!c#@SwaR*UlsJ>Ylu`4afm+6iBc33XQd8Q&&y z(?WexYb1uJ;+ryzfq$*t2mj@0JhStI)nU689a`lvv9 zK0o1WJ$^1GaMzJj{lWc$fj`3O zt5s#|)#0h(P79_>*D$uwc_{{G6xNutU6}ZPf?%h^=SY_{_SfbXv!aidOe2}CI-^!{ zuVuO3C&>>>rOD)$J)vC9GDY{TF;p=+Pr$cRu*xZ?I<7l~qHd>Te%K*w5Cy;CI*=Mj zZGD6PZ7$-_9n+7YXxOys*iY9nb`o+8W4*^9F)8I+Df5tc_$&87z7PMdNLMyX`$jk^ zZ#^XC&B9LdU+KRKNqPT7y3&yL^N6Rq-%Gg`d`N#L^(1r!zwOIeoz9)zQtp@Xp!EMF z>(-_GS;~u2(oy^#YSQ`!n{XXcmpBdmJBdets}k3NX(klk!agH0&F-AU9|Qj)@h;%M zCEf>2Ck^G&oF5a$&CokLBQd>>E8r)4i3SFH9I+GF^nD;af=%aU98Q|S4q&8&>%dEx z4BUub&6i#+Zcf@}!845^Q}?Ql=`wz_Y#F>*8M7EK+uSiLhI!(cRdspAg4uHrV&fy? zjWO^eJlFdqF!xHro9aYx!@=g>Hp_SK;;@mbt&di$yl+IXKExD>~V zro(u*FK;?-(W)GZK3}i64_La9)yMHQinxHbUMlOw3M@K`N_Z6gxNh4elNSn%y#OVQ B+s^<1 literal 0 HcmV?d00001 diff --git a/Ressources/DisableTurboBoost.64bits.kext/Contents/Info.plist b/Ressources/DisableTurboBoost.64bits.kext/Contents/Info.plist new file mode 100755 index 0000000..909af40 --- /dev/null +++ b/Ressources/DisableTurboBoost.64bits.kext/Contents/Info.plist @@ -0,0 +1,53 @@ + + + + + BuildMachineOSBuild + 11D17a + CFBundleDevelopmentRegion + English + CFBundleExecutable + DisableTurboBoost + CFBundleIdentifier + com.rugarciap.DisableTurboBoost + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + DisableTurboBoost + CFBundlePackageType + KEXT + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + 0.0.1 + DTCompiler + + DTPlatformBuild + 11D17a + DTPlatformVersion + GM + DTSDKBuild + 11D17a + DTSDKName + + DTXcode + 0410 + DTXcodeBuild + 11D17a + OSBundleAllowUserLoad + + OSBundleLibraries + + com.apple.kpi.bsd + 9.0.0 + com.apple.kpi.libkern + 9.0.0 + com.apple.kpi.mach + 9.0.0 + com.apple.kpi.unsupported + 9.0.0 + + + diff --git a/Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost b/Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost new file mode 100755 index 0000000000000000000000000000000000000000..44c6f064488fba3e1b6b77f26d109e398234bb04 GIT binary patch literal 8840 zcmeHN-)kII6uxQGw9zzKe_=$i6Hus1LaL=o!ICsto!D4olZYVUI@z7XwYxj(?2Lv= zix4Xv*FY47`XbRMpQNA&+y4n5#_rRTV zzjMEP?z!LY!pz{cik zQ=V;T^*k)4XHR$=+{%1iP0`q4tW8E(%?$(f;)BrhMaqPe&2J>E%s1T}5mkAFX^+(m z`SPBd%8oOkGT#j6dx^&tR{6MW1)-PymK<}fj2(q4^OZQ?4roh8c(eNGb2yDAWpDRT zH_c#E8?55#bD+Gu4CW^-&r*}C=UY+~YVs!P>G zOro`-8HNz|!ROk5L7?yC02&!dMvdyZ2Ti3$x2g>wPxw7DBL6U$w9Zr4miE8%$${U# zYM5O6eenH#Pa>uyL|2-qF8D>Tmy2{?3+}VHpEC>ovKjn*MufC;#0}z0!J;{N zsdHqmWtXV79^H1*dgN-Yw>#o~O|{+0dcpA<3-MJ<5)1Jaa)p;~v^*WeSA*e|g1=&3 zylV6o;;a3Q^JY*QnHz(3wCwtjn5y2`x<1h6+j6-aDR2(G@&z=rZP5(oi*$F3t;T4p z8}qR~sftxmZpl1LlPI^@Hg6W3u3>~=eAji&9SG32|Wj&aa&^4@;q@pO8^Xg?78yF_m)Uz0;y6XO2JiMnG) zMBPNJF4nYt$21Ci4Dm7j5DWcxmuvnfDCO|G#{n zW9$m^p4)_X9%Ciu^=!iX6JxDw(LSo>Q`41)1cGKHoJ@!7k6UgcW#u|p*HHOTctx-3 zJ3Bf%_Ea6MJwP?oV(q4%3Cv?peRY0thR+fHet@Fdv;tZIt$Gj?(Qfd8i3|6u6}jeMwwWV=3De zvU2P-+s&t(>|pe&#BIa + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme new file mode 100644 index 0000000..5ae4966 --- /dev/null +++ b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 65e9667be6c809f49e48ed278fb17f09a5e9aa22 Mon Sep 17 00:00:00 2001 From: tinkernels Date: Mon, 25 May 2020 22:43:07 +0800 Subject: [PATCH 2/8] Change Extension destination location. --- Classes/FanControl.m | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Classes/FanControl.m b/Classes/FanControl.m index 0a5df0f..2192b98 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -42,7 +42,8 @@ @implementation FanControl // Number of fans reported by the hardware. int g_numFans = 0; -NSString *moduleDstPath = @"/Library/Extensions/DisableTurboBoost.64bits.kext"; +NSString *moduleDstPath = +@"/Library/Application Support/smcFanControl2/DisableTurboBoost.64bits.kext"; NSUserDefaults *defaults; @@ -897,11 +898,10 @@ +(void)setRights{ NSString *modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.64bits" ofType:@"kext"]; - NSString *moduleDstPath = @"/Library/Extensions/DisableTurboBoost.64bits.kext"; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:moduleDstPath]){ NSString *tool=@"/bin/sh"; - NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"cp -R \"%@\" \"%@\"", modulePath, moduleDstPath]]; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@\" \"%@\"",moduleDstPath, modulePath, moduleDstPath]]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } NSDictionary *fdicKext = [fmanage attributesOfItemAtPath:moduleDstPath error:nil]; From 2922a3f98ccc7e2068977da116016ace7397c01e Mon Sep 17 00:00:00 2001 From: tinkernels Date: Tue, 26 May 2020 04:05:49 +0800 Subject: [PATCH 3/8] Add missing files or will fail the signature verification. --- Classes/FanControl.m | 2 +- .../Contents/Info.plist~ | 53 ++++++++++++++++++ .../Contents/MacOS/DisableTurboBoost | Bin 2028 -> 2012 bytes .../Contents/Info.plist~ | 53 ++++++++++++++++++ .../Contents/MacOS/DisableTurboBoost | Bin 8840 -> 8840 bytes 5 files changed, 107 insertions(+), 1 deletion(-) create mode 100755 Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist~ mode change 100644 => 100755 Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost create mode 100755 Ressources/DisableTurboBoost.64bits.kext/Contents/Info.plist~ diff --git a/Classes/FanControl.m b/Classes/FanControl.m index 2192b98..5f0a512 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -901,7 +901,7 @@ +(void)setRights{ NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:moduleDstPath]){ NSString *tool=@"/bin/sh"; - NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@\" \"%@\"",moduleDstPath, modulePath, moduleDstPath]]; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@/\" \"%@\"",moduleDstPath, modulePath, moduleDstPath]]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } NSDictionary *fdicKext = [fmanage attributesOfItemAtPath:moduleDstPath error:nil]; diff --git a/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist~ b/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist~ new file mode 100755 index 0000000..f3e94d6 --- /dev/null +++ b/Ressources/DisableTurboBoost.32bits.kext/Contents/Info.plist~ @@ -0,0 +1,53 @@ + + + + + BuildMachineOSBuild + 11D17a + CFBundleDevelopmentRegion + English + CFBundleExecutable + DisableTurboBoost + CFBundleIdentifier + com.nanoant.DisableTurboBoost + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + DisableTurboBoost + CFBundlePackageType + KEXT + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + 0.0.1 + DTCompiler + + DTPlatformBuild + 11D17a + DTPlatformVersion + GM + DTSDKBuild + 11D17a + DTSDKName + + DTXcode + 0410 + DTXcodeBuild + 11D17a + OSBundleAllowUserLoad + + OSBundleLibraries + + com.apple.kpi.bsd + 9.0.0 + com.apple.kpi.libkern + 9.0.0 + com.apple.kpi.mach + 9.0.0 + com.apple.kpi.unsupported + 9.0.0 + + + diff --git a/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost b/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost old mode 100644 new mode 100755 index ce72c29860989736ac9e0e85c5d593067f76221c..6613f4b6c8233d0c1174a96fac0355ac8ff0e07c GIT binary patch delta 345 zcmaFEe}`Z6+^@I)*cliYn1PrPh?#&mVWOxy@AX@;4zpzf;$fCA+4x;*t}9hCh5$nJu&Wq{UCg0l62>~&DK zC6Ij<%60~_pF!C548B0lTM!56^c0}4e?Zw8KsGbbV32qYkPW05_ + + + + BuildMachineOSBuild + 11D17a + CFBundleDevelopmentRegion + English + CFBundleExecutable + DisableTurboBoost + CFBundleIdentifier + com.nanoant.DisableTurboBoost + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + DisableTurboBoost + CFBundlePackageType + KEXT + CFBundleShortVersionString + 0.0.1 + CFBundleSignature + ???? + CFBundleVersion + 0.0.1 + DTCompiler + + DTPlatformBuild + 11D17a + DTPlatformVersion + GM + DTSDKBuild + 11D17a + DTSDKName + + DTXcode + 0410 + DTXcodeBuild + 11D17a + OSBundleAllowUserLoad + + OSBundleLibraries + + com.apple.kpi.bsd + 9.0.0 + com.apple.kpi.libkern + 9.0.0 + com.apple.kpi.mach + 9.0.0 + com.apple.kpi.unsupported + 9.0.0 + + + diff --git a/Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost b/Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost index 44c6f064488fba3e1b6b77f26d109e398234bb04..37e50d339976e055ae72847ae70cd64bbe06b0ce 100755 GIT binary patch delta 330 zcmeBh?Qq?Yz{JELusMlopKLu70|NseBLjm250C)_oIniXZ-Daop?n2ikSqg(1Q3Jd z6QF!$D1QNzuLI?OfbuPXd^wltF80>MxP)lhy4ls^T^FM;xB zgZQir3?~GD3?Ntr#323!D1RfAe*?-t2;}nveK`ZF{|b~p0nArnV0Z=+02;sm)$kF> f1Um2^kOBiv#>q~KdW;H_4=Wy+T%s7j4iyIg4C)?8 delta 330 zcmXZUFAqUs6bA6edud#n#4v$kf)8LeO);8snIsyOdMBA%M4!NHI#scWK7nQvCG#Af zvz@)?_ntptJ8T~U=R$WJxl?Z02jItmW|9SCz%(D^pYGS_Y!-3^fYjl$MQp-$xm|vxMWx`-c0jN_ITWUm*ecG9kA7YR$l*H2CDYK d1!$qck~cnle$heHD%L#KQN7fSrp2=j179B39@zi@ From 1ea73d07bfd5879fb6e90e36395afeafafdc414e Mon Sep 17 00:00:00 2001 From: tinkernels Date: Tue, 26 May 2020 06:07:56 +0800 Subject: [PATCH 4/8] Restore Trubo Boost setting when wake from sleep. --- Classes/FanControl.m | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Classes/FanControl.m b/Classes/FanControl.m index 5f0a512..e9cbe73 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -764,6 +764,12 @@ -(void) syncBinder:(Boolean)bind{ - (void)systemDidWakeFromSleep:(id)sender{ [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; + + if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState){ + [self enableTurboBoost]; + }else{ + [self disableTurboBoost]; + } } From 4b2e923d5030fc0b0741aeed86bd8194b673e036 Mon Sep 17 00:00:00 2001 From: tinkernels Date: Wed, 27 May 2020 05:08:00 +0800 Subject: [PATCH 5/8] Reformat code. --- .gitignore | 1 + Classes/FanControl.h | 124 +- Classes/FanControl.m | 651 +++++------ Classes/MachineDefaults.h | 13 +- Classes/MachineDefaults.m | 134 +-- Classes/NSFileManager+DirectoryLocations.h | 9 +- Classes/NSFileManager+DirectoryLocations.m | 115 +- Classes/Power.h | 19 +- Classes/Power.m | 205 ++-- Classes/Privilege.h | 7 +- Classes/Privilege.m | 46 +- Classes/StatusItemWindow.m | 4 +- Classes/SystemVersion.h | 18 +- Classes/SystemVersion.m | 233 ++-- Classes/smcWrapper.h | 27 +- Classes/smcWrapper.m | 216 ++-- Info.plist | 72 +- Ressources/Machines.plist | 1144 +++++++++---------- Ressources/com.tinkernels.tb-switcher.plist | 25 + main.m | 8 +- smc-command/smc.c | 377 +++--- smc-command/smc.h | 68 +- smcFanControl.xcodeproj/project.pbxproj | 216 +++- tb-switcher/main.c | 23 + tb-switcher/tb-switcher.h | 21 + tb-switcher/tb-switcher_c.c | 80 ++ tb-switcher/tb-switcher_s.c | 78 ++ 27 files changed, 2145 insertions(+), 1789 deletions(-) create mode 100644 Ressources/com.tinkernels.tb-switcher.plist create mode 100644 tb-switcher/main.c create mode 100644 tb-switcher/tb-switcher.h create mode 100644 tb-switcher/tb-switcher_c.c create mode 100644 tb-switcher/tb-switcher_s.c diff --git a/.gitignore b/.gitignore index f907184..3dfcb68 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /smcFanControl.xcodeproj/project.xcworkspace/xcshareddata/ /smcFanControl.xcodeproj/project.xcworkspace/xcuserdata/ /smcFanControl.xcodeproj/xcuserdata/ +.idea/ \ No newline at end of file diff --git a/Classes/FanControl.h b/Classes/FanControl.h index 0e36e0a..d07395d 100755 --- a/Classes/FanControl.h +++ b/Classes/FanControl.h @@ -37,111 +37,125 @@ #import "Constants.h" -#define kMenuBarHeight 22 +#define kMenuBarHeight 22 -@interface FanControl : NSObject - -{ +@interface FanControl : NSObject { IBOutlet id currentSpeed; - IBOutlet id currentSpeed1; - - IBOutlet id slider1; - IBOutlet id slider2; - - IBOutlet id field1; - IBOutlet id field2; + IBOutlet id currentSpeed1; + + IBOutlet id slider1; + IBOutlet id slider2; + + IBOutlet id field1; + IBOutlet id field2; + + IBOutlet id mainwindow; + + IBOutlet id tabview; + + IBOutlet id applybutton; + + IBOutlet id programinfo; + + IBOutlet id copyright; - IBOutlet id mainwindow; + IBOutlet id syncslider; - IBOutlet id tabview; + IBOutlet id TemperatureController; - IBOutlet id applybutton; + IBOutlet id levelIndicator; - IBOutlet id programinfo; + IBOutlet id newfavoritewindow; - IBOutlet id copyright; + IBOutlet id newfavorite_title; - IBOutlet id syncslider; + IBOutlet id autochange; - IBOutlet id TemperatureController; - IBOutlet id levelIndicator; + IBOutlet NSMenu *theMenu; - IBOutlet id newfavoritewindow; + IBOutlet id faqWindow; - IBOutlet id newfavorite_title; + IBOutlet id faqText; - IBOutlet id autochange; + IBOutlet id sliderCell; + IBOutlet id sync; - IBOutlet NSMenu *theMenu; - - IBOutlet id faqWindow; + IBOutlet id colorSelector; - IBOutlet id faqText; - - IBOutlet id sliderCell; - - IBOutlet id sync; + NSStatusItem *statusItem; - IBOutlet id colorSelector; - - NSStatusItem *statusItem; - - NSMutableArray* s_menus; - - NSTimer *_readTimer; - - Power *pw; - - IBOutlet id FavoritesController; - IBOutlet id FanController; - IBOutlet id DefaultsController; - - MachineDefaults *mdefaults; + NSMutableArray *s_menus; - NSDictionary *undo_dic; - - NSImage *menu_image; - NSImage *menu_image_alt; + NSTimer *_readTimer; + + Power *pw; + + IBOutlet id FavoritesController; + IBOutlet id FanController; + IBOutlet id DefaultsController; + + MachineDefaults *mdefaults; + + NSDictionary *undo_dic; + + NSImage *menu_image; + NSImage *menu_image_alt; } -@property (nonatomic, strong ) NSMutableDictionary *machineDefaultsDict; +@property(nonatomic, strong) NSMutableDictionary *machineDefaultsDict; --(void)terminate:(id)sender; +- (void)terminate:(id)sender; - (IBAction)paypal:(id)sender; + - (IBAction)visitHomepage:(id)sender; - (IBAction)closePreferences:(id)sender; + - (IBAction)savePreferences:(id)sender; + - (IBAction)updateCheck:(id)sender; + - (IBAction)resetSettings:(id)sender; - (void)init_statusitem; //new ones, check old later - (IBAction)loginItem:(id)sender; + - (IBAction)add_favorite:(id)sender; + - (IBAction)close_favorite:(id)sender; + - (IBAction)save_favorite:(id)sender; + - (IBAction)delete_favorite:(id)sender; + - (IBAction)syncSliders:(id)sender; + - (void)apply_quickselect:(id)sender; + - (void)apply_settings:(id)sender controllerindex:(int)cIndex; + + (void)setRights; -- (void) syncBinder:(Boolean)bind; + +- (void)syncBinder:(Boolean)bind; + - (IBAction) changeMenu:(id)sender; + - (IBAction)menuSelect:(id)sender; -- (void)menuNeedsUpdate:(NSMenu*)menu; + +- (void)menuNeedsUpdate:(NSMenu *)menu; @end @interface NSNumber (NumberAdditions) -@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *tohex; -@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSNumber *celsius_fahrenheit; +@property(NS_NONATOMIC_IOSONLY, readonly, copy) NSString *tohex; +@property(NS_NONATOMIC_IOSONLY, readonly, copy) NSNumber *celsius_fahrenheit; @end diff --git a/Classes/FanControl.m b/Classes/FanControl.m index e9cbe73..e1e5303 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -23,17 +23,14 @@ #import "FanControl.h" -#import "MachineDefaults.h" -#import -#import -#import #import -#import "SystemVersion.h" #import "Privilege.h" @interface FanControl () + (void)copyMachinesIfNecessary; -@property (NS_NONATOMIC_IOSONLY, getter=isInAutoStart, readonly) BOOL inAutoStart; + +@property(NS_NONATOMIC_IOSONLY, getter=isInAutoStart, readonly) BOOL inAutoStart; + - (void)setStartAtLogin:(BOOL)enabled; @end @@ -43,205 +40,200 @@ @implementation FanControl int g_numFans = 0; NSString *moduleDstPath = -@"/Library/Application Support/smcFanControl2/DisableTurboBoost.64bits.kext"; + @"/Library/Application Support/smcFanControl2/DisableTurboBoost.64bits.kext"; NSUserDefaults *defaults; #pragma mark **Init-Methods** -+(void) initialize { - ++ (void)initialize { + //avoid Zombies when starting external app signal(SIGCHLD, SIG_IGN); - + [FanControl copyMachinesIfNecessary]; //check owner and suid rights [FanControl setRights]; - + //talk to smc [smcWrapper init]; - + //app in foreground for update notifications [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; - + } -+(void)copyMachinesIfNecessary -{ ++ (void)copyMachinesIfNecessary { NSString *path = [[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { [[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"Machines" ofType:@"plist"] toPath:path error:nil]; } } --(void)upgradeFavorites -{ +- (void)upgradeFavorites { //upgrade favorites NSArray *rfavorites = [FavoritesController arrangedObjects]; int j; int i; - for (i=0;i<[rfavorites count];i++) - { + for (i = 0; i < [rfavorites count]; i++) { BOOL selected = NO; NSArray *fans = rfavorites[i][PREF_FAN_ARRAY]; - for (j=0;j<[fans count];j++) { - if ([fans[j][PREF_FAN_SHOWMENU] boolValue] == YES ) { + for (j = 0; j < [fans count]; j++) { + if ([fans[j][PREF_FAN_SHOWMENU] boolValue] == YES) { selected = YES; } } - if (selected==NO) { + if (selected == NO) { rfavorites[i][PREF_FAN_ARRAY][0][PREF_FAN_SHOWMENU] = @YES; } } - + } --(void) awakeFromNib { - - pw=[[Power alloc] init]; +- (void)awakeFromNib { + + pw = [[Power alloc] init]; [pw setDelegate:self]; [pw registerForSleepWakeNotification]; [pw registerForPowerChange]; - - + + //load defaults - + [DefaultsController setAppliesImmediately:NO]; - - mdefaults=[[MachineDefaults alloc] init:nil]; - - self.machineDefaultsDict=[[NSMutableDictionary alloc] initWithDictionary:[mdefaults get_machine_defaults]]; - + + mdefaults = [[MachineDefaults alloc] init:nil]; + + self.machineDefaultsDict = [[NSMutableDictionary alloc] initWithDictionary:[mdefaults get_machine_defaults]]; + NSMutableArray *favorites = [[NSMutableArray alloc] init]; - + NSMutableDictionary *defaultFav = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Default", PREF_FAN_TITLE, - [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY,nil]; - + [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY, nil]; + [favorites addObject:defaultFav]; - - - NSRange range=[[MachineDefaults computerModel] rangeOfString:@"MacBook"]; - if (range.length>0) { + + + NSRange range = [[MachineDefaults computerModel] rangeOfString:@"MacBook"]; + if (range.length > 0) { //for macbooks add a second default - NSMutableDictionary *higherFav=[[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Higher RPM", PREF_FAN_TITLE, - [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY,nil]; - for (NSUInteger i=0;i<[_machineDefaultsDict[@"Fans"] count];i++) { - - int min_value=([[[[_machineDefaultsDict objectForKey:@"Fans"] objectAtIndex:i] objectForKey:PREF_FAN_MINSPEED] intValue])*2; + NSMutableDictionary *higherFav = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"Higher RPM", PREF_FAN_TITLE, + [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:[[mdefaults get_machine_defaults] objectForKey:@"Fans"]]], PREF_FAN_ARRAY, nil]; + for (NSUInteger i = 0; i < [_machineDefaultsDict[@"Fans"] count]; i++) { + + int min_value = ([[[[_machineDefaultsDict objectForKey:@"Fans"] objectAtIndex:i] objectForKey:PREF_FAN_MINSPEED] intValue]) * 2; [[[higherFav objectForKey:PREF_FAN_ARRAY] objectAtIndex:i] setObject:[NSNumber numberWithInt:min_value] forKey:PREF_FAN_SELSPEED]; } [favorites addObject:higherFav]; - + } - + //sync option for Macbook Pro's - NSRange range_mbp=[[MachineDefaults computerModel] rangeOfString:@"MacBookPro"]; - if (range_mbp.length>0 && [_machineDefaultsDict[@"Fans"] count] == 2) { + NSRange range_mbp = [[MachineDefaults computerModel] rangeOfString:@"MacBookPro"]; + if (range_mbp.length > 0 && [_machineDefaultsDict[@"Fans"] count] == 2) { [sync setHidden:NO]; } - + //load user defaults defaults = [NSUserDefaults standardUserDefaults]; [defaults registerDefaults: - [NSMutableDictionary dictionaryWithObjectsAndKeys: - @0, PREF_TEMP_UNIT, - @0, PREF_SELECTION_DEFAULT, - @NO,PREF_AUTOSTART_ENABLED, - @NO,PREF_AUTOMATIC_CHANGE, - @0, PREF_BATTERY_SELECTION, - @0, PREF_AC_SELECTION, - @0, PREF_CHARGING_SELECTION, - @0, PREF_MENU_DISPLAYMODE, - @"TC0D",PREF_TEMPERATURE_SENSOR, - @0, PREF_NUMBEROF_LAUNCHES, - @NO,PREF_DONATIONMESSAGE_DISPLAY, - [NSArchiver archivedDataWithRootObject:[NSColor blackColor]],PREF_MENU_TEXTCOLOR, - favorites,PREF_FAVORITES_ARRAY, - nil]]; - - - + [NSMutableDictionary dictionaryWithObjectsAndKeys: + @0, PREF_TEMP_UNIT, + @0, PREF_SELECTION_DEFAULT, + @NO, PREF_AUTOSTART_ENABLED, + @NO, PREF_AUTOMATIC_CHANGE, + @0, PREF_BATTERY_SELECTION, + @0, PREF_AC_SELECTION, + @0, PREF_CHARGING_SELECTION, + @0, PREF_MENU_DISPLAYMODE, + @"TC0D", PREF_TEMPERATURE_SENSOR, + @0, PREF_NUMBEROF_LAUNCHES, + @NO, PREF_DONATIONMESSAGE_DISPLAY, + [NSArchiver archivedDataWithRootObject:[NSColor blackColor]], PREF_MENU_TEXTCOLOR, + favorites, PREF_FAVORITES_ARRAY, + nil]]; + + g_numFans = [smcWrapper get_fan_num]; - s_menus=[[NSMutableArray alloc] init]; + s_menus = [[NSMutableArray alloc] init]; int i; - for(i=0;i0) { + if (range.length > 0) { [autochange setEnabled:true]; } else { [autochange setEnabled:false]; } - [faqText replaceCharactersInRange:NSMakeRange(0,0) withRTF: [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"F.A.Q" ofType:@"rtf"]]]; + [faqText replaceCharactersInRange:NSMakeRange(0, 0) withRTF:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"F.A.Q" ofType:@"rtf"]]]; [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; [[[[theMenu itemWithTag:1] submenu] itemAtIndex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]] setState:NSOnState]; [[sliderCell dataCell] setControlSize:NSSmallControlSize]; [self changeMenu:nil]; - + //seting toolbar image menu_image = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"smc" ofType:@"png"]]; - menu_image_alt = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"smcover" ofType:@"png"]]; + menu_image_alt = [[NSImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"smcover" ofType:@"png"]]; if ([menu_image respondsToSelector:@selector(setTemplate:)]) { [menu_image setTemplate:YES]; [menu_image_alt setTemplate:YES]; } - + //add timer for reading to RunLoop _readTimer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(readFanData:) userInfo:nil repeats:YES]; if ([_readTimer respondsToSelector:@selector(setTolerance:)]) { [_readTimer setTolerance:2.0]; } [_readTimer fire]; - + //autoapply settings if valid [self upgradeFavorites]; - + //autostart [[NSUserDefaults standardUserDefaults] setValue:@([self isInAutoStart]) forKey:PREF_AUTOSTART_ENABLED]; NSUInteger numLaunches = [[[NSUserDefaults standardUserDefaults] objectForKey:PREF_NUMBEROF_LAUNCHES] integerValue]; - [[NSUserDefaults standardUserDefaults] setObject:@(numLaunches+1) forKey:PREF_NUMBEROF_LAUNCHES]; + [[NSUserDefaults standardUserDefaults] setObject:@(numLaunches + 1) forKey:PREF_NUMBEROF_LAUNCHES]; if (numLaunches != 0 && (numLaunches % 3 == 0) && ![[[NSUserDefaults standardUserDefaults] objectForKey:PREF_DONATIONMESSAGE_DISPLAY] boolValue]) { [self displayDonationMessage]; } - + [[NSDistributedNotificationCenter defaultCenter] addObserver:self selector:@selector(readFanData:) name:@"AppleInterfaceThemeChangedNotification" object:nil]; - + } --(void)displayDonationMessage -{ - NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Consider a donation",nil) - defaultButton:NSLocalizedString(@"Donate over Paypal",nil) alternateButton:NSLocalizedString(@"Never ask me again",nil) otherButton:NSLocalizedString(@"Remind me later",nil) - informativeTextWithFormat:NSLocalizedString(@"smcFanControl keeps your Mac cool since 2006.\n\nIf smcFanControl is helfpul for you and you want to support further development, a small donation over Paypal is much appreciated.",nil)]; - NSModalResponse code=[alert runModal]; +- (void)displayDonationMessage { + NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Consider a donation", nil) + defaultButton:NSLocalizedString(@"Donate over Paypal", nil) alternateButton:NSLocalizedString(@"Never ask me again", nil) otherButton:NSLocalizedString(@"Remind me later", nil) + informativeTextWithFormat:NSLocalizedString(@"smcFanControl keeps your Mac cool since 2006.\n\nIf smcFanControl is helfpul for you and you want to support further development, a small donation over Paypal is much appreciated.", nil)]; + NSModalResponse code = [alert runModal]; if (code == NSAlertDefaultReturn) { [self paypal:nil]; [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:PREF_DONATIONMESSAGE_DISPLAY]; @@ -250,54 +242,54 @@ -(void)displayDonationMessage } } --(void) enableTurboBoost{ +- (void)enableTurboBoost { [Privilege runTaskAsAdmin:@"/sbin/kextunload" andArgs:@[moduleDstPath]]; } --(void) disableTurboBoost{ - NSArray *argsArrayLoadKext = @[@"-v",moduleDstPath]; +- (void)disableTurboBoost { + NSArray *argsArrayLoadKext = @[@"-v", moduleDstPath]; [Privilege runTaskAsAdmin:@"/usr/bin/kextutil" andArgs:argsArrayLoadKext]; } --(void)applyTurboBoost:(id)sender{ +- (void)applyTurboBoost:(id)sender { NSControlStateValue state = [sender state]; - if (state == NSOffState){ + if (state == NSOffState) { [sender setState:NSOnState]; [self enableTurboBoost]; - }else{ + } else { [sender setState:NSOffState]; [self disableTurboBoost]; } } --(void)init_statusitem{ - statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength: NSVariableStatusItemLength]; - [statusItem setMenu: theMenu]; - +- (void)init_statusitem { + statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSVariableStatusItemLength]; + [statusItem setMenu:theMenu]; + if ([statusItem respondsToSelector:@selector(button)]) { [statusItem.button setTitle:@"smc..."]; } else { - [statusItem setEnabled: YES]; + [statusItem setEnabled:YES]; [statusItem setHighlightMode:YES]; [statusItem setTitle:@"smc..."]; } int i; - for(i=0;i<[s_menus count];i++) { + for (i = 0; i < [s_menus count]; i++) { [theMenu insertItem:s_menus[i] atIndex:i]; }; - + [self disableTurboBoost]; NSMenuItem *fan1Item = [theMenu itemWithTitle:@"Fan: 1"]; int fan1ItemIdx = [theMenu indexOfItem:fan1Item]; NSMenuItem *turboBoostItem = [[NSMenuItem alloc] - initWithTitle:@"Turbo Boost" - action:@selector(applyTurboBoost:) - keyEquivalent:@""]; + initWithTitle:@"Turbo Boost" + action:@selector(applyTurboBoost:) + keyEquivalent:@""]; [turboBoostItem setState:NSOffState]; [turboBoostItem setEnabled:true]; [turboBoostItem setTarget:self]; [theMenu insertItem:turboBoostItem atIndex:fan1ItemIdx + 1]; - + // Sign up for menuNeedsUpdate call // so that the fan speeds in the menu can be updated // only when needed. @@ -305,33 +297,33 @@ -(void)init_statusitem{ } - #pragma mark **Action-Methods** -- (IBAction)loginItem:(id)sender{ - if ([sender state]==NSOnState) { + +- (IBAction)loginItem:(id)sender { + if ([sender state] == NSOnState) { [self setStartAtLogin:YES]; } else { [self setStartAtLogin:NO]; } } -- (IBAction)add_favorite:(id)sender{ +- (IBAction)add_favorite:(id)sender { [[NSApplication sharedApplication] beginSheet:newfavoritewindow - modalForWindow: mainwindow - modalDelegate: nil - didEndSelector: nil - contextInfo: nil]; + modalForWindow:mainwindow + modalDelegate:nil + didEndSelector:nil + contextInfo:nil]; } -- (IBAction)close_favorite:(id)sender{ +- (IBAction)close_favorite:(id)sender { [newfavoritewindow close]; [[NSApplication sharedApplication] endSheet:newfavoritewindow]; } -- (IBAction)save_favorite:(id)sender{ - MachineDefaults *msdefaults=[[MachineDefaults alloc] init:nil]; - if ([[newfavorite_title stringValue] length]>0) { - NSMutableDictionary *toinsert=[[NSMutableDictionary alloc] initWithObjectsAndKeys:[newfavorite_title stringValue],@"Title",[msdefaults get_machine_defaults][@"Fans"],PREF_FAN_ARRAY,nil]; //default as template +- (IBAction)save_favorite:(id)sender { + MachineDefaults *msdefaults = [[MachineDefaults alloc] init:nil]; + if ([[newfavorite_title stringValue] length] > 0) { + NSMutableDictionary *toinsert = [[NSMutableDictionary alloc] initWithObjectsAndKeys:[newfavorite_title stringValue], @"Title", [msdefaults get_machine_defaults][@"Fans"], PREF_FAN_ARRAY, nil]; //default as template [toinsert setValue:@0 forKey:@"Standard"]; [FavoritesController addObject:toinsert]; [newfavoritewindow close]; @@ -341,15 +333,14 @@ - (IBAction)save_favorite:(id)sender{ } --(void) check_deletion:(id)combo{ - if ([FavoritesController selectionIndex]==[[defaults objectForKey:combo] intValue]) { +- (void)check_deletion:(id)combo { + if ([FavoritesController selectionIndex] == [[defaults objectForKey:combo] intValue]) { [defaults setObject:@0 forKey:combo]; } } -- (void) deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; -{ - if (returnCode==0) { +- (void)deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo; { + if (returnCode == 0) { //delete favorite, but resets presets before [self check_deletion:PREF_BATTERY_SELECTION]; [self check_deletion:PREF_AC_SELECTION]; @@ -358,26 +349,25 @@ - (void) deleteAlertDidEnd:(NSAlert *)alert returnCode:(NSInteger)returnCode con } } -- (IBAction)delete_favorite:(id)sender{ - - NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Delete favorite",nil) defaultButton:NSLocalizedString(@"No",nil) alternateButton:NSLocalizedString(@"Yes",nil) otherButton:nil informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"Do you really want to delete the favorite %@?",nil), [FavoritesController arrangedObjects][[FavoritesController selectionIndex]][@"Title"] ]]; - +- (IBAction)delete_favorite:(id)sender { + + NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Delete favorite", nil) defaultButton:NSLocalizedString(@"No", nil) alternateButton:NSLocalizedString(@"Yes", nil) otherButton:nil informativeTextWithFormat:[NSString stringWithFormat:NSLocalizedString(@"Do you really want to delete the favorite %@?", nil), [FavoritesController arrangedObjects][[FavoritesController selectionIndex]][@"Title"]]]; + [alert beginSheetModalForWindow:mainwindow modalDelegate:self didEndSelector:@selector(deleteAlertDidEnd:returnCode:contextInfo:) contextInfo:NULL]; } - // Called via a timer mechanism. This is where all the temp / RPM reading is done. //reads fan data and updates the gui --(void) readFanData:(id)caller{ - +- (void)readFanData:(id)caller { + int i = 0; - + //on init handling - if (_machineDefaultsDict==nil) { + if (_machineDefaultsDict == nil) { return; } - + // Determine what data is actually needed to keep the energy impact // as low as possible. bool bNeedTemp = false; @@ -389,100 +379,100 @@ -(void) readFanData:(id)caller{ bNeedTemp = true; bNeedRpm = true; break; - + case 2: bNeedTemp = true; bNeedRpm = true; break; - + case 3: bNeedTemp = true; bNeedRpm = false; break; - + case 4: bNeedTemp = false; bNeedRpm = true; break; } - + NSString *temp = nil; NSString *fan = nil; float c_temp = 0.0f; int selectedRpm = 0; - + if (bNeedRpm == true) { // Read the current fan speed for the desired fan and format text for display in the menubar. NSArray *fans = [FavoritesController arrangedObjects][[FavoritesController selectionIndex]][PREF_FAN_ARRAY]; - for (i=0; i1 ) { - if (bind==YES) { + if ([[FanController arrangedObjects] count] > 1) { + if (bind == YES) { [[FanController arrangedObjects][1] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][0] withKeyPath:PREF_FAN_SELSPEED options:nil]; [[FanController arrangedObjects][0] bind:PREF_FAN_SELSPEED toObject:[FanController arrangedObjects][1] withKeyPath:PREF_FAN_SELSPEED options:nil]; } else { @@ -762,35 +746,35 @@ -(void) syncBinder:(Boolean)bind{ #pragma mark **Power Watchdog-Methods** -- (void)systemDidWakeFromSleep:(id)sender{ +- (void)systemDidWakeFromSleep:(id)sender { [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; - - if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState){ + + if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState) { [self enableTurboBoost]; - }else{ + } else { [self disableTurboBoost]; } } -- (void)powerChangeToBattery:(id)sender{ - - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { +- (void)powerChangeToBattery:(id)sender { + + if ([[defaults objectForKey:@"AutomaticChange"] boolValue] == YES) { [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_BATTERY_SELECTION] intValue]]; } } -- (void)powerChangeToAC:(id)sender{ - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { +- (void)powerChangeToAC:(id)sender { + if ([[defaults objectForKey:@"AutomaticChange"] boolValue] == YES) { [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_AC_SELECTION] intValue]]; - + } } -- (void)powerChangeToACLoading:(id)sender{ - if ([[defaults objectForKey:@"AutomaticChange"] boolValue]==YES) { +- (void)powerChangeToACLoading:(id)sender { + if ([[defaults objectForKey:@"AutomaticChange"] boolValue] == YES) { [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_CHARGING_SELECTION] intValue]]; - + } } @@ -798,27 +782,26 @@ - (void)powerChangeToACLoading:(id)sender{ #pragma mark - #pragma mark Start-at-login control -- (BOOL)isInAutoStart -{ +- (BOOL)isInAutoStart { BOOL found = NO; LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); NSString *path = [[NSBundle mainBundle] bundlePath]; - CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; + CFURLRef URLToToggle = (__bridge CFURLRef) [NSURL fileURLWithPath:path]; //LSSharedFileListItemRef existingItem = NULL; - + UInt32 seed = 0U; NSArray *currentLoginItems = CFBridgingRelease(LSSharedFileListCopySnapshot(loginItems, &seed)); - + for (id itemObject in currentLoginItems) { - LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; - + LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef) itemObject; + UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef URL = NULL; OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); if (err == noErr) { Boolean foundIt = CFEqual(URL, URLToToggle); CFRelease(URL); - + if (foundIt) { //existingItem = item; found = YES; @@ -829,37 +812,37 @@ - (BOOL)isInAutoStart return found; } -- (void) setStartAtLogin:(BOOL)enabled { - +- (void)setStartAtLogin:(BOOL)enabled { + LSSharedFileListRef loginItems = LSSharedFileListCreate(kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, /*options*/ NULL); - - + + NSString *path = [[NSBundle mainBundle] bundlePath]; - + OSStatus status; - CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; + CFURLRef URLToToggle = (__bridge CFURLRef) [NSURL fileURLWithPath:path]; LSSharedFileListItemRef existingItem = NULL; - + UInt32 seed = 0U; NSArray *currentLoginItems = CFBridgingRelease(LSSharedFileListCopySnapshot(loginItems, &seed)); - + for (id itemObject in currentLoginItems) { - LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef)itemObject; - + LSSharedFileListItemRef item = (__bridge LSSharedFileListItemRef) itemObject; + UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef URL = NULL; OSStatus err = LSSharedFileListItemResolve(item, resolutionFlags, &URL, /*outRef*/ NULL); if (err == noErr) { Boolean foundIt = CFEqual(URL, URLToToggle); CFRelease(URL); - + if (foundIt) { existingItem = item; break; } } } - + if (enabled && (existingItem == NULL)) { NSString *displayName = [[NSFileManager defaultManager] displayNameAtPath:path]; IconRef icon = NULL; @@ -867,68 +850,68 @@ - (void) setStartAtLogin:(BOOL)enabled { Boolean gotRef = CFURLGetFSRef(URLToToggle, &ref); if (gotRef) { status = GetIconRefFromFileInfo(&ref, - /*fileNameLength*/ 0, /*fileName*/ NULL, - kFSCatInfoNone, /*catalogInfo*/ NULL, - kIconServicesNormalUsageFlag, - &icon, - /*outLabel*/ NULL); + /*fileNameLength*/ 0, /*fileName*/ NULL, + kFSCatInfoNone, /*catalogInfo*/ NULL, + kIconServicesNormalUsageFlag, + &icon, + /*outLabel*/ NULL); if (status != noErr) icon = NULL; } - - LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, (__bridge CFStringRef)displayName, icon, URLToToggle, /*propertiesToSet*/ NULL, /*propertiesToClear*/ NULL); + + LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, (__bridge CFStringRef) displayName, icon, URLToToggle, /*propertiesToSet*/ NULL, /*propertiesToClear*/ NULL); } else if (!enabled && (existingItem != NULL)) LSSharedFileListItemRemove(loginItems, existingItem); } #pragma mark **SMC-Binary Owner/Right Check** + //TODO: It looks like this function is called inefficiently. //call smc binary with sudo rights and apply -+(void)setRights{ - NSString *smcpath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; - NSFileManager *fmanage=[NSFileManager defaultManager]; ++ (void)setRights { + NSString *smcpath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; + NSFileManager *fmanage = [NSFileManager defaultManager]; NSDictionary *fdic = [fmanage attributesOfItemAtPath:smcpath error:nil]; - if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue]==3437)) { + if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue] == 3437)) { // If the SMC binary has already been modified to run as root, then do nothing. - - }else{ - NSString *tool=@"/usr/sbin/chown"; - NSArray *argsArray = @[@"root:admin",smcpath]; + + } else { + NSString *tool = @"/usr/sbin/chown"; + NSArray *argsArray = @[@"root:admin", smcpath]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; - + //second call for suid-bit - tool=@"/bin/chmod"; - argsArray = @[@"6555",smcpath]; + tool = @"/bin/chmod"; + argsArray = @[@"6555", smcpath]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } - - + + NSString *modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.64bits" ofType:@"kext"]; NSFileManager *fileManager = [NSFileManager defaultManager]; - if (![fileManager fileExistsAtPath:moduleDstPath]){ - NSString *tool=@"/bin/sh"; - NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@/\" \"%@\"",moduleDstPath, modulePath, moduleDstPath]]; + if (![fileManager fileExistsAtPath:moduleDstPath]) { + NSString *tool = @"/bin/sh"; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@/\" \"%@\"", moduleDstPath, modulePath, moduleDstPath]]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } NSDictionary *fdicKext = [fmanage attributesOfItemAtPath:moduleDstPath error:nil]; if ([[fdicKext valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdicKext valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"wheel"]) { // If the SMC binary has already been modified to run as root, then do nothing. - - }else{ - NSString *tool=@"/usr/sbin/chown"; - NSArray *argsArray = @[@"-R", @"root:wheel",moduleDstPath]; - + + } else { + NSString *tool = @"/usr/sbin/chown"; + NSArray *argsArray = @[@"-R", @"root:wheel", moduleDstPath]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; - - tool=@"/bin/chmod"; - argsArray = @[@"-Rf", @"755",moduleDstPath]; + + tool = @"/bin/chmod"; + argsArray = @[@"-Rf", @"755", moduleDstPath]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } } --(void)dealloc -{ +- (void)dealloc { [[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; } @@ -936,14 +919,14 @@ -(void)dealloc @implementation NSNumber (NumberAdditions) -- (NSString*) tohex{ - return [NSString stringWithFormat:@"%0.4x",[self intValue]<<2]; +- (NSString *)tohex { + return [NSString stringWithFormat:@"%0.4x", [self intValue] << 2]; } -- (NSNumber*) celsius_fahrenheit{ - float celsius=[self floatValue]; - float fahrenheit=(celsius*9)/5+32; +- (NSNumber *)celsius_fahrenheit { + float celsius = [self floatValue]; + float fahrenheit = (celsius * 9) / 5 + 32; return @(fahrenheit); } diff --git a/Classes/MachineDefaults.h b/Classes/MachineDefaults.h index 1a89280..a7051a5 100644 --- a/Classes/MachineDefaults.h +++ b/Classes/MachineDefaults.h @@ -24,15 +24,16 @@ @interface MachineDefaults : NSObject { - NSString *machine; - NSArray *supported_machines; - Boolean supported; - int machine_num; + NSString *machine; + NSArray *supported_machines; + Boolean supported; + int machine_num; } + (NSString *)computerModel; -- (instancetype)init:(NSString*)p_machine ; -@property (NS_NONATOMIC_IOSONLY, getter=get_machine_defaults, readonly, copy) NSDictionary *_machine_defaults; +- (instancetype)init:(NSString *)p_machine; + +@property(NS_NONATOMIC_IOSONLY, getter=get_machine_defaults, readonly, copy) NSDictionary *_machine_defaults; @end diff --git a/Classes/MachineDefaults.m b/Classes/MachineDefaults.m index a798f9e..2190822 100644 --- a/Classes/MachineDefaults.m +++ b/Classes/MachineDefaults.m @@ -23,116 +23,108 @@ #import "MachineDefaults.h" #import "NSFileManager+DirectoryLocations.h" -@interface MachineDefaults () -{ - +@interface MachineDefaults () { + } @end @implementation MachineDefaults -- (instancetype)init:(NSString*)p_machine{ - if (self = [super init]){ - machine=[MachineDefaults computerModel]; +- (instancetype)init:(NSString *)p_machine { + if (self = [super init]) { + machine = [MachineDefaults computerModel]; [self refreshPlist]; } - return self; + return self; } --(void)refreshPlist -{ - supported_machines=[[NSArray alloc] initWithContentsOfFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]]; - supported=NO; +- (void)refreshPlist { + supported_machines = [[NSArray alloc] initWithContentsOfFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]]; + supported = NO; int i; - for(i=0;i<[supported_machines count];i++) { + for (i = 0; i < [supported_machines count]; i++) { if ([machine isEqualToString:supported_machines[i][@"Machine"]]) { - supported=YES; - machine_num=i; + supported = YES; + machine_num = i; } } } --(NSDictionary*) readFromPlist{ - if (!supported) {return nil;} - return supported_machines[machine_num]; +- (NSDictionary *)readFromPlist { + if (!supported) {return nil;} + return supported_machines[machine_num]; } - --(void) readFromSMC{ - NSUInteger num_fans=[smcWrapper get_fan_num]; - NSString *desc; - NSNumber *min,*max; - NSData *xmldata; - NSString *error; - NSMutableArray *fans=[[NSMutableArray alloc] init]; - for (NSUInteger i = 0; i < num_fans; i++) { - min=@([smcWrapper get_min_speed:i]); - max=@([smcWrapper get_max_speed:i]); - desc=[smcWrapper get_fan_descr:i]; - [fans addObject:[[NSMutableDictionary alloc] initWithDictionary:@{@"Description": desc,@"Minspeed": min,@"Maxspeed": max,@"selspeed": min}]]; - } - //save to plist for future - NSMutableArray *supported_m=[[NSMutableArray alloc] initWithContentsOfFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]]; +- (void)readFromSMC { + NSUInteger num_fans = [smcWrapper get_fan_num]; + NSString *desc; + NSNumber *min, *max; + NSData *xmldata; + NSString *error; + NSMutableArray *fans = [[NSMutableArray alloc] init]; + for (NSUInteger i = 0; i < num_fans; i++) { + min = @([smcWrapper get_min_speed:i]); + max = @([smcWrapper get_max_speed:i]); + desc = [smcWrapper get_fan_descr:i]; + [fans addObject:[[NSMutableDictionary alloc] initWithDictionary:@{@"Description": desc, @"Minspeed": min, @"Maxspeed": max, @"selspeed": min}]]; + } + //save to plist for future + NSMutableArray *supported_m = [[NSMutableArray alloc] initWithContentsOfFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"]]; NSMutableDictionary *new_machine; - if (fans == nil) - { - new_machine= [[NSMutableDictionary alloc] initWithDictionary:@{@"Fans": [NSNull null],@"NumFans": @(0),@"Machine": machine,@"Comment": @"Autogenerated",@"Minspeed": min,@"Maxspeed": max}]; - + if (fans == nil) { + new_machine = [[NSMutableDictionary alloc] initWithDictionary:@{@"Fans": [NSNull null], @"NumFans": @(0), @"Machine": machine, @"Comment": @"Autogenerated", @"Minspeed": min, @"Maxspeed": max}]; + } else { - new_machine= [[NSMutableDictionary alloc] initWithDictionary:@{@"Fans": fans,@"NumFans": @(num_fans),@"Machine": machine,@"Comment": @"Autogenerated",@"Minspeed": min,@"Maxspeed": max}]; + new_machine = [[NSMutableDictionary alloc] initWithDictionary:@{@"Fans": fans, @"NumFans": @(num_fans), @"Machine": machine, @"Comment": @"Autogenerated", @"Minspeed": min, @"Maxspeed": max}]; } - [supported_m addObject:new_machine]; - - //save to plist - xmldata = [NSPropertyListSerialization dataFromPropertyList:supported_m - format:NSPropertyListXMLFormat_v1_0 - errorDescription:&error]; - [xmldata writeToFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"] atomically:YES]; -} + [supported_m addObject:new_machine]; + //save to plist + xmldata = [NSPropertyListSerialization dataFromPropertyList:supported_m + format:NSPropertyListXMLFormat_v1_0 + errorDescription:&error]; + [xmldata writeToFile:[[[NSFileManager defaultManager] applicationSupportDirectory] stringByAppendingPathComponent:@"Machines.plist"] atomically:YES]; +} +- (NSDictionary *)get_machine_defaults { --(NSDictionary*)get_machine_defaults{ - if (!supported) { - NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Alert!",nil) - defaultButton:NSLocalizedString(@"Continue",nil) alternateButton:NSLocalizedString(@"Quit",nil) otherButton:nil - informativeTextWithFormat:NSLocalizedString(@"smcFanControl has not been tested on this machine yet, but it should run if you follow the instructions. \n\nIf you choose to continue, please make you have no other FanControl-software running. Otherwise please quit, deinstall the other software, restart your machine and rerun smcFanControl!",nil)]; - NSModalResponse code=[alert runModal]; - if (code == NSAlertDefaultReturn) { - [self readFromSMC]; + NSAlert *alert = [NSAlert alertWithMessageText:NSLocalizedString(@"Alert!", nil) + defaultButton:NSLocalizedString(@"Continue", nil) alternateButton:NSLocalizedString(@"Quit", nil) otherButton:nil + informativeTextWithFormat:NSLocalizedString(@"smcFanControl has not been tested on this machine yet, but it should run if you follow the instructions. \n\nIf you choose to continue, please make you have no other FanControl-software running. Otherwise please quit, deinstall the other software, restart your machine and rerun smcFanControl!", nil)]; + NSModalResponse code = [alert runModal]; + if (code == NSAlertDefaultReturn) { + [self readFromSMC]; [self refreshPlist]; - } else { - [[NSApplication sharedApplication] terminate:nil]; - } - - } - - NSDictionary *defaultsDict=[self readFromPlist]; + } else { + [[NSApplication sharedApplication] terminate:nil]; + } + + } + + NSDictionary *defaultsDict = [self readFromPlist]; NSUInteger i; //localize fan-descriptions - for (i=0;i<[defaultsDict[@"Fans"] count];i++) { - NSString *newvalue=NSLocalizedString(defaultsDict[@"Fans"][i][@"Description"],nil); + for (i = 0; i < [defaultsDict[@"Fans"] count]; i++) { + NSString *newvalue = NSLocalizedString(defaultsDict[@"Fans"][i][@"Description"], nil); [defaultsDict[@"Fans"][i] setValue:newvalue forKey:@"Description"]; } - - return defaultsDict; + + return defaultsDict; } -+ (NSString *)computerModel -{ ++ (NSString *)computerModel { static NSString *computerModel = nil; if (!computerModel) { io_service_t pexpdev; - if ((pexpdev = IOServiceGetMatchingService (kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")))) - { + if ((pexpdev = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice")))) { NSData *data; - if ((data = (id)CFBridgingRelease(IORegistryEntryCreateCFProperty(pexpdev, CFSTR("model"), kCFAllocatorDefault, 0)))) { - computerModel = [[NSString allocWithZone:NULL] initWithCString:[data bytes] encoding:NSASCIIStringEncoding]; + if ((data = (id) CFBridgingRelease(IORegistryEntryCreateCFProperty(pexpdev, CFSTR("model"), kCFAllocatorDefault, 0)))) { + computerModel = [[NSString allocWithZone:NULL] initWithCString:[data bytes] encoding:NSASCIIStringEncoding]; } } } diff --git a/Classes/NSFileManager+DirectoryLocations.h b/Classes/NSFileManager+DirectoryLocations.h index 72a0084..1fc6849 100644 --- a/Classes/NSFileManager+DirectoryLocations.h +++ b/Classes/NSFileManager+DirectoryLocations.h @@ -28,9 +28,10 @@ @interface NSFileManager (DirectoryLocations) - (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory - inDomain:(NSSearchPathDomainMask)domainMask - appendPathComponent:(NSString *)appendComponent - error:(NSError **)errorOut; -@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSString *applicationSupportDirectory; + inDomain:(NSSearchPathDomainMask)domainMask + appendPathComponent:(NSString *)appendComponent + error:(NSError **)errorOut; + +@property(NS_NONATOMIC_IOSONLY, readonly, copy) NSString *applicationSupportDirectory; @end diff --git a/Classes/NSFileManager+DirectoryLocations.m b/Classes/NSFileManager+DirectoryLocations.m index 1b57ecd..4b4743e 100644 --- a/Classes/NSFileManager+DirectoryLocations.m +++ b/Classes/NSFileManager+DirectoryLocations.m @@ -21,13 +21,12 @@ #import "NSFileManager+DirectoryLocations.h" -enum -{ - DirectoryLocationErrorNoPathFound, - DirectoryLocationErrorFileExistsAtLocation +enum { + DirectoryLocationErrorNoPathFound, + DirectoryLocationErrorFileExistsAtLocation }; - -NSString * const DirectoryLocationDomain = @"DirectoryLocationDomain"; + +NSString *const DirectoryLocationDomain = @"DirectoryLocationDomain"; @implementation NSFileManager (DirectoryLocations) @@ -47,57 +46,53 @@ @implementation NSFileManager (DirectoryLocations) * \returns returns the path to the directory (if path found and exists), nil otherwise */ - (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory - inDomain:(NSSearchPathDomainMask)domainMask - appendPathComponent:(NSString *)appendComponent - error:(NSError **)errorOut -{ + inDomain:(NSSearchPathDomainMask)domainMask + appendPathComponent:(NSString *)appendComponent + error:(NSError **)errorOut { // Declare an NSError first, so we don't need to check errorOut again and again NSError *error; - + if (errorOut) { error = *errorOut; - } - else { + } else { error = nil; } - // - // Search for the path - // - NSArray* paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory,domainMask,YES); - - if ([paths count] == 0) - { - NSDictionary *userInfo = @{NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"No path found for directory in domain.",@"Errors",nil), - @"NSSearchPathDirectory":@(searchPathDirectory), - @"NSSearchPathDomainMask":@(domainMask)}; - + // + // Search for the path + // + NSArray *paths = NSSearchPathForDirectoriesInDomains(searchPathDirectory, domainMask, YES); + + if ([paths count] == 0) { + NSDictionary *userInfo = @{NSLocalizedDescriptionKey: NSLocalizedStringFromTable(@"No path found for directory in domain.", @"Errors", nil), + @"NSSearchPathDirectory": @(searchPathDirectory), + @"NSSearchPathDomainMask": @(domainMask)}; + error = [NSError errorWithDomain:DirectoryLocationDomain - code:DirectoryLocationErrorNoPathFound - userInfo:userInfo]; - return nil; - } - - // - // Normally only need the first path returned - // - NSString *resolvedPath = paths[0]; - - // - // Append the extra path component - // - if (appendComponent) - { - resolvedPath = [resolvedPath stringByAppendingPathComponent:appendComponent]; - } - - // - // Create the path if it doesn't exist - // - - - if ([self createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES - attributes:nil error:&error]) + code:DirectoryLocationErrorNoPathFound + userInfo:userInfo]; + return nil; + } + + // + // Normally only need the first path returned + // + NSString *resolvedPath = paths[0]; + + // + // Append the extra path component + // + if (appendComponent) { + resolvedPath = [resolvedPath stringByAppendingPathComponent:appendComponent]; + } + + // + // Create the path if it doesn't exist + // + + + if ([self createDirectoryAtPath:resolvedPath withIntermediateDirectories:YES + attributes:nil error:&error]) return resolvedPath; else return nil; @@ -108,21 +103,19 @@ - (NSString *)findOrCreateDirectory:(NSSearchPathDirectory)searchPathDirectory * \returns The path to the applicationSupportDirectory (creating it if it doesn't exist). */ -- (NSString *)applicationSupportDirectory -{ - NSString *executableName = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"]; - - NSError *error = nil; - - NSString *result = [self findOrCreateDirectory:NSApplicationSupportDirectory +- (NSString *)applicationSupportDirectory { + NSString *executableName = [[NSBundle mainBundle] infoDictionary][@"CFBundleExecutable"]; + + NSError *error = nil; + + NSString *result = [self findOrCreateDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appendPathComponent:executableName error:&error]; - if (!result) - { - NSLog(@"Unable to find or create application support directory:\n%@", error); - } - return result; + if (!result) { + NSLog(@"Unable to find or create application support directory:\n%@", error); + } + return result; } @end diff --git a/Classes/Power.h b/Classes/Power.h index a29df84..5c76d85 100644 --- a/Classes/Power.h +++ b/Classes/Power.h @@ -29,26 +29,29 @@ @interface Power : NSObject { - - io_connect_t root_port; - io_object_t notifier; - IONotificationPortRef notificationPort; - id _delegate; - + + io_connect_t root_port; + io_object_t notifier; + IONotificationPortRef notificationPort; + id _delegate; + } - (instancetype)init NS_DESIGNATED_INITIALIZER; -@property (NS_NONATOMIC_IOSONLY, unsafe_unretained) id delegate; +@property(NS_NONATOMIC_IOSONLY, unsafe_unretained) id delegate; - (void)registerForSleepWakeNotification; + - (void)deregisterForSleepWakeNotification; - (void)registerForPowerChange; + - (void)deregisterForPowerChange; //internal -- (void)powerMessageReceived:(natural_t)messageType withArgument:(void *) messageArgument; +- (void)powerMessageReceived:(natural_t)messageType withArgument:(void *)messageArgument; + - (void)powerSourceMesssageReceived:(NSDictionary *)n_description; diff --git a/Classes/Power.m b/Classes/Power.m index 39ed9c2..4f7cf28 100644 --- a/Classes/Power.m +++ b/Classes/Power.m @@ -25,154 +25,137 @@ static CFRunLoopSourceRef powerNotifierRunLoopSource = NULL; -static int lastsource=0; +static int lastsource = 0; @implementation Power -void SleepWatcher( void * refCon, io_service_t service, natural_t messageType, void * messageArgument ){ - [(__bridge Power *)refCon powerMessageReceived: messageType withArgument: messageArgument]; +void SleepWatcher(void *refCon, io_service_t service, natural_t messageType, void *messageArgument) { + [(__bridge Power *) refCon powerMessageReceived:messageType withArgument:messageArgument]; } - -static void powerSourceChanged(void * refCon) -{ - CFTypeRef powerBlob = IOPSCopyPowerSourcesInfo(); - CFArrayRef powerSourcesList = IOPSCopyPowerSourcesList(powerBlob); - unsigned count = CFArrayGetCount(powerSourcesList); - unsigned int i; - for (i = 0U; i < count; ++i) { //in case we have several powersources - CFTypeRef powerSource; - CFDictionaryRef description; - powerSource = CFArrayGetValueAtIndex(powerSourcesList, i); - description = IOPSGetPowerSourceDescription(powerBlob, powerSource); - //work with NSArray from here - NSDictionary *n_description = (__bridge NSDictionary *)description; - [(__bridge Power *)refCon powerSourceMesssageReceived:n_description]; - } - CFRelease(powerBlob); - CFRelease(powerSourcesList); +static void powerSourceChanged(void *refCon) { + CFTypeRef powerBlob = IOPSCopyPowerSourcesInfo(); + CFArrayRef powerSourcesList = IOPSCopyPowerSourcesList(powerBlob); + unsigned count = CFArrayGetCount(powerSourcesList); + unsigned int i; + for (i = 0U; i < count; ++i) { //in case we have several powersources + CFTypeRef powerSource; + CFDictionaryRef description; + powerSource = CFArrayGetValueAtIndex(powerSourcesList, i); + description = IOPSGetPowerSourceDescription(powerBlob, powerSource); + //work with NSArray from here + NSDictionary *n_description = (__bridge NSDictionary *) description; + [(__bridge Power *) refCon powerSourceMesssageReceived:n_description]; + } + CFRelease(powerBlob); + CFRelease(powerSourcesList); } -- (instancetype)init{ +- (instancetype)init { if (self = [super init]) { - + } - return self; + return self; } -- (void)registerForSleepWakeNotification -{ - root_port = IORegisterForSystemPower((__bridge void *)(self), ¬ificationPort, SleepWatcher, ¬ifier); - CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode); +- (void)registerForSleepWakeNotification { + root_port = IORegisterForSystemPower((__bridge void *) (self), ¬ificationPort, SleepWatcher, ¬ifier); + CFRunLoopAddSource(CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode); } -- (void)registerForPowerChange -{ - powerNotifierRunLoopSource = IOPSNotificationCreateRunLoopSource(powerSourceChanged,(__bridge void *)(self)); - if (powerNotifierRunLoopSource) { - CFRunLoopAddSource(CFRunLoopGetCurrent(), powerNotifierRunLoopSource, kCFRunLoopDefaultMode); - } +- (void)registerForPowerChange { + powerNotifierRunLoopSource = IOPSNotificationCreateRunLoopSource(powerSourceChanged, (__bridge void *) (self)); + if (powerNotifierRunLoopSource) { + CFRunLoopAddSource(CFRunLoopGetCurrent(), powerNotifierRunLoopSource, kCFRunLoopDefaultMode); + } } -- (void)deregisterForSleepWakeNotification -{ - CFRunLoopRemoveSource( CFRunLoopGetCurrent(), - IONotificationPortGetRunLoopSource(notificationPort), - kCFRunLoopCommonModes ); - IODeregisterForSystemPower(¬ifier); - IOServiceClose(root_port); - IONotificationPortDestroy(notificationPort); +- (void)deregisterForSleepWakeNotification { + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), + IONotificationPortGetRunLoopSource(notificationPort), + kCFRunLoopCommonModes); + IODeregisterForSystemPower(¬ifier); + IOServiceClose(root_port); + IONotificationPortDestroy(notificationPort); } -- (void)deregisterForPowerChange{ - CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerNotifierRunLoopSource, kCFRunLoopDefaultMode); - CFRelease(powerNotifierRunLoopSource); +- (void)deregisterForPowerChange { + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), powerNotifierRunLoopSource, kCFRunLoopDefaultMode); + CFRelease(powerNotifierRunLoopSource); } +- (void)powerMessageReceived:(natural_t)messageType withArgument:(void *)messageArgument { + switch (messageType) { + case kIOMessageSystemWillSleep: + IOAllowPowerChange(root_port, (long) messageArgument); + break; + case kIOMessageCanSystemSleep: + IOAllowPowerChange(root_port, (long) messageArgument); + break; + case kIOMessageSystemHasPoweredOn: + if ([_delegate respondsToSelector:@selector(systemDidWakeFromSleep:)]) + [_delegate systemDidWakeFromSleep:self]; + else { + [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; + } + break; + } +} + +- (void)powerSourceMesssageReceived:(NSDictionary *)n_description { + if (([n_description[@"Power Source State"] isEqualToString:@"AC Power"] && [n_description[@"Is Charging"] intValue] == 1) && lastsource != 1) { + lastsource = 1; + if ([_delegate respondsToSelector:@selector(powerChangeToACLoading:)]) + [_delegate powerChangeToACLoading:self]; + else { + [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; + } + } + + + if (([n_description[@"Power Source State"] isEqualToString:@"AC Power"] && [n_description[@"Is Charging"] intValue] == 0) && lastsource != 2) { + lastsource = 2; + if ([_delegate respondsToSelector:@selector(powerChangeToAC:)]) + [_delegate powerChangeToAC:self]; + else { + [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; + } + } + + if (([n_description[@"Power Source State"] isEqualToString:@"Battery Power"]) && lastsource != 3) { + lastsource = 3; + if ([_delegate respondsToSelector:@selector(powerChangeToBattery:)]) + [_delegate powerChangeToBattery:self]; + else { + [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; + } + } -- (void)powerMessageReceived:(natural_t)messageType withArgument:(void *) messageArgument -{ - switch (messageType) - { - case kIOMessageSystemWillSleep: - IOAllowPowerChange(root_port, (long)messageArgument); - break; - case kIOMessageCanSystemSleep: - IOAllowPowerChange(root_port, (long)messageArgument); - break; - case kIOMessageSystemHasPoweredOn: - if ([_delegate respondsToSelector:@selector(systemDidWakeFromSleep:)]) - [_delegate systemDidWakeFromSleep:self]; - else - { - [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; - } - break; - } } -- (void)powerSourceMesssageReceived:(NSDictionary *)n_description{ - if (([n_description[@"Power Source State"] isEqualToString:@"AC Power"] && [n_description[@"Is Charging"] intValue]==1) && lastsource!=1) { - lastsource=1; - if ([_delegate respondsToSelector:@selector(powerChangeToACLoading:)]) - [_delegate powerChangeToACLoading:self]; - else - { - [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; - } - } - - - if (([n_description[@"Power Source State"] isEqualToString:@"AC Power"] && [n_description[@"Is Charging"] intValue]==0) && lastsource!=2) { - lastsource=2; - if ([_delegate respondsToSelector:@selector(powerChangeToAC:)]) - [_delegate powerChangeToAC:self]; - else - { - [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; - } - } - - if (([n_description[@"Power Source State"] isEqualToString:@"Battery Power"]) && lastsource!=3) { - lastsource=3; - if ([_delegate respondsToSelector:@selector(powerChangeToBattery:)]) - [_delegate powerChangeToBattery:self]; - else - { - [NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to ourDelegate"]; - } - } - -} - - - -- (id)delegate -{ + +- (id)delegate { return _delegate; } -- (void)setDelegate:(id)new_delegate -{ - - _delegate = new_delegate; +- (void)setDelegate:(id)new_delegate { + + _delegate = new_delegate; } -- (void)dealloc -{ +- (void)dealloc { NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; - + if (_delegate) [nc removeObserver:_delegate name:nil object:self]; - -} +} @end diff --git a/Classes/Privilege.h b/Classes/Privilege.h index aa520c9..ebc548a 100644 --- a/Classes/Privilege.h +++ b/Classes/Privilege.h @@ -10,9 +10,10 @@ #import -@interface Privilege:NSObject -+(AuthorizationRef) Get; -+(BOOL) runTaskAsAdmin:(NSString *) path andArgs:(NSArray *) args; +@interface Privilege : NSObject ++ (AuthorizationRef)Get; + ++ (BOOL)runTaskAsAdmin:(NSString *)path andArgs:(NSArray *)args; @end #endif /* Privilege_h */ diff --git a/Classes/Privilege.m b/Classes/Privilege.m index b89003c..bfe90e0 100644 --- a/Classes/Privilege.m +++ b/Classes/Privilege.m @@ -12,14 +12,14 @@ static AuthorizationRef authorizationRef = nil; @implementation Privilege -+(AuthorizationRef) Get{ - if (authorizationRef == nil){ - AuthorizationItem gencitem = { "system.privilege.admin", 0, NULL, 0 }; - AuthorizationRights gencright = { 1, &gencitem }; ++ (AuthorizationRef)Get { + if (authorizationRef == nil) { + AuthorizationItem gencitem = {"system.privilege.admin", 0, NULL, 0}; + AuthorizationRights gencright = {1, &gencitem}; int flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed; - OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, flags, &authorizationRef); - - if (status != errAuthorizationSuccess){ + OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, flags, &authorizationRef); + + if (status != errAuthorizationSuccess) { NSLog(@"Copy Rights Unsuccessful: %d", status); authorizationRef = nil; } @@ -27,30 +27,30 @@ +(AuthorizationRef) Get{ return authorizationRef; } -+(BOOL) runTaskAsAdmin:(NSString *) path andArgs:(NSArray *) args { - ++ (BOOL)runTaskAsAdmin:(NSString *)path andArgs:(NSArray *)args { + if ([self Get] == nil) { return NO; } - + FILE *myCommunicationsPipe = NULL; - - int count = (int)[args count]; - - char *myArguments[count+1]; - - for (int i=0; i<[args count]; i++) { - myArguments[i] = (char *)[(NSString *)[args objectAtIndex:i] UTF8String]; + + int count = (int) [args count]; + + char *myArguments[count + 1]; + + for (int i = 0; i < [args count]; i++) { + myArguments[i] = (char *) [(NSString *) [args objectAtIndex:i] UTF8String]; } myArguments[count] = NULL; - - OSStatus resultStatus = AuthorizationExecuteWithPrivileges ([self Get], - [path UTF8String], kAuthorizationFlagDefaults, myArguments, - &myCommunicationsPipe); - + + OSStatus resultStatus = AuthorizationExecuteWithPrivileges([self Get], + [path UTF8String], kAuthorizationFlagDefaults, myArguments, + &myCommunicationsPipe); + if (resultStatus != errAuthorizationSuccess) NSLog(@"Error: %d", resultStatus); - + return YES; } @end diff --git a/Classes/StatusItemWindow.m b/Classes/StatusItemWindow.m index f7a15e8..0c96f32 100644 --- a/Classes/StatusItemWindow.m +++ b/Classes/StatusItemWindow.m @@ -22,11 +22,11 @@ #import "StatusItemWindow.h" -@implementation StatusItemWindow +@implementation StatusItemWindow - (void)makeKeyAndOrderFront:(id)sender { [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; [super makeKeyAndOrderFront:sender]; } - + @end diff --git a/Classes/SystemVersion.h b/Classes/SystemVersion.h index 247910d..93303f4 100644 --- a/Classes/SystemVersion.h +++ b/Classes/SystemVersion.h @@ -22,19 +22,23 @@ @interface SystemVersion : NSObject // Returns the current system version major.minor.bugFix -+ (void)getMajor:(SInt32*)major minor:(SInt32*)minor bugFix:(SInt32*)bugFix; ++ (void)getMajor:(SInt32 *)major minor:(SInt32 *)minor bugFix:(SInt32 *)bugFix; // Returns the build number of the OS. Useful when looking for bug fixes // in new OSes which all have a set system version. // eg 10.5.5's build number is 9F33. Easy way to check the build number // is to choose "About this Mac" from the Apple menu and click on the version // number. -+ (NSString*)build; ++ (NSString *)build; + ++ (BOOL)isBuildLessThan:(NSString *)build; + ++ (BOOL)isBuildLessThanOrEqualTo:(NSString *)build; + ++ (BOOL)isBuildGreaterThan:(NSString *)build; + ++ (BOOL)isBuildGreaterThanOrEqualTo:(NSString *)build; -+ (BOOL)isBuildLessThan:(NSString*)build; -+ (BOOL)isBuildLessThanOrEqualTo:(NSString*)build; -+ (BOOL)isBuildGreaterThan:(NSString*)build; -+ (BOOL)isBuildGreaterThanOrEqualTo:(NSString*)build; + (BOOL)isBuildEqualTo:(NSString *)build; // Returns YES if running on 10.3, NO otherwise. @@ -60,7 +64,7 @@ // Returns a YES/NO if the system is 10.6 or better + (BOOL)isSnowLeopardOrGreater; - // GTM_MACOS_SDK +// GTM_MACOS_SDK // Returns one of the achitecture strings below. Note that this is the // architecture that we are currently running as, not the hardware architecture. diff --git a/Classes/SystemVersion.m b/Classes/SystemVersion.m index 667b960..587c5db 100644 --- a/Classes/SystemVersion.m +++ b/Classes/SystemVersion.m @@ -17,6 +17,7 @@ // #import "SystemVersion.h" + #if GTM_MACOS_SDK #import #endif @@ -36,182 +37,182 @@ @implementation SystemVersion + (void)initialize { - if (self == [SystemVersion class]) { - // Gestalt is the recommended way of getting the OS version (despite a - // comment to the contrary in the 10.4 headers and docs; see - // ). - // The iPhone doesn't have Gestalt though, so use the plist there. + if (self == [SystemVersion class]) { + // Gestalt is the recommended way of getting the OS version (despite a + // comment to the contrary in the 10.4 headers and docs; see + // ). + // The iPhone doesn't have Gestalt though, so use the plist there. #if GTM_MACOS_SDK - require_noerr(Gestalt(gestaltSystemVersionMajor, &sGTMSystemVersionMajor), failedGestalt); - require_noerr(Gestalt(gestaltSystemVersionMinor, &sGTMSystemVersionMinor), failedGestalt); - require_noerr(Gestalt(gestaltSystemVersionBugFix, &sGTMSystemVersionBugFix), failedGestalt); - - return; - - failedGestalt: - ; + require_noerr(Gestalt(gestaltSystemVersionMajor, &sGTMSystemVersionMajor), failedGestalt); + require_noerr(Gestalt(gestaltSystemVersionMinor, &sGTMSystemVersionMinor), failedGestalt); + require_noerr(Gestalt(gestaltSystemVersionBugFix, &sGTMSystemVersionBugFix), failedGestalt); + + return; + + failedGestalt: + ; #if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_3 - // gestaltSystemVersionMajor et al are only on 10.4 and above, so they - // could fail when running on 10.3. - SInt32 binaryCodedDec; - OSStatus err = err = Gestalt(gestaltSystemVersion, &binaryCodedDec); - - // Note that this code will return x.9.9 for any system rev parts that are - // greater than 9 (i.e., 10.10.10 will be 10.9.9). This shouldn't ever be a - // problem as the code above takes care of 10.4+. - SInt32 msb = (binaryCodedDec & 0x0000F000L) >> 12; - msb *= 10; - SInt32 lsb = (binaryCodedDec & 0x00000F00L) >> 8; - sGTMSystemVersionMajor = msb + lsb; - sGTMSystemVersionMinor = (binaryCodedDec & 0x000000F0L) >> 4; - sGTMSystemVersionBugFix = (binaryCodedDec & 0x0000000FL); + // gestaltSystemVersionMajor et al are only on 10.4 and above, so they + // could fail when running on 10.3. + SInt32 binaryCodedDec; + OSStatus err = err = Gestalt(gestaltSystemVersion, &binaryCodedDec); + + // Note that this code will return x.9.9 for any system rev parts that are + // greater than 9 (i.e., 10.10.10 will be 10.9.9). This shouldn't ever be a + // problem as the code above takes care of 10.4+. + SInt32 msb = (binaryCodedDec & 0x0000F000L) >> 12; + msb *= 10; + SInt32 lsb = (binaryCodedDec & 0x00000F00L) >> 8; + sGTMSystemVersionMajor = msb + lsb; + sGTMSystemVersionMinor = (binaryCodedDec & 0x000000F0L) >> 4; + sGTMSystemVersionBugFix = (binaryCodedDec & 0x0000000FL); #endif // MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_3 - + #else // GTM_MACOS_SDK - @autoreleasepool { - NSDictionary *systemVersionPlist - = [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath]; - NSString *version = systemVersionPlist[@"ProductVersion"]; - NSArray *versionInfo = [version componentsSeparatedByString:@"."]; - int length = [versionInfo count]; - sGTMSystemVersionMajor = [versionInfo[0] intValue]; - sGTMSystemVersionMinor = [versionInfo[1] intValue]; - if (length == 3) { - sGTMSystemVersionBugFix = [versionInfo[2] intValue]; - } - } + @autoreleasepool { + NSDictionary *systemVersionPlist + = [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath]; + NSString *version = systemVersionPlist[@"ProductVersion"]; + NSArray *versionInfo = [version componentsSeparatedByString:@"."]; + int length = [versionInfo count]; + sGTMSystemVersionMajor = [versionInfo[0] intValue]; + sGTMSystemVersionMinor = [versionInfo[1] intValue]; + if (length == 3) { + sGTMSystemVersionBugFix = [versionInfo[2] intValue]; + } + } #endif // GTM_MACOS_SDK - } + } } -+ (void)getMajor:(SInt32*)major minor:(SInt32*)minor bugFix:(SInt32*)bugFix { - if (major) { - *major = sGTMSystemVersionMajor; - } - if (minor) { - *minor = sGTMSystemVersionMinor; - } - if (bugFix) { - *bugFix = sGTMSystemVersionBugFix; - } ++ (void)getMajor:(SInt32 *)major minor:(SInt32 *)minor bugFix:(SInt32 *)bugFix { + if (major) { + *major = sGTMSystemVersionMajor; + } + if (minor) { + *minor = sGTMSystemVersionMinor; + } + if (bugFix) { + *bugFix = sGTMSystemVersionBugFix; + } } -+ (NSString*)build { - @synchronized(self) { - // Not cached at initialization time because we don't expect "real" - // software to want this, and it costs a bit to get at startup. - // This will mainly be for unit test cases. - if (!sBuild) { - NSDictionary *systemVersionPlist - = [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath]; - sBuild = systemVersionPlist[@"ProductBuildVersion"]; - } - } - return sBuild; ++ (NSString *)build { + @synchronized (self) { + // Not cached at initialization time because we don't expect "real" + // software to want this, and it costs a bit to get at startup. + // This will mainly be for unit test cases. + if (!sBuild) { + NSDictionary *systemVersionPlist + = [NSDictionary dictionaryWithContentsOfFile:kSystemVersionPlistPath]; + sBuild = systemVersionPlist[@"ProductBuildVersion"]; + } + } + return sBuild; } -+ (BOOL)isBuildLessThan:(NSString*)build { - NSComparisonResult result - = [[self build] compare:build - options:NSNumericSearch | NSCaseInsensitiveSearch]; - return result == NSOrderedAscending; ++ (BOOL)isBuildLessThan:(NSString *)build { + NSComparisonResult result + = [[self build] compare:build + options:NSNumericSearch | NSCaseInsensitiveSearch]; + return result == NSOrderedAscending; } -+ (BOOL)isBuildLessThanOrEqualTo:(NSString*)build { - NSComparisonResult result - = [[self build] compare:build - options:NSNumericSearch | NSCaseInsensitiveSearch]; - return result != NSOrderedDescending; ++ (BOOL)isBuildLessThanOrEqualTo:(NSString *)build { + NSComparisonResult result + = [[self build] compare:build + options:NSNumericSearch | NSCaseInsensitiveSearch]; + return result != NSOrderedDescending; } -+ (BOOL)isBuildGreaterThan:(NSString*)build { - NSComparisonResult result - = [[self build] compare:build - options:NSNumericSearch | NSCaseInsensitiveSearch]; - return result == NSOrderedDescending; ++ (BOOL)isBuildGreaterThan:(NSString *)build { + NSComparisonResult result + = [[self build] compare:build + options:NSNumericSearch | NSCaseInsensitiveSearch]; + return result == NSOrderedDescending; } -+ (BOOL)isBuildGreaterThanOrEqualTo:(NSString*)build { - NSComparisonResult result - = [[self build] compare:build - options:NSNumericSearch | NSCaseInsensitiveSearch]; - return result != NSOrderedAscending; ++ (BOOL)isBuildGreaterThanOrEqualTo:(NSString *)build { + NSComparisonResult result + = [[self build] compare:build + options:NSNumericSearch | NSCaseInsensitiveSearch]; + return result != NSOrderedAscending; } + (BOOL)isBuildEqualTo:(NSString *)build { - NSComparisonResult result - = [[self build] compare:build - options:NSNumericSearch | NSCaseInsensitiveSearch]; - return result == NSOrderedSame; + NSComparisonResult result + = [[self build] compare:build + options:NSNumericSearch | NSCaseInsensitiveSearch]; + return result == NSOrderedSame; } + (BOOL)isPanther { - return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 3; + return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 3; } + (BOOL)isTiger { - return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 4; + return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 4; } + (BOOL)isLeopard { - return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 5; + return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 5; } + (BOOL)isSnowLeopard { - return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 6; + return sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor == 6; } + (BOOL)isPantherOrGreater { - return (sGTMSystemVersionMajor > 10) || - (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 3); + return (sGTMSystemVersionMajor > 10) || + (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 3); } + (BOOL)isTigerOrGreater { - return (sGTMSystemVersionMajor > 10) || - (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 4); + return (sGTMSystemVersionMajor > 10) || + (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 4); } + (BOOL)isLeopardOrGreater { - return (sGTMSystemVersionMajor > 10) || - (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 5); + return (sGTMSystemVersionMajor > 10) || + (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 5); } + (BOOL)isSnowLeopardOrGreater { - return (sGTMSystemVersionMajor > 10) || - (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 6); + return (sGTMSystemVersionMajor > 10) || + (sGTMSystemVersionMajor == 10 && sGTMSystemVersionMinor >= 6); } + (NSString *)runtimeArchitecture { - NSString *architecture = nil; + NSString *architecture = nil; #if GTM_IPHONE_SDK - architecture = kGTMArch_iPhone; + architecture = kGTMArch_iPhone; #else // !GTM_IPHONE_SDK - // In reading arch(3) you'd thing this would work: - // - // const NXArchInfo *localInfo = NXGetLocalArchInfo(); - // _GTMDevAssert(localInfo && localInfo->name, @"Couldn't get NXArchInfo"); - // const NXArchInfo *genericInfo = NXGetArchInfoFromCpuType(localInfo->cputype, 0); - // _GTMDevAssert(genericInfo && genericInfo->name, @"Couldn't get generic NXArchInfo"); - // extensions[0] = [NSString stringWithFormat:@".%s", genericInfo->name]; - // - // but on 64bit it returns the same things as on 32bit, so... + // In reading arch(3) you'd thing this would work: + // + // const NXArchInfo *localInfo = NXGetLocalArchInfo(); + // _GTMDevAssert(localInfo && localInfo->name, @"Couldn't get NXArchInfo"); + // const NXArchInfo *genericInfo = NXGetArchInfoFromCpuType(localInfo->cputype, 0); + // _GTMDevAssert(genericInfo && genericInfo->name, @"Couldn't get generic NXArchInfo"); + // extensions[0] = [NSString stringWithFormat:@".%s", genericInfo->name]; + // + // but on 64bit it returns the same things as on 32bit, so... #if __POWERPC__ #if __LP64__ - architecture = kGTMArch_ppc64; + architecture = kGTMArch_ppc64; #else // !__LP64__ - architecture = kGTMArch_ppc; + architecture = kGTMArch_ppc; #endif // __LP64__ #else // !__POWERPC__ #if __LP64__ - architecture = kGTMArch_x86_64; + architecture = kGTMArch_x86_64; #else // !__LP64__ - architecture = kGTMArch_i386; + architecture = kGTMArch_i386; #endif // __LP64__ #endif // !__POWERPC__ - + #endif // GTM_IPHONE_SDK - return architecture; + return architecture; } @end \ No newline at end of file diff --git a/Classes/smcWrapper.h b/Classes/smcWrapper.h index e79c223..10417c8 100755 --- a/Classes/smcWrapper.h +++ b/Classes/smcWrapper.h @@ -29,15 +29,22 @@ @interface smcWrapper : NSObject { } -+(void) cleanUp; - -+(int) get_fan_rpm:(int)fan_number; -+(float) get_maintemp; -+(float) get_mptemp; -+(int) get_fan_num; -+(int) get_min_speed:(int)fan_number; -+(int) get_max_speed:(int)fan_number; -+(void)setKey_external:(NSString *)key value:(NSString *)value; -+(NSString*) get_fan_descr:(int)fan_number; ++ (void)cleanUp; + ++ (int)get_fan_rpm:(int)fan_number; + ++ (float)get_maintemp; + ++ (float)get_mptemp; + ++ (int)get_fan_num; + ++ (int)get_min_speed:(int)fan_number; + ++ (int)get_max_speed:(int)fan_number; + ++ (void)setKey_external:(NSString *)key value:(NSString *)value; + ++ (NSString *)get_fan_descr:(int)fan_number; @end diff --git a/Classes/smcWrapper.m b/Classes/smcWrapper.m index a0c67f5..c8d8843 100755 --- a/Classes/smcWrapper.m +++ b/Classes/smcWrapper.m @@ -23,61 +23,54 @@ #import "smcWrapper.h" #import -#import "Privilege.h" -NSString * const smc_checksum=@"8ab515dbd0f83731306041d96eaff0ac"; +NSString *const smc_checksum = @"8ab515dbd0f83731306041d96eaff0ac"; NSArray *allSensors; @implementation smcWrapper io_connect_t conn; -+(void)init{ ++ (void)init { SMCOpen(&conn); } -+(void)cleanUp{ + ++ (void)cleanUp { SMCClose(conn); } -+(int)convertToNumber:(SMCVal_t) val -{ ++ (int)convertToNumber:(SMCVal_t)val { float fval = -1.0f; - + if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) { - memcpy(&fval,val.bytes,sizeof(float)); - } - else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) { + memcpy(&fval, val.bytes, sizeof(float)); + } else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) { fval = _strtof(val.bytes, val.dataSize, 2); + } else if (strcmp(val.dataType, DATATYPE_UINT16) == 0 && val.dataSize == 2) { + fval = (float) _strtoul((char *) val.bytes, val.dataSize, 10); + } else if (strcmp(val.dataType, DATATYPE_UINT8) == 0 && val.dataSize == 1) { + fval = (float) val.bytes[0]; + } else if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) { + fval = ((val.bytes[0] * 256 + val.bytes[1]) >> 2) / 64; + } else { + NSLog(@"%@", [NSString stringWithFormat:@"Unknown val:%s size-%d", val.dataType, val.dataSize]); } - else if (strcmp(val.dataType, DATATYPE_UINT16) == 0 && val.dataSize == 2) { - fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); - } - else if (strcmp(val.dataType, DATATYPE_UINT8) == 0 && val.dataSize == 1) { - fval = (float)val.bytes[0]; - } - else if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) { - fval = ((val.bytes[0] * 256 + val.bytes[1]) >> 2)/64; - } - else { - NSLog(@"%@", [NSString stringWithFormat:@"Unknown val:%s size-%d",val.dataType,val.dataSize]); - } - - return (int)fval; + + return (int) fval; } -+(float)readTempSensors -{ ++ (float)readTempSensors { float retValue; - SMCVal_t val; + SMCVal_t val; NSString *sensor = [[NSUserDefaults standardUserDefaults] objectForKey:PREF_TEMPERATURE_SENSOR]; - SMCReadKey2((char*)[sensor UTF8String], &val,conn); + SMCReadKey2((char *) [sensor UTF8String], &val, conn); retValue = [self convertToNumber:val]; - allSensors = [NSArray arrayWithObjects:@"TC0D",@"TC0P",@"TCAD",@"TC0H",@"TC0F",@"TCAH",@"TCBH",nil]; - if (retValue<=0 || floor(retValue) == 129 ) { //workaround for some iMac Models + allSensors = [NSArray arrayWithObjects:@"TC0D", @"TC0P", @"TCAD", @"TC0H", @"TC0F", @"TCAH", @"TCBH", nil]; + if (retValue <= 0 || floor(retValue) == 129) { //workaround for some iMac Models for (NSString *sensor in allSensors) { - SMCReadKey2((char*)[sensor UTF8String], &val,conn); - retValue= [self convertToNumber:val]; - if (retValue>0 && floor(retValue) != 129 ) { + SMCReadKey2((char *) [sensor UTF8String], &val, conn); + retValue = [self convertToNumber:val]; + if (retValue > 0 && floor(retValue) != 129) { [[NSUserDefaults standardUserDefaults] setObject:sensor forKey:PREF_TEMPERATURE_SENSOR]; [[NSUserDefaults standardUserDefaults] synchronize]; break; @@ -87,12 +80,12 @@ +(float)readTempSensors return retValue; } -+(float) get_maintemp{ ++ (float)get_maintemp { float retValue; - NSRange range_pro=[[MachineDefaults computerModel] rangeOfString:@"MacPro"]; + NSRange range_pro = [[MachineDefaults computerModel] rangeOfString:@"MacPro"]; if (range_pro.length > 0) { retValue = [smcWrapper get_mptemp]; - if (retValue<=0 || floor(retValue) == 129 ) { + if (retValue <= 0 || floor(retValue) == 129) { retValue = [smcWrapper readTempSensors]; } } else { @@ -103,159 +96,154 @@ +(float) get_maintemp{ //temperature-readout for MacPro contributed by Victor Boyer -+(float) get_mptemp{ - UInt32Char_t keyA; - UInt32Char_t keyB; - SMCVal_t valA; - SMCVal_t valB; ++ (float)get_mptemp { + UInt32Char_t keyA; + UInt32Char_t keyB; + SMCVal_t valA; + SMCVal_t valB; // kern_return_t resultA; // kern_return_t resultB; sprintf(keyA, "TCAH"); - SMCReadKey2(keyA, &valA,conn); + SMCReadKey2(keyA, &valA, conn); sprintf(keyB, "TCBH"); - SMCReadKey2(keyB, &valB,conn); - float c_tempA= [self convertToNumber:valA]; - float c_tempB= [self convertToNumber:valB]; + SMCReadKey2(keyB, &valB, conn); + float c_tempA = [self convertToNumber:valA]; + float c_tempB = [self convertToNumber:valB]; int i_tempA, i_tempB; - if (c_tempA < c_tempB) - { + if (c_tempA < c_tempB) { i_tempB = round(c_tempB); return i_tempB; - } - else - { + } else { i_tempA = round(c_tempA); return i_tempA; } } -+(int) get_fan_rpm:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; ++ (int)get_fan_rpm:(int)fan_number { + UInt32Char_t key; + SMCVal_t val; //kern_return_t result; sprintf(key, "F%dAc", fan_number); - SMCReadKey2(key, &val,conn); - int running= [self convertToNumber:val]; + SMCReadKey2(key, &val, conn); + int running = [self convertToNumber:val]; return running; -} +} -+(int) get_fan_num{ ++ (int)get_fan_num { // kern_return_t result; - SMCVal_t val; - int totalFans; - SMCReadKey2("FNum", &val,conn); + SMCVal_t val; + int totalFans; + SMCReadKey2("FNum", &val, conn); totalFans = [self convertToNumber:val]; return totalFans; } -+(NSString*) get_fan_descr:(int)fan_number{ - UInt32Char_t key; ++ (NSString *)get_fan_descr:(int)fan_number { + UInt32Char_t key; char temp; - SMCVal_t val; + SMCVal_t val; //kern_return_t result; NSMutableString *desc; - + sprintf(key, "F%dID", fan_number); - SMCReadKey2(key, &val,conn); - - if(val.dataSize>0){ - desc=[[NSMutableString alloc]init]; + SMCReadKey2(key, &val, conn); + + if (val.dataSize > 0) { + desc = [[NSMutableString alloc] init]; int i; for (i = 0; i < val.dataSize; i++) { - if ((int)val.bytes[i]>32) { - temp=(unsigned char)val.bytes[i]; - [desc appendFormat:@"%c",temp]; + if ((int) val.bytes[i] > 32) { + temp = (unsigned char) val.bytes[i]; + [desc appendFormat:@"%c", temp]; } } - } - else { + } else { //On MacBookPro 15.1 descriptions aren't available - desc=[[NSMutableString alloc] initWithFormat:@"Fan #%d: ",fan_number+1]; + desc = [[NSMutableString alloc] initWithFormat:@"Fan #%d: ", fan_number + 1]; } return desc; -} +} -+(int) get_min_speed:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; ++ (int)get_min_speed:(int)fan_number { + UInt32Char_t key; + SMCVal_t val; //kern_return_t result; sprintf(key, "F%dMn", fan_number); - SMCReadKey2(key, &val,conn); - int min= [self convertToNumber:val]; + SMCReadKey2(key, &val, conn); + int min = [self convertToNumber:val]; return min; -} +} -+(int) get_max_speed:(int)fan_number{ - UInt32Char_t key; - SMCVal_t val; ++ (int)get_max_speed:(int)fan_number { + UInt32Char_t key; + SMCVal_t val; //kern_return_t result; sprintf(key, "F%dMx", fan_number); - SMCReadKey2(key, &val,conn); - int max= [self convertToNumber:val]; + SMCReadKey2(key, &val, conn); + int max = [self convertToNumber:val]; return max; -} +} -+ (BOOL)validateSMC:(NSString*)path -{ ++ (BOOL)validateSMC:(NSString *)path { SecStaticCodeRef ref = NULL; - - NSURL * url = [NSURL URLWithString:path]; - + + NSURL *url = [NSURL URLWithString:path]; + OSStatus status; - + // obtain the cert info from the executable - status = SecStaticCodeCreateWithPath((__bridge CFURLRef)url, kSecCSDefaultFlags, &ref); - + status = SecStaticCodeCreateWithPath((__bridge CFURLRef) url, kSecCSDefaultFlags, &ref); + if (status != noErr) { return false; } - + @try { status = SecStaticCodeCheckValidity(ref, kSecCSDefaultFlags, nil); - + if (status != noErr) { - NSLog(@"Codesign verification failed: Error id = %d",status); + NSLog(@"Codesign verification failed: Error id = %d", status); return false; } } @catch (NSException *exception) { - NSLog(@"Codesign exception %@",exception); + NSLog(@"Codesign exception %@", exception); return false; } - + return true; } -+ (NSString*)createCheckSum:(NSString*)path { - NSData *d=[NSData dataWithContentsOfMappedFile:path]; ++ (NSString *)createCheckSum:(NSString *)path { + NSData *d = [NSData dataWithContentsOfMappedFile:path]; unsigned char result[CC_MD5_DIGEST_LENGTH]; - CC_MD5((void *)[d bytes], [d length], result); - NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2]; - for(int i = 0; i - - CFBundleDevelopmentRegion - English - CFBundleExecutable - smcFanControl - CFBundleGetInfoString - smcFanControl 2.6, Hendrik Holtmann (GPL) - CFBundleIconFile - smcfancontrol_v2 - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - smcFanControl - CFBundlePackageType - APPL - CFBundleShortVersionString - $(MARKETING_VERSION) - CFBundleSignature - ???? - CFBundleVersion - $(CURRENT_PROJECT_VERSION) - LSApplicationCategoryType - public.app-category.utilities - LSUIElement - 1 - NSHumanReadableCopyright - Hendrik Holtmann (GPL) - NSMainNibFile - MainMenu - NSPrincipalClass - NSApplication - SUFeedURL - https://www.eidac.de/smcfancontrol/smcfancontrol.xml - + + CFBundleDevelopmentRegion + English + CFBundleExecutable + smcFanControl + CFBundleGetInfoString + smcFanControl 2.6, Hendrik Holtmann (GPL) + CFBundleIconFile + smcfancontrol_v2 + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + smcFanControl + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleSignature + ???? + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSApplicationCategoryType + public.app-category.utilities + LSUIElement + 1 + NSHumanReadableCopyright + Hendrik Holtmann (GPL) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + SUFeedURL + https://www.eidac.de/smcfancontrol/smcfancontrol.xml + diff --git a/Ressources/Machines.plist b/Ressources/Machines.plist index 2fde844..8c6866b 100644 --- a/Ressources/Machines.plist +++ b/Ressources/Machines.plist @@ -1,576 +1,576 @@ - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 1000 - selspeed - 1000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 1000 - selspeed - 1000 - - - Machine - MacBookPro1,1 - Maxspeed - 6000 - Minspeed - 1000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 1000 - selspeed - 1000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 1000 - selspeed - 1000 - - - Machine - MacBookPro1,2 - Maxspeed - 6000 - Minspeed - 1000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro2,2 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro2,1 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro3,1 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro4,1 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro5,1 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - Left Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Description - Right Fan - Maxspeed - 6000 - Minspeed - 2000 - selspeed - 2000 - - - Machine - MacBookPro5,2 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 2 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1500 - selspeed - 1500 - - - Machine - MacBook1,1 - Maxspeed - 6200 - Minspeed - 1500 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBook2,1 - Maxspeed - 6200 - Minspeed - 1800 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBook3,1 - Maxspeed - 6200 - Minspeed - 1800 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBook4,1 - Maxspeed - 6200 - Minspeed - 1800 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBook5,1 - Maxspeed - 6000 - Minspeed - 2000 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBook5,2 - Maxspeed - 6200 - Minspeed - 1800 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBookAir1,1 - Maxspeed - 6200 - Minspeed - 2000 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 6200 - Minspeed - 1800 - selspeed - 1800 - - - Machine - MacBookAir2,1 - Maxspeed - 6200 - Minspeed - 2000 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 5500 - Minspeed - 1500 - selspeed - 1500 - - - Machine - MacMini1,1 - Maxspeed - 5500 - Minspeed - 1500 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 5500 - Minspeed - 1500 - selspeed - 1500 - - - Machine - MacMini2,1 - Maxspeed - 5500 - Minspeed - 1500 - NumFans - 1 - - - Fans - - - Description - MainFan - Maxspeed - 5500 - Minspeed - 1500 - selspeed - 1500 - - - Machine - MacMini3,1 - Maxspeed - 5500 - Minspeed - 1500 - NumFans - 1 - - - Fans - - - Description - CPU Fan - Maxspeed - 2900 - Minspeed - 500 - selspeed - 500 - - - Description - PCIe/HDD Fan - Maxspeed - 2900 - Minspeed - 500 - selspeed - 500 - - - Description - Rear Fan - Maxspeed - 2900 - Minspeed - 500 - selspeed - 500 - - - Description - Power Supply Fan - Maxspeed - 2800 - Minspeed - 600 - selspeed - 600 - - - Machine - MacPro1,1 - Maxspeed - 2900 - Minspeed - 500 - NumFans - 4 - - + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 1000 + selspeed + 1000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 1000 + selspeed + 1000 + + + Machine + MacBookPro1,1 + Maxspeed + 6000 + Minspeed + 1000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 1000 + selspeed + 1000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 1000 + selspeed + 1000 + + + Machine + MacBookPro1,2 + Maxspeed + 6000 + Minspeed + 1000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro2,2 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro2,1 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro3,1 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro4,1 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro5,1 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + Left Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Description + Right Fan + Maxspeed + 6000 + Minspeed + 2000 + selspeed + 2000 + + + Machine + MacBookPro5,2 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 2 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1500 + selspeed + 1500 + + + Machine + MacBook1,1 + Maxspeed + 6200 + Minspeed + 1500 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBook2,1 + Maxspeed + 6200 + Minspeed + 1800 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBook3,1 + Maxspeed + 6200 + Minspeed + 1800 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBook4,1 + Maxspeed + 6200 + Minspeed + 1800 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBook5,1 + Maxspeed + 6000 + Minspeed + 2000 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBook5,2 + Maxspeed + 6200 + Minspeed + 1800 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBookAir1,1 + Maxspeed + 6200 + Minspeed + 2000 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 6200 + Minspeed + 1800 + selspeed + 1800 + + + Machine + MacBookAir2,1 + Maxspeed + 6200 + Minspeed + 2000 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 5500 + Minspeed + 1500 + selspeed + 1500 + + + Machine + MacMini1,1 + Maxspeed + 5500 + Minspeed + 1500 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 5500 + Minspeed + 1500 + selspeed + 1500 + + + Machine + MacMini2,1 + Maxspeed + 5500 + Minspeed + 1500 + NumFans + 1 + + + Fans + + + Description + MainFan + Maxspeed + 5500 + Minspeed + 1500 + selspeed + 1500 + + + Machine + MacMini3,1 + Maxspeed + 5500 + Minspeed + 1500 + NumFans + 1 + + + Fans + + + Description + CPU Fan + Maxspeed + 2900 + Minspeed + 500 + selspeed + 500 + + + Description + PCIe/HDD Fan + Maxspeed + 2900 + Minspeed + 500 + selspeed + 500 + + + Description + Rear Fan + Maxspeed + 2900 + Minspeed + 500 + selspeed + 500 + + + Description + Power Supply Fan + Maxspeed + 2800 + Minspeed + 600 + selspeed + 600 + + + Machine + MacPro1,1 + Maxspeed + 2900 + Minspeed + 500 + NumFans + 4 + + diff --git a/Ressources/com.tinkernels.tb-switcher.plist b/Ressources/com.tinkernels.tb-switcher.plist new file mode 100644 index 0000000..24f1d18 --- /dev/null +++ b/Ressources/com.tinkernels.tb-switcher.plist @@ -0,0 +1,25 @@ + + + + + Label + com.github.tinkernels.tb-switcher.plist + ProgramArguments + + /Library/Application Support/smcFanControl2/tb-switcher + -l + /var/run/tb-switcher.socket= + + RunAtLoad + + StandardOutPath + /Library/Logs/com.tinkernels.tb-switcher.log + StandardErrorPath + /Library/Logs/com.tinkernels.tb-switcher.log + KeepAlive + + SuccessfulExit + + + + diff --git a/main.m b/main.m index 3ebb17f..9bad041 100644 --- a/main.m +++ b/main.m @@ -21,11 +21,9 @@ */ #import -#include "smc.h" -int main(int argc, char *argv[]) -{ - return NSApplicationMain(argc, (const char **) argv); - +int main(int argc, char *argv[]) { + return NSApplicationMain(argc, (const char **) argv); + } diff --git a/smc-command/smc.c b/smc-command/smc.c index f023e6e..89d0e12 100755 --- a/smc-command/smc.c +++ b/smc-command/smc.c @@ -40,174 +40,144 @@ kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *ou #pragma mark C Helpers -UInt32 _strtoul(char *str, int size, int base) -{ +UInt32 _strtoul(char *str, int size, int base) { UInt32 total = 0; int i; - for (i = 0; i < size; i++) - { + for (i = 0; i < size; i++) { if (base == 16) total += str[i] << (size - 1 - i) * 8; else - total += ((unsigned char) (str[i]) << (size - 1 - i) * 8); + total += ((unsigned char) (str[i]) << (size - 1 - i) * 8); } return total; } -void _ultostr(char *str, UInt32 val) -{ +void _ultostr(char *str, UInt32 val) { str[0] = '\0'; sprintf(str, "%c%c%c%c", - (unsigned int) val >> 24, - (unsigned int) val >> 16, - (unsigned int) val >> 8, - (unsigned int) val); + (unsigned int) val >> 24, + (unsigned int) val >> 16, + (unsigned int) val >> 8, + (unsigned int) val); } -float _strtof(unsigned char *str, int size, int e) -{ +float _strtof(unsigned char *str, int size, int e) { float total = 0; int i; - - for (i = 0; i < size; i++) - { + + for (i = 0; i < size; i++) { if (i == (size - 1)) total += (str[i] & 0xff) >> e; else total += str[i] << (size - 1 - i) * (8 - e); } - - total += (str[size-1] & 0x03) * 0.25; - + + total += (str[size - 1] & 0x03) * 0.25; + return total; } -void printFLT(SMCVal_t val) -{ +void printFLT(SMCVal_t val) { float fval; - memcpy(&fval,val.bytes,sizeof(float)); + memcpy(&fval, val.bytes, sizeof(float)); printf("%.0f ", fval); } -void printFP1F(SMCVal_t val) -{ - printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 32768.0); +void printFP1F(SMCVal_t val) { + printf("%.5f ", ntohs(*(UInt16 *) val.bytes) / 32768.0); } -void printFP4C(SMCVal_t val) -{ - printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 4096.0); +void printFP4C(SMCVal_t val) { + printf("%.5f ", ntohs(*(UInt16 *) val.bytes) / 4096.0); } -void printFP5B(SMCVal_t val) -{ - printf("%.5f ", ntohs(*(UInt16*)val.bytes) / 2048.0); +void printFP5B(SMCVal_t val) { + printf("%.5f ", ntohs(*(UInt16 *) val.bytes) / 2048.0); } -void printFP6A(SMCVal_t val) -{ - printf("%.4f ", ntohs(*(UInt16*)val.bytes) / 1024.0); +void printFP6A(SMCVal_t val) { + printf("%.4f ", ntohs(*(UInt16 *) val.bytes) / 1024.0); } -void printFP79(SMCVal_t val) -{ - printf("%.4f ", ntohs(*(UInt16*)val.bytes) / 512.0); +void printFP79(SMCVal_t val) { + printf("%.4f ", ntohs(*(UInt16 *) val.bytes) / 512.0); } -void printFP88(SMCVal_t val) -{ - printf("%.3f ", ntohs(*(UInt16*)val.bytes) / 256.0); +void printFP88(SMCVal_t val) { + printf("%.3f ", ntohs(*(UInt16 *) val.bytes) / 256.0); } -void printFPA6(SMCVal_t val) -{ - printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 64.0); +void printFPA6(SMCVal_t val) { + printf("%.2f ", ntohs(*(UInt16 *) val.bytes) / 64.0); } -void printFPC4(SMCVal_t val) -{ - printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 16.0); +void printFPC4(SMCVal_t val) { + printf("%.2f ", ntohs(*(UInt16 *) val.bytes) / 16.0); } -void printFPE2(SMCVal_t val) -{ - printf("%.2f ", ntohs(*(UInt16*)val.bytes) / 4.0); +void printFPE2(SMCVal_t val) { + printf("%.2f ", ntohs(*(UInt16 *) val.bytes) / 4.0); } -void printUInt(SMCVal_t val) -{ - printf("%u ", (unsigned int) _strtoul((char *)val.bytes, val.dataSize, 10)); +void printUInt(SMCVal_t val) { + printf("%u ", (unsigned int) _strtoul((char *) val.bytes, val.dataSize, 10)); } -void printSP1E(SMCVal_t val) -{ - printf("%.5f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 16384.0); +void printSP1E(SMCVal_t val) { + printf("%.5f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 16384.0); } -void printSP3C(SMCVal_t val) -{ - printf("%.5f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 4096.0); +void printSP3C(SMCVal_t val) { + printf("%.5f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 4096.0); } -void printSP4B(SMCVal_t val) -{ - printf("%.4f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 2048.0); +void printSP4B(SMCVal_t val) { + printf("%.4f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 2048.0); } -void printSP5A(SMCVal_t val) -{ - printf("%.4f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 1024.0); +void printSP5A(SMCVal_t val) { + printf("%.4f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 1024.0); } -void printSP69(SMCVal_t val) -{ - printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 512.0); +void printSP69(SMCVal_t val) { + printf("%.3f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 512.0); } -void printSP78(SMCVal_t val) -{ - printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 256.0); +void printSP78(SMCVal_t val) { + printf("%.3f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 256.0); } -void printSP87(SMCVal_t val) -{ - printf("%.3f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 128.0); +void printSP87(SMCVal_t val) { + printf("%.3f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 128.0); } -void printSP96(SMCVal_t val) -{ - printf("%.2f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 64.0); +void printSP96(SMCVal_t val) { + printf("%.2f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 64.0); } -void printSPB4(SMCVal_t val) -{ - printf("%.2f ", ((SInt16)ntohs(*(UInt16*)val.bytes)) / 16.0); +void printSPB4(SMCVal_t val) { + printf("%.2f ", ((SInt16) ntohs(*(UInt16 *) val.bytes)) / 16.0); } -void printSPF0(SMCVal_t val) -{ - printf("%.0f ", (float)ntohs(*(UInt16*)val.bytes)); +void printSPF0(SMCVal_t val) { + printf("%.0f ", (float) ntohs(*(UInt16 *) val.bytes)); } -void printSI8(SMCVal_t val) -{ - printf("%d ", (signed char)*val.bytes); +void printSI8(SMCVal_t val) { + printf("%d ", (signed char) *val.bytes); } -void printSI16(SMCVal_t val) -{ - printf("%d ", ntohs(*(SInt16*)val.bytes)); +void printSI16(SMCVal_t val) { + printf("%d ", ntohs(*(SInt16 *) val.bytes)); } -void printPWM(SMCVal_t val) -{ - printf("%.1f%% ", ntohs(*(UInt16*)val.bytes) * 100 / 65536.0); +void printPWM(SMCVal_t val) { + printf("%.1f%% ", ntohs(*(UInt16 *) val.bytes) * 100 / 65536.0); } -void printBytesHex(SMCVal_t val) -{ +void printBytesHex(SMCVal_t val) { int i; printf("(bytes"); @@ -216,11 +186,9 @@ void printBytesHex(SMCVal_t val) printf(")\n"); } -void printVal(SMCVal_t val) -{ +void printVal(SMCVal_t val) { printf(" %-4s [%-4s] ", val.key, val.dataType); - if (val.dataSize > 0) - { + if (val.dataSize > 0) { if ((strcmp(val.dataType, DATATYPE_UINT8) == 0) || (strcmp(val.dataType, DATATYPE_UINT16) == 0) || (strcmp(val.dataType, DATATYPE_UINT32) == 0)) @@ -245,174 +213,157 @@ void printVal(SMCVal_t val) printFPC4(val); else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) printFPE2(val); - else if (strcmp(val.dataType, DATATYPE_SP1E) == 0 && val.dataSize == 2) - printSP1E(val); - else if (strcmp(val.dataType, DATATYPE_SP3C) == 0 && val.dataSize == 2) - printSP3C(val); - else if (strcmp(val.dataType, DATATYPE_SP4B) == 0 && val.dataSize == 2) - printSP4B(val); - else if (strcmp(val.dataType, DATATYPE_SP5A) == 0 && val.dataSize == 2) - printSP5A(val); - else if (strcmp(val.dataType, DATATYPE_SP69) == 0 && val.dataSize == 2) - printSP69(val); - else if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) - printSP78(val); - else if (strcmp(val.dataType, DATATYPE_SP87) == 0 && val.dataSize == 2) - printSP87(val); - else if (strcmp(val.dataType, DATATYPE_SP96) == 0 && val.dataSize == 2) - printSP96(val); - else if (strcmp(val.dataType, DATATYPE_SPB4) == 0 && val.dataSize == 2) - printSPB4(val); - else if (strcmp(val.dataType, DATATYPE_SPF0) == 0 && val.dataSize == 2) - printSPF0(val); - else if (strcmp(val.dataType, DATATYPE_SI8) == 0 && val.dataSize == 1) - printSI8(val); - else if (strcmp(val.dataType, DATATYPE_SI16) == 0 && val.dataSize == 2) - printSI16(val); - else if (strcmp(val.dataType, DATATYPE_PWM) == 0 && val.dataSize == 2) - printPWM(val); - else if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) - printFLT(val); + else if (strcmp(val.dataType, DATATYPE_SP1E) == 0 && val.dataSize == 2) + printSP1E(val); + else if (strcmp(val.dataType, DATATYPE_SP3C) == 0 && val.dataSize == 2) + printSP3C(val); + else if (strcmp(val.dataType, DATATYPE_SP4B) == 0 && val.dataSize == 2) + printSP4B(val); + else if (strcmp(val.dataType, DATATYPE_SP5A) == 0 && val.dataSize == 2) + printSP5A(val); + else if (strcmp(val.dataType, DATATYPE_SP69) == 0 && val.dataSize == 2) + printSP69(val); + else if (strcmp(val.dataType, DATATYPE_SP78) == 0 && val.dataSize == 2) + printSP78(val); + else if (strcmp(val.dataType, DATATYPE_SP87) == 0 && val.dataSize == 2) + printSP87(val); + else if (strcmp(val.dataType, DATATYPE_SP96) == 0 && val.dataSize == 2) + printSP96(val); + else if (strcmp(val.dataType, DATATYPE_SPB4) == 0 && val.dataSize == 2) + printSPB4(val); + else if (strcmp(val.dataType, DATATYPE_SPF0) == 0 && val.dataSize == 2) + printSPF0(val); + else if (strcmp(val.dataType, DATATYPE_SI8) == 0 && val.dataSize == 1) + printSI8(val); + else if (strcmp(val.dataType, DATATYPE_SI16) == 0 && val.dataSize == 2) + printSI16(val); + else if (strcmp(val.dataType, DATATYPE_PWM) == 0 && val.dataSize == 2) + printPWM(val); + else if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) + printFLT(val); printBytesHex(val); - } - else - { - printf("no data\n"); + } else { + printf("no data\n"); } } #pragma mark Shared SMC functions -kern_return_t SMCOpen(io_connect_t *conn) -{ +kern_return_t SMCOpen(io_connect_t *conn) { kern_return_t result; - mach_port_t masterPort; + mach_port_t masterPort; io_iterator_t iterator; - io_object_t device; - - IOMasterPort(MACH_PORT_NULL, &masterPort); - + io_object_t device; + + IOMasterPort(MACH_PORT_NULL, &masterPort); + CFMutableDictionaryRef matchingDictionary = IOServiceMatching("AppleSMC"); result = IOServiceGetMatchingServices(masterPort, matchingDictionary, &iterator); - if (result != kIOReturnSuccess) - { + if (result != kIOReturnSuccess) { printf("Error: IOServiceGetMatchingServices() = %08x\n", result); return 1; } - + device = IOIteratorNext(iterator); IOObjectRelease(iterator); - if (device == 0) - { + if (device == 0) { printf("Error: no SMC found\n"); return 1; } - + result = IOServiceOpen(device, mach_task_self(), 0, conn); IOObjectRelease(device); - if (result != kIOReturnSuccess) - { + if (result != kIOReturnSuccess) { printf("Error: IOServiceOpen() = %08x\n", result); return 1; } - + return kIOReturnSuccess; } -kern_return_t SMCClose(io_connect_t conn) -{ +kern_return_t SMCClose(io_connect_t conn) { return IOServiceClose(conn); } -kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure,io_connect_t conn) -{ - size_t structureInputSize; - size_t structureOutputSize; +kern_return_t SMCCall2(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure, io_connect_t conn) { + size_t structureInputSize; + size_t structureOutputSize; structureInputSize = sizeof(SMCKeyData_t); structureOutputSize = sizeof(SMCKeyData_t); - + return IOConnectCallStructMethod(conn, index, inputStructure, structureInputSize, outputStructure, &structureOutputSize); } // Provides key info, using a cache to dramatically improve the energy impact of smcFanControl -kern_return_t SMCGetKeyInfo(UInt32 key, SMCKeyData_keyInfo_t* keyInfo, io_connect_t conn) -{ +kern_return_t SMCGetKeyInfo(UInt32 key, SMCKeyData_keyInfo_t *keyInfo, io_connect_t conn) { SMCKeyData_t inputStructure; SMCKeyData_t outputStructure; kern_return_t result = kIOReturnSuccess; int i = 0; - + OSSpinLockLock(&g_keyInfoSpinLock); - - for (; i < g_keyInfoCacheCount; ++i) - { - if (key == g_keyInfoCache[i].key) - { + + for (; i < g_keyInfoCacheCount; ++i) { + if (key == g_keyInfoCache[i].key) { *keyInfo = g_keyInfoCache[i].keyInfo; break; } } - - if (i == g_keyInfoCacheCount) - { + + if (i == g_keyInfoCacheCount) { // Not in cache, must look it up. memset(&inputStructure, 0, sizeof(inputStructure)); memset(&outputStructure, 0, sizeof(outputStructure)); - + inputStructure.key = key; inputStructure.data8 = SMC_CMD_READ_KEYINFO; - + result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure, conn); - if (result == kIOReturnSuccess) - { + if (result == kIOReturnSuccess) { *keyInfo = outputStructure.keyInfo; - if (g_keyInfoCacheCount < KEY_INFO_CACHE_SIZE) - { + if (g_keyInfoCacheCount < KEY_INFO_CACHE_SIZE) { g_keyInfoCache[g_keyInfoCacheCount].key = key; g_keyInfoCache[g_keyInfoCacheCount].keyInfo = outputStructure.keyInfo; ++g_keyInfoCacheCount; } } } - + OSSpinLockUnlock(&g_keyInfoSpinLock); - + return result; } -kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn) -{ +kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val, io_connect_t conn) { kern_return_t result; - SMCKeyData_t inputStructure; - SMCKeyData_t outputStructure; - + SMCKeyData_t inputStructure; + SMCKeyData_t outputStructure; + memset(&inputStructure, 0, sizeof(SMCKeyData_t)); memset(&outputStructure, 0, sizeof(SMCKeyData_t)); memset(val, 0, sizeof(SMCVal_t)); - + inputStructure.key = _strtoul(key, 4, 16); sprintf(val->key, key); - + result = SMCGetKeyInfo(inputStructure.key, &outputStructure.keyInfo, conn); - if (result != kIOReturnSuccess) - { + if (result != kIOReturnSuccess) { return result; } - + val->dataSize = outputStructure.keyInfo.dataSize; _ultostr(val->dataType, outputStructure.keyInfo.dataType); inputStructure.keyInfo.dataSize = val->dataSize; inputStructure.data8 = SMC_CMD_READ_BYTES; - - result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure,conn); - if (result != kIOReturnSuccess) - { + + result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure, conn); + if (result != kIOReturnSuccess) { return result; } - + memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); - + return kIOReturnSuccess; } @@ -423,11 +374,11 @@ kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn) io_connect_t g_conn = 0; void smc_init(){ - SMCOpen(&g_conn); + SMCOpen(&g_conn); } void smc_close(){ - SMCClose(g_conn); + SMCClose(g_conn); } kern_return_t SMCCall(int index, SMCKeyData_t *inputStructure, SMCKeyData_t *outputStructure) @@ -445,25 +396,25 @@ kern_return_t SMCWriteKey2(SMCVal_t writeVal, io_connect_t conn) kern_return_t result; SMCKeyData_t inputStructure; SMCKeyData_t outputStructure; - + SMCVal_t readVal; - + result = SMCReadKey2(writeVal.key, &readVal,conn); if (result != kIOReturnSuccess) return result; - + if (readVal.dataSize != writeVal.dataSize) return kIOReturnError; - + memset(&inputStructure, 0, sizeof(SMCKeyData_t)); memset(&outputStructure, 0, sizeof(SMCKeyData_t)); - + inputStructure.key = _strtoul(writeVal.key, 4, 16); inputStructure.data8 = SMC_CMD_WRITE_BYTES; inputStructure.keyInfo.dataSize = writeVal.dataSize; memcpy(inputStructure.bytes, writeVal.bytes, sizeof(writeVal.bytes)); result = SMCCall2(KERNEL_INDEX_SMC, &inputStructure, &outputStructure,conn); - + if (result != kIOReturnSuccess) return result; return kIOReturnSuccess; @@ -477,7 +428,7 @@ kern_return_t SMCWriteKey(SMCVal_t writeVal) UInt32 SMCReadIndexCount(void) { SMCVal_t val; - + SMCReadKey("#KEY", &val); return _strtoul((char *)val.bytes, val.dataSize, 10); } @@ -487,31 +438,31 @@ kern_return_t SMCPrintAll(void) kern_return_t result; SMCKeyData_t inputStructure; SMCKeyData_t outputStructure; - + int totalKeys, i; UInt32Char_t key; SMCVal_t val; - + totalKeys = SMCReadIndexCount(); for (i = 0; i < totalKeys; i++) { memset(&inputStructure, 0, sizeof(SMCKeyData_t)); memset(&outputStructure, 0, sizeof(SMCKeyData_t)); memset(&val, 0, sizeof(SMCVal_t)); - + inputStructure.data8 = SMC_CMD_READ_INDEX; inputStructure.data32 = i; - + result = SMCCall(KERNEL_INDEX_SMC, &inputStructure, &outputStructure); if (result != kIOReturnSuccess) continue; - + _ultostr(key, outputStructure.key); - - SMCReadKey(key, &val); + + SMCReadKey(key, &val); printVal(val); } - + return kIOReturnSuccess; } @@ -524,16 +475,16 @@ float getFloatFromVal(SMCVal_t val) if (val.dataSize > 0) { if (strcmp(val.dataType, DATATYPE_FLT) == 0 && val.dataSize == 4) { - memcpy(&fval,val.bytes,sizeof(float)); + memcpy(&fval,val.bytes,sizeof(float)); } else if (strcmp(val.dataType, DATATYPE_FPE2) == 0 && val.dataSize == 2) { - fval = _strtof(val.bytes, val.dataSize, 2); + fval = _strtof(val.bytes, val.dataSize, 2); } else if (strcmp(val.dataType, DATATYPE_UINT16) == 0 && val.dataSize == 2) { - fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); + fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); } else if (strcmp(val.dataType, DATATYPE_UINT8) == 0 && val.dataSize == 1) { - fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); + fval = (float)_strtoul((char *)val.bytes, val.dataSize, 10); } } @@ -546,14 +497,14 @@ kern_return_t SMCPrintFans(void) SMCVal_t val; UInt32Char_t key; int totalFans, i; - + result = SMCReadKey("FNum", &val); if (result != kIOReturnSuccess) return kIOReturnError; - + totalFans = _strtoul((char *)val.bytes, val.dataSize, 10); printf("Total fans in system: %d\n", totalFans); - + for (i = 0; i < totalFans; i++) { printf("\nFan #%d:\n", i); @@ -593,7 +544,7 @@ kern_return_t SMCPrintFans(void) printf(" Mode : auto\n"); } } - + return kIOReturnSuccess; } @@ -669,7 +620,7 @@ kern_return_t SMCWriteSimple(UInt32Char_t key, char *wvalue, io_connect_t conn) result = SMCWriteKey2(val, conn); if (result != kIOReturnSuccess) printf("Error: SMCWriteKey() = %08x\n", result); - + return result; } diff --git a/smc-command/smc.h b/smc-command/smc.h index 1d06415..47ded9c 100755 --- a/smc-command/smc.h +++ b/smc-command/smc.h @@ -26,7 +26,7 @@ #define VERSION "0.01" #define OP_NONE 0 -#define OP_LIST 1 +#define OP_LIST 1 #define OP_READ 2 #define OP_READ_FAN 3 #define OP_WRITE 4 @@ -75,64 +75,70 @@ #define DATATYPE_PWM "{pwm" typedef struct { - char major; - char minor; - char build; - char reserved[1]; - UInt16 release; + char major; + char minor; + char build; + char reserved[1]; + UInt16 release; } SMCKeyData_vers_t; typedef struct { - UInt16 version; - UInt16 length; - UInt32 cpuPLimit; - UInt32 gpuPLimit; - UInt32 memPLimit; + UInt16 version; + UInt16 length; + UInt32 cpuPLimit; + UInt32 gpuPLimit; + UInt32 memPLimit; } SMCKeyData_pLimitData_t; typedef struct { - UInt32 dataSize; - UInt32 dataType; - char dataAttributes; + UInt32 dataSize; + UInt32 dataType; + char dataAttributes; } SMCKeyData_keyInfo_t; -typedef unsigned char SMCBytes_t[32]; +typedef unsigned char SMCBytes_t[32]; typedef struct { - UInt32 key; - SMCKeyData_vers_t vers; - SMCKeyData_pLimitData_t pLimitData; - SMCKeyData_keyInfo_t keyInfo; - char result; - char status; - char data8; - UInt32 data32; - SMCBytes_t bytes; + UInt32 key; + SMCKeyData_vers_t vers; + SMCKeyData_pLimitData_t pLimitData; + SMCKeyData_keyInfo_t keyInfo; + char result; + char status; + char data8; + UInt32 data32; + SMCBytes_t bytes; } SMCKeyData_t; -typedef char UInt32Char_t[5]; +typedef char UInt32Char_t[5]; typedef struct { - UInt32Char_t key; - UInt32 dataSize; - UInt32Char_t dataType; - SMCBytes_t bytes; + UInt32Char_t key; + UInt32 dataSize; + UInt32Char_t dataType; + SMCBytes_t bytes; } SMCVal_t; UInt32 _strtoul(char *str, int size, int base); + float _strtof(unsigned char *str, int size, int e); // Exclude command-line only code from smcFanControl UI #ifdef CMD_TOOL void smc_init(); + void smc_close(); + kern_return_t SMCReadKey(UInt32Char_t key, SMCVal_t *val); -kern_return_t SMCWriteSimple(UInt32Char_t key,char *wvalue,io_connect_t conn); + +kern_return_t SMCWriteSimple(UInt32Char_t key, char *wvalue, io_connect_t conn); #endif //#ifdef CMD_TOOL kern_return_t SMCOpen(io_connect_t *conn); + kern_return_t SMCClose(io_connect_t conn); -kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val,io_connect_t conn); + +kern_return_t SMCReadKey2(UInt32Char_t key, SMCVal_t *val, io_connect_t conn); diff --git a/smcFanControl.xcodeproj/project.pbxproj b/smcFanControl.xcodeproj/project.pbxproj index 53755fc..139887d 100644 --- a/smcFanControl.xcodeproj/project.pbxproj +++ b/smcFanControl.xcodeproj/project.pbxproj @@ -37,6 +37,12 @@ AFD3F221247B41B30086D29E /* DisableTurboBoost.32bits.kext in Resources */ = {isa = PBXBuildFile; fileRef = AFD3F220247B41B30086D29E /* DisableTurboBoost.32bits.kext */; }; AFD3F223247B41BC0086D29E /* DisableTurboBoost.64bits.kext in Resources */ = {isa = PBXBuildFile; fileRef = AFD3F222247B41BB0086D29E /* DisableTurboBoost.64bits.kext */; }; AFD3F22C247B58CB0086D29E /* Privilege.m in Sources */ = {isa = PBXBuildFile; fileRef = AFD3F22B247B58CB0086D29E /* Privilege.m */; }; + AFF28ECB247D987C00B47C72 /* main.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ECA247D987C00B47C72 /* main.c */; }; + AFF28ECF247D9A3B00B47C72 /* tb-switcher in CopyFiles */ = {isa = PBXBuildFile; fileRef = AFF28EC8247D987C00B47C72 /* tb-switcher */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; + AFF28ED2247D9B0600B47C72 /* com.tinkernels.tb-switcher.plist in Resources */ = {isa = PBXBuildFile; fileRef = AFF28ED0247D9A9500B47C72 /* com.tinkernels.tb-switcher.plist */; }; + AFF28ED5247DAE4F00B47C72 /* tb-switcher_s.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ED4247DAE4F00B47C72 /* tb-switcher_s.c */; }; + AFF28ED7247DAE7A00B47C72 /* tb-switcher_c.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ED6247DAE7A00B47C72 /* tb-switcher_c.c */; }; + AFF28ED8247DAE7A00B47C72 /* tb-switcher_c.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ED6247DAE7A00B47C72 /* tb-switcher_c.c */; }; /* End PBXBuildFile section */ /* Begin PBXCopyFilesBuildPhase section */ @@ -55,6 +61,7 @@ dstPath = ""; dstSubfolderSpec = 7; files = ( + AFF28ECF247D9A3B00B47C72 /* tb-switcher in CopyFiles */, 899D59DC15E1CF60003E322D /* smc in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 0; @@ -69,16 +76,25 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + AFF28EC6247D987C00B47C72 /* CopyFiles */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = /usr/share/man/man1/; + dstSubfolderSpec = 0; + files = ( + ); + runOnlyForDeploymentPostprocessing = 1; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 089C165DFE840E0CC02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; }; + 089C165DFE840E0CC02AAC07 /* English */ = {isa = PBXFileReference; fileEncoding = 2483028224; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/InfoPlist.strings; sourceTree = ""; }; 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = /System/Library/Frameworks/Cocoa.framework; sourceTree = ""; }; 13E42FB307B3F0F600E4EEF1 /* CoreData.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreData.framework; path = /System/Library/Frameworks/CoreData.framework; sourceTree = ""; }; 29B97316FDCFA39411CA2CEA /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 29B97324FDCFA39411CA2CEA /* AppKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AppKit.framework; path = /System/Library/Frameworks/AppKit.framework; sourceTree = ""; }; 29B97325FDCFA39411CA2CEA /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = /System/Library/Frameworks/Foundation.framework; sourceTree = ""; }; - 4C65C0201AC83BED006E760F /* French */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = French; path = French.lproj/Localizable.strings; sourceTree = ""; }; + 4C65C0201AC83BED006E760F /* French */ = {isa = PBXFileReference; fileEncoding = 2483028224; lastKnownFileType = text.plist.strings; name = French; path = French.lproj/Localizable.strings; sourceTree = ""; }; 4C65C0211AC83BF2006E760F /* French */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = French; path = French.lproj/MainMenu.nib; sourceTree = ""; }; 4C65C0221AC83BF7006E760F /* French */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = French; path = French.lproj/F.A.Q.rtf; sourceTree = ""; }; 89033CA10B80E1DF00FDAF43 /* English */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = English; path = English.lproj/F.A.Q.rtf; sourceTree = ""; }; @@ -99,7 +115,7 @@ 8932CFF813D08DC4008BC447 /* Dutch */ = {isa = PBXFileReference; lastKnownFileType = text.rtf; name = Dutch; path = Dutch.lproj/F.A.Q.rtf; sourceTree = ""; }; 8932CFF913D08DD7008BC447 /* Dutch */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = Dutch; path = Dutch.lproj/Localizable.strings; sourceTree = ""; }; 8932CFFA13D08DDF008BC447 /* Dutch */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = Dutch; path = Dutch.lproj/MainMenu.nib; sourceTree = ""; }; - 893506130B440249001BFBA5 /* English */ = {isa = PBXFileReference; fileEncoding = 10; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = ""; }; + 893506130B440249001BFBA5 /* English */ = {isa = PBXFileReference; fileEncoding = 2483028224; lastKnownFileType = text.plist.strings; name = English; path = English.lproj/Localizable.strings; sourceTree = ""; }; 8935061B0B440264001BFBA5 /* German */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.strings; name = German; path = German.lproj/Localizable.strings; sourceTree = ""; }; 894A465F0ADBD6CF008785F3 /* FanControl.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = FanControl.h; sourceTree = ""; }; 894A46600ADBD6CF008785F3 /* FanControl.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = FanControl.m; sourceTree = ""; }; @@ -127,6 +143,12 @@ AFD3F222247B41BB0086D29E /* DisableTurboBoost.64bits.kext */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.kernel-extension"; path = DisableTurboBoost.64bits.kext; sourceTree = ""; }; AFD3F22B247B58CB0086D29E /* Privilege.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Privilege.m; sourceTree = ""; }; AFD3F22D247B591A0086D29E /* Privilege.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Privilege.h; sourceTree = ""; }; + AFF28EC8247D987C00B47C72 /* tb-switcher */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "tb-switcher"; sourceTree = BUILT_PRODUCTS_DIR; }; + AFF28ECA247D987C00B47C72 /* main.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = main.c; sourceTree = ""; }; + AFF28ED0247D9A9500B47C72 /* com.tinkernels.tb-switcher.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "com.tinkernels.tb-switcher.plist"; sourceTree = ""; }; + AFF28ED3247DA41A00B47C72 /* tb-switcher.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "tb-switcher.h"; sourceTree = ""; }; + AFF28ED4247DAE4F00B47C72 /* tb-switcher_s.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = "tb-switcher_s.c"; sourceTree = ""; }; + AFF28ED6247DAE7A00B47C72 /* tb-switcher_c.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = "tb-switcher_c.c"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -150,6 +172,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + AFF28EC5247D987C00B47C72 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -204,6 +233,7 @@ children = ( 8D1107320486CEB800E47090 /* smcFanControl.app */, 8924ECEE15AC96E70031730C /* smc */, + AFF28EC8247D987C00B47C72 /* tb-switcher */, ); name = Products; sourceTree = ""; @@ -211,6 +241,7 @@ 29B97314FDCFA39411CA2CEA /* FanControl */ = { isa = PBXGroup; children = ( + AFF28EC9247D987C00B47C72 /* tb-switcher */, 898C281A15E2B6E30044EEC3 /* smc-command */, 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, @@ -233,6 +264,7 @@ 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( + AFF28ED0247D9A9500B47C72 /* com.tinkernels.tb-switcher.plist */, AFD3F222247B41BB0086D29E /* DisableTurboBoost.64bits.kext */, AFD3F220247B41B30086D29E /* DisableTurboBoost.32bits.kext */, 89559A830BAC338400DBA37E /* smcover.png */, @@ -268,6 +300,17 @@ path = "smc-command"; sourceTree = ""; }; + AFF28EC9247D987C00B47C72 /* tb-switcher */ = { + isa = PBXGroup; + children = ( + AFF28ECA247D987C00B47C72 /* main.c */, + AFF28ED3247DA41A00B47C72 /* tb-switcher.h */, + AFF28ED4247DAE4F00B47C72 /* tb-switcher_s.c */, + AFF28ED6247DAE7A00B47C72 /* tb-switcher_c.c */, + ); + path = "tb-switcher"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -308,6 +351,23 @@ productReference = 8D1107320486CEB800E47090 /* smcFanControl.app */; productType = "com.apple.product-type.application"; }; + AFF28EC7247D987C00B47C72 /* tb-switcher */ = { + isa = PBXNativeTarget; + buildConfigurationList = AFF28ECE247D987C00B47C72 /* Build configuration list for PBXNativeTarget "tb-switcher" */; + buildPhases = ( + AFF28EC4247D987C00B47C72 /* Sources */, + AFF28EC5247D987C00B47C72 /* Frameworks */, + AFF28EC6247D987C00B47C72 /* CopyFiles */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "tb-switcher"; + productName = "tb-switcher"; + productReference = AFF28EC8247D987C00B47C72 /* tb-switcher */; + productType = "com.apple.product-type.tool"; + }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ @@ -322,6 +382,11 @@ 8D1107260486CEB800E47090 = { DevelopmentTeam = YKS755N9YR; }; + AFF28EC7247D987C00B47C72 = { + CreatedOnToolsVersion = 11.5; + DevelopmentTeam = YKS755N9YR; + ProvisioningStyle = Automatic; + }; }; }; buildConfigurationList = C01FCF4E08A954540054247B /* Build configuration list for PBXProject "smcFanControl" */; @@ -345,6 +410,7 @@ targets = ( 8D1107260486CEB800E47090 /* smcFanControl */, 8924ECED15AC96E70031730C /* smc */, + AFF28EC7247D987C00B47C72 /* tb-switcher */, ); }; /* End PBXProject section */ @@ -362,6 +428,7 @@ 89033CA70B80E1EB00FDAF43 /* F.A.Q.rtf in Resources */, 8987FBD20B878B3900A5ED8E /* smc.png in Resources */, 89559A840BAC338500DBA37E /* smcover.png in Resources */, + AFF28ED2247D9B0600B47C72 /* com.tinkernels.tb-switcher.plist in Resources */, 89FE24230B7F4CD300D2713C /* MainMenu.nib in Resources */, AFD3F221247B41B30086D29E /* DisableTurboBoost.32bits.kext in Resources */, AFD3F223247B41BC0086D29E /* DisableTurboBoost.64bits.kext in Resources */, @@ -390,12 +457,23 @@ 893355FF1CA02F1A00388D5D /* smc.c in Sources */, 891683E90AEBD95B00888535 /* smcWrapper.m in Sources */, 89949E8D0AEEA37700077E93 /* Power.m in Sources */, + AFF28ED7247DAE7A00B47C72 /* tb-switcher_c.c in Sources */, 892A7F450B10B7700041B493 /* MachineDefaults.m in Sources */, 8932CF2413D08551008BC447 /* SystemVersion.m in Sources */, 89148EA315E2543D00A073EE /* NSFileManager+DirectoryLocations.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; + AFF28EC4247D987C00B47C72 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + AFF28ED5247DAE4F00B47C72 /* tb-switcher_s.c in Sources */, + AFF28ECB247D987C00B47C72 /* main.c in Sources */, + AFF28ED8247DAE7A00B47C72 /* tb-switcher_c.c in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXSourcesBuildPhase section */ /* Begin PBXVariantGroup section */ @@ -503,9 +581,123 @@ }; name = Release; }; + AFF28ECC247D987C00B47C72 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Automatic; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = YKS755N9YR; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_VERSION = ""; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + MACOSX_DEPLOYMENT_TARGET = 10.7; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + AFF28ECD247D987C00B47C72 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_STYLE = Automatic; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = YKS755N9YR; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_VERSION = ""; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + MACOSX_DEPLOYMENT_TARGET = 10.7; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; C01FCF4B08A954540054247B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; @@ -548,8 +740,9 @@ C01FCF4C08A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; - CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_IDENTITY = "Mac Developer"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; CURRENT_PROJECT_VERSION = 2.7.0; @@ -576,7 +769,7 @@ ); MACOSX_DEPLOYMENT_TARGET = 10.7; MARKETING_VERSION = 2.7.0; - OBJROOT = "$(HOME)/builds"; + OBJROOT = "build-release"; ONLY_ACTIVE_ARCH = NO; OTHER_CODE_SIGN_FLAGS = "--deep"; PRODUCT_BUNDLE_IDENTIFIER = com.eidac.smcFanControl2; @@ -584,7 +777,7 @@ PROVISIONING_PROFILE = ""; PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; - SYMROOT = "$(HOME)/builds"; + SYMROOT = "build-release"; VALID_ARCHS = "i386 x86_64"; WRAPPER_EXTENSION = app; }; @@ -621,7 +814,7 @@ OTHER_CFLAGS = ""; OTHER_LDFLAGS = ""; SDKROOT = macosx; - SYMROOT = "~/builds"; + SYMROOT = "build-release"; VALID_ARCHS = "i386 x86_64"; }; name = Release; @@ -638,6 +831,15 @@ defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; + AFF28ECE247D987C00B47C72 /* Build configuration list for PBXNativeTarget "tb-switcher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + AFF28ECC247D987C00B47C72 /* Debug */, + AFF28ECD247D987C00B47C72 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; C01FCF4A08A954540054247B /* Build configuration list for PBXNativeTarget "smcFanControl" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/tb-switcher/main.c b/tb-switcher/main.c new file mode 100644 index 0000000..b2cb36b --- /dev/null +++ b/tb-switcher/main.c @@ -0,0 +1,23 @@ +// +// main.c +// tb-switcher +// +// Created by Don Johnny on 2020/5/27. +// + +/************************************************************/ +/* This is a datagram socket server sample program for UNIX */ +/* domain sockets. This program creates a socket and */ +/* receives data from a client. */ +/************************************************************/ + +#include "tb-switcher.h" + +#undef sock_errno +#define sock_errno() errno + +int main() { + + return start_server(); + +} diff --git a/tb-switcher/tb-switcher.h b/tb-switcher/tb-switcher.h new file mode 100644 index 0000000..fdf8ccb --- /dev/null +++ b/tb-switcher/tb-switcher.h @@ -0,0 +1,21 @@ +// +// tb-switcher.h +// smcFanControl +// +// Created by Don Johnny on 2020/5/27. +// + +#ifndef tb_switcher_h +#define tb_switcher_h + +#define ENABLE_TB_CMD "ENABLE_TB" +#define DISABLE_TB_CMD "DISABLE_TB" +#define SOCK_PATH "/var/run/tb-switcher.socket" + +int start_server(void); + +int enable_tb(void); + +int disable_tb(void); + +#endif /* tb_switcher_h */ diff --git a/tb-switcher/tb-switcher_c.c b/tb-switcher/tb-switcher_c.c new file mode 100644 index 0000000..dc80945 --- /dev/null +++ b/tb-switcher/tb-switcher_c.c @@ -0,0 +1,80 @@ +// +// tb-switcher_c.c +// smcFanControl +// +// Created by Don Johnny on 2020/5/27. +// + +/************************************************************/ +/* This is a datagram socket client sample program for UNIX */ +/* domain sockets. This program creates a socket and sends */ +/* data to a server. */ +/************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +#include "tb-switcher.h" + +#undef sock_errno +#define sock_errno() errno + +int client() { + int client_socket; + ssize_t rc; + struct sockaddr_un remote; + char buf[256]; + memset(&remote, 0, sizeof(struct sockaddr_un)); + + /****************************************/ + /* Create a UNIX domain datagram socket */ + /****************************************/ + client_socket = socket(AF_UNIX, SOCK_DGRAM, 0); + if (client_socket == -1) { + printf("SOCKET ERROR = %d\n", sock_errno()); + exit(1); + } + + /***************************************/ + /* Set up the UNIX sockaddr structure */ + /* by using AF_UNIX for the family and */ + /* giving it a filepath to send to. */ + /***************************************/ + remote.sun_family = AF_UNIX; + strcpy(remote.sun_path, SOCK_PATH); + + /***************************************/ + /* Copy the data to be sent to the */ + /* buffer and send it to the server. */ + /***************************************/ + strcpy(buf, "DATA"); + printf("Sending data...\n"); + rc = sendto(client_socket, buf, strlen(buf), 0, (struct sockaddr *) &remote, sizeof(remote)); + if (rc == -1) { + printf("SENDTO ERROR = %d\n", sock_errno()); + close(client_socket); + exit(1); + } else { + printf("Data sent!\n"); + } + + /*****************************/ + /* Close the socket and exit */ + /*****************************/ + rc = close(client_socket); + + return 0; +} + +int enable_tb() { + return 0; +}; + +int disable_tb() { + return 0; +}; \ No newline at end of file diff --git a/tb-switcher/tb-switcher_s.c b/tb-switcher/tb-switcher_s.c new file mode 100644 index 0000000..a1544c8 --- /dev/null +++ b/tb-switcher/tb-switcher_s.c @@ -0,0 +1,78 @@ +// +// tb-switcher_s.c +// tb-switcher +// +// Created by Don Johnny on 2020/5/27. +// + +#include +#include +#include +#include +#include +#include +#include +#include "tb-switcher.h" + +#undef sock_errno +#define sock_errno() errno + +int start_server() { + int server_sock, rc; + socklen_t len; + ssize_t bytes_rec = 0; + struct sockaddr_un server_sockaddr, peer_sock; + char buf[256]; + memset(&server_sockaddr, 0, sizeof(struct sockaddr_un)); + memset(buf, 0, 256); + + /****************************************/ + /* Create a UNIX domain datagram socket */ + /****************************************/ + server_sock = socket(AF_UNIX, SOCK_DGRAM, 0); + if (server_sock == -1) { + printf("SOCKET ERROR = %d\n", sock_errno()); + exit(1); + } + + /***************************************/ + /* Set up the UNIX sockaddr structure */ + /* by using AF_UNIX for the family and */ + /* giving it a filepath to bind to. */ + /* */ + /* Unlink the file so the bind will */ + /* succeed, then bind to that file. */ + /***************************************/ + server_sockaddr.sun_family = AF_UNIX; + strcpy(server_sockaddr.sun_path, SOCK_PATH); + // len = sizeof(server_sockaddr); + len = (socklen_t) SUN_LEN(&server_sockaddr); + unlink(SOCK_PATH); + rc = bind(server_sock, (struct sockaddr *) &server_sockaddr, len); + if (rc == -1) { + printf("BIND ERROR = %d\n", sock_errno()); + close(server_sock); + exit(1); + } + + /****************************************/ + /* Read data on the server from clients */ + /* and print the data that was read. */ + /****************************************/ + printf("waiting to recvfrom...\n"); + bytes_rec = recvfrom(server_sock, buf, 256, 0, (struct sockaddr *) &peer_sock, &len); + if (bytes_rec == -1) { + printf("RECVFROM ERROR = %d\n", sock_errno()); + close(server_sock); + exit(1); + } else { + printf("DATA RECEIVED = %s\n", buf); + } + + /*****************************/ + /* Close the socket and exit */ + /*****************************/ + close(server_sock); + + return 0; +} From 70d749d3020ab14b36b4f1269dad1c9c33d91ccc Mon Sep 17 00:00:00 2001 From: tinkernels Date: Wed, 27 May 2020 13:17:29 +0800 Subject: [PATCH 6/8] Add LaunchDaemon for turbo boost switcher. --- Classes/FanControl.m | 95 +++++++++----- Classes/Privilege.h | 5 + Classes/Privilege.m | 46 ++++++- .../Contents/MacOS/DisableTurboBoost | Bin 2012 -> 2060 bytes .../Contents/MacOS/DisableTurboBoost | Bin 8840 -> 8840 bytes Ressources/com.tinkernels.tb-switcher.plist | 8 +- smcFanControl.xcodeproj/project.pbxproj | 8 +- tb-switcher/tb-switcher.h | 7 +- tb-switcher/tb-switcher_c.c | 64 ++++------ tb-switcher/tb-switcher_s.c | 118 +++++++++++------- 10 files changed, 219 insertions(+), 132 deletions(-) diff --git a/Classes/FanControl.m b/Classes/FanControl.m index e1e5303..b2d0792 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -25,6 +25,7 @@ #import "FanControl.h" #import #import "Privilege.h" +#import "tb-switcher.h" @interface FanControl () + (void)copyMachinesIfNecessary; @@ -39,9 +40,6 @@ @implementation FanControl // Number of fans reported by the hardware. int g_numFans = 0; -NSString *moduleDstPath = - @"/Library/Application Support/smcFanControl2/DisableTurboBoost.64bits.kext"; - NSUserDefaults *defaults; #pragma mark **Init-Methods** @@ -242,23 +240,14 @@ - (void)displayDonationMessage { } } -- (void)enableTurboBoost { - [Privilege runTaskAsAdmin:@"/sbin/kextunload" andArgs:@[moduleDstPath]]; -} - -- (void)disableTurboBoost { - NSArray *argsArrayLoadKext = @[@"-v", moduleDstPath]; - [Privilege runTaskAsAdmin:@"/usr/bin/kextutil" andArgs:argsArrayLoadKext]; -} - - (void)applyTurboBoost:(id)sender { NSControlStateValue state = [sender state]; if (state == NSOffState) { [sender setState:NSOnState]; - [self enableTurboBoost]; + enable_tb(); } else { [sender setState:NSOffState]; - [self disableTurboBoost]; + disable_tb(); } } @@ -278,7 +267,7 @@ - (void)init_statusitem { [theMenu insertItem:s_menus[i] atIndex:i]; }; - [self disableTurboBoost]; + disable_tb(); NSMenuItem *fan1Item = [theMenu itemWithTitle:@"Fan: 1"]; int fan1ItemIdx = [theMenu indexOfItem:fan1Item]; NSMenuItem *turboBoostItem = [[NSMenuItem alloc] @@ -296,7 +285,6 @@ - (void)init_statusitem { [theMenu setDelegate:self]; } - #pragma mark **Action-Methods** - (IBAction)loginItem:(id)sender { @@ -617,7 +605,7 @@ - (void)terminate:(id)sender { [_readTimer invalidate]; [pw deregisterForSleepWakeNotification]; [pw deregisterForPowerChange]; - [self enableTurboBoost]; + enable_tb(); [[NSApplication sharedApplication] terminate:self]; } @@ -750,9 +738,9 @@ - (void)systemDidWakeFromSleep:(id)sender { [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState) { - [self enableTurboBoost]; + enable_tb(); } else { - [self disableTurboBoost]; + disable_tb(); } } @@ -866,46 +854,85 @@ - (void)setStartAtLogin:(BOOL)enabled { #pragma mark **SMC-Binary Owner/Right Check** ++ (void) ensureService { + NSString *tool = @"/bin/launchctl"; + NSArray *argsArray = @[@"load", @LAUNCH_DAEMON_PLIST_PATH]; + NSString *output; + NSString *error; + + if([Privilege runProcessAsAdministrator:tool withArguments:argsArray output:&output errorDescription:&error]){ + NSLog(@"output: %@", output); + }else{ + NSLog(@"error: %@", error); + } +} + //TODO: It looks like this function is called inefficiently. //call smc binary with sudo rights and apply + (void)setRights { - NSString *smcpath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; - NSFileManager *fmanage = [NSFileManager defaultManager]; - NSDictionary *fdic = [fmanage attributesOfItemAtPath:smcpath error:nil]; - if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue] == 3437)) { + NSString *smcPath = [[NSBundle mainBundle] pathForResource:@"smc" ofType:@""]; + NSFileManager *fManger = [NSFileManager defaultManager]; + NSDictionary *fdic = [fManger attributesOfItemAtPath:smcPath error:nil]; + if ([[fdic valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && + [[fdic valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"admin"] && + ([[fdic valueForKey:@"NSFilePosixPermissions"] intValue] == 3437)) { // If the SMC binary has already been modified to run as root, then do nothing. } else { NSString *tool = @"/usr/sbin/chown"; - NSArray *argsArray = @[@"root:admin", smcpath]; + NSArray *argsArray = @[@"root:admin", smcPath]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; //second call for suid-bit tool = @"/bin/chmod"; - argsArray = @[@"6555", smcpath]; + argsArray = @[@"6555", smcPath]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } - NSString *modulePath = [[NSBundle mainBundle] pathForResource:@"DisableTurboBoost.64bits" ofType:@"kext"]; - NSFileManager *fileManager = [NSFileManager defaultManager]; - if (![fileManager fileExistsAtPath:moduleDstPath]) { + if (![fManger fileExistsAtPath:@MODULE_PATH]) { NSString *tool = @"/bin/sh"; - NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@/\" \"%@\"", moduleDstPath, modulePath, moduleDstPath]]; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"mkdir -p \"%@\" && cp -Rf \"%@/\" \"%@\"", + @MODULE_PATH, modulePath, @MODULE_PATH]]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + [self setOwnAndMod:@MODULE_PATH user:@"root" group:@"wheel" mod:@"755"]; } - NSDictionary *fdicKext = [fmanage attributesOfItemAtPath:moduleDstPath error:nil]; - if ([[fdicKext valueForKey:@"NSFileOwnerAccountName"] isEqualToString:@"root"] && [[fdicKext valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:@"wheel"]) { - // If the SMC binary has already been modified to run as root, then do nothing. + + NSString *binPath = [[NSBundle mainBundle] pathForResource:@"tb-switcher" ofType:@""]; + if (![fManger fileExistsAtPath:@TB_SWITCHER_BIN_PATH]) { + NSString *tool = @"/bin/sh"; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"cp -f \"%@\" \"%@\"", + binPath, @TB_SWITCHER_BIN_PATH]]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + [self setOwnAndMod:@TB_SWITCHER_BIN_PATH user:@"root" group:@"wheel" mod:@"755"]; + } + + NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"com.tinkernels.tb-switcher" ofType:@"plist"]; + if (![fManger fileExistsAtPath:@LAUNCH_DAEMON_PLIST_PATH]) { + NSString *tool = @"/bin/sh"; + NSArray *argsArray = @[@"-c", [NSString stringWithFormat:@"cp -f \"%@\" \"%@\"", + plistPath, @LAUNCH_DAEMON_PLIST_PATH]]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + + [self setOwnAndMod:@LAUNCH_DAEMON_PLIST_PATH user:@"root" group:@"wheel" mod:@"644"]; + [self ensureService]; + } +} + ++ (void)setOwnAndMod:(NSString *)path user:(NSString *)user group:(NSString *)group mod:(NSString *)mod { + NSFileManager *fManger = [NSFileManager defaultManager]; + NSDictionary *fdict = [fManger attributesOfItemAtPath:path error:nil]; + if ([[fdict valueForKey:@"NSFileOwnerAccountName"] isEqualToString:user] && + [[fdict valueForKey:@"NSFileGroupOwnerAccountName"] isEqualToString:group]) { } else { NSString *tool = @"/usr/sbin/chown"; - NSArray *argsArray = @[@"-R", @"root:wheel", moduleDstPath]; + NSArray *argsArray = @[@"-R", [NSString stringWithFormat:@"%@:%@", user, group], path]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; tool = @"/bin/chmod"; - argsArray = @[@"-Rf", @"755", moduleDstPath]; + argsArray = @[@"-Rf", mod, path]; [Privilege runTaskAsAdmin:tool andArgs:argsArray]; } } diff --git a/Classes/Privilege.h b/Classes/Privilege.h index ebc548a..6ceb14d 100644 --- a/Classes/Privilege.h +++ b/Classes/Privilege.h @@ -14,6 +14,11 @@ + (AuthorizationRef)Get; + (BOOL)runTaskAsAdmin:(NSString *)path andArgs:(NSArray *)args; + ++ (BOOL) runProcessAsAdministrator:(NSString*)binPath + withArguments:(NSArray *)arguments + output:(NSString **)output + errorDescription:(NSString **)errorDescription; @end #endif /* Privilege_h */ diff --git a/Classes/Privilege.m b/Classes/Privilege.m index bfe90e0..030ecce 100644 --- a/Classes/Privilege.m +++ b/Classes/Privilege.m @@ -17,7 +17,7 @@ + (AuthorizationRef)Get { AuthorizationItem gencitem = {"system.privilege.admin", 0, NULL, 0}; AuthorizationRights gencright = {1, &gencitem}; int flags = kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed; - OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, flags, &authorizationRef); + OSStatus status = AuthorizationCreate(&gencright, kAuthorizationEmptyEnvironment, (AuthorizationFlags) flags, &authorizationRef); if (status != errAuthorizationSuccess) { NSLog(@"Copy Rights Unsuccessful: %d", status); @@ -27,6 +27,50 @@ + (AuthorizationRef)Get { return authorizationRef; } ++ (BOOL) runProcessAsAdministrator:(NSString*)binPath + withArguments:(NSArray *)arguments + output:(NSString **)output + errorDescription:(NSString **)errorDescription { + + NSString * allArgs = [arguments componentsJoinedByString:@" "]; + NSString * fullScript = [NSString stringWithFormat:@"%@ %@", binPath, allArgs]; + + NSDictionary *errorInfo = [NSDictionary new]; + NSString *script = [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript]; + + NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; + NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo]; + + // Check errorInfo + if (! eventResult) + { + // Describe common errors + *errorDescription = nil; + if ([errorInfo valueForKey:NSAppleScriptErrorNumber]) + { + NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber]; + if ([errorNumber intValue] == -128) + *errorDescription = @"The administrator password is required to do this."; + } + + // Set error message from provided message + if (*errorDescription == nil) + { + if ([errorInfo valueForKey:NSAppleScriptErrorMessage]) + *errorDescription = (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage]; + } + + return NO; + } + else + { + // Set output to the AppleScript's output + *output = [eventResult stringValue]; + + return YES; + } +} + + (BOOL)runTaskAsAdmin:(NSString *)path andArgs:(NSArray *)args { if ([self Get] == nil) { diff --git a/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost b/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost index 6613f4b6c8233d0c1174a96fac0355ac8ff0e07c..259ef76df72e532711280502c45f242ee93c2472 100755 GIT binary patch delta 414 zcmcb^-yFiLKVGIzSfloaI&*dag_wZyUnU1KN?VDrF)#=Nc|U-(2vDaHkgWj3DL@PZAUi;IF|g?{ zX#yz$AQoYpypct1^BhJGmiiDNpAV!62%>=)#9jcT6QOJeAU_MrP5`n?q3i`fb{&-c z0LbowvSonIn*?R+1KI1KY)c^fER^jGWIuzj>lu83oVOqj&}%6`m;QjVGk|Pnpur&V z93UG=G4KP`W&p7`l$`)%gFM9#l-vVkn*iBBEnwh-#0Ck(r(_l0q0w@X6ab$8JqcramRt5%PAnybl1B1v!Me)rC7(-a?sg-8iOy8GaJMKIyMF9hhYGS_Y!-3^fYjl$MQp-$xm|vxMWx`-c0jN_ITWUm*ecG9kA7YR$l*H2CDYK d1!$qck~cnle$heHD%L#KQN7fSrp2=j179B39@zi@ delta 330 zcmeBh?Qq?Yz{JELusMlopKLu70|NseBLjm250C)_oIniXZ-Daop?n2ikSqg(1Q3Jd z6QF!$D1QNzuLI?OfbuPXd^wltF80>MxP)lhy4ls^T^FM;xB zgZQir3?~GD3?Ntr#323!D1RfAe*?-t2;}nveK`ZF{|b~p0nArnV0Z=+02;sm)$kF> f1Um2^kOBiv#>q~KdW;H_4=Wy+T%s7j4iyIg4C)?8 diff --git a/Ressources/com.tinkernels.tb-switcher.plist b/Ressources/com.tinkernels.tb-switcher.plist index 24f1d18..d6d2074 100644 --- a/Ressources/com.tinkernels.tb-switcher.plist +++ b/Ressources/com.tinkernels.tb-switcher.plist @@ -3,12 +3,12 @@ Label - com.github.tinkernels.tb-switcher.plist + com.tinkernels.tb-switcher.plist ProgramArguments - /Library/Application Support/smcFanControl2/tb-switcher - -l - /var/run/tb-switcher.socket= + /bin/sh + -c + "/Library/Application Support/smcFanControl2/tb-switcher" RunAtLoad diff --git a/smcFanControl.xcodeproj/project.pbxproj b/smcFanControl.xcodeproj/project.pbxproj index 139887d..a34c368 100644 --- a/smcFanControl.xcodeproj/project.pbxproj +++ b/smcFanControl.xcodeproj/project.pbxproj @@ -25,7 +25,6 @@ 8985F1590ADD0B5500F9EC46 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8985F1580ADD0B5500F9EC46 /* Security.framework */; }; 8987FBD20B878B3900A5ED8E /* smc.png in Resources */ = {isa = PBXBuildFile; fileRef = 8987FBD00B878B3900A5ED8E /* smc.png */; }; 89949E8D0AEEA37700077E93 /* Power.m in Sources */ = {isa = PBXBuildFile; fileRef = 89949E8C0AEEA37700077E93 /* Power.m */; }; - 899D59DC15E1CF60003E322D /* smc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 8924ECEE15AC96E70031730C /* smc */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 899D59DD15E1CFFF003E322D /* Sparkle.framework in CopyFiles */ = {isa = PBXBuildFile; fileRef = 895BDA390B8F8F42003CD894 /* Sparkle.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; 89B243200B7E351000CAD103 /* smcfancontrol_v2.icns in Resources */ = {isa = PBXBuildFile; fileRef = 89B2431F0B7E351000CAD103 /* smcfancontrol_v2.icns */; }; 89E7D3650ADE819B000F67AB /* Machines.plist in Resources */ = {isa = PBXBuildFile; fileRef = 89E7D3640ADE819B000F67AB /* Machines.plist */; }; @@ -37,8 +36,9 @@ AFD3F221247B41B30086D29E /* DisableTurboBoost.32bits.kext in Resources */ = {isa = PBXBuildFile; fileRef = AFD3F220247B41B30086D29E /* DisableTurboBoost.32bits.kext */; }; AFD3F223247B41BC0086D29E /* DisableTurboBoost.64bits.kext in Resources */ = {isa = PBXBuildFile; fileRef = AFD3F222247B41BB0086D29E /* DisableTurboBoost.64bits.kext */; }; AFD3F22C247B58CB0086D29E /* Privilege.m in Sources */ = {isa = PBXBuildFile; fileRef = AFD3F22B247B58CB0086D29E /* Privilege.m */; }; + AFED6518247E2E4800BEDCB5 /* smc in CopyFiles */ = {isa = PBXBuildFile; fileRef = 8924ECEE15AC96E70031730C /* smc */; }; + AFED6519247E2E4B00BEDCB5 /* tb-switcher in CopyFiles */ = {isa = PBXBuildFile; fileRef = AFF28EC8247D987C00B47C72 /* tb-switcher */; }; AFF28ECB247D987C00B47C72 /* main.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ECA247D987C00B47C72 /* main.c */; }; - AFF28ECF247D9A3B00B47C72 /* tb-switcher in CopyFiles */ = {isa = PBXBuildFile; fileRef = AFF28EC8247D987C00B47C72 /* tb-switcher */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; }; AFF28ED2247D9B0600B47C72 /* com.tinkernels.tb-switcher.plist in Resources */ = {isa = PBXBuildFile; fileRef = AFF28ED0247D9A9500B47C72 /* com.tinkernels.tb-switcher.plist */; }; AFF28ED5247DAE4F00B47C72 /* tb-switcher_s.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ED4247DAE4F00B47C72 /* tb-switcher_s.c */; }; AFF28ED7247DAE7A00B47C72 /* tb-switcher_c.c in Sources */ = {isa = PBXBuildFile; fileRef = AFF28ED6247DAE7A00B47C72 /* tb-switcher_c.c */; }; @@ -61,8 +61,8 @@ dstPath = ""; dstSubfolderSpec = 7; files = ( - AFF28ECF247D9A3B00B47C72 /* tb-switcher in CopyFiles */, - 899D59DC15E1CF60003E322D /* smc in CopyFiles */, + AFED6519247E2E4B00BEDCB5 /* tb-switcher in CopyFiles */, + AFED6518247E2E4800BEDCB5 /* smc in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/tb-switcher/tb-switcher.h b/tb-switcher/tb-switcher.h index fdf8ccb..97d44b2 100644 --- a/tb-switcher/tb-switcher.h +++ b/tb-switcher/tb-switcher.h @@ -10,7 +10,12 @@ #define ENABLE_TB_CMD "ENABLE_TB" #define DISABLE_TB_CMD "DISABLE_TB" -#define SOCK_PATH "/var/run/tb-switcher.socket" +#define MODULE_PATH "/Library/Application Support/smcFanControl2/DisableTurboBoost.64bits.kext" +#define LAUNCH_DAEMON_PLIST_PATH "/Library/LaunchDaemons/com.tinkernels.tb-switcher.plist" +#define TB_SWITCHER_BIN_PATH "/Library/Application Support/smcFanControl2/tb-switcher" +#define SOCK_ADDR "127.0.0.1" +#define SOCK_PORT 11532 +#define MAX_LEN 1024 int start_server(void); diff --git a/tb-switcher/tb-switcher_c.c b/tb-switcher/tb-switcher_c.c index dc80945..0d4f026 100644 --- a/tb-switcher/tb-switcher_c.c +++ b/tb-switcher/tb-switcher_c.c @@ -13,68 +13,50 @@ #include #include -#include +#include #include +#include #include -#include -#include +#include #include "tb-switcher.h" #undef sock_errno #define sock_errno() errno -int client() { - int client_socket; - ssize_t rc; - struct sockaddr_un remote; - char buf[256]; - memset(&remote, 0, sizeof(struct sockaddr_un)); +int send_cmd(char *cmd) { + int fd_sock; + char buffer[MAX_LEN]; + strcpy(buffer, cmd); + struct sockaddr_in serv_addr; - /****************************************/ - /* Create a UNIX domain datagram socket */ - /****************************************/ - client_socket = socket(AF_UNIX, SOCK_DGRAM, 0); - if (client_socket == -1) { - printf("SOCKET ERROR = %d\n", sock_errno()); - exit(1); + // Creating socket file descriptor + if ((fd_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + perror("socket creation failed"); + exit(EXIT_FAILURE); } - /***************************************/ - /* Set up the UNIX sockaddr structure */ - /* by using AF_UNIX for the family and */ - /* giving it a filepath to send to. */ - /***************************************/ - remote.sun_family = AF_UNIX; - strcpy(remote.sun_path, SOCK_PATH); + memset(&serv_addr, 0, sizeof(serv_addr)); - /***************************************/ - /* Copy the data to be sent to the */ - /* buffer and send it to the server. */ - /***************************************/ - strcpy(buf, "DATA"); - printf("Sending data...\n"); - rc = sendto(client_socket, buf, strlen(buf), 0, (struct sockaddr *) &remote, sizeof(remote)); - if (rc == -1) { - printf("SENDTO ERROR = %d\n", sock_errno()); - close(client_socket); - exit(1); - } else { - printf("Data sent!\n"); - } + // Filling server information + serv_addr.sin_family = AF_INET; // IPv4 + inet_pton(AF_INET, SOCK_ADDR, &serv_addr.sin_addr); + serv_addr.sin_port = htons(SOCK_PORT); - /*****************************/ - /* Close the socket and exit */ - /*****************************/ - rc = close(client_socket); + sendto(fd_sock, (const char *) buffer, strlen(buffer), + 0, (const struct sockaddr *) &serv_addr, + sizeof(serv_addr)); + close(fd_sock); return 0; } int enable_tb() { + send_cmd(ENABLE_TB_CMD); return 0; }; int disable_tb() { + send_cmd(DISABLE_TB_CMD); return 0; }; \ No newline at end of file diff --git a/tb-switcher/tb-switcher_s.c b/tb-switcher/tb-switcher_s.c index a1544c8..9895e37 100644 --- a/tb-switcher/tb-switcher_s.c +++ b/tb-switcher/tb-switcher_s.c @@ -10,69 +10,93 @@ #include #include #include -#include #include +#include +#include #include "tb-switcher.h" #undef sock_errno #define sock_errno() errno +int fd_sock; + +void handle_sig_before_exit(int sig) { + printf("Caught signal %d\n", sig); + close(fd_sock); + exit(0); +} + +int exec_enable_tb(){ + printf("start enable turbo boost.\n"); + char cmd_enable_tb[512]; + sprintf(cmd_enable_tb, "kextunload \"%s\"", MODULE_PATH); + printf("enable turboot command: %s\n", cmd_enable_tb); + system(cmd_enable_tb); + return 0; +} + +int exec_disable_tb(){ + printf("start disable turbo boost.\n"); + char cmd_disable_tb[512]; + sprintf(cmd_disable_tb, "kextutil -v \"%s\"", MODULE_PATH); + printf("enable turboot command: %s\n", cmd_disable_tb); + system(cmd_disable_tb); + return 0; +} + + int start_server() { - int server_sock, rc; - socklen_t len; - ssize_t bytes_rec = 0; - struct sockaddr_un server_sockaddr, peer_sock; - char buf[256]; - memset(&server_sockaddr, 0, sizeof(struct sockaddr_un)); - memset(buf, 0, 256); - - /****************************************/ - /* Create a UNIX domain datagram socket */ - /****************************************/ - server_sock = socket(AF_UNIX, SOCK_DGRAM, 0); - if (server_sock == -1) { - printf("SOCKET ERROR = %d\n", sock_errno()); - exit(1); + char buffer[MAX_LEN]; + + struct sockaddr_in serv_addr, cli_addr; + ssize_t len_rc_data; + socklen_t len_cli_addr; + + // Creating socket file descriptor + if ((fd_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + printf("CREATE ERROR = %d\n", sock_errno()); + exit(EXIT_FAILURE); } - /***************************************/ - /* Set up the UNIX sockaddr structure */ - /* by using AF_UNIX for the family and */ - /* giving it a filepath to bind to. */ - /* */ - /* Unlink the file so the bind will */ - /* succeed, then bind to that file. */ - /***************************************/ - server_sockaddr.sun_family = AF_UNIX; - strcpy(server_sockaddr.sun_path, SOCK_PATH); - // len = sizeof(server_sockaddr); - len = (socklen_t) SUN_LEN(&server_sockaddr); - unlink(SOCK_PATH); - rc = bind(server_sock, (struct sockaddr *) &server_sockaddr, len); - if (rc == -1) { + memset(&serv_addr, 0, sizeof(serv_addr)); + memset(&cli_addr, 0, sizeof(cli_addr)); + + // Filling server information + serv_addr.sin_family = AF_INET; // IPv4 + inet_pton(AF_INET, SOCK_ADDR, &serv_addr.sin_addr); + serv_addr.sin_port = htons(SOCK_PORT); + + // Bind the socket with the server address + if (bind(fd_sock, (const struct sockaddr *) &serv_addr, + sizeof(serv_addr)) < 0) { printf("BIND ERROR = %d\n", sock_errno()); - close(server_sock); - exit(1); + exit(EXIT_FAILURE); } + printf("LISTEN ON UDP: %s:%i\n", SOCK_ADDR, SOCK_PORT); + signal(SIGINT, handle_sig_before_exit); + signal(SIGQUIT, handle_sig_before_exit); - /****************************************/ - /* Read data on the server from clients */ - /* and print the data that was read. */ - /****************************************/ - printf("waiting to recvfrom...\n"); - bytes_rec = recvfrom(server_sock, buf, 256, 0, (struct sockaddr *) &peer_sock, &len); - if (bytes_rec == -1) { - printf("RECVFROM ERROR = %d\n", sock_errno()); - close(server_sock); - exit(1); - } else { - printf("DATA RECEIVED = %s\n", buf); - } + len_cli_addr = sizeof(cli_addr); + while(fd_sock >= 0) { + len_rc_data = recvfrom(fd_sock, (char *) buffer, MAX_LEN, + MSG_WAITALL, (struct sockaddr *) &cli_addr, + &len_cli_addr); + buffer[len_rc_data] = '\0'; + printf("Client CMD: %s", buffer); + + if (strncasecmp(buffer, ENABLE_TB_CMD, strlen(ENABLE_TB_CMD)) == 0){ + exec_enable_tb(); + }else if (strncasecmp(buffer, DISABLE_TB_CMD, strlen(DISABLE_TB_CMD)) == 0){ + exec_disable_tb(); + } + } /*****************************/ /* Close the socket and exit */ /*****************************/ - close(server_sock); + close(fd_sock); return 0; } + + From 23ad60178e72b63a6e9329fa3d19e9820cd8c598 Mon Sep 17 00:00:00 2001 From: tinkernels Date: Mon, 26 Sep 2022 16:30:36 +0800 Subject: [PATCH 7/8] Update build config. --- Classes/FanControl.m | 1 + .../xcshareddata/xcschemes/smc.xcscheme | 54 ++----------------- .../xcschemes/smcFanControl.xcscheme | 54 ++----------------- 3 files changed, 9 insertions(+), 100 deletions(-) diff --git a/Classes/FanControl.m b/Classes/FanControl.m index b2d0792..5f75d0d 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -740,6 +740,7 @@ - (void)systemDidWakeFromSleep:(id)sender { if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState) { enable_tb(); } else { + enable_tb(); disable_tb(); } } diff --git a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme index 40f6297..133a693 100644 --- a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme +++ b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme @@ -1,17 +1,10 @@ - + + buildForRunning = "YES"> - - - - - + - - - - - - - - - - diff --git a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme index 5ae4966..3f55e0f 100644 --- a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme +++ b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme @@ -1,17 +1,10 @@ - + + buildForRunning = "YES"> - - - - - + - - - - - - - - - - From 4406f8fadbf93185de8048c913edec4d5b7fc9d7 Mon Sep 17 00:00:00 2001 From: tinkernels Date: Thu, 13 Oct 2022 15:37:50 +0800 Subject: [PATCH 8/8] Add turboboost state. --- Classes/FanControl.m | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/Classes/FanControl.m b/Classes/FanControl.m index 619d492..7ec296b 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -27,6 +27,28 @@ #import "Privilege.h" #import "tb-switcher.h" +@interface NSString (ShellExecution) +- (NSString*)runAsCommand; +@end + +@implementation NSString (ShellExecution) + +- (NSString*)runAsCommand { + NSPipe* pipe = [NSPipe pipe]; + + NSTask* task = [[NSTask alloc] init]; + [task setLaunchPath: @"/bin/sh"]; + [task setArguments:@[@"-c", [NSString stringWithFormat:@"%@", self]]]; + [task setStandardOutput:pipe]; + + NSFileHandle* file = [pipe fileHandleForReading]; + [task launch]; + + return [[NSString alloc] initWithData:[file readDataToEndOfFile] encoding:NSUTF8StringEncoding]; +} + +@end + @interface FanControl () + (void)copyMachinesIfNecessary; @@ -245,9 +267,11 @@ - (void)applyTurboBoost:(id)sender { if (state == NSOffState) { [sender setState:NSOnState]; enable_tb(); + [@"echo 1 > ~/.turbo_boost" runAsCommand]; } else { [sender setState:NSOffState]; disable_tb(); + [@"echo 0 > ~/.turbo_boost" runAsCommand]; } } @@ -267,14 +291,21 @@ - (void)init_statusitem { [theMenu insertItem:s_menus[i] atIndex:i]; }; - disable_tb(); NSMenuItem *fan1Item = [theMenu itemWithTitle:@"Fan: 1"]; int fan1ItemIdx = [theMenu indexOfItem:fan1Item]; + NSMenuItem *turboBoostItem = [[NSMenuItem alloc] initWithTitle:@"Turbo Boost" action:@selector(applyTurboBoost:) keyEquivalent:@""]; - [turboBoostItem setState:NSOffState]; + NSString* output = [@"cat ~/.turbo_boost" runAsCommand]; + if ([output isEqual: @"1\n"]) { + enable_tb(); + [turboBoostItem setState:NSOnState]; + } else { + disable_tb(); + [turboBoostItem setState:NSOffState]; + } [turboBoostItem setEnabled:true]; [turboBoostItem setTarget:self]; [theMenu insertItem:turboBoostItem atIndex:fan1ItemIdx + 1];