Reviewed by Antti.
[WebKit-https.git] / WebKitTools / WebKitLauncher / WebKitNightlyEnabler.m
1 /*
2  * Copyright (C) 2006, 2007 Apple Inc.  All rights reserved.
3  * Copyright (C) 2006 Graham Dennis.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer. 
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution. 
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission. 
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #import <Cocoa/Cocoa.h>
31
32 static void enableWebKitNightlyBehaviour() __attribute__ ((constructor));
33
34 static NSString *WKNERunState = @"WKNERunState";
35 static NSString *WKNEShouldMonitorShutdowns = @"WKNEShouldMonitorShutdowns";
36
37 typedef enum {
38     RunStateShutDown,
39     RunStateInitializing,
40     RunStateRunning
41 } WKNERunStates;
42
43 static bool extensionBundlesWereLoaded = NO;
44 static NSSet *extensionPaths = nil;
45
46 static void myBundleDidLoad(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
47 {
48     // Break out early if we have already detected an extension
49     if (extensionBundlesWereLoaded)
50         return;
51
52     NSBundle *bundle = (NSBundle *)object;
53     NSString *bundlePath = [[bundle bundlePath] stringByAbbreviatingWithTildeInPath];
54     NSString *bundleFileName = [bundlePath lastPathComponent];
55
56     // Explicitly ignore SIMBL.bundle, as its only purpose is to load extensions
57     // on a per-application basis.  It's presence indicates a user has application
58     // extensions, but not that any will be loaded into Safari
59     if ([bundleFileName isEqualToString:@"SIMBL.bundle"])
60         return;
61
62     // If the bundle lives inside a known extension path, flag it as an extension
63     NSEnumerator *e = [extensionPaths objectEnumerator];
64     NSString *path = nil;
65     while (path = [e nextObject]) {
66         if ([bundlePath length] < [path length])
67             continue;
68
69         if ([[bundlePath substringToIndex:[path length]] isEqualToString:path]) {
70             extensionBundlesWereLoaded = YES;
71             break;
72         }
73     }
74 }
75
76 static void myApplicationWillFinishLaunching(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
77 {
78     CFNotificationCenterRemoveObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillFinishLaunching, NULL, NULL);
79     CFNotificationCenterRemoveObserver(CFNotificationCenterGetLocalCenter(), &myBundleDidLoad, NULL, NULL);
80     [extensionPaths release];
81     extensionPaths = nil;
82
83     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
84     [userDefaults setInteger:RunStateRunning forKey:WKNERunState];
85     [userDefaults synchronize];
86
87     if (extensionBundlesWereLoaded)
88         NSRunInformationalAlertPanel(@"Safari extensions detected",
89                                      @"Safari extensions were detected on your system.  Extensions are incompatible with nightly builds of WebKit, and may cause crashes or incorrect behavior.  Please disable them if you experience such behavior.", @"Continue",
90                                      nil, nil);
91 }
92
93 static void myApplicationWillTerminate(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
94 {
95     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
96     [userDefaults setInteger:RunStateShutDown forKey:WKNERunState];
97     [userDefaults synchronize];
98 }
99
100 extern char **_CFGetProcessPath() __attribute__((weak));
101
102 static void poseAsWebKitApp()
103 {
104     char *webKitAppPath = getenv("WebKitAppPath");
105     if (!webKitAppPath || !_CFGetProcessPath)
106         return;
107
108     // Set up the main bundle early so it points at Safari.app
109     CFBundleGetMainBundle();
110
111     // Fiddle with CoreFoundation to have it pick up the executable path as being within WebKit.app
112     char **processPath = _CFGetProcessPath();
113     *processPath = NULL;
114     setenv("CFProcessPath", webKitAppPath, 1);
115     _CFGetProcessPath();
116
117     // Clean up
118     unsetenv("CFProcessPath");
119     unsetenv("WebKitAppPath");
120 }
121
122 static void enableWebKitNightlyBehaviour()
123 {
124     unsetenv("DYLD_INSERT_LIBRARIES");
125     poseAsWebKitApp();
126
127     extensionPaths = [[NSSet alloc] initWithObjects:@"~/Library/InputManagers/", @"/Library/InputManagers/",
128                                                     @"~/Library/Application Support/SIMBL/Plugins/", @"/Library/Application Support/SIMBL/Plugins/",
129                                                     @"~/Library/Application Enhancers/", @"/Library/Application Enhancers/",
130                                                     nil];
131
132     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
133     NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
134     NSDictionary *defaultPrefs = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:RunStateShutDown], WKNERunState,
135                                                                             [NSNumber numberWithBool:YES], WKNEShouldMonitorShutdowns, nil];
136     [userDefaults registerDefaults:defaultPrefs];
137     if ([userDefaults boolForKey:WKNEShouldMonitorShutdowns]) {
138         WKNERunStates savedState = (WKNERunStates)[userDefaults integerForKey:WKNERunState];
139         if (savedState == RunStateInitializing) {
140             // Use CoreFoundation here as AppKit hasn't been initialized at this stage of Safari's lifetime
141             CFOptionFlags responseFlags;
142             CFUserNotificationDisplayAlert(0, kCFUserNotificationCautionAlertLevel,
143                                            NULL, NULL, NULL,
144                                            CFSTR("WebKit failed to open correctly"),
145                                            CFSTR("WebKit failed to open correctly on your previous attempt. Please disable any Safari extensions that you may have installed.  If the problem continues to occur, please file a bug report at http://webkit.org/quality/reporting.html"), 
146                                            CFSTR("Continue"), NULL, NULL, &responseFlags);
147         }
148         else if (savedState == RunStateRunning) {
149             NSLog(@"WebKit failed to shut down cleanly.  Checking for Safari extensions.");
150             CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myBundleDidLoad,
151                                             myBundleDidLoad, (CFStringRef) NSBundleDidLoadNotification,
152                                             NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
153         }
154     }
155     [userDefaults setInteger:RunStateInitializing forKey:WKNERunState];
156     [userDefaults synchronize];
157
158     CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillFinishLaunching,
159                                     myApplicationWillFinishLaunching, (CFStringRef) NSApplicationWillFinishLaunchingNotification,
160                                     NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
161     CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), &myApplicationWillTerminate,
162                                     myApplicationWillTerminate, (CFStringRef) NSApplicationWillTerminateNotification,
163                                     NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
164     [pool release];
165 }