diff options
author | tfarina@chromium.org <tfarina@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-02-22 23:32:38 +0000 |
---|---|---|
committer | tfarina@chromium.org <tfarina@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-02-22 23:32:38 +0000 |
commit | 42b79565bd702fa7bd46b9545a73c2852255be23 (patch) | |
tree | 82b64c157c0e40cdfa0eac6777394060b161fcfd /chrome/browser/dom_ui | |
parent | 4f45d458c94df1f27a8e1091387821a71f0b2a91 (diff) | |
download | chromium_src-42b79565bd702fa7bd46b9545a73c2852255be23.zip chromium_src-42b79565bd702fa7bd46b9545a73c2852255be23.tar.gz chromium_src-42b79565bd702fa7bd46b9545a73c2852255be23.tar.bz2 |
WebUI: Move chrome/browser/dom_ui/ to chrome/browser/webui/.
To reduce the size of this change I've left stub header files in chrome/browser/dom_ui/.
I'll updated the references and delete the stub files later.
BUG=59945, 59946
TEST=trybots
Review URL: http://codereview.chromium.org/6538075
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75660 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/dom_ui')
54 files changed, 0 insertions, 5499 deletions
diff --git a/chrome/browser/dom_ui/OWNERS b/chrome/browser/dom_ui/OWNERS deleted file mode 100644 index 741a5c4..0000000 --- a/chrome/browser/dom_ui/OWNERS +++ /dev/null @@ -1 +0,0 @@ -arv@chromium.org diff --git a/chrome/browser/dom_ui/constrained_html_ui_browsertest.cc b/chrome/browser/dom_ui/constrained_html_ui_browsertest.cc deleted file mode 100644 index 6be6693..0000000 --- a/chrome/browser/dom_ui/constrained_html_ui_browsertest.cc +++ /dev/null @@ -1,74 +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/test/ui/ui_test.h" - -#include "base/file_path.h" -#include "base/message_loop.h" -#include "chrome/browser/renderer_host/render_widget_host_view.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/webui/constrained_html_ui.h" -#include "chrome/browser/webui/html_dialog_ui.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/in_process_browser_test.h" -#include "chrome/test/ui_test_utils.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using testing::Eq; - -namespace { - -class TestHtmlDialogUIDelegate : public HtmlDialogUIDelegate { - public: - TestHtmlDialogUIDelegate() {} - virtual ~TestHtmlDialogUIDelegate() {} - - // HTMLDialogUIDelegate implementation: - virtual bool IsDialogModal() const { - return true; - } - virtual std::wstring GetDialogTitle() const { - return std::wstring(L"Test"); - } - virtual GURL GetDialogContentURL() const { - return GURL(chrome::kChromeUIConstrainedHTMLTestURL); - } - virtual void GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const {} - virtual void GetDialogSize(gfx::Size* size) const { - size->set_width(400); - size->set_height(400); - } - virtual std::string GetDialogArgs() const { - return std::string(); - } - virtual void OnDialogClosed(const std::string& json_retval) { } - virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) { - if (out_close_dialog) - *out_close_dialog = true; - } - virtual bool ShouldShowDialogTitle() const { return true; } -}; - -} // namespace - -class ConstrainedHtmlDialogBrowserTest : public InProcessBrowserTest { - public: - ConstrainedHtmlDialogBrowserTest() {} -}; - -// Tests that opening/closing the constrained window won't crash it. -IN_PROC_BROWSER_TEST_F(ConstrainedHtmlDialogBrowserTest, BasicTest) { - // The delegate deletes itself. - HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate(); - TabContents* tab_contents = browser()->GetSelectedTabContents(); - ASSERT_TRUE(tab_contents != NULL); - - ConstrainedHtmlUI::CreateConstrainedHtmlDialog(browser()->profile(), - delegate, - tab_contents); - - ASSERT_EQ(1U, tab_contents->constrained_window_count()); -} diff --git a/chrome/browser/dom_ui/file_browse_browsertest.cc b/chrome/browser/dom_ui/file_browse_browsertest.cc deleted file mode 100644 index a580844..0000000 --- a/chrome/browser/dom_ui/file_browse_browsertest.cc +++ /dev/null @@ -1,130 +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 "base/path_service.h" -#include "base/task.h" -#include "chrome/browser/tab_contents/navigation_controller.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/ui/views/html_dialog_view.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/notification_registrar.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/in_process_browser_test.h" -#include "chrome/test/ui_test_utils.h" -#include "net/test/test_server.h" - -namespace { - -typedef DOMElementProxy::By By; - -class FileBrowseBrowserTest : public InProcessBrowserTest { - public: - FileBrowseBrowserTest() { - EnableDOMAutomation(); - } -}; - -class FileBrowseUiObserver : public NotificationObserver { - public: - FileBrowseUiObserver() : file_browse_tab_(NULL), is_waiting_(false) { - registrar_.Add(this, NotificationType::LOAD_STOP, - NotificationService::AllSources()); - registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, - NotificationService::AllSources()); - } - - void WaitForFileBrowseLoad() { - if (file_browse_tab_ == NULL) { - is_waiting_ = true; - ui_test_utils::RunMessageLoop(); - } - } - - // File browse tab deletion is a non-nestable task and BrowserTest would - // not get related notification because test body runs in a task already. - // Uses a periodical check of the dialog window to implement the wait. - void WaitForFileBrowseClose() { - if (file_browse_tab_ != NULL) { - is_waiting_ = true; - ui_test_utils::RunMessageLoop(); - } - } - - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - if (type == NotificationType::LOAD_STOP) { - NavigationController* controller = - Source<NavigationController>(source).ptr(); - - if (controller) { - TabContents* tab_contents = controller->tab_contents(); - if (tab_contents && - tab_contents->GetURL().SchemeIs(chrome::kChromeUIScheme) && - tab_contents->GetURL().host() == chrome::kChromeUIFileBrowseHost) { - file_browse_tab_ = tab_contents; - - if (is_waiting_) { - is_waiting_ = false; - MessageLoopForUI::current()->Quit(); - } - } - } - } else if (type == NotificationType::TAB_CONTENTS_DESTROYED) { - TabContents* tab_contents = Source<TabContents>(source).ptr(); - if (file_browse_tab_ == tab_contents) { - file_browse_tab_ = NULL; - - if (is_waiting_) { - is_waiting_ = false; - MessageLoopForUI::current()->Quit(); - } - } - } - } - - TabContents* file_browse_tab() { - return file_browse_tab_; - } - - WebUI* file_browse_ui() { - return file_browse_tab_ ? file_browse_tab_->render_manager()->web_ui() : - NULL; - } - - private: - NotificationRegistrar registrar_; - TabContents* file_browse_tab_; - bool is_waiting_; - - DISALLOW_COPY_AND_ASSIGN(FileBrowseUiObserver); -}; - -IN_PROC_BROWSER_TEST_F(FileBrowseBrowserTest, InputFileTriggerFileBrowse) { - ASSERT_TRUE(test_server()->Start()); - ui_test_utils::NavigateToURL(browser(), - test_server()->GetURL("files/input_file.html")); - - DOMElementProxyRef doc = ui_test_utils::GetActiveDOMDocument(browser()); - - DOMElementProxyRef input_file = doc->FindElement(By::Selectors(".single")); - ASSERT_TRUE(input_file); - - // Creates FileBrowseUiObserver before we click. - FileBrowseUiObserver observer; - - // Click on the input control. This should bring up the FileBrowseUI. - input_file->Click(); - - observer.WaitForFileBrowseLoad(); - WebUI* file_browser_ui = observer.file_browse_ui(); - ASSERT_TRUE(file_browser_ui); - - file_browser_ui->CallJavascriptFunction(L"dialogCancelClick"); - - observer.WaitForFileBrowseClose(); -} - -} // namespace diff --git a/chrome/browser/dom_ui/html_dialog_tab_contents_delegate_unittest.cc b/chrome/browser/dom_ui/html_dialog_tab_contents_delegate_unittest.cc deleted file mode 100644 index 58da688..0000000 --- a/chrome/browser/dom_ui/html_dialog_tab_contents_delegate_unittest.cc +++ /dev/null @@ -1,110 +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/webui/html_dialog_tab_contents_delegate.h" - -#include <vector> - -#include "base/logging.h" -#include "base/scoped_ptr.h" -#include "chrome/browser/history/history_types.h" -#include "chrome/browser/tab_contents/test_tab_contents.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/browser_with_test_window_test.h" -#include "chrome/test/test_browser_window.h" -#include "chrome/test/testing_profile.h" -#include "googleurl/src/gurl.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/rect.h" - -namespace { - -class TestTabContentsDelegate : public HtmlDialogTabContentsDelegate { - public: - explicit TestTabContentsDelegate(Profile* profile) - : HtmlDialogTabContentsDelegate(profile) {} - - virtual ~TestTabContentsDelegate() { - } - - virtual void MoveContents(TabContents* source, const gfx::Rect& pos) {} - virtual void ToolbarSizeChanged(TabContents* source, bool is_animating) {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestTabContentsDelegate); -}; - -class HtmlDialogTabContentsDelegateTest : public BrowserWithTestWindowTest { - public: - virtual void SetUp() { - BrowserWithTestWindowTest::SetUp(); - test_tab_contents_delegate_.reset(new TestTabContentsDelegate(profile())); - } - - virtual void TearDown() { - test_tab_contents_delegate_.reset(NULL); - BrowserWithTestWindowTest::TearDown(); - } - - protected: - scoped_ptr<TestTabContentsDelegate> test_tab_contents_delegate_; -}; - -TEST_F(HtmlDialogTabContentsDelegateTest, DoNothingMethodsTest) { - // None of the following calls should do anything. - EXPECT_TRUE(test_tab_contents_delegate_->IsPopup(NULL)); - scoped_refptr<history::HistoryAddPageArgs> should_add_args( - new history::HistoryAddPageArgs( - GURL(), base::Time::Now(), 0, 0, GURL(), history::RedirectList(), - PageTransition::TYPED, history::SOURCE_SYNCED, false)); - EXPECT_FALSE(test_tab_contents_delegate_->ShouldAddNavigationToHistory( - *should_add_args, NavigationType::NEW_PAGE)); - test_tab_contents_delegate_->NavigationStateChanged(NULL, 0); - test_tab_contents_delegate_->ActivateContents(NULL); - test_tab_contents_delegate_->LoadingStateChanged(NULL); - test_tab_contents_delegate_->CloseContents(NULL); - test_tab_contents_delegate_->UpdateTargetURL(NULL, GURL()); - test_tab_contents_delegate_->MoveContents(NULL, gfx::Rect()); - test_tab_contents_delegate_->ToolbarSizeChanged(NULL, false); - EXPECT_EQ(0, browser()->tab_count()); - EXPECT_EQ(1U, BrowserList::size()); -} - -TEST_F(HtmlDialogTabContentsDelegateTest, OpenURLFromTabTest) { - test_tab_contents_delegate_->OpenURLFromTab( - NULL, GURL(chrome::kAboutBlankURL), GURL(), - NEW_FOREGROUND_TAB, PageTransition::LINK); - // This should create a new foreground tab in the existing browser. - EXPECT_EQ(1, browser()->tab_count()); - EXPECT_EQ(1U, BrowserList::size()); -} - -TEST_F(HtmlDialogTabContentsDelegateTest, AddNewContentsForegroundTabTest) { - TabContents* contents = - new TabContents(profile(), NULL, MSG_ROUTING_NONE, NULL, NULL); - test_tab_contents_delegate_->AddNewContents( - NULL, contents, NEW_FOREGROUND_TAB, gfx::Rect(), false); - // This should create a new foreground tab in the existing browser. - EXPECT_EQ(1, browser()->tab_count()); - EXPECT_EQ(1U, BrowserList::size()); -} - -TEST_F(HtmlDialogTabContentsDelegateTest, DetachTest) { - EXPECT_EQ(profile(), test_tab_contents_delegate_->profile()); - test_tab_contents_delegate_->Detach(); - EXPECT_EQ(NULL, test_tab_contents_delegate_->profile()); - // Now, none of the following calls should do anything. - test_tab_contents_delegate_->OpenURLFromTab( - NULL, GURL(chrome::kAboutBlankURL), GURL(), - NEW_FOREGROUND_TAB, PageTransition::LINK); - test_tab_contents_delegate_->AddNewContents(NULL, NULL, NEW_FOREGROUND_TAB, - gfx::Rect(), false); - EXPECT_EQ(0, browser()->tab_count()); - EXPECT_EQ(1U, BrowserList::size()); -} - -} // namespace diff --git a/chrome/browser/dom_ui/mediaplayer_browsertest.cc b/chrome/browser/dom_ui/mediaplayer_browsertest.cc deleted file mode 100644 index 17958e2..0000000 --- a/chrome/browser/dom_ui/mediaplayer_browsertest.cc +++ /dev/null @@ -1,99 +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 "base/command_line.h" -#include "base/ref_counted.h" -#include "base/utf_string_conversions.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" - -namespace { - -class MediaPlayerBrowserTest : public InProcessBrowserTest { - public: - MediaPlayerBrowserTest() {} - - virtual void SetUpCommandLine(CommandLine* command_line) { - command_line->AppendSwitch(switches::kEnableMediaPlayer); - } - - GURL GetMusicTestURL() { - return GURL("http://localhost:1337/files/plugin/sample_mp3.mp3"); - } - - bool IsPlayerVisible() { - for (BrowserList::const_iterator it = BrowserList::begin(); - it != BrowserList::end(); ++it) { - if ((*it)->type() == Browser::TYPE_APP_PANEL) { - const GURL& url = - (*it)->GetTabContentsAt((*it)->selected_index())->GetURL(); - - if (url.SchemeIs(chrome::kChromeUIScheme) && - url.host() == chrome::kChromeUIMediaplayerHost) { - return true; - } - } - } - return false; - } - - bool IsPlaylistVisible() { - for (BrowserList::const_iterator it = BrowserList::begin(); - it != BrowserList::end(); ++it) { - if ((*it)->type() == Browser::TYPE_APP_PANEL) { - const GURL& url = - (*it)->GetTabContentsAt((*it)->selected_index())->GetURL(); - - if (url.SchemeIs(chrome::kChromeUIScheme) && - url.host() == chrome::kChromeUIMediaplayerHost && - url.ref() == "playlist") { - return true; - } - } - } - return false; - } -}; - -IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, Popup) { - ASSERT_TRUE(test_server()->Start()); - // Doing this so we have a valid profile. - ui_test_utils::NavigateToURL(browser(), - GURL("chrome://downloads")); - - MediaPlayer* player = MediaPlayer::GetInstance(); - // Check that its not currently visible - ASSERT_FALSE(IsPlayerVisible()); - - player->EnqueueMediaURL(GetMusicTestURL(), NULL); - - ASSERT_TRUE(IsPlayerVisible()); -} - -IN_PROC_BROWSER_TEST_F(MediaPlayerBrowserTest, PopupPlaylist) { - ASSERT_TRUE(test_server()->Start()); - // Doing this so we have a valid profile. - ui_test_utils::NavigateToURL(browser(), - GURL("chrome://downloads")); - - - MediaPlayer* player = MediaPlayer::GetInstance(); - - player->EnqueueMediaURL(GetMusicTestURL(), NULL); - - EXPECT_FALSE(IsPlaylistVisible()); - - player->TogglePlaylistWindowVisible(); - - EXPECT_TRUE(IsPlaylistVisible()); -} - -} // namespace diff --git a/chrome/browser/dom_ui/most_visited_handler.cc b/chrome/browser/dom_ui/most_visited_handler.cc deleted file mode 100644 index e5291e9..0000000 --- a/chrome/browser/dom_ui/most_visited_handler.cc +++ /dev/null @@ -1,387 +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/most_visited_handler.h" - -#include <set> - -#include "base/callback.h" -#include "base/command_line.h" -#include "base/md5.h" -#include "base/scoped_vector.h" -#include "base/singleton.h" -#include "base/string16.h" -#include "base/string_number_conversions.h" -#include "base/threading/thread.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/new_tab_ui.h" -#include "chrome/browser/dom_ui/web_ui_favicon_source.h" -#include "chrome/browser/dom_ui/web_ui_thumbnail_source.h" -#include "chrome/browser/history/page_usage_data.h" -#include "chrome/browser/history/top_sites.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/common/notification_source.h" -#include "chrome/common/notification_type.h" -#include "chrome/common/pref_names.h" -#include "googleurl/src/gurl.h" -#include "grit/chromium_strings.h" -#include "grit/generated_resources.h" -#include "grit/locale_settings.h" -#include "ui/base/l10n/l10n_util.h" - -namespace { - -// The number of most visited pages we show. -const size_t kMostVisitedPages = 8; - -// The number of days of history we consider for most visited entries. -const int kMostVisitedScope = 90; - -} // namespace - -// This struct is used when getting the pre-populated pages in case the user -// hasn't filled up his most visited pages. -struct MostVisitedHandler::MostVisitedPage { - string16 title; - GURL url; - GURL thumbnail_url; - GURL favicon_url; -}; - -MostVisitedHandler::MostVisitedHandler() - : url_blacklist_(NULL), - pinned_urls_(NULL), - got_first_most_visited_request_(false) { -} - -MostVisitedHandler::~MostVisitedHandler() { -} - -WebUIMessageHandler* MostVisitedHandler::Attach(WebUI* web_ui) { - Profile* profile = web_ui->GetProfile(); - url_blacklist_ = profile->GetPrefs()->GetMutableDictionary( - prefs::kNTPMostVisitedURLsBlacklist); - pinned_urls_ = profile->GetPrefs()->GetMutableDictionary( - prefs::kNTPMostVisitedPinnedURLs); - // Set up our sources for thumbnail and favicon data. - WebUIThumbnailSource* thumbnail_src = new WebUIThumbnailSource(profile); - profile->GetChromeURLDataManager()->AddDataSource(thumbnail_src); - - WebUIFavIconSource* favicon_src = new WebUIFavIconSource(profile); - profile->GetChromeURLDataManager()->AddDataSource(favicon_src); - - // Get notifications when history is cleared. - registrar_.Add(this, NotificationType::HISTORY_URLS_DELETED, - Source<Profile>(profile)); - - WebUIMessageHandler* result = WebUIMessageHandler::Attach(web_ui); - - // We pre-emptively make a fetch for the most visited pages so we have the - // results sooner. - StartQueryForMostVisited(); - return result; -} - -void MostVisitedHandler::RegisterMessages() { - // Register ourselves as the handler for the "mostvisited" message from - // Javascript. - web_ui_->RegisterMessageCallback("getMostVisited", - NewCallback(this, &MostVisitedHandler::HandleGetMostVisited)); - - // Register ourselves for any most-visited item blacklisting. - web_ui_->RegisterMessageCallback("blacklistURLFromMostVisited", - NewCallback(this, &MostVisitedHandler::HandleBlacklistURL)); - web_ui_->RegisterMessageCallback("removeURLsFromMostVisitedBlacklist", - NewCallback(this, &MostVisitedHandler::HandleRemoveURLsFromBlacklist)); - web_ui_->RegisterMessageCallback("clearMostVisitedURLsBlacklist", - NewCallback(this, &MostVisitedHandler::HandleClearBlacklist)); - - // Register ourself for pinned URL messages. - web_ui_->RegisterMessageCallback("addPinnedURL", - NewCallback(this, &MostVisitedHandler::HandleAddPinnedURL)); - web_ui_->RegisterMessageCallback("removePinnedURL", - NewCallback(this, &MostVisitedHandler::HandleRemovePinnedURL)); -} - -void MostVisitedHandler::HandleGetMostVisited(const ListValue* args) { - if (!got_first_most_visited_request_) { - // If our intial data is already here, return it. - SendPagesValue(); - got_first_most_visited_request_ = true; - } else { - StartQueryForMostVisited(); - } -} - -void MostVisitedHandler::SendPagesValue() { - if (pages_value_.get()) { - bool has_blacklisted_urls = !url_blacklist_->empty(); - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - has_blacklisted_urls = ts->HasBlacklistedItems(); - FundamentalValue first_run(IsFirstRun()); - FundamentalValue has_blacklisted_urls_value(has_blacklisted_urls); - web_ui_->CallJavascriptFunction(L"mostVisitedPages", - *(pages_value_.get()), - first_run, - has_blacklisted_urls_value); - pages_value_.reset(); - } -} - -void MostVisitedHandler::StartQueryForMostVisited() { - // Use TopSites. - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) { - ts->GetMostVisitedURLs( - &topsites_consumer_, - NewCallback(this, &MostVisitedHandler::OnMostVisitedURLsAvailable)); - } -} - -void MostVisitedHandler::HandleBlacklistURL(const ListValue* args) { - std::string url = WideToUTF8(ExtractStringValue(args)); - BlacklistURL(GURL(url)); -} - -void MostVisitedHandler::HandleRemoveURLsFromBlacklist(const ListValue* args) { - DCHECK(args->GetSize() != 0); - - for (ListValue::const_iterator iter = args->begin(); - iter != args->end(); ++iter) { - std::string url; - bool r = (*iter)->GetAsString(&url); - if (!r) { - NOTREACHED(); - return; - } - UserMetrics::RecordAction(UserMetricsAction("MostVisited_UrlRemoved"), - web_ui_->GetProfile()); - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - ts->RemoveBlacklistedURL(GURL(url)); - } -} - -void MostVisitedHandler::HandleClearBlacklist(const ListValue* args) { - UserMetrics::RecordAction(UserMetricsAction("MostVisited_BlacklistCleared"), - web_ui_->GetProfile()); - - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - ts->ClearBlacklistedURLs(); -} - -void MostVisitedHandler::HandleAddPinnedURL(const ListValue* args) { - DCHECK_EQ(5U, args->GetSize()) << "Wrong number of params to addPinnedURL"; - MostVisitedPage mvp; - std::string tmp_string; - string16 tmp_string16; - int index; - - bool r = args->GetString(0, &tmp_string); - DCHECK(r) << "Missing URL in addPinnedURL from the NTP Most Visited."; - mvp.url = GURL(tmp_string); - - r = args->GetString(1, &tmp_string16); - DCHECK(r) << "Missing title in addPinnedURL from the NTP Most Visited."; - mvp.title = tmp_string16; - - r = args->GetString(2, &tmp_string); - DCHECK(r) << "Failed to read the favicon URL in addPinnedURL from the NTP " - << "Most Visited."; - if (!tmp_string.empty()) - mvp.favicon_url = GURL(tmp_string); - - r = args->GetString(3, &tmp_string); - DCHECK(r) << "Failed to read the thumbnail URL in addPinnedURL from the NTP " - << "Most Visited."; - if (!tmp_string.empty()) - mvp.thumbnail_url = GURL(tmp_string); - - r = args->GetString(4, &tmp_string); - DCHECK(r) << "Missing index in addPinnedURL from the NTP Most Visited."; - base::StringToInt(tmp_string, &index); - - AddPinnedURL(mvp, index); -} - -void MostVisitedHandler::AddPinnedURL(const MostVisitedPage& page, int index) { - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - ts->AddPinnedURL(page.url, index); -} - -void MostVisitedHandler::HandleRemovePinnedURL(const ListValue* args) { - std::string url = WideToUTF8(ExtractStringValue(args)); - RemovePinnedURL(GURL(url)); -} - -void MostVisitedHandler::RemovePinnedURL(const GURL& url) { - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - ts->RemovePinnedURL(url); -} - -bool MostVisitedHandler::GetPinnedURLAtIndex(int index, - MostVisitedPage* page) { - // This iterates over all the pinned URLs. It might seem like it is worth - // having a map from the index to the item but the number of items is limited - // to the number of items the most visited section is showing on the NTP so - // this will be fast enough for now. - for (DictionaryValue::key_iterator it = pinned_urls_->begin_keys(); - it != pinned_urls_->end_keys(); ++it) { - Value* value; - if (pinned_urls_->GetWithoutPathExpansion(*it, &value)) { - if (!value->IsType(DictionaryValue::TYPE_DICTIONARY)) { - // Moved on to TopSites and now going back. - pinned_urls_->Clear(); - return false; - } - - int dict_index; - DictionaryValue* dict = static_cast<DictionaryValue*>(value); - if (dict->GetInteger("index", &dict_index) && dict_index == index) { - // The favicon and thumbnail URLs may be empty. - std::string tmp_string; - if (dict->GetString("faviconUrl", &tmp_string)) - page->favicon_url = GURL(tmp_string); - if (dict->GetString("thumbnailUrl", &tmp_string)) - page->thumbnail_url = GURL(tmp_string); - - if (dict->GetString("url", &tmp_string)) - page->url = GURL(tmp_string); - else - return false; - - return dict->GetString("title", &page->title); - } - } else { - NOTREACHED() << "DictionaryValue iterators are filthy liars."; - } - } - - return false; -} - -void MostVisitedHandler::SetPagesValueFromTopSites( - const history::MostVisitedURLList& data) { - pages_value_.reset(new ListValue); - for (size_t i = 0; i < data.size(); i++) { - const history::MostVisitedURL& url = data[i]; - DictionaryValue* page_value = new DictionaryValue(); - if (url.url.is_empty()) { - page_value->SetBoolean("filler", true); - pages_value_->Append(page_value); - continue; - } - - NewTabUI::SetURLTitleAndDirection(page_value, - url.title, - url.url); - if (!url.favicon_url.is_empty()) - page_value->SetString("faviconUrl", url.favicon_url.spec()); - - // Special case for prepopulated pages: thumbnailUrl is different from url. - if (url.url.spec() == l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)) { - page_value->SetString("thumbnailUrl", - "chrome://theme/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL"); - } else if (url.url.spec() == - l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)) { - page_value->SetString("thumbnailUrl", - "chrome://theme/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL"); - } - - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts && ts->IsURLPinned(url.url)) - page_value->SetBoolean("pinned", true); - pages_value_->Append(page_value); - } -} - -void MostVisitedHandler::OnMostVisitedURLsAvailable( - const history::MostVisitedURLList& data) { - SetPagesValueFromTopSites(data); - if (got_first_most_visited_request_) { - SendPagesValue(); - } -} - -bool MostVisitedHandler::IsFirstRun() { - // If we found no pages we treat this as the first run. - bool first_run = NewTabUI::NewTabHTMLSource::first_run() && - pages_value_->GetSize() == - MostVisitedHandler::GetPrePopulatedPages().size(); - // but first_run should only be true once. - NewTabUI::NewTabHTMLSource::set_first_run(false); - return first_run; -} - -// static -const std::vector<MostVisitedHandler::MostVisitedPage>& - MostVisitedHandler::GetPrePopulatedPages() { - // TODO(arv): This needs to get the data from some configurable place. - // http://crbug.com/17630 - static std::vector<MostVisitedPage> pages; - if (pages.empty()) { - MostVisitedPage welcome_page = { - l10n_util::GetStringUTF16(IDS_NEW_TAB_CHROME_WELCOME_PAGE_TITLE), - GURL(l10n_util::GetStringUTF8(IDS_CHROME_WELCOME_URL)), - GURL("chrome://theme/IDR_NEWTAB_CHROME_WELCOME_PAGE_THUMBNAIL"), - GURL("chrome://theme/IDR_NEWTAB_CHROME_WELCOME_PAGE_FAVICON")}; - pages.push_back(welcome_page); - - MostVisitedPage gallery_page = { - l10n_util::GetStringUTF16(IDS_NEW_TAB_THEMES_GALLERY_PAGE_TITLE), - GURL(l10n_util::GetStringUTF8(IDS_THEMES_GALLERY_URL)), - GURL("chrome://theme/IDR_NEWTAB_THEMES_GALLERY_THUMBNAIL"), - GURL("chrome://theme/IDR_NEWTAB_THEMES_GALLERY_FAVICON")}; - pages.push_back(gallery_page); - } - - return pages; -} - -void MostVisitedHandler::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - if (type != NotificationType::HISTORY_URLS_DELETED) { - NOTREACHED(); - return; - } - - // Some URLs were deleted from history. Reload the most visited list. - HandleGetMostVisited(NULL); -} - -void MostVisitedHandler::BlacklistURL(const GURL& url) { - history::TopSites* ts = web_ui_->GetProfile()->GetTopSites(); - if (ts) - ts->AddBlacklistedURL(url); -} - -std::string MostVisitedHandler::GetDictionaryKeyForURL(const std::string& url) { - return MD5String(url); -} - -// static -void MostVisitedHandler::RegisterUserPrefs(PrefService* prefs) { - prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedURLsBlacklist); - prefs->RegisterDictionaryPref(prefs::kNTPMostVisitedPinnedURLs); -} - -// static -std::vector<GURL> MostVisitedHandler::GetPrePopulatedUrls() { - const std::vector<MostVisitedPage> pages = - MostVisitedHandler::GetPrePopulatedPages(); - std::vector<GURL> page_urls; - for (size_t i = 0; i < pages.size(); ++i) - page_urls.push_back(pages[i].url); - return page_urls; -} diff --git a/chrome/browser/dom_ui/most_visited_handler.h b/chrome/browser/dom_ui/most_visited_handler.h deleted file mode 100644 index 814d9e1..0000000 --- a/chrome/browser/dom_ui/most_visited_handler.h +++ /dev/null @@ -1,136 +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_MOST_VISITED_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_MOST_VISITED_HANDLER_H_ -#pragma once - -#include <string> -#include <vector> - -#include "chrome/browser/cancelable_request.h" -#include "chrome/browser/history/history_types.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/notification_observer.h" -#include "chrome/common/notification_registrar.h" - -class DictionaryValue; -class GURL; -class ListValue; -class PageUsageData; -class PrefService; -class Value; - -// The handler for Javascript messages related to the "most visited" view. -class MostVisitedHandler : public WebUIMessageHandler, - public NotificationObserver { - public: - - MostVisitedHandler(); - virtual ~MostVisitedHandler(); - - // WebUIMessageHandler override and implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Callback for the "getMostVisited" message. - void HandleGetMostVisited(const ListValue* args); - - // Callback for the "blacklistURLFromMostVisited" message. - void HandleBlacklistURL(const ListValue* args); - - // Callback for the "removeURLsFromMostVisitedBlacklist" message. - void HandleRemoveURLsFromBlacklist(const ListValue* args); - - // Callback for the "clearMostVisitedURLsBlacklist" message. - void HandleClearBlacklist(const ListValue* args); - - // Callback for the "addPinnedURL" message. - void HandleAddPinnedURL(const ListValue* args); - - // Callback for the "removePinnedURL" message. - void HandleRemovePinnedURL(const ListValue* args); - - // NotificationObserver implementation. - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - const std::vector<GURL>& most_visited_urls() const { - return most_visited_urls_; - } - - static void RegisterUserPrefs(PrefService* prefs); - - // Returns a vector containing the urls for the prepopulated pages. - // Used only in testing. - static std::vector<GURL> GetPrePopulatedUrls(); - - private: - struct MostVisitedPage; - - // Send a request to the HistoryService to get the most visited pages. - void StartQueryForMostVisited(); - - // Sets pages_value_ from a format produced by TopSites. - void SetPagesValueFromTopSites(const history::MostVisitedURLList& data); - - // Callback for TopSites. - void OnMostVisitedURLsAvailable(const history::MostVisitedURLList& data); - - // Puts the passed URL in the blacklist (so it does not show as a thumbnail). - void BlacklistURL(const GURL& url); - - // Returns the key used in url_blacklist_ and pinned_urls_ for the passed - // |url|. - std::string GetDictionaryKeyForURL(const std::string& url); - - // Gets the page data for a pinned URL at a given index. This returns - // true if found. - bool GetPinnedURLAtIndex(int index, MostVisitedPage* page); - - void AddPinnedURL(const MostVisitedPage& page, int index); - void RemovePinnedURL(const GURL& url); - - // Sends pages_value_ to the javascript side to and resets page_value_. - void SendPagesValue(); - - // Returns true if we should treat this as the first run of the new tab page. - bool IsFirstRun(); - - static const std::vector<MostVisitedPage>& GetPrePopulatedPages(); - - NotificationRegistrar registrar_; - - // Our consumer for the history service. - CancelableRequestConsumerTSimple<PageUsageData*> cancelable_consumer_; - CancelableRequestConsumer topsites_consumer_; - - // The most visited URLs, in priority order. - // Only used for matching up clicks on the page to which most visited entry - // was clicked on for metrics purposes. - std::vector<GURL> most_visited_urls_; - - // The URL blacklist: URLs we do not want to show in the thumbnails list. It - // is a dictionary for quick access (it associates a dummy boolean to the URL - // string). This is owned by the PrefService. - DictionaryValue* url_blacklist_; - - // This is a dictionary for the pinned URLs for the the most visited part of - // the new tab page. The key of the dictionary is a hash of the URL and the - // value is a dictionary with title, url and index. This is owned by the - // PrefService. - DictionaryValue* pinned_urls_; - - // We pre-fetch the first set of result pages. This variable is false until - // we get the first getMostVisited() call. - bool got_first_most_visited_request_; - - // Keep the results of the db query here. - scoped_ptr<ListValue> pages_value_; - - DISALLOW_COPY_AND_ASSIGN(MostVisitedHandler); -}; - -#endif // CHROME_BROWSER_DOM_UI_MOST_VISITED_HANDLER_H_ diff --git a/chrome/browser/dom_ui/new_tab_page_sync_handler.cc b/chrome/browser/dom_ui/new_tab_page_sync_handler.cc deleted file mode 100644 index ec3da8b..0000000 --- a/chrome/browser/dom_ui/new_tab_page_sync_handler.cc +++ /dev/null @@ -1,221 +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/new_tab_page_sync_handler.h" - -#include <vector> - -#include "base/callback.h" -#include "base/string_split.h" -#include "base/string_util.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/net/chrome_url_request_context.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "grit/browser_resources.h" -#include "grit/generated_resources.h" -#include "net/base/cookie_monster.h" -#include "net/url_request/url_request_context.h" -#include "ui/base/l10n/l10n_util.h" - -// Default URL for the sync web interface. -// -// TODO(idana): when we figure out how we are going to allow third parties to -// plug in their own sync engine, we should allow this value to be -// configurable. -static const char kSyncDefaultViewOnlineUrl[] = "http://docs.google.com"; - -// TODO(idana): the following code was originally copied from -// toolbar_importer.h/cc and it needs to be moved to a common Google Accounts -// utility. - -// A simple pair of fields that identify a set of Google cookies, used to -// filter from a larger set. -struct GoogleCookieFilter { - // The generalized, fully qualified URL of pages where - // cookies with id |cookie_id| are obtained / accessed. - const char* url; - // The id of the cookie this filter is selecting, - // with name/value delimiter (i.e '='). - const char* cookie_id; -}; - -// Filters to select Google GAIA cookies. -static const GoogleCookieFilter kGAIACookieFilters[] = { - { "http://.google.com/", "SID=" }, // Gmail. - // Add filters here for other interesting cookies that should result in - // showing the promotions (e.g ASIDAS for dasher accounts). -}; - -bool IsGoogleGAIACookieInstalled() { - for (size_t i = 0; i < arraysize(kGAIACookieFilters); ++i) { - // Since we are running on the UI thread don't call GetURLRequestContext(). - net::CookieStore* store = - Profile::GetDefaultRequestContext()->GetCookieStore(); - GURL url(kGAIACookieFilters[i].url); - net::CookieOptions options; - options.set_include_httponly(); // The SID cookie might be httponly. - std::string cookies = store->GetCookiesWithOptions(url, options); - std::vector<std::string> cookie_list; - base::SplitString(cookies, ';', &cookie_list); - for (std::vector<std::string>::iterator current = cookie_list.begin(); - current != cookie_list.end(); - ++current) { - size_t position = - current->find(kGAIACookieFilters[i].cookie_id); - if (0 == position) - return true; - } - } - return false; -} - -NewTabPageSyncHandler::NewTabPageSyncHandler() : sync_service_(NULL), - waiting_for_initial_page_load_(true) { -} - -NewTabPageSyncHandler::~NewTabPageSyncHandler() { - if (sync_service_) - sync_service_->RemoveObserver(this); -} - -// static -NewTabPageSyncHandler::MessageType - NewTabPageSyncHandler::FromSyncStatusMessageType( - sync_ui_util::MessageType type) { - switch (type) { - case sync_ui_util::SYNC_ERROR: - return SYNC_ERROR; - case sync_ui_util::SYNC_PROMO: - return SYNC_PROMO; - case sync_ui_util::PRE_SYNCED: - case sync_ui_util::SYNCED: - default: - return HIDE; - } -} - -WebUIMessageHandler* NewTabPageSyncHandler::Attach(WebUI* web_ui) { - sync_service_ = web_ui->GetProfile()->GetProfileSyncService(); - DCHECK(sync_service_); // This shouldn't get called by an incognito NTP. - DCHECK(!sync_service_->IsManaged()); // And neither if sync is managed. - sync_service_->AddObserver(this); - return WebUIMessageHandler::Attach(web_ui); -} - -void NewTabPageSyncHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("GetSyncMessage", - NewCallback(this, &NewTabPageSyncHandler::HandleGetSyncMessage)); - web_ui_->RegisterMessageCallback("SyncLinkClicked", - NewCallback(this, &NewTabPageSyncHandler::HandleSyncLinkClicked)); -} - -void NewTabPageSyncHandler::HandleGetSyncMessage(const ListValue* args) { - waiting_for_initial_page_load_ = false; - BuildAndSendSyncStatus(); -} - -void NewTabPageSyncHandler::HideSyncStatusSection() { - SendSyncMessageToPage(HIDE, std::string(), std::string()); -} - -void NewTabPageSyncHandler::BuildAndSendSyncStatus() { - DCHECK(!waiting_for_initial_page_load_); - - // Hide the sync status section if sync is managed or disabled entirely. - if (!sync_service_ || sync_service_->IsManaged()) { - HideSyncStatusSection(); - return; - } - - // Don't show sync status if setup is not complete. - if (!sync_service_->HasSyncSetupCompleted()) { - return; - } - - // Once sync has been enabled, the supported "sync statuses" for the NNTP - // from the user's perspective are: - // - // "Sync error", when we can't authenticate or establish a connection with - // the sync server (appropriate information appended to - // message). - string16 status_msg; - string16 link_text; - sync_ui_util::MessageType type = - sync_ui_util::GetStatusLabelsForNewTabPage(sync_service_, - &status_msg, - &link_text); - SendSyncMessageToPage(FromSyncStatusMessageType(type), - UTF16ToUTF8(status_msg), UTF16ToUTF8(link_text)); -} - -void NewTabPageSyncHandler::HandleSyncLinkClicked(const ListValue* args) { - DCHECK(!waiting_for_initial_page_load_); - DCHECK(sync_service_); - if (!sync_service_->IsSyncEnabled()) - return; - if (sync_service_->HasSyncSetupCompleted()) { - sync_service_->ShowErrorUI(NULL); - DictionaryValue value; - value.SetString("syncEnabledMessage", - l10n_util::GetStringFUTF16(IDS_SYNC_NTP_SYNCED_TO, - sync_service_->GetAuthenticatedUsername())); - web_ui_->CallJavascriptFunction(L"syncAlreadyEnabled", value); - } else { - // User clicked the 'Start now' link to begin syncing. - ProfileSyncService::SyncEvent(ProfileSyncService::START_FROM_NTP); - sync_service_->ShowLoginDialog(NULL); - } -} - -void NewTabPageSyncHandler::OnStateChanged() { - // Don't do anything if the page has not yet loaded. - if (waiting_for_initial_page_load_) - return; - BuildAndSendSyncStatus(); -} - -void NewTabPageSyncHandler::SendSyncMessageToPage( - MessageType type, std::string msg, - std::string linktext) { - DictionaryValue value; - std::string user; - std::string title; - std::string linkurl; - - // If there is nothing to show, we should hide the sync section altogether. - if (type == HIDE || (msg.empty() && linktext.empty())) { - value.SetBoolean("syncsectionisvisible", false); - } else { - if (type == SYNC_ERROR) - title = l10n_util::GetStringUTF8(IDS_SYNC_NTP_SYNC_SECTION_ERROR_TITLE); - else if (type == SYNC_PROMO) - title = l10n_util::GetStringUTF8(IDS_SYNC_NTP_SYNC_SECTION_PROMO_TITLE); - else - NOTREACHED(); - - value.SetBoolean("syncsectionisvisible", true); - value.SetString("msg", msg); - value.SetString("title", title); - if (linktext.empty()) { - value.SetBoolean("linkisvisible", false); - } else { - value.SetBoolean("linkisvisible", true); - value.SetString("linktext", linktext); - - // The only time we set the URL is when the user is synced and we need to - // show a link to a web interface (e.g. http://docs.google.com). When we - // set that URL, HandleSyncLinkClicked won't be called when the user - // clicks on the link. - if (linkurl.empty()) { - value.SetBoolean("linkurlisset", false); - } else { - value.SetBoolean("linkurlisset", true); - value.SetString("linkurl", linkurl); - } - } - } - web_ui_->CallJavascriptFunction(L"syncMessageChanged", value); -} diff --git a/chrome/browser/dom_ui/new_tab_page_sync_handler.h b/chrome/browser/dom_ui/new_tab_page_sync_handler.h deleted file mode 100644 index 672ac54..0000000 --- a/chrome/browser/dom_ui/new_tab_page_sync_handler.h +++ /dev/null @@ -1,69 +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_NEW_TAB_PAGE_SYNC_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_NEW_TAB_PAGE_SYNC_HANDLER_H_ -#pragma once - -#include <string> - -#include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/sync/sync_ui_util.h" -#include "chrome/browser/webui/web_ui.h" - -class ListValue; - -// Sends sync-state changes to the New Tab Page for UI updating and forwards -// link clicks on the page to the sync service. -class NewTabPageSyncHandler : public WebUIMessageHandler, - public ProfileSyncServiceObserver { - public: - NewTabPageSyncHandler(); - virtual ~NewTabPageSyncHandler(); - - // WebUIMessageHandler implementation. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Callback for "GetSyncMessage". - void HandleGetSyncMessage(const ListValue* args); - // Callback for "SyncLinkClicked". - void HandleSyncLinkClicked(const ListValue* args); - - // ProfileSyncServiceObserver - virtual void OnStateChanged(); - - private: - enum MessageType { - HIDE, - SYNC_ERROR, - SYNC_PROMO - }; - // Helper to invoke the |syncMessageChanged| JS function on the new tab page. - void SendSyncMessageToPage(MessageType type, - std::string msg, std::string linktext); - - // Helper to query the sync service and figure out what to send to - // the page, and send it via SendSyncMessageToPage. - // NOTE: precondition: sync must be enabled. - void BuildAndSendSyncStatus(); - - // Helper to send a message to the NNTP which hides the sync section. - void HideSyncStatusSection(); - - // Helper to convert from a sync status message type to an NTP specific one. - static MessageType FromSyncStatusMessageType( - sync_ui_util::MessageType type); - - // Cached pointer to ProfileSyncService. - ProfileSyncService* sync_service_; - - // Used to make sure we don't register ourselves twice if the user refreshes - // the new tab page. - bool waiting_for_initial_page_load_; - - DISALLOW_COPY_AND_ASSIGN(NewTabPageSyncHandler); -}; - -#endif // CHROME_BROWSER_DOM_UI_NEW_TAB_PAGE_SYNC_HANDLER_H_ diff --git a/chrome/browser/dom_ui/new_tab_ui.cc b/chrome/browser/dom_ui/new_tab_ui.cc deleted file mode 100644 index 6594e1c..0000000 --- a/chrome/browser/dom_ui/new_tab_ui.cc +++ /dev/null @@ -1,600 +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 "build/build_config.h" - -#include "chrome/browser/dom_ui/new_tab_ui.h" - -#include <set> - -#include "base/callback.h" -#include "base/command_line.h" -#include "base/i18n/rtl.h" -#include "base/metrics/histogram.h" -#include "base/singleton.h" -#include "base/string_number_conversions.h" -#include "base/threading/thread.h" -#include "base/utf_string_conversions.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/most_visited_handler.h" -#include "chrome/browser/dom_ui/new_tab_page_sync_handler.h" -#include "chrome/browser/dom_ui/ntp_login_handler.h" -#include "chrome/browser/dom_ui/ntp_resource_cache.h" -#include "chrome/browser/dom_ui/shown_sections_handler.h" -#include "chrome/browser/dom_ui/tips_handler.h" -#include "chrome/browser/dom_ui/value_helper.h" -#include "chrome/browser/dom_ui/web_ui_theme_source.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/browser/sessions/session_types.h" -#include "chrome/browser/sessions/tab_restore_service.h" -#include "chrome/browser/sessions/tab_restore_service_observer.h" -#include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/themes/browser_theme_provider.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/browser/webui/app_launcher_handler.h" -#include "chrome/browser/webui/foreign_session_handler.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/common/notification_service.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "grit/generated_resources.h" -#include "grit/theme_resources.h" -#include "ui/base/l10n/l10n_util.h" - -namespace { - -// The number of recent bookmarks we show. -const int kRecentBookmarks = 9; - -// The number of search URLs to show. -const int kSearchURLs = 3; - -// The amount of time there must be no painting for us to consider painting -// finished. Observed times are in the ~1200ms range on Windows. -const int kTimeoutMs = 2000; - -// Strings sent to the page via jstemplates used to set the direction of the -// HTML document based on locale. -const char kRTLHtmlTextDirection[] = "rtl"; -const char kDefaultHtmlTextDirection[] = "ltr"; - -/////////////////////////////////////////////////////////////////////////////// -// RecentlyClosedTabsHandler - -class RecentlyClosedTabsHandler : public WebUIMessageHandler, - public TabRestoreServiceObserver { - public: - RecentlyClosedTabsHandler() : tab_restore_service_(NULL) {} - virtual ~RecentlyClosedTabsHandler(); - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - // Callback for the "reopenTab" message. Rewrites the history of the - // currently displayed tab to be the one in TabRestoreService with a - // history of a session passed in through the content pointer. - void HandleReopenTab(const ListValue* args); - - // Callback for the "getRecentlyClosedTabs" message. - void HandleGetRecentlyClosedTabs(const ListValue* args); - - // Observer callback for TabRestoreServiceObserver. Sends data on - // recently closed tabs to the javascript side of this page to - // display to the user. - virtual void TabRestoreServiceChanged(TabRestoreService* service); - - // Observer callback to notice when our associated TabRestoreService - // is destroyed. - virtual void TabRestoreServiceDestroyed(TabRestoreService* service); - - private: - // TabRestoreService that we are observing. - TabRestoreService* tab_restore_service_; - - DISALLOW_COPY_AND_ASSIGN(RecentlyClosedTabsHandler); -}; - -void RecentlyClosedTabsHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getRecentlyClosedTabs", - NewCallback(this, - &RecentlyClosedTabsHandler::HandleGetRecentlyClosedTabs)); - web_ui_->RegisterMessageCallback("reopenTab", - NewCallback(this, &RecentlyClosedTabsHandler::HandleReopenTab)); -} - -RecentlyClosedTabsHandler::~RecentlyClosedTabsHandler() { - if (tab_restore_service_) - tab_restore_service_->RemoveObserver(this); -} - -void RecentlyClosedTabsHandler::HandleReopenTab(const ListValue* args) { - Browser* browser = Browser::GetBrowserForController( - &web_ui_->tab_contents()->controller(), NULL); - if (!browser) - return; - - int session_to_restore; - if (ExtractIntegerValue(args, &session_to_restore)) - tab_restore_service_->RestoreEntryById(browser, session_to_restore, true); - // The current tab has been nuked at this point; don't touch any member - // variables. -} - -void RecentlyClosedTabsHandler::HandleGetRecentlyClosedTabs( - const ListValue* args) { - if (!tab_restore_service_) { - tab_restore_service_ = web_ui_->GetProfile()->GetTabRestoreService(); - - // GetTabRestoreService() can return NULL (i.e., when in Off the - // Record mode) - if (tab_restore_service_) { - // This does nothing if the tabs have already been loaded or they - // shouldn't be loaded. - tab_restore_service_->LoadTabsFromLastSession(); - - tab_restore_service_->AddObserver(this); - } - } - - if (tab_restore_service_) - TabRestoreServiceChanged(tab_restore_service_); -} - -void RecentlyClosedTabsHandler::TabRestoreServiceChanged( - TabRestoreService* service) { - ListValue list_value; - NewTabUI::AddRecentlyClosedEntries(service->entries(), &list_value); - - web_ui_->CallJavascriptFunction(L"recentlyClosedTabs", list_value); -} - -void RecentlyClosedTabsHandler::TabRestoreServiceDestroyed( - TabRestoreService* service) { - tab_restore_service_ = NULL; -} - -/////////////////////////////////////////////////////////////////////////////// -// MetricsHandler - -// Let the page contents record UMA actions. Only use when you can't do it from -// C++. For example, we currently use it to let the NTP log the postion of the -// Most Visited or Bookmark the user clicked on, as we don't get that -// information through RequestOpenURL. You will need to update the metrics -// dashboard with the action names you use, as our processor won't catch that -// information (treat it as RecordComputedMetrics) -class MetricsHandler : public WebUIMessageHandler { - public: - MetricsHandler() {} - virtual ~MetricsHandler() {} - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - // Callback which records a user action. - void HandleMetrics(const ListValue* args); - - // Callback for the "logEventTime" message. - void HandleLogEventTime(const ListValue* args); - - private: - - DISALLOW_COPY_AND_ASSIGN(MetricsHandler); -}; - -void MetricsHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("metrics", - NewCallback(this, &MetricsHandler::HandleMetrics)); - - web_ui_->RegisterMessageCallback("logEventTime", - NewCallback(this, &MetricsHandler::HandleLogEventTime)); -} - -void MetricsHandler::HandleMetrics(const ListValue* args) { - std::string string_action = WideToUTF8(ExtractStringValue(args)); - UserMetrics::RecordComputedAction(string_action, web_ui_->GetProfile()); -} - -void MetricsHandler::HandleLogEventTime(const ListValue* args) { - std::string event_name = WideToUTF8(ExtractStringValue(args)); - web_ui_->tab_contents()->LogNewTabTime(event_name); -} - -/////////////////////////////////////////////////////////////////////////////// -// NewTabPageSetHomePageHandler - -// Sets the new tab page as home page when user clicks on "make this my home -// page" link. -class NewTabPageSetHomePageHandler : public WebUIMessageHandler { - public: - NewTabPageSetHomePageHandler() {} - virtual ~NewTabPageSetHomePageHandler() {} - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - // Callback for "setHomePage". - void HandleSetHomePage(const ListValue* args); - - private: - - DISALLOW_COPY_AND_ASSIGN(NewTabPageSetHomePageHandler); -}; - -void NewTabPageSetHomePageHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("setHomePage", NewCallback( - this, &NewTabPageSetHomePageHandler::HandleSetHomePage)); -} - -void NewTabPageSetHomePageHandler::HandleSetHomePage( - const ListValue* args) { - web_ui_->GetProfile()->GetPrefs()->SetBoolean(prefs::kHomePageIsNewTabPage, - true); - ListValue list_value; - list_value.Append(new StringValue( - l10n_util::GetStringUTF16(IDS_NEW_TAB_HOME_PAGE_SET_NOTIFICATION))); - list_value.Append(new StringValue( - l10n_util::GetStringUTF16(IDS_NEW_TAB_HOME_PAGE_HIDE_NOTIFICATION))); - web_ui_->CallJavascriptFunction(L"onHomePageSet", list_value); -} - -/////////////////////////////////////////////////////////////////////////////// -// NewTabPageClosePromoHandler - -// Turns off the promo line permanently when it has been explicitly closed by -// the user. -class NewTabPageClosePromoHandler : public WebUIMessageHandler { - public: - NewTabPageClosePromoHandler() {} - virtual ~NewTabPageClosePromoHandler() {} - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - // Callback for "closePromo". - void HandleClosePromo(const ListValue* args); - - private: - - DISALLOW_COPY_AND_ASSIGN(NewTabPageClosePromoHandler); -}; - -void NewTabPageClosePromoHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("closePromo", NewCallback( - this, &NewTabPageClosePromoHandler::HandleClosePromo)); -} - -void NewTabPageClosePromoHandler::HandleClosePromo( - const ListValue* args) { - web_ui_->GetProfile()->GetPrefs()->SetBoolean(prefs::kNTPPromoClosed, true); - NotificationService* service = NotificationService::current(); - service->Notify(NotificationType::PROMO_RESOURCE_STATE_CHANGED, - Source<NewTabPageClosePromoHandler>(this), - NotificationService::NoDetails()); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// NewTabUI - -NewTabUI::NewTabUI(TabContents* contents) - : WebUI(contents) { - // Override some options on the Web UI. - hide_favicon_ = true; - force_bookmark_bar_visible_ = true; - focus_location_bar_by_default_ = true; - should_hide_url_ = true; - overridden_title_ = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); - - // We count all link clicks as AUTO_BOOKMARK, so that site can be ranked more - // highly. Note this means we're including clicks on not only most visited - // thumbnails, but also clicks on recently bookmarked. - link_transition_type_ = PageTransition::AUTO_BOOKMARK; - - if (NewTabUI::FirstRunDisabled()) - NewTabHTMLSource::set_first_run(false); - - static bool first_view = true; - if (first_view) { - first_view = false; - } - - if (!GetProfile()->IsOffTheRecord()) { - PrefService* pref_service = GetProfile()->GetPrefs(); - AddMessageHandler((new NTPLoginHandler())->Attach(this)); - AddMessageHandler((new ShownSectionsHandler(pref_service))->Attach(this)); - AddMessageHandler((new browser_sync::ForeignSessionHandler())-> - Attach(this)); - AddMessageHandler((new MostVisitedHandler())->Attach(this)); - AddMessageHandler((new RecentlyClosedTabsHandler())->Attach(this)); - AddMessageHandler((new MetricsHandler())->Attach(this)); - if (GetProfile()->IsSyncAccessible()) - AddMessageHandler((new NewTabPageSyncHandler())->Attach(this)); - ExtensionService* service = GetProfile()->GetExtensionService(); - // We might not have an ExtensionService (on ChromeOS when not logged in - // for example). - if (service) - AddMessageHandler((new AppLauncherHandler(service))->Attach(this)); - - AddMessageHandler((new NewTabPageSetHomePageHandler())->Attach(this)); - AddMessageHandler((new NewTabPageClosePromoHandler())->Attach(this)); - } - - // Initializing the CSS and HTML can require some CPU, so do it after - // we've hooked up the most visited handler. This allows the DB query - // for the new tab thumbs to happen earlier. - InitializeCSSCaches(); - NewTabHTMLSource* html_source = - new NewTabHTMLSource(GetProfile()->GetOriginalProfile()); - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); - - // Listen for theme installation. - registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, - NotificationService::AllSources()); - // Listen for bookmark bar visibility changes. - registrar_.Add(this, NotificationType::BOOKMARK_BAR_VISIBILITY_PREF_CHANGED, - NotificationService::AllSources()); -} - -NewTabUI::~NewTabUI() { -} - -// The timer callback. If enough time has elapsed since the last paint -// message, we say we're done painting; otherwise, we keep waiting. -void NewTabUI::PaintTimeout() { - // The amount of time there must be no painting for us to consider painting - // finished. Observed times are in the ~1200ms range on Windows. - base::TimeTicks now = base::TimeTicks::Now(); - if ((now - last_paint_) >= base::TimeDelta::FromMilliseconds(kTimeoutMs)) { - // Painting has quieted down. Log this as the full time to run. - base::TimeDelta load_time = last_paint_ - start_; - int load_time_ms = static_cast<int>(load_time.InMilliseconds()); - NotificationService::current()->Notify( - NotificationType::INITIAL_NEW_TAB_UI_LOAD, - NotificationService::AllSources(), - Details<int>(&load_time_ms)); - UMA_HISTOGRAM_TIMES("NewTabUI load", load_time); - } else { - // Not enough quiet time has elapsed. - // Some more paints must've occurred since we set the timeout. - // Wait some more. - timer_.Start(base::TimeDelta::FromMilliseconds(kTimeoutMs), this, - &NewTabUI::PaintTimeout); - } -} - -void NewTabUI::StartTimingPaint(RenderViewHost* render_view_host) { - start_ = base::TimeTicks::Now(); - last_paint_ = start_; - registrar_.Add(this, NotificationType::RENDER_WIDGET_HOST_DID_PAINT, - Source<RenderWidgetHost>(render_view_host)); - timer_.Start(base::TimeDelta::FromMilliseconds(kTimeoutMs), this, - &NewTabUI::PaintTimeout); - -} -void NewTabUI::RenderViewCreated(RenderViewHost* render_view_host) { - StartTimingPaint(render_view_host); -} - -void NewTabUI::RenderViewReused(RenderViewHost* render_view_host) { - StartTimingPaint(render_view_host); -} - -void NewTabUI::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - switch (type.value) { - case NotificationType::BROWSER_THEME_CHANGED: { - InitializeCSSCaches(); - ListValue args; - args.Append(Value::CreateStringValue( - GetProfile()->GetThemeProvider()->HasCustomImage( - IDR_THEME_NTP_ATTRIBUTION) ? - "true" : "false")); - CallJavascriptFunction(L"themeChanged", args); - break; - } - case NotificationType::BOOKMARK_BAR_VISIBILITY_PREF_CHANGED: { - if (GetProfile()->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar)) - CallJavascriptFunction(L"bookmarkBarAttached"); - else - CallJavascriptFunction(L"bookmarkBarDetached"); - break; - } - case NotificationType::RENDER_WIDGET_HOST_DID_PAINT: { - last_paint_ = base::TimeTicks::Now(); - break; - } - default: - CHECK(false) << "Unexpected notification: " << type.value; - } -} - -void NewTabUI::InitializeCSSCaches() { - Profile* profile = GetProfile(); - WebUIThemeSource* theme = new WebUIThemeSource(profile); - profile->GetChromeURLDataManager()->AddDataSource(theme); -} - -// static -void NewTabUI::RegisterUserPrefs(PrefService* prefs) { - prefs->RegisterIntegerPref(prefs::kNTPPrefVersion, 0); - - MostVisitedHandler::RegisterUserPrefs(prefs); - ShownSectionsHandler::RegisterUserPrefs(prefs); - if (NewTabUI::WebResourcesEnabled()) - TipsHandler::RegisterUserPrefs(prefs); - - UpdateUserPrefsVersion(prefs); -} - -// static -bool NewTabUI::UpdateUserPrefsVersion(PrefService* prefs) { - const int old_pref_version = prefs->GetInteger(prefs::kNTPPrefVersion); - if (old_pref_version != current_pref_version()) { - MigrateUserPrefs(prefs, old_pref_version, current_pref_version()); - prefs->SetInteger(prefs::kNTPPrefVersion, current_pref_version()); - return true; - } - return false; -} - -// static -void NewTabUI::MigrateUserPrefs(PrefService* prefs, int old_pref_version, - int new_pref_version) { - ShownSectionsHandler::MigrateUserPrefs(prefs, old_pref_version, - current_pref_version()); -} - -// static -bool NewTabUI::WebResourcesEnabled() { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - return !command_line->HasSwitch(switches::kDisableWebResources); -} - -// static -bool NewTabUI::FirstRunDisabled() { - const CommandLine* command_line = CommandLine::ForCurrentProcess(); - return command_line->HasSwitch(switches::kDisableNewTabFirstRun); -} - -// static -void NewTabUI::SetURLTitleAndDirection(DictionaryValue* dictionary, - const string16& title, - const GURL& gurl) { - dictionary->SetString("url", gurl.spec()); - - bool using_url_as_the_title = false; - string16 title_to_set(title); - if (title_to_set.empty()) { - using_url_as_the_title = true; - title_to_set = UTF8ToUTF16(gurl.spec()); - } - - // We set the "dir" attribute of the title, so that in RTL locales, a LTR - // title is rendered left-to-right and truncated from the right. For example, - // the title of http://msdn.microsoft.com/en-us/default.aspx is "MSDN: - // Microsoft developer network". In RTL locales, in the [New Tab] page, if - // the "dir" of this title is not specified, it takes Chrome UI's - // directionality. So the title will be truncated as "soft developer - // network". Setting the "dir" attribute as "ltr" renders the truncated title - // as "MSDN: Microsoft D...". As another example, the title of - // http://yahoo.com is "Yahoo!". In RTL locales, in the [New Tab] page, the - // title will be rendered as "!Yahoo" if its "dir" attribute is not set to - // "ltr". - // - // Since the title can contain BiDi text, we need to mark the text as either - // RTL or LTR, depending on the characters in the string. If we use the URL - // as the title, we mark the title as LTR since URLs are always treated as - // left to right strings. Simply setting the title's "dir" attribute works - // fine for rendering and truncating the title. However, it does not work for - // entire title within a tooltip when the mouse is over the title link.. For - // example, without LRE-PDF pair, the title "Yahoo!" will be rendered as - // "!Yahoo" within the tooltip when the mouse is over the title link. - std::string direction = kDefaultHtmlTextDirection; - if (base::i18n::IsRTL()) { - if (using_url_as_the_title) { - base::i18n::WrapStringWithLTRFormatting(&title_to_set); - } else { - if (base::i18n::StringContainsStrongRTLChars(title)) { - base::i18n::WrapStringWithRTLFormatting(&title_to_set); - direction = kRTLHtmlTextDirection; - } else { - base::i18n::WrapStringWithLTRFormatting(&title_to_set); - } - } - } - dictionary->SetString("title", title_to_set); - dictionary->SetString("direction", direction); -} - -namespace { - -bool IsTabUnique(const DictionaryValue* tab, - std::set<std::string>* unique_items) { - DCHECK(unique_items); - std::string title; - std::string url; - if (tab->GetString("title", &title) && - tab->GetString("url", &url)) { - // TODO(viettrungluu): this isn't obviously reliable, since different - // combinations of titles/urls may conceivably yield the same string. - std::string unique_key = title + url; - if (unique_items->find(unique_key) != unique_items->end()) - return false; - else - unique_items->insert(unique_key); - } - return true; -} - -} // namespace - -// static -void NewTabUI::AddRecentlyClosedEntries( - const TabRestoreService::Entries& entries, ListValue* entry_list_value) { - const int max_count = 10; - int added_count = 0; - std::set<std::string> unique_items; - // We filter the list of recently closed to only show 'interesting' entries, - // where an interesting entry is either a closed window or a closed tab - // whose selected navigation is not the new tab ui. - for (TabRestoreService::Entries::const_iterator it = entries.begin(); - it != entries.end() && added_count < max_count; ++it) { - TabRestoreService::Entry* entry = *it; - scoped_ptr<DictionaryValue> entry_dict(new DictionaryValue()); - if ((entry->type == TabRestoreService::TAB && - ValueHelper::TabToValue( - *static_cast<TabRestoreService::Tab*>(entry), - entry_dict.get()) && - IsTabUnique(entry_dict.get(), &unique_items)) || - (entry->type == TabRestoreService::WINDOW && - ValueHelper::WindowToValue( - *static_cast<TabRestoreService::Window*>(entry), - entry_dict.get()))) { - entry_dict->SetInteger("sessionId", entry->id); - entry_list_value->Append(entry_dict.release()); - added_count++; - } - } -} - -/////////////////////////////////////////////////////////////////////////////// -// NewTabHTMLSource - -bool NewTabUI::NewTabHTMLSource::first_run_ = true; - -NewTabUI::NewTabHTMLSource::NewTabHTMLSource(Profile* profile) - : DataSource(chrome::kChromeUINewTabHost, MessageLoop::current()), - profile_(profile) { -} - -void NewTabUI::NewTabHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - - if (AppLauncherHandler::HandlePing(profile_, path)) { - return; - } else if (!path.empty() && path[0] != '#') { - // A path under new-tab was requested; it's likely a bad relative - // URL from the new tab page, but in any case it's an error. - NOTREACHED(); - return; - } - - scoped_refptr<RefCountedBytes> html_bytes( - profile_->GetNTPResourceCache()->GetNewTabHTML(is_off_the_record)); - - SendResponse(request_id, html_bytes); -} - -std::string NewTabUI::NewTabHTMLSource::GetMimeType(const std::string&) const { - return "text/html"; -} diff --git a/chrome/browser/dom_ui/new_tab_ui.h b/chrome/browser/dom_ui/new_tab_ui.h deleted file mode 100644 index e513dc2..0000000 --- a/chrome/browser/dom_ui/new_tab_ui.h +++ /dev/null @@ -1,121 +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_NEW_TAB_UI_H_ -#define CHROME_BROWSER_DOM_UI_NEW_TAB_UI_H_ -#pragma once - -#include <string> - -#include "base/gtest_prod_util.h" -#include "base/timer.h" -#include "chrome/browser/sessions/tab_restore_service.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/notification_observer.h" -#include "chrome/common/notification_registrar.h" - -class GURL; -class MessageLoop; -class PrefService; -class Profile; - -// The TabContents used for the New Tab page. -class NewTabUI : public WebUI, - public NotificationObserver { - public: - explicit NewTabUI(TabContents* manager); - ~NewTabUI(); - - // Override WebUI methods so we can hook up the paint timer to the render - // view host. - virtual void RenderViewCreated(RenderViewHost* render_view_host); - virtual void RenderViewReused(RenderViewHost* render_view_host); - - static void RegisterUserPrefs(PrefService* prefs); - static void MigrateUserPrefs(PrefService* prefs, int old_pref_version, - int new_pref_version); - - // Whether we should disable the web resources backend service - static bool WebResourcesEnabled(); - - // Whether we should disable the first run notification based on the command - // line switch. - static bool FirstRunDisabled(); - - // Adds "url", "title", and "direction" keys on incoming dictionary, setting - // title as the url as a fallback on empty title. - static void SetURLTitleAndDirection(DictionaryValue* dictionary, - const string16& title, - const GURL& gurl); - - // Converts a list of TabRestoreService entries to the JSON format required - // by the NTP and adds them to the given list value. - static void AddRecentlyClosedEntries( - const TabRestoreService::Entries& entries, - ListValue* entry_list_value); - - // The current preference version. - static int current_pref_version() { return current_pref_version_; } - - class NewTabHTMLSource : public ChromeURLDataManager::DataSource { - public: - explicit NewTabHTMLSource(Profile* profile); - - // 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; - - // Setters and getters for first_run. - static void set_first_run(bool first_run) { first_run_ = first_run; } - static bool first_run() { return first_run_; } - - private: - virtual ~NewTabHTMLSource() {} - - // Whether this is the first run. - static bool first_run_; - - // Pointer back to the original profile. - Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(NewTabHTMLSource); - }; - - private: - FRIEND_TEST_ALL_PREFIXES(NewTabUITest, UpdateUserPrefsVersion); - - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - // Reset the CSS caches. - void InitializeCSSCaches(); - - void StartTimingPaint(RenderViewHost* render_view_host); - void PaintTimeout(); - - // Updates the user prefs version and calls |MigrateUserPrefs| if needed. - // Returns true if the version was updated. - static bool UpdateUserPrefsVersion(PrefService* prefs); - - NotificationRegistrar registrar_; - - // The time when we started benchmarking. - base::TimeTicks start_; - // The last time we got a paint notification. - base::TimeTicks last_paint_; - // Scoping so we can be sure our timeouts don't outlive us. - base::OneShotTimer<NewTabUI> timer_; - // The preference version. This used for migrating prefs of the NTP. - static const int current_pref_version_ = 3; - - DISALLOW_COPY_AND_ASSIGN(NewTabUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_NEW_TAB_UI_H_ diff --git a/chrome/browser/dom_ui/new_tab_ui_uitest.cc b/chrome/browser/dom_ui/new_tab_ui_uitest.cc deleted file mode 100644 index 62c33e2..0000000 --- a/chrome/browser/dom_ui/new_tab_ui_uitest.cc +++ /dev/null @@ -1,183 +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/test/ui/ui_test.h" - -#include "base/test/test_timeouts.h" -#include "chrome/app/chrome_command_ids.h" -#include "chrome/browser/dom_ui/new_tab_ui.h" -#include "chrome/browser/prefs/pref_value_store.h" -#include "chrome/browser/sync/signin_manager.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/json_pref_store.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/automation/browser_proxy.h" -#include "chrome/test/automation/tab_proxy.h" -#include "chrome/test/automation/window_proxy.h" -#include "chrome/test/testing_pref_service.h" - -class NewTabUITest : public UITest { - public: - NewTabUITest() { - dom_automation_enabled_ = true; - // Set home page to the empty string so that we can set the home page using - // preferences. - set_homepage(""); - - // Setup the DEFAULT_THEME profile (has fake history entries). - set_template_user_data(UITest::ComputeTypicalUserDataSource( - ProxyLauncher::DEFAULT_THEME)); - } -}; - -TEST_F(NewTabUITest, NTPHasThumbnails) { - // Switch to the "new tab" tab, which should be any new tab after the - // first (the first is about:blank). - scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(window.get()); - - // Bring up a new tab page. - ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); - - scoped_refptr<TabProxy> tab = window->GetActiveTab(); - ASSERT_TRUE(tab.get()); - - // TopSites should return at least 3 non-filler pages. - // 8 - 3 = max 5 filler pages. - ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", - L"window.domAutomationController.send(" - L"document.getElementsByClassName('filler').length <= 5)", - TestTimeouts::action_max_timeout_ms())); -} - -// Sometimes hangs: http://crbug.com/70157 -TEST_F(NewTabUITest, DISABLED_NTPHasLoginName) { - scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(window.get()); - - ASSERT_TRUE(window->SetStringPreference(prefs::kGoogleServicesUsername, - "user@gmail.com")); - // Bring up a new tab page. - ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); - - scoped_refptr<TabProxy> tab = window->GetActiveTab(); - ASSERT_TRUE(tab.get()); - - std::wstring displayed_username; - // The login span should be eventually populated and have the - // correct value. - ASSERT_TRUE(WaitUntilJavaScriptCondition(tab, L"", - L"window.domAutomationController.send(" - L"document.getElementById('login-username').innerText.length > 0)", - TestTimeouts::action_max_timeout_ms())); - - ASSERT_TRUE(tab->ExecuteAndExtractString( - L"", - L"window.domAutomationController.send(" - L"document.getElementById('login-username').innerText)", - &displayed_username)); - - EXPECT_EQ(L"user@gmail.com", displayed_username); -} - -// Loads about:hang into two NTP tabs, ensuring we don't crash. -// See http://crbug.com/59859. -TEST_F(NewTabUITest, AboutHangInNTP) { - scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(window.get()); - - // Bring up a new tab page. - ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); - scoped_refptr<TabProxy> tab = window->GetActiveTab(); - ASSERT_TRUE(tab.get()); - - // Navigate to about:hang to stall the process. - ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); - - // Visit about:hang again in another NTP. Don't bother waiting for the - // NTP to load, because it's hung. - ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); - scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); - ASSERT_TRUE(tab2.get()); - ASSERT_TRUE(tab2->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); -} - -// Allows testing NTP in process-per-tab mode. -class NewTabUIProcessPerTabTest : public NewTabUITest { - public: - NewTabUIProcessPerTabTest() : NewTabUITest() {} - - protected: - virtual void SetUp() { - launch_arguments_.AppendSwitch(switches::kProcessPerTab); - UITest::SetUp(); - } -}; - -// Navigates away from NTP before it commits, in process-per-tab mode. -// Ensures that we don't load the normal page in the NTP process (and thus -// crash), as in http://crbug.com/69224. -TEST_F(NewTabUIProcessPerTabTest, NavBeforeNTPCommits) { - scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(window.get()); - - // Bring up a new tab page. - ASSERT_TRUE(window->RunCommand(IDC_NEW_TAB)); - scoped_refptr<TabProxy> tab = window->GetActiveTab(); - ASSERT_TRUE(tab.get()); - - // Navigate to about:hang to stall the process. - ASSERT_TRUE(tab->NavigateToURLAsync(GURL(chrome::kAboutHangURL))); - - // Visit a normal URL in another NTP that hasn't committed. - ASSERT_TRUE(window->RunCommandAsync(IDC_NEW_TAB)); - scoped_refptr<TabProxy> tab2 = window->GetActiveTab(); - ASSERT_TRUE(tab2.get()); - ASSERT_TRUE(tab2->NavigateToURL(GURL("data:text/html,hello world"))); -} - -// Fails about ~5% of the time on all platforms. http://crbug.com/45001 -TEST_F(NewTabUITest, FLAKY_ChromeInternalLoadsNTP) { - scoped_refptr<BrowserProxy> window(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(window.get()); - - // Go to the "new tab page" using its old url, rather than chrome://newtab. - scoped_refptr<TabProxy> tab = window->GetTab(0); - ASSERT_TRUE(tab.get()); - ASSERT_TRUE(tab->NavigateToURLAsync(GURL("chrome-internal:"))); - int load_time; - ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); - - // Ensure there are some thumbnails loaded in the page. - int thumbnails_count = -1; - ASSERT_TRUE(tab->ExecuteAndExtractInt(L"", - L"window.domAutomationController.send(" - L"document.getElementsByClassName('thumbnail-container').length)", - &thumbnails_count)); - EXPECT_GT(thumbnails_count, 0); -} - -TEST_F(NewTabUITest, UpdateUserPrefsVersion) { - // PrefService with JSON user-pref file only, no enforced or advised prefs. - scoped_ptr<PrefService> prefs(new TestingPrefService); - - // Does the migration - NewTabUI::RegisterUserPrefs(prefs.get()); - - ASSERT_EQ(NewTabUI::current_pref_version(), - prefs->GetInteger(prefs::kNTPPrefVersion)); - - // Reset the version - prefs->ClearPref(prefs::kNTPPrefVersion); - ASSERT_EQ(0, prefs->GetInteger(prefs::kNTPPrefVersion)); - - bool migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); - ASSERT_TRUE(migrated); - ASSERT_EQ(NewTabUI::current_pref_version(), - prefs->GetInteger(prefs::kNTPPrefVersion)); - - migrated = NewTabUI::UpdateUserPrefsVersion(prefs.get()); - ASSERT_FALSE(migrated); -} diff --git a/chrome/browser/dom_ui/ntp_login_handler.cc b/chrome/browser/dom_ui/ntp_login_handler.cc deleted file mode 100644 index 468343d..0000000 --- a/chrome/browser/dom_ui/ntp_login_handler.cc +++ /dev/null @@ -1,55 +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/ntp_login_handler.h" - -#include <string> - -#include "base/values.h" -#include "chrome/browser/prefs/pref_notifier.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/sync/sync_setup_flow.h" -#include "chrome/browser/webui/web_ui_util.h" -#include "chrome/common/notification_details.h" -#include "chrome/common/pref_names.h" - -NTPLoginHandler::NTPLoginHandler() { -} - -NTPLoginHandler::~NTPLoginHandler() { -} - -WebUIMessageHandler* NTPLoginHandler::Attach(WebUI* web_ui) { - PrefService* pref_service = web_ui->GetProfile()->GetPrefs(); - username_pref_.Init(prefs::kGoogleServicesUsername, pref_service, this); - - return WebUIMessageHandler::Attach(web_ui); -} - -void NTPLoginHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("initializeLogin", - NewCallback(this, &NTPLoginHandler::HandleInitializeLogin)); -} - -void NTPLoginHandler::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - DCHECK(type == NotificationType::PREF_CHANGED); - std::string* name = Details<std::string>(details).ptr(); - if (prefs::kGoogleServicesUsername == *name) - UpdateLogin(); -} - -void NTPLoginHandler::HandleInitializeLogin(const ListValue* args) { - UpdateLogin(); -} - -void NTPLoginHandler::UpdateLogin() { - std::string username = web_ui_->GetProfile()->GetPrefs()->GetString( - prefs::kGoogleServicesUsername); - StringValue string_value(username); - web_ui_->CallJavascriptFunction(L"updateLogin", string_value); -} diff --git a/chrome/browser/dom_ui/ntp_login_handler.h b/chrome/browser/dom_ui/ntp_login_handler.h deleted file mode 100644 index 2213e2e..0000000 --- a/chrome/browser/dom_ui/ntp_login_handler.h +++ /dev/null @@ -1,42 +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_NTP_LOGIN_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_NTP_LOGIN_HANDLER_H_ -#pragma once - -#include "chrome/browser/prefs/pref_member.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/notification_observer.h" - -// The NTP login handler currently simply displays the current logged in -// username at the top of the NTP (and update itself when that changes). -// In the future it may expand to allow users to login from the NTP. -class NTPLoginHandler : public WebUIMessageHandler, - public NotificationObserver { - public: - NTPLoginHandler(); - ~NTPLoginHandler(); - - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - - // WebUIMessageHandler interface - virtual void RegisterMessages(); - - // NotificationObserver interface - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - private: - // Called from JS when the NTP is loaded. - void HandleInitializeLogin(const ListValue* args); - - // Internal helper method - void UpdateLogin(); - - StringPrefMember username_pref_; -}; - -#endif // CHROME_BROWSER_DOM_UI_NTP_LOGIN_HANDLER_H_ diff --git a/chrome/browser/dom_ui/ntp_resource_cache.cc b/chrome/browser/dom_ui/ntp_resource_cache.cc deleted file mode 100644 index 6803f0a..0000000 --- a/chrome/browser/dom_ui/ntp_resource_cache.cc +++ /dev/null @@ -1,559 +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/ntp_resource_cache.h" - -#include <algorithm> -#include <vector> - -#include "base/command_line.h" -#include "base/file_util.h" -#include "base/ref_counted_memory.h" -#include "base/string16.h" -#include "base/string_number_conversions.h" -#include "base/time.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/shown_sections_handler.h" -#include "chrome/browser/google/google_util.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/themes/browser_theme_provider.h" -#include "chrome/browser/web_resource/promo_resource_service.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/common/extensions/extension_constants.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/notification_service.h" -#include "chrome/common/notification_type.h" -#include "chrome/common/pref_names.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 "grit/theme_resources.h" -#include "ui/base/animation/animation.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/theme_provider.h" -#include "ui/gfx/color_utils.h" - -#if defined(OS_WIN) || defined(TOOLKIT_VIEWS) -#include "chrome/browser/ui/views/bookmark_bar_view.h" -#elif defined(OS_MACOSX) -#include "chrome/browser/ui/cocoa/bookmarks/bookmark_bar_constants.h" -#elif defined(OS_POSIX) -#include "chrome/browser/ui/gtk/bookmark_bar_gtk.h" -#endif - -using base::Time; - -namespace { - -// The URL for the the Learn More page shown on incognito new tab. -const char kLearnMoreIncognitoUrl[] = -#if defined(OS_CHROMEOS) - "http://www.google.com/support/chromeos/bin/answer.py?answer=95464"; -#else - "http://www.google.com/support/chrome/bin/answer.py?answer=95464"; -#endif - -// The URL for the Learn More page shown on guest session new tab. -const char kLearnMoreGuestSessionUrl[] = - "http://www.google.com/support/chromeos/bin/answer.py?answer=1057090"; - -// The URL for bookmark sync service help. -const char kSyncServiceHelpUrl[] = - "http://www.google.com/support/chrome/bin/answer.py?answer=165139"; - -// The URL to be loaded to display Help. -const char kHelpContentUrl[] = - "http://www.google.com/support/chrome/"; - -string16 GetUrlWithLang(const GURL& url) { - return ASCIIToUTF16(google_util::AppendGoogleLocaleParam(url).spec()); -} - -std::string SkColorToRGBAString(SkColor color) { - // We convert the alpha using DoubleToString because StringPrintf will use - // locale specific formatters (e.g., use , instead of . in German). - return StringPrintf("rgba(%d,%d,%d,%s)", SkColorGetR(color), - SkColorGetG(color), SkColorGetB(color), - base::DoubleToString(SkColorGetA(color) / 255.0).c_str()); -} - -// Get the CSS string for the background position on the new tab page for the -// states when the bar is attached or detached. -std::string GetNewTabBackgroundCSS(const ui::ThemeProvider* theme_provider, - bool bar_attached) { - int alignment; - theme_provider->GetDisplayProperty( - BrowserThemeProvider::NTP_BACKGROUND_ALIGNMENT, &alignment); - - // TODO(glen): This is a quick workaround to hide the notused.png image when - // no image is provided - we don't have time right now to figure out why - // this is painting as white. - // http://crbug.com/17593 - if (!theme_provider->HasCustomImage(IDR_THEME_NTP_BACKGROUND)) { - return "-64px"; - } - - if (bar_attached) - return BrowserThemeProvider::AlignmentToString(alignment); - - // The bar is detached, so we must offset the background by the bar size - // if it's a top-aligned bar. -#if defined(OS_WIN) || defined(TOOLKIT_VIEWS) - int offset = BookmarkBarView::kNewtabBarHeight; -#elif defined(OS_MACOSX) - int offset = bookmarks::kNTPBookmarkBarHeight; -#elif defined(OS_POSIX) - int offset = BookmarkBarGtk::kBookmarkBarNTPHeight; -#else - int offset = 0; -#endif - - if (alignment & BrowserThemeProvider::ALIGN_TOP) { - if (alignment & BrowserThemeProvider::ALIGN_LEFT) - return "0% " + base::IntToString(-offset) + "px"; - else if (alignment & BrowserThemeProvider::ALIGN_RIGHT) - return "100% " + base::IntToString(-offset) + "px"; - return "center " + base::IntToString(-offset) + "px"; - } - return BrowserThemeProvider::AlignmentToString(alignment); -} - -// How the background image on the new tab page should be tiled (see tiling -// masks in browser_theme_provider.h). -std::string GetNewTabBackgroundTilingCSS( - const ui::ThemeProvider* theme_provider) { - int repeat_mode; - theme_provider->GetDisplayProperty( - BrowserThemeProvider::NTP_BACKGROUND_TILING, &repeat_mode); - return BrowserThemeProvider::TilingToString(repeat_mode); -} - -// Is the current time within a given date range? -bool InDateRange(double begin, double end) { - Time start_time = Time::FromDoubleT(begin); - Time end_time = Time::FromDoubleT(end); - return start_time < Time::Now() && end_time > Time::Now(); -} - -} // namespace - -NTPResourceCache::NTPResourceCache(Profile* profile) : profile_(profile) { - registrar_.Add(this, NotificationType::BROWSER_THEME_CHANGED, - NotificationService::AllSources()); - registrar_.Add(this, NotificationType::PROMO_RESOURCE_STATE_CHANGED, - NotificationService::AllSources()); - - // Watch for pref changes that cause us to need to invalidate the HTML cache. - pref_change_registrar_.Init(profile_->GetPrefs()); - pref_change_registrar_.Add(prefs::kShowBookmarkBar, this); - pref_change_registrar_.Add(prefs::kNTPShownSections, this); -} - -NTPResourceCache::~NTPResourceCache() {} - -RefCountedBytes* NTPResourceCache::GetNewTabHTML(bool is_off_the_record) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - if (is_off_the_record) { - if (!new_tab_incognito_html_.get()) - CreateNewTabIncognitoHTML(); - } else { - if (!new_tab_html_.get()) - CreateNewTabHTML(); - } - return is_off_the_record ? new_tab_incognito_html_.get() - : new_tab_html_.get(); -} - -RefCountedBytes* NTPResourceCache::GetNewTabCSS(bool is_off_the_record) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - if (is_off_the_record) { - if (!new_tab_incognito_css_.get()) - CreateNewTabIncognitoCSS(); - } else { - if (!new_tab_css_.get()) - CreateNewTabCSS(); - } - return is_off_the_record ? new_tab_incognito_css_.get() - : new_tab_css_.get(); -} - -void NTPResourceCache::Observe(NotificationType type, - const NotificationSource& source, const NotificationDetails& details) { - // Invalidate the cache. - if (NotificationType::BROWSER_THEME_CHANGED == type || - NotificationType::PROMO_RESOURCE_STATE_CHANGED == type) { - new_tab_incognito_html_ = NULL; - new_tab_html_ = NULL; - new_tab_incognito_css_ = NULL; - new_tab_css_ = NULL; - } else if (NotificationType::PREF_CHANGED == type) { - std::string* pref_name = Details<std::string>(details).ptr(); - if (*pref_name == prefs::kShowBookmarkBar || - *pref_name == prefs::kHomePageIsNewTabPage || - *pref_name == prefs::kNTPShownSections) { - new_tab_incognito_html_ = NULL; - new_tab_html_ = NULL; - } else { - NOTREACHED(); - } - } else { - NOTREACHED(); - } -} - -void NTPResourceCache::CreateNewTabIncognitoHTML() { - DictionaryValue localized_strings; - localized_strings.SetString("title", - l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE)); - int new_tab_message_ids = IDS_NEW_TAB_OTR_MESSAGE; - int new_tab_html_idr = IDR_INCOGNITO_TAB_HTML; - const char* new_tab_link = kLearnMoreIncognitoUrl; - // TODO(altimofeev): consider implementation without 'if def' usage. -#if defined(OS_CHROMEOS) - if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession)) { - new_tab_message_ids = IDS_NEW_TAB_GUEST_SESSION_MESSAGE; - new_tab_html_idr = IDR_GUEST_SESSION_TAB_HTML; - new_tab_link = kLearnMoreGuestSessionUrl; - } -#endif - localized_strings.SetString("content", - l10n_util::GetStringFUTF16(new_tab_message_ids, - GetUrlWithLang(GURL(new_tab_link)))); - localized_strings.SetString("extensionsmessage", - l10n_util::GetStringFUTF16(IDS_NEW_TAB_OTR_EXTENSIONS_MESSAGE, - l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), - ASCIIToUTF16(chrome::kChromeUIExtensionsURL))); - bool bookmark_bar_attached = profile_->GetPrefs()->GetBoolean( - prefs::kShowBookmarkBar); - localized_strings.SetString("bookmarkbarattached", - bookmark_bar_attached ? "true" : "false"); - - ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); - - static const base::StringPiece incognito_tab_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - new_tab_html_idr)); - - std::string full_html = jstemplate_builder::GetI18nTemplateHtml( - incognito_tab_html, &localized_strings); - - new_tab_incognito_html_ = new RefCountedBytes; - new_tab_incognito_html_->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), - new_tab_incognito_html_->data.begin()); -} - -void NTPResourceCache::CreateNewTabHTML() { - // Show the profile name in the title and most visited labels if the current - // profile is not the default. - string16 apps = l10n_util::GetStringUTF16(IDS_NEW_TAB_APPS); - string16 title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE); - string16 most_visited = l10n_util::GetStringUTF16(IDS_NEW_TAB_MOST_VISITED); - DictionaryValue localized_strings; - localized_strings.SetString("bookmarkbarattached", - profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar) ? - "true" : "false"); - localized_strings.SetString("hasattribution", - profile_->GetThemeProvider()->HasCustomImage(IDR_THEME_NTP_ATTRIBUTION) ? - "true" : "false"); - localized_strings.SetString("apps", apps); - localized_strings.SetString("title", title); - localized_strings.SetString("mostvisited", most_visited); - localized_strings.SetString("restorethumbnails", - l10n_util::GetStringUTF16(IDS_NEW_TAB_RESTORE_THUMBNAILS_LINK)); - localized_strings.SetString("recentlyclosed", - l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED)); - localized_strings.SetString("closedwindowsingle", - l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_SINGLE)); - localized_strings.SetString("foreignsessions", - l10n_util::GetStringUTF16(IDS_SYNC_DATATYPE_SESSIONS)); - localized_strings.SetString("closedwindowmultiple", - l10n_util::GetStringUTF16(IDS_NEW_TAB_RECENTLY_CLOSED_WINDOW_MULTIPLE)); - localized_strings.SetString("attributionintro", - l10n_util::GetStringUTF16(IDS_NEW_TAB_ATTRIBUTION_INTRO)); - localized_strings.SetString("thumbnailremovednotification", - l10n_util::GetStringUTF16(IDS_NEW_TAB_THUMBNAIL_REMOVED_NOTIFICATION)); - localized_strings.SetString("undothumbnailremove", - l10n_util::GetStringUTF16(IDS_NEW_TAB_UNDO_THUMBNAIL_REMOVE)); - localized_strings.SetString("removethumbnailtooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_REMOVE_THUMBNAIL_TOOLTIP)); - localized_strings.SetString("pinthumbnailtooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_PIN_THUMBNAIL_TOOLTIP)); - localized_strings.SetString("unpinthumbnailtooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_UNPIN_THUMBNAIL_TOOLTIP)); - localized_strings.SetString("showhidethumbnailtooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_SHOW_HIDE_THUMBNAIL_TOOLTIP)); - localized_strings.SetString("showhidelisttooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_SHOW_HIDE_LIST_TOOLTIP)); - localized_strings.SetString("pagedisplaytooltip", - l10n_util::GetStringUTF16(IDS_NEW_TAB_PAGE_DISPLAY_TOOLTIP)); - localized_strings.SetString("firstrunnotification", - l10n_util::GetStringUTF16(IDS_NEW_TAB_FIRST_RUN_NOTIFICATION)); - localized_strings.SetString("closefirstrunnotification", - l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_FIRST_RUN_NOTIFICATION)); - localized_strings.SetString("close", l10n_util::GetStringUTF16(IDS_CLOSE)); - localized_strings.SetString("history", - l10n_util::GetStringUTF16(IDS_NEW_TAB_HISTORY)); - localized_strings.SetString("downloads", - l10n_util::GetStringUTF16(IDS_NEW_TAB_DOWNLOADS)); - localized_strings.SetString("help", - l10n_util::GetStringUTF16(IDS_NEW_TAB_HELP)); - localized_strings.SetString("helpurl", - GetUrlWithLang(GURL(kHelpContentUrl))); - localized_strings.SetString("appsettings", - l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_SETTINGS)); - localized_strings.SetString("appuninstall", - l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_UNINSTALL)); - localized_strings.SetString("appoptions", - l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_OPTIONS)); - localized_strings.SetString("appcreateshortcut", - l10n_util::GetStringUTF16(IDS_NEW_TAB_APP_CREATE_SHORTCUT)); - localized_strings.SetString("applaunchtypepinned", - l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_PINNED)); - localized_strings.SetString("applaunchtyperegular", - l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_REGULAR)); - localized_strings.SetString("applaunchtypewindow", - l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_WINDOW)); - localized_strings.SetString("applaunchtypefullscreen", - l10n_util::GetStringUTF16(IDS_APP_CONTEXT_MENU_OPEN_FULLSCREEN)); - localized_strings.SetString("web_store_title", - l10n_util::GetStringUTF16(IDS_EXTENSION_WEB_STORE_TITLE)); - localized_strings.SetString("web_store_url", - GetUrlWithLang(GURL(Extension::ChromeStoreLaunchURL()))); - localized_strings.SetString("appspromohide", - l10n_util::GetStringUTF16(IDS_APPS_PROMO_HIDE)); - localized_strings.SetString("appspromoheader", - l10n_util::GetStringUTF16(IDS_APPS_PROMO_HEADER)); - localized_strings.SetString("appspromotext1", - l10n_util::GetStringUTF16(IDS_APPS_PROMO_TEXT_1)); - localized_strings.SetString("appspromotext2", - l10n_util::GetStringUTF16(IDS_APPS_PROMO_TEXT_2)); - localized_strings.SetString("syncpromotext", - l10n_util::GetStringUTF16(IDS_SYNC_START_SYNC_BUTTON_LABEL)); -#if defined(OS_CHROMEOS) - localized_strings.SetString("expandMenu", - l10n_util::GetStringUTF16(IDS_NEW_TAB_CLOSE_MENU_EXPAND)); -#endif - - // Don't initiate the sync related message passing with the page if the sync - // code is not present. - if (profile_->GetProfileSyncService()) - localized_strings.SetString("syncispresent", "true"); - else - localized_strings.SetString("syncispresent", "false"); - - ChromeURLDataManager::DataSource::SetFontAndTextDirection(&localized_strings); - - // Control fade and resize animations. - std::string anim = - ui::Animation::ShouldRenderRichAnimation() ? "true" : "false"; - localized_strings.SetString("anim", anim); - - // Pass the shown_sections pref early so that we can prevent flicker. - const int shown_sections = ShownSectionsHandler::GetShownSections( - profile_->GetPrefs()); - localized_strings.SetInteger("shown_sections", shown_sections); - - // If the user has preferences for a start and end time for a custom logo, - // and the time now is between these two times, show the custom logo. - if (profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoStart) && - profile_->GetPrefs()->FindPreference(prefs::kNTPCustomLogoEnd)) { - localized_strings.SetString("customlogo", - InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoStart), - profile_->GetPrefs()->GetDouble(prefs::kNTPCustomLogoEnd)) ? - "true" : "false"); - } else { - localized_strings.SetString("customlogo", "false"); - } - - // If the user has preferences for a start and end time for a promo from - // the server, and this promo string exists, set the localized string. - if (profile_->GetPrefs()->FindPreference(prefs::kNTPPromoStart) && - profile_->GetPrefs()->FindPreference(prefs::kNTPPromoEnd) && - profile_->GetPrefs()->FindPreference(prefs::kNTPPromoLine) && - PromoResourceServiceUtil::CanShowPromo(profile_)) { - localized_strings.SetString("serverpromo", - InDateRange(profile_->GetPrefs()->GetDouble(prefs::kNTPPromoStart), - profile_->GetPrefs()->GetDouble(prefs::kNTPPromoEnd)) ? - profile_->GetPrefs()->GetString(prefs::kNTPPromoLine) : - std::string()); - } - - base::StringPiece new_tab_html(ResourceBundle::GetSharedInstance(). - GetRawDataResource(IDR_NEW_NEW_TAB_HTML)); - - // Inject the template data into the HTML so that it is available before any - // layout is needed. - std::string json_html; - jstemplate_builder::AppendJsonHtml(&localized_strings, &json_html); - - static const base::StringPiece template_data_placeholder( - "<!-- template data placeholder -->"); - size_t pos = new_tab_html.find(template_data_placeholder); - - std::string full_html; - if (pos != base::StringPiece::npos) { - full_html.assign(new_tab_html.data(), pos); - full_html.append(json_html); - size_t after_offset = pos + template_data_placeholder.size(); - full_html.append(new_tab_html.data() + after_offset, - new_tab_html.size() - after_offset); - } else { - NOTREACHED(); - full_html.assign(new_tab_html.data(), new_tab_html.size()); - } - - new_tab_html_ = new RefCountedBytes; - new_tab_html_->data.resize(full_html.size()); - std::copy(full_html.begin(), full_html.end(), new_tab_html_->data.begin()); -} - -void NTPResourceCache::CreateNewTabIncognitoCSS() { - ui::ThemeProvider* tp = profile_->GetThemeProvider(); - DCHECK(tp); - - // Get our theme colors - SkColor color_background = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND); - - // Generate the replacements. - std::vector<std::string> subst; - - // Cache-buster for background. - subst.push_back( - profile_->GetPrefs()->GetString(prefs::kCurrentThemeID)); // $1 - - // Colors. - subst.push_back(SkColorToRGBAString(color_background)); // $2 - subst.push_back(GetNewTabBackgroundCSS(tp, false)); // $3 - subst.push_back(GetNewTabBackgroundCSS(tp, true)); // $4 - subst.push_back(GetNewTabBackgroundTilingCSS(tp)); // $5 - - // Get our template. - static const base::StringPiece new_tab_theme_css( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_NEW_INCOGNITO_TAB_THEME_CSS)); - - // Create the string from our template and the replacements. - std::string full_css = ReplaceStringPlaceholders( - new_tab_theme_css, subst, NULL); - - new_tab_incognito_css_ = new RefCountedBytes; - new_tab_incognito_css_->data.resize(full_css.size()); - std::copy(full_css.begin(), full_css.end(), - new_tab_incognito_css_->data.begin()); -} - -void NTPResourceCache::CreateNewTabCSS() { - ui::ThemeProvider* tp = profile_->GetThemeProvider(); - DCHECK(tp); - - // Get our theme colors - SkColor color_background = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_BACKGROUND); - SkColor color_text = tp->GetColor(BrowserThemeProvider::COLOR_NTP_TEXT); - SkColor color_link = tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK); - SkColor color_link_underline = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_LINK_UNDERLINE); - - SkColor color_section = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION); - SkColor color_section_text = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_TEXT); - SkColor color_section_link = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK); - SkColor color_section_link_underline = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_LINK_UNDERLINE); - SkColor color_section_header_text = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_HEADER_TEXT); - SkColor color_section_header_text_hover = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_HEADER_TEXT_HOVER); - SkColor color_section_header_rule = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_HEADER_RULE); - SkColor color_section_header_rule_light = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_SECTION_HEADER_RULE_LIGHT); - SkColor color_text_light = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_TEXT_LIGHT); - - SkColor color_header = - tp->GetColor(BrowserThemeProvider::COLOR_NTP_HEADER); - // Generate a lighter color for the header gradients. - color_utils::HSL header_lighter; - color_utils::SkColorToHSL(color_header, &header_lighter); - header_lighter.l += (1 - header_lighter.l) * 0.33; - SkColor color_header_gradient_light = - color_utils::HSLToSkColor(header_lighter, SkColorGetA(color_header)); - - // Generate section border color from the header color. See - // BookmarkBarView::Paint for how we do this for the bookmark bar - // borders. - SkColor color_section_border = - SkColorSetARGB(80, - SkColorGetR(color_header), - SkColorGetG(color_header), - SkColorGetB(color_header)); - - // Generate the replacements. - std::vector<std::string> subst; - // A second list of replacements, each of which must be in $$x format, - // where x is a digit from 1-9. - std::vector<std::string> subst2; - std::vector<std::string> subst3; - - // Cache-buster for background. - subst.push_back( - profile_->GetPrefs()->GetString(prefs::kCurrentThemeID)); // $1 - - // Colors. - subst.push_back(SkColorToRGBAString(color_background)); // $2 - subst.push_back(GetNewTabBackgroundCSS(tp, false)); // $3 - subst.push_back(GetNewTabBackgroundCSS(tp, true)); // $4 - subst.push_back(GetNewTabBackgroundTilingCSS(tp)); // $5 - subst.push_back(SkColorToRGBAString(color_header)); // $6 - subst.push_back(SkColorToRGBAString(color_header_gradient_light)); // $7 - subst.push_back(SkColorToRGBAString(color_text)); // $8 - subst.push_back(SkColorToRGBAString(color_link)); // $9 - - subst2.push_back(SkColorToRGBAString(color_section)); // $$1 - subst2.push_back(SkColorToRGBAString(color_section_border)); // $$2 - subst2.push_back(SkColorToRGBAString(color_section_text)); // $$3 - subst2.push_back(SkColorToRGBAString(color_section_link)); // $$4 - subst2.push_back(SkColorToRGBAString(color_link_underline)); // $$5 - subst2.push_back(SkColorToRGBAString(color_section_link_underline)); // $$6 - subst2.push_back(SkColorToRGBAString(color_section_header_text)); // $$7 - subst2.push_back(SkColorToRGBAString( - color_section_header_text_hover)); // $$8 - subst2.push_back(SkColorToRGBAString(color_section_header_rule)); // $$9 - - subst3.push_back(SkColorToRGBAString( - color_section_header_rule_light)); // $$$1 - subst3.push_back(SkColorToRGBAString( - SkColorSetA(color_section_header_rule, 0))); // $$$2 - subst3.push_back(SkColorToRGBAString(color_text_light)); // $$$3 - - - // Get our template. - static const base::StringPiece new_tab_theme_css( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_NEW_TAB_THEME_CSS)); - - // Create the string from our template and the replacements. - std::string css_string; - css_string = ReplaceStringPlaceholders(new_tab_theme_css, subst, NULL); - css_string = ReplaceStringPlaceholders(css_string, subst2, NULL); - css_string = ReplaceStringPlaceholders(css_string, subst3, NULL); - - new_tab_css_ = new RefCountedBytes; - new_tab_css_->data.resize(css_string.size()); - std::copy(css_string.begin(), css_string.end(), - new_tab_css_->data.begin()); -} diff --git a/chrome/browser/dom_ui/ntp_resource_cache.h b/chrome/browser/dom_ui/ntp_resource_cache.h deleted file mode 100644 index b4d10b6..0000000 --- a/chrome/browser/dom_ui/ntp_resource_cache.h +++ /dev/null @@ -1,52 +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_NTP_RESOURCE_CACHE_H_ -#define CHROME_BROWSER_DOM_UI_NTP_RESOURCE_CACHE_H_ -#pragma once - -#include "base/basictypes.h" -#include "base/ref_counted.h" -#include "chrome/common/notification_observer.h" -#include "chrome/common/notification_registrar.h" -#include "chrome/browser/prefs/pref_change_registrar.h" - -class Profile; -class RefCountedBytes; - -// This class keeps a cache of NTP resources (HTML and CSS) so we don't have to -// regenerate them all the time. -class NTPResourceCache : public NotificationObserver { - public: - explicit NTPResourceCache(Profile* profile); - virtual ~NTPResourceCache(); - - RefCountedBytes* GetNewTabHTML(bool is_off_the_record); - RefCountedBytes* GetNewTabCSS(bool is_off_the_record); - - // NotificationObserver interface. - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - private: - Profile* profile_; - - void CreateNewTabIncognitoHTML(); - scoped_refptr<RefCountedBytes> new_tab_incognito_html_; - void CreateNewTabHTML(); - scoped_refptr<RefCountedBytes> new_tab_html_; - - void CreateNewTabIncognitoCSS(); - scoped_refptr<RefCountedBytes> new_tab_incognito_css_; - void CreateNewTabCSS(); - scoped_refptr<RefCountedBytes> new_tab_css_; - - NotificationRegistrar registrar_; - PrefChangeRegistrar pref_change_registrar_; - - DISALLOW_COPY_AND_ASSIGN(NTPResourceCache); -}; - -#endif // CHROME_BROWSER_DOM_UI_NTP_RESOURCE_CACHE_H_ diff --git a/chrome/browser/dom_ui/print_preview_handler.cc b/chrome/browser/dom_ui/print_preview_handler.cc deleted file mode 100644 index 45d4eac..0000000 --- a/chrome/browser/dom_ui/print_preview_handler.cc +++ /dev/null @@ -1,40 +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/print_preview_handler.h" - -#include "base/values.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "printing/backend/print_backend.h" - -PrintPreviewHandler::PrintPreviewHandler() - : print_backend_(printing::PrintBackend::CreateInstance(NULL)) { -} - -PrintPreviewHandler::~PrintPreviewHandler() { -} - -void PrintPreviewHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getPrinters", - NewCallback(this, &PrintPreviewHandler::HandleGetPrinters)); - web_ui_->RegisterMessageCallback("print", - NewCallback(this, &PrintPreviewHandler::HandlePrint)); -} - -void PrintPreviewHandler::HandleGetPrinters(const ListValue*) { - ListValue printers; - - printing::PrinterList printer_list; - print_backend_->EnumeratePrinters(&printer_list); - for (printing::PrinterList::iterator index = printer_list.begin(); - index != printer_list.end(); ++index) { - printers.Append(new StringValue(index->printer_name)); - } - - web_ui_->CallJavascriptFunction(L"setPrinters", printers); -} - -void PrintPreviewHandler::HandlePrint(const ListValue*) { - web_ui_->GetRenderViewHost()->PrintForPrintPreview(); -} diff --git a/chrome/browser/dom_ui/print_preview_handler.h b/chrome/browser/dom_ui/print_preview_handler.h deleted file mode 100644 index ad2751d..0000000 --- a/chrome/browser/dom_ui/print_preview_handler.h +++ /dev/null @@ -1,40 +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_PRINT_PREVIEW_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_HANDLER_H_ -#pragma once - -#include "base/ref_counted.h" -#include "base/weak_ptr.h" -#include "chrome/browser/webui/web_ui.h" - -namespace printing { -class PrintBackend; -} - -// The handler for Javascript messages related to the "print preview" dialog. -class PrintPreviewHandler : public WebUIMessageHandler, - public base::SupportsWeakPtr<PrintPreviewHandler> { - public: - PrintPreviewHandler(); - virtual ~PrintPreviewHandler(); - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - private: - // Get the list of printers and send it to the Web UI. |args| is unused. - void HandleGetPrinters(const ListValue* args); - - // Print the preview PDF. |args| is unused. - void HandlePrint(const ListValue* args); - - // Pointer to current print system. - scoped_refptr<printing::PrintBackend> print_backend_; - - DISALLOW_COPY_AND_ASSIGN(PrintPreviewHandler); -}; - -#endif // CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_HANDLER_H_ diff --git a/chrome/browser/dom_ui/print_preview_ui.cc b/chrome/browser/dom_ui/print_preview_ui.cc deleted file mode 100644 index 92fdc41..0000000 --- a/chrome/browser/dom_ui/print_preview_ui.cc +++ /dev/null @@ -1,36 +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/print_preview_ui.h" - -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/print_preview_handler.h" -#include "chrome/browser/dom_ui/print_preview_ui_html_source.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" - -PrintPreviewUI::PrintPreviewUI(TabContents* contents) - : WebUI(contents), - html_source_(new PrintPreviewUIHTMLSource()) { - // PrintPreviewUI owns |handler|. - PrintPreviewHandler* handler = new PrintPreviewHandler(); - AddMessageHandler(handler->Attach(this)); - - // Set up the chrome://print/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source_); -} - -PrintPreviewUI::~PrintPreviewUI() { -} - -PrintPreviewUIHTMLSource* PrintPreviewUI::html_source() { - return html_source_.get(); -} - -void PrintPreviewUI::PreviewDataIsAvailable(int expected_pages_count) { - StringValue dummy_url("chrome://print/print.pdf"); - FundamentalValue pages_count(expected_pages_count); - CallJavascriptFunction(L"createPDFPlugin", dummy_url, pages_count); -} diff --git a/chrome/browser/dom_ui/print_preview_ui.h b/chrome/browser/dom_ui/print_preview_ui.h deleted file mode 100644 index 77d0add..0000000 --- a/chrome/browser/dom_ui/print_preview_ui.h +++ /dev/null @@ -1,31 +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_PRINT_PREVIEW_UI_H_ -#define CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_UI_H_ -#pragma once - -#include "base/ref_counted.h" -#include "chrome/browser/webui/web_ui.h" - -class PrintPreviewUIHTMLSource; - -class PrintPreviewUI : public WebUI { - public: - explicit PrintPreviewUI(TabContents* contents); - virtual ~PrintPreviewUI(); - - PrintPreviewUIHTMLSource* html_source(); - - // Notify the Web UI renderer that preview data is available. - // |expected_pages_count| specifies the total number of pages. - void PreviewDataIsAvailable(int expected_pages_count); - - private: - scoped_refptr<PrintPreviewUIHTMLSource> html_source_; - - DISALLOW_COPY_AND_ASSIGN(PrintPreviewUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_UI_H_ diff --git a/chrome/browser/dom_ui/print_preview_ui_html_source.cc b/chrome/browser/dom_ui/print_preview_ui_html_source.cc deleted file mode 100644 index f46771f..0000000 --- a/chrome/browser/dom_ui/print_preview_ui_html_source.cc +++ /dev/null @@ -1,123 +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/print_preview_ui_html_source.h" - -#include <algorithm> -#include <vector> - -#include "base/message_loop.h" -#include "base/shared_memory.h" -#include "base/string_piece.h" -#include "base/values.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "grit/generated_resources.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" - -namespace { - -void SetLocalizedStrings(DictionaryValue* localized_strings) { - localized_strings->SetString(std::string("title"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_TITLE)); - localized_strings->SetString(std::string("loading"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_LOADING)); - localized_strings->SetString(std::string("noPlugin"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PLUGIN)); - localized_strings->SetString(std::string("noPrinter"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_NO_PRINTER)); - - localized_strings->SetString(std::string("printButton"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_PRINT_BUTTON)); - localized_strings->SetString(std::string("cancelButton"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_CANCEL_BUTTON)); - - localized_strings->SetString(std::string("optionAllPages"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_ALL_PAGES)); - localized_strings->SetString(std::string("optionBw"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_BW)); - localized_strings->SetString(std::string("optionCollate"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLLATE)); - localized_strings->SetString(std::string("optionColor"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_COLOR)); - localized_strings->SetString(std::string("optionLandscape"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_LANDSCAPE)); - localized_strings->SetString(std::string("optionPortrait"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_PORTRAIT)); - localized_strings->SetString(std::string("optionTwoSided"), - l10n_util::GetStringUTF8(IDS_PRINT_PREVIEW_OPTION_TWO_SIDED)); -} - -} // namespace - -PrintPreviewUIHTMLSource::PrintPreviewUIHTMLSource() - : DataSource(chrome::kChromeUIPrintHost, MessageLoop::current()), - data_(std::make_pair(static_cast<base::SharedMemory*>(NULL), 0U)) { -} - -PrintPreviewUIHTMLSource::~PrintPreviewUIHTMLSource() { - delete data_.first; -} - -void PrintPreviewUIHTMLSource::GetPrintPreviewData(PrintPreviewData* data) { - *data = data_; -} - -void PrintPreviewUIHTMLSource::SetPrintPreviewData( - const PrintPreviewData& data) { - delete data_.first; - data_ = data; -} - -void PrintPreviewUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - if (path.empty()) { - // Print Preview Index page. - DictionaryValue localized_strings; - SetLocalizedStrings(&localized_strings); - SetFontAndTextDirection(&localized_strings); - - static const base::StringPiece print_html( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_PRINT_PREVIEW_HTML)); - const std::string full_html = jstemplate_builder::GetI18nTemplateHtml( - print_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); - return; - } else if (path == "print.pdf" && data_.first) { - // Print Preview data. - char* preview_data = reinterpret_cast<char*>(data_.first->memory()); - uint32 preview_data_size = data_.second; - - scoped_refptr<RefCountedBytes> html_bytes(new RefCountedBytes); - html_bytes->data.resize(preview_data_size); - std::vector<unsigned char>::iterator it = html_bytes->data.begin(); - for (uint32 i = 0; i < preview_data_size; ++i, ++it) - *it = *(preview_data + i); - SendResponse(request_id, html_bytes); - return; - } else { - // Invalid request. - scoped_refptr<RefCountedBytes> empty_bytes(new RefCountedBytes); - SendResponse(request_id, empty_bytes); - return; - } -} - -std::string PrintPreviewUIHTMLSource::GetMimeType( - const std::string& path) const { - // Print Preview Index page. - if (path.empty()) - return "text/html"; - // Print Preview data. - return "application/pdf"; -} diff --git a/chrome/browser/dom_ui/print_preview_ui_html_source.h b/chrome/browser/dom_ui/print_preview_ui_html_source.h deleted file mode 100644 index 7950ed4..0000000 --- a/chrome/browser/dom_ui/print_preview_ui_html_source.h +++ /dev/null @@ -1,51 +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_PRINT_PREVIEW_UI_HTML_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_UI_HTML_SOURCE_H_ -#pragma once - -#include <string> -#include <utility> - -#include "chrome/browser/webui/chrome_url_data_manager.h" - -namespace base { -class SharedMemory; -} - -class PrintPreviewUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - // A SharedMemory that contains the data for print preview, - // and the size of the print preview data in bytes. - typedef std::pair<base::SharedMemory*, uint32> PrintPreviewData; - - PrintPreviewUIHTMLSource(); - virtual ~PrintPreviewUIHTMLSource(); - - // Gets the print preview |data|. The data is valid as long as the - // PrintPreviewHandler is valid and SetPrintPreviewData() does not get called. - void GetPrintPreviewData(PrintPreviewData* data); - - // Sets the print preview |data|. PrintPreviewHandler owns the data and is - // responsible for freeing it when either: - // a) there is new data. - // b) when PrintPreviewHandler is destroyed. - void SetPrintPreviewData(const PrintPreviewData& data); - - // ChromeURLDataManager::DataSource implementation. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const; - - private: - // Current print preview data, the contents of which are owned by - // PrintPreviewHandler. - PrintPreviewData data_; - - DISALLOW_COPY_AND_ASSIGN(PrintPreviewUIHTMLSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_PRINT_PREVIEW_UI_HTML_SOURCE_H_ diff --git a/chrome/browser/dom_ui/print_preview_ui_html_source_unittest.cc b/chrome/browser/dom_ui/print_preview_ui_html_source_unittest.cc deleted file mode 100644 index 0dc4646..0000000 --- a/chrome/browser/dom_ui/print_preview_ui_html_source_unittest.cc +++ /dev/null @@ -1,60 +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 "base/command_line.h" -#include "base/shared_memory.h" -#include "chrome/browser/dom_ui/print_preview_ui.h" -#include "chrome/browser/dom_ui/print_preview_ui_html_source.h" -#include "chrome/browser/printing/print_preview_tab_controller.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/ui/browser_list.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/test/browser_with_test_window_test.h" -#include "chrome/test/testing_profile.h" - -typedef BrowserWithTestWindowTest PrintPreviewUIHTMLSourceTest; - -// Create/Get a preview tab for initiator tab. -TEST_F(PrintPreviewUIHTMLSourceTest, PrintPreviewData) { - // TODO(thestig) Remove when print preview is enabled by default. - CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnablePrintPreview); - ASSERT_TRUE(browser()); - BrowserList::SetLastActive(browser()); - ASSERT_TRUE(BrowserList::GetLastActive()); - - browser()->NewTab(); - TabContents* initiator_tab = browser()->GetSelectedTabContents(); - ASSERT_TRUE(initiator_tab); - - scoped_refptr<printing::PrintPreviewTabController> - controller(new printing::PrintPreviewTabController()); - ASSERT_TRUE(controller); - - TabContents* preview_tab = controller->GetOrCreatePreviewTab( - initiator_tab, initiator_tab->controller().window_id().id()); - - EXPECT_NE(initiator_tab, preview_tab); - EXPECT_EQ(2, browser()->tab_count()); - - PrintPreviewUI* preview_ui = - reinterpret_cast<PrintPreviewUI*>(preview_tab->web_ui()); - ASSERT_TRUE(preview_ui != NULL); - PrintPreviewUIHTMLSource* html_source = preview_ui->html_source(); - - PrintPreviewUIHTMLSource::PrintPreviewData data; - html_source->GetPrintPreviewData(&data); - EXPECT_EQ(NULL, data.first); - EXPECT_EQ(0U, data.second); - - PrintPreviewUIHTMLSource::PrintPreviewData dummy_data = - std::make_pair(new base::SharedMemory(), 1234); - - html_source->SetPrintPreviewData(dummy_data); - html_source->GetPrintPreviewData(&data); - EXPECT_EQ(dummy_data, data); - - // This should not cause any memory leaks. - dummy_data.first = new base::SharedMemory(); - html_source->SetPrintPreviewData(dummy_data); -} diff --git a/chrome/browser/dom_ui/print_preview_ui_uitest.cc b/chrome/browser/dom_ui/print_preview_ui_uitest.cc deleted file mode 100644 index 5246843..0000000 --- a/chrome/browser/dom_ui/print_preview_ui_uitest.cc +++ /dev/null @@ -1,75 +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. - -#include "base/string16.h" -#include "base/utf_string_conversions.h" -#include "chrome/app/chrome_command_ids.h" -#include "chrome/common/chrome_switches.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/automation/browser_proxy.h" -#include "chrome/test/automation/tab_proxy.h" -#include "chrome/test/ui/ui_test.h" -#include "grit/generated_resources.h" -#include "ui/base/l10n/l10n_util.h" - -namespace { - -class PrintPreviewUITest : public UITest { - public: - PrintPreviewUITest() { - dom_automation_enabled_ = true; - // TODO(thestig): Remove when print preview is enabled by default. - launch_arguments_.AppendSwitch(switches::kEnablePrintPreview); - } - - void AssertIsPrintPage(TabProxy* tab) { - std::wstring title; - ASSERT_TRUE(tab->GetTabTitle(&title)); - string16 expected_title = - l10n_util::GetStringUTF16(IDS_PRINT_PREVIEW_TITLE); - ASSERT_EQ(expected_title, WideToUTF16Hack(title)); - } -}; - -// TODO(thestig) Remove this test in the future if loading -// chrome::kChromeUIPrintURL directly does not make sense. -TEST_F(PrintPreviewUITest, LoadPrintPreviewByURL) { - scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(browser.get()); - - scoped_refptr<TabProxy> tab = browser->GetActiveTab(); - ASSERT_TRUE(tab.get()); - - // Go to the print preview tab via URL. - NavigateToURL(GURL(chrome::kChromeUIPrintURL)); - AssertIsPrintPage(tab); -} - -TEST_F(PrintPreviewUITest, PrintCommandDisabled) { - scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); - ASSERT_TRUE(browser.get()); - - // Go to the about:blank page. - NavigateToURL(GURL(chrome::kAboutBlankURL)); - - // Make sure there is 1 tab and print is enabled. Create print preview tab. - int tab_count; - ASSERT_TRUE(browser->GetTabCount(&tab_count)); - ASSERT_EQ(1, tab_count); - bool enabled; - ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); - ASSERT_TRUE(enabled); - ASSERT_TRUE(browser->RunCommand(IDC_PRINT)); - - // Make sure there are 2 tabs and print is disabled. - ASSERT_TRUE(browser->GetTabCount(&tab_count)); - ASSERT_EQ(2, tab_count); - scoped_refptr<TabProxy> tab = browser->GetActiveTab(); - ASSERT_TRUE(tab.get()); - AssertIsPrintPage(tab); - ASSERT_TRUE(browser->IsMenuCommandEnabled(IDC_PRINT, &enabled)); - ASSERT_FALSE(enabled); -} - -} // namespace diff --git a/chrome/browser/dom_ui/settings_browsertest.cc b/chrome/browser/dom_ui/settings_browsertest.cc deleted file mode 100644 index 789de66..0000000 --- a/chrome/browser/dom_ui/settings_browsertest.cc +++ /dev/null @@ -1,92 +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/web_ui_browsertest.h" -#include "chrome/browser/webui/options/core_options_handler.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/ui_test_utils.h" -#include "googleurl/src/gurl.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -using ::testing::StrictMock; -using ::testing::_; - -MATCHER_P(Eq_ListValue, inList, "") { - return arg->Equals(inList); -} - -class MockCoreOptionsHandler : public CoreOptionsHandler { - public: - MOCK_METHOD1(HandleInitialize, - void(const ListValue* args)); - MOCK_METHOD1(HandleFetchPrefs, - void(const ListValue* args)); - MOCK_METHOD1(HandleObservePrefs, - void(const ListValue* args)); - MOCK_METHOD1(HandleSetBooleanPref, - void(const ListValue* args)); - MOCK_METHOD1(HandleSetIntegerPref, - void(const ListValue* args)); - MOCK_METHOD1(HandleSetDoublePref, - void(const ListValue* args)); - MOCK_METHOD1(HandleSetStringPref, - void(const ListValue* args)); - MOCK_METHOD1(HandleSetObjectPref, - void(const ListValue* args)); - MOCK_METHOD1(HandleClearPref, - void(const ListValue* args)); - MOCK_METHOD1(HandleUserMetricsAction, - void(const ListValue* args)); - - virtual void RegisterMessages() { - web_ui_->RegisterMessageCallback("coreOptionsInitialize", - NewCallback(this, &MockCoreOptionsHandler ::HandleInitialize)); - web_ui_->RegisterMessageCallback("fetchPrefs", - NewCallback(this, &MockCoreOptionsHandler ::HandleFetchPrefs)); - web_ui_->RegisterMessageCallback("observePrefs", - NewCallback(this, &MockCoreOptionsHandler ::HandleObservePrefs)); - web_ui_->RegisterMessageCallback("setBooleanPref", - NewCallback(this, &MockCoreOptionsHandler ::HandleSetBooleanPref)); - web_ui_->RegisterMessageCallback("setIntegerPref", - NewCallback(this, &MockCoreOptionsHandler ::HandleSetIntegerPref)); - web_ui_->RegisterMessageCallback("setDoublePref", - NewCallback(this, &MockCoreOptionsHandler ::HandleSetDoublePref)); - web_ui_->RegisterMessageCallback("setStringPref", - NewCallback(this, &MockCoreOptionsHandler ::HandleSetStringPref)); - web_ui_->RegisterMessageCallback("setObjectPref", - NewCallback(this, &MockCoreOptionsHandler ::HandleSetObjectPref)); - web_ui_->RegisterMessageCallback("clearPref", - NewCallback(this, &MockCoreOptionsHandler ::HandleClearPref)); - web_ui_->RegisterMessageCallback("coreOptionsUserMetricsAction", - NewCallback(this, &MockCoreOptionsHandler ::HandleUserMetricsAction)); - } -}; - -class SettingsWebUITest : public WebUIBrowserTest { - protected: - virtual WebUIMessageHandler* GetMockMessageHandler() { - return &mock_core_options_handler_; - } - - StrictMock<MockCoreOptionsHandler> mock_core_options_handler_; -}; - -// Test the end to end js to WebUI handler code path for -// the message setBooleanPref. -// TODO(dtseng): add more EXPECT_CALL's when updating js test. -IN_PROC_BROWSER_TEST_F(SettingsWebUITest, TestSetBooleanPrefTriggers) { - // This serves as an example of a very constrained test. - ListValue true_list_value; - true_list_value.Append(Value::CreateStringValue("browser.show_home_button")); - true_list_value.Append(Value::CreateBooleanValue(true)); - true_list_value.Append( - Value::CreateStringValue("Options_Homepage_HomeButton")); - ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUISettingsURL)); - EXPECT_CALL(mock_core_options_handler_, - HandleSetBooleanPref(Eq_ListValue(&true_list_value))); - ASSERT_TRUE(RunWebUITest( - FILE_PATH_LITERAL("settings_set_boolean_pref_triggers.js"))); -} - diff --git a/chrome/browser/dom_ui/shared_resources_data_source.cc b/chrome/browser/dom_ui/shared_resources_data_source.cc deleted file mode 100644 index aac3896..0000000 --- a/chrome/browser/dom_ui/shared_resources_data_source.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/shared_resources_data_source.h" - -#include <string> - -#include "base/singleton.h" -#include "base/threading/thread_restrictions.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/io_thread.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/common/url_constants.h" -#include "grit/app_resources.h" -#include "grit/generated_resources.h" -#include "grit/shared_resources.h" -#include "grit/shared_resources_map.h" -#include "grit/theme_resources.h" -#include "net/base/mime_util.h" -#include "ui/base/resource/resource_bundle.h" - -namespace { - -int PathToIDR(const std::string& path) { - int idr = -1; - if (path == "app/resources/folder_closed.png") { - idr = IDR_FOLDER_CLOSED; - } else if (path == "app/resources/folder_closed_rtl.png") { - idr = IDR_FOLDER_CLOSED_RTL; - } else if (path == "app/resources/folder_open.png") { - idr = IDR_FOLDER_OPEN; - } else if (path == "app/resources/folder_open_rtl.png") { - idr = IDR_FOLDER_OPEN_RTL; - } else if (path == "app/resources/throbber.png") { - idr = IDR_THROBBER; - } else { - // The name of the files in the grd list are prefixed with the following - // directory: - std::string key("shared/"); - key += path; - - for (size_t i = 0; i < kSharedResourcesSize; ++i) { - if (kSharedResources[i].name == key) { - idr = kSharedResources[i].value; - break; - } - } - } - - return idr; -} - -} // namespace - -SharedResourcesDataSource::SharedResourcesDataSource() - : DataSource(chrome::kChromeUIResourcesHost, NULL) { -} - -SharedResourcesDataSource::~SharedResourcesDataSource() { -} - -void SharedResourcesDataSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - int idr = PathToIDR(path); - DCHECK_NE(-1, idr); - const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - scoped_refptr<RefCountedStaticMemory> bytes(rb.LoadDataResourceBytes(idr)); - SendResponse(request_id, bytes); -} - -std::string SharedResourcesDataSource::GetMimeType( - const std::string& path) const { - // Requests should not block on the disk! On Windows this goes to the - // registry. - // http://code.google.com/p/chromium/issues/detail?id=59849 - base::ThreadRestrictions::ScopedAllowIO allow_io; - - std::string mime_type; - net::GetMimeTypeFromFile(FilePath().AppendASCII(path), &mime_type); - return mime_type; -} diff --git a/chrome/browser/dom_ui/shared_resources_data_source.h b/chrome/browser/dom_ui/shared_resources_data_source.h deleted file mode 100644 index 90be057..0000000 --- a/chrome/browser/dom_ui/shared_resources_data_source.h +++ /dev/null @@ -1,35 +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_SHARED_RESOURCES_DATA_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_SHARED_RESOURCES_DATA_SOURCE_H_ -#pragma once - -#include "chrome/browser/webui/chrome_url_data_manager.h" - -namespace net { -class URLRequest; -class URLRequestJob; -} // namespace net - -class GURL; - -// A DataSource for chrome://resources/ URLs. -class SharedResourcesDataSource : public ChromeURLDataManager::DataSource { - public: - SharedResourcesDataSource(); - - // Overridden from ChromeURLDataManager::DataSource: - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string&) const; - - private: - ~SharedResourcesDataSource(); - - DISALLOW_COPY_AND_ASSIGN(SharedResourcesDataSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_SHARED_RESOURCES_DATA_SOURCE_H_ diff --git a/chrome/browser/dom_ui/shown_sections_handler.cc b/chrome/browser/dom_ui/shown_sections_handler.cc deleted file mode 100644 index 96afe93..0000000 --- a/chrome/browser/dom_ui/shown_sections_handler.cc +++ /dev/null @@ -1,162 +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/shown_sections_handler.h" - -#include <string> - -#include "base/callback.h" -#include "base/command_line.h" -#include "base/string_number_conversions.h" -#include "base/values.h" -#include "chrome/browser/metrics/user_metrics.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/extensions/extension.h" -#include "chrome/common/notification_details.h" -#include "chrome/common/notification_type.h" -#include "chrome/common/pref_names.h" - -namespace { - -// Will cause an UMA notification if the mode of the new tab page -// was changed to hide/show the most visited thumbnails. -// TODO(aa): Needs to be updated to match newest NTP - http://crbug.com/57440 -void NotifySectionDisabled(int new_mode, int old_mode, Profile *profile) { - // If the oldmode HAD either thumbs or lists visible. - bool old_had_it = (old_mode & THUMB) && !(old_mode & MENU_THUMB); - bool new_has_it = (new_mode & THUMB) && !(new_mode & MENU_THUMB); - - if (old_had_it && !new_has_it) { - UserMetrics::RecordAction( - UserMetricsAction("ShowSections_RecentSitesDisabled"), - profile); - } - - if (new_has_it && !old_had_it) { - UserMetrics::RecordAction( - UserMetricsAction("ShowSections_RecentSitesEnabled"), - profile); - } -} - -} // namespace - -// static -int ShownSectionsHandler::GetShownSections(PrefService* prefs) { - return prefs->GetInteger(prefs::kNTPShownSections); -} - -// static -void ShownSectionsHandler::SetShownSection(PrefService* prefs, - Section section) { - int shown_sections = GetShownSections(prefs); - shown_sections &= ~ALL_SECTIONS_MASK; - shown_sections |= section; - prefs->SetInteger(prefs::kNTPShownSections, shown_sections); -} - -ShownSectionsHandler::ShownSectionsHandler(PrefService* pref_service) - : pref_service_(pref_service) { - pref_registrar_.Init(pref_service); - pref_registrar_.Add(prefs::kNTPShownSections, this); -} - -void ShownSectionsHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getShownSections", - NewCallback(this, &ShownSectionsHandler::HandleGetShownSections)); - web_ui_->RegisterMessageCallback("setShownSections", - NewCallback(this, &ShownSectionsHandler::HandleSetShownSections)); -} - -void ShownSectionsHandler::Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details) { - if (type == NotificationType::PREF_CHANGED) { - std::string* pref_name = Details<std::string>(details).ptr(); - DCHECK(*pref_name == prefs::kNTPShownSections); - int sections = pref_service_->GetInteger(prefs::kNTPShownSections); - FundamentalValue sections_value(sections); - web_ui_->CallJavascriptFunction(L"setShownSections", sections_value); - } else { - NOTREACHED(); - } -} - -void ShownSectionsHandler::HandleGetShownSections(const ListValue* args) { - int sections = GetShownSections(pref_service_); - FundamentalValue sections_value(sections); - web_ui_->CallJavascriptFunction(L"onShownSections", sections_value); -} - -void ShownSectionsHandler::HandleSetShownSections(const ListValue* args) { - double mode_double; - CHECK(args->GetDouble(0, &mode_double)); - int mode = static_cast<int>(mode_double); - int old_mode = pref_service_->GetInteger(prefs::kNTPShownSections); - - if (old_mode != mode) { - NotifySectionDisabled(mode, old_mode, web_ui_->GetProfile()); - pref_service_->SetInteger(prefs::kNTPShownSections, mode); - } -} - -// static -void ShownSectionsHandler::RegisterUserPrefs(PrefService* pref_service) { -#if defined(OS_CHROMEOS) - // Default to have expanded APPS and all other secions are minimized. - pref_service->RegisterIntegerPref(prefs::kNTPShownSections, - APPS | MENU_THUMB | MENU_RECENT); -#else - pref_service->RegisterIntegerPref(prefs::kNTPShownSections, THUMB); -#endif -} - -// static -void ShownSectionsHandler::MigrateUserPrefs(PrefService* pref_service, - int old_pref_version, - int new_pref_version) { - // Nothing to migrate for default kNTPShownSections value. - const PrefService::Preference* shown_sections_pref = - pref_service->FindPreference(prefs::kNTPShownSections); - if (shown_sections_pref->IsDefaultValue()) - return; - - bool changed = false; - int shown_sections = pref_service->GetInteger(prefs::kNTPShownSections); - - if (old_pref_version < 3) { - // In version 3, we went from being able to show multiple sections to being - // able to show only one expanded at a time. The only two expandable - // sections are APPS and THUMBS. - if (shown_sections & APPS) - shown_sections = APPS; - else - shown_sections = THUMB; - - changed = true; - } - - if (changed) - pref_service->SetInteger(prefs::kNTPShownSections, shown_sections); -} - -// static -void ShownSectionsHandler::OnExtensionInstalled(PrefService* prefs, - const Extension* extension) { - if (extension->is_app()) { - int mode = prefs->GetInteger(prefs::kNTPShownSections); - - // De-menu-mode the apps section. - mode &= ~MENU_APPS; - - // Hide any open sections. - mode &= ~ALL_SECTIONS_MASK; - - // Show the apps section. - mode |= APPS; - - prefs->SetInteger(prefs::kNTPShownSections, mode); - } -} diff --git a/chrome/browser/dom_ui/shown_sections_handler.h b/chrome/browser/dom_ui/shown_sections_handler.h deleted file mode 100644 index 3eb75ee..0000000 --- a/chrome/browser/dom_ui/shown_sections_handler.h +++ /dev/null @@ -1,79 +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_SHOWN_SECTIONS_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_SHOWN_SECTIONS_HANDLER_H_ -#pragma once - -#include "chrome/browser/prefs/pref_change_registrar.h" -#include "chrome/browser/webui/web_ui.h" -#include "chrome/common/notification_observer.h" - -class Extension; -class Value; -class PrefService; - -// Use for the shown sections bitmask. -// Currently, only the THUMB and APPS sections can be toggled by the user. Other -// sections are shown automatically if they have data, and hidden otherwise. -enum Section { - // If one of these is set, the corresponding section shows large thumbnails, - // else it shows only a small overview list. - THUMB = 1 << 0, - APPS = 1 << 6, - - // We use the low 16 bits for sections, the high 16 bits for menu mode. - ALL_SECTIONS_MASK = 0x0000FFFF, - - // If one of these is set, then the corresponding section is shown in a menu - // at the bottom of the NTP and no data is directly visible on the NTP. - MENU_THUMB = 1 << (0 + 16), - MENU_RECENT = 1 << (2 + 16), - MENU_APPS = 1 << (6 + 16), -}; - -class ShownSectionsHandler : public WebUIMessageHandler, - public NotificationObserver { - public: - explicit ShownSectionsHandler(PrefService* pref_service); - virtual ~ShownSectionsHandler() {} - - // Helper to get the current shown sections. - static int GetShownSections(PrefService* pref_service); - - // Expands |section|, collapsing any previously expanded section. This is the - // same thing that happens if a user clicks on |section|. - static void SetShownSection(PrefService* prefs, Section section); - - // WebUIMessageHandler implementation. - virtual void RegisterMessages(); - - // NotificationObserver implementation. - virtual void Observe(NotificationType type, - const NotificationSource& source, - const NotificationDetails& details); - - // Callback for "getShownSections" message. - void HandleGetShownSections(const ListValue* args); - - // Callback for "setShownSections" message. - void HandleSetShownSections(const ListValue* args); - - static void RegisterUserPrefs(PrefService* pref_service); - - static void MigrateUserPrefs(PrefService* pref_service, - int old_pref_version, - int new_pref_version); - - static void OnExtensionInstalled(PrefService* prefs, - const Extension* extension); - - private: - PrefService* pref_service_; - PrefChangeRegistrar pref_registrar_; - - DISALLOW_COPY_AND_ASSIGN(ShownSectionsHandler); -}; - -#endif // CHROME_BROWSER_DOM_UI_SHOWN_SECTIONS_HANDLER_H_ diff --git a/chrome/browser/dom_ui/shown_sections_handler_unittest.cc b/chrome/browser/dom_ui/shown_sections_handler_unittest.cc deleted file mode 100644 index 7ca5631..0000000 --- a/chrome/browser/dom_ui/shown_sections_handler_unittest.cc +++ /dev/null @@ -1,43 +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. - -#include "chrome/browser/dom_ui/shown_sections_handler.h" - -#include "base/scoped_ptr.h" -#include "chrome/browser/prefs/pref_value_store.h" -#include "chrome/common/json_pref_store.h" -#include "chrome/common/pref_names.h" -#include "chrome/test/testing_pref_service.h" -#include "testing/gtest/include/gtest/gtest.h" - -class ShownSectionsHandlerTest : public testing::Test { -}; - -namespace { - -int MigratePrefValue(PrefService* prefs, int starting_value) { - prefs->SetInteger(prefs::kNTPShownSections, starting_value); - ShownSectionsHandler::MigrateUserPrefs(prefs, 1, 3); - return prefs->GetInteger(prefs::kNTPShownSections); -} - -} // namespace - -TEST_F(ShownSectionsHandlerTest, MigrateUserPrefs) { - scoped_ptr<PrefService> pref(new TestingPrefService); - - pref->RegisterIntegerPref(prefs::kNTPShownSections, 0); - - EXPECT_EQ(APPS, MigratePrefValue(pref.get(), APPS)); - EXPECT_EQ(THUMB, MigratePrefValue(pref.get(), THUMB)); - EXPECT_EQ(APPS, MigratePrefValue(pref.get(), APPS | THUMB)); - - // 2 is not currently used, but older state may contain it and we should do - // something reasonable. - EXPECT_EQ(THUMB, MigratePrefValue(pref.get(), 3)); - - // 0 can't correspond to any section, but we should still do something - // reasonable. - EXPECT_EQ(THUMB, MigratePrefValue(pref.get(), 0)); -} diff --git a/chrome/browser/dom_ui/sync_internals_html_source.cc b/chrome/browser/dom_ui/sync_internals_html_source.cc deleted file mode 100644 index c35aaab..0000000 --- a/chrome/browser/dom_ui/sync_internals_html_source.cc +++ /dev/null @@ -1,49 +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/sync_internals_html_source.h" - -#include <algorithm> - -#include "base/message_loop.h" -#include "base/ref_counted.h" -#include "base/ref_counted_memory.h" -#include "base/string_piece.h" -#include "base/values.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/url_constants.h" -#include "grit/sync_internals_resources.h" -#include "ui/base/resource/resource_bundle.h" - -SyncInternalsHTMLSource::SyncInternalsHTMLSource() - : DataSource(chrome::kChromeUISyncInternalsHost, - MessageLoop::current()) {} - -SyncInternalsHTMLSource::~SyncInternalsHTMLSource() {} - -void SyncInternalsHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - base::StringPiece html_template( - ResourceBundle::GetSharedInstance().GetRawDataResource( - IDR_SYNC_INTERNALS_INDEX_HTML)); - DictionaryValue localized_strings; - SetFontAndTextDirection(&localized_strings); - - std::string html(html_template.data(), html_template.size()); - jstemplate_builder::AppendI18nTemplateSourceHtml(&html); - jstemplate_builder::AppendJsTemplateSourceHtml(&html); - jstemplate_builder::AppendJsonHtml(&localized_strings, &html); - jstemplate_builder::AppendI18nTemplateProcessHtml(&html); - - scoped_refptr<RefCountedBytes> bytes(new RefCountedBytes()); - bytes->data.resize(html.size()); - std::copy(html.begin(), html.end(), bytes->data.begin()); - SendResponse(request_id, bytes); -} - -std::string SyncInternalsHTMLSource::GetMimeType( - const std::string& path) const { - return "text/html"; -} diff --git a/chrome/browser/dom_ui/sync_internals_html_source.h b/chrome/browser/dom_ui/sync_internals_html_source.h deleted file mode 100644 index 969a11a..0000000 --- a/chrome/browser/dom_ui/sync_internals_html_source.h +++ /dev/null @@ -1,31 +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_SYNC_INTERNALS_HTML_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_SYNC_INTERNALS_HTML_SOURCE_H_ -#pragma once - -#include <string> - -#include "base/basictypes.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" - -class SyncInternalsHTMLSource : public ChromeURLDataManager::DataSource { - public: - SyncInternalsHTMLSource(); - - // ChromeURLDataManager::DataSource implementation. - virtual void StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id); - virtual std::string GetMimeType(const std::string& path) const; - - protected: - virtual ~SyncInternalsHTMLSource(); - - private: - DISALLOW_COPY_AND_ASSIGN(SyncInternalsHTMLSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_SYNC_INTERNALS_HTML_SOURCE_H_ diff --git a/chrome/browser/dom_ui/sync_internals_ui.cc b/chrome/browser/dom_ui/sync_internals_ui.cc deleted file mode 100644 index fd81d8b..0000000 --- a/chrome/browser/dom_ui/sync_internals_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/sync_internals_ui.h" - -#include <string> - -#include "base/logging.h" -#include "base/ref_counted.h" -#include "base/task.h" -#include "base/tracked_objects.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/sync_internals_html_source.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/sync/js_arg_list.h" -#include "chrome/browser/sync/js_frontend.h" -#include "chrome/browser/sync/profile_sync_service.h" -#include "chrome/browser/sync/sync_ui_util.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/common/render_messages_params.h" - -SyncInternalsUI::SyncInternalsUI(TabContents* contents) - : WebUI(contents) { - browser_sync::JsFrontend* backend = GetJsFrontend(); - if (backend) { - backend->AddHandler(this); - } - // If this PostTask() call fails, it's most likely because this is - // being run from a unit test. The created objects will be cleaned - // up, anyway. - contents->profile()->GetChromeURLDataManager()->AddDataSource( - new SyncInternalsHTMLSource()); -} - -SyncInternalsUI::~SyncInternalsUI() { - browser_sync::JsFrontend* backend = GetJsFrontend(); - if (backend) { - backend->RemoveHandler(this); - } -} - -void SyncInternalsUI::ProcessWebUIMessage( - const ViewHostMsg_DomMessage_Params& params) { - const std::string& name = params.name; - browser_sync::JsArgList args(params.arguments); - VLOG(1) << "Received message: " << name << " with args " - << args.ToString(); - // We handle this case directly because it needs to work even if - // the sync service doesn't exist. - if (name == "getAboutInfo") { - ListValue args; - DictionaryValue* about_info = new DictionaryValue(); - args.Append(about_info); - ProfileSyncService* service = GetProfile()->GetProfileSyncService(); - sync_ui_util::ConstructAboutInformation(service, about_info); - HandleJsEvent("onGetAboutInfoFinished", - browser_sync::JsArgList(args)); - } else { - browser_sync::JsFrontend* backend = GetJsFrontend(); - if (backend) { - backend->ProcessMessage(name, args, this); - } else { - LOG(WARNING) << "No sync service; dropping message " << name - << " with args " << args.ToString(); - } - } -} - -void SyncInternalsUI::HandleJsEvent(const std::string& name, - const browser_sync::JsArgList& args) { - VLOG(1) << "Handling event: " << name << " with args " << args.ToString(); - std::vector<const Value*> arg_list(args.Get().begin(), args.Get().end()); - CallJavascriptFunction(UTF8ToWide(name), arg_list); -} - -browser_sync::JsFrontend* SyncInternalsUI::GetJsFrontend() { - // If this returns NULL that means that sync is disabled for - // whatever reason. - ProfileSyncService* sync_service = GetProfile()->GetProfileSyncService(); - return sync_service ? sync_service->GetJsFrontend() : NULL; -} diff --git a/chrome/browser/dom_ui/sync_internals_ui.h b/chrome/browser/dom_ui/sync_internals_ui.h deleted file mode 100644 index 5060426..0000000 --- a/chrome/browser/dom_ui/sync_internals_ui.h +++ /dev/null @@ -1,53 +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_SYNC_INTERNALS_UI_H_ -#define CHROME_BROWSER_DOM_UI_SYNC_INTERNALS_UI_H_ -#pragma once - -#include <string> - -#include "base/basictypes.h" -#include "chrome/browser/sync/js_event_handler.h" -#include "chrome/browser/webui/web_ui.h" - -namespace browser_sync { -class JsFrontend; -} // namespace browser_sync - -// The implementation for the chrome://sync-internals page. -class SyncInternalsUI : public WebUI, public browser_sync::JsEventHandler { - public: - explicit SyncInternalsUI(TabContents* contents); - virtual ~SyncInternalsUI(); - - // WebUI implementation. - // - // The following messages are processed: - // - // getAboutInfo(): - // Immediately fires a onGetAboutInfoFinished() event with a - // dictionary of sync-related stats and info. - // - // All other messages are routed to the sync service if it exists, - // and dropped otherwise. - // - // TODO(akalin): Add a simple isSyncEnabled() message and make - // getAboutInfo() be handled by the sync service. - virtual void ProcessWebUIMessage( - const ViewHostMsg_DomMessage_Params& params); - - // browser_sync::JsEventHandler implementation. - virtual void HandleJsEvent(const std::string& name, - const browser_sync::JsArgList& args); - - private: - // Returns the sync service's JsFrontend object, or NULL if the sync - // service does not exist. - browser_sync::JsFrontend* GetJsFrontend(); - - DISALLOW_COPY_AND_ASSIGN(SyncInternalsUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_SYNC_INTERNALS_UI_H_ diff --git a/chrome/browser/dom_ui/sync_internals_ui_unittest.cc b/chrome/browser/dom_ui/sync_internals_ui_unittest.cc deleted file mode 100644 index a1f392e..0000000 --- a/chrome/browser/dom_ui/sync_internals_ui_unittest.cc +++ /dev/null @@ -1,226 +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/sync_internals_ui.h" - -#include <cstddef> -#include <string> - -#include "base/message_loop.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/renderer_host/test/test_render_view_host.h" -#include "chrome/browser/sync/js_arg_list.h" -#include "chrome/browser/sync/js_test_util.h" -#include "chrome/browser/sync/profile_sync_service_mock.h" -#include "chrome/browser/tab_contents/test_tab_contents.h" -#include "chrome/common/render_messages_params.h" -#include "chrome/test/profile_mock.h" -#include "testing/gmock/include/gmock/gmock.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace { - -using browser_sync::HasArgsAsList; -using browser_sync::JsArgList; -using testing::NiceMock; -using testing::Return; -using testing::StrictMock; - -// Subclass of SyncInternalsUI to mock out ExecuteJavascript. -class TestSyncInternalsUI : public SyncInternalsUI { - public: - explicit TestSyncInternalsUI(TabContents* contents) - : SyncInternalsUI(contents) {} - virtual ~TestSyncInternalsUI() {} - - MOCK_METHOD1(ExecuteJavascript, void(const std::wstring&)); -}; - -class SyncInternalsUITest : public RenderViewHostTestHarness { - protected: - // We allocate memory for |sync_internals_ui_| but we don't - // construct it. This is because we want to set mock expectations - // with its address before we construct it, and its constructor - // calls into our mocks. - SyncInternalsUITest() - // The message loop is provided by RenderViewHostTestHarness. - : ui_thread_(BrowserThread::UI, MessageLoopForUI::current()), - test_sync_internals_ui_buf_(NULL), - test_sync_internals_ui_constructor_called_(false) {} - - virtual void SetUp() { - test_sync_internals_ui_buf_ = operator new(sizeof(TestSyncInternalsUI)); - test_sync_internals_ui_constructor_called_ = false; - profile_.reset(new NiceMock<ProfileMock>()); - RenderViewHostTestHarness::SetUp(); - } - - virtual void TearDown() { - if (test_sync_internals_ui_constructor_called_) { - GetTestSyncInternalsUI()->~TestSyncInternalsUI(); - } - operator delete(test_sync_internals_ui_buf_); - RenderViewHostTestHarness::TearDown(); - } - - NiceMock<ProfileMock>* GetProfileMock() { - return static_cast<NiceMock<ProfileMock>*>(profile()); - } - - // Set up boilerplate expectations for calls done during - // SyncInternalUI's construction/destruction. - void ExpectSetupTeardownCalls() { - EXPECT_CALL(*GetProfileMock(), GetProfileSyncService()) - .WillRepeatedly(Return(&profile_sync_service_mock_)); - - EXPECT_CALL(profile_sync_service_mock_, GetJsFrontend()) - .WillRepeatedly(Return(&mock_js_backend_)); - - // Called by sync_ui_util::ConstructAboutInformation(). - EXPECT_CALL(profile_sync_service_mock_, HasSyncSetupCompleted()) - .WillRepeatedly(Return(false)); - - // Called by SyncInternalsUI's constructor. - EXPECT_CALL(mock_js_backend_, - AddHandler(GetTestSyncInternalsUIAddress())); - - // Called by SyncInternalUI's destructor. - EXPECT_CALL(mock_js_backend_, - RemoveHandler(GetTestSyncInternalsUIAddress())); - } - - // Like ExpectSetupTeardownCalls() but with a NULL - // ProfileSyncService. - void ExpectSetupTeardownCallsNullService() { - EXPECT_CALL(*GetProfileMock(), GetProfileSyncService()) - .WillRepeatedly(Return(static_cast<ProfileSyncService*>(NULL))); - } - - void ConstructTestSyncInternalsUI() { - if (test_sync_internals_ui_constructor_called_) { - ADD_FAILURE() << "ConstructTestSyncInternalsUI() should be called " - << "at most once per test"; - return; - } - new(test_sync_internals_ui_buf_) TestSyncInternalsUI(contents()); - test_sync_internals_ui_constructor_called_ = true; - } - - TestSyncInternalsUI* GetTestSyncInternalsUI() { - if (!test_sync_internals_ui_constructor_called_) { - ADD_FAILURE() << "ConstructTestSyncInternalsUI() should be called " - << "before GetTestSyncInternalsUI()"; - return NULL; - } - return GetTestSyncInternalsUIAddress(); - } - - // Used for passing into EXPECT_CALL(). - TestSyncInternalsUI* GetTestSyncInternalsUIAddress() { - EXPECT_TRUE(test_sync_internals_ui_buf_); - return static_cast<TestSyncInternalsUI*>(test_sync_internals_ui_buf_); - } - - StrictMock<ProfileSyncServiceMock> profile_sync_service_mock_; - StrictMock<browser_sync::MockJsFrontend> mock_js_backend_; - - private: - // Needed by |contents()|. - BrowserThread ui_thread_; - void* test_sync_internals_ui_buf_; - bool test_sync_internals_ui_constructor_called_; -}; - -TEST_F(SyncInternalsUITest, HandleJsEvent) { - ExpectSetupTeardownCalls(); - - ConstructTestSyncInternalsUI(); - - EXPECT_CALL(*GetTestSyncInternalsUI(), - ExecuteJavascript(std::wstring(L"testMessage(5,true);"))); - - ListValue args; - args.Append(Value::CreateIntegerValue(5)); - args.Append(Value::CreateBooleanValue(true)); - GetTestSyncInternalsUI()->HandleJsEvent("testMessage", JsArgList(args)); -} - -TEST_F(SyncInternalsUITest, HandleJsEventNullService) { - ExpectSetupTeardownCallsNullService(); - - ConstructTestSyncInternalsUI(); - - EXPECT_CALL(*GetTestSyncInternalsUI(), - ExecuteJavascript(std::wstring(L"testMessage(5,true);"))); - - ListValue args; - args.Append(Value::CreateIntegerValue(5)); - args.Append(Value::CreateBooleanValue(true)); - GetTestSyncInternalsUI()->HandleJsEvent("testMessage", JsArgList(args)); -} - -TEST_F(SyncInternalsUITest, ProcessWebUIMessageBasic) { - ExpectSetupTeardownCalls(); - - ViewHostMsg_DomMessage_Params params; - params.name = "testName"; - params.arguments.Append(Value::CreateIntegerValue(10)); - - EXPECT_CALL(mock_js_backend_, - ProcessMessage(params.name, HasArgsAsList(params.arguments), - GetTestSyncInternalsUIAddress())); - - ConstructTestSyncInternalsUI(); - - GetTestSyncInternalsUI()->ProcessWebUIMessage(params); -} - -TEST_F(SyncInternalsUITest, ProcessWebUIMessageBasicNullService) { - ExpectSetupTeardownCallsNullService(); - - ConstructTestSyncInternalsUI(); - - ViewHostMsg_DomMessage_Params params; - params.name = "testName"; - params.arguments.Append(Value::CreateIntegerValue(5)); - - // Should drop the message. - GetTestSyncInternalsUI()->ProcessWebUIMessage(params); -} - -namespace { -const wchar_t kAboutInfoCall[] = - L"onGetAboutInfoFinished({\"summary\":\"SYNC DISABLED\"});"; -} // namespace - -TEST_F(SyncInternalsUITest, ProcessWebUIMessageGetAboutInfo) { - ExpectSetupTeardownCalls(); - - ViewHostMsg_DomMessage_Params params; - params.name = "getAboutInfo"; - - ConstructTestSyncInternalsUI(); - - EXPECT_CALL(*GetTestSyncInternalsUI(), - ExecuteJavascript(std::wstring(kAboutInfoCall))); - - GetTestSyncInternalsUI()->ProcessWebUIMessage(params); -} - -TEST_F(SyncInternalsUITest, ProcessWebUIMessageGetAboutInfoNullService) { - ExpectSetupTeardownCallsNullService(); - - ViewHostMsg_DomMessage_Params params; - params.name = "getAboutInfo"; - - ConstructTestSyncInternalsUI(); - - EXPECT_CALL(*GetTestSyncInternalsUI(), - ExecuteJavascript(std::wstring(kAboutInfoCall))); - - GetTestSyncInternalsUI()->ProcessWebUIMessage(params); -} - -} // namespace diff --git a/chrome/browser/dom_ui/textfields_ui.cc b/chrome/browser/dom_ui/textfields_ui.cc deleted file mode 100644 index 7d8891d..0000000 --- a/chrome/browser/dom_ui/textfields_ui.cc +++ /dev/null @@ -1,74 +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/textfields_ui.h" - -#include <algorithm> -#include <string> - -#include "base/singleton.h" -#include "base/string_piece.h" -#include "base/values.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/common/jstemplate_builder.h" -#include "chrome/common/url_constants.h" -#include "grit/browser_resources.h" -#include "ui/base/resource/resource_bundle.h" - -/** - * TextfieldsUIHTMLSource implementation. - */ -TextfieldsUIHTMLSource::TextfieldsUIHTMLSource() - : DataSource(chrome::kChromeUITextfieldsHost, MessageLoop::current()) { -} - -void TextfieldsUIHTMLSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - const std::string full_html = ResourceBundle::GetSharedInstance() - .GetRawDataResource(IDR_TEXTFIELDS_HTML).as_string(); - - 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); -} - -std::string TextfieldsUIHTMLSource::GetMimeType( - const std::string& /* path */) const { - return "text/html"; -} - -TextfieldsUIHTMLSource::~TextfieldsUIHTMLSource() {} - -/** - * TextfieldsDOMHandler implementation. - */ -TextfieldsDOMHandler::TextfieldsDOMHandler() : WebUIMessageHandler() {} - -void TextfieldsDOMHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("textfieldValue", - NewCallback(this, &TextfieldsDOMHandler::HandleTextfieldValue)); -} - -void TextfieldsDOMHandler::HandleTextfieldValue(const ListValue* args) { - static_cast<TextfieldsUI*>(web_ui_)->set_text(ExtractStringValue(args)); -} - -/** - * TextfieldsUI implementation. - */ -TextfieldsUI::TextfieldsUI(TabContents* contents) : WebUI(contents) { - TextfieldsDOMHandler* handler = new TextfieldsDOMHandler(); - AddMessageHandler(handler); - handler->Attach(this); - - TextfieldsUIHTMLSource* html_source = new TextfieldsUIHTMLSource(); - - // Set up the chrome://textfields/ source. - contents->profile()->GetChromeURLDataManager()->AddDataSource(html_source); -} diff --git a/chrome/browser/dom_ui/textfields_ui.h b/chrome/browser/dom_ui/textfields_ui.h deleted file mode 100644 index 145ec69..0000000 --- a/chrome/browser/dom_ui/textfields_ui.h +++ /dev/null @@ -1,71 +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_TEXTFIELDS_UI_H_ -#define CHROME_BROWSER_DOM_UI_TEXTFIELDS_UI_H_ -#pragma once - -#include <string> - -#include "chrome/browser/webui/chrome_url_data_manager.h" -#include "chrome/browser/webui/web_ui.h" - -class RefCountedMemory; - -/** - * ChromeURLDataManager::DataSource implementation that asynchronously answers - * requests for chrome://textfields URL. On receiving a request, this object - * reads the html from the local resource textfields.html and sends back the - * response. - */ -class TextfieldsUIHTMLSource : public ChromeURLDataManager::DataSource { - public: - TextfieldsUIHTMLSource(); - - // 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& path) const; - - private: - virtual ~TextfieldsUIHTMLSource(); - - DISALLOW_COPY_AND_ASSIGN(TextfieldsUIHTMLSource); -}; - -/** - * Handler for JavaScript calls from the DOM. - */ -class TextfieldsDOMHandler : public WebUIMessageHandler { - public: - TextfieldsDOMHandler(); - - // Handles the "textfieldValue" call from the JavaScript. This call - // synchonizes the value inside the JavaScript textfield with the copy in the - // DOM object. - virtual void HandleTextfieldValue(const ListValue* args); - - protected: - virtual void RegisterMessages(); - - private: - DISALLOW_COPY_AND_ASSIGN(TextfieldsDOMHandler); -}; - -class TextfieldsUI : public WebUI { - public: - explicit TextfieldsUI(TabContents* contents); - - const std::wstring& text() const { return text_; } - void set_text(const std::wstring& text) { text_ = text; } - - private: - std::wstring text_; - - DISALLOW_COPY_AND_ASSIGN(TextfieldsUI); -}; - -#endif // CHROME_BROWSER_DOM_UI_TEXTFIELDS_UI_H_ diff --git a/chrome/browser/dom_ui/tips_handler.cc b/chrome/browser/dom_ui/tips_handler.cc deleted file mode 100644 index a636682..0000000 --- a/chrome/browser/dom_ui/tips_handler.cc +++ /dev/null @@ -1,112 +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/tips_handler.h" - -#include <string> - -#include "base/callback.h" -#include "base/utf_string_conversions.h" -#include "base/values.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/prefs/pref_service.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/web_resource/promo_resource_service.h" -#include "chrome/common/pref_names.h" -#include "chrome/common/web_resource/web_resource_unpacker.h" -#include "chrome/common/url_constants.h" -#include "googleurl/src/gurl.h" -#include "grit/generated_resources.h" -#include "ui/base/l10n/l10n_util.h" - -WebUIMessageHandler* TipsHandler::Attach(WebUI* web_ui) { - web_ui_ = web_ui; - tips_cache_ = web_ui_->GetProfile()->GetPrefs()-> - GetMutableDictionary(prefs::kNTPPromoResourceCache); - return WebUIMessageHandler::Attach(web_ui); -} - -void TipsHandler::RegisterMessages() { - web_ui_->RegisterMessageCallback("getTips", - NewCallback(this, &TipsHandler::HandleGetTips)); -} - -void TipsHandler::HandleGetTips(const ListValue* args) { - // List containing the tips to be displayed. - ListValue list_value; - - // Holds the web resource data found in the preferences cache. - ListValue* wr_list; - - // These values hold the data for each web resource item. - int current_tip_index; - std::string current_tip; - - // If tips are not correct for our language, do not send. Wait for update. - // We need to check here because the new tab page calls for tips before - // the tip service starts up. - PrefService* current_prefs = web_ui_->GetProfile()->GetPrefs(); - if (current_prefs->HasPrefPath(prefs::kNTPTipsResourceServer)) { - std::string server = current_prefs->GetString( - prefs::kNTPTipsResourceServer); - std::string locale = g_browser_process->GetApplicationLocale(); - if (!EndsWith(server, locale, false)) { - web_ui_->CallJavascriptFunction(L"tips", list_value); - return; - } - } - - if (tips_cache_ != NULL && !tips_cache_->empty()) { - if (tips_cache_->GetInteger( - PromoResourceService::kCurrentTipPrefName, ¤t_tip_index) && - tips_cache_->GetList( - PromoResourceService::kTipCachePrefName, &wr_list) && - wr_list && wr_list->GetSize() > 0) { - if (wr_list->GetSize() <= static_cast<size_t>(current_tip_index)) { - // Check to see whether the home page is set to NTP; if not, add tip - // to set home page before resetting tip index to 0. - current_tip_index = 0; - const PrefService::Preference* pref = - web_ui_->GetProfile()->GetPrefs()->FindPreference( - prefs::kHomePageIsNewTabPage); - bool value; - if (pref && !pref->IsManaged() && - pref->GetValue()->GetAsBoolean(&value) && !value) { - SendTip(l10n_util::GetStringUTF8(IDS_NEW_TAB_MAKE_THIS_HOMEPAGE), - "set_homepage_tip", current_tip_index); - return; - } - } - if (wr_list->GetString(current_tip_index, ¤t_tip)) { - SendTip(current_tip, "tip_html_text", current_tip_index + 1); - } - } - } -} - -void TipsHandler::SendTip(const std::string& tip, const std::string& tip_type, - int tip_index) { - // List containing the tips to be displayed. - ListValue list_value; - DictionaryValue* tip_dict = new DictionaryValue(); - tip_dict->SetString(tip_type, tip); - list_value.Append(tip_dict); - tips_cache_->SetInteger(PromoResourceService::kCurrentTipPrefName, - tip_index); - // Send list of web resource items back out to the DOM. - web_ui_->CallJavascriptFunction(L"tips", list_value); -} - -// static -void TipsHandler::RegisterUserPrefs(PrefService* prefs) { - prefs->RegisterDictionaryPref(prefs::kNTPPromoResourceCache); - prefs->RegisterStringPref(prefs::kNTPPromoResourceServer, - PromoResourceService::kDefaultPromoResourceServer); -} - -bool TipsHandler::IsValidURL(const std::wstring& url_string) { - GURL url(WideToUTF8(url_string)); - return !url.is_empty() && (url.SchemeIs(chrome::kHttpScheme) || - url.SchemeIs(chrome::kHttpsScheme)); -} diff --git a/chrome/browser/dom_ui/tips_handler.h b/chrome/browser/dom_ui/tips_handler.h deleted file mode 100644 index 1a2cccf..0000000 --- a/chrome/browser/dom_ui/tips_handler.h +++ /dev/null @@ -1,56 +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. - -// This class pulls data from a web resource (such as a JSON feed) which -// has been stored in the user's preferences file. Used mainly -// by the suggestions and tips area of the new tab page. - -#ifndef CHROME_BROWSER_DOM_UI_TIPS_HANDLER_H_ -#define CHROME_BROWSER_DOM_UI_TIPS_HANDLER_H_ -#pragma once - -#include <string> - -#include "chrome/browser/webui/web_ui.h" - -class DictionaryValue; -class ListValue; -class PrefService; - -class TipsHandler : public WebUIMessageHandler { - public: - TipsHandler() : tips_cache_(NULL) {} - virtual ~TipsHandler() {} - - // WebUIMessageHandler implementation and overrides. - virtual WebUIMessageHandler* Attach(WebUI* web_ui); - virtual void RegisterMessages(); - - // Callback which pulls tips data from the preferences. - void HandleGetTips(const ListValue* args); - - // Register tips cache with pref service. - static void RegisterUserPrefs(PrefService* prefs); - - private: - // Make sure the string we are pushing to the NTP is a valid URL. - bool IsValidURL(const std::wstring& url_string); - - // Send a tip to the NTP. tip_type is "tip_html_text" if the tip is from - // the tip server, and "set_homepage_tip" if it's the tip to set the NTP - // as home page. - void SendTip(const std::string& tip, const std::string& tip_type, - int tip_index); - - // So we can push data out to the page that has called this handler. - WebUI* web_ui_; - - // Filled with data from cache in preferences. - DictionaryValue* tips_cache_; - - DISALLOW_COPY_AND_ASSIGN(TipsHandler); -}; - -#endif // CHROME_BROWSER_DOM_UI_TIPS_HANDLER_H_ - diff --git a/chrome/browser/dom_ui/value_helper.cc b/chrome/browser/dom_ui/value_helper.cc deleted file mode 100644 index 93c1137..0000000 --- a/chrome/browser/dom_ui/value_helper.cc +++ /dev/null @@ -1,47 +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. - -#include "chrome/browser/dom_ui/value_helper.h" - -#include "chrome/browser/dom_ui/new_tab_ui.h" -#include "chrome/common/url_constants.h" - -bool ValueHelper::TabToValue( - const TabRestoreService::Tab& tab, - DictionaryValue* dictionary) { - if (tab.navigations.empty()) - return false; - - const TabNavigation& current_navigation = - tab.navigations.at(tab.current_navigation_index); - if (current_navigation.virtual_url() == GURL(chrome::kChromeUINewTabURL)) - return false; - NewTabUI::SetURLTitleAndDirection(dictionary, current_navigation.title(), - current_navigation.virtual_url()); - dictionary->SetString("type", "tab"); - dictionary->SetDouble("timestamp", tab.timestamp.ToDoubleT()); - return true; -} - -bool ValueHelper::WindowToValue( - const TabRestoreService::Window& window, - DictionaryValue* dictionary) { - if (window.tabs.empty()) { - NOTREACHED(); - return false; - } - scoped_ptr<ListValue> tab_values(new ListValue()); - for (size_t i = 0; i < window.tabs.size(); ++i) { - scoped_ptr<DictionaryValue> tab_value(new DictionaryValue()); - if (TabToValue(window.tabs[i], tab_value.get())) - tab_values->Append(tab_value.release()); - } - if (tab_values->GetSize() == 0) - return false; - dictionary->SetString("type", "window"); - dictionary->SetDouble("timestamp", window.timestamp.ToDoubleT()); - dictionary->Set("tabs", tab_values.release()); - return true; -} - diff --git a/chrome/browser/dom_ui/value_helper.h b/chrome/browser/dom_ui/value_helper.h deleted file mode 100644 index b6a11777..0000000 --- a/chrome/browser/dom_ui/value_helper.h +++ /dev/null @@ -1,25 +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_VALUE_HELPER_H_ -#define CHROME_BROWSER_DOM_UI_VALUE_HELPER_H_ -#pragma once - -#include "chrome/browser/sessions/tab_restore_service.h" - -#include "base/values.h" - -// Used to convert TabRestoreService elements to values for JSON processing. -class ValueHelper { - public: - static bool TabToValue(const TabRestoreService::Tab& tab, - DictionaryValue* dictionary); - static bool WindowToValue(const TabRestoreService::Window& window, - DictionaryValue* dictionary); - private: - DISALLOW_IMPLICIT_CONSTRUCTORS(ValueHelper); -}; - -#endif // CHROME_BROWSER_DOM_UI_VALUE_HELPER_H_ - diff --git a/chrome/browser/dom_ui/web_ui_browsertest.cc b/chrome/browser/dom_ui/web_ui_browsertest.cc deleted file mode 100644 index 6bb35bf..0000000 --- a/chrome/browser/dom_ui/web_ui_browsertest.cc +++ /dev/null @@ -1,78 +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/web_ui_browsertest.h" - -#include "base/path_service.h" -#include "chrome/browser/tab_contents/tab_contents.h" -#include "chrome/browser/ui/browser.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/ui_test_utils.h" -#include "ui/base/resource/resource_bundle.h" - -static const FilePath::CharType* kWebUILibraryJS = - FILE_PATH_LITERAL("test_api.js"); -static const FilePath::CharType* kWebUITestFolder = - FILE_PATH_LITERAL("dom_ui"); - -WebUIBrowserTest::~WebUIBrowserTest() {} - -bool WebUIBrowserTest::RunWebUITest(const FilePath::CharType* src_path) { - std::string content; - BuildJavaScriptTest(FilePath(src_path), &content); - SetupHandlers(); - return test_handler_->Execute(content); -} - -WebUIBrowserTest::WebUIBrowserTest() - : test_handler_(new WebUIHandlerBrowserTest()) {} - -void WebUIBrowserTest::SetUpInProcessBrowserTestFixture() { - ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_data_directory_)); - test_data_directory_ = test_data_directory_.Append(kWebUITestFolder); - - // TODO(dtseng): should this be part of every BrowserTest or just WebUI test. - FilePath resources_pack_path; - PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path); - ResourceBundle::AddDataPackToSharedInstance(resources_pack_path); -} - -WebUIMessageHandler* WebUIBrowserTest::GetMockMessageHandler() { - return NULL; -} - -void WebUIBrowserTest::BuildJavaScriptTest(const FilePath& src_path, - std::string* content) { - ASSERT_TRUE(content != NULL); - std::string library_content, src_content; - ASSERT_TRUE(file_util::ReadFileToString( - test_data_directory_.Append(FilePath(kWebUILibraryJS)), - &library_content)); - ASSERT_TRUE(file_util::ReadFileToString( - test_data_directory_.Append(src_path), &src_content)); - - content->append(library_content); - content->append(";\n"); - content->append(src_content); -} - -void WebUIBrowserTest::SetupHandlers() { - WebUI* web_ui_instance = - browser()->GetSelectedTabContents()->web_ui(); - ASSERT_TRUE(web_ui_instance != NULL); - web_ui_instance->register_callback_overwrites(true); - test_handler_->Attach(web_ui_instance); - - if (GetMockMessageHandler()) - GetMockMessageHandler()->Attach(web_ui_instance); -} - -IN_PROC_BROWSER_TEST_F(WebUIBrowserTest, TestSamplePass) { - // Navigate to UI. - // TODO(dtseng): make accessor for subclasses to return? - ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIDownloadsURL)); - - ASSERT_TRUE(RunWebUITest(FILE_PATH_LITERAL("sample_downloads.js"))); -} diff --git a/chrome/browser/dom_ui/web_ui_browsertest.h b/chrome/browser/dom_ui/web_ui_browsertest.h deleted file mode 100644 index 44db102..0000000 --- a/chrome/browser/dom_ui/web_ui_browsertest.h +++ /dev/null @@ -1,58 +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_WEB_UI_BROWSERTEST_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_BROWSERTEST_H_ -#pragma once - -#include <string> - -#include "base/file_path.h" -#include "chrome/browser/dom_ui/web_ui_handler_browsertest.h" -#include "chrome/test/in_process_browser_test.h" - -class WebUIMessageHandler; - -// The runner of WebUI javascript based tests. -// See chrome/test/data/dom_ui/test_api.js for the javascript side test API's. -// -// These tests should follow the form given in: -// chrome/test/data/dom_ui/sample_downloads.js. -// and the lone test within this class. -class WebUIBrowserTest : public InProcessBrowserTest { - public: - virtual ~WebUIBrowserTest(); - - bool RunWebUITest(const FilePath::CharType* src_path); - - protected: - WebUIBrowserTest(); - - // Setup test path. - virtual void SetUpInProcessBrowserTestFixture(); - - // Returns a mock WebUI object under test (if any). - virtual WebUIMessageHandler* GetMockMessageHandler(); - - private: - // Builds a javascript test in the form: - // <js_library> ... - // <src_path> ... - // runTests(function test1() {...}, - // ... - // ); - void BuildJavaScriptTest(const FilePath& src_path, - std::string* content); - - // Attaches mock and test handlers. - void SetupHandlers(); - - // Handles test framework messages. - scoped_ptr<WebUIHandlerBrowserTest> test_handler_; - - // Location of test data (currently test/data/dom_ui). - FilePath test_data_directory_; -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_BROWSERTEST_H_ diff --git a/chrome/browser/dom_ui/web_ui_favicon_source.cc b/chrome/browser/dom_ui/web_ui_favicon_source.cc deleted file mode 100644 index f2d7128..0000000 --- a/chrome/browser/dom_ui/web_ui_favicon_source.cc +++ /dev/null @@ -1,84 +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/web_ui_favicon_source.h" - -#include "base/callback.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/common/url_constants.h" -#include "grit/app_resources.h" -#include "ui/base/resource/resource_bundle.h" - -WebUIFavIconSource::WebUIFavIconSource(Profile* profile) - : DataSource(chrome::kChromeUIFavIconHost, MessageLoop::current()), - profile_(profile->GetOriginalProfile()) { -} - -WebUIFavIconSource::~WebUIFavIconSource() { -} - -void WebUIFavIconSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - FaviconService* favicon_service = - profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); - if (favicon_service) { - FaviconService::Handle handle; - if (path.empty()) { - SendDefaultResponse(request_id); - return; - } - - if (path.size() > 8 && path.substr(0, 8) == "iconurl/") { - handle = favicon_service->GetFavicon( - GURL(path.substr(8)), - &cancelable_consumer_, - NewCallback(this, &WebUIFavIconSource::OnFavIconDataAvailable)); - } else { - handle = favicon_service->GetFaviconForURL( - GURL(path), - &cancelable_consumer_, - NewCallback(this, &WebUIFavIconSource::OnFavIconDataAvailable)); - } - // Attach the ChromeURLDataManager request ID to the history request. - cancelable_consumer_.SetClientData(favicon_service, handle, request_id); - } else { - SendResponse(request_id, NULL); - } -} - -std::string WebUIFavIconSource::GetMimeType(const std::string&) const { - // We need to explicitly return a mime type, otherwise if the user tries to - // drag the image they get no extension. - return "image/png"; -} - -void WebUIFavIconSource::OnFavIconDataAvailable( - FaviconService::Handle request_handle, - bool know_favicon, - scoped_refptr<RefCountedMemory> data, - bool expired, - GURL icon_url) { - FaviconService* favicon_service = - profile_->GetFaviconService(Profile::EXPLICIT_ACCESS); - int request_id = cancelable_consumer_.GetClientData(favicon_service, - request_handle); - - if (know_favicon && data.get() && data->size()) { - // Forward the data along to the networking system. - SendResponse(request_id, data); - } else { - SendDefaultResponse(request_id); - } -} - -void WebUIFavIconSource::SendDefaultResponse(int request_id) { - if (!default_favicon_.get()) { - default_favicon_ = - ResourceBundle::GetSharedInstance().LoadDataResourceBytes( - IDR_DEFAULT_FAVICON); - } - - SendResponse(request_id, default_favicon_); -} diff --git a/chrome/browser/dom_ui/web_ui_favicon_source.h b/chrome/browser/dom_ui/web_ui_favicon_source.h deleted file mode 100644 index 1808128..0000000 --- a/chrome/browser/dom_ui/web_ui_favicon_source.h +++ /dev/null @@ -1,56 +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_WEB_UI_FAVICON_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_FAVICON_SOURCE_H_ -#pragma once - -#include <string> - -#include "base/basictypes.h" -#include "base/ref_counted.h" -#include "chrome/browser/favicon_service.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" - -class GURL; -class Profile; - -// FavIconSource is the gateway between network-level chrome: -// requests for favicons and the history backend that serves these. -class WebUIFavIconSource : public ChromeURLDataManager::DataSource { - public: - explicit WebUIFavIconSource(Profile* profile); - - // 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; - - // Called when favicon data is available from the history backend. - void OnFavIconDataAvailable(FaviconService::Handle request_handle, - bool know_favicon, - scoped_refptr<RefCountedMemory> data, - bool expired, - GURL url); - - private: - // Sends the default favicon. - void SendDefaultResponse(int request_id); - - virtual ~WebUIFavIconSource(); - - Profile* profile_; - CancelableRequestConsumerT<int, 0> cancelable_consumer_; - - // Raw PNG representation of the favicon to show when the favicon - // database doesn't have a favicon for a webpage. - scoped_refptr<RefCountedMemory> default_favicon_; - - DISALLOW_COPY_AND_ASSIGN(WebUIFavIconSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_FAVICON_SOURCE_H_ diff --git a/chrome/browser/dom_ui/web_ui_handler_browsertest.cc b/chrome/browser/dom_ui/web_ui_handler_browsertest.cc deleted file mode 100644 index de15805..0000000 --- a/chrome/browser/dom_ui/web_ui_handler_browsertest.cc +++ /dev/null @@ -1,41 +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/web_ui_handler_browsertest.h" - -#include "base/utf_string_conversions.h" -#include "chrome/browser/renderer_host/render_view_host.h" -#include "chrome/test/ui_test_utils.h" - -bool WebUIHandlerBrowserTest::Execute(const std::string& js_test) { - web_ui_->GetRenderViewHost()->ExecuteJavascriptInWebFrame( - string16(), UTF8ToUTF16(js_test)); - return WaitForResult(); -} - -void WebUIHandlerBrowserTest::HandlePass(const ListValue* args) { - test_succeeded_ = true; - if (is_waiting_) - MessageLoopForUI::current()->Quit(); -} - -void WebUIHandlerBrowserTest::HandleFail(const ListValue* args) { - test_succeeded_ = false; - if (is_waiting_) - MessageLoopForUI::current()->Quit(); -} - -void WebUIHandlerBrowserTest::RegisterMessages() { - web_ui_->RegisterMessageCallback("Pass", - NewCallback(this, &WebUIHandlerBrowserTest::HandlePass)); - web_ui_->RegisterMessageCallback("Fail", - NewCallback(this, &WebUIHandlerBrowserTest::HandleFail)); -} - -bool WebUIHandlerBrowserTest::WaitForResult() { - is_waiting_ = true; - ui_test_utils::RunMessageLoop(); - is_waiting_ = false; - return test_succeeded_; -} diff --git a/chrome/browser/dom_ui/web_ui_handler_browsertest.h b/chrome/browser/dom_ui/web_ui_handler_browsertest.h deleted file mode 100644 index 36bae01..0000000 --- a/chrome/browser/dom_ui/web_ui_handler_browsertest.h +++ /dev/null @@ -1,40 +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_WEB_UI_HANDLER_BROWSERTEST_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_HANDLER_BROWSERTEST_H_ -#pragma once - -#include <string> - -#include "chrome/browser/webui/web_ui.h" - -// This class registers test framework specific handlers on WebUI objects. -class WebUIHandlerBrowserTest : public WebUIMessageHandler { - public: - // Executes a string of javascript. Returns pass fail. - bool Execute(const std::string& js_test); - - protected: - // WebUI handlers which deliver results to any waiting message loops. - // |args| is currently ignored. - void HandlePass(const ListValue* args); - void HandleFail(const ListValue* args); - - // WebUIMessageHandler overrides. - // Add test handlers to the current WebUI object. - virtual void RegisterMessages(); - - private: - // Runs a message loop until test finishes. Returns the result of the test. - bool WaitForResult(); - - // Pass fail result of current tests. - bool test_succeeded_; - - // Waiting for a test to finish. - bool is_waiting_; -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_HANDLER_BROWSERTEST_H_ diff --git a/chrome/browser/dom_ui/web_ui_screenshot_source.cc b/chrome/browser/dom_ui/web_ui_screenshot_source.cc deleted file mode 100644 index 84b78e1..0000000 --- a/chrome/browser/dom_ui/web_ui_screenshot_source.cc +++ /dev/null @@ -1,118 +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/web_ui_screenshot_source.h" - -#include "base/file_util.h" -#include "base/path_service.h" -#include "base/ref_counted_memory.h" -#include "base/synchronization/waitable_event.h" -#include "base/task.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/common/chrome_paths.h" -#include "chrome/common/url_constants.h" - -static const char kCurrentScreenshot[] = "current"; -#if defined(OS_CHROMEOS) -static const char kSavedScreenshots[] = "saved/"; -#endif - -static const char kScreenshotsRelativePath[] = "/Screenshots/"; - -#if defined(OS_CHROMEOS) -// Read the file from the screenshots directory into the read_bytes vector. -void ReadScreenshot(const std::string& filename, - std::vector<unsigned char>* read_bytes, - base::WaitableEvent* read_complete) { - read_bytes->clear(); - - FilePath fileshelf_path; - if (!PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &fileshelf_path)) { - read_complete->Signal(); - return; - } - - FilePath file(fileshelf_path.value() + std::string(kScreenshotsRelativePath) + - filename); - - int64 file_size = 0; - if (!file_util::GetFileSize(file, &file_size)) { - read_complete->Signal(); - return; - } - - // expand vector to file size - read_bytes->resize(file_size); - // read file into the vector - int bytes_read = 0; - if (!(bytes_read = file_util::ReadFile(file, - reinterpret_cast<char*>( - &read_bytes->front()), - static_cast<int>(file_size)))) - read_bytes->clear(); - - // We're done, if successful, read_bytes will have the data - // otherwise, it'll be empty. - read_complete->Signal(); -} - -// Get a saved screenshot - read on the FILE thread. -std::vector<unsigned char> GetSavedScreenshot(std::string filename) { - base::WaitableEvent read_complete(true, false); - std::vector<unsigned char> bytes; - BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, - NewRunnableFunction(&ReadScreenshot, filename, - &bytes, &read_complete)); - read_complete.Wait(); - return bytes; -} -#endif - -std::vector<unsigned char> WebUIScreenshotSource::GetScreenshot( - const std::string& full_path) { - // Strip the query param value - we only use it as a hack to ensure our - // image gets reloaded instead of being pulled from the browser cache - std::string path = full_path.substr(0, full_path.find_first_of("?")); - if (path == kCurrentScreenshot) { - return current_screenshot_; -#if defined(OS_CHROMEOS) - } else if (path.compare(0, strlen(kSavedScreenshots), - kSavedScreenshots) == 0) { - // Split the saved screenshot filename from the path - std::string filename = path.substr(strlen(kSavedScreenshots)); - - return GetSavedScreenshot(filename); -#endif - } else { - std::vector<unsigned char> ret; - // TODO(rkc): Weird vc bug, return std::vector<unsigned char>() causes - // the object assigned to the return value of this function magically - // change it's address 0x0; look into this eventually. - return ret; - } -} - -WebUIScreenshotSource::WebUIScreenshotSource( - std::vector<unsigned char>* current_screenshot) - : DataSource(chrome::kChromeUIScreenshotPath, MessageLoop::current()) { - // Setup the last screenshot taken. - if (current_screenshot) - current_screenshot_ = *current_screenshot; - else - current_screenshot_.clear(); -} - -WebUIScreenshotSource::~WebUIScreenshotSource() {} - -void WebUIScreenshotSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - SendResponse(request_id, new RefCountedBytes(GetScreenshot(path))); -} - -std::string WebUIScreenshotSource::GetMimeType(const std::string&) const { - // We need to explicitly return a mime type, otherwise if the user tries to - // drag the image they get no extension. - return "image/png"; -} diff --git a/chrome/browser/dom_ui/web_ui_screenshot_source.h b/chrome/browser/dom_ui/web_ui_screenshot_source.h deleted file mode 100644 index e5955c0f..0000000 --- a/chrome/browser/dom_ui/web_ui_screenshot_source.h +++ /dev/null @@ -1,39 +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_WEB_UI_SCREENSHOT_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_SCREENSHOT_SOURCE_H_ - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" - -// ScreenshotSource is the data source that serves screenshots (saved -// or current) to the bug report html ui -class WebUIScreenshotSource : public ChromeURLDataManager::DataSource { - public: - explicit WebUIScreenshotSource( - std::vector<unsigned char>* current_screenshot); - - // 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; - - std::vector<unsigned char> GetScreenshot(const std::string& path); - - private: - virtual ~WebUIScreenshotSource(); - - std::vector<unsigned char> current_screenshot_; - - DISALLOW_COPY_AND_ASSIGN(WebUIScreenshotSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_SCREENSHOT_SOURCE_H_ diff --git a/chrome/browser/dom_ui/web_ui_theme_source.cc b/chrome/browser/dom_ui/web_ui_theme_source.cc deleted file mode 100644 index b91ab6a..0000000 --- a/chrome/browser/dom_ui/web_ui_theme_source.cc +++ /dev/null @@ -1,113 +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/web_ui_theme_source.h" - -#include "base/message_loop.h" -#include "base/ref_counted_memory.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/ntp_resource_cache.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/resources_util.h" -#include "chrome/browser/themes/browser_theme_provider.h" -#include "chrome/common/url_constants.h" -#include "googleurl/src/gurl.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/theme_provider.h" - -// use a resource map rather than hard-coded strings. -static const char* kNewTabCSSPath = "css/newtab.css"; -static const char* kNewIncognitoTabCSSPath = "css/newincognitotab.css"; - -static std::string StripQueryParams(const std::string& path) { - GURL path_url = GURL(std::string(chrome::kChromeUIScheme) + "://" + - std::string(chrome::kChromeUIThemePath) + "/" + path); - return path_url.path().substr(1); // path() always includes a leading '/'. -} - -//////////////////////////////////////////////////////////////////////////////// -// WebUIThemeSource, public: - -WebUIThemeSource::WebUIThemeSource(Profile* profile) - : DataSource(chrome::kChromeUIThemePath, MessageLoop::current()), - profile_(profile->GetOriginalProfile()) { - css_bytes_ = profile_->GetNTPResourceCache()->GetNewTabCSS( - profile->IsOffTheRecord()); -} - -WebUIThemeSource::~WebUIThemeSource() { -} - -void WebUIThemeSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - // Our path may include cachebuster arguments, so trim them off. - std::string uncached_path = StripQueryParams(path); - - if (uncached_path == kNewTabCSSPath || - uncached_path == kNewIncognitoTabCSSPath) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - DCHECK((uncached_path == kNewTabCSSPath && !is_off_the_record) || - (uncached_path == kNewIncognitoTabCSSPath && is_off_the_record)); - - SendResponse(request_id, css_bytes_); - return; - } else { - int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path); - if (resource_id != -1) { - SendThemeBitmap(request_id, resource_id); - return; - } - } - // We don't have any data to send back. - SendResponse(request_id, NULL); -} - -std::string WebUIThemeSource::GetMimeType(const std::string& path) const { - std::string uncached_path = StripQueryParams(path); - - if (uncached_path == kNewTabCSSPath || - uncached_path == kNewIncognitoTabCSSPath) { - return "text/css"; - } - - return "image/png"; -} - -MessageLoop* WebUIThemeSource::MessageLoopForRequestPath( - const std::string& path) const { - std::string uncached_path = StripQueryParams(path); - - if (uncached_path == kNewTabCSSPath || - uncached_path == kNewIncognitoTabCSSPath) { - // We generated and cached this when we initialized the object. We don't - // have to go back to the UI thread to send the data. - return NULL; - } - - // If it's not a themeable image, we don't need to go to the UI thread. - int resource_id = ResourcesUtil::GetThemeResourceId(uncached_path); - if (!BrowserThemeProvider::IsThemeableImage(resource_id)) - return NULL; - - return DataSource::MessageLoopForRequestPath(path); -} - -//////////////////////////////////////////////////////////////////////////////// -// WebUIThemeSource, private: - -void WebUIThemeSource::SendThemeBitmap(int request_id, int resource_id) { - if (BrowserThemeProvider::IsThemeableImage(resource_id)) { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); - ui::ThemeProvider* tp = profile_->GetThemeProvider(); - DCHECK(tp); - - scoped_refptr<RefCountedMemory> image_data(tp->GetRawData(resource_id)); - SendResponse(request_id, image_data); - } else { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); - const ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - SendResponse(request_id, rb.LoadDataResourceBytes(resource_id)); - } -} diff --git a/chrome/browser/dom_ui/web_ui_theme_source.h b/chrome/browser/dom_ui/web_ui_theme_source.h deleted file mode 100644 index 2b66635..0000000 --- a/chrome/browser/dom_ui/web_ui_theme_source.h +++ /dev/null @@ -1,46 +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_WEB_UI_THEME_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_THEME_SOURCE_H_ -#pragma once - -#include <string> - -#include "chrome/browser/webui/chrome_url_data_manager.h" - -class Profile; -class RefCountedBytes; - -class WebUIThemeSource : public ChromeURLDataManager::DataSource { - public: - explicit WebUIThemeSource(Profile* profile); - - // 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& path) const; - - // Used to tell ChromeURLDataManager which thread to handle the request on. - virtual MessageLoop* MessageLoopForRequestPath(const std::string& path) const; - - protected: - virtual ~WebUIThemeSource(); - - private: - // Fetch and send the theme bitmap. - void SendThemeBitmap(int request_id, int resource_id); - - // The original profile (never an OTR profile). - Profile* profile_; - - // We grab the CSS early so we don't have to go back to the UI thread later. - scoped_refptr<RefCountedBytes> css_bytes_; - - DISALLOW_COPY_AND_ASSIGN(WebUIThemeSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_THEME_SOURCE_H_ diff --git a/chrome/browser/dom_ui/web_ui_theme_source_unittest.cc b/chrome/browser/dom_ui/web_ui_theme_source_unittest.cc deleted file mode 100644 index 5d9b3cd..0000000 --- a/chrome/browser/dom_ui/web_ui_theme_source_unittest.cc +++ /dev/null @@ -1,100 +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 "base/ref_counted_memory.h" -#include "chrome/browser/browser_thread.h" -#include "chrome/browser/dom_ui/web_ui_theme_source.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/themes/browser_theme_provider.h" -#include "chrome/common/url_constants.h" -#include "chrome/test/testing_profile.h" -#include "grit/theme_resources.h" -#include "testing/gtest/include/gtest/gtest.h" - -// A mock ThemeSource (so we can override SendResponse to get at its data). -class MockThemeSource : public WebUIThemeSource { - public: - explicit MockThemeSource(Profile* profile) - : WebUIThemeSource(profile), - result_request_id_(-1), - result_data_size_(0) { - } - - virtual void SendResponse(int request_id, RefCountedMemory* data) { - result_data_size_ = data ? data->size() : 0; - result_request_id_ = request_id; - } - - int result_request_id_; - size_t result_data_size_; - - private: - ~MockThemeSource() {} -}; - -class WebUISourcesTest : public testing::Test { - public: - WebUISourcesTest() : ui_thread_(BrowserThread::UI, MessageLoop::current()) {} - - TestingProfile* profile() const { return profile_.get(); } - MockThemeSource* theme_source() const { return theme_source_.get(); } - private: - virtual void SetUp() { - profile_.reset(new TestingProfile()); - profile_->InitThemes(); - theme_source_ = new MockThemeSource(profile_.get()); - } - - virtual void TearDown() { - theme_source_ = NULL; - profile_.reset(NULL); - } - - MessageLoop loop_; - BrowserThread ui_thread_; - - scoped_ptr<TestingProfile> profile_; - scoped_refptr<MockThemeSource> theme_source_; -}; - -TEST_F(WebUISourcesTest, ThemeSourceMimeTypes) { - EXPECT_EQ(theme_source()->GetMimeType("css/newtab.css"), "text/css"); - EXPECT_EQ(theme_source()->GetMimeType("css/newtab.css?foo"), "text/css"); - EXPECT_EQ(theme_source()->GetMimeType("WRONGURL"), "image/png"); -} - -TEST_F(WebUISourcesTest, ThemeSourceImages) { - // We used to PNGEncode the images ourselves, but encoder differences - // invalidated that. We now just check that the image exists. - theme_source()->StartDataRequest("IDR_THEME_FRAME_INCOGNITO", true, 1); - size_t min = 0; - EXPECT_EQ(theme_source()->result_request_id_, 1); - EXPECT_GT(theme_source()->result_data_size_, min); - - theme_source()->StartDataRequest("IDR_THEME_TOOLBAR", true, 2); - EXPECT_EQ(theme_source()->result_request_id_, 2); - EXPECT_GT(theme_source()->result_data_size_, min); -} - -TEST_F(WebUISourcesTest, ThemeSourceCSS) { - BrowserThread io_thread(BrowserThread::IO, MessageLoop::current()); - // Generating the test data for the NTP CSS would just involve copying the - // method, or being super brittle and hard-coding the result (requiring - // an update to the unittest every time the CSS template changes), so we - // just check for a successful request and data that is non-null. - size_t empty_size = 0; - - theme_source()->StartDataRequest("css/newtab.css", false, 1); - EXPECT_EQ(theme_source()->result_request_id_, 1); - EXPECT_NE(theme_source()->result_data_size_, empty_size); - - theme_source()->StartDataRequest("css/newtab.css?pie", false, 3); - EXPECT_EQ(theme_source()->result_request_id_, 3); - EXPECT_NE(theme_source()->result_data_size_, empty_size); - - // Check that we send NULL back when we can't find what we're looking for. - theme_source()->StartDataRequest("css/WRONGURL", false, 7); - EXPECT_EQ(theme_source()->result_request_id_, 7); - EXPECT_EQ(theme_source()->result_data_size_, empty_size); -} diff --git a/chrome/browser/dom_ui/web_ui_thumbnail_source.cc b/chrome/browser/dom_ui/web_ui_thumbnail_source.cc deleted file mode 100644 index 0f28b30..0000000 --- a/chrome/browser/dom_ui/web_ui_thumbnail_source.cc +++ /dev/null @@ -1,56 +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/web_ui_thumbnail_source.h" - -#include "base/callback.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/history/top_sites.h" -#include "chrome/common/url_constants.h" -#include "googleurl/src/gurl.h" -#include "grit/theme_resources.h" -#include "ui/base/resource/resource_bundle.h" - -WebUIThumbnailSource::WebUIThumbnailSource(Profile* profile) - : DataSource(chrome::kChromeUIThumbnailPath, MessageLoop::current()), - // Set TopSites now as Profile isn't thread safe. - top_sites_(profile->GetTopSites()) { -} - -WebUIThumbnailSource::~WebUIThumbnailSource() { -} - -void WebUIThumbnailSource::StartDataRequest(const std::string& path, - bool is_off_the_record, - int request_id) { - scoped_refptr<RefCountedBytes> data; - if (top_sites_->GetPageThumbnail(GURL(path), &data)) { - // We have the thumbnail. - SendResponse(request_id, data.get()); - } else { - SendDefaultThumbnail(request_id); - } -} - -std::string WebUIThumbnailSource::GetMimeType(const std::string&) const { - // We need to explicitly return a mime type, otherwise if the user tries to - // drag the image they get no extension. - return "image/png"; -} - -MessageLoop* WebUIThumbnailSource::MessageLoopForRequestPath( - const std::string& path) const { - // TopSites can be accessed from the IO thread. - return top_sites_.get() ? NULL : DataSource::MessageLoopForRequestPath(path); -} - -void WebUIThumbnailSource::SendDefaultThumbnail(int request_id) { - // Use placeholder thumbnail. - if (!default_thumbnail_.get()) { - default_thumbnail_ = - ResourceBundle::GetSharedInstance().LoadDataResourceBytes( - IDR_DEFAULT_THUMBNAIL); - } - SendResponse(request_id, default_thumbnail_); -} diff --git a/chrome/browser/dom_ui/web_ui_thumbnail_source.h b/chrome/browser/dom_ui/web_ui_thumbnail_source.h deleted file mode 100644 index 82dd36d..0000000 --- a/chrome/browser/dom_ui/web_ui_thumbnail_source.h +++ /dev/null @@ -1,54 +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_WEB_UI_THUMBNAIL_SOURCE_H_ -#define CHROME_BROWSER_DOM_UI_WEB_UI_THUMBNAIL_SOURCE_H_ -#pragma once - -#include <string> - -#include "base/basictypes.h" -#include "base/ref_counted.h" -#include "base/ref_counted_memory.h" -#include "chrome/browser/webui/chrome_url_data_manager.h" - -class Profile; - -namespace history { -class TopSites; -} - -// ThumbnailSource is the gateway between network-level chrome: requests for -// thumbnails and the history/top-sites backend that serves these. -class WebUIThumbnailSource : public ChromeURLDataManager::DataSource { - public: - explicit WebUIThumbnailSource(Profile* profile); - - // 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& path) const; - - virtual MessageLoop* MessageLoopForRequestPath(const std::string& path) const; - - private: - virtual ~WebUIThumbnailSource(); - - // Send the default thumbnail when we are missing a real one. - void SendDefaultThumbnail(int request_id); - - // Raw PNG representation of the thumbnail to show when the thumbnail - // database doesn't have a thumbnail for a webpage. - scoped_refptr<RefCountedMemory> default_thumbnail_; - - // TopSites. - scoped_refptr<history::TopSites> top_sites_; - - DISALLOW_COPY_AND_ASSIGN(WebUIThumbnailSource); -}; - -#endif // CHROME_BROWSER_DOM_UI_WEB_UI_THUMBNAIL_SOURCE_H_ |