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"
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"
40 using content::BrowserThread
;
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
,
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());
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.
68 if (!base::CreateTemporaryFileInDir(icon_dir
, &path
))
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
))
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.
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
))
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
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
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
125 if (!JumpListUpdater::IsEnabled())
128 JumpListUpdater
jumplist_updater(app_id
);
129 if (!jumplist_updater
.BeginUpdate())
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
151 if (!jumplist_updater
.AddCustomCategory(
153 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED
)),
154 most_visited_pages
, most_visited_items
)) {
158 // Update the "Recently Closed" category of the JumpList.
159 if (!jumplist_updater
.AddCustomCategory(
161 l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED
)),
162 recently_closed_pages
, recently_closed_items
)) {
166 // Update the "Tasks" category of the JumpList.
167 if (!UpdateTaskCategory(&jumplist_updater
))
170 // Commit this transaction and send the updated JumpList to Windows.
171 if (!jumplist_updater
.CommitUpdate())
180 : weak_ptr_factory_(this),
182 task_id_(base::CancelableTaskTracker::kBadTaskId
) {}
184 JumpList::~JumpList() {
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
)
202 TabRestoreService
* tab_restore_service
=
203 TabRestoreServiceFactory::GetForProfile(profile
);
204 if (!tab_restore_service
)
207 app_id_
= ShellIntegration::GetChromiumModelIdForProfile(profile
->GetPath());
208 icon_dir_
= profile
->GetPath().Append(chrome::kJumpListIconDirname
);
210 history::TopSites
* top_sites
= profile_
->GetTopSites();
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
215 top_sites
->SyncWithHistory();
216 registrar_
.reset(new content::NotificationRegistrar
);
217 // Register for notification when TopSites changes so that we can update
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);
230 void JumpList::Observe(int type
,
231 const content::NotificationSource
& source
,
232 const content::NotificationDetails
& details
) {
234 case chrome::NOTIFICATION_TOP_SITES_CHANGED
: {
235 // Most visited urls changed, query again.
236 history::TopSites
* top_sites
= profile_
->GetTopSites();
238 top_sites
->GetMostVisitedURLs(
239 base::Bind(&JumpList::OnMostVisitedURLsAvailable
,
240 weak_ptr_factory_
.GetWeakPtr()), false);
244 case chrome::NOTIFICATION_PROFILE_DESTROYED
: {
245 // Profile was destroyed, do clean-up.
250 NOTREACHED() << "Unexpected notification type.";
254 void JumpList::RemoveObserver() {
256 TabRestoreService
* tab_restore_service
=
257 TabRestoreServiceFactory::GetForProfile(profile_
);
258 if (tab_restore_service
)
259 tab_restore_service
->RemoveObserver(this);
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();
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
313 // The last URL of the tab object.
315 // The title of the last URL.
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
,
351 // This code adds the URL and the title strings of the given tab to the
353 if (list
->size() >= max_items
)
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
));
367 void JumpList::AddWindow(const TabRestoreService::Window
* window
,
368 ShellLinkItemList
* list
,
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
))
380 void JumpList::StartLoadingFavicon() {
383 base::AutoLock
auto_lock(list_lock_
);
384 if (icon_urls_
.empty()) {
385 // No more favicons are needed by the application JumpList. Schedule a
387 BrowserThread::PostTask(
388 BrowserThread::FILE, FROM_HERE
,
389 base::Bind(&JumpList::RunUpdate
, this));
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(
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())
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
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"
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
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);