<commit_before>// 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/chromeos/media/media_player.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chromeos/extensions/media_player_event_router.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/file_manager_util.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/user_metrics.h"
#include "content/common/url_fetcher.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/panel_browser_view.h"
#endif

static const char* kMediaPlayerAppName = "mediaplayer";
static const int kPopupLeft = 0;
static const int kPopupTop = 0;
static const int kPopupWidth = 350;
static const int kPopupHeight = 300;

const MediaPlayer::UrlVector& MediaPlayer::GetPlaylist() const {
  return current_playlist_;
}

int MediaPlayer::GetPlaylistPosition() const {
  return current_position_;
}

////////////////////////////////////////////////////////////////////////////////
//
// Mediaplayer
//
////////////////////////////////////////////////////////////////////////////////

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(MediaPlayer);

MediaPlayer::~MediaPlayer() {
}

// static
MediaPlayer* MediaPlayer::GetInstance() {
  return Singleton<MediaPlayer>::get();
}

void MediaPlayer::EnqueueMediaFile(Profile* profile, const FilePath& file_path,
                                   Browser* creator) {
  GURL url;
  if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
                                                   GetOriginUrl(), &url)) {
  }
  EnqueueMediaFileUrl(url, creator);
}

void MediaPlayer::EnqueueMediaFileUrl(const GURL& url, Browser* creator) {
  if (mediaplayer_browser_ == NULL) {
    PopupMediaPlayer(creator);
  }
  EnqueueMediaFileUrl(url);
}

void MediaPlayer::EnqueueMediaFileUrl(const GURL& url) {
  current_playlist_.push_back(MediaUrl(url));
  NotifyPlaylistChanged();
}

void MediaPlayer::ForcePlayMediaFile(Profile* profile,
                                     const FilePath& file_path,
                                     Browser* creator) {
  GURL url;
  if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
                                                   GetOriginUrl(), &url)) {
    return;
  }
  ForcePlayMediaURL(url, creator);
}

void MediaPlayer::ForcePlayMediaURL(const GURL& url, Browser* creator) {
  if (mediaplayer_browser_ == NULL) {
    PopupMediaPlayer(creator);
  }
  current_playlist_.clear();
  current_playlist_.push_back(MediaUrl(url));
  current_position_ = current_playlist_.size() - 1;
  pending_playback_request_ = true;
  NotifyPlaylistChanged();
}

void MediaPlayer::TogglePlaylistWindowVisible() {
  if (playlist_browser_) {
    ClosePlaylistWindow();
  } else {
    ShowPlaylistWindow();
  }
}

void MediaPlayer::ShowPlaylistWindow() {
  if (playlist_browser_ == NULL) {
    PopupPlaylist(NULL);
  }
}

void MediaPlayer::ClosePlaylistWindow() {
  if (playlist_browser_ != NULL) {
    playlist_browser_->window()->Close();
  }
}

void MediaPlayer::SetPlaylistPosition(int position) {
  const int playlist_size = current_playlist_.size();
  if (current_position_ < 0 || current_position_ > playlist_size)
    position = current_playlist_.size();
  if (current_position_ != position) {
    current_position_ = position;
    NotifyPlaylistChanged();
  }
}

void MediaPlayer::SetPlaybackError(GURL const& url) {
  for (size_t x = 0; x < current_playlist_.size(); x++) {
    if (current_playlist_[x].url == url) {
      current_playlist_[x].haderror = true;
    }
  }
  NotifyPlaylistChanged();
}

void MediaPlayer::Observe(int type,
                          const NotificationSource& source,
                          const NotificationDetails& details) {
  DCHECK(type == chrome::NOTIFICATION_BROWSER_CLOSING);
  registrar_.Remove(this,
                    chrome::NOTIFICATION_BROWSER_CLOSING,
                    source);
  if (Source<Browser>(source).ptr() == mediaplayer_browser_) {
    mediaplayer_browser_ = NULL;
  } else if (Source<Browser>(source).ptr() == playlist_browser_) {
    playlist_browser_ = NULL;
  }
}

void MediaPlayer::NotifyPlaylistChanged() {
  ExtensionMediaPlayerEventRouter::GetInstance()->NotifyPlaylistChanged();
}

bool MediaPlayer::GetPendingPlayRequestAndReset() {
  bool result = pending_playback_request_;
  pending_playback_request_ = false;
  return result;
}

void MediaPlayer::SetPlaybackRequest() {
  pending_playback_request_ = true;
}

void MediaPlayer::ToggleFullscreen() {
  if (mediaplayer_browser_) {
    mediaplayer_browser_->ToggleFullscreenMode();
  }
}

void MediaPlayer::PopupPlaylist(Browser* creator) {
  Profile* profile = BrowserList::GetLastActive()->profile();
  playlist_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
                                            kMediaPlayerAppName,
                                            gfx::Rect(),
                                            profile);
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_CLOSING,
                 Source<Browser>(playlist_browser_));
  playlist_browser_->AddSelectedTabWithURL(GetMediaplayerPlaylistUrl(),
                                           PageTransition::LINK);
  playlist_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
                                                   kPopupTop,
                                                   kPopupWidth,
                                                   kPopupHeight));
  playlist_browser_->window()->Show();
}

void MediaPlayer::PopupMediaPlayer(Browser* creator) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(this, &MediaPlayer::PopupMediaPlayer,
                          static_cast<Browser*>(NULL)));
    return;
  }
  Profile* profile = BrowserList::GetLastActive()->profile();
  mediaplayer_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
                                               kMediaPlayerAppName,
                                               gfx::Rect(),
                                               profile);
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_CLOSING,
                 Source<Browser>(mediaplayer_browser_));

#if defined(OS_CHROMEOS)
  // Since we are on chromeos, popups should be a PanelBrowserView,
  // so we can just cast it.
  if (creator) {
    chromeos::PanelBrowserView* creatorview =
        static_cast<chromeos::PanelBrowserView*>(creator->window());
    chromeos::PanelBrowserView* view =
        static_cast<chromeos::PanelBrowserView*>(
            mediaplayer_browser_->window());
    view->SetCreatorView(creatorview);
  }
#endif
  mediaplayer_browser_->AddSelectedTabWithURL(GetMediaPlayerUrl(),
                                              PageTransition::LINK);
  mediaplayer_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
                                                      kPopupTop,
                                                      kPopupWidth,
                                                      kPopupHeight));
  mediaplayer_browser_->window()->Show();
}

net::URLRequestJob* MediaPlayer::MaybeIntercept(net::URLRequest* request) {
  // Don't attempt to intercept here as we want to wait until the mime
  // type is fully determined.
  return NULL;
}

// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
  "audio/mpeg",
  "video/mp4",
  "audio/mp3"
};

net::URLRequestJob* MediaPlayer::MaybeInterceptResponse(
    net::URLRequest* request) {
  // Do not intercept this request if it is a download.
  if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
    return NULL;
  }

  std::string mime_type;
  request->GetMimeType(&mime_type);
  // If it is in our list of known URLs, enqueue the url then
  // Cancel the request so the mediaplayer can handle it when
  // it hits it in the playlist.
  if (supported_mime_types_.find(mime_type) != supported_mime_types_.end()) {
    if (request->referrer() != chrome::kChromeUIMediaplayerURL &&
        !request->referrer().empty()) {
      EnqueueMediaFileUrl(request->url(), NULL);
      request->Cancel();
    }
  }
  return NULL;
}

GURL MediaPlayer::GetOriginUrl() const {
  return FileManagerUtil::GetMediaPlayerUrl().GetOrigin();
}

GURL MediaPlayer::GetMediaplayerPlaylistUrl() const {
  return FileManagerUtil::GetMediaPlayerPlaylistUrl();
}

GURL MediaPlayer::GetMediaPlayerUrl() const {
  return FileManagerUtil::GetMediaPlayerUrl();
}

MediaPlayer::MediaPlayer()
    : current_position_(0),
      pending_playback_request_(false),
      playlist_browser_(NULL),
      mediaplayer_browser_(NULL) {
  for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
    supported_mime_types_.insert(supported_mime_type_list[i]);
  }
};
<commit_msg>Fixing: Media file doesn't play after closing the media player using ctrl + w<commit_after>// 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/chromeos/media/media_player.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/string_piece.h"
#include "base/string_util.h"
#include "base/threading/thread.h"
#include "base/time.h"
#include "base/values.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/chromeos/extensions/media_player_event_router.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/extensions/file_manager_util.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/webui/favicon_source.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/jstemplate_builder.h"
#include "chrome/common/time_format.h"
#include "chrome/common/url_constants.h"
#include "content/browser/browser_thread.h"
#include "content/browser/download/download_manager.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/user_metrics.h"
#include "content/common/url_fetcher.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_job.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/frame/panel_browser_view.h"
#endif

static const char* kMediaPlayerAppName = "mediaplayer";
static const int kPopupLeft = 0;
static const int kPopupTop = 0;
static const int kPopupWidth = 350;
static const int kPopupHeight = 300;

const MediaPlayer::UrlVector& MediaPlayer::GetPlaylist() const {
  return current_playlist_;
}

int MediaPlayer::GetPlaylistPosition() const {
  return current_position_;
}

////////////////////////////////////////////////////////////////////////////////
//
// Mediaplayer
//
////////////////////////////////////////////////////////////////////////////////

// Allows InvokeLater without adding refcounting. This class is a Singleton and
// won't be deleted until it's last InvokeLater is run.
DISABLE_RUNNABLE_METHOD_REFCOUNT(MediaPlayer);

MediaPlayer::~MediaPlayer() {
}

// static
MediaPlayer* MediaPlayer::GetInstance() {
  return Singleton<MediaPlayer>::get();
}

void MediaPlayer::EnqueueMediaFile(Profile* profile, const FilePath& file_path,
                                   Browser* creator) {
  GURL url;
  if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
                                                   GetOriginUrl(), &url)) {
  }
  EnqueueMediaFileUrl(url, creator);
}

void MediaPlayer::EnqueueMediaFileUrl(const GURL& url, Browser* creator) {
  if (mediaplayer_browser_ == NULL) {
    PopupMediaPlayer(creator);
  }
  EnqueueMediaFileUrl(url);
}

void MediaPlayer::EnqueueMediaFileUrl(const GURL& url) {
  current_playlist_.push_back(MediaUrl(url));
  NotifyPlaylistChanged();
}

void MediaPlayer::ForcePlayMediaFile(Profile* profile,
                                     const FilePath& file_path,
                                     Browser* creator) {
  GURL url;
  if (!FileManagerUtil::ConvertFileToFileSystemUrl(profile, file_path,
                                                   GetOriginUrl(), &url)) {
    return;
  }
  ForcePlayMediaURL(url, creator);
}

void MediaPlayer::ForcePlayMediaURL(const GURL& url, Browser* creator) {
  if (mediaplayer_browser_ == NULL) {
    PopupMediaPlayer(creator);
  }
  current_playlist_.clear();
  current_playlist_.push_back(MediaUrl(url));
  current_position_ = current_playlist_.size() - 1;
  pending_playback_request_ = true;
  NotifyPlaylistChanged();
}

void MediaPlayer::TogglePlaylistWindowVisible() {
  if (playlist_browser_) {
    ClosePlaylistWindow();
  } else {
    ShowPlaylistWindow();
  }
}

void MediaPlayer::ShowPlaylistWindow() {
  if (playlist_browser_ == NULL) {
    PopupPlaylist(NULL);
  }
}

void MediaPlayer::ClosePlaylistWindow() {
  if (playlist_browser_ != NULL) {
    playlist_browser_->window()->Close();
  }
}

void MediaPlayer::SetPlaylistPosition(int position) {
  const int playlist_size = current_playlist_.size();
  if (current_position_ < 0 || current_position_ > playlist_size)
    position = current_playlist_.size();
  if (current_position_ != position) {
    current_position_ = position;
    NotifyPlaylistChanged();
  }
}

void MediaPlayer::SetPlaybackError(GURL const& url) {
  for (size_t x = 0; x < current_playlist_.size(); x++) {
    if (current_playlist_[x].url == url) {
      current_playlist_[x].haderror = true;
    }
  }
  NotifyPlaylistChanged();
}

void MediaPlayer::Observe(int type,
                          const NotificationSource& source,
                          const NotificationDetails& details) {
  DCHECK(type == chrome::NOTIFICATION_BROWSER_CLOSED);
  registrar_.Remove(this,
                    chrome::NOTIFICATION_BROWSER_CLOSED,
                    source);
  if (Source<Browser>(source).ptr() == mediaplayer_browser_) {
    mediaplayer_browser_ = NULL;
  } else if (Source<Browser>(source).ptr() == playlist_browser_) {
    playlist_browser_ = NULL;
  }
}

void MediaPlayer::NotifyPlaylistChanged() {
  ExtensionMediaPlayerEventRouter::GetInstance()->NotifyPlaylistChanged();
}

bool MediaPlayer::GetPendingPlayRequestAndReset() {
  bool result = pending_playback_request_;
  pending_playback_request_ = false;
  return result;
}

void MediaPlayer::SetPlaybackRequest() {
  pending_playback_request_ = true;
}

void MediaPlayer::ToggleFullscreen() {
  if (mediaplayer_browser_) {
    mediaplayer_browser_->ToggleFullscreenMode();
  }
}

void MediaPlayer::PopupPlaylist(Browser* creator) {
  Profile* profile = BrowserList::GetLastActive()->profile();
  playlist_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
                                            kMediaPlayerAppName,
                                            gfx::Rect(),
                                            profile);
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_CLOSED,
                 Source<Browser>(playlist_browser_));
  playlist_browser_->AddSelectedTabWithURL(GetMediaplayerPlaylistUrl(),
                                           PageTransition::LINK);
  playlist_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
                                                   kPopupTop,
                                                   kPopupWidth,
                                                   kPopupHeight));
  playlist_browser_->window()->Show();
}

void MediaPlayer::PopupMediaPlayer(Browser* creator) {
  if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
    BrowserThread::PostTask(
        BrowserThread::UI, FROM_HERE,
        NewRunnableMethod(this, &MediaPlayer::PopupMediaPlayer,
                          static_cast<Browser*>(NULL)));
    return;
  }
  Profile* profile = BrowserList::GetLastActive()->profile();
  mediaplayer_browser_ = Browser::CreateForApp(Browser::TYPE_PANEL,
                                               kMediaPlayerAppName,
                                               gfx::Rect(),
                                               profile);
  registrar_.Add(this,
                 chrome::NOTIFICATION_BROWSER_CLOSED,
                 Source<Browser>(mediaplayer_browser_));

#if defined(OS_CHROMEOS)
  // Since we are on chromeos, popups should be a PanelBrowserView,
  // so we can just cast it.
  if (creator) {
    chromeos::PanelBrowserView* creatorview =
        static_cast<chromeos::PanelBrowserView*>(creator->window());
    chromeos::PanelBrowserView* view =
        static_cast<chromeos::PanelBrowserView*>(
            mediaplayer_browser_->window());
    view->SetCreatorView(creatorview);
  }
#endif
  mediaplayer_browser_->AddSelectedTabWithURL(GetMediaPlayerUrl(),
                                              PageTransition::LINK);
  mediaplayer_browser_->window()->SetBounds(gfx::Rect(kPopupLeft,
                                                      kPopupTop,
                                                      kPopupWidth,
                                                      kPopupHeight));
  mediaplayer_browser_->window()->Show();
}

net::URLRequestJob* MediaPlayer::MaybeIntercept(net::URLRequest* request) {
  // Don't attempt to intercept here as we want to wait until the mime
  // type is fully determined.
  return NULL;
}

// This is the list of mime types currently supported by the Google
// Document Viewer.
static const char* const supported_mime_type_list[] = {
  "audio/mpeg",
  "video/mp4",
  "audio/mp3"
};

net::URLRequestJob* MediaPlayer::MaybeInterceptResponse(
    net::URLRequest* request) {
  // Do not intercept this request if it is a download.
  if (request->load_flags() & net::LOAD_IS_DOWNLOAD) {
    return NULL;
  }

  std::string mime_type;
  request->GetMimeType(&mime_type);
  // If it is in our list of known URLs, enqueue the url then
  // Cancel the request so the mediaplayer can handle it when
  // it hits it in the playlist.
  if (supported_mime_types_.find(mime_type) != supported_mime_types_.end()) {
    if (request->referrer() != chrome::kChromeUIMediaplayerURL &&
        !request->referrer().empty()) {
      EnqueueMediaFileUrl(request->url(), NULL);
      request->Cancel();
    }
  }
  return NULL;
}

GURL MediaPlayer::GetOriginUrl() const {
  return FileManagerUtil::GetMediaPlayerUrl().GetOrigin();
}

GURL MediaPlayer::GetMediaplayerPlaylistUrl() const {
  return FileManagerUtil::GetMediaPlayerPlaylistUrl();
}

GURL MediaPlayer::GetMediaPlayerUrl() const {
  return FileManagerUtil::GetMediaPlayerUrl();
}

MediaPlayer::MediaPlayer()
    : current_position_(0),
      pending_playback_request_(false),
      playlist_browser_(NULL),
      mediaplayer_browser_(NULL) {
  for (size_t i = 0; i < arraysize(supported_mime_type_list); ++i) {
    supported_mime_types_.insert(supported_mime_type_list[i]);
  }
};
<|endoftext|>


<commit_before>// Copyright (c) 2009 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/extensions/extension_dom_ui.h"

#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_bookmark_manager_api.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"

namespace {
const wchar_t kExtensionURLOverrides[] = L"extensions.chrome_url_overrides";
}

ExtensionDOMUI::ExtensionDOMUI(TabContents* tab_contents)
    : DOMUI(tab_contents) {
  // TODO(aa): It would be cool to show the extension's icon in here.
  hide_favicon_ = true;
  should_hide_url_ = true;
  bindings_ = BindingsPolicy::EXTENSION;

  // For chrome:// overrides, some of the defaults are a little different.
  GURL url = tab_contents->GetURL();
  if (url.SchemeIs(chrome::kChromeUIScheme)) {
    if (url.host() == chrome::kChromeUINewTabHost) {
      focus_location_bar_by_default_ = true;
    } else {
      // Current behavior of other chrome:// pages is to display the URL.
      should_hide_url_ = false;
    }
  }
}

void ExtensionDOMUI::ResetExtensionFunctionDispatcher(
    RenderViewHost* render_view_host) {
  // Use the NavigationController to get the URL rather than the TabContents
  // since this is the real underlying URL (see HandleChromeURLOverride).
  NavigationController& controller = tab_contents()->controller();
  const GURL& url = controller.GetActiveEntry()->url();
  extension_function_dispatcher_.reset(
      new ExtensionFunctionDispatcher(render_view_host, this, url));
}

void ExtensionDOMUI::ResetExtensionBookmarkManagerEventRouter() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTabbedBookmarkManager)) {
    extension_bookmark_manager_event_router_.reset(
        new ExtensionBookmarkManagerEventRouter(GetProfile(), tab_contents()));
  }
}

void ExtensionDOMUI::RenderViewCreated(RenderViewHost* render_view_host) {
  ResetExtensionFunctionDispatcher(render_view_host);
  ResetExtensionBookmarkManagerEventRouter();
}

void ExtensionDOMUI::RenderViewReused(RenderViewHost* render_view_host) {
  ResetExtensionFunctionDispatcher(render_view_host);
  ResetExtensionBookmarkManagerEventRouter();
}

void ExtensionDOMUI::ProcessDOMUIMessage(const std::string& message,
                                         const Value* content,
                                         int request_id,
                                         bool has_callback) {
  extension_function_dispatcher_->HandleRequest(message, content, request_id,
                                                has_callback);
}

Browser* ExtensionDOMUI::GetBrowser(bool include_incognito) const {
  Browser* browser = NULL;
  TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
  if (tab_contents_delegate) {
    browser = tab_contents_delegate->GetBrowser();
    if (browser && browser->profile()->IsOffTheRecord() && !include_incognito) {
      // Fall back to the toplevel regular browser if we don't want to include
      // incognito browsers.
      browser = BrowserList::GetLastActiveWithProfile(
          browser->profile()->GetOriginalProfile());
    }
  }
  return browser;
}

Profile* ExtensionDOMUI::GetProfile() {
  return DOMUI::GetProfile();
}

gfx::NativeWindow ExtensionDOMUI::GetFrameNativeWindow() {
  gfx::NativeWindow native_window =
      ExtensionFunctionDispatcher::Delegate::GetFrameNativeWindow();

  // If there was no window associated with the function dispatcher delegate,
  // then this DOMUI may be hosted in an ExternalTabContainer, and a framing
  // window will be accessible through the tab_contents.
  if (!native_window) {
    TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
    if (tab_contents_delegate)
      native_window = tab_contents_delegate->GetFrameNativeWindow();
  }

  return native_window;
}

gfx::NativeView ExtensionDOMUI::GetNativeViewOfHost() {
  return tab_contents()->GetRenderWidgetHostView()->GetNativeView();
}

////////////////////////////////////////////////////////////////////////////////
// chrome:// URL overrides

// static
void ExtensionDOMUI::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(kExtensionURLOverrides);
}

// static
bool ExtensionDOMUI::HandleChromeURLOverride(GURL* url, Profile* profile) {
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  // Even when the extensions service is enabled by default, it's still
  // disabled in incognito mode.
  ExtensionsService* service = profile->GetExtensionsService();
  if (!service)
    return false;

  const DictionaryValue* overrides =
      profile->GetPrefs()->GetDictionary(kExtensionURLOverrides);
  std::string page = url->host();
  ListValue* url_list;
  if (!overrides || !overrides->GetList(UTF8ToWide(page), &url_list))
    return false;

  if (!service->is_ready()) {
    // TODO(erikkay) So far, it looks like extensions load before the new tab
    // page.  I don't know if we have anything that enforces this, so add this
    // check for safety.
    NOTREACHED() << "Chrome URL override requested before extensions loaded";
    return false;
  }

  while (url_list->GetSize()) {
    Value* val;
    url_list->Get(0, &val);

    // Verify that the override value is good.  If not, unregister it and find
    // the next one.
    std::string override;
    if (!val->GetAsString(&override)) {
      NOTREACHED();
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }
    GURL extension_url(override);
    if (!extension_url.is_valid()) {
      NOTREACHED();
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }

    // Verify that the extension that's being referred to actually exists.
    Extension* extension = service->GetExtensionByURL(extension_url);
    if (!extension) {
      // This can currently happen if you use --load-extension one run, and
      // then don't use it the next.  It could also happen if an extension
      // were deleted directly from the filesystem, etc.
      LOG(WARNING) << "chrome URL override present for non-existant extension";
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }

    *url = extension_url;
    return true;
  }
  return false;
}

// static
void ExtensionDOMUI::RegisterChromeURLOverrides(
    Profile* profile, const Extension::URLOverrideMap& overrides) {
  if (overrides.empty())
    return;

  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);

  // For each override provided by the extension, add it to the front of
  // the override list if it's not already in the list.
  Extension::URLOverrideMap::const_iterator iter = overrides.begin();
  for (;iter != overrides.end(); ++iter) {
    const std::wstring key = UTF8ToWide((*iter).first);
    ListValue* page_overrides;
    if (!all_overrides->GetList(key, &page_overrides)) {
      page_overrides = new ListValue();
      all_overrides->Set(key, page_overrides);
    } else {
      // Verify that the override isn't already in the list.
      ListValue::iterator i = page_overrides->begin();
      for (; i != page_overrides->end(); ++i) {
        std::string override_val;
        if (!(*i)->GetAsString(&override_val)) {
          NOTREACHED();
          continue;
        }
        if (override_val == (*iter).first)
          break;
      }
      // This value is already in the list, leave it alone.
      if (i != page_overrides->end())
        continue;
    }
    // Insert the override at the front of the list.  Last registered override
    // wins.
    page_overrides->Insert(0, new StringValue((*iter).second.spec()));
  }
}

// static
void ExtensionDOMUI::UnregisterAndReplaceOverride(const std::string& page,
    Profile* profile, ListValue* list, Value* override) {
  int index = list->Remove(*override);
  if (index == 0) {
    // This is the active override, so we need to find all existing
    // tabs for this override and get them to reload the original URL.
    for (TabContentsIterator iterator; !iterator.done(); ++iterator) {
      TabContents* tab = *iterator;
      if (tab->profile() != profile)
        continue;

      GURL url = tab->GetURL();
      if (!url.SchemeIs(chrome::kChromeUIScheme) || url.host() != page)
        continue;

      // Don't use Reload() since |url| isn't the same as the internal URL
      // that NavigationController has.
      tab->controller().LoadURL(url, url, PageTransition::RELOAD);
    }
  }
}

// static
void ExtensionDOMUI::UnregisterChromeURLOverride(const std::string& page,
    Profile* profile, Value* override) {
  if (!override)
    return;
  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);
  ListValue* page_overrides;
  if (!all_overrides->GetList(UTF8ToWide(page), &page_overrides)) {
    // If it's being unregistered, it should already be in the list.
    NOTREACHED();
    return;
  } else {
    UnregisterAndReplaceOverride(page, profile, page_overrides, override);
  }
}

RenderViewHost* ExtensionDOMUI::GetRenderViewHost() {
  return tab_contents() ? tab_contents()->render_view_host() : NULL;
}

// static
void ExtensionDOMUI::UnregisterChromeURLOverrides(
    Profile* profile, const Extension::URLOverrideMap& overrides) {
  if (overrides.empty())
    return;
  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);
  Extension::URLOverrideMap::const_iterator iter = overrides.begin();
  for (;iter != overrides.end(); ++iter) {
    std::wstring page = UTF8ToWide((*iter).first);
    ListValue* page_overrides;
    if (!all_overrides->GetList(page, &page_overrides)) {
      // If it's being unregistered, it should already be in the list.
      NOTREACHED();
      continue;
    } else {
      StringValue override((*iter).second.spec());
      UnregisterAndReplaceOverride((*iter).first, profile,
                                   page_overrides, &override);
    }
  }
}
<commit_msg>Hide the URL for all chrome_url_overrides.<commit_after>// Copyright (c) 2009 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/extensions/extension_dom_ui.h"

#include "base/string_util.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/extensions/extension_bookmark_manager_api.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/render_widget_host_view.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/bindings_policy.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"

namespace {
const wchar_t kExtensionURLOverrides[] = L"extensions.chrome_url_overrides";
}

ExtensionDOMUI::ExtensionDOMUI(TabContents* tab_contents)
    : DOMUI(tab_contents) {
  // TODO(aa): It would be cool to show the extension's icon in here.
  hide_favicon_ = true;
  should_hide_url_ = true;
  bindings_ = BindingsPolicy::EXTENSION;

  // For chrome:// overrides, some of the defaults are a little different.
  GURL url = tab_contents->GetURL();
  if (url.SchemeIs(chrome::kChromeUIScheme) &&
      url.host() == chrome::kChromeUINewTabHost) {
    focus_location_bar_by_default_ = true;
  }
}

void ExtensionDOMUI::ResetExtensionFunctionDispatcher(
    RenderViewHost* render_view_host) {
  // Use the NavigationController to get the URL rather than the TabContents
  // since this is the real underlying URL (see HandleChromeURLOverride).
  NavigationController& controller = tab_contents()->controller();
  const GURL& url = controller.GetActiveEntry()->url();
  extension_function_dispatcher_.reset(
      new ExtensionFunctionDispatcher(render_view_host, this, url));
}

void ExtensionDOMUI::ResetExtensionBookmarkManagerEventRouter() {
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableTabbedBookmarkManager)) {
    extension_bookmark_manager_event_router_.reset(
        new ExtensionBookmarkManagerEventRouter(GetProfile(), tab_contents()));
  }
}

void ExtensionDOMUI::RenderViewCreated(RenderViewHost* render_view_host) {
  ResetExtensionFunctionDispatcher(render_view_host);
  ResetExtensionBookmarkManagerEventRouter();
}

void ExtensionDOMUI::RenderViewReused(RenderViewHost* render_view_host) {
  ResetExtensionFunctionDispatcher(render_view_host);
  ResetExtensionBookmarkManagerEventRouter();
}

void ExtensionDOMUI::ProcessDOMUIMessage(const std::string& message,
                                         const Value* content,
                                         int request_id,
                                         bool has_callback) {
  extension_function_dispatcher_->HandleRequest(message, content, request_id,
                                                has_callback);
}

Browser* ExtensionDOMUI::GetBrowser(bool include_incognito) const {
  Browser* browser = NULL;
  TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
  if (tab_contents_delegate) {
    browser = tab_contents_delegate->GetBrowser();
    if (browser && browser->profile()->IsOffTheRecord() && !include_incognito) {
      // Fall back to the toplevel regular browser if we don't want to include
      // incognito browsers.
      browser = BrowserList::GetLastActiveWithProfile(
          browser->profile()->GetOriginalProfile());
    }
  }
  return browser;
}

Profile* ExtensionDOMUI::GetProfile() {
  return DOMUI::GetProfile();
}

gfx::NativeWindow ExtensionDOMUI::GetFrameNativeWindow() {
  gfx::NativeWindow native_window =
      ExtensionFunctionDispatcher::Delegate::GetFrameNativeWindow();

  // If there was no window associated with the function dispatcher delegate,
  // then this DOMUI may be hosted in an ExternalTabContainer, and a framing
  // window will be accessible through the tab_contents.
  if (!native_window) {
    TabContentsDelegate* tab_contents_delegate = tab_contents()->delegate();
    if (tab_contents_delegate)
      native_window = tab_contents_delegate->GetFrameNativeWindow();
  }

  return native_window;
}

gfx::NativeView ExtensionDOMUI::GetNativeViewOfHost() {
  return tab_contents()->GetRenderWidgetHostView()->GetNativeView();
}

////////////////////////////////////////////////////////////////////////////////
// chrome:// URL overrides

// static
void ExtensionDOMUI::RegisterUserPrefs(PrefService* prefs) {
  prefs->RegisterDictionaryPref(kExtensionURLOverrides);
}

// static
bool ExtensionDOMUI::HandleChromeURLOverride(GURL* url, Profile* profile) {
  if (!url->SchemeIs(chrome::kChromeUIScheme))
    return false;

  // Even when the extensions service is enabled by default, it's still
  // disabled in incognito mode.
  ExtensionsService* service = profile->GetExtensionsService();
  if (!service)
    return false;

  const DictionaryValue* overrides =
      profile->GetPrefs()->GetDictionary(kExtensionURLOverrides);
  std::string page = url->host();
  ListValue* url_list;
  if (!overrides || !overrides->GetList(UTF8ToWide(page), &url_list))
    return false;

  if (!service->is_ready()) {
    // TODO(erikkay) So far, it looks like extensions load before the new tab
    // page.  I don't know if we have anything that enforces this, so add this
    // check for safety.
    NOTREACHED() << "Chrome URL override requested before extensions loaded";
    return false;
  }

  while (url_list->GetSize()) {
    Value* val;
    url_list->Get(0, &val);

    // Verify that the override value is good.  If not, unregister it and find
    // the next one.
    std::string override;
    if (!val->GetAsString(&override)) {
      NOTREACHED();
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }
    GURL extension_url(override);
    if (!extension_url.is_valid()) {
      NOTREACHED();
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }

    // Verify that the extension that's being referred to actually exists.
    Extension* extension = service->GetExtensionByURL(extension_url);
    if (!extension) {
      // This can currently happen if you use --load-extension one run, and
      // then don't use it the next.  It could also happen if an extension
      // were deleted directly from the filesystem, etc.
      LOG(WARNING) << "chrome URL override present for non-existant extension";
      UnregisterChromeURLOverride(page, profile, val);
      continue;
    }

    *url = extension_url;
    return true;
  }
  return false;
}

// static
void ExtensionDOMUI::RegisterChromeURLOverrides(
    Profile* profile, const Extension::URLOverrideMap& overrides) {
  if (overrides.empty())
    return;

  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);

  // For each override provided by the extension, add it to the front of
  // the override list if it's not already in the list.
  Extension::URLOverrideMap::const_iterator iter = overrides.begin();
  for (;iter != overrides.end(); ++iter) {
    const std::wstring key = UTF8ToWide((*iter).first);
    ListValue* page_overrides;
    if (!all_overrides->GetList(key, &page_overrides)) {
      page_overrides = new ListValue();
      all_overrides->Set(key, page_overrides);
    } else {
      // Verify that the override isn't already in the list.
      ListValue::iterator i = page_overrides->begin();
      for (; i != page_overrides->end(); ++i) {
        std::string override_val;
        if (!(*i)->GetAsString(&override_val)) {
          NOTREACHED();
          continue;
        }
        if (override_val == (*iter).first)
          break;
      }
      // This value is already in the list, leave it alone.
      if (i != page_overrides->end())
        continue;
    }
    // Insert the override at the front of the list.  Last registered override
    // wins.
    page_overrides->Insert(0, new StringValue((*iter).second.spec()));
  }
}

// static
void ExtensionDOMUI::UnregisterAndReplaceOverride(const std::string& page,
    Profile* profile, ListValue* list, Value* override) {
  int index = list->Remove(*override);
  if (index == 0) {
    // This is the active override, so we need to find all existing
    // tabs for this override and get them to reload the original URL.
    for (TabContentsIterator iterator; !iterator.done(); ++iterator) {
      TabContents* tab = *iterator;
      if (tab->profile() != profile)
        continue;

      GURL url = tab->GetURL();
      if (!url.SchemeIs(chrome::kChromeUIScheme) || url.host() != page)
        continue;

      // Don't use Reload() since |url| isn't the same as the internal URL
      // that NavigationController has.
      tab->controller().LoadURL(url, url, PageTransition::RELOAD);
    }
  }
}

// static
void ExtensionDOMUI::UnregisterChromeURLOverride(const std::string& page,
    Profile* profile, Value* override) {
  if (!override)
    return;
  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);
  ListValue* page_overrides;
  if (!all_overrides->GetList(UTF8ToWide(page), &page_overrides)) {
    // If it's being unregistered, it should already be in the list.
    NOTREACHED();
    return;
  } else {
    UnregisterAndReplaceOverride(page, profile, page_overrides, override);
  }
}

RenderViewHost* ExtensionDOMUI::GetRenderViewHost() {
  return tab_contents() ? tab_contents()->render_view_host() : NULL;
}

// static
void ExtensionDOMUI::UnregisterChromeURLOverrides(
    Profile* profile, const Extension::URLOverrideMap& overrides) {
  if (overrides.empty())
    return;
  PrefService* prefs = profile->GetPrefs();
  DictionaryValue* all_overrides =
      prefs->GetMutableDictionary(kExtensionURLOverrides);
  Extension::URLOverrideMap::const_iterator iter = overrides.begin();
  for (;iter != overrides.end(); ++iter) {
    std::wstring page = UTF8ToWide((*iter).first);
    ListValue* page_overrides;
    if (!all_overrides->GetList(page, &page_overrides)) {
      // If it's being unregistered, it should already be in the list.
      NOTREACHED();
      continue;
    } else {
      StringValue override((*iter).second.spec());
      UnregisterAndReplaceOverride((*iter).first, profile,
                                   page_overrides, &override);
    }
  }
}
<|endoftext|>


<commit_before>// 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/prerender/prerender_manager.h"

#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"

// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
    PRERENDER_MODE_ENABLED;

// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
  return mode_;
}

// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
  mode_ = mode;
}

struct PrerenderManager::PrerenderContentsData {
  PrerenderContents* contents_;
  base::Time start_time_;
  GURL url_;
  PrerenderContentsData(PrerenderContents* contents,
                        base::Time start_time,
                        GURL url)
      : contents_(contents),
        start_time_(start_time),
        url_(url) {
  }
};

PrerenderManager::PrerenderManager(Profile* profile)
    : profile_(profile),
      max_prerender_age_(base::TimeDelta::FromSeconds(
          kDefaultMaxPrerenderAgeSeconds)),
      max_elements_(kDefaultMaxPrerenderElements),
      prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}

PrerenderManager::~PrerenderManager() {
  while (prerender_list_.size() > 0) {
    PrerenderContentsData data = prerender_list_.front();
    prerender_list_.pop_front();
    data.contents_->set_final_status(
        PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
    delete data.contents_;
  }
}

void PrerenderManager::SetPrerenderContentsFactory(
    PrerenderContents::Factory* prerender_contents_factory) {
  prerender_contents_factory_.reset(prerender_contents_factory);
}

void PrerenderManager::AddPreload(const GURL& url,
                                  const std::vector<GURL>& alias_urls) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DeleteOldEntries();
  // If the URL already exists in the set of preloaded URLs, don't do anything.
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->url_ == url)
      return;
  }
  PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
                             GetCurrentTime(), url);
  prerender_list_.push_back(data);
  data.contents_->StartPrerendering();
  while (prerender_list_.size() > max_elements_) {
    data = prerender_list_.front();
    prerender_list_.pop_front();
    data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
    delete data.contents_;
  }
}

void PrerenderManager::DeleteOldEntries() {
  while (prerender_list_.size() > 0) {
    PrerenderContentsData data = prerender_list_.front();
    if (IsPrerenderElementFresh(data.start_time_))
      return;
    prerender_list_.pop_front();
    data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
    delete data.contents_;
  }
}

PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
  DeleteOldEntries();
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    PrerenderContents* pc = it->contents_;
    if (pc->MatchesURL(url)) {
      PrerenderContents* pc = it->contents_;
      prerender_list_.erase(it);
      return pc;
    }
  }
  // Entry not found.
  return NULL;
}

bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<PrerenderContents> pc(GetEntry(url));
  if (pc.get() == NULL)
    return false;

  if (!pc->load_start_time().is_null())
    RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
  pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);

  RenderViewHost* rvh = pc->render_view_host();
  pc->set_render_view_host(NULL);
  rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
  tc->SwapInRenderViewHost(rvh);

  ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
  if (p != NULL)
    tc->DidNavigate(rvh, *p);

  string16 title = pc->title();
  if (!title.empty())
    tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));

  if (pc->has_stopped_loading())
    tc->DidStopLoading();

  return true;
}

void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->contents_ == entry) {
      prerender_list_.erase(it);
      break;
    }
  }
  DeleteOldEntries();
}

base::Time PrerenderManager::GetCurrentTime() const {
  return base::Time::Now();
}

bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
  base::Time now = GetCurrentTime();
  return (now - start < max_prerender_age_);
}

PrerenderContents* PrerenderManager::CreatePrerenderContents(
    const GURL& url,
    const std::vector<GURL>& alias_urls) {
  return prerender_contents_factory_->CreatePrerenderContents(
      this, profile_, url, alias_urls);
}

void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
  bool record_windowed_pplt = ShouldRecordWindowedPPLT();
  switch (mode_) {
    case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
      UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
      if (record_windowed_pplt) {
        UMA_HISTOGRAM_TIMES(
            "PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
      }
      break;
    case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
      UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
      if (record_windowed_pplt) {
        UMA_HISTOGRAM_TIMES(
            "PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
      }
      break;
    default:
      break;
  }
}

void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
  if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
    UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
                        time_until_used);
  }
}

PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->contents_->MatchesURL(url))
      return it->contents_;
  }
  // Entry not found.
  return NULL;
}

void PrerenderManager::RecordPrefetchTagObserved() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // If we observe multiple tags within the 30 second window, we will still
  // reset the window to begin at the most recent occurrence, so that we will
  // always be in a window in the 30 seconds from each occurrence.
  last_prefetch_seen_time_ = base::TimeTicks::Now();
}

bool PrerenderManager::ShouldRecordWindowedPPLT() const {
  if (last_prefetch_seen_time_.is_null())
    return false;
  base::TimeDelta elapsed_time =
      base::TimeTicks::Now() - last_prefetch_seen_time_;
  return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<commit_msg>fix for build break BUG=none TEST=none Review URL: http://codereview.chromium.org/6334063<commit_after>// 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/prerender/prerender_manager.h"

#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/browser_thread.h"
#include "chrome/browser/prerender/prerender_contents.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tab_contents/render_view_host_manager.h"
#include "chrome/common/render_messages.h"

// static
base::TimeTicks PrerenderManager::last_prefetch_seen_time_;

// static
PrerenderManager::PrerenderManagerMode PrerenderManager::mode_ =
    PRERENDER_MODE_ENABLED;

// static
PrerenderManager::PrerenderManagerMode PrerenderManager::GetMode() {
  return mode_;
}

// static
void PrerenderManager::SetMode(PrerenderManagerMode mode) {
  mode_ = mode;
}

struct PrerenderManager::PrerenderContentsData {
  PrerenderContents* contents_;
  base::Time start_time_;
  GURL url_;
  PrerenderContentsData(PrerenderContents* contents,
                        base::Time start_time,
                        GURL url)
      : contents_(contents),
        start_time_(start_time),
        url_(url) {
  }
};

PrerenderManager::PrerenderManager(Profile* profile)
    : profile_(profile),
      max_prerender_age_(base::TimeDelta::FromSeconds(
          kDefaultMaxPrerenderAgeSeconds)),
      max_elements_(kDefaultMaxPrerenderElements),
      prerender_contents_factory_(PrerenderContents::CreateFactory()) {
}

PrerenderManager::~PrerenderManager() {
  while (prerender_list_.size() > 0) {
    PrerenderContentsData data = prerender_list_.front();
    prerender_list_.pop_front();
    data.contents_->set_final_status(
        PrerenderContents::FINAL_STATUS_MANAGER_SHUTDOWN);
    delete data.contents_;
  }
}

void PrerenderManager::SetPrerenderContentsFactory(
    PrerenderContents::Factory* prerender_contents_factory) {
  prerender_contents_factory_.reset(prerender_contents_factory);
}

void PrerenderManager::AddPreload(const GURL& url,
                                  const std::vector<GURL>& alias_urls) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  DeleteOldEntries();
  // If the URL already exists in the set of preloaded URLs, don't do anything.
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->url_ == url)
      return;
  }
  PrerenderContentsData data(CreatePrerenderContents(url, alias_urls),
                             GetCurrentTime(), url);
  prerender_list_.push_back(data);
  data.contents_->StartPrerendering();
  while (prerender_list_.size() > max_elements_) {
    data = prerender_list_.front();
    prerender_list_.pop_front();
    data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_EVICTED);
    delete data.contents_;
  }
}

void PrerenderManager::DeleteOldEntries() {
  while (prerender_list_.size() > 0) {
    PrerenderContentsData data = prerender_list_.front();
    if (IsPrerenderElementFresh(data.start_time_))
      return;
    prerender_list_.pop_front();
    data.contents_->set_final_status(PrerenderContents::FINAL_STATUS_TIMED_OUT);
    delete data.contents_;
  }
}

PrerenderContents* PrerenderManager::GetEntry(const GURL& url) {
  DeleteOldEntries();
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    PrerenderContents* pc = it->contents_;
    if (pc->MatchesURL(url)) {
      PrerenderContents* pc = it->contents_;
      prerender_list_.erase(it);
      return pc;
    }
  }
  // Entry not found.
  return NULL;
}

bool PrerenderManager::MaybeUsePreloadedPage(TabContents* tc, const GURL& url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  scoped_ptr<PrerenderContents> pc(GetEntry(url));
  if (pc.get() == NULL)
    return false;

  if (!pc->load_start_time().is_null())
    RecordTimeUntilUsed(base::TimeTicks::Now() - pc->load_start_time());
  pc->set_final_status(PrerenderContents::FINAL_STATUS_USED);

  RenderViewHost* rvh = pc->render_view_host();
  pc->set_render_view_host(NULL);
  rvh->Send(new ViewMsg_DisplayPrerenderedPage(rvh->routing_id()));
  tc->SwapInRenderViewHost(rvh);

  ViewHostMsg_FrameNavigate_Params* p = pc->navigate_params();
  if (p != NULL)
    tc->DidNavigate(rvh, *p);

  string16 title = pc->title();
  if (!title.empty())
    tc->UpdateTitle(rvh, pc->page_id(), UTF16ToWideHack(title));

  if (pc->has_stopped_loading())
    tc->DidStopLoading();

  return true;
}

void PrerenderManager::RemoveEntry(PrerenderContents* entry) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->contents_ == entry) {
      prerender_list_.erase(it);
      break;
    }
  }
  DeleteOldEntries();
}

base::Time PrerenderManager::GetCurrentTime() const {
  return base::Time::Now();
}

bool PrerenderManager::IsPrerenderElementFresh(const base::Time start) const {
  base::Time now = GetCurrentTime();
  return (now - start < max_prerender_age_);
}

PrerenderContents* PrerenderManager::CreatePrerenderContents(
    const GURL& url,
    const std::vector<GURL>& alias_urls) {
  return prerender_contents_factory_->CreatePrerenderContents(
      this, profile_, url, alias_urls);
}

void PrerenderManager::RecordPerceivedPageLoadTime(base::TimeDelta pplt) {
  bool record_windowed_pplt = ShouldRecordWindowedPPLT();
  switch (mode_) {
    case PRERENDER_MODE_EXPERIMENT_CONTROL_GROUP:
      UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderControl", pplt);
      if (record_windowed_pplt) {
        UMA_HISTOGRAM_TIMES(
            "PLT.PerceivedPageLoadTime_WindowPrerenderControl", pplt);
      }
      break;
    case PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP:
      UMA_HISTOGRAM_TIMES("PLT.PerceivedPageLoadTime_PrerenderTreatment", pplt);
      if (record_windowed_pplt) {
        UMA_HISTOGRAM_TIMES(
            "PLT.PerceivedPageLoadTime_WindowPrerenderTreatment", pplt);
      }
      break;
    default:
      break;
  }
}

void PrerenderManager::RecordTimeUntilUsed(base::TimeDelta time_until_used) {
  if (mode_ == PRERENDER_MODE_EXPERIMENT_PRERENDER_GROUP) {
    UMA_HISTOGRAM_TIMES("PLT.TimeUntilUsed_PrerenderTreatment",
                        time_until_used);
  }
}

PrerenderContents* PrerenderManager::FindEntry(const GURL& url) {
  for (std::list<PrerenderContentsData>::iterator it = prerender_list_.begin();
       it != prerender_list_.end();
       ++it) {
    if (it->contents_->MatchesURL(url))
      return it->contents_;
  }
  // Entry not found.
  return NULL;
}

void PrerenderManager::RecordPrefetchTagObserved() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  // If we observe multiple tags within the 30 second window, we will still
  // reset the window to begin at the most recent occurrence, so that we will
  // always be in a window in the 30 seconds from each occurrence.
  last_prefetch_seen_time_ = base::TimeTicks::Now();
}

bool PrerenderManager::ShouldRecordWindowedPPLT() const {
  if (last_prefetch_seen_time_.is_null())
    return false;
  base::TimeDelta elapsed_time =
      base::TimeTicks::Now() - last_prefetch_seen_time_;
  return elapsed_time <= base::TimeDelta::FromSeconds(kWindowedPPLTSeconds);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/manifest.h"

#include <algorithm>
#include <set>
#include <string>

#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/extensions/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;

namespace extensions {

class ManifestTest : public testing::Test {
 public:
  ManifestTest() : default_value_("test") {}

 protected:
  void AssertType(Manifest* manifest, Extension::Type type) {
    EXPECT_EQ(type, manifest->type());
    EXPECT_EQ(type == Extension::TYPE_THEME, manifest->is_theme());
    EXPECT_EQ(type == Extension::TYPE_PLATFORM_APP,
              manifest->is_platform_app());
    EXPECT_EQ(type == Extension::TYPE_PACKAGED_APP,
              manifest->is_packaged_app());
    EXPECT_EQ(type == Extension::TYPE_HOSTED_APP, manifest->is_hosted_app());
  }

  // Helper function that replaces the Manifest held by |manifest| with a copy
  // with its |key| changed to |value|. If |value| is NULL, then |key| will
  // instead be deleted.
  void MutateManifest(
      scoped_ptr<Manifest>* manifest, const std::string& key, Value* value) {
    scoped_ptr<DictionaryValue> manifest_value(
        manifest->get()->value()->DeepCopy());
    if (value)
      manifest_value->Set(key, value);
    else
      manifest_value->Remove(key, NULL);
    manifest->reset(new Manifest(Extension::INTERNAL, manifest_value.Pass()));
  }

  std::string default_value_;
};

// Verifies that extensions can access the correct keys.
TEST_F(ManifestTest, Extension) {
  scoped_ptr<DictionaryValue> manifest_value(new DictionaryValue());
  manifest_value->SetString(keys::kName, "extension");
  manifest_value->SetString(keys::kVersion, "1");
  // Only supported in manifest_version=1.
  manifest_value->SetString(keys::kBackgroundPageLegacy, "bg.html");
  manifest_value->SetString("unknown_key", "foo");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, manifest_value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  ASSERT_EQ(1u, warnings.size());
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);

  // The known key 'background_page' should be accessible.
  std::string value;
  EXPECT_TRUE(manifest->GetString(keys::kBackgroundPageLegacy, &value));
  EXPECT_EQ("bg.html", value);

  // The unknown key 'unknown_key' should be accesible.
  value.clear();
  EXPECT_TRUE(manifest->GetString("unknown_key", &value));
  EXPECT_EQ("foo", value);

  // Set the manifest_version to 2; background_page should stop working.
  value.clear();
  MutateManifest(
      &manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
  EXPECT_FALSE(manifest->GetString("background_page", &value));
  EXPECT_EQ("", value);

  // Validate should also give a warning.
  warnings.clear();
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  ASSERT_EQ(2u, warnings.size());
  {
    Feature feature;
    feature.set_name("background_page");
    feature.set_max_manifest_version(1);
    EXPECT_EQ(
        "'background_page' requires manifest version of 1 or lower.",
        warnings[0].message);
  }

  // Test DeepCopy and Equals.
  scoped_ptr<Manifest> manifest2(manifest->DeepCopy());
  EXPECT_TRUE(manifest->Equals(manifest2.get()));
  EXPECT_TRUE(manifest2->Equals(manifest.get()));
  MutateManifest(
      &manifest, "foo", Value::CreateStringValue("blah"));
  EXPECT_FALSE(manifest->Equals(manifest2.get()));
}

// Verifies that key restriction based on type works.
TEST_F(ManifestTest, ExtensionTypes) {
  scoped_ptr<DictionaryValue> value(new DictionaryValue());
  value->SetString(keys::kName, "extension");
  value->SetString(keys::kVersion, "1");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  EXPECT_TRUE(warnings.empty());

  // By default, the type is Extension.
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);

  // Theme.
  MutateManifest(
      &manifest, keys::kTheme, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_THEME);
  MutateManifest(
      &manifest, keys::kTheme, NULL);

  // Packaged app.
  MutateManifest(
      &manifest, keys::kApp, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PACKAGED_APP);

  // Platform app.
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, NULL);

  // Hosted app.
  MutateManifest(
      &manifest, keys::kWebURLs, new ListValue());
  AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
  MutateManifest(
      &manifest, keys::kWebURLs, NULL);
  MutateManifest(
      &manifest, keys::kLaunchWebURL, Value::CreateStringValue("foo"));
  AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
  MutateManifest(
      &manifest, keys::kLaunchWebURL, NULL);
};

// Verifies that the getters filter restricted keys.
TEST_F(ManifestTest, RestrictedKeys) {
  scoped_ptr<DictionaryValue> value(new DictionaryValue());
  value->SetString(keys::kName, "extension");
  value->SetString(keys::kVersion, "1");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  EXPECT_TRUE(warnings.empty());

  // Platform apps cannot have a "page_action" key.
  MutateManifest(
      &manifest, keys::kPageAction, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);
  base::Value* output = NULL;
  EXPECT_TRUE(manifest->HasKey(keys::kPageAction));
  EXPECT_TRUE(manifest->Get(keys::kPageAction, &output));

  MutateManifest(
      &manifest, keys::kPlatformAppBackground, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
  EXPECT_FALSE(manifest->HasKey(keys::kPageAction));
  EXPECT_FALSE(manifest->Get(keys::kPageAction, &output));
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, NULL);

  // "commands" is restricted to manifest_version >= 2.
  MutateManifest(
      &manifest, keys::kCommands, new DictionaryValue());
  EXPECT_FALSE(manifest->HasKey(keys::kCommands));
  EXPECT_FALSE(manifest->Get(keys::kCommands, &output));

  MutateManifest(
      &manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
  EXPECT_TRUE(manifest->HasKey(keys::kCommands));
  EXPECT_TRUE(manifest->Get(keys::kCommands, &output));
};

}  // namespace extensions
<commit_msg>Scope ManifestTest.RestrictedKeys to DEV channel for the commands API.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/extensions/manifest.h"

#include <algorithm>
#include <set>
#include <string>

#include "base/memory/scoped_ptr.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/extensions/extension_manifest_constants.h"
#include "chrome/common/extensions/extension_error_utils.h"
#include "chrome/common/extensions/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace errors = extension_manifest_errors;
namespace keys = extension_manifest_keys;

namespace extensions {

class ManifestTest : public testing::Test {
 public:
  ManifestTest() : default_value_("test") {}

 protected:
  void AssertType(Manifest* manifest, Extension::Type type) {
    EXPECT_EQ(type, manifest->type());
    EXPECT_EQ(type == Extension::TYPE_THEME, manifest->is_theme());
    EXPECT_EQ(type == Extension::TYPE_PLATFORM_APP,
              manifest->is_platform_app());
    EXPECT_EQ(type == Extension::TYPE_PACKAGED_APP,
              manifest->is_packaged_app());
    EXPECT_EQ(type == Extension::TYPE_HOSTED_APP, manifest->is_hosted_app());
  }

  // Helper function that replaces the Manifest held by |manifest| with a copy
  // with its |key| changed to |value|. If |value| is NULL, then |key| will
  // instead be deleted.
  void MutateManifest(
      scoped_ptr<Manifest>* manifest, const std::string& key, Value* value) {
    scoped_ptr<DictionaryValue> manifest_value(
        manifest->get()->value()->DeepCopy());
    if (value)
      manifest_value->Set(key, value);
    else
      manifest_value->Remove(key, NULL);
    manifest->reset(new Manifest(Extension::INTERNAL, manifest_value.Pass()));
  }

  std::string default_value_;
};

// Verifies that extensions can access the correct keys.
TEST_F(ManifestTest, Extension) {
  scoped_ptr<DictionaryValue> manifest_value(new DictionaryValue());
  manifest_value->SetString(keys::kName, "extension");
  manifest_value->SetString(keys::kVersion, "1");
  // Only supported in manifest_version=1.
  manifest_value->SetString(keys::kBackgroundPageLegacy, "bg.html");
  manifest_value->SetString("unknown_key", "foo");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, manifest_value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  ASSERT_EQ(1u, warnings.size());
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);

  // The known key 'background_page' should be accessible.
  std::string value;
  EXPECT_TRUE(manifest->GetString(keys::kBackgroundPageLegacy, &value));
  EXPECT_EQ("bg.html", value);

  // The unknown key 'unknown_key' should be accesible.
  value.clear();
  EXPECT_TRUE(manifest->GetString("unknown_key", &value));
  EXPECT_EQ("foo", value);

  // Set the manifest_version to 2; background_page should stop working.
  value.clear();
  MutateManifest(
      &manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
  EXPECT_FALSE(manifest->GetString("background_page", &value));
  EXPECT_EQ("", value);

  // Validate should also give a warning.
  warnings.clear();
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  ASSERT_EQ(2u, warnings.size());
  {
    Feature feature;
    feature.set_name("background_page");
    feature.set_max_manifest_version(1);
    EXPECT_EQ(
        "'background_page' requires manifest version of 1 or lower.",
        warnings[0].message);
  }

  // Test DeepCopy and Equals.
  scoped_ptr<Manifest> manifest2(manifest->DeepCopy());
  EXPECT_TRUE(manifest->Equals(manifest2.get()));
  EXPECT_TRUE(manifest2->Equals(manifest.get()));
  MutateManifest(
      &manifest, "foo", Value::CreateStringValue("blah"));
  EXPECT_FALSE(manifest->Equals(manifest2.get()));
}

// Verifies that key restriction based on type works.
TEST_F(ManifestTest, ExtensionTypes) {
  scoped_ptr<DictionaryValue> value(new DictionaryValue());
  value->SetString(keys::kName, "extension");
  value->SetString(keys::kVersion, "1");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  EXPECT_TRUE(warnings.empty());

  // By default, the type is Extension.
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);

  // Theme.
  MutateManifest(
      &manifest, keys::kTheme, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_THEME);
  MutateManifest(
      &manifest, keys::kTheme, NULL);

  // Packaged app.
  MutateManifest(
      &manifest, keys::kApp, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PACKAGED_APP);

  // Platform app.
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, NULL);

  // Hosted app.
  MutateManifest(
      &manifest, keys::kWebURLs, new ListValue());
  AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
  MutateManifest(
      &manifest, keys::kWebURLs, NULL);
  MutateManifest(
      &manifest, keys::kLaunchWebURL, Value::CreateStringValue("foo"));
  AssertType(manifest.get(), Extension::TYPE_HOSTED_APP);
  MutateManifest(
      &manifest, keys::kLaunchWebURL, NULL);
};

// Verifies that the getters filter restricted keys.
TEST_F(ManifestTest, RestrictedKeys) {
  scoped_ptr<DictionaryValue> value(new DictionaryValue());
  value->SetString(keys::kName, "extension");
  value->SetString(keys::kVersion, "1");

  scoped_ptr<Manifest> manifest(
      new Manifest(Extension::INTERNAL, value.Pass()));
  std::string error;
  Extension::InstallWarningVector warnings;
  manifest->ValidateManifest(&error, &warnings);
  EXPECT_TRUE(error.empty());
  EXPECT_TRUE(warnings.empty());

  // Platform apps cannot have a "page_action" key.
  MutateManifest(
      &manifest, keys::kPageAction, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_EXTENSION);
  base::Value* output = NULL;
  EXPECT_TRUE(manifest->HasKey(keys::kPageAction));
  EXPECT_TRUE(manifest->Get(keys::kPageAction, &output));

  MutateManifest(
      &manifest, keys::kPlatformAppBackground, new DictionaryValue());
  AssertType(manifest.get(), Extension::TYPE_PLATFORM_APP);
  EXPECT_FALSE(manifest->HasKey(keys::kPageAction));
  EXPECT_FALSE(manifest->Get(keys::kPageAction, &output));
  MutateManifest(
      &manifest, keys::kPlatformAppBackground, NULL);

  // "commands" is restricted to manifest_version >= 2.
  {
    // ... and dev channel, for now.
    Feature::ScopedCurrentChannel dev_channel_scope(
        chrome::VersionInfo::CHANNEL_DEV);

    MutateManifest(
        &manifest, keys::kCommands, new DictionaryValue());
    EXPECT_FALSE(manifest->HasKey(keys::kCommands));
    EXPECT_FALSE(manifest->Get(keys::kCommands, &output));

    MutateManifest(
        &manifest, keys::kManifestVersion, Value::CreateIntegerValue(2));
    EXPECT_TRUE(manifest->HasKey(keys::kCommands));
    EXPECT_TRUE(manifest->Get(keys::kCommands, &output));
  }
};

}  // namespace extensions
<|endoftext|>


<commit_before>#include <algorithm>
#include <iostream>
#include <fstream>
#include <libxml/xmlmemory.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"

using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
using string_util::starts_with;

typedef vector<string> StringVec;

static string get_type(const string &location){
  static const string CHAR("CHAR");
  if(starts_with(location,CHAR))
    return "NX_CHAR";

  static const string INT8("INT8");
  if(starts_with(location,INT8))
    return "NX_INT8";

  static const string INT16("INT16");
  if(starts_with(location,INT16))
    return "NX_INT16";

  static const string INT32("INT32");
  if(starts_with(location,INT32))
    return "NX_INT32";

  static const string UINT8("UINT8");
  if(starts_with(location,UINT8))
    return "NX_UINT8";

  static const string UINT16("UINT16");
  if(starts_with(location,UINT16))
    return "NX_UINT16";

  static const string UINT32("UINT32");
  if(starts_with(location,UINT32))
    return "NX_UINT32";

  static const string FLOAT32("FLOAT32");
  if(starts_with(location,FLOAT32))
    return "NX_FLOAT32";

  static const string FLOAT64("FLOAT64");
  if(starts_with(location,FLOAT64))
    return "NX_FLOAT64";

  throw invalid_argument("Cannot determine type in location: "+location);
}

static string xmlChar_to_str(const xmlChar *ch, int len){
  string result((char *)ch);
  if( (len>0) && ((unsigned int)len<result.size()) )
    result.erase(result.begin()+len,result.end());

  return string_util::trim(result);
}

static bool is_right_square_bracket(const char c){
  static const string RIGHT="]";
  return find(RIGHT.begin(),RIGHT.end(),c)!=RIGHT.end();
}

static string get_dims(const string &location){
  using std::find;
  static const string LEFT("[");

  if(!starts_with(location,LEFT))
    return "";

  string result="";
  for(string::const_iterator it=location.begin() ; it!=location.end() ; it++ ){
    result+=(*it);
    if(is_right_square_bracket(*it))
      break;
  }

  if(result.size()==location.size())
    return "";
  else
    return result;
}

static xmlNode* find_element(xmlNode *a_node, const string &name){
  xmlNode *cur_node=NULL;

  string nodeName;
  for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
    nodeName=xmlChar_to_str(cur_node->name,-1);
    if(nodeName==name)
      return cur_node->xmlChildrenNode;
  }
  return NULL;
}

static void print_element_names(xmlNode * a_node){
    xmlNode *cur_node = NULL;

    for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
        if(cur_node->type == XML_ELEMENT_NODE){
          cout << "node type: Element, name: " << cur_node->name << endl;
        }

        //print_element_names(cur_node->children);
    }
}

static xmlNode* open_path(xmlNode *node,StringVec::iterator begin, StringVec::iterator end){
  // error check input
  if(begin==end)
    return NULL;

  // locate the next part of the path
  node=find_element(node,*begin);

  // if it returned poorly then get out now
  if(node==NULL)
    return NULL;

  // go to next step
  begin++;
  if(begin==end)
    return node;

  // recursively call self
  return open_path(node,begin,end);
}

static string getStrValue(const xmlDocPtr &doc, const xmlNodePtr &node){
  xmlChar *char_value=xmlNodeListGetString(doc,node,1);
  if(char_value==NULL)
    throw runtime_error("blah");
  string value=xmlChar_to_str(char_value,-1);
  xmlFree(char_value);
  return value;
}

/**
 * The factory will call the constructor with a string. The string
 * specifies where to locate the data (e.g. a filename), but
 * interpreting the string is left up to the implementing code.
 */
TextXmlRetriever::TextXmlRetriever(const string &str): source(str) /*,current_line(0)*/{
  cout << "****************************************"
       << "****************************************" << endl; // REMOVE
  cout << "TextXmlRetriever(" << source << ")" << endl; // REMOVE

  // open the file
  doc=xmlParseFile(source.c_str());

  // check that open was successful
  if(doc==NULL){
    xmlFreeDoc(doc);
    xmlCleanupParser();
    throw runtime_error("Parsing "+source+" was not successful");
  }

  // check that the document is not empty
  xmlNode *xml_node = NULL;
  xml_node = xmlDocGetRootElement(doc);
  if(xml_node==NULL)
    throw runtime_error("Empty document ["+source+"]");
}

TextXmlRetriever::~TextXmlRetriever(){
  //cout << "~TextXmlRetriever()" << endl;

  if(doc==NULL) return;

  // close the file
  xmlFreeDoc(doc);
  xmlCleanupParser();
}

/**
 * This is the method for retrieving data from a file. The whole
 * tree will be written to the new file immediately after being
 * called. Interpreting the string is left up to the implementing
 * code.
 */
void TextXmlRetriever::getData(const string &location, tree<Node> &tr){
  cout << "TextXmlRetriever::getData(" << location << ",tree)" << endl; // REMOVE
  // check that the argument is not an empty string
  if(location.size()<=0)
    throw invalid_argument("cannot parse empty string");

  // variables for the divided string version of the location
  string str_path;
  string type;
  string str_dims;

  // convert the location to a type and (string) path
  if(starts_with(location,"/")){
    str_path=location;
    type="NX_CHAR";
    str_dims="";
  }else{
    // get the type and remove it from the location
    type=get_type(location);
    str_path=location.substr(type.size()-3,location.size());
    // get the dimensions and remove it from the location
    str_dims=get_dims(str_path);
    str_path=str_path.substr(str_dims.size(),str_path.size());
    // remove the separating colon
    str_path=str_path.substr(1,str_path.size());
  }
  std::cout << "TYPE=" << type << " DIMS=" << str_dims << " PATH=" << str_path << std::endl; // REMOVE
  StringVec path=string_util::string_to_path(str_path);
  Node::NXtype int_type=node_type(type);

  // get the root
  xmlNode *xml_node = NULL;
  xml_node = xmlDocGetRootElement(doc);

  // open the path
  xml_node=open_path(xml_node,path.begin(),path.end());
  if(xml_node==NULL)
    throw invalid_argument("path ["+location+"] does not exist in file");

  // get the value
  string value=getStrValue(doc, xml_node);
  if(value.size()<=0)
    throw runtime_error("Encountered empty value ["+source+","+location+"]");

  // create an empty node
  Node node(*(path.rbegin()),"empty");

  // put the data in the node
  vector<int> dims;
  if(int_type==Node::CHAR){
    dims.push_back(value.size());
  }else{
    dims=string_util::str_to_intVec(str_dims);
  }

  update_node_from_string(node,value,dims,int_type);

  tr.insert(tr.begin(),node);
}

static void openPath(  xmlNode *root_element, const std::vector<std::string> &path, int &num_group, int &num_data){

}

static void closePath(  xmlNode *root_element, int &num_group, int &num_data){

}

const string TextXmlRetriever::MIME_TYPE("text/xml");

string TextXmlRetriever::toString() const{
  return "["+MIME_TYPE+"] "+source;
}
<commit_msg>Removed ^M characters from the file. No other changes from previous version.<commit_after>#include <algorithm>
#include <iostream>
#include <fstream>
#include <libxml/xmlmemory.h>
#include <stdexcept>
#include <string>
#include <vector>
#include "retriever.h"
#include "../node.h"
#include "../node_util.h"
#include "../string_util.h"
#include "../tree.hh"

using std::ifstream;
using std::invalid_argument;
using std::runtime_error;
using std::string;
using std::cout;
using std::endl;
using std::vector;
using string_util::starts_with;

typedef vector<string> StringVec;

static string get_type(const string &location){
  static const string CHAR("CHAR");
  if(starts_with(location,CHAR))
    return "NX_CHAR";

  static const string INT8("INT8");
  if(starts_with(location,INT8))
    return "NX_INT8";

  static const string INT16("INT16");
  if(starts_with(location,INT16))
    return "NX_INT16";

  static const string INT32("INT32");
  if(starts_with(location,INT32))
    return "NX_INT32";

  static const string UINT8("UINT8");
  if(starts_with(location,UINT8))
    return "NX_UINT8";

  static const string UINT16("UINT16");
  if(starts_with(location,UINT16))
    return "NX_UINT16";

  static const string UINT32("UINT32");
  if(starts_with(location,UINT32))
    return "NX_UINT32";

  static const string FLOAT32("FLOAT32");
  if(starts_with(location,FLOAT32))
    return "NX_FLOAT32";

  static const string FLOAT64("FLOAT64");
  if(starts_with(location,FLOAT64))
    return "NX_FLOAT64";

  throw invalid_argument("Cannot determine type in location: "+location);
}

static string xmlChar_to_str(const xmlChar *ch, int len){
  string result((char *)ch);
  if( (len>0) && ((unsigned int)len<result.size()) )
    result.erase(result.begin()+len,result.end());

  return string_util::trim(result);
}

static bool is_right_square_bracket(const char c){
  static const string RIGHT="]";
  return find(RIGHT.begin(),RIGHT.end(),c)!=RIGHT.end();
}

static string get_dims(const string &location){
  using std::find;
  static const string LEFT("[");

  if(!starts_with(location,LEFT))
    return "";

  string result="";
  for(string::const_iterator it=location.begin() ; it!=location.end() ; it++ ){
    result+=(*it);
    if(is_right_square_bracket(*it))
      break;
  }

  if(result.size()==location.size())
    return "";
  else
    return result;
}

static xmlNode* find_element(xmlNode *a_node, const string &name){
  xmlNode *cur_node=NULL;

  string nodeName;
  for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
    nodeName=xmlChar_to_str(cur_node->name,-1);
    if(nodeName==name)
      return cur_node->xmlChildrenNode;
  }
  return NULL;
}

static void print_element_names(xmlNode * a_node){
    xmlNode *cur_node = NULL;

    for( cur_node=a_node ; cur_node!=NULL ; cur_node=cur_node->next ){
        if(cur_node->type == XML_ELEMENT_NODE){
          cout << "node type: Element, name: " << cur_node->name << endl;
        }

        //print_element_names(cur_node->children);
    }
}

static xmlNode* open_path(xmlNode *node,StringVec::iterator begin, StringVec::iterator end){
  // error check input
  if(begin==end)
    return NULL;

  // locate the next part of the path
  node=find_element(node,*begin);

  // if it returned poorly then get out now
  if(node==NULL)
    return NULL;

  // go to next step
  begin++;
  if(begin==end)
    return node;

  // recursively call self
  return open_path(node,begin,end);
}

static string getStrValue(const xmlDocPtr &doc, const xmlNodePtr &node){
  xmlChar *char_value=xmlNodeListGetString(doc,node,1);
  if(char_value==NULL)
    throw runtime_error("blah");
  string value=xmlChar_to_str(char_value,-1);
  xmlFree(char_value);
  return value;
}

/**
 * The factory will call the constructor with a string. The string
 * specifies where to locate the data (e.g. a filename), but
 * interpreting the string is left up to the implementing code.
 */
TextXmlRetriever::TextXmlRetriever(const string &str): source(str) /*,current_line(0)*/{
  cout << "****************************************"
       << "****************************************" << endl; // REMOVE
  cout << "TextXmlRetriever(" << source << ")" << endl; // REMOVE

  // open the file
  doc=xmlParseFile(source.c_str());

  // check that open was successful
  if(doc==NULL){
    xmlFreeDoc(doc);
    xmlCleanupParser();
    throw runtime_error("Parsing "+source+" was not successful");
  }

  // check that the document is not empty
  xmlNode *xml_node = NULL;
  xml_node = xmlDocGetRootElement(doc);
  if(xml_node==NULL)
    throw runtime_error("Empty document ["+source+"]");
}

TextXmlRetriever::~TextXmlRetriever(){
  //cout << "~TextXmlRetriever()" << endl;

  if(doc==NULL) return;

  // close the file
  xmlFreeDoc(doc);
  xmlCleanupParser();
}

/**
 * This is the method for retrieving data from a file. The whole
 * tree will be written to the new file immediately after being
 * called. Interpreting the string is left up to the implementing
 * code.
 */
void TextXmlRetriever::getData(const string &location, tree<Node> &tr){
  cout << "TextXmlRetriever::getData(" << location << ",tree)" << endl; // REMOVE
  // check that the argument is not an empty string
  if(location.size()<=0)
    throw invalid_argument("cannot parse empty string");

  // variables for the divided string version of the location
  string str_path;
  string type;
  string str_dims;

  // convert the location to a type and (string) path
  if(starts_with(location,"/")){
    str_path=location;
    type="NX_CHAR";
    str_dims="";
  }else{
    // get the type and remove it from the location
    type=get_type(location);
    str_path=location.substr(type.size()-3,location.size());
    // get the dimensions and remove it from the location
    str_dims=get_dims(str_path);
    str_path=str_path.substr(str_dims.size(),str_path.size());
    // remove the separating colon
    str_path=str_path.substr(1,str_path.size());
  }
  std::cout << "TYPE=" << type << " DIMS=" << str_dims << " PATH=" << str_path << std::endl; // REMOVE
  StringVec path=string_util::string_to_path(str_path);
  Node::NXtype int_type=node_type(type);

  // get the root
  xmlNode *xml_node = NULL;
  xml_node = xmlDocGetRootElement(doc);

  // open the path
  xml_node=open_path(xml_node,path.begin(),path.end());
  if(xml_node==NULL)
    throw invalid_argument("path ["+location+"] does not exist in file");

  // get the value
  string value=getStrValue(doc, xml_node);
  if(value.size()<=0)
    throw runtime_error("Encountered empty value ["+source+","+location+"]");

  // create an empty node
  Node node(*(path.rbegin()),"empty");

  // put the data in the node
  vector<int> dims;
  if(int_type==Node::CHAR){
    dims.push_back(value.size());
  }else{
    dims=string_util::str_to_intVec(str_dims);
  }

  update_node_from_string(node,value,dims,int_type);

  tr.insert(tr.begin(),node);
}

static void openPath(  xmlNode *root_element, const std::vector<std::string> &path, int &num_group, int &num_data){

}

static void closePath(  xmlNode *root_element, int &num_group, int &num_data){

}

const string TextXmlRetriever::MIME_TYPE("text/xml");

string TextXmlRetriever::toString() const{
  return "["+MIME_TYPE+"] "+source;
}
<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "cpuid.h"

#include <cstdlib>

using namespace Vc;

template<typename Vector> struct Helper
{
    typedef typename Vector::Mask Mask;
    typedef typename Vector::EntryType Scalar;

    static Vector *blackHole;

    static void setBlackHole();

    static void run(const int Repetitions)
    {
        const int Factor = CpuId::L1Data() / sizeof(Vector);
        const int opPerSecondFactor = Factor * Vector::Size;

        setBlackHole();

        Vector *data = new Vector[Factor];
        for (int i = 0; i < Factor; ++i) {
            data[i] = PseudoRandom<Vector>::next();
        }

        {
            Benchmark timer("round", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = round(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("sqrt", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = sqrt(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("log", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = log(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("sin", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = sin(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("cos", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = cos(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("asin", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = asin(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("atan", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = atan(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("atan2", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor - 1; ++i) {
                    *blackHole = atan2(data[i], data[i + 1]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("rsqrt", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = rsqrt(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("recip", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    *blackHole = reciprocal(data[i]);
                }
                timer.Stop();
            }
            timer.Print();
        }

        delete[] data;
    }
};

template<typename Vec> Vec *Helper<Vec>::blackHole = 0;

// global (not file-static!) variable keeps the compiler from identifying the benchmark as dead code
float_v blackHoleFloat;
template<> inline void Helper<float_v>::setBlackHole() { blackHole = &blackHoleFloat; }
#if VC_IMPL_SSE
sfloat_v blackHoleSFloat;
template<> inline void Helper<sfloat_v>::setBlackHole() { blackHole = &blackHoleSFloat; }
#endif

int bmain(Benchmark::OutputMode out)
{
    const int Repetitions = out == Benchmark::Stdout ? 4 : (g_Repetitions > 0 ? g_Repetitions : 100);
    Benchmark::addColumn("datatype");
    Benchmark::setColumnData("datatype", "float_v");
    Helper<float_v>::run(Repetitions);
#if VC_IMPL_SSE
    Benchmark::setColumnData("datatype", "sfloat_v");
    Helper<sfloat_v>::run(Repetitions);
#endif
    return 0;
}
<commit_msg>benchmark double_v, too; use forceToRegisters instead of black hole<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "benchmark.h"
#include "random.h"
#include "cpuid.h"

#include <cstdlib>

using namespace Vc;

template<typename Vector> struct Helper
{
    typedef typename Vector::Mask Mask;
    typedef typename Vector::EntryType Scalar;

    static void run(const int Repetitions)
    {
        const int Factor = CpuId::L1Data() / sizeof(Vector);
        const int opPerSecondFactor = Factor * Vector::Size;

        Vector *data = new Vector[Factor];
        for (int i = 0; i < Factor; ++i) {
            data[i] = PseudoRandom<Vector>::next();
        }

        {
            Benchmark timer("round", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = round(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("sqrt", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = sqrt(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("log", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = log(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("sin", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = sin(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("cos", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = cos(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("asin", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = asin(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("atan", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = atan(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("atan2", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor - 1; ++i) {
                    Vector tmp = atan2(data[i], data[i + 1]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("rsqrt", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = rsqrt(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }
        {
            Benchmark timer("recip", opPerSecondFactor, "Op");
            for (int rep = 0; rep < Repetitions; ++rep) {
                timer.Start();
                for (int i = 0; i < Factor; ++i) {
                    Vector tmp = reciprocal(data[i]);
                    Vc::forceToRegisters(tmp);
                }
                timer.Stop();
            }
            timer.Print();
        }

        delete[] data;
    }
};

int bmain(Benchmark::OutputMode out)
{
    const int Repetitions = out == Benchmark::Stdout ? 4 : (g_Repetitions > 0 ? g_Repetitions : 100);
    Benchmark::addColumn("datatype");
    Benchmark::setColumnData("datatype", "float_v");
    Helper<float_v>::run(Repetitions);
    Benchmark::setColumnData("datatype", "sfloat_v");
    Helper<sfloat_v>::run(Repetitions);
    Benchmark::setColumnData("datatype", "double_v");
    Helper<double_v>::run(Repetitions);
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Create code.cpp<commit_after><|endoftext|>