diff options
Diffstat (limited to 'chrome/browser/ui/webui')
16 files changed, 3 insertions, 1977 deletions
diff --git a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc index 6ebbae1..7b6d615 100644 --- a/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc +++ b/chrome/browser/ui/webui/chrome_web_ui_controller_factory.cc @@ -25,8 +25,6 @@ #include "chrome/browser/ui/webui/crashes_ui.h" #include "chrome/browser/ui/webui/device_log_ui.h" #include "chrome/browser/ui/webui/domain_reliability_internals_ui.h" -#include "chrome/browser/ui/webui/downloads_ui.h" -#include "chrome/browser/ui/webui/downloads_util.h" #include "chrome/browser/ui/webui/flags_ui.h" #include "chrome/browser/ui/webui/flash_ui.h" #include "chrome/browser/ui/webui/gcm_internals_ui.h" @@ -396,11 +394,8 @@ WebUIFactoryFunction GetWebUIFactoryFunction(WebUI* web_ui, if (url.host() == chrome::kChromeUIBookmarksHost) return &NewWebUI<BookmarksUI>; // Downloads list on Android uses the built-in download manager. - if (url.host() == chrome::kChromeUIDownloadsHost) { - if (MdDownloadsEnabled()) - return &NewWebUI<MdDownloadsUI>; - return &NewWebUI<DownloadsUI>; - } + if (url.host() == chrome::kChromeUIDownloadsHost) + return &NewWebUI<MdDownloadsUI>; // Help is implemented with native UI elements on Android. if (url.host() == chrome::kChromeUIHelpFrameHost) return &NewWebUI<HelpUI>; @@ -780,7 +775,7 @@ base::RefCountedMemory* ChromeWebUIControllerFactory::GetFaviconResourceBytes( // Android uses the native download manager. if (page_url.host() == chrome::kChromeUIDownloadsHost) - return DownloadsUI::GetFaviconResourceBytes(scale_factor); + return MdDownloadsUI::GetFaviconResourceBytes(scale_factor); // Android doesn't use the Options pages. if (page_url.host() == chrome::kChromeUISettingsHost || diff --git a/chrome/browser/ui/webui/downloads_dom_handler.cc b/chrome/browser/ui/webui/downloads_dom_handler.cc deleted file mode 100644 index e04a706..0000000 --- a/chrome/browser/ui/webui/downloads_dom_handler.cc +++ /dev/null @@ -1,722 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_dom_handler.h" - -#include <stddef.h> - -#include <algorithm> -#include <functional> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/i18n/rtl.h" -#include "base/i18n/time_formatting.h" -#include "base/logging.h" -#include "base/memory/singleton.h" -#include "base/metrics/field_trial.h" -#include "base/metrics/histogram.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_piece.h" -#include "base/strings/utf_string_conversions.h" -#include "base/supports_user_data.h" -#include "base/threading/thread.h" -#include "base/value_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/download/download_crx_util.h" -#include "chrome/browser/download/download_danger_prompt.h" -#include "chrome/browser/download/download_history.h" -#include "chrome/browser/download/download_item_model.h" -#include "chrome/browser/download/download_prefs.h" -#include "chrome/browser/download/download_query.h" -#include "chrome/browser/download/download_service.h" -#include "chrome/browser/download/download_service_factory.h" -#include "chrome/browser/download/drag_download_item.h" -#include "chrome/browser/extensions/api/downloads/downloads_api.h" -#include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/platform_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/fileicon_source.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/browser_thread.h" -#include "content/public/browser/download_item.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/user_metrics.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui.h" -#include "extensions/browser/extension_system.h" -#include "net/base/filename_util.h" -#include "third_party/icu/source/i18n/unicode/datefmt.h" -#include "ui/base/l10n/time_format.h" -#include "ui/gfx/image/image.h" - -using base::UserMetricsAction; -using content::BrowserContext; -using content::BrowserThread; - -namespace { - -// Maximum number of downloads to show. TODO(glen): Remove this and instead -// stuff the downloads down the pipe slowly. -size_t kMaxNumberOfDownloads = 150; - -enum DownloadsDOMEvent { - DOWNLOADS_DOM_EVENT_GET_DOWNLOADS = 0, - DOWNLOADS_DOM_EVENT_OPEN_FILE = 1, - DOWNLOADS_DOM_EVENT_DRAG = 2, - DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS = 3, - DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS = 4, - DOWNLOADS_DOM_EVENT_SHOW = 5, - DOWNLOADS_DOM_EVENT_PAUSE = 6, - DOWNLOADS_DOM_EVENT_REMOVE = 7, - DOWNLOADS_DOM_EVENT_CANCEL = 8, - DOWNLOADS_DOM_EVENT_CLEAR_ALL = 9, - DOWNLOADS_DOM_EVENT_OPEN_FOLDER = 10, - DOWNLOADS_DOM_EVENT_RESUME = 11, - DOWNLOADS_DOM_EVENT_MAX -}; - -void CountDownloadsDOMEvents(DownloadsDOMEvent event) { - UMA_HISTOGRAM_ENUMERATION("Download.DOMEvent", - event, - DOWNLOADS_DOM_EVENT_MAX); -} - -// Returns a string constant to be used as the |danger_type| value in -// CreateDownloadItemValue(). Only return strings for DANGEROUS_FILE, -// DANGEROUS_URL, DANGEROUS_CONTENT, and UNCOMMON_CONTENT because the -// |danger_type| value is only defined if the value of |state| is |DANGEROUS|. -const char* GetDangerTypeString(content::DownloadDangerType danger_type) { - switch (danger_type) { - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: - return "DANGEROUS_FILE"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: - return "DANGEROUS_URL"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: - return "DANGEROUS_CONTENT"; - case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: - return "UNCOMMON_CONTENT"; - case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: - return "DANGEROUS_HOST"; - case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: - return "POTENTIALLY_UNWANTED"; - default: - // Don't return a danger type string if it is NOT_DANGEROUS or - // MAYBE_DANGEROUS_CONTENT. - NOTREACHED(); - return ""; - } -} - -// Returns a JSON dictionary containing some of the attributes of |download|. -// The JSON dictionary will also have a field "id" set to |id|, and a field -// "otr" set to |incognito|. -base::DictionaryValue* CreateDownloadItemValue( - content::DownloadItem* download_item, - bool incognito) { - // TODO(asanka): Move towards using download_model here for getting status and - // progress. The difference currently only matters to Drive downloads and - // those don't show up on the downloads page, but should. - DownloadItemModel download_model(download_item); - - // The items which are to be written into file_value are also described in - // chrome/browser/resources/downloads/downloads.js in @typedef for - // BackendDownloadObject. Please update it whenever you add or remove - // any keys in file_value. - base::DictionaryValue* file_value = new base::DictionaryValue(); - - file_value->SetInteger( - "started", static_cast<int>(download_item->GetStartTime().ToTimeT())); - file_value->SetString( - "since_string", ui::TimeFormat::RelativeDate( - download_item->GetStartTime(), NULL)); - - base::Time start_time = download_item->GetStartTime(); - base::string16 date_string = base::TimeFormatShortDate(start_time); - file_value->SetString("date_string", date_string); - - file_value->SetString("id", base::Uint64ToString(download_item->GetId())); - - base::FilePath download_path(download_item->GetTargetFilePath()); - file_value->Set("file_path", base::CreateFilePathValue(download_path)); - file_value->SetString("file_url", - net::FilePathToFileURL(download_path).spec()); - - extensions::DownloadedByExtension* by_ext = - extensions::DownloadedByExtension::Get(download_item); - std::string by_ext_id; - std::string by_ext_name; - if (by_ext) { - by_ext_id = by_ext->id(); - // TODO(dbeam): why doesn't DownloadsByExtension::name() return a string16? - by_ext_name = by_ext->name(); - - // Lookup the extension's current name() in case the user changed their - // language. This won't work if the extension was uninstalled, so the name - // might be the wrong language. - bool include_disabled = true; - const extensions::Extension* extension = extensions::ExtensionSystem::Get( - Profile::FromBrowserContext(download_item->GetBrowserContext()))-> - extension_service()->GetExtensionById(by_ext->id(), include_disabled); - if (extension) - file_value->SetString("by_ext_name", extension->name()); - } - file_value->SetString("by_ext_id", by_ext_id); - file_value->SetString("by_ext_name", by_ext_name); - - // Keep file names as LTR. - base::string16 file_name = - download_item->GetFileNameToReportUser().LossyDisplayName(); - file_name = base::i18n::GetDisplayStringInLTRDirectionality(file_name); - file_value->SetString("file_name", file_name); - file_value->SetString("url", download_item->GetURL().spec()); - file_value->SetBoolean("otr", incognito); - file_value->SetInteger("total", static_cast<int>( - download_item->GetTotalBytes())); - file_value->SetBoolean("file_externally_removed", - download_item->GetFileExternallyRemoved()); - file_value->SetBoolean("resume", download_item->CanResume()); - - const char* danger_type = ""; - base::string16 last_reason_text; - // -2 is invalid, -1 means indeterminate, and 0-100 are in-progress. - int percent = -2; - base::string16 progress_status_text; - bool retry = false; - const char* state = nullptr; - - switch (download_item->GetState()) { - case content::DownloadItem::IN_PROGRESS: { - if (download_item->IsDangerous()) { - state = "DANGEROUS"; - // These are the only danger states that the UI is equipped to handle. - DCHECK(download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE || - download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL || - download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT || - download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT || - download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST || - download_item->GetDangerType() == - content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED); - danger_type = GetDangerTypeString(download_item->GetDangerType()); - } else if (download_item->IsPaused()) { - state = "PAUSED"; - } else { - state = "IN_PROGRESS"; - } - progress_status_text = download_model.GetTabProgressStatusText(); - percent = std::max(0, download_item->PercentComplete()); - break; - } - - case content::DownloadItem::INTERRUPTED: - state = "INTERRUPTED"; - progress_status_text = download_model.GetTabProgressStatusText(); - - if (download_item->CanResume()) - percent = download_item->PercentComplete(); - - last_reason_text = download_model.GetInterruptReasonText(); - if (content::DOWNLOAD_INTERRUPT_REASON_CRASH == - download_item->GetLastReason() && !download_item->CanResume()) { - retry = true; - } - break; - - case content::DownloadItem::CANCELLED: - state = "CANCELLED"; - retry = true; - break; - - case content::DownloadItem::COMPLETE: - DCHECK(!download_item->IsDangerous()); - state = "COMPLETE"; - break; - - case content::DownloadItem::MAX_DOWNLOAD_STATE: - NOTREACHED(); - } - - DCHECK(state); - - file_value->SetString("danger_type", danger_type); - file_value->SetString("last_reason_text", last_reason_text); - file_value->SetInteger("percent", percent); - file_value->SetString("progress_status_text", progress_status_text); - file_value->SetBoolean("retry", retry); - file_value->SetString("state", state); - - return file_value; -} - -// Filters out extension downloads and downloads that don't have a filename yet. -bool IsDownloadDisplayable(const content::DownloadItem& item) { - return !download_crx_util::IsExtensionDownload(item) && - !item.IsTemporary() && - !item.GetFileNameToReportUser().empty() && - !item.GetTargetFilePath().empty() && - DownloadItemModel( - const_cast<content::DownloadItem*>(&item)).ShouldShowInShelf(); -} - -} // namespace - -DownloadsDOMHandler::DownloadsDOMHandler( - content::DownloadManager* download_manager) - : download_manager_(download_manager), - update_scheduled_(false), - weak_ptr_factory_(this) { - // Create our fileicon data source. - Profile* profile = Profile::FromBrowserContext( - download_manager->GetBrowserContext()); - content::URLDataSource::Add(profile, new FileIconSource()); -} - -DownloadsDOMHandler::~DownloadsDOMHandler() { - FinalizeRemovals(); -} - -// DownloadsDOMHandler, public: ----------------------------------------------- - -void DownloadsDOMHandler::RegisterMessages() { - web_ui()->RegisterMessageCallback("getDownloads", - base::Bind(&DownloadsDOMHandler::HandleGetDownloads, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("openFile", - base::Bind(&DownloadsDOMHandler::HandleOpenFile, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("drag", - base::Bind(&DownloadsDOMHandler::HandleDrag, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("saveDangerous", - base::Bind(&DownloadsDOMHandler::HandleSaveDangerous, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("discardDangerous", - base::Bind(&DownloadsDOMHandler::HandleDiscardDangerous, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("show", - base::Bind(&DownloadsDOMHandler::HandleShow, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("pause", - base::Bind(&DownloadsDOMHandler::HandlePause, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("resume", - base::Bind(&DownloadsDOMHandler::HandleResume, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("remove", - base::Bind(&DownloadsDOMHandler::HandleRemove, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("undo", - base::Bind(&DownloadsDOMHandler::HandleUndo, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("cancel", - base::Bind(&DownloadsDOMHandler::HandleCancel, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("clearAll", - base::Bind(&DownloadsDOMHandler::HandleClearAll, - weak_ptr_factory_.GetWeakPtr())); - web_ui()->RegisterMessageCallback("openDownloadsFolder", - base::Bind(&DownloadsDOMHandler::HandleOpenDownloadsFolder, - weak_ptr_factory_.GetWeakPtr())); -} - -void DownloadsDOMHandler::OnDownloadCreated( - content::DownloadManager* manager, content::DownloadItem* download_item) { - if (IsDownloadDisplayable(*download_item)) - ScheduleSendCurrentDownloads(); - else - new_downloads_.insert(download_item->GetId()); -} - -void DownloadsDOMHandler::OnDownloadUpdated( - content::DownloadManager* manager, - content::DownloadItem* download_item) { - if (update_scheduled_) - return; - - bool showing_new_item = false; - - if (new_downloads_.count(download_item->GetId())) { - // A new download (that the page doesn't know about yet) has been updated. - if (!IsDownloadDisplayable(*download_item)) { - // Item isn't ready to be displayed yet. Wait until it is. - return; - } - - new_downloads_.erase(download_item->GetId()); - showing_new_item = true; - } - - if (showing_new_item || DownloadItemModel(download_item).IsBeingRevived() || - !IsDownloadDisplayable(*download_item)) { - // A download will be shown or hidden by this update. Resend the list. - ScheduleSendCurrentDownloads(); - return; - } - - if (search_terms_ && !search_terms_->empty()) { - // Don't CallUpdateItem() if download_item doesn't match - // search_terms_. - // TODO(benjhayden): Consider splitting MatchesQuery() out to a function. - content::DownloadManager::DownloadVector all_items, filtered_items; - all_items.push_back(download_item); - DownloadQuery query; - query.AddFilter(DownloadQuery::FILTER_QUERY, *search_terms_); - query.Search(all_items.begin(), all_items.end(), &filtered_items); - if (filtered_items.empty()) - return; - } - - DCHECK(manager); - scoped_ptr<base::DictionaryValue> item(CreateDownloadItemValue( - download_item, - original_notifier_ && manager == GetMainNotifierManager())); - CallUpdateItem(*item); -} - -void DownloadsDOMHandler::OnDownloadRemoved( - content::DownloadManager* manager, - content::DownloadItem* download_item) { - if (!DownloadItemModel(download_item).ShouldShowInShelf()) - return; - - // This relies on |download_item| being removed from DownloadManager in this - // MessageLoop iteration. |download_item| may not have been removed from - // DownloadManager when OnDownloadRemoved() is fired, so bounce off the - // MessageLoop to give it a chance to be removed. SendCurrentDownloads() looks - // at all downloads, and we do not tell it that |download_item| is being - // removed. If DownloadManager is ever changed to not immediately remove - // |download_item| from its map when OnDownloadRemoved is sent, then - // DownloadsDOMHandler::OnDownloadRemoved() will need to explicitly tell - // SendCurrentDownloads() that |download_item| was removed. A - // SupportsUserData::Data would be the correct way to do this. - ScheduleSendCurrentDownloads(); -} - -void DownloadsDOMHandler::HandleGetDownloads(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_GET_DOWNLOADS); - search_terms_.reset(args && !args->empty() ? args->DeepCopy() : NULL); - ScheduleSendCurrentDownloads(); - - if (!main_notifier_) { - main_notifier_.reset(new AllDownloadItemNotifier(download_manager_, this)); - - Profile* profile = Profile::FromBrowserContext( - download_manager_->GetBrowserContext()); - if (profile->IsOffTheRecord()) { - original_notifier_.reset(new AllDownloadItemNotifier( - BrowserContext::GetDownloadManager(profile->GetOriginalProfile()), - this)); - } - } -} - -void DownloadsDOMHandler::HandleOpenFile(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FILE); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->OpenDownload(); -} - -void DownloadsDOMHandler::HandleDrag(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DRAG); - content::DownloadItem* file = GetDownloadByValue(args); - if (!file) - return; - - content::WebContents* web_contents = GetWebUIWebContents(); - // |web_contents| is only NULL in the test. - if (!web_contents) - return; - - if (file->GetState() != content::DownloadItem::COMPLETE) - return; - - gfx::Image* icon = g_browser_process->icon_manager()->LookupIconFromFilepath( - file->GetTargetFilePath(), IconLoader::NORMAL); - gfx::NativeView view = web_contents->GetNativeView(); - { - // Enable nested tasks during DnD, while |DragDownload()| blocks. - base::MessageLoop::ScopedNestableTaskAllower allow( - base::MessageLoop::current()); - DragDownloadItem(file, icon, view); - } -} - -void DownloadsDOMHandler::HandleSaveDangerous(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - ShowDangerPrompt(file); -} - -void DownloadsDOMHandler::HandleDiscardDangerous(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_DISCARD_DANGEROUS); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->Remove(); -} - -void DownloadsDOMHandler::HandleShow(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SHOW); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->ShowDownloadInShell(); -} - -void DownloadsDOMHandler::HandlePause(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_PAUSE); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->Pause(); -} - -void DownloadsDOMHandler::HandleResume(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_RESUME); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->Resume(); -} - -void DownloadsDOMHandler::HandleRemove(const base::ListValue* args) { - if (!IsDeletingHistoryAllowed()) - return; - - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_REMOVE); - content::DownloadItem* file = GetDownloadByValue(args); - if (!file) - return; - - std::vector<content::DownloadItem*> downloads; - downloads.push_back(file); - RemoveDownloads(downloads); -} - -void DownloadsDOMHandler::HandleUndo(const base::ListValue* args) { - // TODO(dbeam): handle more than removed downloads someday? - if (removals_.empty()) - return; - - const std::set<uint32_t> last_removed_ids = removals_.back(); - removals_.pop_back(); - - for (auto id : last_removed_ids) { - content::DownloadItem* download = GetDownloadById(id); - if (!download) - continue; - - DownloadItemModel model(download); - model.SetShouldShowInShelf(true); - model.SetIsBeingRevived(true); - - download->UpdateObservers(); - - model.SetIsBeingRevived(false); - } -} - -void DownloadsDOMHandler::HandleCancel(const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CANCEL); - content::DownloadItem* file = GetDownloadByValue(args); - if (file) - file->Cancel(true); -} - -void DownloadsDOMHandler::HandleClearAll(const base::ListValue* args) { - if (!IsDeletingHistoryAllowed()) { - // This should only be reached during tests. - return; - } - - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_CLEAR_ALL); - - std::vector<content::DownloadItem*> downloads; - if (GetMainNotifierManager()) - GetMainNotifierManager()->GetAllDownloads(&downloads); - if (GetOriginalNotifierManager()) - GetOriginalNotifierManager()->GetAllDownloads(&downloads); - RemoveDownloads(downloads); -} - -void DownloadsDOMHandler::RemoveDownloads( - const std::vector<content::DownloadItem*>& to_remove) { - std::set<uint32_t> ids; - - for (auto* download : to_remove) { - DownloadItemModel item_model(download); - if (!item_model.ShouldShowInShelf() || - download->GetState() == content::DownloadItem::IN_PROGRESS) { - continue; - } - - item_model.SetShouldShowInShelf(false); - ids.insert(download->GetId()); - download->UpdateObservers(); - } - - if (!ids.empty()) - removals_.push_back(ids); -} - -void DownloadsDOMHandler::HandleOpenDownloadsFolder( - const base::ListValue* args) { - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_OPEN_FOLDER); - content::DownloadManager* manager = GetMainNotifierManager(); - if (manager) { - platform_util::OpenItem( - Profile::FromBrowserContext(manager->GetBrowserContext()), - DownloadPrefs::FromDownloadManager(manager)->DownloadPath(), - platform_util::OPEN_FOLDER, platform_util::OpenOperationCallback()); - } -} - -// DownloadsDOMHandler, private: ---------------------------------------------- - -void DownloadsDOMHandler::ScheduleSendCurrentDownloads() { - // Don't call SendCurrentDownloads() every time anything changes. Batch them - // together instead. This may handle hundreds of OnDownloadDestroyed() calls - // in a single UI message loop iteration when the user Clears All downloads. - if (update_scheduled_) - return; - - update_scheduled_ = true; - - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::Bind(&DownloadsDOMHandler::SendCurrentDownloads, - weak_ptr_factory_.GetWeakPtr())); -} - -content::DownloadManager* DownloadsDOMHandler::GetMainNotifierManager() const { - return main_notifier_ ? main_notifier_->GetManager() : nullptr; -} - -content::DownloadManager* DownloadsDOMHandler::GetOriginalNotifierManager() - const { - return original_notifier_ ? original_notifier_->GetManager() : nullptr; -} - -void DownloadsDOMHandler::FinalizeRemovals() { - while (!removals_.empty()) { - const std::set<uint32_t> remove = removals_.back(); - removals_.pop_back(); - - for (const auto id : remove) { - content::DownloadItem* download = GetDownloadById(id); - if (download) - download->Remove(); - } - } -} - -void DownloadsDOMHandler::SendCurrentDownloads() { - update_scheduled_ = false; - - content::DownloadManager::DownloadVector all_items, filtered_items; - if (GetMainNotifierManager()) { - GetMainNotifierManager()->GetAllDownloads(&all_items); - GetMainNotifierManager()->CheckForHistoryFilesRemoval(); - } - if (GetOriginalNotifierManager()) { - GetOriginalNotifierManager()->GetAllDownloads(&all_items); - GetOriginalNotifierManager()->CheckForHistoryFilesRemoval(); - } - - DownloadQuery query; - if (search_terms_ && !search_terms_->empty()) - query.AddFilter(DownloadQuery::FILTER_QUERY, *search_terms_); - query.AddFilter(base::Bind(&IsDownloadDisplayable)); - query.AddSorter(DownloadQuery::SORT_START_TIME, DownloadQuery::DESCENDING); - query.Limit(kMaxNumberOfDownloads); - query.Search(all_items.begin(), all_items.end(), &filtered_items); - - base::ListValue results_value; - for (auto* item : filtered_items) { - results_value.Append(CreateDownloadItemValue( - item, - original_notifier_ && GetMainNotifierManager() && - GetMainNotifierManager()->GetDownload(item->GetId()) == item)); - } - CallUpdateAll(results_value); -} - -void DownloadsDOMHandler::ShowDangerPrompt( - content::DownloadItem* dangerous_item) { - DownloadDangerPrompt* danger_prompt = DownloadDangerPrompt::Create( - dangerous_item, - GetWebUIWebContents(), - false, - base::Bind(&DownloadsDOMHandler::DangerPromptDone, - weak_ptr_factory_.GetWeakPtr(), dangerous_item->GetId())); - // danger_prompt will delete itself. - DCHECK(danger_prompt); -} - -void DownloadsDOMHandler::DangerPromptDone( - int download_id, DownloadDangerPrompt::Action action) { - if (action != DownloadDangerPrompt::ACCEPT) - return; - content::DownloadItem* item = NULL; - if (GetMainNotifierManager()) - item = GetMainNotifierManager()->GetDownload(download_id); - if (!item && GetOriginalNotifierManager()) - item = GetOriginalNotifierManager()->GetDownload(download_id); - if (!item || item->IsDone()) - return; - CountDownloadsDOMEvents(DOWNLOADS_DOM_EVENT_SAVE_DANGEROUS); - item->ValidateDangerousDownload(); -} - -bool DownloadsDOMHandler::IsDeletingHistoryAllowed() { - content::DownloadManager* manager = GetMainNotifierManager(); - return manager && - Profile::FromBrowserContext(manager->GetBrowserContext())-> - GetPrefs()->GetBoolean(prefs::kAllowDeletingBrowserHistory); -} - -content::DownloadItem* DownloadsDOMHandler::GetDownloadByValue( - const base::ListValue* args) { - std::string download_id; - if (!args->GetString(0, &download_id)) { - NOTREACHED(); - return nullptr; - } - - uint64_t id; - if (!base::StringToUint64(download_id, &id)) { - NOTREACHED(); - return nullptr; - } - - return GetDownloadById(static_cast<uint32_t>(id)); -} - -content::DownloadItem* DownloadsDOMHandler::GetDownloadById(uint32_t id) { - content::DownloadItem* item = NULL; - if (GetMainNotifierManager()) - item = GetMainNotifierManager()->GetDownload(id); - if (!item && GetOriginalNotifierManager()) - item = GetOriginalNotifierManager()->GetDownload(id); - return item; -} - -content::WebContents* DownloadsDOMHandler::GetWebUIWebContents() { - return web_ui()->GetWebContents(); -} - -void DownloadsDOMHandler::CallUpdateAll(const base::ListValue& list) { - web_ui()->CallJavascriptFunction("downloads.Manager.updateAll", list); -} - -void DownloadsDOMHandler::CallUpdateItem(const base::DictionaryValue& item) { - web_ui()->CallJavascriptFunction("downloads.Manager.updateItem", item); -} diff --git a/chrome/browser/ui/webui/downloads_dom_handler.h b/chrome/browser/ui/webui/downloads_dom_handler.h deleted file mode 100644 index 1324642..0000000 --- a/chrome/browser/ui/webui/downloads_dom_handler.h +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_DOWNLOADS_DOM_HANDLER_H_ -#define CHROME_BROWSER_UI_WEBUI_DOWNLOADS_DOM_HANDLER_H_ - -#include <stdint.h> - -#include <set> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "chrome/browser/download/all_download_item_notifier.h" -#include "chrome/browser/download/download_danger_prompt.h" -#include "content/public/browser/download_item.h" -#include "content/public/browser/download_manager.h" -#include "content/public/browser/web_ui_message_handler.h" - -namespace base { -class ListValue; -} - -namespace content { -class WebContents; -} - -// The handler for Javascript messages related to the "downloads" view, -// also observes changes to the download manager. -class DownloadsDOMHandler : public content::WebUIMessageHandler, - public AllDownloadItemNotifier::Observer { - public: - explicit DownloadsDOMHandler(content::DownloadManager* download_manager); - ~DownloadsDOMHandler() override; - - void Init(); - - // WebUIMessageHandler implementation. - void RegisterMessages() override; - - // AllDownloadItemNotifier::Observer interface - void OnDownloadCreated(content::DownloadManager* manager, - content::DownloadItem* download_item) override; - void OnDownloadUpdated(content::DownloadManager* manager, - content::DownloadItem* download_item) override; - void OnDownloadRemoved(content::DownloadManager* manager, - content::DownloadItem* download_item) override; - - // Callback for the "getDownloads" message. - void HandleGetDownloads(const base::ListValue* args); - - // Callback for the "openFile" message - opens the file in the shell. - void HandleOpenFile(const base::ListValue* args); - - // Callback for the "drag" message - initiates a file object drag. - void HandleDrag(const base::ListValue* args); - - // Callback for the "saveDangerous" message - specifies that the user - // wishes to save a dangerous file. - void HandleSaveDangerous(const base::ListValue* args); - - // Callback for the "discardDangerous" message - specifies that the user - // wishes to discard (remove) a dangerous file. - void HandleDiscardDangerous(const base::ListValue* args); - - // Callback for the "show" message - shows the file in explorer. - void HandleShow(const base::ListValue* args); - - // Callback for the "pause" message - pauses the file download. - void HandlePause(const base::ListValue* args); - - // Callback for the "resume" message - resumes the file download. - void HandleResume(const base::ListValue* args); - - // Callback for the "remove" message - removes the file download from shelf - // and list. - void HandleRemove(const base::ListValue* args); - - // Callback for the "undo" message. Currently only undoes removals. - void HandleUndo(const base::ListValue* args); - - // Callback for the "cancel" message - cancels the download. - void HandleCancel(const base::ListValue* args); - - // Callback for the "clearAll" message - clears all the downloads. - void HandleClearAll(const base::ListValue* args); - - // Callback for the "openDownloadsFolder" message - opens the downloads - // folder. - void HandleOpenDownloadsFolder(const base::ListValue* args); - - protected: - // These methods are for mocking so that most of this class does not actually - // depend on WebUI. The other methods that depend on WebUI are - // RegisterMessages() and HandleDrag(). - virtual content::WebContents* GetWebUIWebContents(); - virtual void CallUpdateAll(const base::ListValue& list); - virtual void CallUpdateItem(const base::DictionaryValue& item); - - // Schedules a call to SendCurrentDownloads() in the next message loop - // iteration. Protected rather than private for use in tests. - void ScheduleSendCurrentDownloads(); - - // Actually remove downloads with an ID in |removals_|. This cannot be undone. - void FinalizeRemovals(); - - private: - // Shorthand for |observing_items_|, which tracks all items that this is - // observing so that RemoveObserver will be called for all of them. - typedef std::set<content::DownloadItem*> DownloadSet; - - // Convenience method to call |main_notifier_->GetManager()| while - // null-checking |main_notifier_|. - content::DownloadManager* GetMainNotifierManager() const; - - // Convenience method to call |original_notifier_->GetManager()| while - // null-checking |original_notifier_|. - content::DownloadManager* GetOriginalNotifierManager() const; - - // Sends the current list of downloads to the page. - void SendCurrentDownloads(); - - // Displays a native prompt asking the user for confirmation after accepting - // the dangerous download specified by |dangerous|. The function returns - // immediately, and will invoke DangerPromptAccepted() asynchronously if the - // user accepts the dangerous download. The native prompt will observe - // |dangerous| until either the dialog is dismissed or |dangerous| is no - // longer an in-progress dangerous download. - void ShowDangerPrompt(content::DownloadItem* dangerous); - - // Conveys danger acceptance from the DownloadDangerPrompt to the - // DownloadItem. - void DangerPromptDone(int download_id, DownloadDangerPrompt::Action action); - - // Returns true if the records of any downloaded items are allowed (and able) - // to be deleted. - bool IsDeletingHistoryAllowed(); - - // Returns the download that is referred to in a given value. - content::DownloadItem* GetDownloadByValue(const base::ListValue* args); - - // Returns the download with |id| or NULL if it doesn't exist. - content::DownloadItem* GetDownloadById(uint32_t id); - - // Remove all downloads in |to_remove| with the ability to undo removal later. - void RemoveDownloads(const std::vector<content::DownloadItem*>& to_remove); - - // Weak reference to the DownloadManager this class was constructed with. You - // should probably be using use Get{Main,Original}NotifierManager() instead. - content::DownloadManager* download_manager_; - - // Current search terms. - scoped_ptr<base::ListValue> search_terms_; - - // Notifies OnDownload*() and provides safe access to the DownloadManager. - scoped_ptr<AllDownloadItemNotifier> main_notifier_; - - // If |main_notifier_| observes an incognito profile, then this observes the - // DownloadManager for the original profile; otherwise, this is NULL. - scoped_ptr<AllDownloadItemNotifier> original_notifier_; - - // IDs of downloads to remove when this handler gets deleted. - std::vector<std::set<uint32_t>> removals_; - - // Whether a call to SendCurrentDownloads() is currently scheduled. - bool update_scheduled_; - - // IDs of new downloads that the page doesn't know about yet. - std::set<uint32_t> new_downloads_; - - base::WeakPtrFactory<DownloadsDOMHandler> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(DownloadsDOMHandler); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_DOWNLOADS_DOM_HANDLER_H_ diff --git a/chrome/browser/ui/webui/downloads_dom_handler_browsertest.cc b/chrome/browser/ui/webui/downloads_dom_handler_browsertest.cc deleted file mode 100644 index adf13bc..0000000 --- a/chrome/browser/ui/webui/downloads_dom_handler_browsertest.cc +++ /dev/null @@ -1,330 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stddef.h> - -#include "base/auto_reset.h" -#include "base/files/scoped_temp_dir.h" -#include "base/json/json_reader.h" -#include "base/macros.h" -#include "base/values.h" -#include "chrome/browser/download/download_item_model.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/webui/downloads_dom_handler.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/base/in_process_browser_test.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/mock_download_item.h" -#include "content/public/test/mock_download_manager.h" -#include "content/public/test/test_utils.h" -#include "net/test/embedded_test_server/embedded_test_server.h" - -namespace { - -// Reads |right_json| into a ListValue |left_list|; returns true if all -// key-value pairs in in all dictionaries in |right_list| are also in the -// corresponding dictionary in |left_list|. Ignores keys in dictionaries in -// |left_list| that are not in the corresponding dictionary in |right_list|. -bool ListMatches(base::ListValue* left_list, const std::string& right_json) { - scoped_ptr<base::Value> right_value = base::JSONReader::Read(right_json); - base::ListValue* right_list = NULL; - CHECK(right_value->GetAsList(&right_list)); - for (size_t i = 0; i < left_list->GetSize(); ++i) { - base::DictionaryValue* left_dict = NULL; - base::DictionaryValue* right_dict = NULL; - CHECK(left_list->GetDictionary(i, &left_dict)); - CHECK(right_list->GetDictionary(i, &right_dict)); - for (base::DictionaryValue::Iterator iter(*right_dict); - !iter.IsAtEnd(); iter.Advance()) { - base::Value* left_value = NULL; - if (left_dict->HasKey(iter.key()) && - left_dict->Get(iter.key(), &left_value) && - !iter.value().Equals(left_value)) { - LOG(WARNING) << "key \"" << iter.key() << "\" doesn't match (" - << iter.value() << " vs. " << *left_value << ")"; - return false; - } - } - } - return true; -} - -// A |DownloadsDOMHandler| that doesn't use a real WebUI object, but is real in -// all other respects. -class MockDownloadsDOMHandler : public DownloadsDOMHandler { - public: - explicit MockDownloadsDOMHandler(content::DownloadManager* download_manager) - : DownloadsDOMHandler(download_manager), - waiting_list_(false), - waiting_updated_(false) { - } - ~MockDownloadsDOMHandler() override {} - - base::ListValue* downloads_list() { return downloads_list_.get(); } - base::DictionaryValue* download_updated() { return download_updated_.get(); } - - void WaitForDownloadsList() { - if (downloads_list_) - return; - base::AutoReset<bool> reset_waiting(&waiting_list_, true); - content::RunMessageLoop(); - } - - void WaitForDownloadUpdated() { - if (download_updated_) - return; - base::AutoReset<bool> reset_waiting(&waiting_updated_, true); - content::RunMessageLoop(); - } - - void ForceSendCurrentDownloads() { - ScheduleSendCurrentDownloads(); - } - - void reset_downloads_list() { downloads_list_.reset(); } - void reset_download_updated() { download_updated_.reset(); } - - using DownloadsDOMHandler::FinalizeRemovals; - - protected: - content::WebContents* GetWebUIWebContents() override { return NULL; } - - void CallUpdateAll(const base::ListValue& list) override { - downloads_list_.reset(list.DeepCopy()); - if (waiting_list_) { - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::MessageLoop::QuitWhenIdleClosure()); - } - } - - void CallUpdateItem(const base::DictionaryValue& item) override { - download_updated_.reset(item.DeepCopy()); - if (waiting_updated_) { - content::BrowserThread::PostTask( - content::BrowserThread::UI, FROM_HERE, - base::MessageLoop::QuitWhenIdleClosure()); - } - } - - private: - scoped_ptr<base::ListValue> downloads_list_; - scoped_ptr<base::DictionaryValue> download_updated_; - bool waiting_list_; - bool waiting_updated_; - - DISALLOW_COPY_AND_ASSIGN(MockDownloadsDOMHandler); -}; - -} // namespace - -class DownloadsDOMHandlerTest : public InProcessBrowserTest { - public: - DownloadsDOMHandlerTest() {} - - ~DownloadsDOMHandlerTest() override {} - - void SetUpOnMainThread() override { - mock_handler_.reset(new MockDownloadsDOMHandler(download_manager())); - CHECK(downloads_directory_.CreateUniqueTempDir()); - browser()->profile()->GetPrefs()->SetFilePath( - prefs::kDownloadDefaultDirectory, - downloads_directory_.path()); - CHECK(embedded_test_server()->Start()); - mock_handler_->HandleGetDownloads(nullptr); - } - - content::DownloadManager* download_manager() { - return content::BrowserContext::GetDownloadManager(browser()->profile()); - } - - void DownloadAnItem() { - GURL url = embedded_test_server()->GetURL("/downloads/image.jpg"); - std::vector<GURL> url_chain; - url_chain.push_back(url); - base::Time current(base::Time::Now()); - download_manager()->CreateDownloadItem( - 1, // id - base::FilePath(FILE_PATH_LITERAL("/path/to/file")), - base::FilePath(FILE_PATH_LITERAL("/path/to/file")), - url_chain, - GURL(std::string()), - "application/octet-stream", - "application/octet-stream", - current, - current, - std::string(), - std::string(), - 128, - 128, - content::DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, - content::DOWNLOAD_INTERRUPT_REASON_NONE, - false); - - mock_handler_->ForceSendCurrentDownloads(); - mock_handler_->WaitForDownloadsList(); - ASSERT_EQ(1, static_cast<int>(mock_handler_->downloads_list()->GetSize())); - EXPECT_TRUE(ListMatches( - mock_handler_->downloads_list(), - "[{\"file_externally_removed\": false," - " \"file_name\": \"file\"," - " \"id\": \"1\"," - " \"otr\": false," - " \"since_string\": \"Today\"," - " \"state\": \"COMPLETE\"," - " \"total\": 128}]")); - } - - protected: - scoped_ptr<MockDownloadsDOMHandler> mock_handler_; - - private: - base::ScopedTempDir downloads_directory_; - - DISALLOW_COPY_AND_ASSIGN(DownloadsDOMHandlerTest); -}; - -// Tests removing all items, both when prohibited and when allowed. -IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest, RemoveAll) { - DownloadAnItem(); - - mock_handler_->reset_downloads_list(); - browser()->profile()->GetPrefs()->SetBoolean( - prefs::kAllowDeletingBrowserHistory, false); - mock_handler_->HandleClearAll(NULL); - // Attempting to clear all shouldn't do anything when deletion is disabled. - mock_handler_->ForceSendCurrentDownloads(); - mock_handler_->WaitForDownloadsList(); - ASSERT_EQ(1, static_cast<int>(mock_handler_->downloads_list()->GetSize())); - - mock_handler_->reset_downloads_list(); - browser()->profile()->GetPrefs()->SetBoolean( - prefs::kAllowDeletingBrowserHistory, true); - mock_handler_->HandleClearAll(NULL); - mock_handler_->WaitForDownloadsList(); - EXPECT_EQ(0, static_cast<int>(mock_handler_->downloads_list()->GetSize())); -} - -// Tests removing one item, both when prohibited and when allowed. -IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest, RemoveOneItem) { - DownloadAnItem(); - base::ListValue item; - item.AppendString("1"); - - mock_handler_->reset_downloads_list(); - browser()->profile()->GetPrefs()->SetBoolean( - prefs::kAllowDeletingBrowserHistory, false); - mock_handler_->HandleRemove(&item); - // Removing an item only sends the new download list if anything was actually - // removed, so force it. - mock_handler_->ForceSendCurrentDownloads(); - mock_handler_->WaitForDownloadsList(); - ASSERT_EQ(1, static_cast<int>(mock_handler_->downloads_list()->GetSize())); - - mock_handler_->reset_downloads_list(); - browser()->profile()->GetPrefs()->SetBoolean( - prefs::kAllowDeletingBrowserHistory, true); - mock_handler_->HandleRemove(&item); - mock_handler_->WaitForDownloadsList(); - EXPECT_EQ(0, static_cast<int>(mock_handler_->downloads_list()->GetSize())); -} - -IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest, ClearAllSkipsInProgress) { - testing::NiceMock<content::MockDownloadManager> manager; - EXPECT_CALL(manager, GetBrowserContext()).WillRepeatedly( - testing::Return(browser()->profile())); - mock_handler_.reset(new MockDownloadsDOMHandler(&manager)); - mock_handler_->HandleGetDownloads(nullptr); - - content::MockDownloadItem item; - EXPECT_CALL(item, GetState()).WillRepeatedly( - testing::Return(content::DownloadItem::IN_PROGRESS)); - EXPECT_CALL(item, UpdateObservers()).Times(0); - - std::vector<content::DownloadItem*> items; - items.push_back(&item); - EXPECT_CALL(manager, GetAllDownloads(testing::_)).WillOnce( - testing::SetArgPointee<0>(items)); - - mock_handler_->HandleClearAll(NULL); - EXPECT_TRUE(DownloadItemModel(&item).ShouldShowInShelf()); - - mock_handler_.reset(); -} - -// Tests that DownloadsDOMHandler detects new downloads and relays them to the -// renderer. -// crbug.com/159390: This test fails when daylight savings time ends. -IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest, DownloadsRelayed) { - DownloadAnItem(); - - mock_handler_->WaitForDownloadUpdated(); - const base::DictionaryValue* update = mock_handler_->download_updated(); - ASSERT_TRUE(update); - - bool removed; - ASSERT_TRUE(update->GetBoolean("file_externally_removed", &removed)); - EXPECT_TRUE(removed); - - std::string id; - ASSERT_TRUE(update->GetString("id", &id)); - EXPECT_EQ("1", id); - - mock_handler_->reset_downloads_list(); - browser()->profile()->GetPrefs()->SetBoolean( - prefs::kAllowDeletingBrowserHistory, true); - mock_handler_->HandleClearAll(NULL); - mock_handler_->WaitForDownloadsList(); - EXPECT_EQ(0, static_cast<int>(mock_handler_->downloads_list()->GetSize())); -} - -// Tests that DownloadsDOMHandler actually calls DownloadItem::Remove() when -// it's closed (and removals can no longer be undone). -IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest, RemoveCalledOnPageClose) { - testing::NiceMock<content::MockDownloadManager> manager; - EXPECT_CALL(manager, GetBrowserContext()).WillRepeatedly( - testing::Return(browser()->profile())); - mock_handler_.reset(new MockDownloadsDOMHandler(&manager)); - mock_handler_->HandleGetDownloads(nullptr); - - content::MockDownloadItem item; - EXPECT_CALL(item, GetId()).WillRepeatedly(testing::Return(1)); - EXPECT_CALL(item, GetState()).WillRepeatedly( - testing::Return(content::DownloadItem::COMPLETE)); - - DownloadItemModel model(&item); - EXPECT_TRUE(model.ShouldShowInShelf()); - - EXPECT_CALL(manager, GetDownload(1)).WillRepeatedly(testing::Return(&item)); - - base::ListValue remove; - remove.AppendString("1"); - EXPECT_CALL(item, UpdateObservers()).Times(1); - mock_handler_->HandleRemove(&remove); - EXPECT_FALSE(model.ShouldShowInShelf()); - - EXPECT_CALL(item, Remove()).Times(1); - // Call |mock_handler_->FinalizeRemovals()| instead of |mock_handler_.reset()| - // because the vtable is affected during destruction and the fake manager - // rigging doesn't work. - mock_handler_->FinalizeRemovals(); - mock_handler_.reset(); -} - -// TODO(benjhayden): Test the extension downloads filter for both -// mock_handler_.downloads_list() and mock_handler_.download_updated(). - -// TODO(benjhayden): Test incognito, both downloads_list() and that on-record -// calls can't access off-record items. - -// TODO(benjhayden): Test that bad download ids incoming from the javascript are -// dropped on the floor. - -// TODO(benjhayden): Test that IsTemporary() downloads are not shown. - -// TODO(benjhayden): Test that RemoveObserver is called on all download items, -// including items that crossed IsTemporary() and back. diff --git a/chrome/browser/ui/webui/downloads_ui.cc b/chrome/browser/ui/webui/downloads_ui.cc deleted file mode 100644 index 37c2feb..0000000 --- a/chrome/browser/ui/webui/downloads_ui.cc +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_ui.h" - -#include "base/memory/ref_counted_memory.h" -#include "base/memory/singleton.h" -#include "base/strings/string_piece.h" -#include "base/threading/thread.h" -#include "base/values.h" -#include "chrome/browser/defaults.h" -#include "chrome/browser/download/download_service.h" -#include "chrome/browser/download/download_service_factory.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/webui/downloads_dom_handler.h" -#include "chrome/browser/ui/webui/theme_source.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/grit/chromium_strings.h" -#include "chrome/grit/generated_resources.h" -#include "components/prefs/pref_service.h" -#include "content/public/browser/download_manager.h" -#include "content/public/browser/url_data_source.h" -#include "content/public/browser/web_contents.h" -#include "content/public/browser/web_ui.h" -#include "content/public/browser/web_ui_data_source.h" -#include "grit/browser_resources.h" -#include "grit/theme_resources.h" -#include "ui/base/resource/resource_bundle.h" - -using content::BrowserContext; -using content::DownloadManager; -using content::WebContents; - -namespace { - -content::WebUIDataSource* CreateDownloadsUIHTMLSource(Profile* profile) { - content::WebUIDataSource* source = - content::WebUIDataSource::Create(chrome::kChromeUIDownloadsHost); - - source->AddLocalizedString("title", IDS_DOWNLOAD_TITLE); - source->AddLocalizedString("searchResultsFor", IDS_DOWNLOAD_SEARCHRESULTSFOR); - source->AddLocalizedString("downloads", IDS_DOWNLOAD_TITLE); - source->AddLocalizedString("clearAll", IDS_DOWNLOAD_LINK_CLEAR_ALL); - source->AddLocalizedString("openDownloadsFolder", - IDS_DOWNLOAD_LINK_OPEN_DOWNLOADS_FOLDER); - source->AddLocalizedString("searchButton", IDS_DOWNLOAD_SEARCH_BUTTON); - - // No results message that shows instead of the downloads list. - source->AddLocalizedString("noDownloads", IDS_DOWNLOAD_NO_DOWNLOADS); - source->AddLocalizedString("noSearchResults", - IDS_DOWNLOAD_NO_SEARCH_RESULTS); - - // Status. - source->AddLocalizedString("statusCancelled", IDS_DOWNLOAD_TAB_CANCELLED); - source->AddLocalizedString("statusRemoved", IDS_DOWNLOAD_FILE_REMOVED); - - // Dangerous file. - source->AddLocalizedString("dangerFileDesc", IDS_PROMPT_DANGEROUS_DOWNLOAD); - source->AddLocalizedString("dangerUrlDesc", - IDS_PROMPT_MALICIOUS_DOWNLOAD_URL); - source->AddLocalizedString("dangerContentDesc", - IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT); - source->AddLocalizedString("dangerUncommonDesc", - IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT); - source->AddLocalizedString("dangerSettingsDesc", - IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS); - source->AddLocalizedString("dangerSave", IDS_CONFIRM_DOWNLOAD); - source->AddLocalizedString("dangerRestore", IDS_CONFIRM_DOWNLOAD_RESTORE); - source->AddLocalizedString("dangerDiscard", IDS_DISCARD_DOWNLOAD); - - // Controls. - source->AddLocalizedString("controlPause", IDS_DOWNLOAD_LINK_PAUSE); - if (browser_defaults::kDownloadPageHasShowInFolder) - source->AddLocalizedString("controlShowInFolder", IDS_DOWNLOAD_LINK_SHOW); - source->AddLocalizedString("controlCancel", IDS_DOWNLOAD_LINK_CANCEL); - source->AddLocalizedString("controlResume", IDS_DOWNLOAD_LINK_RESUME); - source->AddLocalizedString("controlRemoveFromList", - IDS_DOWNLOAD_LINK_REMOVE); - source->AddLocalizedString("controlRetry", IDS_DOWNLOAD_LINK_RETRY); - source->AddLocalizedString("controlByExtension", - IDS_DOWNLOAD_BY_EXTENSION); - - PrefService* prefs = profile->GetPrefs(); - source->AddBoolean("allowDeletingHistory", - prefs->GetBoolean(prefs::kAllowDeletingBrowserHistory) && - !profile->IsSupervised()); - - source->AddResourcePath("constants.html", IDR_DOWNLOADS_CONSTANTS_HTML); - source->AddResourcePath("constants.js", IDR_DOWNLOADS_CONSTANTS_JS); - source->AddResourcePath("item_view.js", IDR_DOWNLOADS_ITEM_VIEW_JS); - source->AddResourcePath("focus_row.js", IDR_DOWNLOADS_FOCUS_ROW_JS); - source->AddResourcePath("manager.js", IDR_DOWNLOADS_MANAGER_JS); - source->AddResourcePath("throttled_icon_loader.html", - IDR_DOWNLOADS_THROTTLED_ICON_LOADER_HTML); - source->AddResourcePath("throttled_icon_loader.js", - IDR_DOWNLOADS_THROTTLED_ICON_LOADER_JS); - - source->SetDefaultResource(IDR_DOWNLOADS_DOWNLOADS_HTML); - source->SetJsonPath("strings.js"); - - return source; -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// DownloadsUI -// -/////////////////////////////////////////////////////////////////////////////// - -DownloadsUI::DownloadsUI(content::WebUI* web_ui) : WebUIController(web_ui) { - Profile* profile = Profile::FromWebUI(web_ui); - DownloadManager* dlm = BrowserContext::GetDownloadManager(profile); - - DownloadsDOMHandler* handler = new DownloadsDOMHandler(dlm); - web_ui->AddMessageHandler(handler); - - // Set up the chrome://downloads/ source. - content::WebUIDataSource* source = CreateDownloadsUIHTMLSource(profile); - content::WebUIDataSource::Add(profile, source); -#if defined(ENABLE_THEMES) - ThemeSource* theme = new ThemeSource(profile); - content::URLDataSource::Add(profile, theme); -#endif -} - -// static -base::RefCountedMemory* DownloadsUI::GetFaviconResourceBytes( - ui::ScaleFactor scale_factor) { - return ResourceBundle::GetSharedInstance(). - LoadDataResourceBytesForScale(IDR_DOWNLOADS_FAVICON, scale_factor); -} diff --git a/chrome/browser/ui/webui/downloads_ui.h b/chrome/browser/ui/webui/downloads_ui.h deleted file mode 100644 index 7ac8707..0000000 --- a/chrome/browser/ui/webui/downloads_ui.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_H_ -#define CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_H_ - -#include "base/macros.h" -#include "content/public/browser/web_ui_controller.h" -#include "ui/base/layout.h" - -namespace base { -class RefCountedMemory; -} - -class DownloadsUI : public content::WebUIController { - public: - explicit DownloadsUI(content::WebUI* web_ui); - - static base::RefCountedMemory* GetFaviconResourceBytes( - ui::ScaleFactor scale_factor); - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsUI); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_H_ diff --git a/chrome/browser/ui/webui/downloads_ui_browsertest.cc b/chrome/browser/ui/webui/downloads_ui_browsertest.cc deleted file mode 100644 index 0caa51d..0000000 --- a/chrome/browser/ui/webui/downloads_ui_browsertest.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_ui_browsertest.h" - -#include "base/command_line.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/webui/downloads_util.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/pref_names.h" -#include "components/prefs/pref_service.h" -#include "content/public/test/test_utils.h" - -DownloadsUIBrowserTest::DownloadsUIBrowserTest() {} - -DownloadsUIBrowserTest::~DownloadsUIBrowserTest() {} - -void DownloadsUIBrowserTest::SetUpCommandLine( - base::CommandLine* command_line) { - WebUIBrowserTest::SetUpCommandLine(command_line); - command_line->AppendSwitch(switches::kDisableMaterialDesignDownloads); - ASSERT_FALSE(MdDownloadsEnabled()); -} - -void DownloadsUIBrowserTest::SetDeleteAllowed(bool allowed) { - browser()->profile()->GetPrefs()-> - SetBoolean(prefs::kAllowDeletingBrowserHistory, allowed); -} diff --git a/chrome/browser/ui/webui/downloads_ui_browsertest.h b/chrome/browser/ui/webui/downloads_ui_browsertest.h deleted file mode 100644 index 38e718a..0000000 --- a/chrome/browser/ui/webui/downloads_ui_browsertest.h +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_BROWSERTEST_H_ -#define CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_BROWSERTEST_H_ - -#include "base/macros.h" -#include "chrome/test/base/web_ui_browser_test.h" - -// This is a helper class used by downloads_ui_browsertest.js. -class DownloadsUIBrowserTest : public WebUIBrowserTest { - public: - DownloadsUIBrowserTest(); - ~DownloadsUIBrowserTest() override; - - // WebUIBrowserTest: - void SetUpCommandLine(base::CommandLine* command_line) override; - - protected: - // Sets the pref to allow or prohibit deleting history entries. - void SetDeleteAllowed(bool allowed); - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsUIBrowserTest); -}; - -#endif // CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_BROWSERTEST_H_ diff --git a/chrome/browser/ui/webui/downloads_ui_browsertest.js b/chrome/browser/ui/webui/downloads_ui_browsertest.js deleted file mode 100644 index 8ffba04..0000000 --- a/chrome/browser/ui/webui/downloads_ui_browsertest.js +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -GEN_INCLUDE(['downloads_ui_browsertest_base.js']); -GEN('#include "chrome/browser/ui/webui/downloads_ui_browsertest.h"'); - -// Test UI when removing entries is allowed. -TEST_F('BaseDownloadsWebUITest', 'DeleteAllowed', function() { - this.expectDeleteControlsVisible(true); - // TODO(pamg): Mock out the back-end calls, so we can also test removing a - // single item. -}); - -TEST_F('BaseDownloadsWebUITest', 'NoResultsHiddenWhenDownloads', function() { - assertNotEquals(0, downloads.Manager.size()); - expectFalse($('downloads-display').hidden); - expectTrue($('no-downloads-or-results').hidden); -}); - -TEST_F('BaseDownloadsWebUITest', 'NoSearchResultsShown', function() { - expectFalse($('downloads-display').hidden); - var noResults = $('no-downloads-or-results'); - expectTrue(noResults.hidden); - - downloads.Manager.setSearchText('just try to search for me!'); - this.sendEmptyList(); - - expectTrue($('downloads-display').hidden); - this.checkShowing(noResults, loadTimeData.getString('noSearchResults')); -}); - -TEST_F('BaseDownloadsWebUITest', 'NoDownloadsAfterClearAll', function() { - expectFalse($('downloads-display').hidden); - var noResults = $('no-downloads-or-results'); - expectTrue(noResults.hidden); - - $('clear-all').click(); - this.sendEmptyList(); - - expectTrue($('downloads-display').hidden); - this.checkShowing(noResults, loadTimeData.getString('noDownloads')); -}); - -TEST_F('BaseDownloadsWebUITest', 'PauseResumeFocus', function() { - assertGE(downloads.Manager.size(), 0); - - var freshestDownload = this.createdDownloads[0]; - freshestDownload.state = downloads.States.IN_PROGRESS; - freshestDownload.resume = false; - downloads.Manager.updateItem(freshestDownload); - - var manager = downloads.Manager.getInstance(); - var node = manager.idMap_[freshestDownload.id].node; - var pause = node.querySelector('.pause'); - var resume = node.querySelector('.resume'); - - expectFalse(pause.hidden); - expectTrue(resume.hidden); - // Move the focus to "Pause" then pretend the download was resumed. The focus - // should move to the equivalent button ("Resume" in this case). - pause.focus(); - assertEquals(document.activeElement, pause); - - freshestDownload.state = downloads.States.PAUSED; - freshestDownload.resume = true; - downloads.Manager.updateItem(freshestDownload); - - expectTrue(pause.hidden); - expectFalse(resume.hidden); - expectEquals(document.activeElement, resume); -}); - -TEST_F('BaseDownloadsWebUITest', 'DatesCollapse', function() { - function datesShowing() { - var displayDiv = $('downloads-display'); - return displayDiv.querySelectorAll('.date-container:not([hidden])').length; - } - - var numDownloads = downloads.Manager.size(); - assertGE(numDownloads, 2); - - expectEquals(1, datesShowing()); - - var freshestId = this.createdDownloads[0].id; - this.createDangerousDownload(freshestId + 1, Date.now()); - downloads.Manager.updateAll(this.createdDownloads); - - expectEquals(numDownloads + 1, downloads.Manager.size()); - expectEquals(1, datesShowing()); - - var firstContainer = document.querySelector('.date-container'); - assertFalse(firstContainer.hidden); - expectGT(firstContainer.querySelector('.since').textContent.trim().length, 0); - expectGT(firstContainer.querySelector('.date').textContent.trim().length, 0); -}); - -TEST_F('BaseDownloadsWebUITest', 'EmptyProgressStatusText', function() { - this.createdDownloads[0].state = downloads.States.PAUSED; - this.createdDownloads[0].progress_status_text = ''; - downloads.Manager.updateItem(this.createdDownloads[0]); // Might assert(). -}); - -TEST_F('BaseDownloadsWebUITest', 'EmptyLastStatusText', function() { - this.createdDownloads[0].state = downloads.States.INTERRUPTED; - this.createdDownloads[0].last_reason_text = ''; - downloads.Manager.updateItem(this.createdDownloads[0]); // Might assert(). -}); - -/** - * @constructor - * @extends {BaseDownloadsWebUITest} - */ -function EmptyDownloadsWebUITest() {} - -EmptyDownloadsWebUITest.prototype = { - __proto__: BaseDownloadsWebUITest.prototype, - - /** @override */ - setUp: function() { - // Doesn't create any fake downloads. - assertEquals(0, downloads.Manager.size()); - - this.updateAccessibilityAuditConfig(); - }, -}; - -TEST_F('EmptyDownloadsWebUITest', 'NoDownloadsMessageShowing', function() { - expectTrue($('downloads-display').hidden); - var noResults = $('no-downloads-or-results'); - this.checkShowing(noResults, loadTimeData.getString('noDownloads')); -}); - -TEST_F('EmptyDownloadsWebUITest', 'NoSearchResultsWithNoDownloads', function() { - downloads.Manager.setSearchText('bananas'); - this.sendEmptyList(); - - expectTrue($('downloads-display').hidden); - var noResults = $('no-downloads-or-results'); - this.checkShowing(noResults, loadTimeData.getString('noSearchResults')); -}); - -/** - * Fixture for Downloads WebUI testing when deletions are prohibited. - * @extends {BaseDownloadsWebUITest} - * @constructor - */ -function DownloadsWebUIDeleteProhibitedTest() {} - -DownloadsWebUIDeleteProhibitedTest.prototype = { - __proto__: BaseDownloadsWebUITest.prototype, - - /** @override */ - testGenPreamble: function() { - GEN(' SetDeleteAllowed(false);'); - }, -}; - -// Test UI when removing entries is prohibited. -TEST_F('DownloadsWebUIDeleteProhibitedTest', 'DeleteProhibited', function() { - this.expectDeleteControlsVisible(false); - // TODO(pamg): Mock out the back-end calls, so we can also test removing a - // single item. -}); - -TEST_F('DownloadsWebUIDeleteProhibitedTest', 'ClearLeavesSearch', function() { - downloads.Manager.setSearchText('muhahaha'); - $('clear-all').click(); - expectGE(downloads.Manager.getInstance().searchText_.length, 0); -}); diff --git a/chrome/browser/ui/webui/downloads_ui_browsertest_base.js b/chrome/browser/ui/webui/downloads_ui_browsertest_base.js deleted file mode 100644 index 24ec279..0000000 --- a/chrome/browser/ui/webui/downloads_ui_browsertest_base.js +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** @const */ var TOTAL_RESULT_COUNT = 25; - -/** - * Test C++ fixture for downloads WebUI testing. - * @constructor - * @extends {testing.Test} - */ -function DownloadsUIBrowserTest() {} - -/** - * Base fixture for Downloads WebUI testing. - * @extends {testing.Test} - * @constructor - */ -function BaseDownloadsWebUITest() {} - -BaseDownloadsWebUITest.prototype = { - __proto__: testing.Test.prototype, - - /** - * Browse to the downloads page & call our preLoad(). - */ - browsePreload: 'chrome://downloads/', - - /** @override */ - typedefCppFixture: 'DownloadsUIBrowserTest', - - /** @override */ - testGenPreamble: function() { - GEN(' SetDeleteAllowed(true);'); - }, - - /** @override */ - runAccessibilityChecks: true, - - /** @override */ - accessibilityIssuesAreErrors: true, - - /** - * Sends TOTAL_RESULT_COUNT fake downloads to the page. This can't be called - * in the preLoad, because it requires the global Download object to have - * been created by the page. - * @override - */ - setUp: function() { - testing.Test.prototype.setUp.call(this); - - this.createdDownloads = []; - - // The entries will begin at 1:00 AM on Sept 2, 2008, and will be spaced - // two minutes apart. - var timestamp = new Date(2008, 9, 2, 1, 0).getTime(); - for (var i = 0; i < TOTAL_RESULT_COUNT; ++i) { - this.createDownload(i, timestamp); - timestamp += 2 * 60 * 1000; // Next visit is two minutes later. - } - downloads.Manager.updateAll(this.createdDownloads); - expectEquals(downloads.Manager.size(), TOTAL_RESULT_COUNT); - - this.updateAccessibilityAuditConfig(); - }, - - /** - * Disables failing accessibility audits. This should be removed when all - * audit issues have been resolved. - */ - updateAccessibilityAuditConfig: function() { - // Enable when failure is resolved. - // AX_TEXT_01: http://crbug.com/559217 - this.accessibilityAuditConfig.ignoreSelectors( - 'controlsWithoutLabel', - '#term'); - - // Enable when failure is resolved. - // AX_FOCUS_03: http://crbug.com/559219 - this.accessibilityAuditConfig.ignoreSelectors( - 'tabIndexGreaterThanZero', - '#term'); - }, - - /** - * Creates a download object to be passed to the page, following the expected - * backend format (see downloads_dom_handler.cc). - * @param {number} id A unique ID for the download. - * @param {number} timestamp The time the download purportedly started. - * @return {!Object} A fake download object. - */ - createDownload: function(id, timestamp) { - this.createdDownloads.unshift({ - id: id, - started: timestamp, - otr: false, - state: downloads.States.COMPLETE, - retry: false, - file_path: '/path/to/file', - file_url: 'http://google.com/' + timestamp, - file_name: 'download_' + timestamp, - url: 'http://google.com/' + timestamp, - file_externally_removed: false, - danger_type: downloads.DangerType.NOT_DANGEROUS, - last_reason_text: '', - since_string: 'today', - date_string: 'today', - percent: 100, - progress_status_text: 'done', - received: 128, - }); - return this.createdDownloads[0]; - }, - - /** - * Creates a dangerous download object. See downloads_dom_handler.cc. - * @param {number} id The ID of the download. - * @param {number} timestamp The time this download started. - * @return {!Object} A fake, dangerous download object. - */ - createDangerousDownload: function(id, timestamp) { - this.createdDownloads.unshift({ - id: id, - started: timestamp, - otr: false, - state: downloads.States.DANGEROUS, - retry: false, - file_path: '/oh/noes.jpg.exe', - file_url: 'http://evil.com/cute/kittens' + timestamp, - file_name: 'evil.' + timestamp + '.jar', - file_url: 'http://evil.com/cute/kittens' + timestamp, - file_externally_removed: false, - danger_type: downloads.DangerType.DANGEROUS_FILE, - last_reason_text: '', - since_string: 'today', - date_string: 'today', - percent: 0, - progress_status_text: '', - received: 128, - }); - return this.createdDownloads[0]; - }, - - /** - * Simulates getting no results from C++. - */ - sendEmptyList: function() { - downloads.Manager.updateAll([]); - assertEquals(0, downloads.Manager.size()); - }, - - /** - * Check that |element| is showing and contains |text|. - * @param {Element} element - * @param {string} text - */ - checkShowing: function(element, text) { - expectFalse(element.hidden); - expectNotEquals(-1, element.textContent.indexOf(text)); - }, - - /** - * Asserts the correctness of the state of the UI elements that delete the - * download history. - * @param {boolean} visible True if download deletion UI should be visible. - */ - expectDeleteControlsVisible: function(visible) { - // "Clear all" should only be showing when deletions are allowed. - expectEquals(!visible, $('clear-all').hidden); - - // "Remove from list" links should only exist when deletions are allowed. - var query = '#downloads-display .safe .remove'; - if (!visible) - query += '[hidden]'; - expectEquals(TOTAL_RESULT_COUNT, document.querySelectorAll(query).length); - }, -}; diff --git a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.cc b/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.cc deleted file mode 100644 index 04c44a5..0000000 --- a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.cc +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_ui_supervised_browsertest.h" - -#include "base/command_line.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/chrome_switches.h" -#include "content/public/test/test_utils.h" - -void DownloadsWebUIForSupervisedUsersTest::SetUpCommandLine( - base::CommandLine* command_line) { - DownloadsUIBrowserTest::SetUpCommandLine(command_line); - command_line->AppendSwitchASCII(switches::kSupervisedUserId, "asdf"); -} diff --git a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.h b/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.h deleted file mode 100644 index ee60fc6..0000000 --- a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_SUPERVISED_BROWSERTEST_H_ -#define CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_SUPERVISED_BROWSERTEST_H_ - -#include "chrome/browser/ui/webui/downloads_ui_browsertest.h" - -class DownloadsWebUIForSupervisedUsersTest : public DownloadsUIBrowserTest { - public: - // InProcessBrowserTest implementation. - void SetUpCommandLine(base::CommandLine* command_line) override; -}; - -#endif // CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UI_SUPERVISED_BROWSERTEST_H_ diff --git a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.js b/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.js deleted file mode 100644 index 84870a8..0000000 --- a/chrome/browser/ui/webui/downloads_ui_supervised_browsertest.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -GEN_INCLUDE(['downloads_ui_browsertest_base.js']); -GEN('#include "chrome/browser/ui/webui/downloads_ui_supervised_browsertest.h"'); - -/** - * Fixture for Downloads WebUI testing for a supervised user. - * @extends {BaseDownloadsWebUITest} - * @constructor - */ -function DownloadsWebUIForSupervisedUsersTest() {} - -DownloadsWebUIForSupervisedUsersTest.prototype = { - __proto__: BaseDownloadsWebUITest.prototype, - - /** @override */ - typedefCppFixture: 'DownloadsWebUIForSupervisedUsersTest', -}; - -// Test UI for supervised users, removing entries should be disabled -// and removal controls should be hidden. -TEST_F('DownloadsWebUIForSupervisedUsersTest', 'SupervisedUsers', function() { - this.expectDeleteControlsVisible(false); - testDone(); -}); diff --git a/chrome/browser/ui/webui/downloads_util.cc b/chrome/browser/ui/webui/downloads_util.cc deleted file mode 100644 index 404cc80..0000000 --- a/chrome/browser/ui/webui/downloads_util.cc +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_util.h" - -#include "base/command_line.h" -#include "base/metrics/field_trial.h" -#include "base/strings/string_util.h" -#include "chrome/common/channel_info.h" -#include "chrome/common/chrome_switches.h" -#include "components/version_info/version_info.h" - -const char kMaterialDesignDownloadsFinchTrialName[] = "MaterialDesignDownloads"; - -bool MdDownloadsEnabled() { - // Intentionally call this before checking command line to assign a group. - std::string group = base::FieldTrialList::FindFullName( - kMaterialDesignDownloadsFinchTrialName); - - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - if (cl->HasSwitch(switches::kEnableMaterialDesignDownloads)) - return true; - - if (cl->HasSwitch(switches::kDisableMaterialDesignDownloads)) - return false; - - return base::StartsWith(group, "Enabled", - base::CompareCase::INSENSITIVE_ASCII); -} diff --git a/chrome/browser/ui/webui/downloads_util.h b/chrome/browser/ui/webui/downloads_util.h deleted file mode 100644 index 69774605..0000000 --- a/chrome/browser/ui/webui/downloads_util.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UTIL_H_ -#define CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UTIL_H_ - -extern const char kMaterialDesignDownloadsFinchTrialName[]; - -// Whether the Material Design version of chrome://downloads should be enabled. -bool MdDownloadsEnabled(); - -#endif // CHROME_BROWSER_UI_WEBUI_DOWNLOADS_UTIL_H_ diff --git a/chrome/browser/ui/webui/downloads_util_unittest.cc b/chrome/browser/ui/webui/downloads_util_unittest.cc deleted file mode 100644 index 378ded5..0000000 --- a/chrome/browser/ui/webui/downloads_util_unittest.cc +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "chrome/browser/ui/webui/downloads_util.h" - -#include "base/command_line.h" -#include "base/macros.h" -#include "base/metrics/field_trial.h" -#include "base/test/mock_entropy_provider.h" -#include "chrome/common/chrome_switches.h" -#include "testing/gtest/include/gtest/gtest.h" - -using base::FieldTrialList; - -const char* kFieldTrialName = kMaterialDesignDownloadsFinchTrialName; - -class MdDownloadsEnabledTest : public testing::Test { - public: - MdDownloadsEnabledTest() : field_trial_list_(new base::MockEntropyProvider) {} - ~MdDownloadsEnabledTest() override {} - - private: - base::FieldTrialList field_trial_list_; -}; - -TEST_F(MdDownloadsEnabledTest, DisabledByDefault) { - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - ASSERT_FALSE(cl->HasSwitch(switches::kDisableMaterialDesignDownloads)); - ASSERT_FALSE(cl->HasSwitch(switches::kEnableMaterialDesignDownloads)); - ASSERT_FALSE(base::FieldTrialList::TrialExists(kFieldTrialName)); - EXPECT_FALSE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, EnabledByFieldTrial) { - ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kFieldTrialName, "Enabled2")); - EXPECT_TRUE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, DisabledByFieldTrial) { - ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kFieldTrialName, "Disabled2")); - EXPECT_FALSE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, EnabledBySwitch) { - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - cl->AppendSwitch(switches::kEnableMaterialDesignDownloads); - EXPECT_TRUE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, DisabledBySwitch) { - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - cl->AppendSwitch(switches::kDisableMaterialDesignDownloads); - EXPECT_FALSE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, SwitchOverridesFieldTrial1) { - ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kFieldTrialName, "Disabled2")); - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - cl->AppendSwitch(switches::kEnableMaterialDesignDownloads); - EXPECT_TRUE(MdDownloadsEnabled()); -} - -TEST_F(MdDownloadsEnabledTest, SwitchOverridesFieldTrial2) { - ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kFieldTrialName, "Enabled2")); - base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); - cl->AppendSwitch(switches::kDisableMaterialDesignDownloads); - EXPECT_FALSE(MdDownloadsEnabled()); -} |
