Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / chrome / browser / jumplist_win.cc
blobb4a311a54bb5781675b410c0dac9ff5b0ac16ac5
1 // Copyright 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 #include "chrome/browser/jumplist_win.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/files/file_util.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/path_service.h"
13 #include "base/prefs/pref_change_registrar.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/threading/thread.h"
17 #include "chrome/browser/browser_process.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/favicon/favicon_service.h"
20 #include "chrome/browser/favicon/favicon_service_factory.h"
21 #include "chrome/browser/history/history_service.h"
22 #include "chrome/browser/history/top_sites_factory.h"
23 #include "chrome/browser/metrics/jumplist_metrics_win.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_info_cache.h"
26 #include "chrome/browser/profiles/profile_manager.h"
27 #include "chrome/browser/sessions/tab_restore_service.h"
28 #include "chrome/browser/sessions/tab_restore_service_factory.h"
29 #include "chrome/browser/shell_integration.h"
30 #include "chrome/common/chrome_constants.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/pref_names.h"
33 #include "chrome/common/url_constants.h"
34 #include "chrome/grit/generated_resources.h"
35 #include "components/favicon_base/favicon_types.h"
36 #include "components/history/core/browser/page_usage_data.h"
37 #include "components/history/core/browser/top_sites.h"
38 #include "components/sessions/session_types.h"
39 #include "components/signin/core/common/profile_management_switches.h"
40 #include "content/public/browser/browser_thread.h"
41 #include "content/public/browser/notification_source.h"
42 #include "ui/base/l10n/l10n_util.h"
43 #include "ui/gfx/codec/png_codec.h"
44 #include "ui/gfx/favicon_size.h"
45 #include "ui/gfx/icon_util.h"
46 #include "ui/gfx/image/image_family.h"
47 #include "url/gurl.h"
49 using content::BrowserThread;
51 namespace {
53 // Append the common switches to each shell link.
54 void AppendCommonSwitches(ShellLinkItem* shell_link) {
55 const char* kSwitchNames[] = { switches::kUserDataDir };
56 const base::CommandLine& command_line =
57 *base::CommandLine::ForCurrentProcess();
58 shell_link->GetCommandLine()->CopySwitchesFrom(command_line,
59 kSwitchNames,
60 arraysize(kSwitchNames));
63 // Create a ShellLinkItem preloaded with common switches.
64 scoped_refptr<ShellLinkItem> CreateShellLink() {
65 scoped_refptr<ShellLinkItem> link(new ShellLinkItem);
66 AppendCommonSwitches(link.get());
67 return link;
70 // Creates a temporary icon file to be shown in JumpList.
71 bool CreateIconFile(const SkBitmap& bitmap,
72 const base::FilePath& icon_dir,
73 base::FilePath* icon_path) {
74 // Retrieve the path to a temporary file.
75 // We don't have to care about the extension of this temporary file because
76 // JumpList does not care about it.
77 base::FilePath path;
78 if (!base::CreateTemporaryFileInDir(icon_dir, &path))
79 return false;
81 // Create an icon file from the favicon attached to the given |page|, and
82 // save it as the temporary file.
83 gfx::ImageFamily image_family;
84 image_family.Add(gfx::Image::CreateFrom1xBitmap(bitmap));
85 if (!IconUtil::CreateIconFileFromImageFamily(image_family, path))
86 return false;
88 // Add this icon file to the list and return its absolute path.
89 // The IShellLink::SetIcon() function needs the absolute path to an icon.
90 *icon_path = path;
91 return true;
94 // Updates the "Tasks" category of the JumpList.
95 bool UpdateTaskCategory(
96 JumpListUpdater* jumplist_updater,
97 IncognitoModePrefs::Availability incognito_availability) {
98 base::FilePath chrome_path;
99 if (!PathService::Get(base::FILE_EXE, &chrome_path))
100 return false;
102 ShellLinkItemList items;
104 // Create an IShellLink object which launches Chrome, and add it to the
105 // collection. We use our application icon as the icon for this item.
106 // We remove '&' characters from this string so we can share it with our
107 // system menu.
108 if (incognito_availability != IncognitoModePrefs::FORCED) {
109 scoped_refptr<ShellLinkItem> chrome = CreateShellLink();
110 base::string16 chrome_title = l10n_util::GetStringUTF16(IDS_NEW_WINDOW);
111 ReplaceSubstringsAfterOffset(&chrome_title, 0, L"&", L"");
112 chrome->set_title(chrome_title);
113 chrome->set_icon(chrome_path.value(), 0);
114 items.push_back(chrome);
117 // Create an IShellLink object which launches Chrome in incognito mode, and
118 // add it to the collection. We use our application icon as the icon for
119 // this item.
120 if (incognito_availability != IncognitoModePrefs::DISABLED) {
121 scoped_refptr<ShellLinkItem> incognito = CreateShellLink();
122 incognito->GetCommandLine()->AppendSwitch(switches::kIncognito);
123 base::string16 incognito_title =
124 l10n_util::GetStringUTF16(IDS_NEW_INCOGNITO_WINDOW);
125 ReplaceSubstringsAfterOffset(&incognito_title, 0, L"&", L"");
126 incognito->set_title(incognito_title);
127 incognito->set_icon(chrome_path.value(), 0);
128 items.push_back(incognito);
131 return jumplist_updater->AddTasks(items);
134 // Updates the application JumpList.
135 bool UpdateJumpList(const wchar_t* app_id,
136 const ShellLinkItemList& most_visited_pages,
137 const ShellLinkItemList& recently_closed_pages,
138 const ShellLinkItemList& profile_switcher,
139 IncognitoModePrefs::Availability incognito_availability,
140 bool use_profiles_category) {
141 // JumpList is implemented only on Windows 7 or later.
142 // So, we should return now when this function is called on earlier versions
143 // of Windows.
144 if (!JumpListUpdater::IsEnabled())
145 return true;
147 JumpListUpdater jumplist_updater(app_id);
148 if (!jumplist_updater.BeginUpdate())
149 return false;
151 size_t recently_closed_items;
152 size_t profiles_or_most_visited_items;
154 // Depending on the experiment, we are either showing the "Most-Visited" or
155 // "People" categories.
156 if (use_profiles_category) {
157 // Show at most 8 profiles, and fill the rest of the slots with the
158 // "recently-closed" items.
159 const size_t kMaxProfiles = 8;
160 size_t max_displayed_items = std::min(kMaxProfiles,
161 jumplist_updater.user_max_items());
162 profiles_or_most_visited_items = std::min(max_displayed_items,
163 profile_switcher.size());
164 recently_closed_items =
165 jumplist_updater.user_max_items() - profiles_or_most_visited_items;
166 } else {
167 // We allocate 60% of the given JumpList slots to "most-visited" items
168 // and 40% to "recently-closed" items, respectively.
169 // Nevertheless, if there are not so many items in |recently_closed_pages|,
170 // we give the remaining slots to "most-visited" items.
171 const int kMostVisited = 60;
172 const int kRecentlyClosed = 40;
173 const int kTotal = kMostVisited + kRecentlyClosed;
174 profiles_or_most_visited_items =
175 MulDiv(jumplist_updater.user_max_items(), kMostVisited, kTotal);
176 recently_closed_items =
177 jumplist_updater.user_max_items() - profiles_or_most_visited_items;
178 if (recently_closed_pages.size() < recently_closed_items) {
179 profiles_or_most_visited_items +=
180 recently_closed_items - recently_closed_pages.size();
181 recently_closed_items = recently_closed_pages.size();
185 // Update the "Most Visited" category of the JumpList if it exists.
186 // This update request is applied into the JumpList when we commit this
187 // transaction.
188 if (!use_profiles_category && !jumplist_updater.AddCustomCategory(
189 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED),
190 most_visited_pages, profiles_or_most_visited_items)) {
191 return false;
194 // Update the "Recently Closed" category of the JumpList.
195 if (!jumplist_updater.AddCustomCategory(
196 l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED),
197 recently_closed_pages, recently_closed_items)) {
198 return false;
201 // Update the "People" category of the JumpList if it exists. Only display it
202 // if there's more than one profile available.
203 if (use_profiles_category && profile_switcher.size() > 1 &&
204 !jumplist_updater.AddCustomCategory(
205 l10n_util::GetStringUTF16(IDS_PROFILES_OPTIONS_GROUP_NAME),
206 profile_switcher, profiles_or_most_visited_items)) {
207 return false;
210 // Update the "Tasks" category of the JumpList.
211 if (!UpdateTaskCategory(&jumplist_updater, incognito_availability))
212 return false;
214 // Commit this transaction and send the updated JumpList to Windows.
215 if (!jumplist_updater.CommitUpdate())
216 return false;
218 return true;
221 // Checks whether the experiment that replaces the Most Visited category
222 // with a Profiles list exists.
223 bool HasProfilesJumplistExperiment() {
224 const std::string group_name =
225 base::FieldTrialList::FindFullName("WindowsJumplistProfiles");
226 return group_name == "UseProfiles";
229 } // namespace
231 JumpList::JumpList(Profile* profile)
232 : profile_(profile),
233 task_id_(base::CancelableTaskTracker::kBadTaskId),
234 weak_ptr_factory_(this),
235 use_profiles_category_(false) {
236 DCHECK(Enabled());
237 // To update JumpList when a tab is added or removed, we add this object to
238 // the observer list of the TabRestoreService class.
239 // When we add this object to the observer list, we save the pointer to this
240 // TabRestoreService object. This pointer is used when we remove this object
241 // from the observer list.
242 TabRestoreService* tab_restore_service =
243 TabRestoreServiceFactory::GetForProfile(profile_);
244 if (!tab_restore_service)
245 return;
247 app_id_ = ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath());
248 icon_dir_ = profile_->GetPath().Append(chrome::kJumpListIconDirname);
249 use_profiles_category_ = HasProfilesJumplistExperiment();
251 scoped_refptr<history::TopSites> top_sites =
252 TopSitesFactory::GetForProfile(profile_);
253 if (top_sites) {
254 // TopSites updates itself after a delay. This is especially noticable when
255 // your profile is empty. Ask TopSites to update itself when jumplist is
256 // initialized.
257 top_sites->SyncWithHistory();
258 registrar_.reset(new content::NotificationRegistrar);
259 // Register as TopSitesObserver so that we can update ourselves when the
260 // TopSites changes.
261 top_sites->AddObserver(this);
262 // Register for notification when profile is destroyed to ensure that all
263 // observers are detatched at that time.
264 registrar_->Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
265 content::Source<Profile>(profile_));
267 tab_restore_service->AddObserver(this);
268 pref_change_registrar_.reset(new PrefChangeRegistrar);
269 pref_change_registrar_->Init(profile_->GetPrefs());
270 pref_change_registrar_->Add(
271 prefs::kIncognitoModeAvailability,
272 base::Bind(&JumpList::OnIncognitoAvailabilityChanged, this));
274 ProfileManager* profile_manager = g_browser_process->profile_manager();
275 avatar_menu_.reset(new AvatarMenu(
276 &profile_manager->GetProfileInfoCache(), this, NULL));
277 if (use_profiles_category_) {
278 avatar_menu_->RebuildMenu();
279 UpdateProfileSwitcher();
283 JumpList::~JumpList() {
284 Terminate();
287 // static
288 bool JumpList::Enabled() {
289 return JumpListUpdater::IsEnabled();
292 void JumpList::Observe(int type,
293 const content::NotificationSource& source,
294 const content::NotificationDetails& details) {
295 DCHECK_EQ(type, chrome::NOTIFICATION_PROFILE_DESTROYED);
296 // Profile was destroyed, do clean-up.
297 Terminate();
300 void JumpList::CancelPendingUpdate() {
301 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
302 cancelable_task_tracker_.TryCancel(task_id_);
303 task_id_ = base::CancelableTaskTracker::kBadTaskId;
307 void JumpList::Terminate() {
308 CancelPendingUpdate();
309 if (profile_) {
310 TabRestoreService* tab_restore_service =
311 TabRestoreServiceFactory::GetForProfile(profile_);
312 if (tab_restore_service)
313 tab_restore_service->RemoveObserver(this);
314 scoped_refptr<history::TopSites> top_sites =
315 TopSitesFactory::GetForProfile(profile_);
316 if (top_sites)
317 top_sites->RemoveObserver(this);
318 registrar_.reset();
319 pref_change_registrar_.reset();
321 profile_ = NULL;
324 void JumpList::OnMostVisitedURLsAvailable(
325 const history::MostVisitedURLList& data) {
326 // If we have a pending favicon request, cancel it here (it is out of date).
327 CancelPendingUpdate();
330 base::AutoLock auto_lock(list_lock_);
331 most_visited_pages_.clear();
332 for (size_t i = 0; i < data.size(); i++) {
333 const history::MostVisitedURL& url = data[i];
334 scoped_refptr<ShellLinkItem> link = CreateShellLink();
335 std::string url_string = url.url.spec();
336 std::wstring url_string_wide = base::UTF8ToWide(url_string);
337 link->GetCommandLine()->AppendArgNative(url_string_wide);
338 link->GetCommandLine()->AppendSwitchASCII(
339 switches::kWinJumplistAction, jumplist::kMostVisitedCategory);
340 link->set_title(!url.title.empty()? url.title : url_string_wide);
341 most_visited_pages_.push_back(link);
342 icon_urls_.push_back(make_pair(url_string, link));
346 // Send a query that retrieves the first favicon.
347 StartLoadingFavicon();
350 void JumpList::TabRestoreServiceChanged(TabRestoreService* service) {
351 // if we have a pending handle request, cancel it here (it is out of date).
352 CancelPendingUpdate();
354 // local list to pass to methods
355 ShellLinkItemList temp_list;
357 // Create a list of ShellLinkItems from the "Recently Closed" pages.
358 // As noted above, we create a ShellLinkItem objects with the following
359 // parameters.
360 // * arguments
361 // The last URL of the tab object.
362 // * title
363 // The title of the last URL.
364 // * icon
365 // An empty string. This value is to be updated in OnFaviconDataAvailable().
366 // This code is copied from
367 // RecentlyClosedTabsHandler::TabRestoreServiceChanged() to emulate it.
368 const int kRecentlyClosedCount = 4;
369 TabRestoreService* tab_restore_service =
370 TabRestoreServiceFactory::GetForProfile(profile_);
371 const TabRestoreService::Entries& entries = tab_restore_service->entries();
372 for (TabRestoreService::Entries::const_iterator it = entries.begin();
373 it != entries.end(); ++it) {
374 const TabRestoreService::Entry* entry = *it;
375 if (entry->type == TabRestoreService::TAB) {
376 AddTab(static_cast<const TabRestoreService::Tab*>(entry),
377 &temp_list, kRecentlyClosedCount);
378 } else if (entry->type == TabRestoreService::WINDOW) {
379 AddWindow(static_cast<const TabRestoreService::Window*>(entry),
380 &temp_list, kRecentlyClosedCount);
383 // Lock recently_closed_pages and copy temp_list into it.
385 base::AutoLock auto_lock(list_lock_);
386 recently_closed_pages_ = temp_list;
389 // Send a query that retrieves the first favicon.
390 StartLoadingFavicon();
393 void JumpList::TabRestoreServiceDestroyed(TabRestoreService* service) {
396 void JumpList::OnAvatarMenuChanged(AvatarMenu* avatar_menu) {
397 if (!use_profiles_category_)
398 return;
400 UpdateProfileSwitcher();
401 PostRunUpdate();
404 bool JumpList::AddTab(const TabRestoreService::Tab* tab,
405 ShellLinkItemList* list,
406 size_t max_items) {
407 // This code adds the URL and the title strings of the given tab to the
408 // specified list.
409 if (list->size() >= max_items)
410 return false;
412 scoped_refptr<ShellLinkItem> link = CreateShellLink();
413 const sessions::SerializedNavigationEntry& current_navigation =
414 tab->navigations.at(tab->current_navigation_index);
415 std::string url = current_navigation.virtual_url().spec();
416 link->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url));
417 link->GetCommandLine()->AppendSwitchASCII(
418 switches::kWinJumplistAction, jumplist::kRecentlyClosedCategory);
419 link->set_title(current_navigation.title());
420 list->push_back(link);
421 icon_urls_.push_back(make_pair(url, link));
422 return true;
425 void JumpList::AddWindow(const TabRestoreService::Window* window,
426 ShellLinkItemList* list,
427 size_t max_items) {
428 // This code enumerates al the tabs in the given window object and add their
429 // URLs and titles to the list.
430 DCHECK(!window->tabs.empty());
432 for (size_t i = 0; i < window->tabs.size(); ++i) {
433 if (!AddTab(&window->tabs[i], list, max_items))
434 return;
438 void JumpList::StartLoadingFavicon() {
439 GURL url;
440 bool waiting_for_icons = true;
442 base::AutoLock auto_lock(list_lock_);
443 waiting_for_icons = !icon_urls_.empty();
444 if (waiting_for_icons) {
445 // Ask FaviconService if it has a favicon of a URL.
446 // When FaviconService has one, it will call OnFaviconDataAvailable().
447 url = GURL(icon_urls_.front().first);
451 if (!waiting_for_icons) {
452 // No more favicons are needed by the application JumpList. Schedule a
453 // RunUpdateOnFileThread call.
454 PostRunUpdate();
455 return;
458 FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
459 profile_, ServiceAccessType::EXPLICIT_ACCESS);
460 task_id_ = favicon_service->GetFaviconImageForPageURL(
461 url,
462 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
463 &cancelable_task_tracker_);
466 void JumpList::OnFaviconDataAvailable(
467 const favicon_base::FaviconImageResult& image_result) {
468 // If there is currently a favicon request in progress, it is now outdated,
469 // as we have received another, so nullify the handle from the old request.
470 task_id_ = base::CancelableTaskTracker::kBadTaskId;
471 // Lock the list to set icon data and pop the url.
473 base::AutoLock auto_lock(list_lock_);
474 // Attach the received data to the ShellLinkItem object.
475 // This data will be decoded by the RunUpdateOnFileThread method.
476 if (!image_result.image.IsEmpty()) {
477 if (!icon_urls_.empty() && icon_urls_.front().second.get())
478 icon_urls_.front().second->set_icon_data(image_result.image.AsBitmap());
481 if (!icon_urls_.empty())
482 icon_urls_.pop_front();
484 // Check whether we need to load more favicons.
485 StartLoadingFavicon();
488 void JumpList::OnIncognitoAvailabilityChanged() {
489 bool waiting_for_icons = true;
491 base::AutoLock auto_lock(list_lock_);
492 waiting_for_icons = !icon_urls_.empty();
494 if (!waiting_for_icons)
495 PostRunUpdate();
496 // If |icon_urls_| isn't empty then OnFaviconDataAvailable will eventually
497 // call PostRunUpdate().
500 void JumpList::PostRunUpdate() {
501 // Check if incognito windows (or normal windows) are disabled by policy.
502 IncognitoModePrefs::Availability incognito_availability =
503 profile_ ? IncognitoModePrefs::GetAvailability(profile_->GetPrefs())
504 : IncognitoModePrefs::ENABLED;
506 BrowserThread::PostTask(
507 BrowserThread::FILE, FROM_HERE,
508 base::Bind(&JumpList::RunUpdateOnFileThread,
509 this,
510 incognito_availability));
513 void JumpList::RunUpdateOnFileThread(
514 IncognitoModePrefs::Availability incognito_availability) {
515 ShellLinkItemList local_most_visited_pages;
516 ShellLinkItemList local_recently_closed_pages;
517 ShellLinkItemList local_profile_switcher;
520 base::AutoLock auto_lock(list_lock_);
521 // Make sure we are not out of date: if icon_urls_ is not empty, then
522 // another notification has been received since we processed this one
523 if (!icon_urls_.empty())
524 return;
526 // Make local copies of lists so we can release the lock.
527 local_most_visited_pages = most_visited_pages_;
528 local_recently_closed_pages = recently_closed_pages_;
529 local_profile_switcher = profile_switcher_;
532 // Delete the directory which contains old icon files, rename the current
533 // icon directory, and create a new directory which contains new JumpList
534 // icon files.
535 base::FilePath icon_dir_old(icon_dir_.value() + L"Old");
536 if (base::PathExists(icon_dir_old))
537 base::DeleteFile(icon_dir_old, true);
538 base::Move(icon_dir_, icon_dir_old);
539 base::CreateDirectory(icon_dir_);
541 // Create temporary icon files for shortcuts in the "Most Visited" category.
542 CreateIconFiles(local_most_visited_pages);
544 // Create temporary icon files for shortcuts in the "Recently Closed"
545 // category.
546 CreateIconFiles(local_recently_closed_pages);
548 // Create temporary icon files for the profile avatars in the "People"
549 // category.
550 if (use_profiles_category_)
551 CreateIconFiles(local_profile_switcher);
553 // We finished collecting all resources needed for updating an application
554 // JumpList. So, create a new JumpList and replace the current JumpList
555 // with it.
556 UpdateJumpList(app_id_.c_str(),
557 local_most_visited_pages,
558 local_recently_closed_pages,
559 local_profile_switcher,
560 incognito_availability,
561 use_profiles_category_);
564 void JumpList::CreateIconFiles(const ShellLinkItemList& item_list) {
565 for (ShellLinkItemList::const_iterator item = item_list.begin();
566 item != item_list.end(); ++item) {
567 base::FilePath icon_path;
568 if (CreateIconFile((*item)->icon_data(), icon_dir_, &icon_path))
569 (*item)->set_icon(icon_path.value(), 0);
573 void JumpList::UpdateProfileSwitcher() {
574 DCHECK(use_profiles_category_);
575 ShellLinkItemList new_profile_switcher;
577 // Don't display a menu in the single profile case.
578 if (avatar_menu_->GetNumberOfItems() > 1) {
579 for (size_t i = 0; i < avatar_menu_->GetNumberOfItems(); ++i) {
580 scoped_refptr<ShellLinkItem> link = CreateShellLink();
581 const AvatarMenu::Item& item = avatar_menu_->GetItemAt(i);
583 link->set_title(item.name);
584 link->GetCommandLine()->AppendSwitchPath(
585 switches::kProfileDirectory, item.profile_path.BaseName());
586 link->GetCommandLine()->AppendSwitch(
587 switches::kActivateExistingProfileBrowser);
588 link->GetCommandLine()->AppendSwitchASCII(
589 switches::kWinJumplistAction, jumplist::kProfilesCategory);
591 gfx::Image avatar;
592 bool is_rectangle;
593 avatar_menu_->GetImageForMenuButton(
594 item.profile_path, &avatar, &is_rectangle);
595 link->set_icon_data(avatar.AsBitmap());
596 new_profile_switcher.push_back(link);
601 base::AutoLock auto_lock(list_lock_);
602 new_profile_switcher.swap(profile_switcher_);
606 void JumpList::TopSitesLoaded(history::TopSites* top_sites) {
609 void JumpList::TopSitesChanged(history::TopSites* top_sites) {
610 top_sites->GetMostVisitedURLs(
611 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
612 weak_ptr_factory_.GetWeakPtr()),
613 false);