diff options
author | tfarina@chromium.org <tfarina@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-02-18 10:56:31 +0000 |
---|---|---|
committer | tfarina@chromium.org <tfarina@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-02-18 10:56:31 +0000 |
commit | 229688ddef58126e746dcb26b9cb8dbf55ae3586 (patch) | |
tree | 15e63b708d9bca394c97757ac865e0a5c2f87f10 /chrome/browser/dom_ui | |
parent | 4f57fd3756fd5774c85670f40a8805d39af757e2 (diff) | |
download | chromium_src-229688ddef58126e746dcb26b9cb8dbf55ae3586.zip chromium_src-229688ddef58126e746dcb26b9cb8dbf55ae3586.tar.gz chromium_src-229688ddef58126e746dcb26b9cb8dbf55ae3586.tar.bz2 |
WebUI: Move more files from chrome/browser/dom_ui to chrome/browser/webui. Part 4.
BUG=59945, 59946
TEST=trybots
Review URL: http://codereview.chromium.org/6532045
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75380 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/dom_ui')
-rw-r--r-- | chrome/browser/dom_ui/filebrowse_ui.cc | 1272 | ||||
-rw-r--r-- | chrome/browser/dom_ui/filebrowse_ui.h | 39 | ||||
-rw-r--r-- | chrome/browser/dom_ui/mediaplayer_browsertest.cc | 6 | ||||
-rw-r--r-- | chrome/browser/dom_ui/mediaplayer_ui.cc | 613 | ||||
-rw-r--r-- | chrome/browser/dom_ui/mediaplayer_ui.h | 161 | ||||
-rw-r--r-- | chrome/browser/dom_ui/net_internals_ui.cc | 1315 | ||||
-rw-r--r-- | chrome/browser/dom_ui/net_internals_ui.h | 19 | ||||
-rw-r--r-- | chrome/browser/dom_ui/plugins_ui.cc | 374 | ||||
-rw-r--r-- | chrome/browser/dom_ui/plugins_ui.h | 25 | ||||
-rw-r--r-- | chrome/browser/dom_ui/remoting_ui.cc | 83 | ||||
-rw-r--r-- | chrome/browser/dom_ui/remoting_ui.h | 25 | ||||
-rw-r--r-- | chrome/browser/dom_ui/slideshow_ui.cc | 284 | ||||
-rw-r--r-- | chrome/browser/dom_ui/slideshow_ui.h | 19 |
13 files changed, 3 insertions, 4232 deletions
diff --git a/chrome/browser/dom_ui/filebrowse_ui.cc b/chrome/browser/dom_ui/filebrowse_ui.cc deleted file mode 100644 index f9a6fee..0000000 --- a/chrome/browser/dom_ui/filebrowse_ui.cc +++ /dev/null @@ -1,1272 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/filebrowse_ui.h" - -#include <algorithm> -#include <vector> - -#include "base/callback.h" -#include "base/command_line.h" -#include "base/file_util.h" -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/singleton.h" -#include "base/string_piece.h" -#include "base/string_util.h" -#include "base/threading/thread.h" -#include "base/time.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "base/weak_ptr.h" -#include "chrome/browser/bookmarks/bookmark_model.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/mediaplayer_ui.h" -#include "chrome/browser/dom_ui/web_ui_favicon_source.h" -#include "chrome/browser/download/download_item.h" -#include "chrome/browser/download/download_manager.h" -#include "chrome/browser/download/download_util.h" -#include "chrome/browser/history/history_types.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/tabs/tab_strip_model.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_navigator.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/net/url_fetcher.h" -#include "chrome/common/time_format.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "grit/chromium_strings.h" -#include "grit/generated_resources.h" -#include "grit/locale_settings.h" -#include "net/base/escape.h" -#include "net/url_request/url_request_file_job.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" - -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/cros/cros_library.h" -#include "chrome/browser/chromeos/cros/mount_library.h" -#include "chrome/browser/chromeos/login/user_manager.h" -#endif - -// Maximum number of search results to return in a given search. We should -// eventually remove this. -static const int kMaxSearchResults = 100; -static const char kPropertyPath[] = "path"; -static const char kPropertyTitle[] = "title"; -static const char kPropertyDirectory[] = "isDirectory"; -static const char kPicasawebUserPrefix[] = - "http://picasaweb.google.com/data/feed/api/user/"; -static const char kPicasawebDefault[] = "/albumid/default"; -static const char kPicasawebDropBox[] = "/home"; -static const char kPicasawebBaseUrl[] = "http://picasaweb.google.com/"; -static const char kMediaPath[] = "/media"; -static const char kFilebrowseURLHash[] = "chrome://filebrowse#"; -static const int kPopupLeft = 0; -static const int kPopupTop = 0; - -class FileBrowseUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - FileBrowseUIHTMLSource(); - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const { - return "text/html"; - } - - private: - ~FileBrowseUIHTMLSource() {} - - DISALLOW_COPY_AND_ASSIGN(FileBrowseUIHTMLSource); -}; - -class TaskProxy; - -// The handler for Javascript messages related to the "filebrowse" view. -class FilebrowseHandler : public net::DirectoryLister::DirectoryListerDelegate, - public WebUIMessageHandler, -#if defined(OS_CHROMEOS) - public chromeos::MountLibrary::Observer, -#endif - public base::SupportsWeakPtr<FilebrowseHandler>, - public URLFetcher::Delegate, - public DownloadManager::Observer, - public DownloadItem::Observer { - public: - FilebrowseHandler(); - virtual ~FilebrowseHandler(); - - // Init work after Attach. - void Init(); - - // DirectoryLister::DirectoryListerDelegate methods: - virtual void OnListFile( - const net::DirectoryLister::DirectoryListerData& data); - virtual void OnListDone(int error); - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - -#if defined(OS_CHROMEOS) - void MountChanged(chromeos::MountLibrary* obj, - chromeos::MountEventType evt, - const std::string& path); -#endif - - // DownloadItem::Observer interface - virtual void OnDownloadUpdated(DownloadItem* download); - virtual void OnDownloadFileCompleted(DownloadItem* download); - virtual void OnDownloadOpened(DownloadItem* download) { } - - // DownloadManager::Observer interface - virtual void ModelChanged(); - - // Callback for the "getRoots" message. - void HandleGetRoots(const ListValue* args); - - void GetChildrenForPath(const FilePath& path, bool is_refresh); - - void OnURLFetchComplete(const URLFetcher* source, - const GURL& url, - const net::URLRequestStatus& status, - int response_code, - const ResponseCookies& cookies, - const std::string& data); - - // Callback for the "getChildren" message. - void HandleGetChildren(const ListValue* args); - // Callback for the "refreshDirectory" message. - void HandleRefreshDirectory(const ListValue* args); - void HandleIsAdvancedEnabled(const ListValue* args); - - // Callback for the "getMetadata" message. - void HandleGetMetadata(const ListValue* args); - - // Callback for the "openNewWindow" message. - void OpenNewFullWindow(const ListValue* args); - void OpenNewPopupWindow(const ListValue* args); - - // Callback for the "uploadToPicasaweb" message. - void UploadToPicasaweb(const ListValue* args); - - // Callback for the "getDownloads" message. - void HandleGetDownloads(const ListValue* args); - - void HandleCreateNewFolder(const ListValue* args); - - void PlayMediaFile(const ListValue* args); - void EnqueueMediaFile(const ListValue* args); - - void HandleDeleteFile(const ListValue* args); - void HandleCopyFile(const ListValue* value); - void CopyFile(const FilePath& src, const FilePath& dest, TaskProxy* task); - void DeleteFile(const FilePath& path, TaskProxy* task); - void FireDeleteComplete(const FilePath& path); - void FireCopyComplete(const FilePath& src, const FilePath& dest); - - void HandlePauseToggleDownload(const ListValue* args); - - void HandleCancelDownload(const ListValue* args); - void HandleAllowDownload(const ListValue* args); - - void CreateNewFolder(const FilePath& path) const; - - void ReadInFile(); - void FireUploadComplete(); - - void SendPicasawebRequest(); - - // Callback for the "validateSavePath" message. - void HandleValidateSavePath(const ListValue* args); - - // Validate a save path on file thread. - void ValidateSavePathOnFileThread(const FilePath& save_path, TaskProxy* task); - - // Fire save path validation result to JS onValidatedSavePath. - void FireOnValidatedSavePathOnUIThread(bool valid, const FilePath& save_path); - - private: - - // Retrieves downloads from the DownloadManager and updates the page. - void UpdateDownloadList(); - - void OpenNewWindow(const ListValue* args, bool popup); - - // Clear all download items and their observers. - void ClearDownloadItems(); - - // Send the current list of downloads to the page. - void SendCurrentDownloads(); - - void SendNewDownload(DownloadItem* download); - - bool ValidateSaveDir(const FilePath& save_dir, bool exists) const; - bool AccessDisabled(const FilePath& path) const; - - scoped_ptr<ListValue> filelist_value_; - FilePath currentpath_; - Profile* profile_; - TabContents* tab_contents_; - std::string current_file_contents_; - std::string current_file_uploaded_; - int upload_response_code_; - TaskProxy* current_task_; - scoped_refptr<net::DirectoryLister> lister_; - bool is_refresh_; - scoped_ptr<URLFetcher> fetch_; - - DownloadManager* download_manager_; - typedef std::vector<DownloadItem*> DownloadList; - DownloadList active_download_items_; - DownloadList download_items_; - bool got_first_download_list_; - DISALLOW_COPY_AND_ASSIGN(FilebrowseHandler); -}; - -class TaskProxy : public base::RefCountedThreadSafe<TaskProxy> { - public: - TaskProxy(const base::WeakPtr<FilebrowseHandler>& handler, - const FilePath& path, const FilePath& dest) - : handler_(handler), - src_(path), - dest_(dest) {} - TaskProxy(const base::WeakPtr<FilebrowseHandler>& handler, - const FilePath& path) - : handler_(handler), - src_(path) {} - - // TaskProxy is created on the UI thread, so in some cases, - // we need to post back to the UI thread for destruction. - void DeleteOnUIThread() { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod(this, &TaskProxy::DoNothing)); - } - - void DoNothing() {} - - void ReadInFileProxy() { - if (handler_) - handler_->ReadInFile(); - DeleteOnUIThread(); - } - - void DeleteFetcher(URLFetcher* fetch) { - delete fetch; - } - - void SendPicasawebRequestProxy() { - if (handler_) - handler_->SendPicasawebRequest(); - DeleteOnUIThread(); - } - - void FireUploadCompleteProxy() { - if (handler_) - handler_->FireUploadComplete(); - } - - void DeleteFileProxy() { - if (handler_) - handler_->DeleteFile(src_, this); - } - - void CopyFileProxy() { - if (handler_) - handler_->CopyFile(src_, dest_, this); - } - - void CreateNewFolderProxy() { - if (handler_) - handler_->CreateNewFolder(src_); - DeleteOnUIThread(); - } - - void FireDeleteCompleteProxy() { - if (handler_) - handler_->FireDeleteComplete(src_); - } - void FireCopyCompleteProxy() { - if (handler_) - handler_->FireCopyComplete(src_, dest_); - } - - void ValidateSavePathOnFileThread() { - if (handler_) - handler_->ValidateSavePathOnFileThread(src_, this); - } - - void FireOnValidatedSavePathOnUIThread(bool valid) { - if (handler_) - handler_->FireOnValidatedSavePathOnUIThread(valid, src_); - } - - private: - base::WeakPtr<FilebrowseHandler> handler_; - FilePath src_; - FilePath dest_; - friend class base::RefCountedThreadSafe<TaskProxy>; - DISALLOW_COPY_AND_ASSIGN(TaskProxy); -}; - - -//////////////////////////////////////////////////////////////////////////////// -// -// FileBrowseHTMLSource -// -//////////////////////////////////////////////////////////////////////////////// - -FileBrowseUIHTMLSource::FileBrowseUIHTMLSource() - : DataSource(chrome::kChromeUIFileBrowseHost, MessageLoop::current()) { -} - -void FileBrowseUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - DictionaryValue localized_strings; - // TODO(dhg): Add stirings to localized strings, also add more strings - // that are currently hardcoded. - localized_strings.SetString("title", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_TITLE)); - localized_strings.SetString("pause", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_PAUSE)); - localized_strings.SetString("resume", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_RESUME)); - localized_strings.SetString("scanning", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_SCANNING)); - localized_strings.SetString("confirmdelete", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_CONFIRM_DELETE)); - localized_strings.SetString("confirmyes", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_CONFIRM_YES)); - localized_strings.SetString("confirmcancel", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_CONFIRM_CANCEL)); - localized_strings.SetString("allowdownload", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_CONFIRM_DOWNLOAD)); - localized_strings.SetString("filenameprompt", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_PROMPT_FILENAME)); - localized_strings.SetString("save", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_SAVE)); - localized_strings.SetString("newfolder", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_NEW_FOLDER)); - localized_strings.SetString("open", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_OPEN)); - localized_strings.SetString("picasaweb", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_UPLOAD_PICASAWEB)); - localized_strings.SetString("flickr", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_UPLOAD_FLICKR)); - localized_strings.SetString("email", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_UPLOAD_EMAIL)); - localized_strings.SetString("delete", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_DELETE)); - localized_strings.SetString("enqueue", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_ENQUEUE)); - localized_strings.SetString("mediapath", kMediaPath); - FilePath default_download_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, - &default_download_path)) { - NOTREACHED(); - } - // TODO(viettrungluu): this is wrong -- FilePath's need not be Unicode. - localized_strings.SetString("downloadpath", default_download_path.value()); - localized_strings.SetString("error_unknown_file_type", - l10n_util::GetStringUTF16(IDS_FILEBROWSER_ERROR_UNKNOWN_FILE_TYPE)); - SetFontAndTextDirection(&localized_strings); - - static const base::StringPiece filebrowse_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_FILEBROWSE_HTML)); - const std::string full_html = jstemplate_builder::GetI18nTemplateHtml( - filebrowse_html, &localized_strings); - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - - SendResponse(request_id, html_bytes); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// FilebrowseHandler -// -//////////////////////////////////////////////////////////////////////////////// -FilebrowseHandler::FilebrowseHandler() - : profile_(NULL), - tab_contents_(NULL), - is_refresh_(false), - fetch_(NULL), - download_manager_(NULL), - got_first_download_list_(false) { - lister_ = NULL; -#if defined(OS_CHROMEOS) - chromeos::MountLibrary* lib = - chromeos::CrosLibrary::Get()->GetMountLibrary(); - lib->AddObserver(this); -#endif -} - -FilebrowseHandler::~FilebrowseHandler() { -#if defined(OS_CHROMEOS) - chromeos::MountLibrary* lib = - chromeos::CrosLibrary::Get()->GetMountLibrary(); - lib->RemoveObserver(this); -#endif - if (lister_.get()) { - lister_->Cancel(); - lister_->set_delegate(NULL); - } - - ClearDownloadItems(); - download_manager_->RemoveObserver(this); - URLFetcher* fetch = fetch_.release(); - if (fetch) { - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), currentpath_); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::DeleteFetcher, fetch)); - } -} - -WebUIMessageHandler* FilebrowseHandler::Attach(WebUI* web_ui) { - // Create our favicon data source. - profile_ = web_ui->GetProfile(); - profile_->GetChromeURLDataManager()->AddDataSource( - new WebUIFavIconSource(profile_)); - tab_contents_ = web_ui->tab_contents(); - return WebUIMessageHandler::Attach(web_ui); -} - -void FilebrowseHandler::Init() { - download_manager_ = profile_->GetDownloadManager(); - download_manager_->AddObserver(this); - static bool sent_request = false; - if (!sent_request) { - // If we have not sent a request before, we should do one in order to - // ensure that we have the correct cookies. This is for uploads. - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), currentpath_); - current_task_ = task; - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::SendPicasawebRequestProxy)); - sent_request = true; - } -} - -void FilebrowseHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getRoots", - NewCallback(this, &FilebrowseHandler::HandleGetRoots)); - web_ui_->RegisterMessageCallback("getChildren", - NewCallback(this, &FilebrowseHandler::HandleGetChildren)); - web_ui_->RegisterMessageCallback("getMetadata", - NewCallback(this, &FilebrowseHandler::HandleGetMetadata)); - web_ui_->RegisterMessageCallback("openNewPopupWindow", - NewCallback(this, &FilebrowseHandler::OpenNewPopupWindow)); - web_ui_->RegisterMessageCallback("openNewFullWindow", - NewCallback(this, &FilebrowseHandler::OpenNewFullWindow)); - web_ui_->RegisterMessageCallback("uploadToPicasaweb", - NewCallback(this, &FilebrowseHandler::UploadToPicasaweb)); - web_ui_->RegisterMessageCallback("getDownloads", - NewCallback(this, &FilebrowseHandler::HandleGetDownloads)); - web_ui_->RegisterMessageCallback("createNewFolder", - NewCallback(this, &FilebrowseHandler::HandleCreateNewFolder)); - web_ui_->RegisterMessageCallback("playMediaFile", - NewCallback(this, &FilebrowseHandler::PlayMediaFile)); - web_ui_->RegisterMessageCallback("enqueueMediaFile", - NewCallback(this, &FilebrowseHandler::EnqueueMediaFile)); - web_ui_->RegisterMessageCallback("pauseToggleDownload", - NewCallback(this, &FilebrowseHandler::HandlePauseToggleDownload)); - web_ui_->RegisterMessageCallback("deleteFile", - NewCallback(this, &FilebrowseHandler::HandleDeleteFile)); - web_ui_->RegisterMessageCallback("copyFile", - NewCallback(this, &FilebrowseHandler::HandleCopyFile)); - web_ui_->RegisterMessageCallback("cancelDownload", - NewCallback(this, &FilebrowseHandler::HandleCancelDownload)); - web_ui_->RegisterMessageCallback("allowDownload", - NewCallback(this, &FilebrowseHandler::HandleAllowDownload)); - web_ui_->RegisterMessageCallback("refreshDirectory", - NewCallback(this, &FilebrowseHandler::HandleRefreshDirectory)); - web_ui_->RegisterMessageCallback("isAdvancedEnabled", - NewCallback(this, &FilebrowseHandler::HandleIsAdvancedEnabled)); - web_ui_->RegisterMessageCallback("validateSavePath", - NewCallback(this, &FilebrowseHandler::HandleValidateSavePath)); -} - - -void FilebrowseHandler::FireDeleteComplete(const FilePath& path) { - // We notify the UI by telling it to refresh its contents. - FilePath dir_path = path.DirName(); - GetChildrenForPath(dir_path, true); -}; - -void FilebrowseHandler::FireCopyComplete(const FilePath& src, - const FilePath& dest) { - // Notify the UI somehow. - FilePath dir_path = dest.DirName(); - GetChildrenForPath(dir_path, true); -}; - -void FilebrowseHandler::FireUploadComplete() { -#if defined(OS_CHROMEOS) - DictionaryValue info_value; - info_value.SetString("path", current_file_uploaded_); - - std::string username; - chromeos::UserManager* user_man = chromeos::UserManager::Get(); - username = user_man->logged_in_user().email(); - - if (username.empty()) { - LOG(ERROR) << "Unable to get username"; - return; - } - int location = username.find_first_of('@', 0); - if (location <= 0) { - LOG(ERROR) << "Username not formatted correctly"; - return; - } - username = username.erase(username.find_first_of('@', 0)); - std::string picture_url = kPicasawebBaseUrl; - picture_url += username; - picture_url += kPicasawebDropBox; - info_value.SetString("url", picture_url); - info_value.SetInteger("status_code", upload_response_code_); - web_ui_->CallJavascriptFunction(L"uploadComplete", info_value); -#endif -} - -#if defined(OS_CHROMEOS) -void FilebrowseHandler::MountChanged(chromeos::MountLibrary* obj, - chromeos::MountEventType evt, - const std::string& path) { - if (evt == chromeos::DISK_REMOVED || - evt == chromeos::DISK_CHANGED) { - web_ui_->CallJavascriptFunction(L"rootsChanged"); - } -} -#endif - -void FilebrowseHandler::OnURLFetchComplete(const URLFetcher* source, - const GURL& url, - const net::URLRequestStatus& status, - int response_code, - const ResponseCookies& cookies, - const std::string& data) { - upload_response_code_ = response_code; - VLOG(1) << "Response code: " << response_code; - VLOG(1) << "Request url: " << url; - if (StartsWithASCII(url.spec(), kPicasawebUserPrefix, true)) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod(current_task_, &TaskProxy::FireUploadCompleteProxy)); - } - fetch_.reset(); -} - -void FilebrowseHandler::HandleGetRoots(const ListValue* args) { - ListValue results_value; - DictionaryValue info_value; - // TODO(dhg): add other entries, make this more general -#if defined(OS_CHROMEOS) - chromeos::MountLibrary* lib = - chromeos::CrosLibrary::Get()->GetMountLibrary(); - const chromeos::MountLibrary::DiskVector& disks = lib->disks(); - - for (size_t i = 0; i < disks.size(); ++i) { - if (!disks[i].mount_path.empty()) { - DictionaryValue* page_value = new DictionaryValue(); - page_value->SetString(kPropertyPath, disks[i].mount_path); - FilePath currentpath(disks[i].mount_path); - std::string filename; - filename = currentpath.BaseName().value(); - page_value->SetString(kPropertyTitle, filename); - page_value->SetBoolean(kPropertyDirectory, true); - results_value.Append(page_value); - } - } -#else - DictionaryValue* page_value = new DictionaryValue(); - page_value->SetString(kPropertyPath, "/media"); - page_value->SetString(kPropertyTitle, "Removeable"); - page_value->SetBoolean(kPropertyDirectory, true); - results_value.Append(page_value); -#endif - FilePath default_download_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, - &default_download_path)) { - NOTREACHED(); - } - - DictionaryValue* download_value = new DictionaryValue(); - download_value->SetString(kPropertyPath, default_download_path.value()); - download_value->SetString(kPropertyTitle, "File Shelf"); - download_value->SetBoolean(kPropertyDirectory, true); - - results_value.Append(download_value); - - info_value.SetString("functionCall", "getRoots"); - info_value.SetString(kPropertyPath, ""); - web_ui_->CallJavascriptFunction(L"browseFileResult", - info_value, results_value); -} - -void FilebrowseHandler::HandleCreateNewFolder(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string path = WideToUTF8(ExtractStringValue(args)); - FilePath currentpath(path); - - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), currentpath); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::CreateNewFolderProxy)); -#endif -} - -void FilebrowseHandler::CreateNewFolder(const FilePath& currentpath) const { - if (!ValidateSaveDir(currentpath, false) || - !file_util::CreateDirectory(currentpath)) - LOG(ERROR) << "Unable to create directory " << currentpath.value(); -} - -void FilebrowseHandler::PlayMediaFile(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string url = WideToUTF8(ExtractStringValue(args)); - GURL gurl(url); - - Browser* browser = Browser::GetBrowserForController( - &tab_contents_->controller(), NULL); - MediaPlayer* mediaplayer = MediaPlayer::GetInstance(); - mediaplayer->ForcePlayMediaURL(gurl, browser); -#endif -} - -void FilebrowseHandler::EnqueueMediaFile(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string url = WideToUTF8(ExtractStringValue(args)); - GURL gurl(url); - - Browser* browser = Browser::GetBrowserForController( - &tab_contents_->controller(), NULL); - MediaPlayer* mediaplayer = MediaPlayer::GetInstance(); - mediaplayer->EnqueueMediaURL(gurl, browser); -#endif -} - -void FilebrowseHandler::HandleIsAdvancedEnabled(const ListValue* args) { -#if defined(OS_CHROMEOS) - bool is_enabled = CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableAdvancedFileSystem); - bool mp_enabled = CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableMediaPlayer); - DictionaryValue info_value; - info_value.SetBoolean("enabled", is_enabled); - info_value.SetBoolean("mpEnabled", mp_enabled); - web_ui_->CallJavascriptFunction(L"enabledResult", - info_value); - -#endif -} - -void FilebrowseHandler::HandleRefreshDirectory(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string path = WideToUTF8(ExtractStringValue(args)); - FilePath currentpath(path); - GetChildrenForPath(currentpath, true); -#endif -} - -void FilebrowseHandler::HandlePauseToggleDownload(const ListValue* args) { -#if defined(OS_CHROMEOS) - int id; - ExtractIntegerValue(args, &id); - if ((id - 1) >= static_cast<int>(active_download_items_.size())) { - return; - } - DownloadItem* item = active_download_items_[id]; - item->TogglePause(); -#endif -} - -void FilebrowseHandler::HandleAllowDownload(const ListValue* args) { -#if defined(OS_CHROMEOS) - int id; - ExtractIntegerValue(args, &id); - if ((id - 1) >= static_cast<int>(active_download_items_.size())) { - return; - } - - DownloadItem* item = active_download_items_[id]; - download_manager_->DangerousDownloadValidated(item); -#endif -} - -void FilebrowseHandler::HandleCancelDownload(const ListValue* args) { -#if defined(OS_CHROMEOS) - int id; - ExtractIntegerValue(args, &id); - if ((id - 1) >= static_cast<int>(active_download_items_.size())) { - return; - } - DownloadItem* item = active_download_items_[id]; - FilePath path = item->full_path(); - item->Cancel(true); - FilePath dir_path = path.DirName(); - item->Remove(true); - GetChildrenForPath(dir_path, true); -#endif -} - -void FilebrowseHandler::OpenNewFullWindow(const ListValue* args) { - OpenNewWindow(args, false); -} - -void FilebrowseHandler::OpenNewPopupWindow(const ListValue* args) { - OpenNewWindow(args, true); -} - -void FilebrowseHandler::OpenNewWindow(const ListValue* args, bool popup) { - std::string url = WideToUTF8(ExtractStringValue(args)); - Browser* browser = popup ? - Browser::CreateForType(Browser::TYPE_APP_PANEL, profile_) : - BrowserList::GetLastActive(); - browser::NavigateParams params(browser, GURL(url), PageTransition::LINK); - params.disposition = NEW_FOREGROUND_TAB; - browser::Navigate(¶ms); - // TODO(beng): The following two calls should be automatic by Navigate(). - if (popup) { - // TODO(dhg): Remove these from being hardcoded. Allow javascript - // to specify. - params.browser->window()->SetBounds(gfx::Rect(0, 0, 400, 300)); - } - params.browser->window()->Show(); -} - -void FilebrowseHandler::SendPicasawebRequest() { -#if defined(OS_CHROMEOS) - chromeos::UserManager* user_man = chromeos::UserManager::Get(); - std::string username = user_man->logged_in_user().email(); - - if (username.empty()) { - LOG(ERROR) << "Unable to get username"; - return; - } - - fetch_.reset(URLFetcher::Create(0, - GURL(kPicasawebBaseUrl), - URLFetcher::GET, - this)); - fetch_->set_request_context(profile_->GetRequestContext()); - fetch_->Start(); -#endif -} - -void FilebrowseHandler::ReadInFile() { -#if defined(OS_CHROMEOS) - // Get the users username - std::string username; - chromeos::UserManager* user_man = chromeos::UserManager::Get(); - username = user_man->logged_in_user().email(); - - if (username.empty()) { - LOG(ERROR) << "Unable to get username"; - return; - } - int location = username.find_first_of('@', 0); - if (location <= 0) { - LOG(ERROR) << "Username not formatted correctly"; - return; - } - username = username.erase(username.find_first_of('@', 0)); - std::string url = kPicasawebUserPrefix; - url += username; - url += kPicasawebDefault; - - FilePath currentpath(current_file_uploaded_); - // Get the filename - std::string filename; - filename = currentpath.BaseName().value(); - std::string filecontents; - if (!file_util::ReadFileToString(currentpath, &filecontents)) { - LOG(ERROR) << "Unable to read this file:" << currentpath.value(); - return; - } - fetch_.reset(URLFetcher::Create(0, - GURL(url), - URLFetcher::POST, - this)); - fetch_->set_upload_data("image/jpeg", filecontents); - // Set the filename on the server - std::string slug = "Slug: "; - slug += filename; - fetch_->set_extra_request_headers(slug); - fetch_->set_request_context(profile_->GetRequestContext()); - fetch_->Start(); -#endif -} - -// This is just a prototype for allowing generic uploads to various sites -// TODO(dhg): Remove this and implement general upload. -void FilebrowseHandler::UploadToPicasaweb(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string search_string = WideToUTF8(ExtractStringValue(args)); - current_file_uploaded_ = search_string; - // ReadInFile(); - FilePath current_path(search_string); - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), current_path); - current_task_ = task; - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::ReadInFileProxy)); -#endif -} - -void FilebrowseHandler::GetChildrenForPath(const FilePath& path, - bool is_refresh) { - if (path.empty()) - return; - - filelist_value_.reset(new ListValue()); - currentpath_ = path; - - if (lister_.get()) { - lister_->Cancel(); - lister_->set_delegate(NULL); - lister_ = NULL; - } - - is_refresh_ = is_refresh; - -#if defined(OS_CHROMEOS) - // Don't allow listing files in inaccessible dirs. - if (AccessDisabled(path)) - return; -#endif - - FilePath default_download_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, - &default_download_path)) { - NOTREACHED(); - } - - if (currentpath_ == default_download_path) { - lister_ = new net::DirectoryLister(currentpath_, - false, - net::DirectoryLister::DATE, - this); - } else { - lister_ = new net::DirectoryLister(currentpath_, this); - } - lister_->Start(); -} - -void FilebrowseHandler::HandleGetChildren(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string path = WideToUTF8(ExtractStringValue(args)); - FilePath currentpath(path); - filelist_value_.reset(new ListValue()); - - GetChildrenForPath(currentpath, false); -#endif -} - -void FilebrowseHandler::OnListFile( - const net::DirectoryLister::DirectoryListerData& data) { -#if defined(OS_WIN) - if (data.info.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) { - return; - } -#elif defined(OS_POSIX) - if (data.info.filename[0] == '.') { - return; - } - - // Suppress .crdownload files. - static const char crdownload[] = (".crdownload"); - static const size_t crdownload_size = arraysize(crdownload); - const std::string& filename = data.info.filename; - if ((filename.size() > crdownload_size) && - (filename.rfind(crdownload) == (filename.size() - crdownload_size))) - return; -#endif - - DictionaryValue* file_value = new DictionaryValue(); - -#if defined(OS_WIN) - int64 size = (static_cast<int64>(data.info.nFileSizeHigh) << 32) | - data.info.nFileSizeLow; - file_value->SetString(kPropertyTitle, data.info.cFileName); - file_value->SetString(kPropertyPath, - currentpath_.Append(data.info.cFileName).value()); - file_value->SetBoolean(kPropertyDirectory, - (data.info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? true : false); -#elif defined(OS_POSIX) - file_value->SetString(kPropertyTitle, data.info.filename); - file_value->SetString(kPropertyPath, - currentpath_.Append(data.info.filename).value()); - file_value->SetBoolean(kPropertyDirectory, S_ISDIR(data.info.stat.st_mode)); -#endif - filelist_value_->Append(file_value); -} - -void FilebrowseHandler::OnListDone(int error) { - DictionaryValue info_value; - if (is_refresh_) { - info_value.SetString("functionCall", "refresh"); - } else { - info_value.SetString("functionCall", "getChildren"); - } - info_value.SetString(kPropertyPath, currentpath_.value()); - web_ui_->CallJavascriptFunction(L"browseFileResult", - info_value, *(filelist_value_.get())); -} - -void FilebrowseHandler::HandleGetMetadata(const ListValue* args) { -} - -void FilebrowseHandler::HandleGetDownloads(const ListValue* args) { - UpdateDownloadList(); -} - -void FilebrowseHandler::ModelChanged() { - if (!currentpath_.empty()) - GetChildrenForPath(currentpath_, true); - else - UpdateDownloadList(); -} - -void FilebrowseHandler::UpdateDownloadList() { - ClearDownloadItems(); - - std::vector<DownloadItem*> downloads; - download_manager_->GetAllDownloads(FilePath(), &downloads); - - std::vector<DownloadItem*> new_downloads; - // Scan for any in progress downloads and add ourself to them as an observer. - for (DownloadList::iterator it = downloads.begin(); - it != downloads.end(); ++it) { - DownloadItem* download = *it; - // We want to know what happens as the download progresses and be notified - // when the user validates the dangerous download. - if (download->state() == DownloadItem::IN_PROGRESS || - download->safety_state() == DownloadItem::DANGEROUS) { - download->AddObserver(this); - active_download_items_.push_back(download); - } - DownloadList::iterator item = find(download_items_.begin(), - download_items_.end(), - download); - if (item == download_items_.end() && got_first_download_list_) { - SendNewDownload(download); - } - new_downloads.push_back(download); - } - download_items_.swap(new_downloads); - got_first_download_list_ = true; - SendCurrentDownloads(); -} - -void FilebrowseHandler::SendNewDownload(DownloadItem* download) { - ListValue results_value; - results_value.Append(download_util::CreateDownloadItemValue(download, -1)); - web_ui_->CallJavascriptFunction(L"newDownload", results_value); -} - -void FilebrowseHandler::DeleteFile(const FilePath& path, TaskProxy* task) { - if (!file_util::Delete(path, true)) { - LOG(ERROR) << "unable to delete directory"; - } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod(task, &TaskProxy::FireDeleteCompleteProxy)); -} - -void FilebrowseHandler::CopyFile(const FilePath& src, - const FilePath& dest, - TaskProxy* task) { - if (file_util::DirectoryExists(src)) { - if (!file_util::CopyDirectory(src, dest, true)) { - LOG(ERROR) << "unable to copy directory:" << src.value(); - } - } else { - if (!file_util::CopyFile(src, dest)) { - LOG(ERROR) << "unable to copy file" << src.value(); - } - } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod(task, &TaskProxy::FireCopyCompleteProxy)); -} - -void FilebrowseHandler::HandleDeleteFile(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string path = WideToUTF8(ExtractStringValue(args)); - FilePath currentpath(path); - - // Don't allow file deletion in inaccessible dirs. - if (AccessDisabled(currentpath)) - return; - - for (unsigned int x = 0; x < active_download_items_.size(); x++) { - FilePath item = active_download_items_[x]->full_path(); - if (item == currentpath) { - active_download_items_[x]->Cancel(true); - active_download_items_[x]->Remove(true); - FilePath dir_path = item.DirName(); - GetChildrenForPath(dir_path, true); - return; - } - } - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), currentpath); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::DeleteFileProxy)); -#endif -} - -void FilebrowseHandler::HandleCopyFile(const ListValue* value) { -#if defined(OS_CHROMEOS) - if (value && value->GetType() == Value::TYPE_LIST) { - const ListValue* list_value = static_cast<const ListValue*>(value); - std::string src; - std::string dest; - - // Get path string. - if (list_value->GetString(0, &src) && - list_value->GetString(1, &dest)) { - FilePath SrcPath = FilePath(src); - FilePath DestPath = FilePath(dest); - - // Don't allow file copy to inaccessible dirs. - if (AccessDisabled(DestPath)) - return; - - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), - SrcPath, DestPath); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - NewRunnableMethod( - task.get(), &TaskProxy::CopyFileProxy)); - } else { - LOG(ERROR) << "Unable to get string"; - return; - } - } -#endif -} - -void FilebrowseHandler::HandleValidateSavePath(const ListValue* args) { - std::string string_path; - if (!args || !args->GetString(0, &string_path)) { - FireOnValidatedSavePathOnUIThread(false, FilePath()); // Invalid save path. - return; - } - - FilePath save_path(string_path); - -#if defined(OS_CHROMEOS) - scoped_refptr<TaskProxy> task = new TaskProxy(AsWeakPtr(), save_path); - BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, - NewRunnableMethod(task.get(), &TaskProxy::ValidateSavePathOnFileThread)); -#else - // No save path checking for non-ChromeOS platforms. - FireOnValidatedSavePathOnUIThread(true, save_path); -#endif -} - -void FilebrowseHandler::ValidateSavePathOnFileThread( - const FilePath& save_path, TaskProxy* task) { -#if defined(OS_CHROMEOS) - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - - const bool valid = ValidateSaveDir(save_path.DirName(), true); - - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, - NewRunnableMethod(task, - &TaskProxy::FireOnValidatedSavePathOnUIThread, - valid)); -#endif -} - -bool FilebrowseHandler::ValidateSaveDir(const FilePath& save_dir, - bool exists) const { -#if defined(OS_CHROMEOS) - FilePath default_download_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, - &default_download_path)) { - NOTREACHED(); - } - - // Valid save dir must be inside default download dir. - if (default_download_path == save_dir) - return true; - if (exists) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - return file_util::ContainsPath(default_download_path, save_dir); - } else { - return default_download_path.IsParent(save_dir); - } -#endif - return false; -} - -void FilebrowseHandler::FireOnValidatedSavePathOnUIThread(bool valid, - const FilePath& save_path) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - - FundamentalValue valid_value(valid); - StringValue path_value(save_path.value()); - web_ui_->CallJavascriptFunction(L"onValidatedSavePath", - valid_value, path_value); -} - -void FilebrowseHandler::OnDownloadUpdated(DownloadItem* download) { - DownloadList::iterator it = find(active_download_items_.begin(), - active_download_items_.end(), - download); - if (it == active_download_items_.end()) - return; - const int id = static_cast<int>(it - active_download_items_.begin()); - - scoped_ptr<DictionaryValue> download_item( - download_util::CreateDownloadItemValue(download, id)); - web_ui_->CallJavascriptFunction(L"downloadUpdated", *download_item.get()); -} - -void FilebrowseHandler::ClearDownloadItems() { - for (DownloadList::iterator it = active_download_items_.begin(); - it != active_download_items_.end(); ++it) { - (*it)->RemoveObserver(this); - } - active_download_items_.clear(); -} - -void FilebrowseHandler::SendCurrentDownloads() { - ListValue results_value; - for (DownloadList::iterator it = active_download_items_.begin(); - it != active_download_items_.end(); ++it) { - int index = static_cast<int>(it - active_download_items_.begin()); - results_value.Append(download_util::CreateDownloadItemValue(*it, index)); - } - - web_ui_->CallJavascriptFunction(L"downloadsList", results_value); -} - -void FilebrowseHandler::OnDownloadFileCompleted(DownloadItem* download) { - GetChildrenForPath(currentpath_, true); -} - -bool FilebrowseHandler::AccessDisabled(const FilePath& path) const { - return !ValidateSaveDir(path, false) && - net::URLRequestFileJob::AccessDisabled(path); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// FileBrowseUI -// -//////////////////////////////////////////////////////////////////////////////// - -FileBrowseUI::FileBrowseUI(TabContents* contents) : HtmlDialogUI(contents) { - FilebrowseHandler* handler = new FilebrowseHandler(); - AddMessageHandler((handler)->Attach(this)); - handler->Init(); - FileBrowseUIHTMLSource* html_source = new FileBrowseUIHTMLSource(); - - // Set up the chrome://filebrowse/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} - -// static -Browser* FileBrowseUI::OpenPopup(Profile* profile, - const std::string& hashArgument, - int width, - int height) { - // Get existing pop up for given hashArgument. - Browser* browser = GetPopupForPath(hashArgument, profile); - - // Create new browser if no matching pop up found. - if (browser == NULL) { - browser = Browser::CreateForType(Browser::TYPE_APP_PANEL, profile); - std::string url; - if (hashArgument.empty()) { - url = chrome::kChromeUIFileBrowseURL; - } else { - url = kFilebrowseURLHash; - url.append(hashArgument); - } - - browser::NavigateParams params(browser, GURL(url), PageTransition::LINK); - params.disposition = NEW_FOREGROUND_TAB; - browser::Navigate(¶ms); - // TODO(beng): The following two calls should be automatic by Navigate(). - params.browser->window()->SetBounds(gfx::Rect(kPopupLeft, - kPopupTop, - width, - height)); - - params.browser->window()->Show(); - } else { - browser->window()->Show(); - } - - return browser; -} - -Browser* FileBrowseUI::GetPopupForPath(const std::string& path, - Profile* profile) { - std::string current_path = path; - if (current_path.empty()) { - bool is_enabled = CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableAdvancedFileSystem); - if (!is_enabled) { - FilePath default_download_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, - &default_download_path)) { - NOTREACHED(); - } - current_path = default_download_path.value(); - } - } - - for (BrowserList::const_iterator it = BrowserList::begin(); - it != BrowserList::end(); ++it) { - if (((*it)->type() == Browser::TYPE_APP_PANEL)) { - TabContents* tab_contents = (*it)->GetSelectedTabContents(); - DCHECK(tab_contents); - if (!tab_contents) - continue; - const GURL& url = tab_contents->GetURL(); - - if (url.SchemeIs(chrome::kChromeUIScheme) && - url.host() == chrome::kChromeUIFileBrowseHost && - url.ref() == current_path && - (*it)->profile() == profile) { - return (*it); - } - } - } - - return NULL; -} - -const int FileBrowseUI::kPopupWidth = 250; -const int FileBrowseUI::kPopupHeight = 300; -const int FileBrowseUI::kSmallPopupWidth = 250; -const int FileBrowseUI::kSmallPopupHeight = 50; diff --git a/chrome/browser/dom_ui/filebrowse_ui.h b/chrome/browser/dom_ui/filebrowse_ui.h deleted file mode 100644 index 5d2e867..0000000 --- a/chrome/browser/dom_ui/filebrowse_ui.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2010 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_DOM_UI_FILEBROWSE_UI_H_ -#define CHROME_BROWSER_DOM_UI_FILEBROWSE_UI_H_ -#pragma once - -#include <string> - -#include "chrome/browser/dom_ui/chrome_url_data_manager.h" -#include "chrome/browser/dom_ui/html_dialog_ui.h" -#include "chrome/browser/history/history.h" -#include "net/base/directory_lister.h" - -class Browser; -class Profile; - -class FileBrowseUI : public HtmlDialogUI { - public: - static const int kPopupWidth; - static const int kPopupHeight; - static const int kSmallPopupWidth; - static const int kSmallPopupHeight; - - explicit FileBrowseUI(TabContents* contents); - - static Browser* OpenPopup(Profile* profile, - const std::string& hashArgument, - int width, - int height); - static Browser* GetPopupForPath(const std::string& path, - Profile* profile); - - private: - DISALLOW_COPY_AND_ASSIGN(FileBrowseUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_FILEBROWSE_UI_H_ diff --git a/chrome/browser/dom_ui/mediaplayer_browsertest.cc b/chrome/browser/dom_ui/mediaplayer_browsertest.cc index 74cbc30..17958e2 100644 --- a/chrome/browser/dom_ui/mediaplayer_browsertest.cc +++ b/chrome/browser/dom_ui/mediaplayer_browsertest.cc @@ -1,17 +1,17 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. +// Copyright (c) 2011 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 "base/command_line.h" #include "base/ref_counted.h" #include "base/utf_string_conversions.h" -#include "chrome/test/automation/dom_element_proxy.h" -#include "chrome/browser/dom_ui/mediaplayer_ui.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" +#include "chrome/browser/webui/mediaplayer_ui.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" +#include "chrome/test/automation/dom_element_proxy.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" diff --git a/chrome/browser/dom_ui/mediaplayer_ui.cc b/chrome/browser/dom_ui/mediaplayer_ui.cc deleted file mode 100644 index 23fc229..0000000 --- a/chrome/browser/dom_ui/mediaplayer_ui.cc +++ /dev/null @@ -1,613 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/mediaplayer_ui.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/singleton.h" -#include "base/string_piece.h" -#include "base/string_util.h" -#include "base/threading/thread.h" -#include "base/time.h" -#include "base/values.h" -#include "base/weak_ptr.h" -#include "chrome/browser/bookmarks/bookmark_model.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/web_ui_favicon_source.h" -#include "chrome/browser/download/download_manager.h" -#include "chrome/browser/download/download_util.h" -#include "chrome/browser/history/history_types.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/tabs/tab_strip_model.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/net/url_fetcher.h" -#include "chrome/common/time_format.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "grit/chromium_strings.h" -#include "grit/generated_resources.h" -#include "grit/locale_settings.h" -#include "net/base/escape.h" -#include "net/base/load_flags.h" -#include "net/url_request/url_request_job.h" -#include "ui/base/resource/resource_bundle.h" - -#if defined(OS_CHROMEOS) -#include "chrome/browser/chromeos/frame/panel_browser_view.h" -#endif - -static const char kPropertyPath[] = "path"; -static const char kPropertyForce[] = "force"; -static const char kPropertyOffset[] = "currentOffset"; -static const char kPropertyError[] = "error"; - -static const char* kMediaplayerURL = "chrome://mediaplayer"; -static const char* kMediaplayerPlaylistURL = "chrome://mediaplayer#playlist"; -static const int kPopupLeft = 0; -static const int kPopupTop = 0; -static const int kPopupWidth = 350; -static const int kPopupHeight = 300; - -class MediaplayerUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - explicit MediaplayerUIHTMLSource(bool is_playlist); - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const { - return "text/html"; - } - - private: - ~MediaplayerUIHTMLSource() {} - bool is_playlist_; - - DISALLOW_COPY_AND_ASSIGN(MediaplayerUIHTMLSource); -}; - -// The handler for Javascript messages related to the "mediaplayer" view. -class MediaplayerHandler : public WebUIMessageHandler, - public base::SupportsWeakPtr<MediaplayerHandler> { - public: - - struct MediaUrl { - MediaUrl() {} - explicit MediaUrl(const GURL& newurl) - : url(newurl), - haderror(false) {} - GURL url; - bool haderror; - }; - typedef std::vector<MediaUrl> UrlVector; - - explicit MediaplayerHandler(bool is_playlist); - - virtual ~MediaplayerHandler(); - - // Init work after Attach. - void Init(bool is_playlist, TabContents* contents); - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Callback for the "currentOffsetChanged" message. - void HandleCurrentOffsetChanged(const ListValue* args); - - void FirePlaylistChanged(const std::string& path, - bool force, - int offset); - - void PlaybackMediaFile(const GURL& url); - - void EnqueueMediaFile(const GURL& url); - - void GetPlaylistValue(ListValue& args); - - // Callback for the "playbackError" message. - void HandlePlaybackError(const ListValue* args); - - // Callback for the "getCurrentPlaylist" message. - void HandleGetCurrentPlaylist(const ListValue* args); - - void HandleTogglePlaylist(const ListValue* args); - void HandleShowPlaylist(const ListValue* args); - void HandleSetCurrentPlaylistOffset(const ListValue* args); - void HandleToggleFullscreen(const ListValue* args); - - const UrlVector& GetCurrentPlaylist(); - - int GetCurrentPlaylistOffset(); - void SetCurrentPlaylistOffset(int offset); - // Sets the playlist for playlist views, since the playlist is - // maintained by the mediaplayer itself. Offset is the item in the - // playlist which is either now playing, or should be played. - void SetCurrentPlaylist(const UrlVector& playlist, int offset); - - private: - // The current playlist of urls. - UrlVector current_playlist_; - // The offset into the current_playlist_ of the currently playing item. - int current_offset_; - // Indicator of if this handler is a playlist or a mediaplayer. - bool is_playlist_; - DISALLOW_COPY_AND_ASSIGN(MediaplayerHandler); -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// MediaplayerHTMLSource -// -//////////////////////////////////////////////////////////////////////////////// - -MediaplayerUIHTMLSource::MediaplayerUIHTMLSource(bool is_playlist) - : DataSource(chrome::kChromeUIMediaplayerHost, MessageLoop::current()) { - is_playlist_ = is_playlist; -} - -void MediaplayerUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - DictionaryValue localized_strings; - // TODO(dhg): Fix the strings that are currently hardcoded so they - // use the localized versions. - localized_strings.SetString("errorstring", "Error Playing Back"); - - SetFontAndTextDirection(&localized_strings); - - std::string full_html; - - static const base::StringPiece mediaplayer_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_MEDIAPLAYER_HTML)); - - static const base::StringPiece playlist_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_MEDIAPLAYERPLAYLIST_HTML)); - - if (is_playlist_) { - full_html = jstemplate_builder::GetI18nTemplateHtml( - playlist_html, &localized_strings); - } else { - full_html = jstemplate_builder::GetI18nTemplateHtml( - mediaplayer_html, &localized_strings); - } - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - - SendResponse(request_id, html_bytes); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// MediaplayerHandler -// -//////////////////////////////////////////////////////////////////////////////// -MediaplayerHandler::MediaplayerHandler(bool is_playlist) - : current_offset_(0), - is_playlist_(is_playlist) { -} - -MediaplayerHandler::~MediaplayerHandler() { -} - -WebUIMessageHandler* MediaplayerHandler::Attach(WebUI* web_ui) { - // Create our favicon data source. - Profile* profile = web_ui->GetProfile(); - profile->GetChromeURLDataManager()->AddDataSource( - new WebUIFavIconSource(profile)); - - return WebUIMessageHandler::Attach(web_ui); -} - -void MediaplayerHandler::Init(bool is_playlist, TabContents* contents) { - MediaPlayer* player = MediaPlayer::GetInstance(); - if (!is_playlist) { - player->SetNewHandler(this, contents); - } else { - player->RegisterNewPlaylistHandler(this, contents); - } -} - -void MediaplayerHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("currentOffsetChanged", - NewCallback(this, &MediaplayerHandler::HandleCurrentOffsetChanged)); - web_ui_->RegisterMessageCallback("playbackError", - NewCallback(this, &MediaplayerHandler::HandlePlaybackError)); - web_ui_->RegisterMessageCallback("getCurrentPlaylist", - NewCallback(this, &MediaplayerHandler::HandleGetCurrentPlaylist)); - web_ui_->RegisterMessageCallback("togglePlaylist", - NewCallback(this, &MediaplayerHandler::HandleTogglePlaylist)); - web_ui_->RegisterMessageCallback("setCurrentPlaylistOffset", - NewCallback(this, &MediaplayerHandler::HandleSetCurrentPlaylistOffset)); - web_ui_->RegisterMessageCallback("toggleFullscreen", - NewCallback(this, &MediaplayerHandler::HandleToggleFullscreen)); - web_ui_->RegisterMessageCallback("showPlaylist", - NewCallback(this, &MediaplayerHandler::HandleShowPlaylist)); -} - -void MediaplayerHandler::GetPlaylistValue(ListValue& urls) { - for (size_t x = 0; x < current_playlist_.size(); x++) { - DictionaryValue* url_value = new DictionaryValue(); - url_value->SetString(kPropertyPath, current_playlist_[x].url.spec()); - url_value->SetBoolean(kPropertyError, current_playlist_[x].haderror); - urls.Append(url_value); - } -} - -void MediaplayerHandler::PlaybackMediaFile(const GURL& url) { - current_playlist_.clear(); - current_playlist_.push_back(MediaplayerHandler::MediaUrl(url)); - FirePlaylistChanged(url.spec(), true, 0); - MediaPlayer::GetInstance()->NotifyPlaylistChanged(); -} - -const MediaplayerHandler::UrlVector& MediaplayerHandler::GetCurrentPlaylist() { - return current_playlist_; -} - -int MediaplayerHandler::GetCurrentPlaylistOffset() { - return current_offset_; -} - -void MediaplayerHandler::HandleToggleFullscreen(const ListValue* args) { - MediaPlayer::GetInstance()->ToggleFullscreen(); -} - -void MediaplayerHandler::HandleSetCurrentPlaylistOffset(const ListValue* args) { - int id; - CHECK(ExtractIntegerValue(args, &id)); - MediaPlayer::GetInstance()->SetPlaylistOffset(id); -} - -void MediaplayerHandler::FirePlaylistChanged(const std::string& path, - bool force, - int offset) { - DictionaryValue info_value; - ListValue urls; - GetPlaylistValue(urls); - info_value.SetString(kPropertyPath, path); - info_value.SetBoolean(kPropertyForce, force); - info_value.SetInteger(kPropertyOffset, offset); - web_ui_->CallJavascriptFunction(L"playlistChanged", info_value, urls); -} - -void MediaplayerHandler::SetCurrentPlaylistOffset(int offset) { - current_offset_ = offset; - FirePlaylistChanged(std::string(), true, current_offset_); -} - -void MediaplayerHandler::SetCurrentPlaylist( - const MediaplayerHandler::UrlVector& playlist, int offset) { - current_playlist_ = playlist; - current_offset_ = offset; - FirePlaylistChanged(std::string(), false, current_offset_); -} - -void MediaplayerHandler::EnqueueMediaFile(const GURL& url) { - current_playlist_.push_back(MediaplayerHandler::MediaUrl(url)); - FirePlaylistChanged(url.spec(), false, current_offset_); - MediaPlayer::GetInstance()->NotifyPlaylistChanged(); -} - -void MediaplayerHandler::HandleCurrentOffsetChanged(const ListValue* args) { - CHECK(ExtractIntegerValue(args, ¤t_offset_)); - MediaPlayer::GetInstance()->NotifyPlaylistChanged(); -} - -void MediaplayerHandler::HandlePlaybackError(const ListValue* args) { - std::string error; - std::string url; - // Get path string. - if (args->GetString(0, &error)) - LOG(ERROR) << "Playback error" << error; - if (args->GetString(1, &url)) { - for (size_t x = 0; x < current_playlist_.size(); x++) { - if (current_playlist_[x].url == GURL(url)) { - current_playlist_[x].haderror = true; - } - } - FirePlaylistChanged(std::string(), false, current_offset_); - } -} - -void MediaplayerHandler::HandleGetCurrentPlaylist(const ListValue* args) { - FirePlaylistChanged(std::string(), false, current_offset_); -} - -void MediaplayerHandler::HandleTogglePlaylist(const ListValue* args) { - MediaPlayer::GetInstance()->TogglePlaylistWindowVisible(); -} - -void MediaplayerHandler::HandleShowPlaylist(const ListValue* args) { - MediaPlayer::GetInstance()->ShowPlaylistWindow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// Mediaplayer -// -//////////////////////////////////////////////////////////////////////////////// - -// Allows InvokeLater without adding refcounting. This class is a Singleton and -// won't be deleted until it's last InvokeLater is run. -DISABLE_RUNNABLE_METHOD_REFCOUNT(MediaPlayer); - -MediaPlayer::~MediaPlayer() { -} - -// static -MediaPlayer* MediaPlayer::GetInstance() { - return Singleton<MediaPlayer>::get(); -} - -void MediaPlayer::EnqueueMediaURL(const GURL& url, Browser* creator) { - if (!Enabled()) { - return; - } - if (handler_ == NULL) { - unhandled_urls_.push_back(url); - PopupMediaPlayer(creator); - } else { - handler_->EnqueueMediaFile(url); - } -} - -void MediaPlayer::ForcePlayMediaURL(const GURL& url, Browser* creator) { - if (!Enabled()) { - return; - } - if (handler_ == NULL) { - unhandled_urls_.push_back(url); - PopupMediaPlayer(creator); - } else { - handler_->PlaybackMediaFile(url); - } -} - -bool MediaPlayer::Enabled() { -#if defined(OS_CHROMEOS) - return CommandLine::ForCurrentProcess()->HasSwitch( - switches::kEnableMediaPlayer); -#else - return true; -#endif -} - -void MediaPlayer::TogglePlaylistWindowVisible() { - if (playlist_browser_) { - ClosePlaylistWindow(); - } else { - ShowPlaylistWindow(); - } -} - -void MediaPlayer::ShowPlaylistWindow() { - if (playlist_browser_ == NULL) { - PopupPlaylist(NULL); - } -} - -void MediaPlayer::ClosePlaylistWindow() { - if (playlist_browser_ != NULL) { - playlist_browser_->window()->Close(); - } -} - -void MediaPlayer::SetPlaylistOffset(int offset) { - if (handler_) { - handler_->SetCurrentPlaylistOffset(offset); - } - if (playlist_) { - playlist_->SetCurrentPlaylistOffset(offset); - } -} - -void MediaPlayer::SetNewHandler(MediaplayerHandler* handler, - TabContents* contents) { - handler_ = handler; - mediaplayer_tab_ = contents; - RegisterListeners(); - for (size_t x = 0; x < unhandled_urls_.size(); x++) { - handler_->EnqueueMediaFile(unhandled_urls_[x]); - } - unhandled_urls_.clear(); -} - -void MediaPlayer::RegisterListeners() { - registrar_.RemoveAll(); - if (playlist_tab_) { - registrar_.Add(this, - NotificationType::TAB_CONTENTS_DESTROYED, - Source<TabContents>(playlist_tab_)); - } - if (mediaplayer_tab_) { - registrar_.Add(this, - NotificationType::TAB_CONTENTS_DESTROYED, - Source<TabContents>(mediaplayer_tab_)); - } -}; - -void MediaPlayer::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED); - if (Source<TabContents>(source).ptr() == mediaplayer_tab_) { - RemoveHandler(handler_); - RegisterListeners(); - ClosePlaylistWindow(); - } else if (Source<TabContents>(source).ptr() == playlist_tab_) { - RemovePlaylistHandler(playlist_); - RegisterListeners(); - } -} - -void MediaPlayer::RegisterNewPlaylistHandler(MediaplayerHandler* handler, - TabContents* contents) { - playlist_ = handler; - playlist_tab_ = contents; - RegisterListeners(); - NotifyPlaylistChanged(); -} - -void MediaPlayer::RemovePlaylistHandler(MediaplayerHandler* handler) { - if (handler == playlist_) { - playlist_ = NULL; - playlist_browser_ = NULL; - playlist_tab_ = NULL; - } -} - -void MediaPlayer::NotifyPlaylistChanged() { - if (handler_ && playlist_) { - playlist_->SetCurrentPlaylist(handler_->GetCurrentPlaylist(), - handler_->GetCurrentPlaylistOffset()); - } -} - -void MediaPlayer::ToggleFullscreen() { - if (handler_ && mediaplayer_browser_) { - mediaplayer_browser_->ToggleFullscreenMode(); - } -} - -void MediaPlayer::RemoveHandler(MediaplayerHandler* handler) { - if (handler == handler_) { - handler_ = NULL; - mediaplayer_browser_ = NULL; - mediaplayer_tab_ = NULL; - } -} - -void MediaPlayer::PopupPlaylist(Browser* creator) { - Profile* profile = BrowserList::GetLastActive()->profile(); - playlist_browser_ = Browser::CreateForType(Browser::TYPE_APP_PANEL, - profile); - playlist_browser_->AddSelectedTabWithURL(GURL(kMediaplayerPlaylistURL), - PageTransition::LINK); - playlist_browser_->window()->SetBounds(gfx::Rect(kPopupLeft, - kPopupTop, - kPopupWidth, - kPopupHeight)); - playlist_browser_->window()->Show(); -} - -void MediaPlayer::PopupMediaPlayer(Browser* creator) { - if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod(this, &MediaPlayer::PopupMediaPlayer, - static_cast<Browser*>(NULL))); - return; - } - Profile* profile = BrowserList::GetLastActive()->profile(); - mediaplayer_browser_ = Browser::CreateForType(Browser::TYPE_APP_PANEL, - profile); -#if defined(OS_CHROMEOS) - // Since we are on chromeos, popups should be a PanelBrowserView, - // so we can just cast it. - if (creator) { - chromeos::PanelBrowserView* creatorview = - static_cast<chromeos::PanelBrowserView*>(creator->window()); - chromeos::PanelBrowserView* view = - static_cast<chromeos::PanelBrowserView*>( - mediaplayer_browser_->window()); - view->SetCreatorView(creatorview); - } -#endif - mediaplayer_browser_->AddSelectedTabWithURL(GURL(kMediaplayerURL), - PageTransition::LINK); - mediaplayer_browser_->window()->SetBounds(gfx::Rect(kPopupLeft, - kPopupTop, - kPopupWidth, - kPopupHeight)); - mediaplayer_browser_->window()->Show(); -} - -net::URLRequestJob* MediaPlayer::MaybeIntercept(net::URLRequest* request) { - // Don't attempt to intercept here as we want to wait until the mime - // type is fully determined. - return NULL; -} - -// This is the list of mime types currently supported by the Google -// Document Viewer. -static const char* const supported_mime_type_list[] = { - "audio/mpeg", - "video/mp4", - "audio/mp3" -}; - -net::URLRequestJob* MediaPlayer::MaybeInterceptResponse( - net::URLRequest* request) { - // Do not intercept this request if it is a download. - if (request->load_flags() & net::LOAD_IS_DOWNLOAD) { - return NULL; - } - - std::string mime_type; - request->GetMimeType(&mime_type); - // If it is in our list of known URLs, enqueue the url then - // Cancel the request so the mediaplayer can handle it when - // it hits it in the playlist. - if (supported_mime_types_.find(mime_type) != supported_mime_types_.end()) { - if (request->referrer() != chrome::kChromeUIMediaplayerURL && - !request->referrer().empty()) { - EnqueueMediaURL(request->url(), NULL); - request->Cancel(); - } - } - return NULL; -} - -MediaPlayer::MediaPlayer() - : handler_(NULL), - playlist_(NULL), - playlist_browser_(NULL), - mediaplayer_browser_(NULL), - mediaplayer_tab_(NULL), - playlist_tab_(NULL) { - for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) { - supported_mime_types_.insert(supported_mime_type_list[i]); - } -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// MediaplayerUIContents -// -//////////////////////////////////////////////////////////////////////////////// - -MediaplayerUI::MediaplayerUI(TabContents* contents) : WebUI(contents) { - const GURL& url = contents->GetURL(); - bool is_playlist = (url.ref() == "playlist"); - MediaplayerHandler* handler = new MediaplayerHandler(is_playlist); - AddMessageHandler(handler->Attach(this)); - if (is_playlist) { - handler->Init(true, contents); - } else { - handler->Init(false, contents); - } - - MediaplayerUIHTMLSource* html_source = - new MediaplayerUIHTMLSource(is_playlist); - - // Set up the chrome://mediaplayer/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} diff --git a/chrome/browser/dom_ui/mediaplayer_ui.h b/chrome/browser/dom_ui/mediaplayer_ui.h deleted file mode 100644 index 0c6fcc3..0000000 --- a/chrome/browser/dom_ui/mediaplayer_ui.h +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright (c) 2011 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_DOM_UI_MEDIAPLAYER_UI_H_ -#define CHROME_BROWSER_DOM_UI_MEDIAPLAYER_UI_H_ -#pragma once - -#include <set> -#include <vector> - -#include "chrome/browser/dom_ui/chrome_url_data_manager.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/notification_observer.h" -#include "chrome/common/notification_registrar.h" -#include "chrome/common/notification_source.h" -#include "chrome/common/notification_type.h" -#include "net/base/directory_lister.h" -#include "net/url_request/url_request.h" - -template <typename T> struct DefaultSingletonTraits; -class GURL; -class MediaplayerHandler; -class Browser; - -class MediaPlayer : public NotificationObserver, - public net::URLRequest::Interceptor { - public: - ~MediaPlayer(); - - // Enqueues this url into the current playlist. If the mediaplayer is - // not currently visible, show it, and play the given url. - void EnqueueMediaURL(const GURL& url, Browser* creator); - - // Clears out the current playlist, and start playback of the given url. - // If there is no mediaplayer currently, show it, and play the given url. - void ForcePlayMediaURL(const GURL& url, Browser* creator); - - // Toggle the visibility of the playlist window. - void TogglePlaylistWindowVisible(); - - // Force the playlist window to be shown. - void ShowPlaylistWindow(); - - // Toggle the mediaplayer between fullscreen and windowed. - void ToggleFullscreen(); - - // Force the playlist window to be closed. - void ClosePlaylistWindow(); - - // Sets the currently playing element to the given offset. - void SetPlaylistOffset(int offset); - - // Set a new playback handler to give events to, along with the - // tab contents of the page which holds the mediaplayer. it is expected - // That only one of these will exist at any given time. - void SetNewHandler(MediaplayerHandler* handler, - TabContents* contents); - - // Removes the handler. - void RemoveHandler(MediaplayerHandler* handler); - - // Registers a new playlist handler which receives events from the - // mediaplayer, along with the tab contents which has the playlist in it. - void RegisterNewPlaylistHandler(MediaplayerHandler* handler, - TabContents* contents); - - // Removes the playlist handler. - void RemovePlaylistHandler(MediaplayerHandler* handler); - - // Notfiys the mediaplayer that the playlist changed. This could be - // called from the mediaplayer itself for example. - void NotifyPlaylistChanged(); - - // Always returns NULL because we don't want to attempt a redirect - // before seeing the detected mime type of the request. - // Implementation of net::URLRequest::Interceptor. - virtual net::URLRequestJob* MaybeIntercept(net::URLRequest* request); - - // Determines if the requested document can be viewed by the - // MediaPlayer. If it can, returns a net::URLRequestJob that - // redirects the browser to the view URL. - // Implementation of net::URLRequest::Interceptor. - virtual net::URLRequestJob* MaybeInterceptResponse(net::URLRequest* request); - - // Used to detect when the mediaplayer is closed. - void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - // Getter for the singleton. - static MediaPlayer* GetInstance(); - - private: - friend struct DefaultSingletonTraits<MediaPlayer>; - - MediaPlayer(); - - // Popup the mediaplayer, this shows the browser, and sets up its - // locations correctly. - void PopupMediaPlayer(Browser* creator); - - // Checks to see the the mediaplayer is currently enabled - bool Enabled(); - - // Popup the playlist. Shows the browser, sets it up to point at - // chrome://mediaplayer#playlist - void PopupPlaylist(Browser* creator); - - // Registers the listeners for the close events on the browser windows. - void RegisterListeners(); - - // Set when the register handler is called. When the media player is - // closed, this pointer is set back to NULL. - MediaplayerHandler* handler_; - - // Set when the register playlist handler is called. When the playlist - // is closed, this pointer is set back to NULL. - MediaplayerHandler* playlist_; - - // Browser containing the playlist. Used to force closes. This is created - // By the PopupPlaylist call, and is NULLed out when the window is closed. - Browser* playlist_browser_; - - // Browser containing the Mediaplayer. Used to force closes. This is - // created by the PopupMediaplayer call, and is NULLed out when the window - // is closed. - Browser* mediaplayer_browser_; - - // List of URLs that were enqueued during the time that the mediaplayer - // had not poped up yet. This is claered out after the mediaplayer pops up. - std::vector<GURL> unhandled_urls_; - - // Used to register for events on the windows, like to listen for closes. - NotificationRegistrar registrar_; - - // Tab contents of the mediaplayer. Used to listen for events - // which would cause the mediaplayer to be closed. These are cleared out - // when the mediaplayer is closed. - TabContents* mediaplayer_tab_; - - // Tab contents of the playlist tab. used to listen for events which would - // cause the mediaplayer to be closed. These are cleared out when the - // playlist is closed. - TabContents* playlist_tab_; - - // List of mimetypes that the mediaplayer should listen to. Used for - // interceptions of url GETs. - std::set<std::string> supported_mime_types_; - DISALLOW_COPY_AND_ASSIGN(MediaPlayer); -}; - -class MediaplayerUI : public WebUI { - public: - explicit MediaplayerUI(TabContents* contents); - - private: - DISALLOW_COPY_AND_ASSIGN(MediaplayerUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_MEDIAPLAYER_UI_H_ diff --git a/chrome/browser/dom_ui/net_internals_ui.cc b/chrome/browser/dom_ui/net_internals_ui.cc deleted file mode 100644 index 6808367..0000000 --- a/chrome/browser/dom_ui/net_internals_ui.cc +++ /dev/null @@ -1,1315 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/net_internals_ui.h" - -#include <algorithm> -#include <string> -#include <utility> -#include <vector> - -#include "base/command_line.h" -#include "base/file_util.h" -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/singleton.h" -#include "base/string_number_conversions.h" -#include "base/string_piece.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/chrome_url_data_manager.h" -#include "chrome/browser/io_thread.h" -#include "chrome/browser/net/chrome_net_log.h" -#include "chrome/browser/net/connection_tester.h" -#include "chrome/browser/net/passive_log_collector.h" -#include "chrome/browser/net/url_fixer_upper.h" -#include "chrome/browser/platform_util.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/tab_contents/tab_contents_view.h" -#include "chrome/browser/ui/shell_dialogs.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/chrome_version_info.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/net/url_request_context_getter.h" -#include "chrome/common/url_constants.h" -#include "grit/generated_resources.h" -#include "grit/net_internals_resources.h" -#include "net/base/escape.h" -#include "net/base/host_resolver_impl.h" -#include "net/base/net_errors.h" -#include "net/base/net_util.h" -#include "net/base/sys_addrinfo.h" -#include "net/disk_cache/disk_cache.h" -#include "net/http/http_alternate_protocols.h" -#include "net/http/http_cache.h" -#include "net/http/http_stream_factory.h" -#include "net/http/http_network_layer.h" -#include "net/http/http_network_session.h" -#include "net/proxy/proxy_service.h" -#include "net/url_request/url_request_context.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" - -#ifdef OS_WIN -#include "chrome/browser/net/service_providers_win.h" -#endif - -namespace { - -// Delay between when an event occurs and when it is passed to the Javascript -// page. All events that occur during this period are grouped together and -// sent to the page at once, which reduces context switching and CPU usage. -const int kNetLogEventDelayMilliseconds = 100; - -// Returns the HostCache for |context|'s primary HostResolver, or NULL if -// there is none. -net::HostCache* GetHostResolverCache(net::URLRequestContext* context) { - net::HostResolverImpl* host_resolver_impl = - context->host_resolver()->GetAsHostResolverImpl(); - - if (!host_resolver_impl) - return NULL; - - return host_resolver_impl->cache(); -} - -// Returns the disk cache backend for |context| if there is one, or NULL. -disk_cache::Backend* GetDiskCacheBackend(net::URLRequestContext* context) { - if (!context->http_transaction_factory()) - return NULL; - - net::HttpCache* http_cache = context->http_transaction_factory()->GetCache(); - if (!http_cache) - return NULL; - - return http_cache->GetCurrentBackend(); -} - -// Returns the http network session for |context| if there is one. -// Otherwise, returns NULL. -net::HttpNetworkSession* GetHttpNetworkSession( - net::URLRequestContext* context) { - if (!context->http_transaction_factory()) - return NULL; - - return context->http_transaction_factory()->GetSession(); -} - -Value* ExperimentToValue(const ConnectionTester::Experiment& experiment) { - DictionaryValue* dict = new DictionaryValue(); - - if (experiment.url.is_valid()) - dict->SetString("url", experiment.url.spec()); - - dict->SetString("proxy_settings_experiment", - ConnectionTester::ProxySettingsExperimentDescription( - experiment.proxy_settings_experiment)); - dict->SetString("host_resolver_experiment", - ConnectionTester::HostResolverExperimentDescription( - experiment.host_resolver_experiment)); - return dict; -} - -class NetInternalsHTMLSource : public ChromeURLDataManager::DataSource { - public: - NetInternalsHTMLSource(); - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const; - - private: - ~NetInternalsHTMLSource() {} - DISALLOW_COPY_AND_ASSIGN(NetInternalsHTMLSource); -}; - -// This class receives javascript messages from the renderer. -// Note that the WebUI infrastructure runs on the UI thread, therefore all of -// this class's methods are expected to run on the UI thread. -// -// Since the network code we want to run lives on the IO thread, we proxy -// everything over to NetInternalsMessageHandler::IOThreadImpl, which runs -// on the IO thread. -// -// TODO(eroman): Can we start on the IO thread to begin with? -class NetInternalsMessageHandler - : public WebUIMessageHandler, - public SelectFileDialog::Listener, - public base::SupportsWeakPtr<NetInternalsMessageHandler> { - public: - NetInternalsMessageHandler(); - virtual ~NetInternalsMessageHandler(); - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Executes the javascript function |function_name| in the renderer, passing - // it the argument |value|. - void CallJavascriptFunction(const std::wstring& function_name, - const Value* value); - - // SelectFileDialog::Listener implementation - virtual void FileSelected(const FilePath& path, int index, void* params); - virtual void FileSelectionCanceled(void* params); - - // The only callback handled on the UI thread. As it needs to access fields - // from |web_ui_|, it can't be called on the IO thread. - void OnLoadLogFile(const ListValue* list); - - private: - class IOThreadImpl; - - // Task run on the FILE thread to read the contents of a log file. The result - // is then passed to IOThreadImpl's CallJavascriptFunction, which sends it - // back to the web page. IOThreadImpl is used instead of the - // NetInternalsMessageHandler directly because it checks if the message - // handler has been destroyed in the meantime. - class ReadLogFileTask : public Task { - public: - ReadLogFileTask(IOThreadImpl* proxy, const FilePath& path); - - virtual void Run(); - - private: - // IOThreadImpl implements existence checks already. Simpler to reused them - // then to reimplement them. - scoped_refptr<IOThreadImpl> proxy_; - - // Path of the file to open. - const FilePath path_; - }; - - // This is the "real" message handler, which lives on the IO thread. - scoped_refptr<IOThreadImpl> proxy_; - - // Used for loading log files. - scoped_refptr<SelectFileDialog> select_log_file_dialog_; - - DISALLOW_COPY_AND_ASSIGN(NetInternalsMessageHandler); -}; - -// This class is the "real" message handler. It is allocated and destroyed on -// the UI thread. With the exception of OnAddEntry, OnWebUIDeleted, and -// CallJavascriptFunction, its methods are all expected to be called from the IO -// thread. OnAddEntry and CallJavascriptFunction can be called from any thread, -// and OnWebUIDeleted can only be called from the UI thread. -class NetInternalsMessageHandler::IOThreadImpl - : public base::RefCountedThreadSafe< - NetInternalsMessageHandler::IOThreadImpl, - BrowserThread::DeleteOnUIThread>, - public ChromeNetLog::ThreadSafeObserver, - public ConnectionTester::Delegate { - public: - // Type for methods that can be used as MessageHandler callbacks. - typedef void (IOThreadImpl::*MessageHandler)(const ListValue*); - - // Creates a proxy for |handler| that will live on the IO thread. - // |handler| is a weak pointer, since it is possible for the - // WebUIMessageHandler to be deleted on the UI thread while we were executing - // on the IO thread. |io_thread| is the global IOThread (it is passed in as - // an argument since we need to grab it from the UI thread). - IOThreadImpl( - const base::WeakPtr<NetInternalsMessageHandler>& handler, - IOThread* io_thread, - URLRequestContextGetter* context_getter); - - ~IOThreadImpl(); - - // Creates a callback that will run |method| on the IO thread. - // - // This can be used with WebUI::RegisterMessageCallback() to bind to a method - // on the IO thread. - WebUI::MessageCallback* CreateCallback(MessageHandler method); - - // Called once the WebUI has been deleted (i.e. renderer went away), on the - // IO thread. - void Detach(); - - // Sends all passive log entries in |passive_entries| to the Javascript - // handler, called on the IO thread. - void SendPassiveLogEntries(const ChromeNetLog::EntryList& passive_entries); - - // Called when the WebUI is deleted. Prevents calling Javascript functions - // afterwards. Called on UI thread. - void OnWebUIDeleted(); - - //-------------------------------- - // Javascript message handlers: - //-------------------------------- - - void OnRendererReady(const ListValue* list); - - void OnGetProxySettings(const ListValue* list); - void OnReloadProxySettings(const ListValue* list); - void OnGetBadProxies(const ListValue* list); - void OnClearBadProxies(const ListValue* list); - void OnGetHostResolverInfo(const ListValue* list); - void OnClearHostResolverCache(const ListValue* list); - void OnEnableIPv6(const ListValue* list); - void OnStartConnectionTests(const ListValue* list); - void OnHSTSQuery(const ListValue* list); - void OnHSTSAdd(const ListValue* list); - void OnHSTSDelete(const ListValue* list); - void OnGetHttpCacheInfo(const ListValue* list); - void OnGetSocketPoolInfo(const ListValue* list); - void OnGetSpdySessionInfo(const ListValue* list); - void OnGetSpdyStatus(const ListValue* list); - void OnGetSpdyAlternateProtocolMappings(const ListValue* list); -#ifdef OS_WIN - void OnGetServiceProviders(const ListValue* list); -#endif - - void OnSetLogLevel(const ListValue* list); - - // ChromeNetLog::ThreadSafeObserver implementation: - virtual void OnAddEntry(net::NetLog::EventType type, - const base::TimeTicks& time, - const net::NetLog::Source& source, - net::NetLog::EventPhase phase, - net::NetLog::EventParameters* params); - - // ConnectionTester::Delegate implementation: - virtual void OnStartConnectionTestSuite(); - virtual void OnStartConnectionTestExperiment( - const ConnectionTester::Experiment& experiment); - virtual void OnCompletedConnectionTestExperiment( - const ConnectionTester::Experiment& experiment, - int result); - virtual void OnCompletedConnectionTestSuite(); - - // Helper that executes |function_name| in the attached renderer. - // The function takes ownership of |arg|. Note that this can be called from - // any thread. - void CallJavascriptFunction(const std::wstring& function_name, Value* arg); - - private: - class CallbackHelper; - - // Helper that runs |method| with |arg|, and deletes |arg| on completion. - void DispatchToMessageHandler(ListValue* arg, MessageHandler method); - - // Adds |entry| to the queue of pending log entries to be sent to the page via - // Javascript. Must be called on the IO Thread. Also creates a delayed task - // that will call PostPendingEntries, if there isn't one already. - void AddEntryToQueue(Value* entry); - - // Sends all pending entries to the page via Javascript, and clears the list - // of pending entries. Sending multiple entries at once results in a - // significant reduction of CPU usage when a lot of events are happening. - // Must be called on the IO Thread. - void PostPendingEntries(); - - // Pointer to the UI-thread message handler. Only access this from - // the UI thread. - base::WeakPtr<NetInternalsMessageHandler> handler_; - - // The global IOThread, which contains the global NetLog to observer. - IOThread* io_thread_; - - scoped_refptr<URLRequestContextGetter> context_getter_; - - // Helper that runs the suite of connection tests. - scoped_ptr<ConnectionTester> connection_tester_; - - // True if the Web UI has been deleted. This is used to prevent calling - // Javascript functions after the Web UI is destroyed. On refresh, the - // messages can end up being sent to the refreshed page, causing duplicate - // or partial entries. - // - // This is only read and written to on the UI thread. - bool was_webui_deleted_; - - // True if we have attached an observer to the NetLog already. - bool is_observing_log_; - friend class base::RefCountedThreadSafe<IOThreadImpl>; - - // Log entries that have yet to be passed along to Javascript page. Non-NULL - // when and only when there is a pending delayed task to call - // PostPendingEntries. Read and written to exclusively on the IO Thread. - scoped_ptr<ListValue> pending_entries_; -}; - -// Helper class for a WebUI::MessageCallback which when excuted calls -// instance->*method(value) on the IO thread. -class NetInternalsMessageHandler::IOThreadImpl::CallbackHelper - : public WebUI::MessageCallback { - public: - CallbackHelper(IOThreadImpl* instance, IOThreadImpl::MessageHandler method) - : instance_(instance), - method_(method) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - } - - virtual void RunWithParams(const Tuple1<const ListValue*>& params) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - - // We need to make a copy of the value in order to pass it over to the IO - // thread. We will delete this in IOThreadImpl::DispatchMessageHandler(). - ListValue* list_copy = static_cast<ListValue*>( - params.a ? params.a->DeepCopy() : NULL); - - if (!BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - NewRunnableMethod(instance_.get(), - &IOThreadImpl::DispatchToMessageHandler, - list_copy, method_))) { - // Failed posting the task, avoid leaking |list_copy|. - delete list_copy; - } - } - - private: - scoped_refptr<IOThreadImpl> instance_; - IOThreadImpl::MessageHandler method_; -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// NetInternalsHTMLSource -// -//////////////////////////////////////////////////////////////////////////////// - -NetInternalsHTMLSource::NetInternalsHTMLSource() - : DataSource(chrome::kChromeUINetInternalsHost, MessageLoop::current()) { -} - -void NetInternalsHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - DictionaryValue localized_strings; - SetFontAndTextDirection(&localized_strings); - - // The provided "path" may contain a fragment, or query section. We only - // care about the path itself, and will disregard anything else. - std::string filename = - GURL(std::string("chrome://net/") + path).path().substr(1); - - // The source for the net internals page is flattened during compilation, so - // the only resource that should legitimately be requested is the main file. - // Note that users can type anything into the address bar, though, so we must - // handle arbitrary input. - if (filename.empty() || filename == "index.html") { - base::StringPiece html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_NET_INTERNALS_INDEX_HTML)); - std::string full_html(html.data(), html.size()); - jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html); - jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html); - jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html); - jstemplate_builder::AppendJsTemplateSourceHtml(&full_html); - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - SendResponse(request_id, html_bytes); - return; - } - - const std::string data_string("<p style='color:red'>Failed to read resource" + - EscapeForHTML(filename) + "</p>"); - scoped_refptr<RefCountedBytes> bytes(new RefCountedBytes); - bytes->data.resize(data_string.size()); - std::copy(data_string.begin(), data_string.end(), bytes->data.begin()); - SendResponse(request_id, bytes); -} - -std::string NetInternalsHTMLSource::GetMimeType(const std::string&) const { - return "text/html"; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// NetInternalsMessageHandler -// -//////////////////////////////////////////////////////////////////////////////// - -NetInternalsMessageHandler::NetInternalsMessageHandler() {} - -NetInternalsMessageHandler::~NetInternalsMessageHandler() { - if (proxy_) { - proxy_.get()->OnWebUIDeleted(); - // Notify the handler on the IO thread that the renderer is gone. - BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, - NewRunnableMethod(proxy_.get(), &IOThreadImpl::Detach)); - } - if (select_log_file_dialog_) - select_log_file_dialog_->ListenerDestroyed(); -} - -WebUIMessageHandler* NetInternalsMessageHandler::Attach(WebUI* web_ui) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - proxy_ = new IOThreadImpl(this->AsWeakPtr(), g_browser_process->io_thread(), - web_ui->GetProfile()->GetRequestContext()); - WebUIMessageHandler* result = WebUIMessageHandler::Attach(web_ui); - return result; -} - -void NetInternalsMessageHandler::FileSelected( - const FilePath& path, int index, void* params) { - select_log_file_dialog_.release(); - BrowserThread::PostTask( - BrowserThread::FILE, FROM_HERE, - new ReadLogFileTask(proxy_.get(), path)); -} - -void NetInternalsMessageHandler::FileSelectionCanceled(void* params) { - select_log_file_dialog_.release(); -} - -void NetInternalsMessageHandler::OnLoadLogFile(const ListValue* list) { - // Only allow a single dialog at a time. - if (select_log_file_dialog_.get()) - return; - select_log_file_dialog_ = SelectFileDialog::Create(this); - select_log_file_dialog_->SelectFile( - SelectFileDialog::SELECT_OPEN_FILE, string16(), FilePath(), NULL, 0, - FILE_PATH_LITERAL(""), - web_ui_->tab_contents()->view()->GetTopLevelNativeWindow(), NULL); -} - -void NetInternalsMessageHandler::RegisterMessages() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - // Only callback handled on UI thread. - web_ui_->RegisterMessageCallback( - "loadLogFile", - NewCallback(this, &NetInternalsMessageHandler::OnLoadLogFile)); - - web_ui_->RegisterMessageCallback( - "notifyReady", - proxy_->CreateCallback(&IOThreadImpl::OnRendererReady)); - web_ui_->RegisterMessageCallback( - "getProxySettings", - proxy_->CreateCallback(&IOThreadImpl::OnGetProxySettings)); - web_ui_->RegisterMessageCallback( - "reloadProxySettings", - proxy_->CreateCallback(&IOThreadImpl::OnReloadProxySettings)); - web_ui_->RegisterMessageCallback( - "getBadProxies", - proxy_->CreateCallback(&IOThreadImpl::OnGetBadProxies)); - web_ui_->RegisterMessageCallback( - "clearBadProxies", - proxy_->CreateCallback(&IOThreadImpl::OnClearBadProxies)); - web_ui_->RegisterMessageCallback( - "getHostResolverInfo", - proxy_->CreateCallback(&IOThreadImpl::OnGetHostResolverInfo)); - web_ui_->RegisterMessageCallback( - "clearHostResolverCache", - proxy_->CreateCallback(&IOThreadImpl::OnClearHostResolverCache)); - web_ui_->RegisterMessageCallback( - "enableIPv6", - proxy_->CreateCallback(&IOThreadImpl::OnEnableIPv6)); - web_ui_->RegisterMessageCallback( - "startConnectionTests", - proxy_->CreateCallback(&IOThreadImpl::OnStartConnectionTests)); - web_ui_->RegisterMessageCallback( - "hstsQuery", - proxy_->CreateCallback(&IOThreadImpl::OnHSTSQuery)); - web_ui_->RegisterMessageCallback( - "hstsAdd", - proxy_->CreateCallback(&IOThreadImpl::OnHSTSAdd)); - web_ui_->RegisterMessageCallback( - "hstsDelete", - proxy_->CreateCallback(&IOThreadImpl::OnHSTSDelete)); - web_ui_->RegisterMessageCallback( - "getHttpCacheInfo", - proxy_->CreateCallback(&IOThreadImpl::OnGetHttpCacheInfo)); - web_ui_->RegisterMessageCallback( - "getSocketPoolInfo", - proxy_->CreateCallback(&IOThreadImpl::OnGetSocketPoolInfo)); - web_ui_->RegisterMessageCallback( - "getSpdySessionInfo", - proxy_->CreateCallback(&IOThreadImpl::OnGetSpdySessionInfo)); - web_ui_->RegisterMessageCallback( - "getSpdyStatus", - proxy_->CreateCallback(&IOThreadImpl::OnGetSpdyStatus)); - web_ui_->RegisterMessageCallback( - "getSpdyAlternateProtocolMappings", - proxy_->CreateCallback( - &IOThreadImpl::OnGetSpdyAlternateProtocolMappings)); -#ifdef OS_WIN - web_ui_->RegisterMessageCallback( - "getServiceProviders", - proxy_->CreateCallback(&IOThreadImpl::OnGetServiceProviders)); -#endif - - web_ui_->RegisterMessageCallback( - "setLogLevel", - proxy_->CreateCallback(&IOThreadImpl::OnSetLogLevel)); -} - -void NetInternalsMessageHandler::CallJavascriptFunction( - const std::wstring& function_name, - const Value* value) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - if (value) { - web_ui_->CallJavascriptFunction(function_name, *value); - } else { - web_ui_->CallJavascriptFunction(function_name); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// -// NetInternalsMessageHandler::ReadLogFileTask -// -//////////////////////////////////////////////////////////////////////////////// - -NetInternalsMessageHandler::ReadLogFileTask::ReadLogFileTask( - IOThreadImpl* proxy, const FilePath& path) - : proxy_(proxy), path_(path) { -} - -void NetInternalsMessageHandler::ReadLogFileTask::Run() { - std::string file_contents; - if (!file_util::ReadFileToString(path_, &file_contents)) - return; - proxy_->CallJavascriptFunction(L"g_browser.loadedLogFile", - new StringValue(file_contents)); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// NetInternalsMessageHandler::IOThreadImpl -// -//////////////////////////////////////////////////////////////////////////////// - -NetInternalsMessageHandler::IOThreadImpl::IOThreadImpl( - const base::WeakPtr<NetInternalsMessageHandler>& handler, - IOThread* io_thread, - URLRequestContextGetter* context_getter) - : ThreadSafeObserver(net::NetLog::LOG_ALL_BUT_BYTES), - handler_(handler), - io_thread_(io_thread), - context_getter_(context_getter), - was_webui_deleted_(false), - is_observing_log_(false) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); -} - -NetInternalsMessageHandler::IOThreadImpl::~IOThreadImpl() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); -} - -WebUI::MessageCallback* -NetInternalsMessageHandler::IOThreadImpl::CreateCallback( - MessageHandler method) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - return new CallbackHelper(this, method); -} - -void NetInternalsMessageHandler::IOThreadImpl::Detach() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - // Unregister with network stack to observe events. - if (is_observing_log_) - io_thread_->net_log()->RemoveObserver(this); - - // Cancel any in-progress connection tests. - connection_tester_.reset(); -} - -void NetInternalsMessageHandler::IOThreadImpl::SendPassiveLogEntries( - const ChromeNetLog::EntryList& passive_entries) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - ListValue* dict_list = new ListValue(); - for (size_t i = 0; i < passive_entries.size(); ++i) { - const ChromeNetLog::Entry& e = passive_entries[i]; - dict_list->Append(net::NetLog::EntryToDictionaryValue(e.type, - e.time, - e.source, - e.phase, - e.params, - false)); - } - - CallJavascriptFunction(L"g_browser.receivedPassiveLogEntries", dict_list); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnWebUIDeleted() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - was_webui_deleted_ = true; -} - -void NetInternalsMessageHandler::IOThreadImpl::OnRendererReady( - const ListValue* list) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK(!is_observing_log_) << "notifyReady called twice"; - - // Tell the javascript about the relationship between event type enums and - // their symbolic name. - { - std::vector<net::NetLog::EventType> event_types = - net::NetLog::GetAllEventTypes(); - - DictionaryValue* dict = new DictionaryValue(); - - for (size_t i = 0; i < event_types.size(); ++i) { - const char* name = net::NetLog::EventTypeToString(event_types[i]); - dict->SetInteger(name, static_cast<int>(event_types[i])); - } - - CallJavascriptFunction(L"g_browser.receivedLogEventTypeConstants", dict); - } - - // Tell the javascript about the version of the client and its - // command line arguments. - { - DictionaryValue* dict = new DictionaryValue(); - - chrome::VersionInfo version_info; - - if (!version_info.is_valid()) { - DLOG(ERROR) << "Unable to create chrome::VersionInfo"; - } else { - // We have everything we need to send the right values. - dict->SetString("version", version_info.Version()); - dict->SetString("cl", version_info.LastChange()); - dict->SetString("version_mod", - platform_util::GetVersionStringModifier()); - dict->SetString("official", - l10n_util::GetStringUTF16( - version_info.IsOfficialBuild() ? - IDS_ABOUT_VERSION_OFFICIAL - : IDS_ABOUT_VERSION_UNOFFICIAL)); - - dict->SetString("command_line", - CommandLine::ForCurrentProcess()->command_line_string()); - } - - CallJavascriptFunction(L"g_browser.receivedClientInfo", - dict); - } - - // Tell the javascript about the relationship between load flag enums and - // their symbolic name. - { - DictionaryValue* dict = new DictionaryValue(); - -#define LOAD_FLAG(label, value) \ - dict->SetInteger(# label, static_cast<int>(value)); -#include "net/base/load_flags_list.h" -#undef LOAD_FLAG - - CallJavascriptFunction(L"g_browser.receivedLoadFlagConstants", dict); - } - - // Tell the javascript about the relationship between net error codes and - // their symbolic name. - { - DictionaryValue* dict = new DictionaryValue(); - -#define NET_ERROR(label, value) \ - dict->SetInteger(# label, static_cast<int>(value)); -#include "net/base/net_error_list.h" -#undef NET_ERROR - - CallJavascriptFunction(L"g_browser.receivedNetErrorConstants", dict); - } - - // Tell the javascript about the relationship between event phase enums and - // their symbolic name. - { - DictionaryValue* dict = new DictionaryValue(); - - dict->SetInteger("PHASE_BEGIN", net::NetLog::PHASE_BEGIN); - dict->SetInteger("PHASE_END", net::NetLog::PHASE_END); - dict->SetInteger("PHASE_NONE", net::NetLog::PHASE_NONE); - - CallJavascriptFunction(L"g_browser.receivedLogEventPhaseConstants", dict); - } - - // Tell the javascript about the relationship between source type enums and - // their symbolic names. - { - DictionaryValue* dict = new DictionaryValue(); - -#define SOURCE_TYPE(label, value) dict->SetInteger(# label, value); -#include "net/base/net_log_source_type_list.h" -#undef SOURCE_TYPE - - CallJavascriptFunction(L"g_browser.receivedLogSourceTypeConstants", dict); - } - - // Tell the javascript about the relationship between LogLevel enums and their - // symbolic names. - { - DictionaryValue* dict = new DictionaryValue(); - - dict->SetInteger("LOG_ALL", net::NetLog::LOG_ALL); - dict->SetInteger("LOG_ALL_BUT_BYTES", net::NetLog::LOG_ALL_BUT_BYTES); - dict->SetInteger("LOG_BASIC", net::NetLog::LOG_BASIC); - - CallJavascriptFunction(L"g_browser.receivedLogLevelConstants", dict); - } - - // Tell the javascript about the relationship between address family enums and - // their symbolic names. - { - DictionaryValue* dict = new DictionaryValue(); - - dict->SetInteger("ADDRESS_FAMILY_UNSPECIFIED", - net::ADDRESS_FAMILY_UNSPECIFIED); - dict->SetInteger("ADDRESS_FAMILY_IPV4", - net::ADDRESS_FAMILY_IPV4); - dict->SetInteger("ADDRESS_FAMILY_IPV6", - net::ADDRESS_FAMILY_IPV6); - - CallJavascriptFunction(L"g_browser.receivedAddressFamilyConstants", dict); - } - - // Tell the javascript how the "time ticks" values we have given it relate to - // actual system times. (We used time ticks throughout since they are stable - // across system clock changes). - { - int64 cur_time_ms = (base::Time::Now() - base::Time()).InMilliseconds(); - - int64 cur_time_ticks_ms = - (base::TimeTicks::Now() - base::TimeTicks()).InMilliseconds(); - - // If we add this number to a time tick value, it gives the timestamp. - int64 tick_to_time_ms = cur_time_ms - cur_time_ticks_ms; - - // Chrome on all platforms stores times using the Windows epoch - // (Jan 1 1601), but the javascript wants a unix epoch. - // TODO(eroman): Getting the timestamp relative the to unix epoch should - // be part of the time library. - const int64 kUnixEpochMs = 11644473600000LL; - int64 tick_to_unix_time_ms = tick_to_time_ms - kUnixEpochMs; - - // Pass it as a string, since it may be too large to fit in an integer. - CallJavascriptFunction(L"g_browser.receivedTimeTickOffset", - Value::CreateStringValue( - base::Int64ToString(tick_to_unix_time_ms))); - } - - // Register with network stack to observe events. - is_observing_log_ = true; - ChromeNetLog::EntryList entries; - io_thread_->net_log()->AddObserverAndGetAllPassivelyCapturedEvents(this, - &entries); - SendPassiveLogEntries(entries); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetProxySettings( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - net::ProxyService* proxy_service = context->proxy_service(); - - DictionaryValue* dict = new DictionaryValue(); - if (proxy_service->fetched_config().is_valid()) - dict->Set("original", proxy_service->fetched_config().ToValue()); - if (proxy_service->config().is_valid()) - dict->Set("effective", proxy_service->config().ToValue()); - - CallJavascriptFunction(L"g_browser.receivedProxySettings", dict); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnReloadProxySettings( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - context->proxy_service()->ForceReloadProxyConfig(); - - // Cause the renderer to be notified of the new values. - OnGetProxySettings(NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetBadProxies( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - - const net::ProxyRetryInfoMap& bad_proxies_map = - context->proxy_service()->proxy_retry_info(); - - ListValue* dict_list = new ListValue(); - - for (net::ProxyRetryInfoMap::const_iterator it = bad_proxies_map.begin(); - it != bad_proxies_map.end(); ++it) { - const std::string& proxy_uri = it->first; - const net::ProxyRetryInfo& retry_info = it->second; - - DictionaryValue* dict = new DictionaryValue(); - dict->SetString("proxy_uri", proxy_uri); - dict->SetString("bad_until", - net::NetLog::TickCountToString(retry_info.bad_until)); - - dict_list->Append(dict); - } - - CallJavascriptFunction(L"g_browser.receivedBadProxies", dict_list); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnClearBadProxies( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - context->proxy_service()->ClearBadProxiesCache(); - - // Cause the renderer to be notified of the new values. - OnGetBadProxies(NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetHostResolverInfo( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - net::HostResolverImpl* host_resolver_impl = - context->host_resolver()->GetAsHostResolverImpl(); - net::HostCache* cache = GetHostResolverCache(context); - - if (!host_resolver_impl || !cache) { - CallJavascriptFunction(L"g_browser.receivedHostResolverInfo", NULL); - return; - } - - DictionaryValue* dict = new DictionaryValue(); - - dict->SetInteger( - "default_address_family", - static_cast<int>(host_resolver_impl->GetDefaultAddressFamily())); - - DictionaryValue* cache_info_dict = new DictionaryValue(); - - cache_info_dict->SetInteger( - "capacity", - static_cast<int>(cache->max_entries())); - cache_info_dict->SetInteger( - "ttl_success_ms", - static_cast<int>(cache->success_entry_ttl().InMilliseconds())); - cache_info_dict->SetInteger( - "ttl_failure_ms", - static_cast<int>(cache->failure_entry_ttl().InMilliseconds())); - - ListValue* entry_list = new ListValue(); - - for (net::HostCache::EntryMap::const_iterator it = - cache->entries().begin(); - it != cache->entries().end(); - ++it) { - const net::HostCache::Key& key = it->first; - const net::HostCache::Entry* entry = it->second.get(); - - DictionaryValue* entry_dict = new DictionaryValue(); - - entry_dict->SetString("hostname", key.hostname); - entry_dict->SetInteger("address_family", - static_cast<int>(key.address_family)); - entry_dict->SetString("expiration", - net::NetLog::TickCountToString(entry->expiration)); - - if (entry->error != net::OK) { - entry_dict->SetInteger("error", entry->error); - } else { - // Append all of the resolved addresses. - ListValue* address_list = new ListValue(); - const struct addrinfo* current_address = entry->addrlist.head(); - while (current_address) { - address_list->Append(Value::CreateStringValue( - net::NetAddressToStringWithPort(current_address))); - current_address = current_address->ai_next; - } - entry_dict->Set("addresses", address_list); - } - - entry_list->Append(entry_dict); - } - - cache_info_dict->Set("entries", entry_list); - dict->Set("cache", cache_info_dict); - - CallJavascriptFunction(L"g_browser.receivedHostResolverInfo", dict); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnClearHostResolverCache( - const ListValue* list) { - net::HostCache* cache = - GetHostResolverCache(context_getter_->GetURLRequestContext()); - - if (cache) - cache->clear(); - - // Cause the renderer to be notified of the new values. - OnGetHostResolverInfo(NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnEnableIPv6( - const ListValue* list) { - net::URLRequestContext* context = context_getter_->GetURLRequestContext(); - net::HostResolverImpl* host_resolver_impl = - context->host_resolver()->GetAsHostResolverImpl(); - - if (host_resolver_impl) { - host_resolver_impl->SetDefaultAddressFamily( - net::ADDRESS_FAMILY_UNSPECIFIED); - } - - // Cause the renderer to be notified of the new value. - OnGetHostResolverInfo(NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTests( - const ListValue* list) { - // |value| should be: [<URL to test>]. - string16 url_str; - CHECK(list->GetString(0, &url_str)); - - // Try to fix-up the user provided URL into something valid. - // For example, turn "www.google.com" into "http://www.google.com". - GURL url(URLFixerUpper::FixupURL(UTF16ToUTF8(url_str), std::string())); - - connection_tester_.reset(new ConnectionTester( - this, io_thread_->globals()->proxy_script_fetcher_context.get())); - connection_tester_->RunAllTests(url); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnHSTSQuery( - const ListValue* list) { - // |list| should be: [<domain to query>]. - std::string domain; - CHECK(list->GetString(0, &domain)); - DictionaryValue* result = new(DictionaryValue); - - if (!IsStringASCII(domain)) { - result->SetString("error", "non-ASCII domain name"); - } else { - net::TransportSecurityState* transport_security_state = - context_getter_->GetURLRequestContext()->transport_security_state(); - if (!transport_security_state) { - result->SetString("error", "no TransportSecurityState active"); - } else { - net::TransportSecurityState::DomainState state; - const bool found = transport_security_state->IsEnabledForHost( - &state, domain); - - result->SetBoolean("result", found); - if (found) { - result->SetInteger("mode", static_cast<int>(state.mode)); - result->SetBoolean("subdomains", state.include_subdomains); - result->SetBoolean("preloaded", state.preloaded); - result->SetString("domain", state.domain); - } - } - } - - CallJavascriptFunction(L"g_browser.receivedHSTSResult", result); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnHSTSAdd( - const ListValue* list) { - // |list| should be: [<domain to query>, <include subdomains>]. - std::string domain; - CHECK(list->GetString(0, &domain)); - if (!IsStringASCII(domain)) { - // Silently fail. The user will get a helpful error if they query for the - // name. - return; - } - bool include_subdomains; - CHECK(list->GetBoolean(1, &include_subdomains)); - - net::TransportSecurityState* transport_security_state = - context_getter_->GetURLRequestContext()->transport_security_state(); - if (!transport_security_state) - return; - - net::TransportSecurityState::DomainState state; - state.expiry = state.created + base::TimeDelta::FromDays(1000); - state.include_subdomains = include_subdomains; - - transport_security_state->EnableHost(domain, state); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnHSTSDelete( - const ListValue* list) { - // |list| should be: [<domain to query>]. - std::string domain; - CHECK(list->GetString(0, &domain)); - if (!IsStringASCII(domain)) { - // There cannot be a unicode entry in the HSTS set. - return; - } - net::TransportSecurityState* transport_security_state = - context_getter_->GetURLRequestContext()->transport_security_state(); - if (!transport_security_state) - return; - - transport_security_state->DeleteHost(domain); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetHttpCacheInfo( - const ListValue* list) { - DictionaryValue* info_dict = new DictionaryValue(); - DictionaryValue* stats_dict = new DictionaryValue(); - - disk_cache::Backend* disk_cache = GetDiskCacheBackend( - context_getter_->GetURLRequestContext()); - - if (disk_cache) { - // Extract the statistics key/value pairs from the backend. - std::vector<std::pair<std::string, std::string> > stats; - disk_cache->GetStats(&stats); - for (size_t i = 0; i < stats.size(); ++i) { - stats_dict->Set(stats[i].first, - Value::CreateStringValue(stats[i].second)); - } - } - - info_dict->Set("stats", stats_dict); - - CallJavascriptFunction(L"g_browser.receivedHttpCacheInfo", info_dict); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetSocketPoolInfo( - const ListValue* list) { - net::HttpNetworkSession* http_network_session = - GetHttpNetworkSession(context_getter_->GetURLRequestContext()); - - Value* socket_pool_info = NULL; - if (http_network_session) - socket_pool_info = http_network_session->SocketPoolInfoToValue(); - - CallJavascriptFunction(L"g_browser.receivedSocketPoolInfo", socket_pool_info); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetSpdySessionInfo( - const ListValue* list) { - net::HttpNetworkSession* http_network_session = - GetHttpNetworkSession(context_getter_->GetURLRequestContext()); - - Value* spdy_info = NULL; - if (http_network_session) { - spdy_info = http_network_session->SpdySessionPoolInfoToValue(); - } - - CallJavascriptFunction(L"g_browser.receivedSpdySessionInfo", spdy_info); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnGetSpdyStatus( - const ListValue* list) { - DictionaryValue* status_dict = new DictionaryValue(); - - status_dict->Set("spdy_enabled", - Value::CreateBooleanValue( - net::HttpStreamFactory::spdy_enabled())); - status_dict->Set("use_alternate_protocols", - Value::CreateBooleanValue( - net::HttpStreamFactory::use_alternate_protocols())); - status_dict->Set("force_spdy_over_ssl", - Value::CreateBooleanValue( - net::HttpStreamFactory::force_spdy_over_ssl())); - status_dict->Set("force_spdy_always", - Value::CreateBooleanValue( - net::HttpStreamFactory::force_spdy_always())); - status_dict->Set("next_protos", - Value::CreateStringValue( - *net::HttpStreamFactory::next_protos())); - - CallJavascriptFunction(L"g_browser.receivedSpdyStatus", status_dict); -} - -void -NetInternalsMessageHandler::IOThreadImpl::OnGetSpdyAlternateProtocolMappings( - const ListValue* list) { - net::HttpNetworkSession* http_network_session = - GetHttpNetworkSession(context_getter_->GetURLRequestContext()); - - ListValue* dict_list = new ListValue(); - - if (http_network_session) { - const net::HttpAlternateProtocols& http_alternate_protocols = - http_network_session->alternate_protocols(); - const net::HttpAlternateProtocols::ProtocolMap& map = - http_alternate_protocols.protocol_map(); - - for (net::HttpAlternateProtocols::ProtocolMap::const_iterator it = - map.begin(); - it != map.end(); ++it) { - DictionaryValue* dict = new DictionaryValue(); - dict->SetString("host_port_pair", it->first.ToString()); - dict->SetString("alternate_protocol", it->second.ToString()); - dict_list->Append(dict); - } - } - - CallJavascriptFunction(L"g_browser.receivedSpdyAlternateProtocolMappings", - dict_list); -} - -#ifdef OS_WIN -void NetInternalsMessageHandler::IOThreadImpl::OnGetServiceProviders( - const ListValue* list) { - - DictionaryValue* service_providers = new DictionaryValue(); - - WinsockLayeredServiceProviderList layered_providers; - GetWinsockLayeredServiceProviders(&layered_providers); - ListValue* layered_provider_list = new ListValue(); - for (size_t i = 0; i < layered_providers.size(); ++i) { - DictionaryValue* service_dict = new DictionaryValue(); - service_dict->SetString("name", layered_providers[i].name); - service_dict->SetInteger("version", layered_providers[i].version); - service_dict->SetInteger("chain_length", layered_providers[i].chain_length); - service_dict->SetInteger("socket_type", layered_providers[i].socket_type); - service_dict->SetInteger("socket_protocol", - layered_providers[i].socket_protocol); - service_dict->SetString("path", layered_providers[i].path); - - layered_provider_list->Append(service_dict); - } - service_providers->Set("service_providers", layered_provider_list); - - WinsockNamespaceProviderList namespace_providers; - GetWinsockNamespaceProviders(&namespace_providers); - ListValue* namespace_list = new ListValue; - for (size_t i = 0; i < namespace_providers.size(); ++i) { - DictionaryValue* namespace_dict = new DictionaryValue(); - namespace_dict->SetString("name", namespace_providers[i].name); - namespace_dict->SetBoolean("active", namespace_providers[i].active); - namespace_dict->SetInteger("version", namespace_providers[i].version); - namespace_dict->SetInteger("type", namespace_providers[i].type); - - namespace_list->Append(namespace_dict); - } - service_providers->Set("namespace_providers", namespace_list); - - CallJavascriptFunction(L"g_browser.receivedServiceProviders", - service_providers); -} -#endif - -void NetInternalsMessageHandler::IOThreadImpl::OnSetLogLevel( - const ListValue* list) { - int log_level; - std::string log_level_string; - if (!list->GetString(0, &log_level_string) || - !base::StringToInt(log_level_string, &log_level)) { - NOTREACHED(); - return; - } - - DCHECK_GE(log_level, net::NetLog::LOG_ALL); - DCHECK_LE(log_level, net::NetLog::LOG_BASIC); - SetLogLevel(static_cast<net::NetLog::LogLevel>(log_level)); -} - -// Note that unlike other methods of IOThreadImpl, this function -// can be called from ANY THREAD. -void NetInternalsMessageHandler::IOThreadImpl::OnAddEntry( - net::NetLog::EventType type, - const base::TimeTicks& time, - const net::NetLog::Source& source, - net::NetLog::EventPhase phase, - net::NetLog::EventParameters* params) { - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - NewRunnableMethod( - this, &IOThreadImpl::AddEntryToQueue, - net::NetLog::EntryToDictionaryValue(type, time, source, phase, - params, false))); -} - -void NetInternalsMessageHandler::IOThreadImpl::AddEntryToQueue(Value* entry) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - if (!pending_entries_.get()) { - pending_entries_.reset(new ListValue()); - BrowserThread::PostDelayedTask( - BrowserThread::IO, FROM_HERE, - NewRunnableMethod(this, &IOThreadImpl::PostPendingEntries), - kNetLogEventDelayMilliseconds); - } - pending_entries_->Append(entry); -} - -void NetInternalsMessageHandler::IOThreadImpl::PostPendingEntries() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - CallJavascriptFunction( - L"g_browser.receivedLogEntries", - pending_entries_.release()); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTestSuite() { - CallJavascriptFunction(L"g_browser.receivedStartConnectionTestSuite", NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::OnStartConnectionTestExperiment( - const ConnectionTester::Experiment& experiment) { - CallJavascriptFunction( - L"g_browser.receivedStartConnectionTestExperiment", - ExperimentToValue(experiment)); -} - -void -NetInternalsMessageHandler::IOThreadImpl::OnCompletedConnectionTestExperiment( - const ConnectionTester::Experiment& experiment, - int result) { - DictionaryValue* dict = new DictionaryValue(); - - dict->Set("experiment", ExperimentToValue(experiment)); - dict->SetInteger("result", result); - - CallJavascriptFunction( - L"g_browser.receivedCompletedConnectionTestExperiment", - dict); -} - -void -NetInternalsMessageHandler::IOThreadImpl::OnCompletedConnectionTestSuite() { - CallJavascriptFunction( - L"g_browser.receivedCompletedConnectionTestSuite", - NULL); -} - -void NetInternalsMessageHandler::IOThreadImpl::DispatchToMessageHandler( - ListValue* arg, MessageHandler method) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - (this->*method)(arg); - delete arg; -} - -// Note that this can be called from ANY THREAD. -void NetInternalsMessageHandler::IOThreadImpl::CallJavascriptFunction( - const std::wstring& function_name, - Value* arg) { - if (BrowserThread::CurrentlyOn(BrowserThread::UI)) { - if (handler_ && !was_webui_deleted_) { - // We check |handler_| in case it was deleted on the UI thread earlier - // while we were running on the IO thread. - handler_->CallJavascriptFunction(function_name, arg); - } - delete arg; - return; - } - - if (!BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - NewRunnableMethod( - this, - &IOThreadImpl::CallJavascriptFunction, - function_name, arg))) { - // Failed posting the task, avoid leaking. - delete arg; - } -} - -} // namespace - - -//////////////////////////////////////////////////////////////////////////////// -// -// NetInternalsUI -// -//////////////////////////////////////////////////////////////////////////////// - -NetInternalsUI::NetInternalsUI(TabContents* contents) : WebUI(contents) { - AddMessageHandler((new NetInternalsMessageHandler())->Attach(this)); - - NetInternalsHTMLSource* html_source = new NetInternalsHTMLSource(); - - // Set up the chrome://net-internals/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} diff --git a/chrome/browser/dom_ui/net_internals_ui.h b/chrome/browser/dom_ui/net_internals_ui.h deleted file mode 100644 index 53af9ae..0000000 --- a/chrome/browser/dom_ui/net_internals_ui.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2011 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_DOM_UI_NET_INTERNALS_UI_H_ -#define CHROME_BROWSER_DOM_UI_NET_INTERNALS_UI_H_ -#pragma once - -#include "chrome/browser/webui/web_ui.h" - -class NetInternalsUI : public WebUI { - public: - explicit NetInternalsUI(TabContents* contents); - - private: - DISALLOW_COPY_AND_ASSIGN(NetInternalsUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_NET_INTERNALS_UI_H_ diff --git a/chrome/browser/dom_ui/plugins_ui.cc b/chrome/browser/dom_ui/plugins_ui.cc deleted file mode 100644 index e895ff9..0000000 --- a/chrome/browser/dom_ui/plugins_ui.cc +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/plugins_ui.h" - -#include <algorithm> -#include <string> -#include <vector> - -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/singleton.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/chrome_url_data_manager.h" -#include "chrome/browser/plugin_updater.h" -#include "chrome/browser/prefs/pref_member.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_window.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/notification_service.h" -#include "chrome/common/pepper_plugin_registry.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "grit/generated_resources.h" -#include "grit/theme_resources.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "webkit/plugins/npapi/plugin_list.h" - -namespace { - -/////////////////////////////////////////////////////////////////////////////// -// -// PluginsHTMLSource -// -/////////////////////////////////////////////////////////////////////////////// - -class PluginsUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - PluginsUIHTMLSource() - : DataSource(chrome::kChromeUIPluginsHost, MessageLoop::current()) {} - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const { - return "text/html"; - } - - private: - ~PluginsUIHTMLSource() {} - - DISALLOW_COPY_AND_ASSIGN(PluginsUIHTMLSource); -}; - -void PluginsUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - // Strings used in the JsTemplate file. - DictionaryValue localized_strings; - localized_strings.SetString("pluginsTitle", - l10n_util::GetStringUTF16(IDS_PLUGINS_TITLE)); - localized_strings.SetString("pluginsDetailsModeLink", - l10n_util::GetStringUTF16(IDS_PLUGINS_DETAILS_MODE_LINK)); - localized_strings.SetString("pluginsNoneInstalled", - l10n_util::GetStringUTF16(IDS_PLUGINS_NONE_INSTALLED)); - localized_strings.SetString("pluginDisabled", - l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_PLUGIN)); - localized_strings.SetString("pluginDisabledByPolicy", - l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLED_BY_POLICY_PLUGIN)); - localized_strings.SetString("pluginCannotBeEnabledDueToPolicy", - l10n_util::GetStringUTF16(IDS_PLUGINS_CANNOT_ENABLE_DUE_TO_POLICY)); - localized_strings.SetString("pluginDownload", - l10n_util::GetStringUTF16(IDS_PLUGINS_DOWNLOAD)); - localized_strings.SetString("pluginName", - l10n_util::GetStringUTF16(IDS_PLUGINS_NAME)); - localized_strings.SetString("pluginVersion", - l10n_util::GetStringUTF16(IDS_PLUGINS_VERSION)); - localized_strings.SetString("pluginDescription", - l10n_util::GetStringUTF16(IDS_PLUGINS_DESCRIPTION)); - localized_strings.SetString("pluginPath", - l10n_util::GetStringUTF16(IDS_PLUGINS_PATH)); - localized_strings.SetString("pluginMimeTypes", - l10n_util::GetStringUTF16(IDS_PLUGINS_MIME_TYPES)); - localized_strings.SetString("pluginMimeTypesMimeType", - l10n_util::GetStringUTF16(IDS_PLUGINS_MIME_TYPES_MIME_TYPE)); - localized_strings.SetString("pluginMimeTypesDescription", - l10n_util::GetStringUTF16(IDS_PLUGINS_MIME_TYPES_DESCRIPTION)); - localized_strings.SetString("pluginMimeTypesFileExtensions", - l10n_util::GetStringUTF16(IDS_PLUGINS_MIME_TYPES_FILE_EXTENSIONS)); - localized_strings.SetString("disable", - l10n_util::GetStringUTF16(IDS_PLUGINS_DISABLE)); - localized_strings.SetString("enable", - l10n_util::GetStringUTF16(IDS_PLUGINS_ENABLE)); - - ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); - - static const base::StringPiece plugins_html( - ResourceBundle::GetSharedInstance().GetRawDataResource(IDR_PLUGINS_HTML)); - std::string full_html(plugins_html.data(), plugins_html.size()); - jstemplate_builder::AppendJsonHtml(&localized_strings, &full_html); - jstemplate_builder::AppendI18nTemplateSourceHtml(&full_html); - jstemplate_builder::AppendI18nTemplateProcessHtml(&full_html); - jstemplate_builder::AppendJsTemplateSourceHtml(&full_html); - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - - SendResponse(request_id, html_bytes); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// PluginsDOMHandler -// -//////////////////////////////////////////////////////////////////////////////// - -// The handler for Javascript messages for the chrome://plugins/ page. -// TODO(viettrungluu): Make plugin list updates notify, and then observe -// changes; maybe replumb plugin list through plugin service? -// <http://crbug.com/39101> -class PluginsDOMHandler : public WebUIMessageHandler, - public NotificationObserver { - public: - explicit PluginsDOMHandler(); - virtual ~PluginsDOMHandler() {} - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Callback for the "requestPluginsData" message. - void HandleRequestPluginsData(const ListValue* args); - - // Callback for the "enablePlugin" message. - void HandleEnablePluginMessage(const ListValue* args); - - // Callback for the "showTermsOfService" message. This really just opens a new - // window with about:terms. Flash can't link directly to about:terms due to - // the security model. - void HandleShowTermsOfServiceMessage(const ListValue* args); - - // Callback for the "saveShowDetailsToPrefs" message. - void HandleSaveShowDetailsToPrefs(const ListValue* args); - - // Calback for the "getShowDetails" message. - void HandleGetShowDetails(const ListValue* args); - - // NotificationObserver method overrides - void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - private: - // This extra wrapper is used to ensure we don't leak the ListValue* pointer - // if the PluginsDOMHandler object goes away before the task on the UI thread - // to give it the plugin list runs. - struct ListWrapper { - ListValue* list; - }; - // Loads the plugins on the FILE thread. - static void LoadPluginsOnFileThread(ListWrapper* wrapper, Task* task); - - // Used in conjunction with ListWrapper to avoid any memory leaks. - static void EnsureListDeleted(ListWrapper* wrapper); - - // Call this to start getting the plugins on the UI thread. - void LoadPlugins(); - - // Called on the UI thread when the plugin information is ready. - void PluginsLoaded(ListWrapper* wrapper); - - NotificationRegistrar registrar_; - - ScopedRunnableMethodFactory<PluginsDOMHandler> get_plugins_factory_; - - // This pref guards the value whether about:plugins is in the details mode or - // not. - BooleanPrefMember show_details_; - - DISALLOW_COPY_AND_ASSIGN(PluginsDOMHandler); -}; - -PluginsDOMHandler::PluginsDOMHandler() - : ALLOW_THIS_IN_INITIALIZER_LIST(get_plugins_factory_(this)) { - registrar_.Add(this, - NotificationType::PLUGIN_ENABLE_STATUS_CHANGED, - NotificationService::AllSources()); -} - -WebUIMessageHandler* PluginsDOMHandler::Attach(WebUI* web_ui) { - PrefService* prefs = web_ui->GetProfile()->GetPrefs(); - - show_details_.Init(prefs::kPluginsShowDetails, prefs, this); - - return WebUIMessageHandler::Attach(web_ui); -} - -void PluginsDOMHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("requestPluginsData", - NewCallback(this, &PluginsDOMHandler::HandleRequestPluginsData)); - web_ui_->RegisterMessageCallback("enablePlugin", - NewCallback(this, &PluginsDOMHandler::HandleEnablePluginMessage)); - web_ui_->RegisterMessageCallback("showTermsOfService", - NewCallback(this, &PluginsDOMHandler::HandleShowTermsOfServiceMessage)); - web_ui_->RegisterMessageCallback("saveShowDetailsToPrefs", - NewCallback(this, &PluginsDOMHandler::HandleSaveShowDetailsToPrefs)); - web_ui_->RegisterMessageCallback("getShowDetails", - NewCallback(this, &PluginsDOMHandler::HandleGetShowDetails)); -} - -void PluginsDOMHandler::HandleRequestPluginsData(const ListValue* args) { - LoadPlugins(); -} - -void PluginsDOMHandler::HandleEnablePluginMessage(const ListValue* args) { - // Be robust in accepting badness since plug-ins display HTML (hence - // JavaScript). - if (args->GetSize() != 3) - return; - - std::string enable_str; - std::string is_group_str; - if (!args->GetString(1, &enable_str) || !args->GetString(2, &is_group_str)) - return; - bool enable = enable_str == "true"; - - PluginUpdater* plugin_updater = PluginUpdater::GetInstance(); - if (is_group_str == "true") { - string16 group_name; - if (!args->GetString(0, &group_name)) - return; - - plugin_updater->EnablePluginGroup(enable, group_name); - if (enable) { - // See http://crbug.com/50105 for background. - string16 adobereader = ASCIIToUTF16( - webkit::npapi::PluginGroup::kAdobeReaderGroupName); - string16 internalpdf = ASCIIToUTF16(PepperPluginRegistry::kPDFPluginName); - if (group_name == adobereader) { - plugin_updater->EnablePluginGroup(false, internalpdf); - } else if (group_name == internalpdf) { - plugin_updater->EnablePluginGroup(false, adobereader); - } - } - } else { - FilePath::StringType file_path; - if (!args->GetString(0, &file_path)) - return; - - plugin_updater->EnablePlugin(enable, file_path); - } - - // TODO(viettrungluu): We might also want to ensure that the plugins - // list is always written to prefs even when the user hasn't disabled a - // plugin. <http://crbug.com/39101> - plugin_updater->UpdatePreferences(web_ui_->GetProfile(), 0); -} - -void PluginsDOMHandler::HandleShowTermsOfServiceMessage(const ListValue* args) { - // Show it in a new browser window.... - Browser* browser = Browser::Create(web_ui_->GetProfile()); - browser->OpenURL(GURL(chrome::kAboutTermsURL), - GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK); - browser->window()->Show(); -} - -void PluginsDOMHandler::HandleSaveShowDetailsToPrefs(const ListValue* args) { - std::string details_mode; - if (!args->GetString(0, &details_mode)) { - NOTREACHED(); - return; - } - show_details_.SetValue(details_mode == "true"); -} - -void PluginsDOMHandler::HandleGetShowDetails(const ListValue* args) { - FundamentalValue show_details(show_details_.GetValue()); - web_ui_->CallJavascriptFunction(L"loadShowDetailsFromPrefs", show_details); -} - -void PluginsDOMHandler::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - DCHECK_EQ(NotificationType::PLUGIN_ENABLE_STATUS_CHANGED, type.value); - LoadPlugins(); -} - -void PluginsDOMHandler::LoadPluginsOnFileThread(ListWrapper* wrapper, - Task* task) { - wrapper->list = PluginUpdater::GetInstance()->GetPluginGroupsData(); - BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, task); - BrowserThread::PostTask( - BrowserThread::UI, - FROM_HERE, - NewRunnableFunction(&PluginsDOMHandler::EnsureListDeleted, wrapper)); -} - -void PluginsDOMHandler::EnsureListDeleted(ListWrapper* wrapper) { - delete wrapper->list; - delete wrapper; -} - -void PluginsDOMHandler::LoadPlugins() { - if (!get_plugins_factory_.empty()) - return; - - ListWrapper* wrapper = new ListWrapper; - wrapper->list = NULL; - Task* task = get_plugins_factory_.NewRunnableMethod( - &PluginsDOMHandler::PluginsLoaded, wrapper); - - BrowserThread::PostTask( - BrowserThread::FILE, - FROM_HERE, - NewRunnableFunction( - &PluginsDOMHandler::LoadPluginsOnFileThread, wrapper, task)); -} - -void PluginsDOMHandler::PluginsLoaded(ListWrapper* wrapper) { - DictionaryValue results; - results.Set("plugins", wrapper->list); - wrapper->list = NULL; // So it doesn't get deleted. - web_ui_->CallJavascriptFunction(L"returnPluginsData", results); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// PluginsUI -// -/////////////////////////////////////////////////////////////////////////////// - -PluginsUI::PluginsUI(TabContents* contents) : WebUI(contents) { - AddMessageHandler((new PluginsDOMHandler())->Attach(this)); - - PluginsUIHTMLSource* html_source = new PluginsUIHTMLSource(); - - // Set up the chrome://plugins/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} - - -// static -RefCountedMemory* PluginsUI::GetFaviconResourceBytes() { - return ResourceBundle::GetSharedInstance(). - LoadDataResourceBytes(IDR_PLUGIN); -} - -// static -void PluginsUI::RegisterUserPrefs(PrefService* prefs) { - FilePath internal_dir; - PathService::Get(chrome::DIR_INTERNAL_PLUGINS, &internal_dir); - prefs->RegisterFilePathPref(prefs::kPluginsLastInternalDirectory, - internal_dir); - - prefs->RegisterListPref(prefs::kPluginsPluginsBlacklist); - prefs->RegisterListPref(prefs::kPluginsPluginsList); - prefs->RegisterBooleanPref(prefs::kPluginsEnabledInternalPDF, false); - prefs->RegisterBooleanPref(prefs::kPluginsShowDetails, false); - prefs->RegisterBooleanPref(prefs::kPluginsShowSetReaderDefaultInfobar, true); -} diff --git a/chrome/browser/dom_ui/plugins_ui.h b/chrome/browser/dom_ui/plugins_ui.h deleted file mode 100644 index 787ef53..0000000 --- a/chrome/browser/dom_ui/plugins_ui.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2011 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_DOM_UI_PLUGINS_UI_H_ -#define CHROME_BROWSER_DOM_UI_PLUGINS_UI_H_ -#pragma once - -#include "chrome/browser/webui/web_ui.h" - -class PrefService; -class RefCountedMemory; - -class PluginsUI : public WebUI { - public: - explicit PluginsUI(TabContents* contents); - - static RefCountedMemory* GetFaviconResourceBytes(); - static void RegisterUserPrefs(PrefService* prefs); - - private: - DISALLOW_COPY_AND_ASSIGN(PluginsUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_PLUGINS_UI_H_ diff --git a/chrome/browser/dom_ui/remoting_ui.cc b/chrome/browser/dom_ui/remoting_ui.cc deleted file mode 100644 index e849bb0..0000000 --- a/chrome/browser/dom_ui/remoting_ui.cc +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/remoting_ui.h" - -#include "base/singleton.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/chrome_url_data_manager.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/common/url_constants.h" -#include "grit/theme_resources.h" -#include "ui/base/resource/resource_bundle.h" - -namespace { - -/////////////////////////////////////////////////////////////////////////////// -// -// RemotingHTMLSource -// -/////////////////////////////////////////////////////////////////////////////// - -class RemotingUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - RemotingUIHTMLSource() - : DataSource(chrome::kChromeUIRemotingHost, MessageLoop::current()) {} - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const { - return "pepper-application/x-chromoting"; - } - - private: - ~RemotingUIHTMLSource() {} - - DISALLOW_COPY_AND_ASSIGN(RemotingUIHTMLSource); -}; - -void RemotingUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - // Dummy data. Not used, but we need to send something back in the response. - std::string full_html = "remoting"; - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes()); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - - SendResponse(request_id, html_bytes); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// -// RemotingUI -// -/////////////////////////////////////////////////////////////////////////////// - -RemotingUI::RemotingUI(TabContents* contents) : WebUI(contents) { - RemotingUIHTMLSource* html_source = new RemotingUIHTMLSource(); - - // Set up the chrome://remoting source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} - - -// static -RefCountedMemory* RemotingUI::GetFaviconResourceBytes() { - return ResourceBundle::GetSharedInstance(). - // TODO(garykac): Have custom remoting icon created. - LoadDataResourceBytes(IDR_PLUGIN); -} - -// static -void RemotingUI::RegisterUserPrefs(PrefService* prefs) { - // TODO(garykac): Add remoting prefs (if needed). -} diff --git a/chrome/browser/dom_ui/remoting_ui.h b/chrome/browser/dom_ui/remoting_ui.h deleted file mode 100644 index 4da8f30..0000000 --- a/chrome/browser/dom_ui/remoting_ui.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) 2011 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_DOM_UI_REMOTING_UI_H_ -#define CHROME_BROWSER_DOM_UI_REMOTING_UI_H_ -#pragma once - -#include "chrome/browser/webui/web_ui.h" - -class PrefService; -class RefCountedMemory; - -class RemotingUI : public WebUI { - public: - explicit RemotingUI(TabContents* contents); - - static RefCountedMemory* GetFaviconResourceBytes(); - static void RegisterUserPrefs(PrefService* prefs); - - private: - DISALLOW_COPY_AND_ASSIGN(RemotingUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_REMOTING_UI_H_ diff --git a/chrome/browser/dom_ui/slideshow_ui.cc b/chrome/browser/dom_ui/slideshow_ui.cc deleted file mode 100644 index 5552e6a..0000000 --- a/chrome/browser/dom_ui/slideshow_ui.cc +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) 2011 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/dom_ui/slideshow_ui.h" - -#include "base/callback.h" -#include "base/message_loop.h" -#include "base/path_service.h" -#include "base/singleton.h" -#include "base/string_piece.h" -#include "base/string_util.h" -#include "base/threading/thread.h" -#include "base/time.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "base/weak_ptr.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/web_ui_favicon_source.h" -#include "chrome/browser/history/history_types.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "grit/chromium_strings.h" -#include "grit/generated_resources.h" -#include "grit/locale_settings.h" -#include "net/base/escape.h" -#include "net/base/directory_lister.h" -#include "ui/base/resource/resource_bundle.h" - -static const char kPropertyPath[] = "path"; -static const char kPropertyTitle[] = "title"; -static const char kPropertyOffset[] = "currentOffset"; -static const char kPropertyDirectory[] = "isDirectory"; - -class SlideshowUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - SlideshowUIHTMLSource(); - - // Called when the network layer has requested a resource underneath - // the path we registered. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const { - return "text/html"; - } - - private: - ~SlideshowUIHTMLSource() {} - - DISALLOW_COPY_AND_ASSIGN(SlideshowUIHTMLSource); -}; - -// The handler for Javascript messages related to the "slideshow" view. -class SlideshowHandler : public net::DirectoryLister::DirectoryListerDelegate, - public WebUIMessageHandler, - public base::SupportsWeakPtr<SlideshowHandler> { - public: - SlideshowHandler(); - virtual ~SlideshowHandler(); - - // Init work after Attach. - void Init(); - - // DirectoryLister::DirectoryListerDelegate methods: - virtual void OnListFile( - const net::DirectoryLister::DirectoryListerData& data); - virtual void OnListDone(int error); - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - void GetChildrenForPath(const FilePath& path, bool is_refresh); - - // Callback for the "getChildren" message. - void HandleGetChildren(const ListValue* args); - - void HandleRefreshDirectory(const ListValue* args); - - private: - bool PathIsImageFile(const char* filename); - - scoped_ptr<ListValue> filelist_value_; - FilePath currentpath_; - FilePath originalpath_; - Profile* profile_; - int counter_; - int currentOffset_; - scoped_refptr<net::DirectoryLister> lister_; - bool is_refresh_; - - DISALLOW_COPY_AND_ASSIGN(SlideshowHandler); -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// SlideshowHTMLSource -// -//////////////////////////////////////////////////////////////////////////////// - -SlideshowUIHTMLSource::SlideshowUIHTMLSource() - : DataSource(chrome::kChromeUISlideshowHost, MessageLoop::current()) { -} - -void SlideshowUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - DictionaryValue localized_strings; - // TODO(dhg): Add stirings to localized strings, also add more strings - // that are currently hardcoded. - SetFontAndTextDirection(&localized_strings); - - static const base::StringPiece slideshow_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_SLIDESHOW_HTML)); - const std::string full_html = jstemplate_builder::GetI18nTemplateHtml( - slideshow_html, &localized_strings); - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), html_bytes->data.begin()); - - SendResponse(request_id, html_bytes); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// SlideshowHandler -// -//////////////////////////////////////////////////////////////////////////////// -SlideshowHandler::SlideshowHandler() - : profile_(NULL), - is_refresh_(false) { - lister_ = NULL; -} - -SlideshowHandler::~SlideshowHandler() { - if (lister_.get()) { - lister_->Cancel(); - lister_->set_delegate(NULL); - } -} - -WebUIMessageHandler* SlideshowHandler::Attach(WebUI* web_ui) { - profile_ = web_ui->GetProfile(); - // Create our favicon data source. - profile_->GetChromeURLDataManager()->AddDataSource( - new WebUIFavIconSource(profile_)); - return WebUIMessageHandler::Attach(web_ui); -} - -void SlideshowHandler::Init() { -} - -void SlideshowHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getChildren", - NewCallback(this, &SlideshowHandler::HandleGetChildren)); - web_ui_->RegisterMessageCallback("refreshDirectory", - NewCallback(this, &SlideshowHandler::HandleRefreshDirectory)); -} - -void SlideshowHandler::HandleRefreshDirectory(const ListValue* args) { -#if defined(OS_CHROMEOS) - std::string path = WideToUTF8(ExtractStringValue(args)); - GetChildrenForPath(FilePath(path), true); -#endif -} - -void SlideshowHandler::GetChildrenForPath(const FilePath& path, - bool is_refresh) { - filelist_value_.reset(new ListValue()); - currentpath_ = path; - - if (lister_.get()) { - lister_->Cancel(); - lister_->set_delegate(NULL); - lister_ = NULL; - } - - is_refresh_ = is_refresh; - if (file_util::EnsureEndsWithSeparator(¤tpath_) && - currentpath_.IsAbsolute()) { - lister_ = new net::DirectoryLister(currentpath_, this); - } else { - originalpath_ = currentpath_; - currentpath_ = currentpath_.DirName(); - lister_ = new net::DirectoryLister(currentpath_, this); - } - counter_ = 0; - currentOffset_ = -1; - lister_->Start(); -} - -void SlideshowHandler::HandleGetChildren(const ListValue* args) { -#if defined(OS_CHROMEOS) - filelist_value_.reset(new ListValue()); - std::string path = WideToUTF8(ExtractStringValue(args)); - GetChildrenForPath(FilePath(path), false); -#endif -} - -bool SlideshowHandler::PathIsImageFile(const char* filename) { -#if defined(OS_CHROMEOS) - FilePath file = FilePath(filename); - std::string ext = file.Extension(); - ext = StringToLowerASCII(ext); - if (ext == ".jpg" || - ext == ".jpeg" || - ext == ".png" || - ext == ".gif") { - return true; - } else { - return false; - } -#else - return false; -#endif -} - -void SlideshowHandler::OnListFile( - const net::DirectoryLister::DirectoryListerData& data) { -#if defined(OS_CHROMEOS) - if (data.info.filename[0] == '.') { - return; - } - if (!PathIsImageFile(data.info.filename.c_str())) { - return; - } - - DictionaryValue* file_value = new DictionaryValue(); - - file_value->SetString(kPropertyTitle, data.info.filename); - file_value->SetString(kPropertyPath, - currentpath_.Append(data.info.filename).value()); - file_value->SetBoolean(kPropertyDirectory, S_ISDIR(data.info.stat.st_mode)); - filelist_value_->Append(file_value); - std::string val; - file_value->GetString(kPropertyTitle, &val); - if (val == originalpath_.BaseName().value()) { - currentOffset_ = counter_; - } - counter_++; -#endif -} - -void SlideshowHandler::OnListDone(int error) { - DictionaryValue info_value; - counter_ = 0; - if (!(file_util::EnsureEndsWithSeparator(&originalpath_) && - originalpath_.IsAbsolute()) && - currentOffset_ != -1) { - info_value.SetInteger(kPropertyOffset, currentOffset_); - } - if (is_refresh_) { - info_value.SetString("functionCall", "refresh"); - } else { - info_value.SetString("functionCall", "getChildren"); - } - info_value.SetString(kPropertyPath, currentpath_.value()); - web_ui_->CallJavascriptFunction(L"browseFileResult", - info_value, *(filelist_value_.get())); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// SlideshowUI -// -//////////////////////////////////////////////////////////////////////////////// - -SlideshowUI::SlideshowUI(TabContents* contents) : WebUI(contents) { - SlideshowHandler* handler = new SlideshowHandler(); - AddMessageHandler((handler)->Attach(this)); - handler->Init(); - SlideshowUIHTMLSource* html_source = new SlideshowUIHTMLSource(); - - // Set up the chrome://slideshow/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} diff --git a/chrome/browser/dom_ui/slideshow_ui.h b/chrome/browser/dom_ui/slideshow_ui.h deleted file mode 100644 index 88740ac..0000000 --- a/chrome/browser/dom_ui/slideshow_ui.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2011 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_DOM_UI_SLIDESHOW_UI_H_ -#define CHROME_BROWSER_DOM_UI_SLIDESHOW_UI_H_ -#pragma once - -#include "chrome/browser/webui/web_ui.h" - -class SlideshowUI : public WebUI { - public: - explicit SlideshowUI(TabContents* contents); - - private: - DISALLOW_COPY_AND_ASSIGN(SlideshowUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_SLIDESHOW_UI_H_ |