Roll src/third_party/WebKit 8b42d1d:744641d (svn 186770:186771)
[chromium-blink-merge.git] / chrome / browser / jumplist_win.cc
blob1eb72f594f41574bbd54ba47ee04b41fa57b670f
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.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/sessions/session_types.h"
38 #include "components/signin/core/common/profile_management_switches.h"
39 #include "content/public/browser/browser_thread.h"
40 #include "content/public/browser/notification_source.h"
41 #include "ui/base/l10n/l10n_util.h"
42 #include "ui/gfx/codec/png_codec.h"
43 #include "ui/gfx/favicon_size.h"
44 #include "ui/gfx/icon_util.h"
45 #include "ui/gfx/image/image_family.h"
46 #include "url/gurl.h"
48 using content::BrowserThread;
50 namespace {
52 // Append the common switches to each shell link.
53 void AppendCommonSwitches(ShellLinkItem* shell_link) {
54 const char* kSwitchNames[] = { switches::kUserDataDir };
55 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
56 shell_link->GetCommandLine()->CopySwitchesFrom(command_line,
57 kSwitchNames,
58 arraysize(kSwitchNames));
61 // Create a ShellLinkItem preloaded with common switches.
62 scoped_refptr<ShellLinkItem> CreateShellLink() {
63 scoped_refptr<ShellLinkItem> link(new ShellLinkItem);
64 AppendCommonSwitches(link.get());
65 return link;
68 // Creates a temporary icon file to be shown in JumpList.
69 bool CreateIconFile(const SkBitmap& bitmap,
70 const base::FilePath& icon_dir,
71 base::FilePath* icon_path) {
72 // Retrieve the path to a temporary file.
73 // We don't have to care about the extension of this temporary file because
74 // JumpList does not care about it.
75 base::FilePath path;
76 if (!base::CreateTemporaryFileInDir(icon_dir, &path))
77 return false;
79 // Create an icon file from the favicon attached to the given |page|, and
80 // save it as the temporary file.
81 gfx::ImageFamily image_family;
82 image_family.Add(gfx::Image::CreateFrom1xBitmap(bitmap));
83 if (!IconUtil::CreateIconFileFromImageFamily(image_family, path))
84 return false;
86 // Add this icon file to the list and return its absolute path.
87 // The IShellLink::SetIcon() function needs the absolute path to an icon.
88 *icon_path = path;
89 return true;
92 // Updates the "Tasks" category of the JumpList.
93 bool UpdateTaskCategory(
94 JumpListUpdater* jumplist_updater,
95 IncognitoModePrefs::Availability incognito_availability) {
96 base::FilePath chrome_path;
97 if (!PathService::Get(base::FILE_EXE, &chrome_path))
98 return false;
100 ShellLinkItemList items;
102 // Create an IShellLink object which launches Chrome, and add it to the
103 // collection. We use our application icon as the icon for this item.
104 // We remove '&' characters from this string so we can share it with our
105 // system menu.
106 if (incognito_availability != IncognitoModePrefs::FORCED) {
107 scoped_refptr<ShellLinkItem> chrome = CreateShellLink();
108 base::string16 chrome_title = l10n_util::GetStringUTF16(IDS_NEW_WINDOW);
109 ReplaceSubstringsAfterOffset(&chrome_title, 0, L"&", L"");
110 chrome->set_title(chrome_title);
111 chrome->set_icon(chrome_path.value(), 0);
112 items.push_back(chrome);
115 // Create an IShellLink object which launches Chrome in incognito mode, and
116 // add it to the collection. We use our application icon as the icon for
117 // this item.
118 if (incognito_availability != IncognitoModePrefs::DISABLED) {
119 scoped_refptr<ShellLinkItem> incognito = CreateShellLink();
120 incognito->GetCommandLine()->AppendSwitch(switches::kIncognito);
121 base::string16 incognito_title =
122 l10n_util::GetStringUTF16(IDS_NEW_INCOGNITO_WINDOW);
123 ReplaceSubstringsAfterOffset(&incognito_title, 0, L"&", L"");
124 incognito->set_title(incognito_title);
125 incognito->set_icon(chrome_path.value(), 0);
126 items.push_back(incognito);
129 return jumplist_updater->AddTasks(items);
132 // Updates the application JumpList.
133 bool UpdateJumpList(const wchar_t* app_id,
134 const ShellLinkItemList& most_visited_pages,
135 const ShellLinkItemList& recently_closed_pages,
136 const ShellLinkItemList& profile_switcher,
137 IncognitoModePrefs::Availability incognito_availability,
138 bool use_profiles_category) {
139 // JumpList is implemented only on Windows 7 or later.
140 // So, we should return now when this function is called on earlier versions
141 // of Windows.
142 if (!JumpListUpdater::IsEnabled())
143 return true;
145 JumpListUpdater jumplist_updater(app_id);
146 if (!jumplist_updater.BeginUpdate())
147 return false;
149 size_t recently_closed_items;
150 size_t profiles_or_most_visited_items;
152 // Depending on the experiment, we are either showing the "Most-Visited" or
153 // "People" categories.
154 if (use_profiles_category) {
155 // Show at most 8 profiles, and fill the rest of the slots with the
156 // "recently-closed" items.
157 const size_t kMaxProfiles = 8;
158 size_t max_displayed_items = std::min(kMaxProfiles,
159 jumplist_updater.user_max_items());
160 profiles_or_most_visited_items = std::min(max_displayed_items,
161 profile_switcher.size());
162 recently_closed_items =
163 jumplist_updater.user_max_items() - profiles_or_most_visited_items;
164 } else {
165 // We allocate 60% of the given JumpList slots to "most-visited" items
166 // and 40% to "recently-closed" items, respectively.
167 // Nevertheless, if there are not so many items in |recently_closed_pages|,
168 // we give the remaining slots to "most-visited" items.
169 const int kMostVisited = 60;
170 const int kRecentlyClosed = 40;
171 const int kTotal = kMostVisited + kRecentlyClosed;
172 profiles_or_most_visited_items =
173 MulDiv(jumplist_updater.user_max_items(), kMostVisited, kTotal);
174 recently_closed_items =
175 jumplist_updater.user_max_items() - profiles_or_most_visited_items;
176 if (recently_closed_pages.size() < recently_closed_items) {
177 profiles_or_most_visited_items +=
178 recently_closed_items - recently_closed_pages.size();
179 recently_closed_items = recently_closed_pages.size();
183 // Update the "Most Visited" category of the JumpList if it exists.
184 // This update request is applied into the JumpList when we commit this
185 // transaction.
186 if (!use_profiles_category && !jumplist_updater.AddCustomCategory(
187 base::UTF16ToWide(
188 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)),
189 most_visited_pages, profiles_or_most_visited_items)) {
190 return false;
193 // Update the "Recently Closed" category of the JumpList.
194 if (!jumplist_updater.AddCustomCategory(
195 base::UTF16ToWide(
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 history::TopSites* top_sites = profile_->GetTopSites();
252 if (top_sites) {
253 // TopSites updates itself after a delay. This is especially noticable when
254 // your profile is empty. Ask TopSites to update itself when jumplist is
255 // initialized.
256 top_sites->SyncWithHistory();
257 registrar_.reset(new content::NotificationRegistrar);
258 // Register for notification when TopSites changes so that we can update
259 // ourself.
260 registrar_->Add(this, chrome::NOTIFICATION_TOP_SITES_CHANGED,
261 content::Source<history::TopSites>(top_sites));
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 avatar_menu_->RebuildMenu();
278 UpdateProfileSwitcher();
281 JumpList::~JumpList() {
282 Terminate();
285 // static
286 bool JumpList::Enabled() {
287 return JumpListUpdater::IsEnabled();
290 void JumpList::Observe(int type,
291 const content::NotificationSource& source,
292 const content::NotificationDetails& details) {
293 switch (type) {
294 case chrome::NOTIFICATION_TOP_SITES_CHANGED: {
295 // Most visited urls changed, query again.
296 history::TopSites* top_sites = profile_->GetTopSites();
297 if (top_sites) {
298 top_sites->GetMostVisitedURLs(
299 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
300 weak_ptr_factory_.GetWeakPtr()), false);
302 break;
304 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
305 // Profile was destroyed, do clean-up.
306 Terminate();
307 break;
309 default:
310 NOTREACHED() << "Unexpected notification type.";
314 void JumpList::CancelPendingUpdate() {
315 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
316 cancelable_task_tracker_.TryCancel(task_id_);
317 task_id_ = base::CancelableTaskTracker::kBadTaskId;
321 void JumpList::Terminate() {
322 CancelPendingUpdate();
323 if (profile_) {
324 TabRestoreService* tab_restore_service =
325 TabRestoreServiceFactory::GetForProfile(profile_);
326 if (tab_restore_service)
327 tab_restore_service->RemoveObserver(this);
328 registrar_.reset();
329 pref_change_registrar_.reset();
331 profile_ = NULL;
334 void JumpList::OnMostVisitedURLsAvailable(
335 const history::MostVisitedURLList& data) {
336 // If we have a pending favicon request, cancel it here (it is out of date).
337 CancelPendingUpdate();
340 base::AutoLock auto_lock(list_lock_);
341 most_visited_pages_.clear();
342 for (size_t i = 0; i < data.size(); i++) {
343 const history::MostVisitedURL& url = data[i];
344 scoped_refptr<ShellLinkItem> link = CreateShellLink();
345 std::string url_string = url.url.spec();
346 std::wstring url_string_wide = base::UTF8ToWide(url_string);
347 link->GetCommandLine()->AppendArgNative(url_string_wide);
348 link->GetCommandLine()->AppendSwitchASCII(
349 switches::kWinJumplistAction, jumplist::kMostVisitedCategory);
350 link->set_title(!url.title.empty()? url.title : url_string_wide);
351 most_visited_pages_.push_back(link);
352 icon_urls_.push_back(make_pair(url_string, link));
356 // Send a query that retrieves the first favicon.
357 StartLoadingFavicon();
360 void JumpList::TabRestoreServiceChanged(TabRestoreService* service) {
361 // if we have a pending handle request, cancel it here (it is out of date).
362 CancelPendingUpdate();
364 // local list to pass to methods
365 ShellLinkItemList temp_list;
367 // Create a list of ShellLinkItems from the "Recently Closed" pages.
368 // As noted above, we create a ShellLinkItem objects with the following
369 // parameters.
370 // * arguments
371 // The last URL of the tab object.
372 // * title
373 // The title of the last URL.
374 // * icon
375 // An empty string. This value is to be updated in OnFaviconDataAvailable().
376 // This code is copied from
377 // RecentlyClosedTabsHandler::TabRestoreServiceChanged() to emulate it.
378 const int kRecentlyClosedCount = 4;
379 TabRestoreService* tab_restore_service =
380 TabRestoreServiceFactory::GetForProfile(profile_);
381 const TabRestoreService::Entries& entries = tab_restore_service->entries();
382 for (TabRestoreService::Entries::const_iterator it = entries.begin();
383 it != entries.end(); ++it) {
384 const TabRestoreService::Entry* entry = *it;
385 if (entry->type == TabRestoreService::TAB) {
386 AddTab(static_cast<const TabRestoreService::Tab*>(entry),
387 &temp_list, kRecentlyClosedCount);
388 } else if (entry->type == TabRestoreService::WINDOW) {
389 AddWindow(static_cast<const TabRestoreService::Window*>(entry),
390 &temp_list, kRecentlyClosedCount);
393 // Lock recently_closed_pages and copy temp_list into it.
395 base::AutoLock auto_lock(list_lock_);
396 recently_closed_pages_ = temp_list;
399 // Send a query that retrieves the first favicon.
400 StartLoadingFavicon();
403 void JumpList::TabRestoreServiceDestroyed(TabRestoreService* service) {
406 void JumpList::OnAvatarMenuChanged(AvatarMenu* avatar_menu) {
407 UpdateProfileSwitcher();
408 PostRunUpdate();
411 bool JumpList::AddTab(const TabRestoreService::Tab* tab,
412 ShellLinkItemList* list,
413 size_t max_items) {
414 // This code adds the URL and the title strings of the given tab to the
415 // specified list.
416 if (list->size() >= max_items)
417 return false;
419 scoped_refptr<ShellLinkItem> link = CreateShellLink();
420 const sessions::SerializedNavigationEntry& current_navigation =
421 tab->navigations.at(tab->current_navigation_index);
422 std::string url = current_navigation.virtual_url().spec();
423 link->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url));
424 link->GetCommandLine()->AppendSwitchASCII(
425 switches::kWinJumplistAction, jumplist::kRecentlyClosedCategory);
426 link->set_title(current_navigation.title());
427 list->push_back(link);
428 icon_urls_.push_back(make_pair(url, link));
429 return true;
432 void JumpList::AddWindow(const TabRestoreService::Window* window,
433 ShellLinkItemList* list,
434 size_t max_items) {
435 // This code enumerates al the tabs in the given window object and add their
436 // URLs and titles to the list.
437 DCHECK(!window->tabs.empty());
439 for (size_t i = 0; i < window->tabs.size(); ++i) {
440 if (!AddTab(&window->tabs[i], list, max_items))
441 return;
445 void JumpList::StartLoadingFavicon() {
446 GURL url;
447 bool waiting_for_icons = true;
449 base::AutoLock auto_lock(list_lock_);
450 waiting_for_icons = !icon_urls_.empty();
451 if (waiting_for_icons) {
452 // Ask FaviconService if it has a favicon of a URL.
453 // When FaviconService has one, it will call OnFaviconDataAvailable().
454 url = GURL(icon_urls_.front().first);
458 if (!waiting_for_icons) {
459 // No more favicons are needed by the application JumpList. Schedule a
460 // RunUpdateOnFileThread call.
461 PostRunUpdate();
462 return;
465 FaviconService* favicon_service =
466 FaviconServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
467 task_id_ = favicon_service->GetFaviconImageForPageURL(
468 url,
469 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
470 &cancelable_task_tracker_);
473 void JumpList::OnFaviconDataAvailable(
474 const favicon_base::FaviconImageResult& image_result) {
475 // If there is currently a favicon request in progress, it is now outdated,
476 // as we have received another, so nullify the handle from the old request.
477 task_id_ = base::CancelableTaskTracker::kBadTaskId;
478 // Lock the list to set icon data and pop the url.
480 base::AutoLock auto_lock(list_lock_);
481 // Attach the received data to the ShellLinkItem object.
482 // This data will be decoded by the RunUpdateOnFileThread method.
483 if (!image_result.image.IsEmpty()) {
484 if (!icon_urls_.empty() && icon_urls_.front().second.get())
485 icon_urls_.front().second->set_icon_data(image_result.image.AsBitmap());
488 if (!icon_urls_.empty())
489 icon_urls_.pop_front();
491 // Check whether we need to load more favicons.
492 StartLoadingFavicon();
495 void JumpList::OnIncognitoAvailabilityChanged() {
496 bool waiting_for_icons = true;
498 base::AutoLock auto_lock(list_lock_);
499 waiting_for_icons = !icon_urls_.empty();
501 if (!waiting_for_icons)
502 PostRunUpdate();
503 // If |icon_urls_| isn't empty then OnFaviconDataAvailable will eventually
504 // call PostRunUpdate().
507 void JumpList::PostRunUpdate() {
508 // Check if incognito windows (or normal windows) are disabled by policy.
509 IncognitoModePrefs::Availability incognito_availability =
510 profile_ ? IncognitoModePrefs::GetAvailability(profile_->GetPrefs())
511 : IncognitoModePrefs::ENABLED;
513 BrowserThread::PostTask(
514 BrowserThread::FILE, FROM_HERE,
515 base::Bind(&JumpList::RunUpdateOnFileThread,
516 this,
517 incognito_availability));
520 void JumpList::RunUpdateOnFileThread(
521 IncognitoModePrefs::Availability incognito_availability) {
522 ShellLinkItemList local_most_visited_pages;
523 ShellLinkItemList local_recently_closed_pages;
524 ShellLinkItemList local_profile_switcher;
527 base::AutoLock auto_lock(list_lock_);
528 // Make sure we are not out of date: if icon_urls_ is not empty, then
529 // another notification has been received since we processed this one
530 if (!icon_urls_.empty())
531 return;
533 // Make local copies of lists so we can release the lock.
534 local_most_visited_pages = most_visited_pages_;
535 local_recently_closed_pages = recently_closed_pages_;
536 local_profile_switcher = profile_switcher_;
539 // Delete the directory which contains old icon files, rename the current
540 // icon directory, and create a new directory which contains new JumpList
541 // icon files.
542 base::FilePath icon_dir_old(icon_dir_.value() + L"Old");
543 if (base::PathExists(icon_dir_old))
544 base::DeleteFile(icon_dir_old, true);
545 base::Move(icon_dir_, icon_dir_old);
546 base::CreateDirectory(icon_dir_);
548 // Create temporary icon files for shortcuts in the "Most Visited" category.
549 CreateIconFiles(local_most_visited_pages);
551 // Create temporary icon files for shortcuts in the "Recently Closed"
552 // category.
553 CreateIconFiles(local_recently_closed_pages);
555 // Create temporary icon files for the profile avatars in the "People"
556 // category.
557 CreateIconFiles(local_profile_switcher);
559 // We finished collecting all resources needed for updating an application
560 // JumpList. So, create a new JumpList and replace the current JumpList
561 // with it.
562 UpdateJumpList(app_id_.c_str(),
563 local_most_visited_pages,
564 local_recently_closed_pages,
565 local_profile_switcher,
566 incognito_availability,
567 use_profiles_category_);
570 void JumpList::CreateIconFiles(const ShellLinkItemList& item_list) {
571 for (ShellLinkItemList::const_iterator item = item_list.begin();
572 item != item_list.end(); ++item) {
573 base::FilePath icon_path;
574 if (CreateIconFile((*item)->icon_data(), icon_dir_, &icon_path))
575 (*item)->set_icon(icon_path.value(), 0);
579 void JumpList::UpdateProfileSwitcher() {
580 ShellLinkItemList new_profile_switcher;
582 // Don't display a menu in the single profile case.
583 if (avatar_menu_->GetNumberOfItems() > 1) {
584 for (size_t i = 0; i < avatar_menu_->GetNumberOfItems(); ++i) {
585 scoped_refptr<ShellLinkItem> link = CreateShellLink();
586 const AvatarMenu::Item& item = avatar_menu_->GetItemAt(i);
588 link->set_title(item.name);
589 link->GetCommandLine()->AppendSwitchPath(
590 switches::kProfileDirectory, item.profile_path.BaseName());
591 link->GetCommandLine()->AppendSwitch(
592 switches::kActivateExistingProfileBrowser);
593 link->GetCommandLine()->AppendSwitchASCII(
594 switches::kWinJumplistAction, jumplist::kProfilesCategory);
596 gfx::Image avatar;
597 bool is_rectangle;
598 avatar_menu_->GetImageForMenuButton(
599 item.profile_path, &avatar, &is_rectangle);
600 link->set_icon_data(avatar.AsBitmap());
601 new_profile_switcher.push_back(link);
606 base::AutoLock auto_lock(list_lock_);
607 new_profile_switcher.swap(profile_switcher_);