1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "chrome/browser/ui/cocoa/first_run_dialog.h"
8 #include "base/mac/bundle_locations.h"
9 #import "base/mac/scoped_nsobject.h"
10 #include "base/memory/ref_counted.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/strings/sys_string_conversions.h"
13 #include "chrome/browser/first_run/first_run.h"
14 #include "chrome/browser/first_run/first_run_dialog.h"
15 #include "chrome/browser/profiles/profile.h"
16 #include "chrome/browser/search_engines/template_url_service_factory.h"
17 #include "chrome/browser/shell_integration.h"
18 #include "chrome/common/chrome_version_info.h"
19 #include "chrome/common/url_constants.h"
20 #include "components/search_engines/template_url_service.h"
21 #import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h"
22 #include "ui/base/l10n/l10n_util_mac.h"
25 #if defined(GOOGLE_CHROME_BUILD)
26 #include "base/prefs/pref_service.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/common/pref_names.h"
29 #include "chrome/installer/util/google_update_settings.h"
32 @interface FirstRunDialogController (PrivateMethods)
39 // Compare function for -[NSArray sortedArrayUsingFunction:context:] that
40 // sorts the views in Y order bottom up.
41 NSInteger CompareFrameY(id view1, id view2, void* context) {
42 CGFloat y1 = NSMinY([view1 frame]);
43 CGFloat y2 = NSMinY([view2 frame]);
45 return NSOrderedAscending;
47 return NSOrderedDescending;
52 class FirstRunShowBridge : public base::RefCounted<FirstRunShowBridge> {
54 FirstRunShowBridge(FirstRunDialogController* controller);
59 friend class base::RefCounted<FirstRunShowBridge>;
61 ~FirstRunShowBridge();
63 FirstRunDialogController* controller_;
66 FirstRunShowBridge::FirstRunShowBridge(
67 FirstRunDialogController* controller) : controller_(controller) {
70 void FirstRunShowBridge::ShowDialog() {
72 base::MessageLoop::current()->QuitNow();
75 FirstRunShowBridge::~FirstRunShowBridge() {}
77 // Show the first run UI.
78 // Returns true if the first run dialog was shown.
79 bool ShowFirstRun(Profile* profile) {
80 bool dialog_shown = false;
81 #if defined(GOOGLE_CHROME_BUILD)
82 // The purpose of the dialog is to ask the user to enable stats and crash
83 // reporting. This setting may be controlled through configuration management
84 // in enterprise scenarios. If that is the case, skip the dialog entirely, as
85 // it's not worth bothering the user for only the default browser question
86 // (which is likely to be forced in enterprise deployments anyway).
87 const PrefService::Preference* metrics_reporting_pref =
88 g_browser_process->local_state()->FindPreference(
89 prefs::kMetricsReportingEnabled);
90 if (!metrics_reporting_pref || !metrics_reporting_pref->IsManaged()) {
91 base::scoped_nsobject<FirstRunDialogController> dialog(
92 [[FirstRunDialogController alloc] init]);
94 [dialog.get() showWindow:nil];
97 // If the dialog asked the user to opt-in for stats and crash reporting,
98 // record the decision and enable the crash reporter if appropriate.
99 bool stats_enabled = [dialog.get() statsEnabled];
100 GoogleUpdateSettings::SetCollectStatsConsent(stats_enabled);
102 // If selected set as default browser.
103 BOOL make_default_browser = [dialog.get() makeDefaultBrowser];
104 if (make_default_browser) {
105 bool success = ShellIntegration::SetAsDefaultBrowser();
109 #else // GOOGLE_CHROME_BUILD
110 // We don't show the dialog in Chromium.
111 #endif // GOOGLE_CHROME_BUILD
113 // Set preference to show first run bubble and welcome page.
114 // Only display the bubble if there is a default search provider.
115 TemplateURLService* search_engines_model =
116 TemplateURLServiceFactory::GetForProfile(profile);
117 if (search_engines_model &&
118 search_engines_model->GetDefaultSearchProvider()) {
119 first_run::SetShowFirstRunBubblePref(first_run::FIRST_RUN_BUBBLE_SHOW);
121 first_run::SetShouldShowWelcomePage();
126 // True when the stats checkbox should be checked by default. This is only
127 // the case when the canary is running.
128 bool StatsCheckboxDefault() {
129 return chrome::VersionInfo::GetChannel() ==
130 chrome::VersionInfo::CHANNEL_CANARY;
135 namespace first_run {
137 bool ShowFirstRunDialog(Profile* profile) {
138 return ShowFirstRun(profile);
141 } // namespace first_run
143 @implementation FirstRunDialogController
145 @synthesize statsEnabled = statsEnabled_;
146 @synthesize makeDefaultBrowser = makeDefaultBrowser_;
150 [base::mac::FrameworkBundle() pathForResource:@"FirstRunDialog"
152 if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
153 // Bound to the dialog checkboxes.
154 makeDefaultBrowser_ = ShellIntegration::CanSetAsDefaultBrowser() !=
155 ShellIntegration::SET_DEFAULT_NOT_ALLOWED;
156 statsEnabled_ = StatsCheckboxDefault();
165 - (IBAction)showWindow:(id)sender {
166 // The main MessageLoop has not yet run, but has been spun. If we call
167 // -[NSApplication runModalForWindow:] we will hang <http://crbug.com/54248>.
168 // Therefore the main MessageLoop is run so things work.
170 scoped_refptr<FirstRunShowBridge> bridge(new FirstRunShowBridge(self));
171 base::MessageLoop::current()->PostTask(FROM_HERE,
172 base::Bind(&FirstRunShowBridge::ShowDialog, bridge.get()));
173 base::MessageLoop::current()->Run();
177 NSWindow* win = [self window];
179 if (!ShellIntegration::CanSetAsDefaultBrowser()) {
180 [setAsDefaultCheckbox_ setHidden:YES];
183 // Only support the sizing the window once.
184 DCHECK(!beenSized_) << "ShowWindow was called twice?";
187 DCHECK_GT([objectsToSize_ count], 0U);
189 // Size everything to fit, collecting the widest growth needed (XIB provides
190 // the min size, i.e.-never shrink, just grow).
191 CGFloat largestWidthChange = 0.0;
192 for (NSView* view in objectsToSize_) {
193 DCHECK_NE(statsCheckbox_, view) << "Stats checkbox shouldn't be in list";
194 if (![view isHidden]) {
195 NSSize delta = [GTMUILocalizerAndLayoutTweaker sizeToFitView:view];
196 DCHECK_EQ(delta.height, 0.0)
197 << "Didn't expect anything to change heights";
198 if (largestWidthChange < delta.width)
199 largestWidthChange = delta.width;
203 // Make the window wide enough to fit everything.
204 if (largestWidthChange > 0.0) {
205 NSView* contentView = [win contentView];
206 NSRect windowFrame = [contentView convertRect:[win frame] fromView:nil];
207 windowFrame.size.width += largestWidthChange;
208 windowFrame = [contentView convertRect:windowFrame toView:nil];
209 [win setFrame:windowFrame display:NO];
212 // The stats checkbox gets some really long text, so it gets word wrapped
214 DCHECK(statsCheckbox_);
215 CGFloat statsCheckboxHeightChange = 0.0;
216 [GTMUILocalizerAndLayoutTweaker wrapButtonTitleForWidth:statsCheckbox_];
217 statsCheckboxHeightChange =
218 [GTMUILocalizerAndLayoutTweaker sizeToFitView:statsCheckbox_].height;
220 // Walk bottom up shuffling for all the hidden views.
222 [[[win contentView] subviews] sortedArrayUsingFunction:CompareFrameY
224 CGFloat moveDown = 0.0;
225 NSUInteger numSubViews = [subViews count];
226 for (NSUInteger idx = 0 ; idx < numSubViews ; ++idx) {
227 NSView* view = [subViews objectAtIndex:idx];
229 // If the view is hidden, collect the amount to move everything above it
230 // down, if it's not hidden, apply any shift down.
231 if ([view isHidden]) {
232 DCHECK_GT((numSubViews - 1), idx)
233 << "Don't support top view being hidden";
234 NSView* nextView = [subViews objectAtIndex:(idx + 1)];
235 CGFloat viewBottom = [view frame].origin.y;
236 CGFloat nextViewBottom = [nextView frame].origin.y;
237 moveDown += nextViewBottom - viewBottom;
239 if (moveDown != 0.0) {
240 NSPoint origin = [view frame].origin;
241 origin.y -= moveDown;
242 [view setFrameOrigin:origin];
245 // Special case, if this is the stats checkbox, everything above it needs
246 // to get moved up by the amount it changed height.
247 if (view == statsCheckbox_) {
248 moveDown -= statsCheckboxHeightChange;
252 // Resize the window for any height change from hidden views, etc.
253 if (moveDown != 0.0) {
254 NSView* contentView = [win contentView];
255 [contentView setAutoresizesSubviews:NO];
256 NSRect windowFrame = [contentView convertRect:[win frame] fromView:nil];
257 windowFrame.size.height -= moveDown;
258 windowFrame = [contentView convertRect:windowFrame toView:nil];
259 [win setFrame:windowFrame display:NO];
260 [contentView setAutoresizesSubviews:YES];
265 // Neat weirdness in the below code - the Application menu stays enabled
266 // while the window is open but selecting items from it (e.g. Quit) has
267 // no effect. I'm guessing that this is an artifact of us being a
268 // background-only application at this stage and displaying a modal
273 [NSApp runModalForWindow:win];
276 - (IBAction)ok:(id)sender {
277 [[self window] close];
281 - (IBAction)learnMore:(id)sender {
282 NSString* urlStr = base::SysUTF8ToNSString(chrome::kLearnMoreReportingURL);
283 NSURL* learnMoreUrl = [NSURL URLWithString:urlStr];
284 [[NSWorkspace sharedWorkspace] openURL:learnMoreUrl];