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 cd721e7..7ec296b 100755 --- a/Classes/FanControl.m +++ b/Classes/FanControl.m @@ -20,21 +20,41 @@ * 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" -#import -#import -#import #import -#import "SystemVersion.h" +#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; -@property (NS_NONATOMIC_IOSONLY, getter=isInAutoStart, readonly) BOOL inAutoStart; + +@property(NS_NONATOMIC_IOSONLY, getter=isInAutoStart, readonly) BOOL inAutoStart; + - (void)setStartAtLogin:(BOOL)enabled; -+ (void)checkRightStatus:(OSStatus)status; @end @implementation FanControl @@ -42,204 +62,198 @@ @implementation FanControl // Number of fans reported by the hardware. int g_numFans = 0; - NSUserDefaults *defaults; #pragma mark **Init-Methods** -+(void) initialize { - - //avoid Zombies when starting external app - signal(SIGCHLD, SIG_IGN); - ++ (void)initialize { + + //avoid Zombies when starting external app + signal(SIGCHLD, SIG_IGN); + [FanControl copyMachinesIfNecessary]; - //check owner and suid rights - [FanControl setRights]; + //check owner and suid rights + [FanControl setRights]; - //talk to smc - [smcWrapper init]; - - //app in foreground for update notifications - [[NSApplication sharedApplication] activateIgnoringOtherApps:YES]; + //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 -{ - //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)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; + } + } + } --(void) awakeFromNib { - - pw=[[Power alloc] init]; - [pw setDelegate:self]; - [pw registerForSleepWakeNotification]; - [pw registerForPowerChange]; - +- (void)awakeFromNib { + + 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]]; + 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, - [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; + + + 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; [[[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]; - } + //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, + //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]]; - - + @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; i < g_numFans; i++) { + NSMenuItem *mitem = [[NSMenuItem alloc] initWithTitle:[NSString stringWithFormat:@"Fan: %d", i] action:NULL keyEquivalent:@""]; + [mitem setTag:(i + 1) * 10]; + [s_menus insertObject:mitem atIndex:i]; + } - 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 + [programinfo setStringValue:[NSString stringWithFormat:@"%@ %@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"] + , [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"]]]; + // + [copyright setStringValue:[[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSHumanReadableCopyright"]]; + + + //power controls only available on portables + 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"]]]; + [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]; + //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]; - + [_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]; + 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 -{ - 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]; @@ -248,104 +262,131 @@ -(void)displayDonationMessage } } +- (void)applyTurboBoost:(id)sender { + NSControlStateValue state = [sender state]; + if (state == NSOffState) { + [sender setState:NSOnState]; + enable_tb(); + [@"echo 1 > ~/.turbo_boost" runAsCommand]; + } else { + [sender setState:NSOffState]; + disable_tb(); + [@"echo 0 > ~/.turbo_boost" runAsCommand]; + } +} + +- (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++) { - [theMenu insertItem:s_menus[i] atIndex:i]; - }; - + int i; + for (i = 0; i < [s_menus count]; i++) { + [theMenu insertItem:s_menus[i] atIndex:i]; + }; + + NSMenuItem *fan1Item = [theMenu itemWithTitle:@"Fan: 1"]; + int fan1ItemIdx = [theMenu indexOfItem:fan1Item]; + + NSMenuItem *turboBoostItem = [[NSMenuItem alloc] + initWithTitle:@"Turbo Boost" + action:@selector(applyTurboBoost:) + keyEquivalent:@""]; + 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]; + // Sign up for menuNeedsUpdate call // so that the fan speeds in the menu can be updated // only when needed. [theMenu setDelegate:self]; } - #pragma mark **Action-Methods** -- (IBAction)loginItem:(id)sender{ - if ([sender state]==NSOnState) { - [self setStartAtLogin:YES]; - } else { + +- (IBAction)loginItem:(id)sender { + 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]; +- (IBAction)add_favorite:(id)sender { + [[NSApplication sharedApplication] beginSheet:newfavoritewindow + modalForWindow:mainwindow + modalDelegate:nil + didEndSelector:nil + contextInfo:nil]; } -- (IBAction)close_favorite:(id)sender{ - [newfavoritewindow close]; - [[NSApplication sharedApplication] endSheet:newfavoritewindow]; +- (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 - [toinsert setValue:@0 forKey:@"Standard"]; - [FavoritesController addObject:toinsert]; - [newfavoritewindow close]; - [[NSApplication sharedApplication] endSheet:newfavoritewindow]; - } - [self upgradeFavorites]; +- (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]; } --(void) check_deletion:(id)combo{ - if ([FavoritesController selectionIndex]==[[defaults objectForKey:combo] intValue]) { - [defaults setObject:@0 forKey:combo]; - } +- (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) { - //delete favorite, but resets presets before - [self check_deletion:PREF_BATTERY_SELECTION]; - [self check_deletion:PREF_AC_SELECTION]; - [self check_deletion:PREF_CHARGING_SELECTION]; +- (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]; [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"] ]]; - +- (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) { - return; - } - + + //on init handling + if (_machineDefaultsDict == nil) { + return; + } + // Determine what data is actually needed to keep the energy impact // as low as possible. bool bNeedTemp = false; @@ -357,17 +398,17 @@ -(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; @@ -375,76 +416,77 @@ -(void) readFanData:(id)caller{ } NSString *temp = nil; - NSString *fan = 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) { - [[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]; - } - } +- (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]; + } + } } #pragma mark **Power Watchdog-Methods** -- (void)systemDidWakeFromSleep:(id)sender{ - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; +- (void)systemDidWakeFromSleep:(id)sender { + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_SELECTION_DEFAULT] intValue]]; + + if ([[theMenu itemWithTitle:@"Turbo Boost"] state] == NSOnState) { + enable_tb(); + } else { + enable_tb(); + disable_tb(); + } } -- (void)powerChangeToBattery:(id)sender{ +- (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]]; +- (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) { - [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_CHARGING_SELECTION] intValue]]; +- (void)powerChangeToACLoading:(id)sender { + if ([[defaults objectForKey:@"AutomaticChange"] boolValue] == YES) { + [self apply_settings:nil controllerindex:[[defaults objectForKey:PREF_CHARGING_SELECTION] intValue]]; - } + } } #pragma mark - #pragma mark Start-at-login control -- (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)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; 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); - - - NSString *path = [[NSBundle mainBundle] bundlePath]; - - OSStatus status; - CFURLRef URLToToggle = (__bridge CFURLRef)[NSURL fileURLWithPath:path]; - LSSharedFileListItemRef existingItem = NULL; - - UInt32 seed = 0U; +- (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]; + 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]; - - if (result == NSAlertDefaultReturn) { - [[NSApplication sharedApplication] terminate:self]; + + 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); } #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)) { - // 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); ++ (void)setRights { + 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. - [self checkRightStatus:status]; -} + } 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"]; + if (![fManger fileExistsAtPath:@MODULE_PATH]) { + NSString *tool = @"/bin/sh"; + 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"]; + } --(void)dealloc -{ - [[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; + 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]; + } } -@end ++ (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", [NSString stringWithFormat:@"%@:%@", user, group], path]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + tool = @"/bin/chmod"; + argsArray = @[@"-Rf", mod, path]; + [Privilege runTaskAsAdmin:tool andArgs:argsArray]; + } +} +- (void)dealloc { + [[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; +} + +@end + @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; - return @(fahrenheit); +- (NSNumber *)celsius_fahrenheit { + float celsius = [self floatValue]; + float fahrenheit = (celsius * 9) / 5 + 32; + return @(fahrenheit); } @end 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/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 new file mode 100644 index 0000000..6ceb14d --- /dev/null +++ b/Classes/Privilege.h @@ -0,0 +1,24 @@ +// +// 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; + ++ (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 new file mode 100644 index 0000000..030ecce --- /dev/null +++ b/Classes/Privilege.m @@ -0,0 +1,100 @@ +// +// 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, (AuthorizationFlags) flags, &authorizationRef); + + if (status != errAuthorizationSuccess) { + NSLog(@"Copy Rights Unsuccessful: %d", status); + authorizationRef = nil; + } + } + 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) { + 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/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/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 100755 index 0000000..259ef76 Binary files /dev/null and b/Ressources/DisableTurboBoost.32bits.kext/Contents/MacOS/DisableTurboBoost differ 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 0000000..44c6f06 Binary files /dev/null and b/Ressources/DisableTurboBoost.64bits.kext/Contents/MacOS/DisableTurboBoost differ diff --git a/Ressources/com.tinkernels.tb-switcher.plist b/Ressources/com.tinkernels.tb-switcher.plist new file mode 100644 index 0000000..d6d2074 --- /dev/null +++ b/Ressources/com.tinkernels.tb-switcher.plist @@ -0,0 +1,25 @@ + + + + + Label + com.tinkernels.tb-switcher.plist + ProgramArguments + + /bin/sh + -c + "/Library/Application Support/smcFanControl2/tb-switcher" + + 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 0e03339..6a0a717 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 b0a11e1..7ed4bab 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,66 +75,72 @@ #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]; static UInt8 fannum[] = "0123456789ABCDEFGHIJ"; 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 b6be402..a34c368 100644 --- a/smcFanControl.xcodeproj/project.pbxproj +++ b/smcFanControl.xcodeproj/project.pbxproj @@ -13,7 +13,6 @@ 891683E90AEBD95B00888535 /* smcWrapper.m in Sources */ = {isa = PBXBuildFile; fileRef = 891683E80AEBD95B00888535 /* smcWrapper.m */; }; 8917FB860ADEECAD00443DA1 /* paypal.gif in Resources */ = {isa = PBXBuildFile; fileRef = 8917FB850ADEECAD00443DA1 /* paypal.gif */; }; 891DEF110B40736D001A7C32 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 891DEF100B40736D001A7C32 /* WebKit.framework */; }; - 8924ECFD15AC98380031730C /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8924ECFC15AC98380031730C /* IOKit.framework */; }; 8924ECFE15AC98880031730C /* smc.c in Sources */ = {isa = PBXBuildFile; fileRef = 89C053BC0ADAB7630037CA16 /* smc.c */; }; 892A7F450B10B7700041B493 /* MachineDefaults.m in Sources */ = {isa = PBXBuildFile; fileRef = 892A7F440B10B7700041B493 /* MachineDefaults.m */; }; 8932CF2413D08551008BC447 /* SystemVersion.m in Sources */ = {isa = PBXBuildFile; fileRef = 8932CF2313D08551008BC447 /* SystemVersion.m */; }; @@ -26,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 */; }; @@ -34,6 +32,17 @@ 8D11072B0486CEB800E47090 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = 089C165CFE840E0CC02AAC07 /* InfoPlist.strings */; }; 8D11072D0486CEB800E47090 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 29B97316FDCFA39411CA2CEA /* main.m */; settings = {ATTRIBUTES = (); }; }; 8D11072F0486CEB800E47090 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 1058C7A1FEA54F0111CA2CBB /* Cocoa.framework */; }; + AFD3F21F247B41340086D29E /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 894A494A0ADBEEF4008785F3 /* IOKit.framework */; }; + 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 */; }; + 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 */ @@ -52,7 +61,8 @@ dstPath = ""; dstSubfolderSpec = 7; files = ( - 899D59DC15E1CF60003E322D /* smc in CopyFiles */, + AFED6519247E2E4B00BEDCB5 /* tb-switcher in CopyFiles */, + AFED6518247E2E4800BEDCB5 /* smc in CopyFiles */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -66,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 = ""; }; @@ -89,7 +108,6 @@ 8917FB850ADEECAD00443DA1 /* paypal.gif */ = {isa = PBXFileReference; lastKnownFileType = image.gif; path = paypal.gif; sourceTree = ""; }; 891DEF100B40736D001A7C32 /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = /System/Library/Frameworks/WebKit.framework; sourceTree = ""; }; 8924ECEE15AC96E70031730C /* smc */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = smc; sourceTree = BUILT_PRODUCTS_DIR; }; - 8924ECFC15AC98380031730C /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk/System/Library/Frameworks/IOKit.framework; sourceTree = DEVELOPER_DIR; }; 892A7F430B10B7700041B493 /* MachineDefaults.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MachineDefaults.h; sourceTree = ""; }; 892A7F440B10B7700041B493 /* MachineDefaults.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MachineDefaults.m; sourceTree = ""; }; 8932CF2213D0850F008BC447 /* SystemVersion.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SystemVersion.h; sourceTree = ""; }; @@ -97,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 = ""; }; @@ -121,6 +139,16 @@ 89FE24280B7F4CE900D2713C /* German */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; name = German; path = German.lproj/MainMenu.nib; sourceTree = ""; }; 8D1107310486CEB800E47090 /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 8D1107320486CEB800E47090 /* smcFanControl.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = smcFanControl.app; sourceTree = BUILT_PRODUCTS_DIR; }; + AFD3F220247B41B30086D29E /* DisableTurboBoost.32bits.kext */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.kernel-extension"; path = DisableTurboBoost.32bits.kext; sourceTree = ""; }; + 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 */ @@ -128,7 +156,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 8924ECFD15AC98380031730C /* IOKit.framework in Frameworks */, + AFD3F21F247B41340086D29E /* IOKit.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -144,12 +172,21 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + AFF28EC5247D987C00B47C72 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ 080E96DDFE201D6D7F000001 /* Classes */ = { isa = PBXGroup; children = ( + AFD3F22D247B591A0086D29E /* Privilege.h */, + AFD3F22B247B58CB0086D29E /* Privilege.m */, 897753AB1DB3D89D00595411 /* Constants.h */, 89148EA115E2543D00A073EE /* NSFileManager+DirectoryLocations.m */, 89148EA215E2543D00A073EE /* NSFileManager+DirectoryLocations.h */, @@ -181,7 +218,6 @@ 1058C7A2FEA54F0111CA2CBB /* Other Frameworks */ = { isa = PBXGroup; children = ( - 8924ECFC15AC98380031730C /* IOKit.framework */, 891DEF100B40736D001A7C32 /* WebKit.framework */, 8985F1580ADD0B5500F9EC46 /* Security.framework */, 894A494A0ADBEEF4008785F3 /* IOKit.framework */, @@ -197,6 +233,7 @@ children = ( 8D1107320486CEB800E47090 /* smcFanControl.app */, 8924ECEE15AC96E70031730C /* smc */, + AFF28EC8247D987C00B47C72 /* tb-switcher */, ); name = Products; sourceTree = ""; @@ -204,6 +241,7 @@ 29B97314FDCFA39411CA2CEA /* FanControl */ = { isa = PBXGroup; children = ( + AFF28EC9247D987C00B47C72 /* tb-switcher */, 898C281A15E2B6E30044EEC3 /* smc-command */, 080E96DDFE201D6D7F000001 /* Classes */, 29B97315FDCFA39411CA2CEA /* Other Sources */, @@ -226,6 +264,9 @@ 29B97317FDCFA39411CA2CEA /* Resources */ = { isa = PBXGroup; children = ( + AFF28ED0247D9A9500B47C72 /* com.tinkernels.tb-switcher.plist */, + AFD3F222247B41BB0086D29E /* DisableTurboBoost.64bits.kext */, + AFD3F220247B41B30086D29E /* DisableTurboBoost.32bits.kext */, 89559A830BAC338400DBA37E /* smcover.png */, 8987FBD00B878B3900A5ED8E /* smc.png */, 89033CA60B80E1EB00FDAF43 /* F.A.Q.rtf */, @@ -259,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 */ @@ -299,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 */ @@ -308,12 +377,15 @@ LastUpgradeCheck = 1000; TargetAttributes = { 8924ECED15AC96E70031730C = { - DevelopmentTeam = H4G85G26BP; - ProvisioningStyle = Manual; + DevelopmentTeam = YKS755N9YR; }; 8D1107260486CEB800E47090 = { - DevelopmentTeam = H4G85G26BP; - ProvisioningStyle = Manual; + DevelopmentTeam = YKS755N9YR; + }; + AFF28EC7247D987C00B47C72 = { + CreatedOnToolsVersion = 11.5; + DevelopmentTeam = YKS755N9YR; + ProvisioningStyle = Automatic; }; }; }; @@ -338,6 +410,7 @@ targets = ( 8D1107260486CEB800E47090 /* smcFanControl */, 8924ECED15AC96E70031730C /* smc */, + AFF28EC7247D987C00B47C72 /* tb-switcher */, ); }; /* End PBXProject section */ @@ -352,10 +425,13 @@ 8917FB860ADEECAD00443DA1 /* paypal.gif in Resources */, 893506180B440255001BFBA5 /* Localizable.strings in Resources */, 89B243200B7E351000CAD103 /* smcfancontrol_v2.icns in Resources */, - 89FE24230B7F4CD300D2713C /* MainMenu.nib in Resources */, 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 */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -377,15 +453,27 @@ 8D11072D0486CEB800E47090 /* main.m in Sources */, 894A46610ADBD6CF008785F3 /* FanControl.m in Sources */, 8916827A0AEBB14F00888535 /* StatusItemWindow.m in Sources */, + AFD3F22C247B58CB0086D29E /* Privilege.m in Sources */, 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 */ @@ -444,9 +532,9 @@ CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; CODE_SIGN_IDENTITY = "Mac Developer"; - "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Developer ID Application"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer"; COPY_PHASE_STRIP = NO; - DEVELOPMENT_TEAM = H4G85G26BP; + DEVELOPMENT_TEAM = YKS755N9YR; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_ENABLE_OBJC_EXCEPTIONS = YES; @@ -472,11 +560,12 @@ CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_ENABLE_OBJC_WEAK = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - CODE_SIGN_IDENTITY = "Mac Developer"; - "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Developer ID Application"; + CODE_SIGN_IDENTITY = "Apple Development"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Mac Developer"; + CODE_SIGN_STYLE = Automatic; COPY_PHASE_STRIP = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - DEVELOPMENT_TEAM = H4G85G26BP; + DEVELOPMENT_TEAM = YKS755N9YR; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_PREPROCESSOR_DEFINITIONS = CMD_TOOL_BUILD; @@ -487,18 +576,134 @@ MACOSX_DEPLOYMENT_TARGET = 10.7; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; }; 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 = "Developer ID Application"; + CODE_SIGN_IDENTITY = "Mac Developer"; COMBINE_HIDPI_IMAGES = YES; COPY_PHASE_STRIP = NO; - DEVELOPMENT_TEAM = H4G85G26BP; + CURRENT_PROJECT_VERSION = 2.7.0; + DEVELOPMENT_TEAM = YKS755N9YR; FRAMEWORK_SEARCH_PATHS = ( ., "$(inherited)", @@ -519,6 +724,7 @@ "\"$(SDKROOT)/usr/lib/system\"", ); MACOSX_DEPLOYMENT_TARGET = 10.7; + MARKETING_VERSION = 2.7.0; ONLY_ACTIVE_ARCH = NO; OTHER_CODE_SIGN_FLAGS = "--deep"; PRODUCT_BUNDLE_IDENTIFIER = com.eidac.smcFanControl2; @@ -534,10 +740,13 @@ C01FCF4C08A954540054247B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; CLANG_ENABLE_OBJC_ARC = YES; - CODE_SIGN_IDENTITY = "Developer ID Application"; + CODE_SIGN_IDENTITY = "Mac Developer"; + CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - DEVELOPMENT_TEAM = H4G85G26BP; + CURRENT_PROJECT_VERSION = 2.7.0; + DEVELOPMENT_TEAM = YKS755N9YR; FRAMEWORK_SEARCH_PATHS = ( "$(inherited)", "$(FRAMEWORK_SEARCH_PATHS_QUOTED_1)", @@ -547,6 +756,7 @@ FRAMEWORK_SEARCH_PATHS_QUOTED_2 = "\"$(SRCROOT)\""; GCC_GENERATE_DEBUGGING_SYMBOLS = NO; GCC_MODEL_TUNING = ""; + "GCC_PREPROCESSOR_DEFINITIONS[arch=*]" = "RELEASE=1"; GCC_VERSION = ""; GCC_WARN_ABOUT_DEPRECATED_FUNCTIONS = NO; GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = NO; @@ -558,14 +768,16 @@ "\"$(SDKROOT)/usr/lib/system\"", ); MACOSX_DEPLOYMENT_TARGET = 10.7; - OBJROOT = "$(HOME)/builds"; + MARKETING_VERSION = 2.7.0; + OBJROOT = "build-release"; ONLY_ACTIVE_ARCH = NO; OTHER_CODE_SIGN_FLAGS = "--deep"; PRODUCT_BUNDLE_IDENTIFIER = com.eidac.smcFanControl2; PRODUCT_NAME = smcFanControl; PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; SDKROOT = macosx; - SYMROOT = "$(HOME)/builds"; + SYMROOT = "build-release"; VALID_ARCHS = "i386 x86_64"; WRAPPER_EXTENSION = app; }; @@ -602,7 +814,7 @@ OTHER_CFLAGS = ""; OTHER_LDFLAGS = ""; SDKROOT = macosx; - SYMROOT = "~/builds"; + SYMROOT = "build-release"; VALID_ARCHS = "i386 x86_64"; }; name = Release; @@ -619,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/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme new file mode 100644 index 0000000..133a693 --- /dev/null +++ b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smc.xcscheme @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + diff --git a/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme new file mode 100644 index 0000000..3f55e0f --- /dev/null +++ b/smcFanControl.xcodeproj/xcshareddata/xcschemes/smcFanControl.xcscheme @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + 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..97d44b2 --- /dev/null +++ b/tb-switcher/tb-switcher.h @@ -0,0 +1,26 @@ +// +// 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 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); + +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..0d4f026 --- /dev/null +++ b/tb-switcher/tb-switcher_c.c @@ -0,0 +1,62 @@ +// +// 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 send_cmd(char *cmd) { + int fd_sock; + char buffer[MAX_LEN]; + strcpy(buffer, cmd); + struct sockaddr_in serv_addr; + + // Creating socket file descriptor + if ((fd_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { + perror("socket creation failed"); + exit(EXIT_FAILURE); + } + + memset(&serv_addr, 0, sizeof(serv_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); + + 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 new file mode 100644 index 0000000..9895e37 --- /dev/null +++ b/tb-switcher/tb-switcher_s.c @@ -0,0 +1,102 @@ +// +// tb-switcher_s.c +// tb-switcher +// +// Created by Don Johnny on 2020/5/27. +// + +#include +#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() { + 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); + } + + 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()); + 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); + + 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(fd_sock); + + return 0; +} + +