Move StartsWith[ASCII] to base namespace.
[chromium-blink-merge.git] / chrome / browser / jumplist_win.cc
blobbed6653d6f79b919a736f456698aa8133528ba42
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 ReplaceSubstringsAfterOffset(&chrome_title, 0, L"&", L"");
112 chrome->set_title(chrome_title);
113 chrome->set_icon(chrome_path.value(), 0);
114 items.push_back(chrome);
117 // Create an IShellLink object which launches Chrome in incognito mode, and
118 // add it to the collection. We use our application icon as the icon for
119 // this item.
120 if (incognito_availability != IncognitoModePrefs::DISABLED) {
121 scoped_refptr<ShellLinkItem> incognito = CreateShellLink();
122 incognito->GetCommandLine()->AppendSwitch(switches::kIncognito);
123 base::string16 incognito_title =
124 l10n_util::GetStringUTF16(IDS_NEW_INCOGNITO_WINDOW);
125 ReplaceSubstringsAfterOffset(&incognito_title, 0, L"&", L"");
126 incognito->set_title(incognito_title);
127 incognito->set_icon(chrome_path.value(), 0);
128 items.push_back(incognito);
131 return jumplist_updater->AddTasks(items);
134 // Updates the application JumpList.
135 bool UpdateJumpList(const wchar_t* app_id,
136 const ShellLinkItemList& most_visited_pages,
137 const ShellLinkItemList& recently_closed_pages,
138 IncognitoModePrefs::Availability incognito_availability) {
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 // We allocate 60% of the given JumpList slots to "most-visited" items
150 // and 40% to "recently-closed" items, respectively.
151 // Nevertheless, if there are not so many items in |recently_closed_pages|,
152 // we give the remaining slots to "most-visited" items.
153 const int kMostVisited = 60;
154 const int kRecentlyClosed = 40;
155 const int kTotal = kMostVisited + kRecentlyClosed;
156 size_t most_visited_items =
157 MulDiv(jumplist_updater.user_max_items(), kMostVisited, kTotal);
158 size_t recently_closed_items =
159 jumplist_updater.user_max_items() - most_visited_items;
160 if (recently_closed_pages.size() < recently_closed_items) {
161 most_visited_items += recently_closed_items - recently_closed_pages.size();
162 recently_closed_items = recently_closed_pages.size();
165 // Update the "Most Visited" category of the JumpList if it exists.
166 // This update request is applied into the JumpList when we commit this
167 // transaction.
168 if (!jumplist_updater.AddCustomCategory(
169 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED),
170 most_visited_pages, most_visited_items)) {
171 return false;
174 // Update the "Recently Closed" category of the JumpList.
175 if (!jumplist_updater.AddCustomCategory(
176 l10n_util::GetStringUTF16(IDS_RECENTLY_CLOSED),
177 recently_closed_pages, recently_closed_items)) {
178 return false;
181 // Update the "Tasks" category of the JumpList.
182 if (!UpdateTaskCategory(&jumplist_updater, incognito_availability))
183 return false;
185 // Commit this transaction and send the updated JumpList to Windows.
186 if (!jumplist_updater.CommitUpdate())
187 return false;
189 return true;
192 } // namespace
194 JumpList::JumpList(Profile* profile)
195 : profile_(profile),
196 task_id_(base::CancelableTaskTracker::kBadTaskId),
197 weak_ptr_factory_(this) {
198 DCHECK(Enabled());
199 // To update JumpList when a tab is added or removed, we add this object to
200 // the observer list of the TabRestoreService class.
201 // When we add this object to the observer list, we save the pointer to this
202 // TabRestoreService object. This pointer is used when we remove this object
203 // from the observer list.
204 TabRestoreService* tab_restore_service =
205 TabRestoreServiceFactory::GetForProfile(profile_);
206 if (!tab_restore_service)
207 return;
209 app_id_ = ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath());
210 icon_dir_ = profile_->GetPath().Append(chrome::kJumpListIconDirname);
212 scoped_refptr<history::TopSites> top_sites =
213 TopSitesFactory::GetForProfile(profile_);
214 if (top_sites) {
215 // TopSites updates itself after a delay. This is especially noticable when
216 // your profile is empty. Ask TopSites to update itself when jumplist is
217 // initialized.
218 top_sites->SyncWithHistory();
219 registrar_.reset(new content::NotificationRegistrar);
220 // Register as TopSitesObserver so that we can update ourselves when the
221 // TopSites changes.
222 top_sites->AddObserver(this);
223 // Register for notification when profile is destroyed to ensure that all
224 // observers are detatched at that time.
225 registrar_->Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
226 content::Source<Profile>(profile_));
228 tab_restore_service->AddObserver(this);
229 pref_change_registrar_.reset(new PrefChangeRegistrar);
230 pref_change_registrar_->Init(profile_->GetPrefs());
231 pref_change_registrar_->Add(
232 prefs::kIncognitoModeAvailability,
233 base::Bind(&JumpList::OnIncognitoAvailabilityChanged, this));
236 JumpList::~JumpList() {
237 Terminate();
240 // static
241 bool JumpList::Enabled() {
242 return JumpListUpdater::IsEnabled();
245 void JumpList::Observe(int type,
246 const content::NotificationSource& source,
247 const content::NotificationDetails& details) {
248 DCHECK_EQ(type, chrome::NOTIFICATION_PROFILE_DESTROYED);
249 // Profile was destroyed, do clean-up.
250 Terminate();
253 void JumpList::CancelPendingUpdate() {
254 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
255 cancelable_task_tracker_.TryCancel(task_id_);
256 task_id_ = base::CancelableTaskTracker::kBadTaskId;
260 void JumpList::Terminate() {
261 CancelPendingUpdate();
262 if (profile_) {
263 TabRestoreService* tab_restore_service =
264 TabRestoreServiceFactory::GetForProfile(profile_);
265 if (tab_restore_service)
266 tab_restore_service->RemoveObserver(this);
267 scoped_refptr<history::TopSites> top_sites =
268 TopSitesFactory::GetForProfile(profile_);
269 if (top_sites)
270 top_sites->RemoveObserver(this);
271 registrar_.reset();
272 pref_change_registrar_.reset();
274 profile_ = NULL;
277 void JumpList::OnMostVisitedURLsAvailable(
278 const history::MostVisitedURLList& data) {
279 // If we have a pending favicon request, cancel it here (it is out of date).
280 CancelPendingUpdate();
283 base::AutoLock auto_lock(list_lock_);
284 most_visited_pages_.clear();
285 for (size_t i = 0; i < data.size(); i++) {
286 const history::MostVisitedURL& url = data[i];
287 scoped_refptr<ShellLinkItem> link = CreateShellLink();
288 std::string url_string = url.url.spec();
289 std::wstring url_string_wide = base::UTF8ToWide(url_string);
290 link->GetCommandLine()->AppendArgNative(url_string_wide);
291 link->GetCommandLine()->AppendSwitchASCII(
292 switches::kWinJumplistAction, jumplist::kMostVisitedCategory);
293 link->set_title(!url.title.empty()? url.title : url_string_wide);
294 most_visited_pages_.push_back(link);
295 icon_urls_.push_back(make_pair(url_string, link));
299 // Send a query that retrieves the first favicon.
300 StartLoadingFavicon();
303 void JumpList::TabRestoreServiceChanged(TabRestoreService* service) {
304 // if we have a pending handle request, cancel it here (it is out of date).
305 CancelPendingUpdate();
307 // local list to pass to methods
308 ShellLinkItemList temp_list;
310 // Create a list of ShellLinkItems from the "Recently Closed" pages.
311 // As noted above, we create a ShellLinkItem objects with the following
312 // parameters.
313 // * arguments
314 // The last URL of the tab object.
315 // * title
316 // The title of the last URL.
317 // * icon
318 // An empty string. This value is to be updated in OnFaviconDataAvailable().
319 // This code is copied from
320 // RecentlyClosedTabsHandler::TabRestoreServiceChanged() to emulate it.
321 const int kRecentlyClosedCount = 4;
322 TabRestoreService* tab_restore_service =
323 TabRestoreServiceFactory::GetForProfile(profile_);
324 const TabRestoreService::Entries& entries = tab_restore_service->entries();
325 for (TabRestoreService::Entries::const_iterator it = entries.begin();
326 it != entries.end(); ++it) {
327 const TabRestoreService::Entry* entry = *it;
328 if (entry->type == TabRestoreService::TAB) {
329 AddTab(static_cast<const TabRestoreService::Tab*>(entry),
330 &temp_list, kRecentlyClosedCount);
331 } else if (entry->type == TabRestoreService::WINDOW) {
332 AddWindow(static_cast<const TabRestoreService::Window*>(entry),
333 &temp_list, kRecentlyClosedCount);
336 // Lock recently_closed_pages and copy temp_list into it.
338 base::AutoLock auto_lock(list_lock_);
339 recently_closed_pages_ = temp_list;
342 // Send a query that retrieves the first favicon.
343 StartLoadingFavicon();
346 void JumpList::TabRestoreServiceDestroyed(TabRestoreService* service) {
349 bool JumpList::AddTab(const TabRestoreService::Tab* tab,
350 ShellLinkItemList* list,
351 size_t max_items) {
352 // This code adds the URL and the title strings of the given tab to the
353 // specified list.
354 if (list->size() >= max_items)
355 return false;
357 scoped_refptr<ShellLinkItem> link = CreateShellLink();
358 const sessions::SerializedNavigationEntry& current_navigation =
359 tab->navigations.at(tab->current_navigation_index);
360 std::string url = current_navigation.virtual_url().spec();
361 link->GetCommandLine()->AppendArgNative(base::UTF8ToWide(url));
362 link->GetCommandLine()->AppendSwitchASCII(
363 switches::kWinJumplistAction, jumplist::kRecentlyClosedCategory);
364 link->set_title(current_navigation.title());
365 list->push_back(link);
366 icon_urls_.push_back(make_pair(url, link));
367 return true;
370 void JumpList::AddWindow(const TabRestoreService::Window* window,
371 ShellLinkItemList* list,
372 size_t max_items) {
373 // This code enumerates al the tabs in the given window object and add their
374 // URLs and titles to the list.
375 DCHECK(!window->tabs.empty());
377 for (size_t i = 0; i < window->tabs.size(); ++i) {
378 if (!AddTab(&window->tabs[i], list, max_items))
379 return;
383 void JumpList::StartLoadingFavicon() {
384 GURL url;
385 bool waiting_for_icons = true;
387 base::AutoLock auto_lock(list_lock_);
388 waiting_for_icons = !icon_urls_.empty();
389 if (waiting_for_icons) {
390 // Ask FaviconService if it has a favicon of a URL.
391 // When FaviconService has one, it will call OnFaviconDataAvailable().
392 url = GURL(icon_urls_.front().first);
396 if (!waiting_for_icons) {
397 // No more favicons are needed by the application JumpList. Schedule a
398 // RunUpdateOnFileThread call.
399 PostRunUpdate();
400 return;
403 favicon::FaviconService* favicon_service =
404 FaviconServiceFactory::GetForProfile(profile_,
405 ServiceAccessType::EXPLICIT_ACCESS);
406 task_id_ = favicon_service->GetFaviconImageForPageURL(
407 url,
408 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
409 &cancelable_task_tracker_);
412 void JumpList::OnFaviconDataAvailable(
413 const favicon_base::FaviconImageResult& image_result) {
414 // If there is currently a favicon request in progress, it is now outdated,
415 // as we have received another, so nullify the handle from the old request.
416 task_id_ = base::CancelableTaskTracker::kBadTaskId;
417 // Lock the list to set icon data and pop the url.
419 base::AutoLock auto_lock(list_lock_);
420 // Attach the received data to the ShellLinkItem object.
421 // This data will be decoded by the RunUpdateOnFileThread method.
422 if (!image_result.image.IsEmpty()) {
423 if (!icon_urls_.empty() && icon_urls_.front().second.get())
424 icon_urls_.front().second->set_icon_data(image_result.image.AsBitmap());
427 if (!icon_urls_.empty())
428 icon_urls_.pop_front();
430 // Check whether we need to load more favicons.
431 StartLoadingFavicon();
434 void JumpList::OnIncognitoAvailabilityChanged() {
435 bool waiting_for_icons = true;
437 base::AutoLock auto_lock(list_lock_);
438 waiting_for_icons = !icon_urls_.empty();
440 if (!waiting_for_icons)
441 PostRunUpdate();
442 // If |icon_urls_| isn't empty then OnFaviconDataAvailable will eventually
443 // call PostRunUpdate().
446 void JumpList::PostRunUpdate() {
447 TRACE_EVENT0("browser", "JumpList::PostRunUpdate");
448 // Initialize the one-shot timer to update the jumplists in a while.
449 // If there is already a request queued then cancel it and post the new
450 // request. This ensures that JumpListUpdates won't happen until there has
451 // been a brief quiet period, thus avoiding update storms.
452 if (timer_.IsRunning()) {
453 timer_.Reset();
454 } else {
455 timer_.Start(FROM_HERE,
456 base::TimeDelta::FromMilliseconds(kDelayForJumplistUpdateInMS),
457 this,
458 &JumpList::DeferredRunUpdate);
462 void JumpList::DeferredRunUpdate() {
463 TRACE_EVENT0("browser", "JumpList::DeferredRunUpdate");
464 // Check if incognito windows (or normal windows) are disabled by policy.
465 IncognitoModePrefs::Availability incognito_availability =
466 profile_ ? IncognitoModePrefs::GetAvailability(profile_->GetPrefs())
467 : IncognitoModePrefs::ENABLED;
469 BrowserThread::PostTask(
470 BrowserThread::FILE, FROM_HERE,
471 base::Bind(&JumpList::RunUpdateOnFileThread,
472 this,
473 incognito_availability));
476 void JumpList::RunUpdateOnFileThread(
477 IncognitoModePrefs::Availability incognito_availability) {
478 ShellLinkItemList local_most_visited_pages;
479 ShellLinkItemList local_recently_closed_pages;
482 base::AutoLock auto_lock(list_lock_);
483 // Make sure we are not out of date: if icon_urls_ is not empty, then
484 // another notification has been received since we processed this one
485 if (!icon_urls_.empty())
486 return;
488 // Make local copies of lists so we can release the lock.
489 local_most_visited_pages = most_visited_pages_;
490 local_recently_closed_pages = recently_closed_pages_;
493 // Delete the directory which contains old icon files, rename the current
494 // icon directory, and create a new directory which contains new JumpList
495 // icon files.
496 base::FilePath icon_dir_old(icon_dir_.value() + L"Old");
497 if (base::PathExists(icon_dir_old))
498 base::DeleteFile(icon_dir_old, true);
499 base::Move(icon_dir_, icon_dir_old);
500 base::CreateDirectory(icon_dir_);
502 // Create temporary icon files for shortcuts in the "Most Visited" category.
503 CreateIconFiles(local_most_visited_pages);
505 // Create temporary icon files for shortcuts in the "Recently Closed"
506 // category.
507 CreateIconFiles(local_recently_closed_pages);
509 // We finished collecting all resources needed for updating an application
510 // JumpList. So, create a new JumpList and replace the current JumpList
511 // with it.
512 UpdateJumpList(app_id_.c_str(),
513 local_most_visited_pages,
514 local_recently_closed_pages,
515 incognito_availability);
518 void JumpList::CreateIconFiles(const ShellLinkItemList& item_list) {
519 for (ShellLinkItemList::const_iterator item = item_list.begin();
520 item != item_list.end(); ++item) {
521 base::FilePath icon_path;
522 if (CreateIconFile((*item)->icon_data(), icon_dir_, &icon_path))
523 (*item)->set_icon(icon_path.value(), 0);
527 void JumpList::TopSitesLoaded(history::TopSites* top_sites) {
530 void JumpList::TopSitesChanged(history::TopSites* top_sites) {
531 top_sites->GetMostVisitedURLs(
532 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
533 weak_ptr_factory_.GetWeakPtr()),
534 false);