1 /* Cydia Substrate - Powerful Code Insertion Platform
2 * Copyright (C) 2008-2013 Jay Freeman (saurik)
5 /* GNU Lesser General Public License, Version 3 {{{ */
7 * Substrate is free software: you can redistribute it and/or modify it under
8 * the terms of the GNU Lesser General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
12 * Substrate is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 * License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with Substrate. If not, see <http://www.gnu.org/licenses/>.
22 #import <CoreFoundation/CoreFoundation.h>
23 #import <Foundation/Foundation.h>
24 #import <CoreGraphics/CGGeometry.h>
25 #import <UIKit/UIKit.h>
28 #include <substrate.h>
30 Class $SafeModeAlertItem;
32 #define UIAlertActionStyleDefault 0
34 @interface UIAlertAction
35 + (UIAlertAction *) actionWithTitle:(NSString *)title style:(NSUInteger)style handler:(void (^)(UIAlertAction *action))handler;
38 @interface UIAlertController : UIViewController
39 - (void) addAction:(UIAlertAction *)action;
40 - (void) setMessage:(NSString *)message;
41 - (void) setTitle:(NSString *)title;
44 @interface SBAlertItem : NSObject {
46 - (UIAlertController *) alertController;
47 - (UIAlertView *) alertSheet;
48 - (void) deactivateForButton;
52 @interface SBAlertItemsController : NSObject {
54 + (SBAlertItemsController *) sharedInstance;
55 - (void) activateAlertItem:(SBAlertItem *)item;
58 @interface SBStatusBarTimeView : UIView {
63 @interface UIApplication (CydiaSubstrate)
64 - (void) applicationOpenURL:(id)url;
67 @interface UIAlertView (CydiaSubstrate)
68 - (void) setForceHorizontalButtonsLayout:(BOOL)force;
69 - (void) setBodyText:(NSString *)body;
70 - (void) setNumberOfRows:(NSInteger)rows;
73 void SafeModeButtonClicked(int button) {
79 if (kCFCoreFoundationVersionNumber >= 700)
80 system("killall backboardd");
82 // XXX: there are better ways of restarting SpringBoard that would actually save state
87 [[UIApplication sharedApplication] applicationOpenURL:[NSURL URLWithString:@"http://cydia.saurik.com/safemode/"]];
92 void SafeModeButtonClicked(id self, int button) {
93 SafeModeButtonClicked(button);
94 [self deactivateForButton];
97 void SafeModeAlertItem$alertSheet$buttonClicked$(id self, SEL sel, id sheet, int button) {
98 SafeModeButtonClicked(button);
102 void SafeModeAlertItem$alertView$clickedButtonAtIndex$(id self, SEL sel, id sheet, NSInteger button) {
103 SafeModeButtonClicked(button + 1);
107 void SafeModeAlertItem$configure$requirePasscodeForActions$(id self, SEL sel, BOOL configure, BOOL require) {
108 NSString *text(@"We apologize for the inconvenience, but SpringBoard has just crashed.\n\nMobileSubstrate /did not/ cause this problem: it has protected you from it.\n\nSpringBoard is now running in Safe Mode. All extensions that support this safety system are disabled.\n\nReboot (or restart SpringBoard) to return to the normal mode. To return to this dialog touch the status bar.\n\nTap \"Help\" below for more tips.");
111 if ([self respondsToSelector:@selector(alertController)]) {
112 UIAlertController *alert([self alertController]);
114 [alert setTitle:@""];
115 [alert setMessage:text];
117 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 1); }]];
118 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"Restart" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 2); }]];
119 [alert addAction:[%c(UIAlertAction) actionWithTitle:@"Help" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { SafeModeButtonClicked(self, 3); }]];
124 if (false) %c(UIAlertAction);
127 UIAlertView *sheet([self alertSheet]);
128 [sheet setDelegate:self];
130 [sheet setTitle:@""];
131 [sheet setBodyText:text];
133 [sheet addButtonWithTitle:@"OK"];
134 [sheet addButtonWithTitle:@"Restart"];
135 [sheet addButtonWithTitle:@"Help"];
137 [sheet setNumberOfRows:1];
138 if ([sheet respondsToSelector:@selector(setForceHorizontalButtonsLayout:)])
139 [sheet setForceHorizontalButtonsLayout:YES];
142 void SafeModeAlertItem$performUnlockAction(id self, SEL sel) {
143 [[%c(SBAlertItemsController) sharedInstance] activateAlertItem:self];
146 static void MSAlert() {
147 if ($SafeModeAlertItem == nil)
148 $SafeModeAlertItem = objc_lookUpClass("SafeModeAlertItem");
149 if ($SafeModeAlertItem == nil) {
150 $SafeModeAlertItem = objc_allocateClassPair(objc_getClass("SBAlertItem"), "SafeModeAlertItem", 0);
151 if ($SafeModeAlertItem == nil)
154 class_addMethod($SafeModeAlertItem, @selector(alertSheet:buttonClicked:), (IMP) &SafeModeAlertItem$alertSheet$buttonClicked$, "v@:@i");
155 class_addMethod($SafeModeAlertItem, @selector(alertView:clickedButtonAtIndex:), (IMP) &SafeModeAlertItem$alertView$clickedButtonAtIndex$, "v@:@i");
156 class_addMethod($SafeModeAlertItem, @selector(configure:requirePasscodeForActions:), (IMP) &SafeModeAlertItem$configure$requirePasscodeForActions$, "v@:cc");
157 class_addMethod($SafeModeAlertItem, @selector(performUnlockAction), (IMP) SafeModeAlertItem$performUnlockAction, "v@:");
158 objc_registerClassPair($SafeModeAlertItem);
161 if (%c(SBAlertItemsController) != nil)
162 [[%c(SBAlertItemsController) sharedInstance] activateAlertItem:[[[$SafeModeAlertItem alloc] init] autorelease]];
166 // XXX: on iOS 5.0, we really would prefer avoiding
169 - (void) touchesEnded:(id)touches withEvent:(id)event {
171 %orig(touches, event);
175 - (void) mouseDown:(void *)event {
181 - (void) touchesBegan:(void *)touches withEvent:(void *)event {
183 %orig(touches, event);
187 // this fairly complex code came from Grant, to solve the "it Safe Mode"-in-bar bug
189 %hook SBStatusBarDataManager
190 - (void) _updateTimeString {
191 char *_data(&MSHookIvar<char>(self, "_data"));
195 Ivar _itemIsEnabled(object_getInstanceVariable(self, "_itemIsEnabled", NULL));
196 if (_itemIsEnabled == NULL)
199 Ivar _itemIsCloaked(object_getInstanceVariable(self, "_itemIsCloaked", NULL));
200 if (_itemIsCloaked == NULL)
203 size_t enabledOffset(ivar_getOffset(_itemIsEnabled));
204 size_t cloakedOffset(ivar_getOffset(_itemIsCloaked));
205 if (enabledOffset >= cloakedOffset)
208 size_t offset(cloakedOffset - enabledOffset);
209 char *timeString(_data + offset);
210 strcpy(timeString, "Exit Safe Mode");
214 // this /insanely/ complex code came from that parrot guy... omg this is getting bad
216 @interface SBStatusBarStateAggregator : NSObject
217 - (void) _stopTimeItemTimer;
220 %hook SBStatusBarStateAggregator
222 - (void) _updateTimeItems {
223 if ([self respondsToSelector:@selector(_stopTimeItemTimer)])
224 [self _stopTimeItemTimer];
228 - (void) _restartTimeItemTimer {
231 - (void) _resetTimeItemFormatter {
233 if (NSDateFormatter *df = MSHookIvar<NSDateFormatter *>(self, "_timeItemDateFormatter"))
234 [df setDateFormat:@"'Exit' 'Safe' 'Mode'"];
240 static bool alerted_;
242 static void AlertIfNeeded() {
250 %hook SBLockScreenManager
251 - (void) _finishUIUnlockFromSource:(int)source withOptions:(id)options {
257 %hook SBAwayController
258 - (void) _finishUnlockWithSound:(BOOL)sound unlockSource:(int)source isAutoUnlock:(BOOL)is {
264 %hook SBAwayController
265 - (void) _unlockWithSound:(BOOL)sound isAutoUnlock:(BOOL)is unlockSource:(int)source {
270 // iOS 4.3 XXX: check lower versions
271 %hook SBAwayController
272 - (void) _unlockWithSound:(BOOL)sound isAutoUnlock:(BOOL)is unlockType:(int)type {
277 // -[SBIconController showInfoAlertIfNeeded] explains how to drag icons around the iPhone home screen
278 // it used to be shown to users when they unlocked their screen for the first time, and happened every unlock
279 // however, as of iOS 4.3, it got relegated to only appearing once the user installed an app or web clip
281 %hook SBIconController
282 - (void) showInfoAlertIfNeeded {
287 // the icon state, including crazy configurations like Five Icon Dock, is stored in SpringBoard's defaults
288 // unfortunately, SpringBoard on iOS 2.0 and 2.1 (maybe 2.2 as well) buffer overrun with more than 4 icons
289 // there is a third party package called IconSupport that remedies this, but not everyone is using it yet
292 - (int) maxIconColumns {
296 if (NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults])
297 if (NSDictionary *iconState = [defaults objectForKey:@"iconState"])
298 if (NSDictionary *buttonBar = [iconState objectForKey:@"buttonBar"])
299 if (NSArray *iconMatrix = [buttonBar objectForKey:@"iconMatrix"])
300 if ([iconMatrix count] != 0)
301 if (NSArray *row = [iconMatrix objectAtIndex:0]) {
302 int count([row count]);
312 if ((self = %orig()) != nil) {
313 UIView *&_contentLayer(MSHookIvar<UIView *>(self, "_contentLayer"));
314 UIView *&_contentView(MSHookIvar<UIView *>(self, "_contentView"));
317 if (&_contentLayer != NULL)
318 layer = _contentLayer;
319 else if (&_contentView != NULL)
320 layer = _contentView;
325 [layer setBackgroundColor:[UIColor darkGrayColor]];
329 #define Paper_ "/Library/MobileSubstrate/MobileSafety.png"
331 %hook SBWallpaperImage
337 + (UIImage *) defaultDesktopImage {
338 return [UIImage imageWithContentsOfFile:@Paper_];
341 %hook SBStatusBarTimeView
343 NSString *&_time(MSHookIvar<NSString *>(self, "_time"));
344 CGRect &_textRect(MSHookIvar<CGRect>(self, "_textRect"));
347 _time = [@"Exit Safe Mode" retain];
348 id font([self textFont]);
349 CGSize size([_time sizeWithFont:font]);
350 CGRect frame([self frame]);
351 _textRect.size = size;
352 _textRect.origin.x = (frame.size.width - size.width) / 2;
353 _textRect.origin.y = (frame.size.height - size.height) / 2;
357 // on iOS 6.0, Apple split parts of SpringBoard into a daemon called backboardd, including app launches
358 // in order to allow safe mode to propogate into applications, we need to then tell backboardd here
359 // XXX: (all of this should be replaced, however, with per-process launchd-mediated exception handling)
361 %hook BKSApplicationLaunchSettings
362 - (void) setEnvironment:(NSDictionary *)original {
366 NSMutableDictionary *modified([original mutableCopy]);
367 [modified setObject:@"1" forKey:@"_MSSafeMode"];
368 return %orig(modified);
372 // this highly-general hook replaces all previous attempts to protect SpringBoard from spurious code
373 // the main purpose is to protect SpringBoard from non-Substrate "away view plug-ins" and "wee apps"
375 const char *dylibs_[] = {
377 "/System/Library/Frameworks",
378 "/System/Library/PrivateFrameworks",
379 "/System/Library/CoreServices",
380 "/System/Library/AccessibilityBundles",
381 "/System/Library/HIDPlugins",
385 MSHook(void *, dlopen, const char *path, int mode) {
386 // we probably don't need this whitelist, but it has the nifty benefit of letting Cycript inject
387 // that said, older versions of iOS (before 3.1) will need a special case due to now shared cache
389 for (const char **dylib = dylibs_; *dylib != NULL; ++dylib) {
390 size_t length(strlen(*dylib));
391 if (strncmp(path, *dylib, length) != 0)
393 if (path[length] != '/')
398 // if the file is not on disk, and isn't already loaded (LC_ID_DYLIB), it is in the shared cache
399 // files loaded from the shared cache are "trusted". ones that don't exist are clearly harmless.
400 // this allows us to load most of the dynamic functionality of SpringBoard without going nuts ;P
402 if (access(path, F_OK) == 0)
406 return _dlopen(path, mode);
411 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
413 MSHookFunction(&dlopen, MSHake(dlopen));
415 // on iOS 6, backboardd is in charge of brightness, and freaks out when SpringBoard restarts :(
416 // the result is that the device is super dark until we attempt to update the brightness here.
418 if (kCFCoreFoundationVersionNumber >= 700) {
419 if (void (*GSEventSetBacklightLevel)(float) = reinterpret_cast<void (*)(float)>(dlsym(RTLD_DEFAULT, "GSEventSetBacklightLevel")))
420 if (NSMutableDictionary *defaults = [NSMutableDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/Library/Preferences/com.apple.springboard.plist", NSHomeDirectory()]])
421 if (NSNumber *level = [defaults objectForKey:@"SBBacklightLevel2"])
422 GSEventSetBacklightLevel([level floatValue]);