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/channel_info.h"
19 #include "chrome/common/url_constants.h"
20 #include "components/search_engines/template_url_service.h"
21 #include "components/version_info/version_info.h"
22 #import "third_party/google_toolbox_for_mac/src/AppKit/GTMUILocalizerAndLayoutTweaker.h"
23 #include "ui/base/l10n/l10n_util_mac.h"
26 #if defined(GOOGLE_CHROME_BUILD)
27 #include "base/prefs/pref_service.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/installer/util/google_update_settings.h"
33 @interface FirstRunDialogController (PrivateMethods)
40 // Compare function for -[NSArray sortedArrayUsingFunction:context:] that
41 // sorts the views in Y order bottom up.
42 NSInteger CompareFrameY(id view1, id view2, void* context) {
43 CGFloat y1 = NSMinY([view1 frame]);
44 CGFloat y2 = NSMinY([view2 frame]);
46 return NSOrderedAscending;
48 return NSOrderedDescending;
53 class FirstRunShowBridge : public base::RefCounted<FirstRunShowBridge> {
55 FirstRunShowBridge(FirstRunDialogController* controller);
60 friend class base::RefCounted<FirstRunShowBridge>;
62 ~FirstRunShowBridge();
64 FirstRunDialogController* controller_;
67 FirstRunShowBridge::FirstRunShowBridge(
68 FirstRunDialogController* controller) : controller_(controller) {
71 void FirstRunShowBridge::ShowDialog() {
73 base::MessageLoop::current()->QuitNow();
76 FirstRunShowBridge::~FirstRunShowBridge() {}
78 // Show the first run UI.
79 // Returns true if the first run dialog was shown.
80 bool ShowFirstRun(Profile* profile) {
81 bool dialog_shown = false;
82 #if defined(GOOGLE_CHROME_BUILD)
83 // The purpose of the dialog is to ask the user to enable stats and crash
84 // reporting. This setting may be controlled through configuration management
85 // in enterprise scenarios. If that is the case, skip the dialog entirely, as
86 // it's not worth bothering the user for only the default browser question
87 // (which is likely to be forced in enterprise deployments anyway).
88 const PrefService::Preference* metrics_reporting_pref =
89 g_browser_process->local_state()->FindPreference(
90 prefs::kMetricsReportingEnabled);
91 if (!metrics_reporting_pref || !metrics_reporting_pref->IsManaged()) {
92 base::scoped_nsobject<FirstRunDialogController> dialog(
93 [[FirstRunDialogController alloc] init]);
95 [dialog.get() showWindow:nil];
98 // If the dialog asked the user to opt-in for stats and crash reporting,
99 // record the decision and enable the crash reporter if appropriate.
100 bool stats_enabled = [dialog.get() statsEnabled];
101 GoogleUpdateSettings::SetCollectStatsConsent(stats_enabled);
103 // If selected set as default browser.
104 BOOL make_default_browser = [dialog.get() makeDefaultBrowser];
105 if (make_default_browser) {
106 bool success = ShellIntegration::SetAsDefaultBrowser();
110 #else // GOOGLE_CHROME_BUILD
111 // We don't show the dialog in Chromium.
112 #endif // GOOGLE_CHROME_BUILD
114 // Set preference to show first run bubble and welcome page.
115 // Only display the bubble if there is a default search provider.
116 TemplateURLService* search_engines_model =
117 TemplateURLServiceFactory::GetForProfile(profile);
118 if (search_engines_model &&
119 search_engines_model->GetDefaultSearchProvider()) {
120 first_run::SetShowFirstRunBubblePref(first_run::FIRST_RUN_BUBBLE_SHOW);
122 first_run::SetShouldShowWelcomePage();
127 // True when the stats checkbox should be checked by default. This is only
128 // the case when the canary is running.
129 bool StatsCheckboxDefault() {
130 return chrome::GetChannel() == version_info::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];