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"
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_factory.h"
23 #include "chrome/browser/shell_integration.h"
24 #include "chrome/common/chrome_constants.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/pref_names.h"
27 #include "chrome/common/url_constants.h"
28 #include "chrome/grit/generated_resources.h"
29 #include "components/favicon/core/favicon_service.h"
30 #include "components/favicon_base/favicon_types.h"
31 #include "components/history/core/browser/history_service.h"
32 #include "components/history/core/browser/page_usage_data.h"
33 #include "components/history/core/browser/top_sites.h"
34 #include "components/sessions/core/tab_restore_service.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"
46 using content::BrowserThread
;
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
,
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());
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.
78 if (!base::CreateTemporaryFileInDir(icon_dir
, &path
))
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
))
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.
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
))
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
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
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
144 if (!JumpListUpdater::IsEnabled())
147 JumpListUpdater
jumplist_updater(app_id
);
148 if (!jumplist_updater
.BeginUpdate())
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
170 if (!jumplist_updater
.AddCustomCategory(
171 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED
),
172 most_visited_pages
, most_visited_items
)) {
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
)) {
183 // Update the "Tasks" category of the JumpList.
184 if (!UpdateTaskCategory(&jumplist_updater
, incognito_availability
))
187 // Commit this transaction and send the updated JumpList to Windows.
188 if (!jumplist_updater
.CommitUpdate())
196 JumpList::JumpList(Profile
* profile
)
198 task_id_(base::CancelableTaskTracker::kBadTaskId
),
199 weak_ptr_factory_(this) {
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 sessions::TabRestoreService
* tab_restore_service
=
207 TabRestoreServiceFactory::GetForProfile(profile_
);
208 if (!tab_restore_service
)
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_
);
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
220 top_sites
->SyncWithHistory();
221 registrar_
.reset(new content::NotificationRegistrar
);
222 // Register as TopSitesObserver so that we can update ourselves when the
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() {
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.
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();
265 sessions::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_
);
272 top_sites
->RemoveObserver(this);
274 pref_change_registrar_
.reset();
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(sessions::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
316 // The last URL of the tab object.
318 // The title of the last URL.
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 sessions::TabRestoreService
* tab_restore_service
=
325 TabRestoreServiceFactory::GetForProfile(profile_
);
326 const sessions::TabRestoreService::Entries
& entries
=
327 tab_restore_service
->entries();
328 for (sessions::TabRestoreService::Entries::const_iterator it
=
330 it
!= entries
.end(); ++it
) {
331 const sessions::TabRestoreService::Entry
* entry
= *it
;
332 if (entry
->type
== sessions::TabRestoreService::TAB
) {
333 AddTab(static_cast<const sessions::TabRestoreService::Tab
*>(entry
),
334 &temp_list
, kRecentlyClosedCount
);
335 } else if (entry
->type
== sessions::TabRestoreService::WINDOW
) {
336 AddWindow(static_cast<const sessions::TabRestoreService::Window
*>(entry
),
337 &temp_list
, kRecentlyClosedCount
);
340 // Lock recently_closed_pages and copy temp_list into it.
342 base::AutoLock
auto_lock(list_lock_
);
343 recently_closed_pages_
= temp_list
;
346 // Send a query that retrieves the first favicon.
347 StartLoadingFavicon();
350 void JumpList::TabRestoreServiceDestroyed(
351 sessions::TabRestoreService
* service
) {}
353 bool JumpList::AddTab(const sessions::TabRestoreService::Tab
* tab
,
354 ShellLinkItemList
* list
,
356 // This code adds the URL and the title strings of the given tab to the
358 if (list
->size() >= max_items
)
361 scoped_refptr
<ShellLinkItem
> link
= CreateShellLink();
362 const sessions::SerializedNavigationEntry
& current_navigation
=
363 tab
->navigations
.at(tab
->current_navigation_index
);
364 std::string url
= current_navigation
.virtual_url().spec();
365 link
->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url
));
366 link
->GetCommandLine()->AppendSwitchASCII(
367 switches::kWinJumplistAction
, jumplist::kRecentlyClosedCategory
);
368 link
->set_title(current_navigation
.title());
369 list
->push_back(link
);
370 icon_urls_
.push_back(make_pair(url
, link
));
374 void JumpList::AddWindow(const sessions::TabRestoreService::Window
* window
,
375 ShellLinkItemList
* list
,
377 // This code enumerates al the tabs in the given window object and add their
378 // URLs and titles to the list.
379 DCHECK(!window
->tabs
.empty());
381 for (size_t i
= 0; i
< window
->tabs
.size(); ++i
) {
382 if (!AddTab(&window
->tabs
[i
], list
, max_items
))
387 void JumpList::StartLoadingFavicon() {
389 bool waiting_for_icons
= true;
391 base::AutoLock
auto_lock(list_lock_
);
392 waiting_for_icons
= !icon_urls_
.empty();
393 if (waiting_for_icons
) {
394 // Ask FaviconService if it has a favicon of a URL.
395 // When FaviconService has one, it will call OnFaviconDataAvailable().
396 url
= GURL(icon_urls_
.front().first
);
400 if (!waiting_for_icons
) {
401 // No more favicons are needed by the application JumpList. Schedule a
402 // RunUpdateOnFileThread call.
407 favicon::FaviconService
* favicon_service
=
408 FaviconServiceFactory::GetForProfile(profile_
,
409 ServiceAccessType::EXPLICIT_ACCESS
);
410 task_id_
= favicon_service
->GetFaviconImageForPageURL(
412 base::Bind(&JumpList::OnFaviconDataAvailable
, base::Unretained(this)),
413 &cancelable_task_tracker_
);
416 void JumpList::OnFaviconDataAvailable(
417 const favicon_base::FaviconImageResult
& image_result
) {
418 // If there is currently a favicon request in progress, it is now outdated,
419 // as we have received another, so nullify the handle from the old request.
420 task_id_
= base::CancelableTaskTracker::kBadTaskId
;
421 // Lock the list to set icon data and pop the url.
423 base::AutoLock
auto_lock(list_lock_
);
424 // Attach the received data to the ShellLinkItem object.
425 // This data will be decoded by the RunUpdateOnFileThread method.
426 if (!image_result
.image
.IsEmpty()) {
427 if (!icon_urls_
.empty() && icon_urls_
.front().second
.get())
428 icon_urls_
.front().second
->set_icon_data(image_result
.image
.AsBitmap());
431 if (!icon_urls_
.empty())
432 icon_urls_
.pop_front();
434 // Check whether we need to load more favicons.
435 StartLoadingFavicon();
438 void JumpList::OnIncognitoAvailabilityChanged() {
439 bool waiting_for_icons
= true;
441 base::AutoLock
auto_lock(list_lock_
);
442 waiting_for_icons
= !icon_urls_
.empty();
444 if (!waiting_for_icons
)
446 // If |icon_urls_| isn't empty then OnFaviconDataAvailable will eventually
447 // call PostRunUpdate().
450 void JumpList::PostRunUpdate() {
451 TRACE_EVENT0("browser", "JumpList::PostRunUpdate");
452 // Initialize the one-shot timer to update the jumplists in a while.
453 // If there is already a request queued then cancel it and post the new
454 // request. This ensures that JumpListUpdates won't happen until there has
455 // been a brief quiet period, thus avoiding update storms.
456 if (timer_
.IsRunning()) {
459 timer_
.Start(FROM_HERE
,
460 base::TimeDelta::FromMilliseconds(kDelayForJumplistUpdateInMS
),
462 &JumpList::DeferredRunUpdate
);
466 void JumpList::DeferredRunUpdate() {
467 TRACE_EVENT0("browser", "JumpList::DeferredRunUpdate");
468 // Check if incognito windows (or normal windows) are disabled by policy.
469 IncognitoModePrefs::Availability incognito_availability
=
470 profile_
? IncognitoModePrefs::GetAvailability(profile_
->GetPrefs())
471 : IncognitoModePrefs::ENABLED
;
473 BrowserThread::PostTask(
474 BrowserThread::FILE, FROM_HERE
,
475 base::Bind(&JumpList::RunUpdateOnFileThread
,
477 incognito_availability
));
480 void JumpList::RunUpdateOnFileThread(
481 IncognitoModePrefs::Availability incognito_availability
) {
482 ShellLinkItemList local_most_visited_pages
;
483 ShellLinkItemList local_recently_closed_pages
;
486 base::AutoLock
auto_lock(list_lock_
);
487 // Make sure we are not out of date: if icon_urls_ is not empty, then
488 // another notification has been received since we processed this one
489 if (!icon_urls_
.empty())
492 // Make local copies of lists so we can release the lock.
493 local_most_visited_pages
= most_visited_pages_
;
494 local_recently_closed_pages
= recently_closed_pages_
;
497 // Delete the directory which contains old icon files, rename the current
498 // icon directory, and create a new directory which contains new JumpList
500 base::FilePath
icon_dir_old(icon_dir_
.value() + L
"Old");
501 if (base::PathExists(icon_dir_old
))
502 base::DeleteFile(icon_dir_old
, true);
503 base::Move(icon_dir_
, icon_dir_old
);
504 base::CreateDirectory(icon_dir_
);
506 // Create temporary icon files for shortcuts in the "Most Visited" category.
507 CreateIconFiles(local_most_visited_pages
);
509 // Create temporary icon files for shortcuts in the "Recently Closed"
511 CreateIconFiles(local_recently_closed_pages
);
513 // We finished collecting all resources needed for updating an application
514 // JumpList. So, create a new JumpList and replace the current JumpList
516 UpdateJumpList(app_id_
.c_str(),
517 local_most_visited_pages
,
518 local_recently_closed_pages
,
519 incognito_availability
);
522 void JumpList::CreateIconFiles(const ShellLinkItemList
& item_list
) {
523 for (ShellLinkItemList::const_iterator item
= item_list
.begin();
524 item
!= item_list
.end(); ++item
) {
525 base::FilePath icon_path
;
526 if (CreateIconFile((*item
)->icon_data(), icon_dir_
, &icon_path
))
527 (*item
)->set_icon(icon_path
.value(), 0);
531 void JumpList::TopSitesLoaded(history::TopSites
* top_sites
) {
534 void JumpList::TopSitesChanged(history::TopSites
* top_sites
,
535 ChangeReason change_reason
) {
536 top_sites
->GetMostVisitedURLs(
537 base::Bind(&JumpList::OnMostVisitedURLsAvailable
,
538 weak_ptr_factory_
.GetWeakPtr()),