Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / chrome / browser / jumplist_win.cc
bloba0881e7c1c3d30ad92dfca44f4e6c6f5a13367d4
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 #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/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/threading/thread.h"
15 #include "chrome/browser/chrome_notification_types.h"
16 #include "chrome/browser/favicon/favicon_service.h"
17 #include "chrome/browser/favicon/favicon_service_factory.h"
18 #include "chrome/browser/history/history_service.h"
19 #include "chrome/browser/history/top_sites.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/sessions/session_types.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/url_constants.h"
28 #include "chrome/grit/generated_resources.h"
29 #include "components/favicon_base/favicon_types.h"
30 #include "components/history/core/browser/page_usage_data.h"
31 #include "content/public/browser/browser_thread.h"
32 #include "content/public/browser/notification_source.h"
33 #include "ui/base/l10n/l10n_util.h"
34 #include "ui/gfx/codec/png_codec.h"
35 #include "ui/gfx/favicon_size.h"
36 #include "ui/gfx/icon_util.h"
37 #include "ui/gfx/image/image_family.h"
38 #include "url/gurl.h"
40 using content::BrowserThread;
42 namespace {
44 // Append the common switches to each shell link.
45 void AppendCommonSwitches(ShellLinkItem* shell_link) {
46 const char* kSwitchNames[] = { switches::kUserDataDir };
47 const CommandLine& command_line = *CommandLine::ForCurrentProcess();
48 shell_link->GetCommandLine()->CopySwitchesFrom(command_line,
49 kSwitchNames,
50 arraysize(kSwitchNames));
53 // Create a ShellLinkItem preloaded with common switches.
54 scoped_refptr<ShellLinkItem> CreateShellLink() {
55 scoped_refptr<ShellLinkItem> link(new ShellLinkItem);
56 AppendCommonSwitches(link.get());
57 return link;
60 // Creates a temporary icon file to be shown in JumpList.
61 bool CreateIconFile(const SkBitmap& bitmap,
62 const base::FilePath& icon_dir,
63 base::FilePath* icon_path) {
64 // Retrieve the path to a temporary file.
65 // We don't have to care about the extension of this temporary file because
66 // JumpList does not care about it.
67 base::FilePath path;
68 if (!base::CreateTemporaryFileInDir(icon_dir, &path))
69 return false;
71 // Create an icon file from the favicon attached to the given |page|, and
72 // save it as the temporary file.
73 gfx::ImageFamily image_family;
74 image_family.Add(gfx::Image::CreateFrom1xBitmap(bitmap));
75 if (!IconUtil::CreateIconFileFromImageFamily(image_family, path))
76 return false;
78 // Add this icon file to the list and return its absolute path.
79 // The IShellLink::SetIcon() function needs the absolute path to an icon.
80 *icon_path = path;
81 return true;
84 // Updates the "Tasks" category of the JumpList.
85 bool UpdateTaskCategory(JumpListUpdater* jumplist_updater) {
86 base::FilePath chrome_path;
87 if (!PathService::Get(base::FILE_EXE, &chrome_path))
88 return false;
90 ShellLinkItemList items;
92 // Create an IShellLink object which launches Chrome, and add it to the
93 // collection. We use our application icon as the icon for this item.
94 // We remove '&' characters from this string so we can share it with our
95 // system menu.
96 scoped_refptr<ShellLinkItem> chrome = CreateShellLink();
97 base::string16 chrome_title = l10n_util::GetStringUTF16(IDS_NEW_WINDOW);
98 ReplaceSubstringsAfterOffset(&chrome_title, 0, L"&", L"");
99 chrome->set_title(chrome_title);
100 chrome->set_icon(chrome_path.value(), 0);
101 items.push_back(chrome);
103 // Create an IShellLink object which launches Chrome in incognito mode, and
104 // add it to the collection. We use our application icon as the icon for
105 // this item.
106 scoped_refptr<ShellLinkItem> incognito = CreateShellLink();
107 incognito->GetCommandLine()->AppendSwitch(switches::kIncognito);
108 base::string16 incognito_title =
109 l10n_util::GetStringUTF16(IDS_NEW_INCOGNITO_WINDOW);
110 ReplaceSubstringsAfterOffset(&incognito_title, 0, L"&", L"");
111 incognito->set_title(incognito_title);
112 incognito->set_icon(chrome_path.value(), 0);
113 items.push_back(incognito);
115 return jumplist_updater->AddTasks(items);
118 // Updates the application JumpList.
119 bool UpdateJumpList(const wchar_t* app_id,
120 const ShellLinkItemList& most_visited_pages,
121 const ShellLinkItemList& recently_closed_pages) {
122 // JumpList is implemented only on Windows 7 or later.
123 // So, we should return now when this function is called on earlier versions
124 // of Windows.
125 if (!JumpListUpdater::IsEnabled())
126 return true;
128 JumpListUpdater jumplist_updater(app_id);
129 if (!jumplist_updater.BeginUpdate())
130 return false;
132 // We allocate 60% of the given JumpList slots to "most-visited" items
133 // and 40% to "recently-closed" items, respectively.
134 // Nevertheless, if there are not so many items in |recently_closed_pages|,
135 // we give the remaining slots to "most-visited" items.
136 const int kMostVisited = 60;
137 const int kRecentlyClosed = 40;
138 const int kTotal = kMostVisited + kRecentlyClosed;
139 size_t most_visited_items =
140 MulDiv(jumplist_updater.user_max_items(), kMostVisited, kTotal);
141 size_t recently_closed_items =
142 jumplist_updater.user_max_items() - most_visited_items;
143 if (recently_closed_pages.size() < recently_closed_items) {
144 most_visited_items += recently_closed_items - recently_closed_pages.size();
145 recently_closed_items = recently_closed_pages.size();
148 // Update the "Most Visited" category of the JumpList.
149 // This update request is applied into the JumpList when we commit this
150 // transaction.
151 if (!jumplist_updater.AddCustomCategory(
152 base::UTF16ToWide(
153 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED)),
154 most_visited_pages, most_visited_items)) {
155 return false;
158 // Update the "Recently Closed" category of the JumpList.
159 if (!jumplist_updater.AddCustomCategory(
160 base::UTF16ToWide(
161 l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)),
162 recently_closed_pages, recently_closed_items)) {
163 return false;
166 // Update the "Tasks" category of the JumpList.
167 if (!UpdateTaskCategory(&jumplist_updater))
168 return false;
170 // Commit this transaction and send the updated JumpList to Windows.
171 if (!jumplist_updater.CommitUpdate())
172 return false;
174 return true;
177 } // namespace
179 JumpList::JumpList()
180 : weak_ptr_factory_(this),
181 profile_(NULL),
182 task_id_(base::CancelableTaskTracker::kBadTaskId) {}
184 JumpList::~JumpList() {
185 Terminate();
188 // static
189 bool JumpList::Enabled() {
190 return JumpListUpdater::IsEnabled();
193 bool JumpList::AddObserver(Profile* profile) {
194 // To update JumpList when a tab is added or removed, we add this object to
195 // the observer list of the TabRestoreService class.
196 // When we add this object to the observer list, we save the pointer to this
197 // TabRestoreService object. This pointer is used when we remove this object
198 // from the observer list.
199 if (!JumpListUpdater::IsEnabled() || !profile)
200 return false;
202 TabRestoreService* tab_restore_service =
203 TabRestoreServiceFactory::GetForProfile(profile);
204 if (!tab_restore_service)
205 return false;
207 app_id_ = ShellIntegration::GetChromiumModelIdForProfile(profile->GetPath());
208 icon_dir_ = profile->GetPath().Append(chrome::kJumpListIconDirname);
209 profile_ = profile;
210 history::TopSites* top_sites = profile_->GetTopSites();
211 if (top_sites) {
212 // TopSites updates itself after a delay. This is especially noticable when
213 // your profile is empty. Ask TopSites to update itself when jumplist is
214 // initialized.
215 top_sites->SyncWithHistory();
216 registrar_.reset(new content::NotificationRegistrar);
217 // Register for notification when TopSites changes so that we can update
218 // ourself.
219 registrar_->Add(this, chrome::NOTIFICATION_TOP_SITES_CHANGED,
220 content::Source<history::TopSites>(top_sites));
221 // Register for notification when profile is destroyed to ensure that all
222 // observers are detatched at that time.
223 registrar_->Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
224 content::Source<Profile>(profile_));
226 tab_restore_service->AddObserver(this);
227 return true;
230 void JumpList::Observe(int type,
231 const content::NotificationSource& source,
232 const content::NotificationDetails& details) {
233 switch (type) {
234 case chrome::NOTIFICATION_TOP_SITES_CHANGED: {
235 // Most visited urls changed, query again.
236 history::TopSites* top_sites = profile_->GetTopSites();
237 if (top_sites) {
238 top_sites->GetMostVisitedURLs(
239 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
240 weak_ptr_factory_.GetWeakPtr()), false);
242 break;
244 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
245 // Profile was destroyed, do clean-up.
246 Terminate();
247 break;
249 default:
250 NOTREACHED() << "Unexpected notification type.";
254 void JumpList::RemoveObserver() {
255 if (profile_) {
256 TabRestoreService* tab_restore_service =
257 TabRestoreServiceFactory::GetForProfile(profile_);
258 if (tab_restore_service)
259 tab_restore_service->RemoveObserver(this);
260 registrar_.reset();
262 profile_ = NULL;
265 void JumpList::CancelPendingUpdate() {
266 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
267 cancelable_task_tracker_.TryCancel(task_id_);
268 task_id_ = base::CancelableTaskTracker::kBadTaskId;
272 void JumpList::Terminate() {
273 CancelPendingUpdate();
274 RemoveObserver();
277 void JumpList::OnMostVisitedURLsAvailable(
278 const history::MostVisitedURLList& data) {
280 // If we have a pending favicon request, cancel it here (it is out of date).
281 CancelPendingUpdate();
284 base::AutoLock auto_lock(list_lock_);
285 most_visited_pages_.clear();
286 for (size_t i = 0; i < data.size(); i++) {
287 const history::MostVisitedURL& url = data[i];
288 scoped_refptr<ShellLinkItem> link = CreateShellLink();
289 std::string url_string = url.url.spec();
290 std::wstring url_string_wide = base::UTF8ToWide(url_string);
291 link->GetCommandLine()->AppendArgNative(url_string_wide);
292 link->set_title(!url.title.empty()? url.title : url_string_wide);
293 most_visited_pages_.push_back(link);
294 icon_urls_.push_back(make_pair(url_string, link));
298 // Send a query that retrieves the first favicon.
299 StartLoadingFavicon();
302 void JumpList::TabRestoreServiceChanged(TabRestoreService* service) {
303 // if we have a pending handle request, cancel it here (it is out of date).
304 CancelPendingUpdate();
306 // local list to pass to methods
307 ShellLinkItemList temp_list;
309 // Create a list of ShellLinkItems from the "Recently Closed" pages.
310 // As noted above, we create a ShellLinkItem objects with the following
311 // parameters.
312 // * arguments
313 // The last URL of the tab object.
314 // * title
315 // The title of the last URL.
316 // * icon
317 // An empty string. This value is to be updated in OnFaviconDataAvailable().
318 // This code is copied from
319 // RecentlyClosedTabsHandler::TabRestoreServiceChanged() to emulate it.
320 const int kRecentlyClosedCount = 4;
321 TabRestoreService* tab_restore_service =
322 TabRestoreServiceFactory::GetForProfile(profile_);
323 const TabRestoreService::Entries& entries = tab_restore_service->entries();
324 for (TabRestoreService::Entries::const_iterator it = entries.begin();
325 it != entries.end(); ++it) {
326 const TabRestoreService::Entry* entry = *it;
327 if (entry->type == TabRestoreService::TAB) {
328 AddTab(static_cast<const TabRestoreService::Tab*>(entry),
329 &temp_list, kRecentlyClosedCount);
330 } else if (entry->type == TabRestoreService::WINDOW) {
331 AddWindow(static_cast<const TabRestoreService::Window*>(entry),
332 &temp_list, kRecentlyClosedCount);
335 // Lock recently_closed_pages and copy temp_list into it.
337 base::AutoLock auto_lock(list_lock_);
338 recently_closed_pages_ = temp_list;
341 // Send a query that retrieves the first favicon.
342 StartLoadingFavicon();
345 void JumpList::TabRestoreServiceDestroyed(TabRestoreService* service) {
348 bool JumpList::AddTab(const TabRestoreService::Tab* tab,
349 ShellLinkItemList* list,
350 size_t max_items) {
351 // This code adds the URL and the title strings of the given tab to the
352 // specified list.
353 if (list->size() >= max_items)
354 return false;
356 scoped_refptr<ShellLinkItem> link = CreateShellLink();
357 const sessions::SerializedNavigationEntry& current_navigation =
358 tab->navigations.at(tab->current_navigation_index);
359 std::string url = current_navigation.virtual_url().spec();
360 link->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url));
361 link->set_title(current_navigation.title());
362 list->push_back(link);
363 icon_urls_.push_back(make_pair(url, link));
364 return true;
367 void JumpList::AddWindow(const TabRestoreService::Window* window,
368 ShellLinkItemList* list,
369 size_t max_items) {
370 // This code enumerates al the tabs in the given window object and add their
371 // URLs and titles to the list.
372 DCHECK(!window->tabs.empty());
374 for (size_t i = 0; i < window->tabs.size(); ++i) {
375 if (!AddTab(&window->tabs[i], list, max_items))
376 return;
380 void JumpList::StartLoadingFavicon() {
381 GURL url;
383 base::AutoLock auto_lock(list_lock_);
384 if (icon_urls_.empty()) {
385 // No more favicons are needed by the application JumpList. Schedule a
386 // RunUpdate call.
387 BrowserThread::PostTask(
388 BrowserThread::FILE, FROM_HERE,
389 base::Bind(&JumpList::RunUpdate, this));
390 return;
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);
396 FaviconService* favicon_service =
397 FaviconServiceFactory::GetForProfile(profile_, Profile::EXPLICIT_ACCESS);
398 task_id_ = favicon_service->GetFaviconImageForPageURL(
399 url,
400 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
401 &cancelable_task_tracker_);
404 void JumpList::OnFaviconDataAvailable(
405 const favicon_base::FaviconImageResult& image_result) {
406 // If there is currently a favicon request in progress, it is now outdated,
407 // as we have received another, so nullify the handle from the old request.
408 task_id_ = base::CancelableTaskTracker::kBadTaskId;
409 // lock the list to set icon data and pop the url
411 base::AutoLock auto_lock(list_lock_);
412 // Attach the received data to the ShellLinkItem object.
413 // This data will be decoded by the RunUpdate method.
414 if (!image_result.image.IsEmpty()) {
415 if (!icon_urls_.empty() && icon_urls_.front().second)
416 icon_urls_.front().second->set_icon_data(image_result.image.AsBitmap());
419 if (!icon_urls_.empty())
420 icon_urls_.pop_front();
422 // Check whether we need to load more favicons.
423 StartLoadingFavicon();
426 void JumpList::RunUpdate() {
427 ShellLinkItemList local_most_visited_pages;
428 ShellLinkItemList local_recently_closed_pages;
431 base::AutoLock auto_lock(list_lock_);
432 // Make sure we are not out of date: if icon_urls_ is not empty, then
433 // another notification has been received since we processed this one
434 if (!icon_urls_.empty())
435 return;
437 // Make local copies of lists so we can release the lock.
438 local_most_visited_pages = most_visited_pages_;
439 local_recently_closed_pages = recently_closed_pages_;
442 // Delete the directory which contains old icon files, rename the current
443 // icon directory, and create a new directory which contains new JumpList
444 // icon files.
445 base::FilePath icon_dir_old(icon_dir_.value() + L"Old");
446 if (base::PathExists(icon_dir_old))
447 base::DeleteFile(icon_dir_old, true);
448 base::Move(icon_dir_, icon_dir_old);
449 base::CreateDirectory(icon_dir_);
451 // Create temporary icon files for shortcuts in the "Most Visited" category.
452 CreateIconFiles(local_most_visited_pages);
454 // Create temporary icon files for shortcuts in the "Recently Closed"
455 // category.
456 CreateIconFiles(local_recently_closed_pages);
458 // We finished collecting all resources needed for updating an appliation
459 // JumpList. So, create a new JumpList and replace the current JumpList
460 // with it.
461 UpdateJumpList(app_id_.c_str(), local_most_visited_pages,
462 local_recently_closed_pages);
465 void JumpList::CreateIconFiles(const ShellLinkItemList& item_list) {
466 for (ShellLinkItemList::const_iterator item = item_list.begin();
467 item != item_list.end(); ++item) {
468 base::FilePath icon_path;
469 if (CreateIconFile((*item)->icon_data(), icon_dir_, &icon_path))
470 (*item)->set_icon(icon_path.value(), 0);