Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(705)

Side by Side Diff: chrome/browser/win/jumplist.cc

Issue 2931573003: Fix stability and data racing issues, coalesce more updates for JumpList (Closed)
Patch Set: Address comments Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« chrome/browser/win/jumplist.h ('K') | « chrome/browser/win/jumplist.h ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/win/jumplist.h" 5 #include "chrome/browser/win/jumplist.h"
6 6
7 #include "base/base_paths.h" 7 #include "base/base_paths.h"
8 #include "base/bind.h" 8 #include "base/bind.h"
9 #include "base/bind_helpers.h" 9 #include "base/bind_helpers.h"
10 #include "base/command_line.h" 10 #include "base/command_line.h"
(...skipping 20 matching lines...) Expand all
31 #include "chrome/browser/shell_integration_win.h" 31 #include "chrome/browser/shell_integration_win.h"
32 #include "chrome/browser/win/jumplist_file_util.h" 32 #include "chrome/browser/win/jumplist_file_util.h"
33 #include "chrome/browser/win/jumplist_update_util.h" 33 #include "chrome/browser/win/jumplist_update_util.h"
34 #include "chrome/common/chrome_constants.h" 34 #include "chrome/common/chrome_constants.h"
35 #include "chrome/common/chrome_icon_resources_win.h" 35 #include "chrome/common/chrome_icon_resources_win.h"
36 #include "chrome/common/chrome_switches.h" 36 #include "chrome/common/chrome_switches.h"
37 #include "chrome/common/pref_names.h" 37 #include "chrome/common/pref_names.h"
38 #include "chrome/grit/generated_resources.h" 38 #include "chrome/grit/generated_resources.h"
39 #include "chrome/install_static/install_util.h" 39 #include "chrome/install_static/install_util.h"
40 #include "components/favicon/core/favicon_service.h" 40 #include "components/favicon/core/favicon_service.h"
41 #include "components/history/core/browser/history_service.h"
41 #include "components/history/core/browser/top_sites.h" 42 #include "components/history/core/browser/top_sites.h"
42 #include "components/prefs/pref_change_registrar.h" 43 #include "components/prefs/pref_change_registrar.h"
43 #include "components/sessions/core/session_types.h" 44 #include "components/sessions/core/session_types.h"
44 #include "components/strings/grit/components_strings.h" 45 #include "components/strings/grit/components_strings.h"
45 #include "ui/base/l10n/l10n_util.h" 46 #include "ui/base/l10n/l10n_util.h"
46 #include "ui/gfx/codec/png_codec.h" 47 #include "ui/gfx/codec/png_codec.h"
47 #include "ui/gfx/favicon_size.h" 48 #include "ui/gfx/favicon_size.h"
48 #include "ui/gfx/icon_util.h" 49 #include "ui/gfx/icon_util.h"
49 #include "ui/gfx/image/image.h" 50 #include "ui/gfx/image/image.h"
50 #include "ui/gfx/image/image_family.h" 51 #include "ui/gfx/image/image_family.h"
51 #include "ui/gfx/image/image_skia.h" 52 #include "ui/gfx/image/image_skia.h"
52 #include "ui/gfx/image/image_skia_rep.h" 53 #include "ui/gfx/image/image_skia_rep.h"
53 #include "url/gurl.h" 54 #include "url/gurl.h"
54 55
55 using content::BrowserThread; 56 using content::BrowserThread;
56 using JumpListData = JumpList::JumpListData;
57 57
58 namespace { 58 namespace {
59 59
60 // The default maximum number of items to display in JumpList is 10. 60 // The default maximum number of items to display in JumpList is 10.
61 // https://msdn.microsoft.com/library/windows/desktop/dd378398.aspx 61 // https://msdn.microsoft.com/library/windows/desktop/dd378398.aspx
62 // The "Most visited" and "Recently closed" category titles always take 2 slots. 62 // The "Most visited" and "Recently closed" category titles always take 2 slots.
63 // For the remaining 8 slots, we allocate 5 slots to "most-visited" items and 3 63 // For the remaining 8 slots, we allocate 5 slots to "most-visited" items and 3
64 // slots to "recently-closed" items, respectively. 64 // slots to "recently-closed" items, respectively.
65 constexpr size_t kMostVisitedItems = 5; 65 constexpr size_t kMostVisitedItems = 5;
66 constexpr size_t kRecentlyClosedItems = 3; 66 constexpr size_t kRecentlyClosedItems = 3;
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
189 base::FilePath GenerateJumplistIconDirName( 189 base::FilePath GenerateJumplistIconDirName(
190 const base::FilePath& profile_dir, 190 const base::FilePath& profile_dir,
191 const base::FilePath::StringPieceType& suffix) { 191 const base::FilePath::StringPieceType& suffix) {
192 base::FilePath::StringType dir_name(chrome::kJumpListIconDirname); 192 base::FilePath::StringType dir_name(chrome::kJumpListIconDirname);
193 suffix.AppendToString(&dir_name); 193 suffix.AppendToString(&dir_name);
194 return profile_dir.Append(dir_name); 194 return profile_dir.Append(dir_name);
195 } 195 }
196 196
197 } // namespace 197 } // namespace
198 198
199 JumpList::JumpListData::JumpListData() {} 199 JumpList::UpdateResults::UpdateResults() {}
200 200
201 JumpList::JumpListData::~JumpListData() {} 201 JumpList::UpdateResults::~UpdateResults() {}
202 202
203 JumpList::JumpList(Profile* profile) 203 JumpList::JumpList(Profile* profile)
204 : RefcountedKeyedService(content::BrowserThread::GetTaskRunnerForThread( 204 : RefcountedKeyedService(content::BrowserThread::GetTaskRunnerForThread(
205 content::BrowserThread::UI)), 205 content::BrowserThread::UI)),
206 profile_(profile), 206 profile_(profile),
207 jumplist_data_(new base::RefCountedData<JumpListData>),
208 task_id_(base::CancelableTaskTracker::kBadTaskId),
209 update_jumplist_task_runner_(base::CreateCOMSTATaskRunnerWithTraits( 207 update_jumplist_task_runner_(base::CreateCOMSTATaskRunnerWithTraits(
210 {base::MayBlock(), base::TaskPriority::USER_VISIBLE, 208 {base::MayBlock(), base::TaskPriority::USER_VISIBLE,
211 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), 209 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})),
212 delete_jumplisticons_task_runner_( 210 delete_jumplisticons_task_runner_(
213 base::CreateSequencedTaskRunnerWithTraits( 211 base::CreateSequencedTaskRunnerWithTraits(
214 {base::MayBlock(), base::TaskPriority::BACKGROUND, 212 {base::MayBlock(), base::TaskPriority::BACKGROUND,
215 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})), 213 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN})),
216 weak_ptr_factory_(this) { 214 weak_ptr_factory_(this) {
217 DCHECK(Enabled()); 215 DCHECK(Enabled());
218 // To update JumpList when a tab is added or removed, we add this object to 216 // To update JumpList when a tab is added or removed, we add this object to
219 // the observer list of the TabRestoreService class. 217 // the observer list of the TabRestoreService class.
220 // When we add this object to the observer list, we save the pointer to this 218 // When we add this object to the observer list, we save the pointer to this
221 // TabRestoreService object. This pointer is used when we remove this object 219 // TabRestoreService object. This pointer is used when we remove this object
222 // from the observer list. 220 // from the observer list.
223 sessions::TabRestoreService* tab_restore_service = 221 sessions::TabRestoreService* tab_restore_service =
224 TabRestoreServiceFactory::GetForProfile(profile_); 222 TabRestoreServiceFactory::GetForProfile(profile_);
225 if (!tab_restore_service) 223 if (!tab_restore_service)
226 return; 224 return;
227 225
228 app_id_ = 226 app_id_ =
229 shell_integration::win::GetChromiumModelIdForProfile(profile_->GetPath()); 227 shell_integration::win::GetChromiumModelIdForProfile(profile_->GetPath());
230 228
229 // Register as TopSitesObserver so that we can update ourselves when the
230 // TopSites changes. TopSites updates itself after a delay. This is especially
231 // noticable when your profile is empty.
231 scoped_refptr<history::TopSites> top_sites = 232 scoped_refptr<history::TopSites> top_sites =
232 TopSitesFactory::GetForProfile(profile_); 233 TopSitesFactory::GetForProfile(profile_);
233 if (top_sites) { 234 if (top_sites)
234 // Register as TopSitesObserver so that we can update ourselves when the
235 // TopSites changes. TopSites updates itself after a delay. This is
236 // especially noticable when your profile is empty.
237 top_sites->AddObserver(this); 235 top_sites->AddObserver(this);
238 } 236
237 // Register as TabRestoreServiceObserver so that we can update ourselves when
238 // recently closed tabs have changes.
239 tab_restore_service->AddObserver(this); 239 tab_restore_service->AddObserver(this);
240
241 // kIncognitoModeAvailability is monitored for changes on Incognito mode.
240 pref_change_registrar_.reset(new PrefChangeRegistrar); 242 pref_change_registrar_.reset(new PrefChangeRegistrar);
241 pref_change_registrar_->Init(profile_->GetPrefs()); 243 pref_change_registrar_->Init(profile_->GetPrefs());
244 // base::Unretained is safe since |this| is guaranteed to outlive
245 // pref_change_registrar_.
242 pref_change_registrar_->Add( 246 pref_change_registrar_->Add(
243 prefs::kIncognitoModeAvailability, 247 prefs::kIncognitoModeAvailability,
244 base::Bind(&JumpList::OnIncognitoAvailabilityChanged, this)); 248 base::Bind(&JumpList::OnIncognitoAvailabilityChanged,
249 base::Unretained(this)));
245 } 250 }
246 251
247 JumpList::~JumpList() { 252 JumpList::~JumpList() {
248 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 253 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
249 Terminate(); 254 Terminate();
250 } 255 }
251 256
252 // static 257 // static
253 bool JumpList::Enabled() { 258 bool JumpList::Enabled() {
254 return JumpListUpdater::IsEnabled(); 259 return JumpListUpdater::IsEnabled();
255 } 260 }
256 261
257 void JumpList::CancelPendingUpdate() { 262 void JumpList::CancelPendingUpdate() {
258 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 263 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
264
265 // Cancel a pending most-visited URL fetch by invalidating the weak pointer.
266 weak_ptr_factory_.InvalidateWeakPtrs();
267
268 // Cancel a pending favicon loading by invalidating its task id.
259 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) { 269 if (task_id_ != base::CancelableTaskTracker::kBadTaskId) {
260 cancelable_task_tracker_.TryCancel(task_id_); 270 cancelable_task_tracker_.TryCancel(task_id_);
261 task_id_ = base::CancelableTaskTracker::kBadTaskId; 271 task_id_ = base::CancelableTaskTracker::kBadTaskId;
262 } 272 }
263 } 273 }
264 274
265 void JumpList::Terminate() { 275 void JumpList::Terminate() {
266 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 276 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
267 timer_most_visited_.Stop(); 277 timer_.Stop();
268 timer_recently_closed_.Stop();
269 CancelPendingUpdate(); 278 CancelPendingUpdate();
279 update_in_progress_ = false;
270 if (profile_) { 280 if (profile_) {
271 sessions::TabRestoreService* tab_restore_service = 281 sessions::TabRestoreService* tab_restore_service =
272 TabRestoreServiceFactory::GetForProfile(profile_); 282 TabRestoreServiceFactory::GetForProfile(profile_);
273 if (tab_restore_service) 283 if (tab_restore_service)
274 tab_restore_service->RemoveObserver(this); 284 tab_restore_service->RemoveObserver(this);
275 scoped_refptr<history::TopSites> top_sites = 285 scoped_refptr<history::TopSites> top_sites =
276 TopSitesFactory::GetForProfile(profile_); 286 TopSitesFactory::GetForProfile(profile_);
277 if (top_sites) 287 if (top_sites)
278 top_sites->RemoveObserver(this); 288 top_sites->RemoveObserver(this);
279 pref_change_registrar_.reset(); 289 pref_change_registrar_.reset();
280 } 290 }
281 profile_ = NULL; 291 profile_ = nullptr;
282 } 292 }
283 293
284 void JumpList::ShutdownOnUIThread() { 294 void JumpList::ShutdownOnUIThread() {
285 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 295 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
286 Terminate(); 296 Terminate();
287 } 297 }
288 298
289 void JumpList::OnMostVisitedURLsAvailable( 299 void JumpList::OnMostVisitedURLsAvailable(
290 const history::MostVisitedURLList& urls) { 300 const history::MostVisitedURLList& urls) {
291 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 301 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
292 302
293 { 303 top_sites_has_pending_notification_ = false;
294 JumpListData* data = &jumplist_data_->data;
295 base::AutoLock auto_lock(data->list_lock_);
296 304
297 // There is no need to update the JumpList if the top most visited sites in 305 // There is no need to update the JumpList if the top most visited sites in
298 // display have not changed. 306 // display have not changed.
299 if (MostVisitedItemsUnchanged(data->most_visited_pages_, urls, 307 if (MostVisitedItemsUnchanged(most_visited_pages_, urls, kMostVisitedItems))
300 kMostVisitedItems)) { 308 return;
301 return;
302 }
303 309
304 data->most_visited_pages_.clear(); 310 most_visited_pages_.clear();
305 311
306 for (size_t i = 0; i < urls.size() && i < kMostVisitedItems; i++) { 312 const size_t num_items = std::min(urls.size(), kMostVisitedItems);
307 const history::MostVisitedURL& url = urls[i]; 313 for (size_t i = 0; i < num_items; ++i) {
308 scoped_refptr<ShellLinkItem> link = CreateShellLink(); 314 const history::MostVisitedURL& url = urls[i];
309 std::string url_string = url.url.spec(); 315 scoped_refptr<ShellLinkItem> link = CreateShellLink();
310 base::string16 url_string_wide = base::UTF8ToUTF16(url_string); 316 std::string url_string = url.url.spec();
311 link->GetCommandLine()->AppendArgNative(url_string_wide); 317 base::string16 url_string_wide = base::UTF8ToUTF16(url_string);
312 link->GetCommandLine()->AppendSwitchASCII( 318 link->GetCommandLine()->AppendArgNative(url_string_wide);
313 switches::kWinJumplistAction, jumplist::kMostVisitedCategory); 319 link->GetCommandLine()->AppendSwitchASCII(switches::kWinJumplistAction,
314 link->set_title(!url.title.empty() ? url.title : url_string_wide); 320 jumplist::kMostVisitedCategory);
315 link->set_url(url_string); 321 link->set_title(!url.title.empty() ? url.title : url_string_wide);
316 data->most_visited_pages_.push_back(link); 322 link->set_url(url_string);
317 data->icon_urls_.push_back(std::make_pair(url_string, link)); 323 most_visited_pages_.push_back(link);
318 } 324 icon_urls_.emplace_back(std::move(url_string), std::move(link));
319 data->most_visited_pages_have_updates_ = true;
320 } 325 }
321 326
327 most_visited_should_update_ = true;
328
322 // Send a query that retrieves the first favicon. 329 // Send a query that retrieves the first favicon.
323 StartLoadingFavicon(); 330 StartLoadingFavicon();
324 } 331 }
325 332
326 void JumpList::TabRestoreServiceChanged(sessions::TabRestoreService* service) { 333 void JumpList::TabRestoreServiceChanged(sessions::TabRestoreService* service) {
327 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 334 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
328 335
329 // if we have a pending favicon request, cancel it here (it is out of date). 336 tab_restore_has_pending_notification_ = true;
337
338 // Postpone handling this notification until a pending update completes.
339 if (update_in_progress_)
340 return;
341
342 // if we have a pending favicon request, cancel it here as it's out of date.
330 CancelPendingUpdate(); 343 CancelPendingUpdate();
331 344
332 // Initialize the one-shot timer to update the the "Recently Closed" category 345 // Initialize the one-shot timer to update the JumpList in a while.
333 // in a while. If there is already a request queued then cancel it and post 346 InitializeTimerForUpdate();
334 // the new request. This ensures that JumpList update of the "Recently Closed"
335 // category won't happen until there has been a brief quiet period, thus
336 // avoiding update storms.
337 if (timer_recently_closed_.IsRunning()) {
338 timer_recently_closed_.Reset();
339 } else {
340 timer_recently_closed_.Start(
341 FROM_HERE, kDelayForJumplistUpdate,
342 base::Bind(&JumpList::DeferredTabRestoreServiceChanged,
343 base::Unretained(this)));
344 }
345 } 347 }
346 348
347 void JumpList::TabRestoreServiceDestroyed( 349 void JumpList::TabRestoreServiceDestroyed(
348 sessions::TabRestoreService* service) {} 350 sessions::TabRestoreService* service) {}
349 351
350 bool JumpList::AddTab(const sessions::TabRestoreService::Tab& tab, 352 bool JumpList::AddTab(const sessions::TabRestoreService::Tab& tab,
351 size_t max_items, 353 size_t max_items) {
352 JumpListData* data) {
353 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 354 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
354 data->list_lock_.AssertAcquired();
355 355
356 // This code adds the URL and the title strings of the given tab to |data|. 356 // This code adds the URL and the title strings of the given tab to the
357 if (data->recently_closed_pages_.size() >= max_items) 357 // JumpList variables.
358 if (recently_closed_pages_.size() >= max_items)
358 return false; 359 return false;
359 360
360 scoped_refptr<ShellLinkItem> link = CreateShellLink(); 361 scoped_refptr<ShellLinkItem> link = CreateShellLink();
361 const sessions::SerializedNavigationEntry& current_navigation = 362 const sessions::SerializedNavigationEntry& current_navigation =
362 tab.navigations.at(tab.current_navigation_index); 363 tab.navigations.at(tab.current_navigation_index);
363 std::string url = current_navigation.virtual_url().spec(); 364 std::string url = current_navigation.virtual_url().spec();
364 link->GetCommandLine()->AppendArgNative(base::UTF8ToUTF16(url)); 365 link->GetCommandLine()->AppendArgNative(base::UTF8ToUTF16(url));
365 link->GetCommandLine()->AppendSwitchASCII(switches::kWinJumplistAction, 366 link->GetCommandLine()->AppendSwitchASCII(switches::kWinJumplistAction,
366 jumplist::kRecentlyClosedCategory); 367 jumplist::kRecentlyClosedCategory);
367 link->set_title(current_navigation.title()); 368 link->set_title(current_navigation.title());
368 link->set_url(url); 369 link->set_url(url);
369 data->recently_closed_pages_.push_back(link); 370 recently_closed_pages_.push_back(link);
370 data->icon_urls_.push_back(std::make_pair(std::move(url), std::move(link))); 371 icon_urls_.emplace_back(std::move(url), std::move(link));
371 372
372 return true; 373 return true;
373 } 374 }
374 375
375 void JumpList::AddWindow(const sessions::TabRestoreService::Window& window, 376 void JumpList::AddWindow(const sessions::TabRestoreService::Window& window,
376 size_t max_items, 377 size_t max_items) {
377 JumpListData* data) {
378 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 378 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
379 data->list_lock_.AssertAcquired();
380
381 // This code enumerates all the tabs in the given window object and add their
382 // URLs and titles to |data|.
383 DCHECK(!window.tabs.empty()); 379 DCHECK(!window.tabs.empty());
384 380
385 for (const auto& tab : window.tabs) { 381 for (const auto& tab : window.tabs) {
386 if (!AddTab(*tab, max_items, data)) 382 if (!AddTab(*tab, max_items))
387 return; 383 return;
388 } 384 }
389 } 385 }
390 386
391 void JumpList::StartLoadingFavicon() { 387 void JumpList::StartLoadingFavicon() {
392 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 388 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
393 389
394 base::ElapsedTimer timer; 390 if (icon_urls_.empty()) {
395
396 GURL url;
397 bool waiting_for_icons = true;
398 {
399 JumpListData* data = &jumplist_data_->data;
400 base::AutoLock auto_lock(data->list_lock_);
401 waiting_for_icons = !data->icon_urls_.empty();
402 if (waiting_for_icons) {
403 // Ask FaviconService if it has a favicon of a URL.
404 // When FaviconService has one, it will call OnFaviconDataAvailable().
405 url = GURL(data->icon_urls_.front().first);
406 }
407 }
408
409 if (!waiting_for_icons) {
410 // No more favicons are needed by the application JumpList. Schedule a 391 // No more favicons are needed by the application JumpList. Schedule a
411 // RunUpdateJumpList call. 392 // RunUpdateJumpList call.
412 PostRunUpdate(); 393 PostRunUpdate();
413 return; 394 return;
414 } 395 }
415 396
397 base::ElapsedTimer timer;
398
399 // Ask FaviconService if it has a favicon of a URL.
400 // When FaviconService has one, it will call OnFaviconDataAvailable().
416 favicon::FaviconService* favicon_service = 401 favicon::FaviconService* favicon_service =
417 FaviconServiceFactory::GetForProfile(profile_, 402 FaviconServiceFactory::GetForProfile(profile_,
418 ServiceAccessType::EXPLICIT_ACCESS); 403 ServiceAccessType::EXPLICIT_ACCESS);
404 // base::Unretained is safe since |this| is guaranteed to outlive
405 // cancelable_task_tracker_.
419 task_id_ = favicon_service->GetFaviconImageForPageURL( 406 task_id_ = favicon_service->GetFaviconImageForPageURL(
420 url, 407 GURL(icon_urls_.front().first),
421 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)), 408 base::Bind(&JumpList::OnFaviconDataAvailable, base::Unretained(this)),
422 &cancelable_task_tracker_); 409 &cancelable_task_tracker_);
423 410
424 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/717236 411 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/717236
425 UMA_HISTOGRAM_TIMES("WinJumplist.StartLoadingFaviconDuration", 412 UMA_HISTOGRAM_TIMES("WinJumplist.StartLoadingFaviconDuration",
426 timer.Elapsed()); 413 timer.Elapsed());
427 } 414 }
428 415
429 void JumpList::OnFaviconDataAvailable( 416 void JumpList::OnFaviconDataAvailable(
430 const favicon_base::FaviconImageResult& image_result) { 417 const favicon_base::FaviconImageResult& image_result) {
431 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 418 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
432 419
433 base::ElapsedTimer timer; 420 base::ElapsedTimer timer;
434 421
435 // If there is currently a favicon request in progress, it is now outdated, 422 // If there is currently a favicon request in progress, it is now outdated,
436 // as we have received another, so nullify the handle from the old request. 423 // as we have received another, so nullify the handle from the old request.
437 task_id_ = base::CancelableTaskTracker::kBadTaskId; 424 task_id_ = base::CancelableTaskTracker::kBadTaskId;
438 // Lock the list to set icon data and pop the url. 425
439 { 426 // Attach the received data to the ShellLinkItem object. This data will be
440 JumpListData* data = &jumplist_data_->data; 427 // decoded by the RunUpdateJumpList method.
441 base::AutoLock auto_lock(data->list_lock_); 428 if (!icon_urls_.empty()) {
442 // Attach the received data to the ShellLinkItem object. 429 if (!image_result.image.IsEmpty() && icon_urls_.front().second.get()) {
443 // This data will be decoded by the RunUpdateJumpList
444 // method.
445 if (!image_result.image.IsEmpty() && !data->icon_urls_.empty() &&
446 data->icon_urls_.front().second.get()) {
447 gfx::ImageSkia image_skia = image_result.image.AsImageSkia(); 430 gfx::ImageSkia image_skia = image_result.image.AsImageSkia();
448 image_skia.EnsureRepsForSupportedScales(); 431 image_skia.EnsureRepsForSupportedScales();
449 std::unique_ptr<gfx::ImageSkia> deep_copy(image_skia.DeepCopy()); 432 std::unique_ptr<gfx::ImageSkia> deep_copy(image_skia.DeepCopy());
450 data->icon_urls_.front().second->set_icon_image(*deep_copy); 433 icon_urls_.front().second->set_icon_image(*deep_copy);
451 } 434 }
452 435 icon_urls_.pop_front();
453 if (!data->icon_urls_.empty())
454 data->icon_urls_.pop_front();
455 } 436 }
456 437
457 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/717236 438 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/717236
458 UMA_HISTOGRAM_TIMES("WinJumplist.OnFaviconDataAvailableDuration", 439 UMA_HISTOGRAM_TIMES("WinJumplist.OnFaviconDataAvailableDuration",
459 timer.Elapsed()); 440 timer.Elapsed());
460 441
461 // Check whether we need to load more favicons. 442 // Check whether we need to load more favicons.
462 StartLoadingFavicon(); 443 StartLoadingFavicon();
463 } 444 }
464 445
465 void JumpList::OnIncognitoAvailabilityChanged() { 446 void JumpList::OnIncognitoAvailabilityChanged() {
466 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 447 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
467 448
468 bool waiting_for_icons = true;
469 {
470 JumpListData* data = &jumplist_data_->data;
471 base::AutoLock auto_lock(data->list_lock_);
472 waiting_for_icons = !data->icon_urls_.empty();
473 }
474
475 // Since neither the "Most Visited" category nor the "Recently Closed" 449 // Since neither the "Most Visited" category nor the "Recently Closed"
grt (UTC plus 2) 2017/06/12 07:15:33 i don't understand what this comment means. there'
chengx 2017/06/12 19:13:24 I've removed those obsolete comments.
476 // category changes, mark the flags so that icon files for those categories 450 // category changes, mark the flags so that icon files for those categories
477 // won't be updated later on. 451 // won't be updated later on.
478 if (!waiting_for_icons) 452 if (icon_urls_.empty())
479 PostRunUpdate(); 453 PostRunUpdate();
480 } 454 }
481 455
482 void JumpList::PostRunUpdate() { 456 void JumpList::PostRunUpdate() {
483 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 457 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
484 458
485 TRACE_EVENT0("browser", "JumpList::PostRunUpdate"); 459 TRACE_EVENT0("browser", "JumpList::PostRunUpdate");
486 if (!profile_) 460
487 return; 461 update_in_progress_ = true;
488 462
489 base::FilePath profile_dir = profile_->GetPath(); 463 base::FilePath profile_dir = profile_->GetPath();
490 464
491 // Check if incognito windows (or normal windows) are disabled by policy. 465 // Check if incognito windows (or normal windows) are disabled by policy.
492 IncognitoModePrefs::Availability incognito_availability = 466 IncognitoModePrefs::Availability incognito_availability =
493 IncognitoModePrefs::GetAvailability(profile_->GetPrefs()); 467 IncognitoModePrefs::GetAvailability(profile_->GetPrefs());
494 468
495 // Post a task to update the JumpList, which consists of 1) delete old icons, 469 // Make local copies of JumpList member variables and use them for an update.
496 // 2) create new icons, 3) notify the OS. 470 ShellLinkItemList local_most_visited_pages = most_visited_pages_;
497 update_jumplist_task_runner_->PostTask( 471 ShellLinkItemList local_recently_closed_pages = recently_closed_pages_;
498 FROM_HERE,
499 base::Bind(&JumpList::RunUpdateJumpList, this, incognito_availability,
500 app_id_, profile_dir, base::RetainedRef(jumplist_data_)));
501 472
502 // Post a task to delete JumpListIcons folder as it's no longer needed. 473 bool most_visited_should_update = most_visited_should_update_;
503 // Now we have JumpListIconsMostVisited folder and JumpListIconsRecentClosed 474 bool recently_closed_should_update = recently_closed_should_update_;
504 // folder instead.
505 base::FilePath icon_dir =
506 GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL(""));
507 475
508 delete_jumplisticons_task_runner_->PostTask( 476 auto update_results = base::MakeUnique<UpdateResults>();
509 FROM_HERE, 477 update_results->most_visited_icons_in_update_ = most_visited_icons_;
510 base::Bind(&DeleteDirectory, std::move(icon_dir), kFileDeleteLimit)); 478 update_results->recently_closed_icons_in_update = recently_closed_icons_;
511 479
512 // Post a task to delete JumpListIconsOld folder as it's no longer needed. 480 // Post a task to update the JumpList, which consists of 1) create new icons,
513 base::FilePath icon_dir_old = 481 // 2) delete old icons, 3) notify the OS.
514 GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL("Old")); 482 if (!update_jumplist_task_runner_->PostTaskAndReply(
515 483 FROM_HERE,
516 delete_jumplisticons_task_runner_->PostTask( 484 base::Bind(&JumpList::RunUpdateJumpList, app_id_, profile_dir,
517 FROM_HERE, 485 local_most_visited_pages, local_recently_closed_pages,
518 base::Bind(&DeleteDirectory, std::move(icon_dir_old), kFileDeleteLimit)); 486 most_visited_should_update, recently_closed_should_update,
487 incognito_availability, update_results.get()),
488 base::Bind(&JumpList::OnRunUpdateCompletion,
489 weak_ptr_factory_.GetWeakPtr(),
490 base::Passed(std::move(update_results))))) {
491 OnRunUpdateCompletion(base::MakeUnique<UpdateResults>());
492 }
519 } 493 }
520 494
521 void JumpList::TopSitesLoaded(history::TopSites* top_sites) { 495 void JumpList::TopSitesLoaded(history::TopSites* top_sites) {
522 } 496 }
523 497
524 void JumpList::TopSitesChanged(history::TopSites* top_sites, 498 void JumpList::TopSitesChanged(history::TopSites* top_sites,
525 ChangeReason change_reason) { 499 ChangeReason change_reason) {
526 // If we have a pending favicon request, cancel it here (it is out of date). 500 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
501
502 top_sites_has_pending_notification_ = true;
503
504 // Postpone handling this notification until a pending update completes.
505 if (update_in_progress_)
506 return;
507
508 // If we have a pending favicon request, cancel it here as it's out of date.
527 CancelPendingUpdate(); 509 CancelPendingUpdate();
528 510
529 // Initialize the one-shot timer to update the the "Most visited" category in 511 // Initialize the one-shot timer to update the JumpList in a while.
530 // a while. If there is already a request queued then cancel it and post the 512 InitializeTimerForUpdate();
531 // new request. This ensures that JumpList update of the "Most visited" 513 }
532 // category won't happen until there has been a brief quiet period, thus 514
533 // avoiding update storms. 515 void JumpList::InitializeTimerForUpdate() {
534 if (timer_most_visited_.IsRunning()) { 516 if (timer_.IsRunning()) {
535 timer_most_visited_.Reset(); 517 timer_.Reset();
536 } else { 518 } else {
537 timer_most_visited_.Start( 519 // base::Unretained is safe since |this| is guaranteed to outlive timer_.
538 FROM_HERE, kDelayForJumplistUpdate, 520 timer_.Start(FROM_HERE, kDelayForJumplistUpdate,
539 base::Bind(&JumpList::DeferredTopSitesChanged, base::Unretained(this))); 521 base::Bind(&JumpList::OnDelayTimer, base::Unretained(this)));
540 } 522 }
541 } 523 }
542 524
543 void JumpList::DeferredTopSitesChanged() { 525 void JumpList::OnDelayTimer() {
544 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 526 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
545 527
546 if (updates_to_skip_ > 0) { 528 if (updates_to_skip_ > 0) {
547 --updates_to_skip_; 529 --updates_to_skip_;
548 return; 530 return;
549 } 531 }
550 532
533 // Retrieve the recently closed URLs synchronously.
534 if (tab_restore_has_pending_notification_) {
535 tab_restore_has_pending_notification_ = false;
536 ProcessTabRestoreServiceNotification();
537 }
538
539 // If TopSites has updates, retrieve the URLs asynchronously, and on its
540 // completion, trigger favicon loading.
541 // Otherwise, call StartLoadingFavicon directly to start favicon loading.
542 if (top_sites_has_pending_notification_) {
543 top_sites_has_pending_notification_ = false;
grt (UTC plus 2) 2017/06/12 07:15:33 should this not be true until the results are rece
chengx 2017/06/12 19:13:24 Ah, I forgot to delete this line of code. Now it's
544 ProcessTopSitesNotification();
545 } else {
546 StartLoadingFavicon();
547 }
548 }
549
550 void JumpList::ProcessTopSitesNotification() {
551 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
552
551 // Opening the first tab in one session triggers a TopSite history sync. 553 // Opening the first tab in one session triggers a TopSite history sync.
552 // Delay this sync till the first tab is closed to allow the "recently closed" 554 // Delay this sync till the first tab is closed to allow the "recently closed"
553 // category from last session to stay longer. 555 // category from last session to stay longer.
554 if (!has_tab_closed_) 556 if (!has_tab_closed_)
555 return; 557 return;
556 558
557 scoped_refptr<history::TopSites> top_sites = 559 scoped_refptr<history::TopSites> top_sites =
558 TopSitesFactory::GetForProfile(profile_); 560 TopSitesFactory::GetForProfile(profile_);
559 if (top_sites) { 561 if (top_sites) {
560 top_sites->GetMostVisitedURLs( 562 top_sites->GetMostVisitedURLs(
561 base::Bind(&JumpList::OnMostVisitedURLsAvailable, 563 base::Bind(&JumpList::OnMostVisitedURLsAvailable,
562 weak_ptr_factory_.GetWeakPtr()), 564 weak_ptr_factory_.GetWeakPtr()),
563 false); 565 false);
564 } 566 }
565 } 567 }
566 568
567 void JumpList::DeferredTabRestoreServiceChanged() { 569 void JumpList::ProcessTabRestoreServiceNotification() {
568 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); 570 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
569 571
570 if (updates_to_skip_ > 0) {
571 --updates_to_skip_;
572 return;
573 }
574
575 // Force a TopSite history sync when closing a first tab in one session.
576 if (!has_tab_closed_) {
577 has_tab_closed_ = true;
578 scoped_refptr<history::TopSites> top_sites =
579 TopSitesFactory::GetForProfile(profile_);
580 if (top_sites)
581 top_sites->SyncWithHistory();
582 }
583
584 // Create a list of ShellLinkItems from the "Recently Closed" pages. 572 // Create a list of ShellLinkItems from the "Recently Closed" pages.
585 // As noted above, we create a ShellLinkItem objects with the following 573 // As noted above, we create a ShellLinkItem objects with the following
586 // parameters. 574 // parameters.
587 // * arguments 575 // * arguments
588 // The last URL of the tab object. 576 // The last URL of the tab object.
589 // * title 577 // * title
590 // The title of the last URL. 578 // The title of the last URL.
591 // * icon 579 // * icon
592 // An empty string. This value is to be updated in OnFaviconDataAvailable(). 580 // An empty string. This value is to be updated in OnFaviconDataAvailable().
593 581
594 sessions::TabRestoreService* tab_restore_service = 582 sessions::TabRestoreService* tab_restore_service =
595 TabRestoreServiceFactory::GetForProfile(profile_); 583 TabRestoreServiceFactory::GetForProfile(profile_);
596 584
597 { 585 recently_closed_pages_.clear();
598 JumpListData* data = &jumplist_data_->data;
599 base::AutoLock auto_lock(data->list_lock_);
600 data->recently_closed_pages_.clear();
601 586
602 for (const auto& entry : tab_restore_service->entries()) { 587 for (const auto& entry : tab_restore_service->entries()) {
603 if (data->recently_closed_pages_.size() >= kRecentlyClosedItems) 588 if (recently_closed_pages_.size() >= kRecentlyClosedItems)
589 break;
590 switch (entry->type) {
591 case sessions::TabRestoreService::TAB:
592 AddTab(static_cast<const sessions::TabRestoreService::Tab&>(*entry),
593 kRecentlyClosedItems);
604 break; 594 break;
605 switch (entry->type) { 595 case sessions::TabRestoreService::WINDOW:
606 case sessions::TabRestoreService::TAB: 596 AddWindow(
607 AddTab(static_cast<const sessions::TabRestoreService::Tab&>(*entry), 597 static_cast<const sessions::TabRestoreService::Window&>(*entry),
608 kRecentlyClosedItems, data); 598 kRecentlyClosedItems);
609 break; 599 break;
610 case sessions::TabRestoreService::WINDOW:
611 AddWindow(
612 static_cast<const sessions::TabRestoreService::Window&>(*entry),
613 kRecentlyClosedItems, data);
614 break;
615 }
616 } 600 }
617
618 data->recently_closed_pages_have_updates_ = true;
619 } 601 }
620 602
621 // Send a query that retrieves the first favicon. 603 recently_closed_should_update_ = true;
622 StartLoadingFavicon(); 604
605 // Force a TopSite history sync when closing a first tab in one session.
606 if (!has_tab_closed_) {
607 has_tab_closed_ = true;
608 scoped_refptr<history::TopSites> top_sites =
609 TopSitesFactory::GetForProfile(profile_);
610 if (top_sites)
611 top_sites->SyncWithHistory();
612 }
623 } 613 }
624 614
615 // static
625 void JumpList::DeleteIconFiles(const base::FilePath& icon_dir, 616 void JumpList::DeleteIconFiles(const base::FilePath& icon_dir,
626 JumpListCategory category) { 617 URLIconCache* icon_cache) {
627 base::flat_map<std::string, base::FilePath>* source_map = nullptr;
628 switch (category) {
629 case JumpListCategory::kMostVisited:
630 source_map = &most_visited_icons_;
631 break;
632 case JumpListCategory::kRecentlyClosed:
633 source_map = &recently_closed_icons_;
634 break;
635 }
636
637 // Put all cached icon file paths into a set. 618 // Put all cached icon file paths into a set.
638 base::flat_set<base::FilePath> cached_files; 619 base::flat_set<base::FilePath> cached_files;
639 cached_files.reserve(source_map->size()); 620 cached_files.reserve(icon_cache->size());
640 621
641 for (const auto& url_path_pair : *source_map) 622 for (const auto& url_path_pair : *icon_cache)
642 cached_files.insert(url_path_pair.second); 623 cached_files.insert(url_path_pair.second);
643 624
644 DeleteNonCachedFiles(icon_dir, cached_files); 625 DeleteNonCachedFiles(icon_dir, cached_files);
645 } 626 }
646 627
628 // static
647 int JumpList::CreateIconFiles(const base::FilePath& icon_dir, 629 int JumpList::CreateIconFiles(const base::FilePath& icon_dir,
648 const ShellLinkItemList& item_list, 630 const ShellLinkItemList& item_list,
649 size_t max_items, 631 size_t max_items,
650 JumpListCategory category) { 632 URLIconCache* icon_cache) {
651 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407. 633 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407.
652 SCOPED_UMA_HISTOGRAM_TIMER("WinJumplist.CreateIconFilesDuration"); 634 SCOPED_UMA_HISTOGRAM_TIMER("WinJumplist.CreateIconFilesDuration");
653 635
654 int icons_created = 0; 636 int icons_created = 0;
655 637
656 // Reuse icons for urls that were already present in the jumplist for this 638 // Reuse icons for urls that already present in the current JumpList.
657 // category. 639 URLIconCache updated_map;
658
659 base::flat_map<std::string, base::FilePath>* source_map = nullptr;
660 switch (category) {
661 case JumpListCategory::kMostVisited:
662 source_map = &most_visited_icons_;
663 break;
664 case JumpListCategory::kRecentlyClosed:
665 source_map = &recently_closed_icons_;
666 break;
667 }
668
669 base::flat_map<std::string, base::FilePath> updated_map;
670
671 for (ShellLinkItemList::const_iterator iter = item_list.begin(); 640 for (ShellLinkItemList::const_iterator iter = item_list.begin();
672 iter != item_list.end() && max_items > 0; ++iter, --max_items) { 641 iter != item_list.end() && max_items > 0; ++iter, --max_items) {
673 ShellLinkItem* item = iter->get(); 642 ShellLinkItem* item = iter->get();
674 auto cache_iter = source_map->find(item->url()); 643 auto cache_iter = icon_cache->find(item->url());
675 if (cache_iter != source_map->end()) { 644 if (cache_iter != icon_cache->end()) {
676 item->set_icon(cache_iter->second.value(), 0); 645 item->set_icon(cache_iter->second.value(), 0);
677 updated_map[item->url()] = cache_iter->second; 646 updated_map[item->url()] = cache_iter->second;
678 } else { 647 } else {
679 base::FilePath icon_path; 648 base::FilePath icon_path;
680 if (CreateIconFile(item->icon_image(), icon_dir, &icon_path)) { 649 if (CreateIconFile(item->icon_image(), icon_dir, &icon_path)) {
681 ++icons_created; 650 ++icons_created;
682 item->set_icon(icon_path.value(), 0); 651 item->set_icon(icon_path.value(), 0);
683 updated_map[item->url()] = icon_path; 652 updated_map[item->url()] = icon_path;
684 } 653 }
685 } 654 }
686 } 655 }
687 source_map->swap(updated_map); 656 icon_cache->swap(updated_map);
688 657
689 return icons_created; 658 return icons_created;
690 } 659 }
691 660
661 // static
692 int JumpList::UpdateIconFiles(const base::FilePath& icon_dir, 662 int JumpList::UpdateIconFiles(const base::FilePath& icon_dir,
693 const ShellLinkItemList& page_list, 663 const ShellLinkItemList& page_list,
694 size_t slot_limit, 664 size_t slot_limit,
695 JumpListCategory category) { 665 URLIconCache* icon_cache) {
696 int icons_created = 0; 666 int icons_created = 0;
697 667
698 // Maximum number of icon files that each JumpList icon folder may hold, which
699 // is set to 2 times the normal amount.
700 size_t icon_limit =
701 2 * ((category == JumpListCategory::kMostVisited) ? kMostVisitedItems
702 : kRecentlyClosedItems);
703
704 // Clear the JumpList icon folder at |icon_dir| and the cache when 668 // Clear the JumpList icon folder at |icon_dir| and the cache when
705 // 1) "Most visited" category updates for the 1st time after Chrome is 669 // 1) |icon_cache| is empty. This happens when "Most visited" or "Recently
706 // launched. This actually happens right after Chrome is launched. 670 // closed" category updates for the 1st time after Chrome is launched.
707 // 2) "Recently closed" category updates for the 1st time after Chrome is 671 // 2) The number of icons in |icon_dir| has exceeded the limit.
708 // launched. 672 if (icon_cache->empty() || FilesExceedLimitInDir(icon_dir, slot_limit * 2)) {
709 // 3) The number of icons in |icon_dir| has exceeded the limit.
710 if ((category == JumpListCategory::kMostVisited &&
711 most_visited_icons_.empty()) ||
712 (category == JumpListCategory::kRecentlyClosed &&
713 recently_closed_icons_.empty()) ||
714 FilesExceedLimitInDir(icon_dir, icon_limit)) {
715 DeleteDirectoryContentAndLogRuntime(icon_dir, kFileDeleteLimit); 673 DeleteDirectoryContentAndLogRuntime(icon_dir, kFileDeleteLimit);
716 most_visited_icons_.clear(); 674 icon_cache->clear();
717 recently_closed_icons_.clear();
718 // Create new icons only when the directory exists and is empty. 675 // Create new icons only when the directory exists and is empty.
719 if (base::CreateDirectory(icon_dir) && base::IsDirectoryEmpty(icon_dir)) 676 if (base::CreateDirectory(icon_dir) && base::IsDirectoryEmpty(icon_dir))
720 icons_created += 677 icons_created +=
721 CreateIconFiles(icon_dir, page_list, slot_limit, category); 678 CreateIconFiles(icon_dir, page_list, slot_limit, icon_cache);
722 } else if (base::CreateDirectory(icon_dir)) { 679 } else if (base::CreateDirectory(icon_dir)) {
723 icons_created += CreateIconFiles(icon_dir, page_list, slot_limit, category); 680 icons_created +=
724 DeleteIconFiles(icon_dir, category); 681 CreateIconFiles(icon_dir, page_list, slot_limit, icon_cache);
682 DeleteIconFiles(icon_dir, icon_cache);
725 } 683 }
726 684
727 return icons_created; 685 return icons_created;
728 } 686 }
729 687
730 bool JumpList::UpdateJumpList( 688 // static
689 void JumpList::RunUpdateJumpList(
731 const base::string16& app_id, 690 const base::string16& app_id,
732 const base::FilePath& profile_dir, 691 const base::FilePath& profile_dir,
733 const ShellLinkItemList& most_visited_pages, 692 const ShellLinkItemList& most_visited_pages,
734 const ShellLinkItemList& recently_closed_pages, 693 const ShellLinkItemList& recently_closed_pages,
735 bool most_visited_pages_have_updates, 694 bool most_visited_should_update,
736 bool recently_closed_pages_have_updates, 695 bool recently_closed_should_update,
737 IncognitoModePrefs::Availability incognito_availability) { 696 IncognitoModePrefs::Availability incognito_availability,
697 UpdateResults* update_results) {
738 if (!JumpListUpdater::IsEnabled()) 698 if (!JumpListUpdater::IsEnabled())
739 return true; 699 return;
700
701 DCHECK(update_results);
740 702
741 JumpListUpdater jumplist_updater(app_id); 703 JumpListUpdater jumplist_updater(app_id);
742 704
743 base::ElapsedTimer begin_update_timer; 705 base::ElapsedTimer begin_update_timer;
744 706
745 if (!jumplist_updater.BeginUpdate()) 707 if (!jumplist_updater.BeginUpdate())
746 return false; 708 return;
747 709
748 // Discard this JumpList update if JumpListUpdater::BeginUpdate takes longer 710 // Discard this JumpList update if JumpListUpdater::BeginUpdate takes longer
749 // than the maximum allowed time, as it's very likely the following update 711 // than the maximum allowed time, as it's very likely the following update
750 // steps will also take a long time. As we've not updated the icons on the 712 // steps will also take a long time. As we've not updated the icons on the
751 // disk, discarding this update wont't affect the current JumpList used by OS. 713 // disk, discarding this update wont't affect the current JumpList used by OS.
752 if (begin_update_timer.Elapsed() >= kTimeOutForJumplistBeginUpdate) { 714 if (begin_update_timer.Elapsed() >= kTimeOutForJumplistBeginUpdate) {
753 updates_to_skip_ = kUpdatesToSkipUnderHeavyLoad; 715 update_results->update_timeout_ = true;
754 return false; 716 return;
755 } 717 }
756 718
757 // Record the desired number of icons created in this JumpList update. 719 // Record the desired number of icons created in this JumpList update.
758 int icons_created = 0; 720 int icons_created = 0;
759 721
760 // Update the icons for "Most Visisted" category of the JumpList if needed. 722 // Update the icons for "Most Visisted" category of the JumpList if needed.
761 if (most_visited_pages_have_updates) { 723 if (most_visited_should_update) {
762 base::FilePath icon_dir_most_visited = GenerateJumplistIconDirName( 724 base::FilePath icon_dir_most_visited = GenerateJumplistIconDirName(
763 profile_dir, FILE_PATH_LITERAL("MostVisited")); 725 profile_dir, FILE_PATH_LITERAL("MostVisited"));
764 726
765 icons_created += 727 icons_created += UpdateIconFiles(
766 UpdateIconFiles(icon_dir_most_visited, most_visited_pages, 728 icon_dir_most_visited, most_visited_pages, kMostVisitedItems,
767 kMostVisitedItems, JumpListCategory::kMostVisited); 729 &update_results->most_visited_icons_in_update_);
768 } 730 }
769 731
770 // Update the icons for "Recently Closed" category of the JumpList if needed. 732 // Update the icons for "Recently Closed" category of the JumpList if needed.
771 if (recently_closed_pages_have_updates) { 733 if (recently_closed_should_update) {
772 base::FilePath icon_dir_recent_closed = GenerateJumplistIconDirName( 734 base::FilePath icon_dir_recent_closed = GenerateJumplistIconDirName(
773 profile_dir, FILE_PATH_LITERAL("RecentClosed")); 735 profile_dir, FILE_PATH_LITERAL("RecentClosed"));
774 736
775 icons_created += UpdateIconFiles( 737 icons_created += UpdateIconFiles(
776 icon_dir_recent_closed, recently_closed_pages, kRecentlyClosedItems, 738 icon_dir_recent_closed, recently_closed_pages, kRecentlyClosedItems,
777 JumpListCategory::kRecentlyClosed); 739 &update_results->recently_closed_icons_in_update);
778 } 740 }
779 741
780 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407. 742 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407.
781 UMA_HISTOGRAM_COUNTS_100("WinJumplist.CreateIconFilesCount", icons_created); 743 UMA_HISTOGRAM_COUNTS_100("WinJumplist.CreateIconFilesCount", icons_created);
782 744
783 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407. 745 // TODO(chengx): Remove the UMA histogram after fixing http://crbug.com/40407.
784 SCOPED_UMA_HISTOGRAM_TIMER("WinJumplist.UpdateJumpListDuration"); 746 SCOPED_UMA_HISTOGRAM_TIMER("WinJumplist.UpdateJumpListDuration");
785 747
786 base::ElapsedTimer add_custom_category_timer; 748 base::ElapsedTimer add_custom_category_timer;
787 749
788 // Update the "Most Visited" category of the JumpList if it exists. 750 // Update the "Most Visited" category of the JumpList if it exists.
789 // This update request is applied into the JumpList when we commit this 751 // This update request is applied into the JumpList when we commit this
790 // transaction. 752 // transaction.
791 if (!jumplist_updater.AddCustomCategory( 753 if (!jumplist_updater.AddCustomCategory(
792 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED), 754 l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED),
793 most_visited_pages, kMostVisitedItems)) { 755 most_visited_pages, kMostVisitedItems)) {
794 return false; 756 return;
795 } 757 }
796 758
797 // Update the "Recently Closed" category of the JumpList. 759 // Update the "Recently Closed" category of the JumpList.
798 if (!jumplist_updater.AddCustomCategory( 760 if (!jumplist_updater.AddCustomCategory(
799 l10n_util::GetStringUTF16(IDS_RECENTLY_CLOSED), recently_closed_pages, 761 l10n_util::GetStringUTF16(IDS_RECENTLY_CLOSED), recently_closed_pages,
800 kRecentlyClosedItems)) { 762 kRecentlyClosedItems)) {
801 return false; 763 return;
802 } 764 }
803 765
804 // If JumpListUpdater::AddCustomCategory or JumpListUpdater::CommitUpdate 766 // If JumpListUpdater::AddCustomCategory or JumpListUpdater::CommitUpdate
805 // takes longer than the maximum allowed time, skip the next 767 // takes longer than the maximum allowed time, skip the next
806 // |kUpdatesToSkipUnderHeavyLoad| updates. This update should be finished 768 // |kUpdatesToSkipUnderHeavyLoad| updates. This update should be finished
807 // because we've already updated the icons on the disk. If discarding this 769 // because we've already updated the icons on the disk. If discarding this
808 // update from here, some items in the current JumpList may not have icons 770 // update from here, some items in the current JumpList may not have icons
809 // as they've been delete from the disk. In this case, the background color of 771 // as they've been delete from the disk. In this case, the background color of
810 // the JumpList panel is used instead, which doesn't look nice. 772 // the JumpList panel is used instead, which doesn't look nice.
811 773
812 if (add_custom_category_timer.Elapsed() >= kTimeOutForAddCustomCategory) 774 if (add_custom_category_timer.Elapsed() >= kTimeOutForAddCustomCategory)
813 updates_to_skip_ = kUpdatesToSkipUnderHeavyLoad; 775 update_results->update_timeout_ = true;
814 776
815 // Update the "Tasks" category of the JumpList. 777 // Update the "Tasks" category of the JumpList.
816 if (!UpdateTaskCategory(&jumplist_updater, incognito_availability)) 778 if (!UpdateTaskCategory(&jumplist_updater, incognito_availability))
817 return false; 779 return;
818 780
819 base::ElapsedTimer commit_update_timer; 781 base::ElapsedTimer commit_update_timer;
820 782
821 // Commit this transaction and send the updated JumpList to Windows. 783 // Commit this transaction and send the updated JumpList to Windows.
822 bool commit_result = jumplist_updater.CommitUpdate(); 784 if (jumplist_updater.CommitUpdate())
785 update_results->update_success_ = true;
823 786
824 if (commit_update_timer.Elapsed() >= kTimeOutForJumplistCommitUpdate) 787 if (commit_update_timer.Elapsed() >= kTimeOutForJumplistCommitUpdate)
788 update_results->update_timeout_ = true;
789 }
790
791 void JumpList::OnRunUpdateCompletion(
792 std::unique_ptr<UpdateResults> update_results) {
793 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
794
795 // Update JumpList member variables based on the results from the update run
796 // just finished.
797 if (update_results->update_timeout_)
825 updates_to_skip_ = kUpdatesToSkipUnderHeavyLoad; 798 updates_to_skip_ = kUpdatesToSkipUnderHeavyLoad;
826 799
827 return commit_result; 800 if (update_results->update_success_) {
828 } 801 most_visited_icons_.swap(update_results->most_visited_icons_in_update_);
829 802 recently_closed_icons_.swap(
830 void JumpList::RunUpdateJumpList( 803 update_results->recently_closed_icons_in_update);
831 IncognitoModePrefs::Availability incognito_availability, 804 most_visited_should_update_ = false;
832 const base::string16& app_id, 805 recently_closed_should_update_ = false;
833 const base::FilePath& profile_dir,
834 base::RefCountedData<JumpListData>* ref_counted_data) {
835 JumpListData* data = &ref_counted_data->data;
836 ShellLinkItemList local_most_visited_pages;
837 ShellLinkItemList local_recently_closed_pages;
838 bool most_visited_pages_have_updates;
839 bool recently_closed_pages_have_updates;
840
841 {
842 base::AutoLock auto_lock(data->list_lock_);
843 // Make sure we are not out of date: if icon_urls_ is not empty, then
844 // another notification has been received since we processed this one
845 if (!data->icon_urls_.empty())
846 return;
847
848 // Make local copies of lists and flags so we can release the lock.
849 local_most_visited_pages = data->most_visited_pages_;
850 local_recently_closed_pages = data->recently_closed_pages_;
851
852 most_visited_pages_have_updates = data->most_visited_pages_have_updates_;
853 recently_closed_pages_have_updates =
854 data->recently_closed_pages_have_updates_;
855
856 // Clear the flags to reflect that we'll take actions on these updates.
857 data->most_visited_pages_have_updates_ = false;
858 data->recently_closed_pages_have_updates_ = false;
859 } 806 }
860 807
861 if (!most_visited_pages_have_updates && !recently_closed_pages_have_updates) 808 update_in_progress_ = false;
862 return;
863 809
864 // Update the application JumpList. If it fails, reset the flags to true if 810 // If there is any new notification during the update run just finished, start
865 // they were so that the corresponding JumpList categories will be tried to 811 // another JumpList update.
866 // update again in the next run. 812 // Otherwise, post a task to delete the JumpListIcons and JumpListIconsOld
867 if (!UpdateJumpList( 813 // folders as they are no longer needed. Now we have the
868 app_id, profile_dir, local_most_visited_pages, 814 // JumpListIcons{MostVisited, RecentClosed} folders instead.
869 local_recently_closed_pages, most_visited_pages_have_updates, 815 if (top_sites_has_pending_notification_ ||
870 recently_closed_pages_have_updates, incognito_availability)) { 816 tab_restore_has_pending_notification_) {
871 base::AutoLock auto_lock(data->list_lock_); 817 InitializeTimerForUpdate();
872 if (most_visited_pages_have_updates) 818 } else {
873 data->most_visited_pages_have_updates_ = true; 819 base::FilePath profile_dir = profile_->GetPath();
874 if (recently_closed_pages_have_updates) 820 base::FilePath icon_dir =
875 data->recently_closed_pages_have_updates_ = true; 821 GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL(""));
822 delete_jumplisticons_task_runner_->PostTask(
823 FROM_HERE,
824 base::Bind(&DeleteDirectory, std::move(icon_dir), kFileDeleteLimit));
825
826 base::FilePath icon_dir_old =
827 GenerateJumplistIconDirName(profile_dir, FILE_PATH_LITERAL("Old"));
828 delete_jumplisticons_task_runner_->PostTask(
829 FROM_HERE, base::Bind(&DeleteDirectory, std::move(icon_dir_old),
830 kFileDeleteLimit));
876 } 831 }
877 } 832 }
OLDNEW
« chrome/browser/win/jumplist.h ('K') | « chrome/browser/win/jumplist.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698