Roll src/third_party/WebKit 1cd8cc5:4e01097 (svn 202507:202508)
[chromium-blink-merge.git] / chrome / browser / jumplist_win.cc
blob52cf7dd364a32ab92e83dd748465c08953bdd1e4
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/path_service.h"
12 #include "base/prefs/pref_change_registrar.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/threading/thread.h"
16 #include "base/trace_event/trace_event.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/favicon/favicon_service_factory.h"
19 #include "chrome/browser/history/top_sites_factory.h"
20 #include "chrome/browser/metrics/jumplist_metrics_win.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/sessions/tab_restore_service.h"
23 #include "chrome/browser/sessions/tab_restore_service_factory.h"
24 #include "chrome/browser/shell_integration.h"
25 #include "chrome/common/chrome_constants.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/common/url_constants.h"
29 #include "chrome/grit/generated_resources.h"
30 #include "components/favicon/core/favicon_service.h"
31 #include "components/favicon_base/favicon_types.h"
32 #include "components/history/core/browser/history_service.h"
33 #include "components/history/core/browser/page_usage_data.h"
34 #include "components/history/core/browser/top_sites.h"
35 #include "components/sessions/session_types.h"
36 #include "content/public/browser/browser_thread.h"
37 #include "content/public/browser/notification_registrar.h"
38 #include "content/public/browser/notification_source.h"
39 #include "ui/base/l10n/l10n_util.h"
40 #include "ui/gfx/codec/png_codec.h"
41 #include "ui/gfx/favicon_size.h"
42 #include "ui/gfx/icon_util.h"
43 #include "ui/gfx/image/image_family.h"
44 #include "url/gurl.h"
46 using content::BrowserThread;
48 namespace {
50 // Delay jumplist updates to allow collapsing of redundant update requests.
51 const int kDelayForJumplistUpdateInMS = 3500;
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 base::ReplaceSubstringsAfterOffset(
112 &chrome_title, 0, L"&", base::StringPiece16());
113 chrome->set_title(chrome_title);
114 chrome->set_icon(chrome_path.value(), 0);
115 items.push_back(chrome);
118 // Create an IShellLink object which launches Chrome in incognito mode, and
119 // add it to the collection. We use our application icon as the icon for
120 // this item.
121 if (incognito_availability != IncognitoModePrefs::DISABLED) {
122 scoped_refptr<ShellLinkItem> incognito = CreateShellLink();
123 incognito->GetCommandLine()->AppendSwitch(switches::kIncognito);
124 base::string16 incognito_title =
125 l10n_util::GetStringUTF16(IDS_NEW_INCOGNITO_WINDOW);
126 base::ReplaceSubstringsAfterOffset(
127 &incognito_title, 0, L"&", base::StringPiece16());
128 incognito->set_title(incognito_title);
129 incognito->set_icon(chrome_path.value(), 0);
130 items.push_back(incognito);
133 return jumplist_updater->AddTasks(items);
136 // Updates the application JumpList.
137 bool UpdateJumpList(const wchar_t* app_id,
138 const ShellLinkItemList& most_visited_pages,
139 const ShellLinkItemList& recently_closed_pages,
140 IncognitoModePrefs::Availability incognito_availability) {
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 // We allocate 60% of the given JumpList slots to "most-visited" items
152 // and 40% to "recently-closed" items, respectively.
153 // Nevertheless, if there are not so many items in |recently_closed_pages|,
154 // we give the remaining slots to "most-visited" items.
155 const int kMostVisited = 60;
156 const int kRecentlyClosed = 40;
157 const int kTotal = kMostVisited + kRecentlyClosed;
158 size_t most_visited_items =
159 MulDiv(jumplist_updater.user_max_items(), kMostVisited, kTotal);
160 size_t recently_closed_items =
161 jumplist_updater.user_max_items() - most_visited_items;
162 if (recently_closed_pages.size() < recently_closed_items) {
163 most_visited_items += recently_closed_items - recently_closed_pages.size();
164 recently_closed_items = recently_closed_pages.size();
167 // Update the "Most Visited" category of the JumpList if it exists.
168 // This update request is applied into the JumpList when we commit this
169 // transaction.
170 if (!jumplist_updater.AddCustomCategory(
171 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED),
172 most_visited_pages, most_visited_items)) {
173 return false;
176 // Update the "Recently Closed" category of the JumpList.
177 if (!jumplist_updater.AddCustomCategory(
178 l10n_util::GetStringUTF16(IDS_RECENTLY_CLOSED),
179 recently_closed_pages, recently_closed_items)) {
180 return false;
183 // Update the "Tasks" category of the JumpList.
184 if (!UpdateTaskCategory(&jumplist_updater, incognito_availability))
185 return false;
187 // Commit this transaction and send the updated JumpList to Windows.
188 if (!jumplist_updater.CommitUpdate())
189 return false;
191 return true;
194 } // namespace
196 JumpList::JumpList(Profile* profile)
197 : profile_(profile),
198 task_id_(base::CancelableTaskTracker::kBadTaskId),
199 weak_ptr_factory_(this) {
200 DCHECK(Enabled());
201 // To update JumpList when a tab is added or removed, we add this object to
202 // the observer list of the TabRestoreService class.
203 // When we add this object to the observer list, we save the pointer to this
204 // TabRestoreService object. This pointer is used when we remove this object
205 // from the observer list.
206 TabRestoreService* tab_restore_service =
207 TabRestoreServiceFactory::GetForProfile(profile_);
208 if (!tab_restore_service)
209 return;
211 app_id_ = ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath());
212 icon_dir_ = profile_->GetPath().Append(chrome::kJumpListIconDirname);
214 scoped_refptr<history::TopSites> top_sites =
215 TopSitesFactory::GetForProfile(profile_);
216 if (top_sites) {
217 // TopSites updates itself after a delay. This is especially noticable when
218 // your profile is empty. Ask TopSites to update itself when jumplist is
219 // initialized.
220 top_sites->SyncWithHistory();
221 registrar_.reset(new content::NotificationRegistrar);
222 // Register as TopSitesObserver so that we can update ourselves when the
223 // TopSites changes.
224 top_sites->AddObserver(this);
225 // Register for notification when profile is destroyed to ensure that all
226 // observers are detatched at that time.
227 registrar_->Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
228 content::Source<Profile>(profile_));
230 tab_restore_service->AddObserver(this);
231 pref_change_registrar_.reset(new PrefChangeRegistrar);
232 pref_change_registrar_->Init(profile_->GetPrefs());
233 pref_change_registrar_->Add(
234 prefs::kIncognitoModeAvailability,
235 base::Bind(&JumpList::OnIncognitoAvailabilityChanged, this));
238 JumpList::~JumpList() {
239 Terminate();
242 // static
243 bool JumpList::Enabled() {
244 return JumpListUpdater::IsEnabled();
247 void JumpList::Observe(int type,
248 const content::NotificationSource& source,
249 const content::NotificationDetails& details) {
250 DCHECK_EQ(type, chrome::NOTIFICATION_PROFILE_DESTROYED);
251 // Profile was destroyed, do clean-up.
252 Terminate();
255 void JumpList::CancelPendingUpdate() {
256 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
257 cancelable_task_tracker_.TryCancel(task_id_);
258 task_id_ = base::CancelableTaskTracker::kBadTaskId;
262 void JumpList::Terminate() {
263 CancelPendingUpdate();
264 if (profile_) {
265 TabRestoreService* tab_restore_service =
266 TabRestoreServiceFactory::GetForProfile(profile_);
267 if (tab_restore_service)
268 tab_restore_service->RemoveObserver(this);
269 scoped_refptr<history::TopSites> top_sites =
270 TopSitesFactory::GetForProfile(profile_);
271 if (top_sites)
272 top_sites->RemoveObserver(this);
273 registrar_.reset();
274 pref_change_registrar_.reset();
276 profile_ = NULL;
279 void JumpList::OnMostVisitedURLsAvailable(
280 const history::MostVisitedURLList& data) {
281 // If we have a pending favicon request, cancel it here (it is out of date).
282 CancelPendingUpdate();
285 base::AutoLock auto_lock(list_lock_);
286 most_visited_pages_.clear();
287 for (size_t i = 0; i < data.size(); i++) {
288 const history::MostVisitedURL& url = data[i];
289 scoped_refptr<ShellLinkItem> link = CreateShellLink();
290 std::string url_string = url.url.spec();
291 std::wstring url_string_wide = base::UTF8ToWide(url_string);
292 link->GetCommandLine()->AppendArgNative(url_string_wide);
293 link->GetCommandLine()->AppendSwitchASCII(
294 switches::kWinJumplistAction, jumplist::kMostVisitedCategory);
295 link->set_title(!url.title.empty()? url.title : url_string_wide);
296 most_visited_pages_.push_back(link);
297 icon_urls_.push_back(make_pair(url_string, link));
301 // Send a query that retrieves the first favicon.
302 StartLoadingFavicon();
305 void JumpList::TabRestoreServiceChanged(TabRestoreService* service) {
306 // if we have a pending handle request, cancel it here (it is out of date).
307 CancelPendingUpdate();
309 // local list to pass to methods
310 ShellLinkItemList temp_list;
312 // Create a list of ShellLinkItems from the "Recently Closed" pages.
313 // As noted above, we create a ShellLinkItem objects with the following
314 // parameters.
315 // * arguments
316 // The last URL of the tab object.
317 // * title
318 // The title of the last URL.
319 // * icon
320 // An empty string. This value is to be updated in OnFaviconDataAvailable().
321 // This code is copied from
322 // RecentlyClosedTabsHandler::TabRestoreServiceChanged() to emulate it.
323 const int kRecentlyClosedCount = 4;
324 TabRestoreService* tab_restore_service =
325 TabRestoreServiceFactory::GetForProfile(profile_);
326 const TabRestoreService::Entries& entries = tab_restore_service->entries();
327 for (TabRestoreService::Entries::const_iterator it = entries.begin();
328 it != entries.end(); ++it) {
329 const TabRestoreService::Entry* entry = *it;
330 if (entry->type == TabRestoreService::TAB) {
331 AddTab(static_cast<const TabRestoreService::Tab*>(entry),
332 &temp_list, kRecentlyClosedCount);
333 } else if (entry->type == TabRestoreService::WINDOW) {
334 AddWindow(static_cast<const TabRestoreService::Window*>(entry),
335 &temp_list, kRecentlyClosedCount);
338 // Lock recently_closed_pages and copy temp_list into it.
340 base::AutoLock auto_lock(list_lock_);
341 recently_closed_pages_ = temp_list;
344 // Send a query that retrieves the first favicon.
345 StartLoadingFavicon();
348 void JumpList::TabRestoreServiceDestroyed(TabRestoreService* service) {
351 bool JumpList::AddTab(const TabRestoreService::Tab* tab,
352 ShellLinkItemList* list,
353 size_t max_items) {
354 // This code adds the URL and the title strings of the given tab to the
355 // specified list.
356 if (list->size() >= max_items)
357 return false;
359 scoped_refptr<ShellLinkItem> link = CreateShellLink();
360 const sessions::SerializedNavigationEntry& current_navigation =
361 tab->navigations.at(tab->current_navigation_index);
362 std::string url = current_navigation.virtual_url().spec();
363 link->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url));
364 link->GetCommandLine()->AppendSwitchASCII(
365 switches::kWinJumplistAction, jumplist::kRecentlyClosedCategory);
366 link->set_title(current_navigation.title());
367 list->push_back(link);
368 icon_urls_.push_back(make_pair(url, link));
369 return true;
372 void JumpList::AddWindow(const TabRestoreService::Window* window,
373 ShellLinkItemList* list,
374 size_t max_items) {
375 // This code enumerates al the tabs in the given window object and add their
376 // URLs and titles to the list.
377 DCHECK(!window->tabs.empty());
379 for (size_t i = 0; i < window->tabs.size(); ++i) {
380 if (!AddTab(&window->tabs[i], list, max_items))
381 return;
385 void JumpList::StartLoadingFavicon() {
386 GURL url;
387 bool waiting_for_icons = true;
389 base::AutoLock auto_lock(list_lock_);
390 waiting_for_icons = !icon_urls_.empty();
391 if (waiting_for_icons) {
392 // Ask FaviconService if it has a favicon of a URL.
393 // When FaviconService has one, it will call OnFaviconDataAvailable().
394 url = GURL(icon_urls_.front().first);
398 if (!waiting_for_icons) {
399 // No more favicons are needed by the application JumpList. Schedule a
400 // RunUpdateOnFileThread call.
401 PostRunUpdate();
402 return;
405 favicon::FaviconService* favicon_service =
406 FaviconServiceFactory::GetForProfile(profile_,
407 ServiceAccessType::EXPLICIT_ACCESS);
408 task_id_ = favicon_service->GetFaviconImageForPageURL(
409 url,
410 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
411 &cancelable_task_tracker_);
414 void JumpList::OnFaviconDataAvailable(
415 const favicon_base::FaviconImageResult& image_result) {
416 // If there is currently a favicon request in progress, it is now outdated,
417 // as we have received another, so nullify the handle from the old request.
418 task_id_ = base::CancelableTaskTracker::kBadTaskId;
419 // Lock the list to set icon data and pop the url.
421 base::AutoLock auto_lock(list_lock_);
422 // Attach the received data to the ShellLinkItem object.
423 // This data will be decoded by the RunUpdateOnFileThread method.
424 if (!image_result.image.IsEmpty()) {
425 if (!icon_urls_.empty() && icon_urls_.front().second.get())
426 icon_urls_.front().second->set_icon_data(image_result.image.AsBitmap());
429 if (!icon_urls_.empty())
430 icon_urls_.pop_front();
432 // Check whether we need to load more favicons.
433 StartLoadingFavicon();
436 void JumpList::OnIncognitoAvailabilityChanged() {
437 bool waiting_for_icons = true;
439 base::AutoLock auto_lock(list_lock_);
440 waiting_for_icons = !icon_urls_.empty();
442 if (!waiting_for_icons)
443 PostRunUpdate();
444 // If |icon_urls_| isn't empty then OnFaviconDataAvailable will eventually
445 // call PostRunUpdate().
448 void JumpList::PostRunUpdate() {
449 TRACE_EVENT0("browser", "JumpList::PostRunUpdate");
450 // Initialize the one-shot timer to update the jumplists in a while.
451 // If there is already a request queued then cancel it and post the new
452 // request. This ensures that JumpListUpdates won't happen until there has
453 // been a brief quiet period, thus avoiding update storms.
454 if (timer_.IsRunning()) {
455 timer_.Reset();
456 } else {
457 timer_.Start(FROM_HERE,
458 base::TimeDelta::FromMilliseconds(kDelayForJumplistUpdateInMS),
459 this,
460 &JumpList::DeferredRunUpdate);
464 void JumpList::DeferredRunUpdate() {
465 TRACE_EVENT0("browser", "JumpList::DeferredRunUpdate");
466 // Check if incognito windows (or normal windows) are disabled by policy.
467 IncognitoModePrefs::Availability incognito_availability =
468 profile_ ? IncognitoModePrefs::GetAvailability(profile_->GetPrefs())
469 : IncognitoModePrefs::ENABLED;
471 BrowserThread::PostTask(
472 BrowserThread::FILE, FROM_HERE,
473 base::Bind(&JumpList::RunUpdateOnFileThread,
474 this,
475 incognito_availability));
478 void JumpList::RunUpdateOnFileThread(
479 IncognitoModePrefs::Availability incognito_availability) {
480 ShellLinkItemList local_most_visited_pages;
481 ShellLinkItemList local_recently_closed_pages;
484 base::AutoLock auto_lock(list_lock_);
485 // Make sure we are not out of date: if icon_urls_ is not empty, then
486 // another notification has been received since we processed this one
487 if (!icon_urls_.empty())
488 return;
490 // Make local copies of lists so we can release the lock.
491 local_most_visited_pages = most_visited_pages_;
492 local_recently_closed_pages = recently_closed_pages_;
495 // Delete the directory which contains old icon files, rename the current
496 // icon directory, and create a new directory which contains new JumpList
497 // icon files.
498 base::FilePath icon_dir_old(icon_dir_.value() + L"Old");
499 if (base::PathExists(icon_dir_old))
500 base::DeleteFile(icon_dir_old, true);
501 base::Move(icon_dir_, icon_dir_old);
502 base::CreateDirectory(icon_dir_);
504 // Create temporary icon files for shortcuts in the "Most Visited" category.
505 CreateIconFiles(local_most_visited_pages);
507 // Create temporary icon files for shortcuts in the "Recently Closed"
508 // category.
509 CreateIconFiles(local_recently_closed_pages);
511 // We finished collecting all resources needed for updating an application
512 // JumpList. So, create a new JumpList and replace the current JumpList
513 // with it.
514 UpdateJumpList(app_id_.c_str(),
515 local_most_visited_pages,
516 local_recently_closed_pages,
517 incognito_availability);
520 void JumpList::CreateIconFiles(const ShellLinkItemList& item_list) {
521 for (ShellLinkItemList::const_iterator item = item_list.begin();
522 item != item_list.end(); ++item) {
523 base::FilePath icon_path;
524 if (CreateIconFile((*item)->icon_data(), icon_dir_, &icon_path))
525 (*item)->set_icon(icon_path.value(), 0);
529 void JumpList::TopSitesLoaded(history::TopSites* top_sites) {
532 void JumpList::TopSitesChanged(history::TopSites* top_sites,
533 ChangeReason change_reason) {
534 top_sites->GetMostVisitedURLs(
535 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
536 weak_ptr_factory_.GetWeakPtr()),
537 false);