1 // Copyright 2013 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 #include "chrome/browser/ui/views/app_list/win/app_list_service_win.h"
10 #include "base/command_line.h"
11 #include "base/file_util.h"
12 #include "base/lazy_instance.h"
13 #include "base/memory/weak_ptr.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/histogram.h"
16 #include "base/path_service.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/sequenced_worker_pool.h"
20 #include "base/time/time.h"
21 #include "base/timer/timer.h"
22 #include "base/win/shortcut.h"
23 #include "base/win/windows_version.h"
24 #include "chrome/app/chrome_dll_resource.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/platform_util.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/profiles/profile_manager.h"
29 #include "chrome/browser/shell_integration.h"
30 #include "chrome/browser/ui/app_list/app_list.h"
31 #include "chrome/browser/ui/app_list/app_list_controller_delegate.h"
32 #include "chrome/browser/ui/app_list/app_list_factory.h"
33 #include "chrome/browser/ui/app_list/app_list_service_impl.h"
34 #include "chrome/browser/ui/app_list/app_list_shower.h"
35 #include "chrome/browser/ui/app_list/app_list_view_delegate.h"
36 #include "chrome/browser/ui/app_list/keep_alive_service_impl.h"
37 #include "chrome/browser/ui/apps/app_metro_infobar_delegate_win.h"
38 #include "chrome/browser/ui/views/app_list/win/activation_tracker_win.h"
39 #include "chrome/browser/ui/views/app_list/win/app_list_controller_delegate_win.h"
40 #include "chrome/browser/ui/views/app_list/win/app_list_win.h"
41 #include "chrome/browser/web_applications/web_app.h"
42 #include "chrome/common/chrome_constants.h"
43 #include "chrome/common/chrome_switches.h"
44 #include "chrome/common/chrome_version_info.h"
45 #include "chrome/common/pref_names.h"
46 #include "chrome/installer/launcher_support/chrome_launcher_support.h"
47 #include "chrome/installer/util/browser_distribution.h"
48 #include "chrome/installer/util/google_update_settings.h"
49 #include "chrome/installer/util/install_util.h"
50 #include "chrome/installer/util/util_constants.h"
51 #include "content/public/browser/browser_thread.h"
52 #include "grit/chromium_strings.h"
53 #include "grit/generated_resources.h"
54 #include "grit/google_chrome_strings.h"
55 #include "grit/theme_resources.h"
56 #include "ui/app_list/app_list_model.h"
57 #include "ui/app_list/pagination_model.h"
58 #include "ui/app_list/views/app_list_view.h"
59 #include "ui/base/l10n/l10n_util.h"
60 #include "ui/base/resource/resource_bundle.h"
61 #include "ui/base/win/shell.h"
62 #include "ui/gfx/display.h"
63 #include "ui/gfx/image/image_skia.h"
64 #include "ui/gfx/screen.h"
65 #include "ui/views/bubble/bubble_border.h"
66 #include "ui/views/widget/widget.h"
67 #include "win8/util/win8_util.h"
70 #include "ui/aura/root_window.h"
71 #include "ui/aura/window.h"
75 #include "chrome/browser/ui/app_list/app_list_service_ash.h"
76 #include "chrome/browser/ui/host_desktop.h"
79 #if defined(GOOGLE_CHROME_BUILD)
80 #include "chrome/installer/util/install_util.h"
84 AppListService* AppListService::Get(chrome::HostDesktopType desktop_type) {
86 if (desktop_type == chrome::HOST_DESKTOP_TYPE_ASH)
87 return chrome::GetAppListServiceAsh();
90 return chrome::GetAppListServiceWin();
94 void AppListService::InitAll(Profile* initial_profile) {
96 chrome::GetAppListServiceAsh()->Init(initial_profile);
98 chrome::GetAppListServiceWin()->Init(initial_profile);
103 // Migrate chrome::kAppLauncherIsEnabled pref to
104 // chrome::kAppLauncherHasBeenEnabled pref.
105 void MigrateAppLauncherEnabledPref() {
106 PrefService* prefs = g_browser_process->local_state();
107 if (prefs->HasPrefPath(prefs::kAppLauncherIsEnabled)) {
108 prefs->SetBoolean(prefs::kAppLauncherHasBeenEnabled,
109 prefs->GetBoolean(prefs::kAppLauncherIsEnabled));
110 prefs->ClearPref(prefs::kAppLauncherIsEnabled);
114 int GetAppListIconIndex() {
115 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
116 return dist->GetIconIndex(BrowserDistribution::SHORTCUT_APP_LAUNCHER);
119 base::string16 GetAppListIconPath() {
120 base::FilePath icon_path;
121 if (!PathService::Get(base::FILE_EXE, &icon_path)) {
123 return base::string16();
126 std::stringstream ss;
127 ss << "," << GetAppListIconIndex();
128 base::string16 result = icon_path.value();
129 result.append(base::UTF8ToUTF16(ss.str()));
133 base::string16 GetAppListShortcutName() {
134 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
135 return dist->GetShortcutName(BrowserDistribution::SHORTCUT_APP_LAUNCHER);
138 CommandLine GetAppListCommandLine() {
139 const char* const kSwitchesToCopy[] = { switches::kUserDataDir };
140 CommandLine* current = CommandLine::ForCurrentProcess();
141 base::FilePath chrome_exe;
142 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
144 return CommandLine(CommandLine::NO_PROGRAM);
146 CommandLine command_line(chrome_exe);
147 command_line.CopySwitchesFrom(*current, kSwitchesToCopy,
148 arraysize(kSwitchesToCopy));
149 command_line.AppendSwitch(switches::kShowAppList);
153 base::string16 GetAppModelId() {
154 // The AppModelId should be the same for all profiles in a user data directory
155 // but different for different user data directories, so base it on the
156 // initial profile in the current user data directory.
157 base::FilePath initial_profile_path;
158 CommandLine* command_line = CommandLine::ForCurrentProcess();
159 if (command_line->HasSwitch(switches::kUserDataDir)) {
160 initial_profile_path =
161 command_line->GetSwitchValuePath(switches::kUserDataDir).AppendASCII(
162 chrome::kInitialProfile);
164 return ShellIntegration::GetAppListAppModelIdForProfile(initial_profile_path);
167 void SetDidRunForNDayActiveStats() {
168 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
169 base::FilePath exe_path;
170 if (!PathService::Get(base::DIR_EXE, &exe_path)) {
174 bool system_install =
175 !InstallUtil::IsPerUserInstall(exe_path.value().c_str());
176 // Using Chrome Binary dist: Chrome dist may not exist for the legacy
177 // App Launcher, and App Launcher dist may be "shadow", which does not
178 // contain the information needed to determine multi-install.
179 // Edge case involving Canary: crbug/239163.
180 BrowserDistribution* chrome_binaries_dist =
181 BrowserDistribution::GetSpecificDistribution(
182 BrowserDistribution::CHROME_BINARIES);
183 if (chrome_binaries_dist &&
184 InstallUtil::IsMultiInstall(chrome_binaries_dist, system_install)) {
185 BrowserDistribution* app_launcher_dist =
186 BrowserDistribution::GetSpecificDistribution(
187 BrowserDistribution::CHROME_APP_HOST);
188 GoogleUpdateSettings::UpdateDidRunStateForDistribution(
195 // The start menu shortcut is created on first run by users that are
196 // upgrading. The desktop and taskbar shortcuts are created the first time the
197 // user enables the app list. The taskbar shortcut is created in
198 // |user_data_dir| and will use a Windows Application Model Id of
199 // |app_model_id|. This runs on the FILE thread and not in the blocking IO
200 // thread pool as there are other tasks running (also on the FILE thread)
201 // which fiddle with shortcut icons
202 // (ShellIntegration::MigrateWin7ShortcutsOnPath). Having different threads
203 // fiddle with the same shortcuts could cause race issues.
204 void CreateAppListShortcuts(
205 const base::FilePath& user_data_dir,
206 const base::string16& app_model_id,
207 const ShellIntegration::ShortcutLocations& creation_locations) {
208 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
210 // Shortcut paths under which to create shortcuts.
211 std::vector<base::FilePath> shortcut_paths =
212 web_app::internals::GetShortcutPaths(creation_locations);
214 bool pin_to_taskbar = creation_locations.in_quick_launch_bar &&
215 (base::win::GetVersion() >= base::win::VERSION_WIN7);
217 // Create a shortcut in the |user_data_dir| for taskbar pinning.
219 shortcut_paths.push_back(user_data_dir);
222 base::FilePath chrome_exe;
223 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
228 base::string16 app_list_shortcut_name = GetAppListShortcutName();
230 base::string16 wide_switches(GetAppListCommandLine().GetArgumentsString());
232 base::win::ShortcutProperties shortcut_properties;
233 shortcut_properties.set_target(chrome_exe);
234 shortcut_properties.set_working_dir(chrome_exe.DirName());
235 shortcut_properties.set_arguments(wide_switches);
236 shortcut_properties.set_description(app_list_shortcut_name);
237 shortcut_properties.set_icon(chrome_exe, GetAppListIconIndex());
238 shortcut_properties.set_app_id(app_model_id);
240 for (size_t i = 0; i < shortcut_paths.size(); ++i) {
241 base::FilePath shortcut_file =
242 shortcut_paths[i].Append(app_list_shortcut_name).
243 AddExtension(installer::kLnkExt);
244 if (!base::PathExists(shortcut_file.DirName()) &&
245 !base::CreateDirectory(shortcut_file.DirName())) {
249 success = success && base::win::CreateOrUpdateShortcutLink(
250 shortcut_file, shortcut_properties,
251 base::win::SHORTCUT_CREATE_ALWAYS);
254 if (success && pin_to_taskbar) {
255 base::FilePath shortcut_to_pin =
256 user_data_dir.Append(app_list_shortcut_name).
257 AddExtension(installer::kLnkExt);
258 success = base::win::TaskbarPinShortcutLink(
259 shortcut_to_pin.value().c_str()) && success;
263 // Customizes the app list |hwnd| for Windows (eg: disable aero peek, set up
265 void SetWindowAttributes(HWND hwnd) {
266 if (base::win::GetVersion() > base::win::VERSION_VISTA) {
267 // Disable aero peek. Without this, hovering over the taskbar popup puts
268 // Windows into a mode for switching between windows in the same
269 // application. The app list has just one window, so it is just distracting.
270 BOOL disable_value = TRUE;
271 ::DwmSetWindowAttribute(hwnd,
274 sizeof(disable_value));
277 ui::win::SetAppIdForWindow(GetAppModelId(), hwnd);
278 CommandLine relaunch = GetAppListCommandLine();
279 base::string16 app_name(GetAppListShortcutName());
280 ui::win::SetRelaunchDetailsForWindow(
281 relaunch.GetCommandLineString(), app_name, hwnd);
282 ::SetWindowText(hwnd, app_name.c_str());
283 base::string16 icon_path = GetAppListIconPath();
284 ui::win::SetAppIconForWindow(icon_path, hwnd);
287 class AppListFactoryWin : public AppListFactory {
289 explicit AppListFactoryWin(AppListServiceWin* service)
290 : service_(service) {
293 virtual ~AppListFactoryWin() {
296 virtual AppList* CreateAppList(
298 AppListService* service,
299 const base::Closure& on_should_dismiss) OVERRIDE {
300 // The view delegate will be owned by the app list view. The app list view
301 // manages it's own lifetime.
302 AppListViewDelegate* view_delegate =
303 new AppListViewDelegate(profile,
304 service->GetControllerDelegate());
305 app_list::AppListView* view = new app_list::AppListView(view_delegate);
306 gfx::Point cursor = gfx::Screen::GetNativeScreen()->GetCursorScreenPoint();
307 view->InitAsBubbleAtFixedLocation(NULL,
310 views::BubbleBorder::FLOAT,
311 false /* border_accepts_events */);
312 SetWindowAttributes(view->GetHWND());
313 return new AppListWin(view, on_should_dismiss);
317 // PaginationModel that is shared across all views.
318 app_list::PaginationModel pagination_model_;
319 AppListServiceWin* service_;
321 DISALLOW_COPY_AND_ASSIGN(AppListFactoryWin);
327 AppListServiceWin* AppListServiceWin::GetInstance() {
328 return Singleton<AppListServiceWin,
329 LeakySingletonTraits<AppListServiceWin> >::get();
332 AppListServiceWin::AppListServiceWin()
333 : enable_app_list_on_next_init_(false),
334 shower_(new AppListShower(
335 scoped_ptr<AppListFactory>(new AppListFactoryWin(this)),
336 scoped_ptr<KeepAliveService>(new KeepAliveServiceImpl),
338 controller_delegate_(new AppListControllerDelegateWin(this)),
339 weak_factory_(this) {
342 AppListServiceWin::~AppListServiceWin() {
345 void AppListServiceWin::set_can_close(bool can_close) {
346 shower_->set_can_close(can_close);
349 gfx::NativeWindow AppListServiceWin::GetAppListWindow() {
350 return shower_->GetWindow();
353 Profile* AppListServiceWin::GetCurrentAppListProfile() {
354 return shower_->profile();
357 AppListControllerDelegate* AppListServiceWin::GetControllerDelegate() {
358 return controller_delegate_.get();
361 void AppListServiceWin::ShowForProfile(Profile* requested_profile) {
362 DCHECK(requested_profile);
363 if (requested_profile->IsManaged())
366 ScopedKeepAlive show_app_list_keepalive;
368 content::BrowserThread::PostBlockingPoolTask(
369 FROM_HERE, base::Bind(SetDidRunForNDayActiveStats));
371 if (win8::IsSingleWindowMetroMode()) {
372 // This request came from Windows 8 in desktop mode, but chrome is currently
373 // running in Metro mode.
374 AppMetroInfoBarDelegateWin::Create(
375 requested_profile, AppMetroInfoBarDelegateWin::SHOW_APP_LIST,
380 InvalidatePendingProfileLoads();
381 SetProfilePath(requested_profile->GetPath());
382 shower_->ShowForProfile(requested_profile);
383 RecordAppListLaunch();
386 void AppListServiceWin::DismissAppList() {
387 shower_->DismissAppList();
390 void AppListServiceWin::OnAppListClosing() {
391 shower_->CloseAppList();
394 void AppListServiceWin::OnLoadProfileForWarmup(Profile* initial_profile) {
395 if (!IsWarmupNeeded())
398 base::Time before_warmup(base::Time::Now());
399 shower_->WarmupForProfile(initial_profile);
400 UMA_HISTOGRAM_TIMES("Apps.AppListWarmupDuration",
401 base::Time::Now() - before_warmup);
404 void AppListServiceWin::SetAppListNextPaintCallback(void (*callback)()) {
405 app_list::AppListView::SetNextPaintCallback(callback);
408 void AppListServiceWin::HandleFirstRun() {
409 PrefService* local_state = g_browser_process->local_state();
410 // If the app list is already enabled during first run, then the user had
411 // opted in to the app launcher before uninstalling, so we re-enable to
412 // restore shortcuts to the app list.
413 // Note we can't directly create the shortcuts here because the IO thread
414 // hasn't been created yet.
415 enable_app_list_on_next_init_ = local_state->GetBoolean(
416 prefs::kAppLauncherHasBeenEnabled);
419 void AppListServiceWin::Init(Profile* initial_profile) {
420 // In non-Ash metro mode, we can not show the app list for this process, so do
421 // not bother performing Init tasks.
422 if (win8::IsSingleWindowMetroMode())
425 if (enable_app_list_on_next_init_) {
426 enable_app_list_on_next_init_ = false;
427 EnableAppList(initial_profile);
431 PrefService* prefs = g_browser_process->local_state();
432 if (prefs->HasPrefPath(prefs::kRestartWithAppList) &&
433 prefs->GetBoolean(prefs::kRestartWithAppList)) {
434 prefs->SetBoolean(prefs::kRestartWithAppList, false);
435 // If we are restarting in Metro mode we will lose focus straight away. We
436 // need to reacquire focus when that happens.
437 shower_->ShowAndReacquireFocus(initial_profile);
440 // Migrate from legacy app launcher if we are on a non-canary and non-chromium
442 #if defined(GOOGLE_CHROME_BUILD)
443 if (!InstallUtil::IsChromeSxSProcess() &&
444 !chrome_launcher_support::GetAnyAppHostPath().empty()) {
445 chrome_launcher_support::InstallationState state =
446 chrome_launcher_support::GetAppLauncherInstallationState();
447 if (state == chrome_launcher_support::NOT_INSTALLED) {
448 // If app_host.exe is found but can't be located in the registry,
449 // skip the migration as this is likely a developer build.
451 } else if (state == chrome_launcher_support::INSTALLED_AT_SYSTEM_LEVEL) {
452 chrome_launcher_support::UninstallLegacyAppLauncher(
453 chrome_launcher_support::SYSTEM_LEVEL_INSTALLATION);
454 } else if (state == chrome_launcher_support::INSTALLED_AT_USER_LEVEL) {
455 chrome_launcher_support::UninstallLegacyAppLauncher(
456 chrome_launcher_support::USER_LEVEL_INSTALLATION);
458 EnableAppList(initial_profile);
465 MigrateAppLauncherEnabledPref();
466 HandleCommandLineFlags(initial_profile);
470 void AppListServiceWin::CreateForProfile(Profile* profile) {
471 shower_->CreateViewForProfile(profile);
474 bool AppListServiceWin::IsAppListVisible() const {
475 return shower_->IsAppListVisible();
478 void AppListServiceWin::CreateShortcut() {
479 // Check if the app launcher shortcuts have ever been created before.
480 // Shortcuts should only be created once. If the user unpins the taskbar
481 // shortcut, they can restore it by pinning the start menu or desktop
483 ShellIntegration::ShortcutLocations shortcut_locations;
484 shortcut_locations.on_desktop = true;
485 shortcut_locations.in_quick_launch_bar = true;
486 shortcut_locations.applications_menu_location =
487 ShellIntegration::APP_MENU_LOCATION_SUBDIR_CHROME;
488 base::FilePath user_data_dir(
489 g_browser_process->profile_manager()->user_data_dir());
491 content::BrowserThread::PostTask(
492 content::BrowserThread::FILE,
494 base::Bind(&CreateAppListShortcuts,
495 user_data_dir, GetAppModelId(), shortcut_locations));
498 void AppListServiceWin::ScheduleWarmup() {
499 // Post a task to create the app list. This is posted to not impact startup
501 const int kInitWindowDelay = 30;
502 base::MessageLoop::current()->PostDelayedTask(
504 base::Bind(&AppListServiceWin::LoadProfileForWarmup,
505 weak_factory_.GetWeakPtr()),
506 base::TimeDelta::FromSeconds(kInitWindowDelay));
509 bool AppListServiceWin::IsWarmupNeeded() {
510 if (!g_browser_process || g_browser_process->IsShuttingDown())
513 // We only need to initialize the view if there's no view already created and
514 // there's no profile loading to be shown.
515 return !shower_->HasView() && !profile_loader().IsAnyProfileLoading();
518 void AppListServiceWin::LoadProfileForWarmup() {
519 if (!IsWarmupNeeded())
522 ProfileManager* profile_manager = g_browser_process->profile_manager();
523 base::FilePath profile_path(GetProfilePath(profile_manager->user_data_dir()));
525 profile_loader().LoadProfileInvalidatingOtherLoads(
527 base::Bind(&AppListServiceWin::OnLoadProfileForWarmup,
528 weak_factory_.GetWeakPtr()));
533 AppListService* GetAppListServiceWin() {
534 return AppListServiceWin::GetInstance();
537 } // namespace chrome