<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/browser/ui/webui/options/password_manager_handler.h"

#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/autofill/core/common/password_form.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"

namespace options {

PasswordManagerHandler::PasswordManagerHandler()
    : populater_(this),
      exception_populater_(this),
      is_user_authenticated_(false) {
}

PasswordManagerHandler::~PasswordManagerHandler() {
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->RemoveObserver(this);
}

void PasswordManagerHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsNoPasswordsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
                               chrome::kPasswordManagerLearnMoreURL);
}

void PasswordManagerHandler::InitializeHandler() {
  // Due to the way that handlers are (re)initialized under certain types of
  // navigation, we may already be initialized. (See bugs 88986 and 86448.)
  // If this is the case, return immediately. This is a hack.
  // TODO(mdm): remove this hack once it is no longer necessary.
  if (!show_passwords_.GetPrefName().empty())
    return;

  show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
                       Profile::FromWebUI(web_ui())->GetPrefs(),
                       base::Bind(&PasswordManagerHandler::UpdatePasswordLists,
                                  base::Unretained(this),
                                  static_cast<base::ListValue*>(NULL)));
  // We should not cache web_ui()->GetProfile(). See crosbug.com/6304.
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->AddObserver(this);
}

void PasswordManagerHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("updatePasswordLists",
      base::Bind(&PasswordManagerHandler::UpdatePasswordLists,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("removeSavedPassword",
      base::Bind(&PasswordManagerHandler::RemoveSavedPassword,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("removePasswordException",
      base::Bind(&PasswordManagerHandler::RemovePasswordException,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("requestShowPassword",
      base::Bind(&PasswordManagerHandler::RequestShowPassword,
                 base::Unretained(this)));
}

void PasswordManagerHandler::OnLoginsChanged() {
  UpdatePasswordLists(NULL);
}

PasswordStore* PasswordManagerHandler::GetPasswordStore() {
  return PasswordStoreFactory::GetForProfile(Profile::FromWebUI(web_ui()),
                                             Profile::EXPLICIT_ACCESS).get();
}

void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
  // Reset the current lists.
  password_list_.clear();
  password_exception_list_.clear();

  languages_ = Profile::FromWebUI(web_ui())->GetPrefs()->
      GetString(prefs::kAcceptLanguages);
  populater_.Populate();
  exception_populater_.Populate();
}

void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_list_.size()) {
    store->RemoveLogin(*password_list_[index]);
    content::RecordAction(
        content::UserMetricsAction("PasswordManager_RemoveSavedPassword"));
  }
}

void PasswordManagerHandler::RemovePasswordException(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_exception_list_.size()) {
    store->RemoveLogin(*password_exception_list_[index]);
    content::RecordAction(
        content::UserMetricsAction("PasswordManager_RemovePasswordException"));
  }
}

void PasswordManagerHandler::RequestShowPassword(const ListValue* args) {
  int index;
  if (!ExtractIntegerValue(args, &index)) {
    NOTREACHED();
    return;
  }

  if (!is_user_authenticated_) {
    // TODO(dubroy): Insert actual authentication code here.
    is_user_authenticated_ = true;
  }

  // Call back the front end to reveal the password.
  web_ui()->CallJavascriptFunction(
      "PasswordManager.showPassword",
      base::FundamentalValue(index),
      StringValue(password_list_[index]->password_value));
}

void PasswordManagerHandler::SetPasswordList() {
  // Due to the way that handlers are (re)initialized under certain types of
  // navigation, we may not be initialized yet. (See bugs 88986 and 86448.)
  // If this is the case, initialize on demand. This is a hack.
  // TODO(mdm): remove this hack once it is no longer necessary.
  if (show_passwords_.GetPrefName().empty())
    InitializeHandler();

  ListValue entries;
  bool show_passwords = *show_passwords_ && is_user_authenticated_;
  string16 placeholder(ASCIIToUTF16("        "));
  for (size_t i = 0; i < password_list_.size(); ++i) {
    ListValue* entry = new ListValue();
    entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
                                                 languages_)));
    entry->Append(new StringValue(password_list_[i]->username_value));
    entry->Append(new StringValue(
        show_passwords ? password_list_[i]->password_value : placeholder));
    entries.Append(entry);
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                   entries);
}

void PasswordManagerHandler::SetPasswordExceptionList() {
  ListValue entries;
  for (size_t i = 0; i < password_exception_list_.size(); ++i) {
    entries.Append(new StringValue(
        net::FormatUrl(password_exception_list_[i]->origin, languages_)));
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                   entries);
}

PasswordManagerHandler::ListPopulater::ListPopulater(
    PasswordManagerHandler* page)
    : page_(page),
      pending_login_query_(0) {
}

PasswordManagerHandler::ListPopulater::~ListPopulater() {
}

PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
    PasswordManagerHandler* page) : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetAutofillableLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display passwords.";
  }
}

void PasswordManagerHandler::PasswordListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_list_.clear();
  page_->password_list_.insert(page_->password_list_.end(),
                               result.begin(), result.end());
  page_->SetPasswordList();
}

void PasswordManagerHandler::PasswordListPopulater::OnGetPasswordStoreResults(
    const std::vector<autofill::PasswordForm*>& results) {
  // TODO(kaiwang): Implement when I refactor
  // PasswordStore::GetAutofillableLogins and PasswordStore::GetBlacklistLogins.
  NOTIMPLEMENTED();
}

PasswordManagerHandler::PasswordExceptionListPopulater::
    PasswordExceptionListPopulater(PasswordManagerHandler* page)
        : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetBlacklistLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display exceptions.";
  }
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_exception_list_.clear();
  page_->password_exception_list_.insert(page_->password_exception_list_.end(),
                                         result.begin(), result.end());
  page_->SetPasswordExceptionList();
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnGetPasswordStoreResults(
        const std::vector<autofill::PasswordForm*>& results) {
  // TODO(kaiwang): Implement when I refactor
  // PasswordStore::GetAutofillableLogins and PasswordStore::GetBlacklistLogins.
  NOTIMPLEMENTED();
}

}  // namespace options
<commit_msg>Password Manager: Make placeholder value the same length as the real password.<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/browser/ui/webui/options/password_manager_handler.h"

#include "base/bind.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/password_manager/password_store_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "components/autofill/core/common/password_form.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "content/public/browser/web_ui.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "ui/base/l10n/l10n_util.h"

namespace options {

PasswordManagerHandler::PasswordManagerHandler()
    : populater_(this),
      exception_populater_(this),
      is_user_authenticated_(false) {
}

PasswordManagerHandler::~PasswordManagerHandler() {
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->RemoveObserver(this);
}

void PasswordManagerHandler::GetLocalizedValues(
    DictionaryValue* localized_strings) {
  DCHECK(localized_strings);

  static const OptionsStringResource resources[] = {
    { "savedPasswordsTitle",
      IDS_PASSWORDS_SHOW_PASSWORDS_TAB_TITLE },
    { "passwordExceptionsTitle",
      IDS_PASSWORDS_EXCEPTIONS_TAB_TITLE },
    { "passwordSearchPlaceholder",
      IDS_PASSWORDS_PAGE_SEARCH_PASSWORDS },
    { "passwordShowButton",
      IDS_PASSWORDS_PAGE_VIEW_SHOW_BUTTON },
    { "passwordHideButton",
      IDS_PASSWORDS_PAGE_VIEW_HIDE_BUTTON },
    { "passwordsNoPasswordsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_PASSWORDS_DESCRIPTION },
    { "passwordsNoExceptionsDescription",
      IDS_PASSWORDS_PAGE_VIEW_NO_EXCEPTIONS_DESCRIPTION },
  };

  RegisterStrings(localized_strings, resources, arraysize(resources));
  RegisterTitle(localized_strings, "passwordsPage",
                IDS_PASSWORDS_EXCEPTIONS_WINDOW_TITLE);

  localized_strings->SetString("passwordManagerLearnMoreURL",
                               chrome::kPasswordManagerLearnMoreURL);
}

void PasswordManagerHandler::InitializeHandler() {
  // Due to the way that handlers are (re)initialized under certain types of
  // navigation, we may already be initialized. (See bugs 88986 and 86448.)
  // If this is the case, return immediately. This is a hack.
  // TODO(mdm): remove this hack once it is no longer necessary.
  if (!show_passwords_.GetPrefName().empty())
    return;

  show_passwords_.Init(prefs::kPasswordManagerAllowShowPasswords,
                       Profile::FromWebUI(web_ui())->GetPrefs(),
                       base::Bind(&PasswordManagerHandler::UpdatePasswordLists,
                                  base::Unretained(this),
                                  static_cast<base::ListValue*>(NULL)));
  // We should not cache web_ui()->GetProfile(). See crosbug.com/6304.
  PasswordStore* store = GetPasswordStore();
  if (store)
    store->AddObserver(this);
}

void PasswordManagerHandler::RegisterMessages() {
  web_ui()->RegisterMessageCallback("updatePasswordLists",
      base::Bind(&PasswordManagerHandler::UpdatePasswordLists,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("removeSavedPassword",
      base::Bind(&PasswordManagerHandler::RemoveSavedPassword,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("removePasswordException",
      base::Bind(&PasswordManagerHandler::RemovePasswordException,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("requestShowPassword",
      base::Bind(&PasswordManagerHandler::RequestShowPassword,
                 base::Unretained(this)));
}

void PasswordManagerHandler::OnLoginsChanged() {
  UpdatePasswordLists(NULL);
}

PasswordStore* PasswordManagerHandler::GetPasswordStore() {
  return PasswordStoreFactory::GetForProfile(Profile::FromWebUI(web_ui()),
                                             Profile::EXPLICIT_ACCESS).get();
}

void PasswordManagerHandler::UpdatePasswordLists(const ListValue* args) {
  // Reset the current lists.
  password_list_.clear();
  password_exception_list_.clear();

  languages_ = Profile::FromWebUI(web_ui())->GetPrefs()->
      GetString(prefs::kAcceptLanguages);
  populater_.Populate();
  exception_populater_.Populate();
}

void PasswordManagerHandler::RemoveSavedPassword(const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_list_.size()) {
    store->RemoveLogin(*password_list_[index]);
    content::RecordAction(
        content::UserMetricsAction("PasswordManager_RemoveSavedPassword"));
  }
}

void PasswordManagerHandler::RemovePasswordException(
    const ListValue* args) {
  PasswordStore* store = GetPasswordStore();
  if (!store)
    return;
  std::string string_value = UTF16ToUTF8(ExtractStringValue(args));
  int index;
  if (base::StringToInt(string_value, &index) && index >= 0 &&
      static_cast<size_t>(index) < password_exception_list_.size()) {
    store->RemoveLogin(*password_exception_list_[index]);
    content::RecordAction(
        content::UserMetricsAction("PasswordManager_RemovePasswordException"));
  }
}

void PasswordManagerHandler::RequestShowPassword(const ListValue* args) {
  int index;
  if (!ExtractIntegerValue(args, &index)) {
    NOTREACHED();
    return;
  }

  if (!is_user_authenticated_) {
    // TODO(dubroy): Insert actual authentication code here.
    is_user_authenticated_ = true;
  }

  // Call back the front end to reveal the password.
  web_ui()->CallJavascriptFunction(
      "PasswordManager.showPassword",
      base::FundamentalValue(index),
      StringValue(password_list_[index]->password_value));
}

void PasswordManagerHandler::SetPasswordList() {
  // Due to the way that handlers are (re)initialized under certain types of
  // navigation, we may not be initialized yet. (See bugs 88986 and 86448.)
  // If this is the case, initialize on demand. This is a hack.
  // TODO(mdm): remove this hack once it is no longer necessary.
  if (show_passwords_.GetPrefName().empty())
    InitializeHandler();

  ListValue entries;
  bool show_passwords = *show_passwords_ && is_user_authenticated_;
  string16 placeholder(ASCIIToUTF16("        "));
  for (size_t i = 0; i < password_list_.size(); ++i) {
    ListValue* entry = new ListValue();
    entry->Append(new StringValue(net::FormatUrl(password_list_[i]->origin,
                                                 languages_)));
    entry->Append(new StringValue(password_list_[i]->username_value));
    if (show_passwords) {
      entry->Append(new StringValue(password_list_[i]->password_value));
    } else {
      // Use a placeholder value with the same length as the password.
      entry->Append(new StringValue(
          string16(password_list_[i]->password_value.length(), ' ')));
    }
    entries.Append(entry);
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setSavedPasswordsList",
                                   entries);
}

void PasswordManagerHandler::SetPasswordExceptionList() {
  ListValue entries;
  for (size_t i = 0; i < password_exception_list_.size(); ++i) {
    entries.Append(new StringValue(
        net::FormatUrl(password_exception_list_[i]->origin, languages_)));
  }

  web_ui()->CallJavascriptFunction("PasswordManager.setPasswordExceptionsList",
                                   entries);
}

PasswordManagerHandler::ListPopulater::ListPopulater(
    PasswordManagerHandler* page)
    : page_(page),
      pending_login_query_(0) {
}

PasswordManagerHandler::ListPopulater::~ListPopulater() {
}

PasswordManagerHandler::PasswordListPopulater::PasswordListPopulater(
    PasswordManagerHandler* page) : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetAutofillableLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display passwords.";
  }
}

void PasswordManagerHandler::PasswordListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_list_.clear();
  page_->password_list_.insert(page_->password_list_.end(),
                               result.begin(), result.end());
  page_->SetPasswordList();
}

void PasswordManagerHandler::PasswordListPopulater::OnGetPasswordStoreResults(
    const std::vector<autofill::PasswordForm*>& results) {
  // TODO(kaiwang): Implement when I refactor
  // PasswordStore::GetAutofillableLogins and PasswordStore::GetBlacklistLogins.
  NOTIMPLEMENTED();
}

PasswordManagerHandler::PasswordExceptionListPopulater::
    PasswordExceptionListPopulater(PasswordManagerHandler* page)
        : ListPopulater(page) {
}

void PasswordManagerHandler::PasswordExceptionListPopulater::Populate() {
  PasswordStore* store = page_->GetPasswordStore();
  if (store != NULL) {
    if (pending_login_query_)
      store->CancelRequest(pending_login_query_);

    pending_login_query_ = store->GetBlacklistLogins(this);
  } else {
    LOG(ERROR) << "No password store! Cannot display exceptions.";
  }
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnPasswordStoreRequestDone(
        CancelableRequestProvider::Handle handle,
        const std::vector<autofill::PasswordForm*>& result) {
  DCHECK_EQ(pending_login_query_, handle);
  pending_login_query_ = 0;
  page_->password_exception_list_.clear();
  page_->password_exception_list_.insert(page_->password_exception_list_.end(),
                                         result.begin(), result.end());
  page_->SetPasswordExceptionList();
}

void PasswordManagerHandler::PasswordExceptionListPopulater::
    OnGetPasswordStoreResults(
        const std::vector<autofill::PasswordForm*>& results) {
  // TODO(kaiwang): Implement when I refactor
  // PasswordStore::GetAutofillableLogins and PasswordStore::GetBlacklistLogins.
  NOTIMPLEMENTED();
}

}  // namespace options
<|endoftext|>


<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <type_traits>

#include <hadesmem/config.hpp>

namespace hadesmem
{

namespace detail
{

template <typename T, typename U = typename std::remove_cv<T>::type>
struct IsCharType
{
  static bool const value = std::is_same<U, char>::value ||
    std::is_same<U, signed char>::value ||
    std::is_same<U, unsigned char>::value ||
    std::is_same<U, wchar_t>::value ||
    std::is_same<U, char16_t>::value ||
    std::is_same<U, char32_t>::value;
};

template <typename T>
struct IsTriviallyCopyable
{
#if defined(HADESMEM_GCC) || defined(HADESMEM_CLANG)
  // TODO: Update to use std::is_trivially_copyable trait when available in
  // libstdc++.
  static bool const value = std::is_trivial<T>::value;
#else
  static bool const value = std::is_trivially_copyable<T>::value;
#endif
};

template <typename T>
struct IsDefaultConstructible
{
#if defined(HADESMEM_CLANG)
  // TODO: Update to use std::is_default_constructible trait when available in
  // libstdc++. In the meantime it should be safe to mark every type as
  // default constructible as even if it isn't, it will result in a
  // compile-time error anyway.
  static bool const value = true;
#else
  static bool const value = std::is_default_constructible<T>::value;
#endif
};

}

}
<commit_msg>* Workaround for Dev12 build break.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <type_traits>

#include <hadesmem/config.hpp>

namespace hadesmem
{

namespace detail
{

template <typename T, typename U = typename std::remove_cv<T>::type>
struct IsCharType
{
  static bool const value = std::is_same<U, char>::value ||
    std::is_same<U, signed char>::value ||
    std::is_same<U, unsigned char>::value ||
    std::is_same<U, wchar_t>::value ||
    std::is_same<U, char16_t>::value ||
    std::is_same<U, char32_t>::value;
};

template <typename T>
struct IsTriviallyCopyable
{
#if defined(HADESMEM_GCC) || defined(HADESMEM_CLANG)
  // TODO: Update to use std::is_trivially_copyable trait when available in
  // libstdc++.
  static bool const value = std::is_trivial<T>::value;
#else
  // TODO: Update to use std::is_trivially_copyable when MSVC is fixed. Dev12
  // seems to be broken for arrays.
  static bool const value = std::is_trivial<T>::value;
#endif
};

template <typename T>
struct IsDefaultConstructible
{
#if defined(HADESMEM_CLANG)
  // TODO: Update to use std::is_default_constructible trait when available in
  // libstdc++. In the meantime it should be safe to mark every type as
  // default constructible as even if it isn't, it will result in a
  // compile-time error anyway.
  static bool const value = true;
#else
  static bool const value = std::is_default_constructible<T>::value;
#endif
};

}

}
<|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/chromeos/login/account_creation_view.h"

#include "app/gfx/canvas.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "views/border.h"

namespace {

const int kCornerRadius = 12;
const int kShadow = 10;
const int kPadding = 30;
const SkColor kBackground = SK_ColorWHITE;
const SkColor kShadowColor = 0x40223673;

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// AccountCreationView, public:
AccountCreationView::AccountCreationView() {
}

AccountCreationView::~AccountCreationView() {
}

void AccountCreationView::Init() {
  // Use rounded rect background.
  views::Border* border = chromeos::CreateWizardBorder(
      &chromeos::BorderDefinition::kScreenBorder);
  set_border(border);
}

void AccountCreationView::InitDOM(Profile* profile,
                                  SiteInstance* site_instance) {
  DOMView::Init(profile, site_instance);
}

void AccountCreationView::SetTabContentsDelegate(
    TabContentsDelegate* delegate) {
  tab_contents_->set_delegate(delegate);
}

///////////////////////////////////////////////////////////////////////////////
// AccountCreationView, views::View implementation:
void AccountCreationView::Paint(gfx::Canvas* canvas) {
  PaintBorder(canvas);
  DOMView::Paint(canvas);
}
<commit_msg>chromeos: remove some variables that are now not more necessary. <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/chromeos/login/account_creation_view.h"

#include "app/gfx/canvas.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "views/border.h"

///////////////////////////////////////////////////////////////////////////////
// AccountCreationView, public:
AccountCreationView::AccountCreationView() {
}

AccountCreationView::~AccountCreationView() {
}

void AccountCreationView::Init() {
  // Use rounded rect background.
  views::Border* border = chromeos::CreateWizardBorder(
      &chromeos::BorderDefinition::kScreenBorder);
  set_border(border);
}

void AccountCreationView::InitDOM(Profile* profile,
                                  SiteInstance* site_instance) {
  DOMView::Init(profile, site_instance);
}

void AccountCreationView::SetTabContentsDelegate(
    TabContentsDelegate* delegate) {
  tab_contents_->set_delegate(delegate);
}

///////////////////////////////////////////////////////////////////////////////
// AccountCreationView, views::View implementation:
void AccountCreationView::Paint(gfx::Canvas* canvas) {
  PaintBorder(canvas);
  DOMView::Paint(canvas);
}
<|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 "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/extensions/api/socket/socket_api.h"
#include "chrome/browser/extensions/api/socket/test_echo_server_udp.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"

using namespace extension_function_test_utils;

namespace {

class SocketApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
  }
};

}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function, "[\"udp\"]", browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  EXPECT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  // TODO(miket): this test currently passes only because of artificial code
  // that doesn't run in production. Fix this when we're able to.
  RunFunctionAndReturnError(socket_create_function, "[\"xxxx\"]", browser(),
                            NONE);
}

// http://code.google.com/p/chromium/issues/detail?id=109337
//
// Currently believed to be fixed, but we're leaving it marked flaky
// for a few days to let it percolate through the trybots.
IN_PROC_BROWSER_TEST_F(SocketApiTest, FLAKY_SocketExtension) {
  scoped_refptr<extensions::TestEchoServerUDP> server =
      new extensions::TestEchoServerUDP();

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ASSERT_TRUE(StartTestServer());
  ExtensionTestMessageListener listener("port_please", true);

  int port = server->Start();
  ASSERT_TRUE(port > 0);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(port);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();

  EXPECT_TRUE(server->WaitUntilFinished());
}
<commit_msg>Remove FLAKY_ prefix after confirming several good days on waterfall.<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 "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "chrome/browser/extensions/api/socket/socket_api.h"
#include "chrome/browser/extensions/api/socket/test_echo_server_udp.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"

using namespace extension_function_test_utils;

namespace {

class SocketApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
    command_line->AppendSwitch(switches::kEnablePlatformApps);
  }
};

}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateGood) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
      socket_create_function, "[\"udp\"]", browser(), NONE));
  ASSERT_EQ(base::Value::TYPE_DICTIONARY, result->GetType());
  DictionaryValue *value = static_cast<DictionaryValue*>(result.get());
  int socketId = -1;
  EXPECT_TRUE(value->GetInteger("socketId", &socketId));
  EXPECT_TRUE(socketId > 0);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketCreateBad) {
  scoped_refptr<extensions::SocketCreateFunction> socket_create_function(
      new extensions::SocketCreateFunction());
  scoped_refptr<Extension> empty_extension(CreateEmptyExtension());

  socket_create_function->set_extension(empty_extension.get());
  socket_create_function->set_has_callback(true);

  // TODO(miket): this test currently passes only because of artificial code
  // that doesn't run in production. Fix this when we're able to.
  RunFunctionAndReturnError(socket_create_function, "[\"xxxx\"]", browser(),
                            NONE);
}

IN_PROC_BROWSER_TEST_F(SocketApiTest, SocketExtension) {
  scoped_refptr<extensions::TestEchoServerUDP> server =
      new extensions::TestEchoServerUDP();

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());

  ASSERT_TRUE(StartTestServer());
  ExtensionTestMessageListener listener("port_please", true);

  int port = server->Start();
  ASSERT_TRUE(port > 0);

  ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("socket/api")));
  EXPECT_TRUE(listener.WaitUntilSatisfied());
  listener.Reply(port);

  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();

  EXPECT_TRUE(server->WaitUntilFinished());
}
<|endoftext|>


<commit_before>#define HAS_HTTP_CLIENT_LOG
#include <boost/thread.hpp>
#include "asynchttpclient.h"
#include "synchttpclient.h"

boost::asio::io_service g_io_service;

void r_cb(boost::shared_ptr<CAsyncHttpClient>& pClient, const ResponseInfo& r)
{
    if (r.timeout)
    {
        std::cout << "timeout" << std::endl;
    }
    else if (!r.error_msg.empty())
    {
        std::cout << r.error_msg.c_str() << std::endl;
    }
    else if (-1 == r.status_code)
    {
        std::cout << "unknown error" << std::endl;
    }
    else
    {
        std::cout << "response size=" << r.content.size()
            << ", content:\r\n" << r.content.c_str() << std::endl;
    }
}

void f()
{
    while (1)
    {
        RequestInfo req;
        req.set_url("http://www.baidu.com/123");
        req.set_method(METHOD_GET);
        boost::shared_ptr<CAsyncHttpClient> pClient = boost::make_shared<CAsyncHttpClient>(boost::ref(g_io_service), 5);
        pClient->make_request(boost::bind(r_cb, pClient, _1), req);
        boost::this_thread::sleep(boost::posix_time::seconds(1));
    }
}

void test_sync()
{
    RequestInfo req;
    req.set_url("http://www.baidu.com/123");
    req.set_method(METHOD_GET);
    CSyncHttpClient client(5);
    const ResponseInfo& r = client.make_request(req);
}

void test_async()
{
    boost::thread t(f);
    {
        boost::asio::io_service::work work(g_io_service);
        g_io_service.run();
    }
}

int main()
{
    test_async();
    return 0;
}

<commit_msg>modify test gcc warnning<commit_after>#define HAS_HTTP_CLIENT_LOG
#include <boost/thread.hpp>
#include "asynchttpclient.h"
#include "synchttpclient.h"

boost::asio::io_service g_io_service;

void handle_response(const ResponseInfo& r)
{
    if (r.timeout)
    {
        std::cout << "timeout" << std::endl;
    }
    else if (!r.error_msg.empty())
    {
        std::cout << r.error_msg.c_str() << std::endl;
    }
    else if (-1 == r.status_code)
    {
        std::cout << "unknown error" << std::endl;
    }
    else
    {
        std::cout << "response size=" << r.content.size()
            << ", content:\r\n" << r.content.c_str() << std::endl;
    }
}

void r_cb(boost::shared_ptr<CAsyncHttpClient>& pClient, const ResponseInfo& r)
{
    handle_response(r);
}

void f()
{
    while (1)
    {
        RequestInfo req;
        req.set_url("http://www.baidu.com/123");
        req.set_method(METHOD_GET);
        boost::shared_ptr<CAsyncHttpClient> pClient = boost::make_shared<CAsyncHttpClient>(boost::ref(g_io_service), 5);
        pClient->make_request(boost::bind(r_cb, pClient, _1), req);
        boost::this_thread::sleep(boost::posix_time::seconds(1));
    }
}

void test_sync()
{
    RequestInfo req;
    req.set_url("http://www.baidu.com/123");
    req.set_method(METHOD_GET);
    CSyncHttpClient client(5);
    handle_response(client.make_request(req));
}

void test_async()
{
    boost::thread t(f);
    {
        boost::asio::io_service::work work(g_io_service);
        g_io_service.run();
    }
}

int main()
{
    test_async();
    return 0;
}

<|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/extensions/extension_permissions_api.h"

#include "base/json/json_writer.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_permissions_api_constants.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "chrome/common/extensions/url_pattern_set.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"

namespace keys = extension_permissions_module_constants;

namespace {

enum AutoConfirmForTest {
  DO_NOT_SKIP = 0,
  PROCEED,
  ABORT
};
AutoConfirmForTest auto_confirm_for_tests = DO_NOT_SKIP;

DictionaryValue* PackPermissionsToValue(const ExtensionPermissionSet* set) {
  DictionaryValue* value = new DictionaryValue();

  // Generate the list of API permissions.
  ListValue* apis = new ListValue();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  for (ExtensionAPIPermissionSet::const_iterator i = set->apis().begin();
       i != set->apis().end(); ++i)
    apis->Append(Value::CreateStringValue(info->GetByID(*i)->name()));

  // TODO(jstritar): Include hosts once the API supports them. At that point,
  // we could also shared this code with ExtensionPermissionSet methods in
  // ExtensionPrefs.

  value->Set(keys::kApisKey, apis);
  return value;
}

// Creates a new ExtensionPermissionSet from its |value| and passes ownership to
// the caller through |ptr|. Sets |bad_message| to true if the message is badly
// formed. Returns false if the method fails to unpack a permission set.
bool UnpackPermissionsFromValue(DictionaryValue* value,
                                scoped_refptr<ExtensionPermissionSet>* ptr,
                                bool* bad_message,
                                std::string* error) {
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  ExtensionAPIPermissionSet apis;
  if (value->HasKey(keys::kApisKey)) {
    ListValue* api_list = NULL;
    if (!value->GetList(keys::kApisKey, &api_list)) {
      *bad_message = true;
      return false;
    }
    for (size_t i = 0; i < api_list->GetSize(); ++i) {
      std::string api_name;
      if (!api_list->GetString(i, &api_name)) {
        *bad_message = true;
        return false;
      }

      ExtensionAPIPermission* permission = info->GetByName(api_name);
      if (!permission) {
        *error = base::StringPrintf(
            keys::kUnknownPermissionError, api_name.c_str());
        return false;
      }
      apis.insert(permission->id());
    }
  }

  // Ignore host permissions for now.
  URLPatternSet empty_set;
  *ptr = new ExtensionPermissionSet(apis, empty_set, empty_set);
  return true;
}

} // namespace

ExtensionPermissionsManager::ExtensionPermissionsManager(
    ExtensionService* extension_service)
    : extension_service_(extension_service) {
  RegisterWhitelist();
}

ExtensionPermissionsManager::~ExtensionPermissionsManager() {
}

void ExtensionPermissionsManager::AddPermissions(
    const Extension* extension, const ExtensionPermissionSet* permissions) {
  scoped_refptr<const ExtensionPermissionSet> existing(
      extension->GetActivePermissions());
  scoped_refptr<ExtensionPermissionSet> total(
      ExtensionPermissionSet::CreateUnion(existing, permissions));
  scoped_refptr<ExtensionPermissionSet> added(
      ExtensionPermissionSet::CreateDifference(total.get(), existing));

  extension_service_->UpdateActivePermissions(extension, total.get());

  // Update the granted permissions so we don't auto-disable the extension.
  extension_service_->GrantPermissions(extension);

  NotifyPermissionsUpdated(extension, total.get(), added.get(), ADDED);
}

void ExtensionPermissionsManager::RemovePermissions(
    const Extension* extension, const ExtensionPermissionSet* permissions) {
  scoped_refptr<const ExtensionPermissionSet> existing(
      extension->GetActivePermissions());
  scoped_refptr<ExtensionPermissionSet> total(
      ExtensionPermissionSet::CreateDifference(existing, permissions));
  scoped_refptr<ExtensionPermissionSet> removed(
      ExtensionPermissionSet::CreateDifference(existing, total.get()));

  // We update the active permissions, and not the granted permissions, because
  // the extension, not the user, removed the permissions. This allows the
  // extension to add them again without prompting the user.
  extension_service_->UpdateActivePermissions(extension, total.get());

  NotifyPermissionsUpdated(extension, total.get(), removed.get(), REMOVED);
}

void ExtensionPermissionsManager::DispatchEvent(
    const std::string& extension_id,
    const char* event_name,
    const ExtensionPermissionSet* changed_permissions) {
  Profile* profile = extension_service_->profile();
  if (profile && profile->GetExtensionEventRouter()) {
    ListValue value;
    value.Append(PackPermissionsToValue(changed_permissions));
    std::string json_value;
    base::JSONWriter::Write(&value, false, &json_value);
    profile->GetExtensionEventRouter()->DispatchEventToExtension(
        extension_id, event_name, json_value, profile, GURL());
  }
}

void ExtensionPermissionsManager::NotifyPermissionsUpdated(
    const Extension* extension,
    const ExtensionPermissionSet* active,
    const ExtensionPermissionSet* changed,
    EventType event_type) {
  if (!changed || changed->IsEmpty())
    return;

  UpdatedExtensionPermissionsInfo::Reason reason;
  const char* event_name = NULL;

  if (event_type == REMOVED) {
    reason = UpdatedExtensionPermissionsInfo::REMOVED;
    event_name = keys::kOnRemoved;
  } else {
    CHECK_EQ(ADDED, event_type);
    reason = UpdatedExtensionPermissionsInfo::ADDED;
    event_name = keys::kOnAdded;
  }

  // Notify other APIs or interested parties.
  UpdatedExtensionPermissionsInfo info = UpdatedExtensionPermissionsInfo(
      extension, changed, reason);
  NotificationService::current()->Notify(
      chrome::NOTIFICATION_EXTENSION_PERMISSIONS_UPDATED,
      Source<Profile>(extension_service_->profile()),
      Details<UpdatedExtensionPermissionsInfo>(&info));

  // Trigger the onAdded and onRemoved events in the extension.
  DispatchEvent(extension->id(), event_name, changed);

  // Send the new permissions to the renderers.
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance()) {
    RenderProcessHost* host = i.GetCurrentValue();
    Profile* profile = Profile::FromBrowserContext(host->browser_context());
    if (extension_service_->profile()->IsSameProfile(profile))
      host->Send(new ExtensionMsg_UpdatePermissions(
          extension->id(),
          active->apis(),
          active->explicit_hosts(),
          active->scriptable_hosts()));
  }
}

void ExtensionPermissionsManager::RegisterWhitelist() {
  // TODO(jstritar): This could be a field on ExtensionAPIPermission.
  ExtensionAPIPermissionSet api_whitelist;
  api_whitelist.insert(ExtensionAPIPermission::kClipboardRead);
  api_whitelist.insert(ExtensionAPIPermission::kClipboardWrite);
  api_whitelist.insert(ExtensionAPIPermission::kNotification);
  api_whitelist.insert(ExtensionAPIPermission::kBookmark);
  api_whitelist.insert(ExtensionAPIPermission::kContextMenus);
  api_whitelist.insert(ExtensionAPIPermission::kCookie);
  api_whitelist.insert(ExtensionAPIPermission::kDebugger);
  api_whitelist.insert(ExtensionAPIPermission::kHistory);
  api_whitelist.insert(ExtensionAPIPermission::kIdle);
  api_whitelist.insert(ExtensionAPIPermission::kTab);
  api_whitelist.insert(ExtensionAPIPermission::kManagement);
  api_whitelist.insert(ExtensionAPIPermission::kBackground);
  whitelist_ = new ExtensionPermissionSet(
      api_whitelist, URLPatternSet(), URLPatternSet());
}

bool ContainsPermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  std::string error;
  if (!args)
    return false;

  scoped_refptr<ExtensionPermissionSet> permissions;
  if (!UnpackPermissionsFromValue(args, &permissions, &bad_message_, &error_))
    return false;
  CHECK(permissions.get());

  result_.reset(Value::CreateBooleanValue(
      GetExtension()->GetActivePermissions()->Contains(*permissions)));
  return true;
}

bool GetAllPermissionsFunction::RunImpl() {
  result_.reset(PackPermissionsToValue(
      GetExtension()->GetActivePermissions()));
  return true;
}

bool RemovePermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  if (!args)
    return false;

  scoped_refptr<ExtensionPermissionSet> permissions;
  if (!UnpackPermissionsFromValue(args, &permissions, &bad_message_, &error_))
    return false;
  CHECK(permissions.get());

  const Extension* extension = GetExtension();
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();

  // Make sure they're only trying to remove permissions supported by this API.
  scoped_refptr<ExtensionPermissionSet> unsupported(
      ExtensionPermissionSet::CreateDifference(
          permissions.get(), &perms_manager->whitelist()));
  if (unsupported->apis().size()) {
    std::string api_name = info->GetByID(*unsupported->apis().begin())->name();
    error_ = base::StringPrintf(keys::kNotWhitelistedError, api_name.c_str());
    return false;
  }

  // Make sure we don't remove any required pemissions.
  const ExtensionPermissionSet* required = extension->required_permission_set();
  scoped_refptr<ExtensionPermissionSet> intersection(
      ExtensionPermissionSet::CreateIntersection(permissions.get(), required));
  if (!intersection->IsEmpty()) {
    error_ = keys::kCantRemoveRequiredPermissionsError;
    result_.reset(Value::CreateBooleanValue(false));
    return false;
  }

  perms_manager->RemovePermissions(extension, permissions.get());
  result_.reset(Value::CreateBooleanValue(true));
  return true;
}

// static
void RequestPermissionsFunction::SetAutoConfirmForTests(bool should_proceed) {
  auto_confirm_for_tests = should_proceed ? PROCEED : ABORT;
}

RequestPermissionsFunction::RequestPermissionsFunction() {}
RequestPermissionsFunction::~RequestPermissionsFunction() {}

bool RequestPermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  if (!args)
    return false;

  if (!UnpackPermissionsFromValue(
          args, &requested_permissions_, &bad_message_, &error_))
    return false;
  CHECK(requested_permissions_.get());

  extension_ = GetExtension();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();
  ExtensionPrefs* prefs = profile()->GetExtensionService()->extension_prefs();

  // Make sure only white listed permissions have been requested.
  scoped_refptr<ExtensionPermissionSet> unsupported(
      ExtensionPermissionSet::CreateDifference(
          requested_permissions_.get(), &perms_manager->whitelist()));
  if (unsupported->apis().size()) {
    std::string api_name = info->GetByID(*unsupported->apis().begin())->name();
    error_ = base::StringPrintf(keys::kNotWhitelistedError, api_name.c_str());
    return false;
  }

  // The requested permissions must be defined as optional in the manifest.
  if (!extension_->optional_permission_set()->Contains(
          *requested_permissions_)) {
    error_ = keys::kNotInOptionalPermissionsError;
    result_.reset(Value::CreateBooleanValue(false));
    return false;
  }

  // We don't need to prompt the user if the requested permissions are a subset
  // of the granted permissions set.
  const ExtensionPermissionSet* granted =
      prefs->GetGrantedPermissions(extension_->id());
  if (granted && granted->Contains(*requested_permissions_)) {
    perms_manager->AddPermissions(extension_, requested_permissions_.get());
    result_.reset(Value::CreateBooleanValue(true));
    SendResponse(true);
    return true;
  }

  // Filter out the granted permissions so we only prompt for new ones.
  requested_permissions_ = ExtensionPermissionSet::CreateDifference(
      requested_permissions_.get(), granted);

  // Balanced with Release() in InstallUIProceed() and InstallUIAbort().
  AddRef();

  // We don't need to show the prompt if there are no new warnings, or if
  // we're skipping the confirmation UI. All extension types but INTERNAL
  // are allowed to silently increase their permission level.
  if (auto_confirm_for_tests == PROCEED ||
      requested_permissions_->GetWarningMessages().size() == 0) {
    InstallUIProceed();
  } else if (auto_confirm_for_tests == ABORT) {
    // Pretend the user clicked cancel.
    InstallUIAbort(true);
  } else {
    CHECK_EQ(DO_NOT_SKIP, auto_confirm_for_tests);
    install_ui_.reset(new ExtensionInstallUI(profile()));
    install_ui_->ConfirmPermissions(
        this, extension_, requested_permissions_.get());
  }

  return true;
}

void RequestPermissionsFunction::InstallUIProceed() {
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();

  install_ui_.reset();
  result_.reset(Value::CreateBooleanValue(true));
  perms_manager->AddPermissions(extension_, requested_permissions_.get());

  SendResponse(true);

  Release();
}

void RequestPermissionsFunction::InstallUIAbort(bool user_initiated) {
  install_ui_.reset();
  result_.reset(Value::CreateBooleanValue(false));
  requested_permissions_ = NULL;

  SendResponse(true);
  Release();
}
<commit_msg>Revert 94337 - Fix missed use.<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/extensions/extension_permissions_api.h"

#include "base/json/json_writer.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "chrome/browser/extensions/extension_event_router.h"
#include "chrome/browser/extensions/extension_permissions_api_constants.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_messages.h"
#include "chrome/common/extensions/extension_permission_set.h"
#include "chrome/common/extensions/url_pattern_set.h"
#include "content/common/notification_service.h"
#include "googleurl/src/gurl.h"

namespace keys = extension_permissions_module_constants;

namespace {

enum AutoConfirmForTest {
  DO_NOT_SKIP = 0,
  PROCEED,
  ABORT
};
AutoConfirmForTest auto_confirm_for_tests = DO_NOT_SKIP;

DictionaryValue* PackPermissionsToValue(const ExtensionPermissionSet* set) {
  DictionaryValue* value = new DictionaryValue();

  // Generate the list of API permissions.
  ListValue* apis = new ListValue();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  for (ExtensionAPIPermissionSet::const_iterator i = set->apis().begin();
       i != set->apis().end(); ++i)
    apis->Append(Value::CreateStringValue(info->GetByID(*i)->name()));

  // TODO(jstritar): Include hosts once the API supports them. At that point,
  // we could also shared this code with ExtensionPermissionSet methods in
  // ExtensionPrefs.

  value->Set(keys::kApisKey, apis);
  return value;
}

// Creates a new ExtensionPermissionSet from its |value| and passes ownership to
// the caller through |ptr|. Sets |bad_message| to true if the message is badly
// formed. Returns false if the method fails to unpack a permission set.
bool UnpackPermissionsFromValue(DictionaryValue* value,
                                scoped_refptr<ExtensionPermissionSet>* ptr,
                                bool* bad_message,
                                std::string* error) {
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  ExtensionAPIPermissionSet apis;
  if (value->HasKey(keys::kApisKey)) {
    ListValue* api_list = NULL;
    if (!value->GetList(keys::kApisKey, &api_list)) {
      *bad_message = true;
      return false;
    }
    for (size_t i = 0; i < api_list->GetSize(); ++i) {
      std::string api_name;
      if (!api_list->GetString(i, &api_name)) {
        *bad_message = true;
        return false;
      }

      ExtensionAPIPermission* permission = info->GetByName(api_name);
      if (!permission) {
        *error = base::StringPrintf(
            keys::kUnknownPermissionError, api_name.c_str());
        return false;
      }
      apis.insert(permission->id());
    }
  }

  // Ignore host permissions for now.
  URLPatternSet empty_set;
  *ptr = new ExtensionPermissionSet(apis, empty_set, empty_set);
  return true;
}

} // namespace

ExtensionPermissionsManager::ExtensionPermissionsManager(
    ExtensionService* extension_service)
    : extension_service_(extension_service) {
  RegisterWhitelist();
}

ExtensionPermissionsManager::~ExtensionPermissionsManager() {
}

void ExtensionPermissionsManager::AddPermissions(
    const Extension* extension, const ExtensionPermissionSet* permissions) {
  scoped_refptr<const ExtensionPermissionSet> existing(
      extension->GetActivePermissions());
  scoped_refptr<ExtensionPermissionSet> total(
      ExtensionPermissionSet::CreateUnion(existing, permissions));
  scoped_refptr<ExtensionPermissionSet> added(
      ExtensionPermissionSet::CreateDifference(total.get(), existing));

  extension_service_->UpdateActivePermissions(extension, total.get());

  // Update the granted permissions so we don't auto-disable the extension.
  extension_service_->GrantPermissions(extension);

  NotifyPermissionsUpdated(extension, total.get(), added.get(), ADDED);
}

void ExtensionPermissionsManager::RemovePermissions(
    const Extension* extension, const ExtensionPermissionSet* permissions) {
  scoped_refptr<const ExtensionPermissionSet> existing(
      extension->GetActivePermissions());
  scoped_refptr<ExtensionPermissionSet> total(
      ExtensionPermissionSet::CreateDifference(existing, permissions));
  scoped_refptr<ExtensionPermissionSet> removed(
      ExtensionPermissionSet::CreateDifference(existing, total.get()));

  // We update the active permissions, and not the granted permissions, because
  // the extension, not the user, removed the permissions. This allows the
  // extension to add them again without prompting the user.
  extension_service_->UpdateActivePermissions(extension, total.get());

  NotifyPermissionsUpdated(extension, total.get(), removed.get(), REMOVED);
}

void ExtensionPermissionsManager::DispatchEvent(
    const std::string& extension_id,
    const char* event_name,
    const ExtensionPermissionSet* changed_permissions) {
  Profile* profile = extension_service_->profile();
  if (profile && profile->GetExtensionEventRouter()) {
    ListValue value;
    value.Append(PackPermissionsToValue(changed_permissions));
    std::string json_value;
    base::JSONWriter::Write(&value, false, &json_value);
    profile->GetExtensionEventRouter()->DispatchEventToExtension(
        extension_id, event_name, json_value, profile, GURL());
  }
}

void ExtensionPermissionsManager::NotifyPermissionsUpdated(
    const Extension* extension,
    const ExtensionPermissionSet* active,
    const ExtensionPermissionSet* changed,
    EventType event_type) {
  if (!changed || changed->IsEmpty())
    return;

  UpdatedExtensionPermissionsInfo::Reason reason;
  const char* event_name = NULL;

  if (event_type == REMOVED) {
    reason = UpdatedExtensionPermissionsInfo::REMOVED;
    event_name = keys::kOnRemoved;
  } else {
    CHECK_EQ(ADDED, event_type);
    reason = UpdatedExtensionPermissionsInfo::ADDED;
    event_name = keys::kOnAdded;
  }

  // Notify other APIs or interested parties.
  UpdatedExtensionPermissionsInfo info = UpdatedExtensionPermissionsInfo(
      extension, changed, reason);
  NotificationService::current()->Notify(
      chrome::NOTIFICATION_EXTENSION_PERMISSIONS_UPDATED,
      Source<Profile>(extension_service_->profile()),
      Details<UpdatedExtensionPermissionsInfo>(&info));

  // Trigger the onAdded and onRemoved events in the extension.
  DispatchEvent(extension->id(), event_name, changed);

  // Send the new permissions to the renderers.
  for (RenderProcessHost::iterator i(RenderProcessHost::AllHostsIterator());
       !i.IsAtEnd(); i.Advance()) {
    RenderProcessHost* host = i.GetCurrentValue();
    if (extension_service_->profile()->IsSameProfile(host->profile()))
      host->Send(new ExtensionMsg_UpdatePermissions(
          extension->id(),
          active->apis(),
          active->explicit_hosts(),
          active->scriptable_hosts()));
  }
}

void ExtensionPermissionsManager::RegisterWhitelist() {
  // TODO(jstritar): This could be a field on ExtensionAPIPermission.
  ExtensionAPIPermissionSet api_whitelist;
  api_whitelist.insert(ExtensionAPIPermission::kClipboardRead);
  api_whitelist.insert(ExtensionAPIPermission::kClipboardWrite);
  api_whitelist.insert(ExtensionAPIPermission::kNotification);
  api_whitelist.insert(ExtensionAPIPermission::kBookmark);
  api_whitelist.insert(ExtensionAPIPermission::kContextMenus);
  api_whitelist.insert(ExtensionAPIPermission::kCookie);
  api_whitelist.insert(ExtensionAPIPermission::kDebugger);
  api_whitelist.insert(ExtensionAPIPermission::kHistory);
  api_whitelist.insert(ExtensionAPIPermission::kIdle);
  api_whitelist.insert(ExtensionAPIPermission::kTab);
  api_whitelist.insert(ExtensionAPIPermission::kManagement);
  api_whitelist.insert(ExtensionAPIPermission::kBackground);
  whitelist_ = new ExtensionPermissionSet(
      api_whitelist, URLPatternSet(), URLPatternSet());
}

bool ContainsPermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  std::string error;
  if (!args)
    return false;

  scoped_refptr<ExtensionPermissionSet> permissions;
  if (!UnpackPermissionsFromValue(args, &permissions, &bad_message_, &error_))
    return false;
  CHECK(permissions.get());

  result_.reset(Value::CreateBooleanValue(
      GetExtension()->GetActivePermissions()->Contains(*permissions)));
  return true;
}

bool GetAllPermissionsFunction::RunImpl() {
  result_.reset(PackPermissionsToValue(
      GetExtension()->GetActivePermissions()));
  return true;
}

bool RemovePermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  if (!args)
    return false;

  scoped_refptr<ExtensionPermissionSet> permissions;
  if (!UnpackPermissionsFromValue(args, &permissions, &bad_message_, &error_))
    return false;
  CHECK(permissions.get());

  const Extension* extension = GetExtension();
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();

  // Make sure they're only trying to remove permissions supported by this API.
  scoped_refptr<ExtensionPermissionSet> unsupported(
      ExtensionPermissionSet::CreateDifference(
          permissions.get(), &perms_manager->whitelist()));
  if (unsupported->apis().size()) {
    std::string api_name = info->GetByID(*unsupported->apis().begin())->name();
    error_ = base::StringPrintf(keys::kNotWhitelistedError, api_name.c_str());
    return false;
  }

  // Make sure we don't remove any required pemissions.
  const ExtensionPermissionSet* required = extension->required_permission_set();
  scoped_refptr<ExtensionPermissionSet> intersection(
      ExtensionPermissionSet::CreateIntersection(permissions.get(), required));
  if (!intersection->IsEmpty()) {
    error_ = keys::kCantRemoveRequiredPermissionsError;
    result_.reset(Value::CreateBooleanValue(false));
    return false;
  }

  perms_manager->RemovePermissions(extension, permissions.get());
  result_.reset(Value::CreateBooleanValue(true));
  return true;
}

// static
void RequestPermissionsFunction::SetAutoConfirmForTests(bool should_proceed) {
  auto_confirm_for_tests = should_proceed ? PROCEED : ABORT;
}

RequestPermissionsFunction::RequestPermissionsFunction() {}
RequestPermissionsFunction::~RequestPermissionsFunction() {}

bool RequestPermissionsFunction::RunImpl() {
  DictionaryValue* args = NULL;
  EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &args));
  if (!args)
    return false;

  if (!UnpackPermissionsFromValue(
          args, &requested_permissions_, &bad_message_, &error_))
    return false;
  CHECK(requested_permissions_.get());

  extension_ = GetExtension();
  ExtensionPermissionsInfo* info = ExtensionPermissionsInfo::GetInstance();
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();
  ExtensionPrefs* prefs = profile()->GetExtensionService()->extension_prefs();

  // Make sure only white listed permissions have been requested.
  scoped_refptr<ExtensionPermissionSet> unsupported(
      ExtensionPermissionSet::CreateDifference(
          requested_permissions_.get(), &perms_manager->whitelist()));
  if (unsupported->apis().size()) {
    std::string api_name = info->GetByID(*unsupported->apis().begin())->name();
    error_ = base::StringPrintf(keys::kNotWhitelistedError, api_name.c_str());
    return false;
  }

  // The requested permissions must be defined as optional in the manifest.
  if (!extension_->optional_permission_set()->Contains(
          *requested_permissions_)) {
    error_ = keys::kNotInOptionalPermissionsError;
    result_.reset(Value::CreateBooleanValue(false));
    return false;
  }

  // We don't need to prompt the user if the requested permissions are a subset
  // of the granted permissions set.
  const ExtensionPermissionSet* granted =
      prefs->GetGrantedPermissions(extension_->id());
  if (granted && granted->Contains(*requested_permissions_)) {
    perms_manager->AddPermissions(extension_, requested_permissions_.get());
    result_.reset(Value::CreateBooleanValue(true));
    SendResponse(true);
    return true;
  }

  // Filter out the granted permissions so we only prompt for new ones.
  requested_permissions_ = ExtensionPermissionSet::CreateDifference(
      requested_permissions_.get(), granted);

  // Balanced with Release() in InstallUIProceed() and InstallUIAbort().
  AddRef();

  // We don't need to show the prompt if there are no new warnings, or if
  // we're skipping the confirmation UI. All extension types but INTERNAL
  // are allowed to silently increase their permission level.
  if (auto_confirm_for_tests == PROCEED ||
      requested_permissions_->GetWarningMessages().size() == 0) {
    InstallUIProceed();
  } else if (auto_confirm_for_tests == ABORT) {
    // Pretend the user clicked cancel.
    InstallUIAbort(true);
  } else {
    CHECK_EQ(DO_NOT_SKIP, auto_confirm_for_tests);
    install_ui_.reset(new ExtensionInstallUI(profile()));
    install_ui_->ConfirmPermissions(
        this, extension_, requested_permissions_.get());
  }

  return true;
}

void RequestPermissionsFunction::InstallUIProceed() {
  ExtensionPermissionsManager* perms_manager =
      profile()->GetExtensionService()->permissions_manager();

  install_ui_.reset();
  result_.reset(Value::CreateBooleanValue(true));
  perms_manager->AddPermissions(extension_, requested_permissions_.get());

  SendResponse(true);

  Release();
}

void RequestPermissionsFunction::InstallUIAbort(bool user_initiated) {
  install_ui_.reset();
  result_.reset(Value::CreateBooleanValue(false));
  requested_permissions_ = NULL;

  SendResponse(true);
  Release();
}
<|endoftext|>


<commit_before>#include <assert.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>

#include "binaryheap.hpp"

int main() {
    std::vector<int> numbers;
    BinaryHeap<int, int> heap;
    for (int i = 0; i < 100; i++) {
        int n = rand();
        heap.insert(n, n);
        heap.check();
        numbers.push_back(n);
    }
    std::sort(numbers.begin(), numbers.end());
    std::vector<int> numbers2;
    while (!heap.empty()) {
        int payload, value;
        heap.top(payload, value);
        heap.pop();
        heap.check();
        assert(payload == value);
        numbers2.push_back(value);
    }
    assert(numbers == numbers2);
}
<commit_msg>test: ensure numbers are not repeated<commit_after>#include <assert.h>
#include <stdlib.h>
#include <vector>
#include <set>
#include <algorithm>

#include "binaryheap.hpp"

int main() {
    std::set<int> seen;
    std::vector<int> numbers;
    BinaryHeap<int, int> heap;
    for (int i = 0; i < 100; i++) {
        int n = rand();
        if (seen.find(n) == seen.end()) {
            heap.insert(n, n);
            heap.check();
            numbers.push_back(n);
        }
    }
    std::sort(numbers.begin(), numbers.end());
    std::vector<int> numbers2;
    while (!heap.empty()) {
        int payload, value;
        heap.top(payload, value);
        heap.pop();
        heap.check();
        assert(payload == value);
        numbers2.push_back(value);
    }
    assert(numbers == numbers2);
}
<|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_apitest.h"

// TODO(jcampan): http://crbug.com/27216 disabled because failing.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<commit_msg>Re-enable the ExtensionApiTest.Storage test.<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_apitest.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Storage) {
  ASSERT_TRUE(RunExtensionTest("storage")) << message_;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <algorithm>
#include "io/PGMIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 2) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " file.pgm" << std::endl;
        std::exit(1);
    }

    // const std::string filename{argv[1]};
    PGMIO pgm;
    auto mat = pgm.read<uint8_t>("tmp_ascii.pgm");
    // pgm.write(mat, "tmp_binary.pgm", PGMIO::PType::BINARY);
    pgm.write(mat, "tmp_ascii2.pgm", PGMIO::PType::ASCII);
}
<commit_msg>Update for removal of type-specifier from reader<commit_after>#include <iostream>
#include <algorithm>
#include "io/PgmIO.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " infile.pgm outfile.pgm"
                  << std::endl;
        std::exit(1);
    }

    // const std::string filename{argv[1]};
    PgmIO pgm;
    auto mat = pgm.read(argv[1]);
    pgm.write(mat, argv[2], PGMIO::PType::BINARY);
    // pgm.write(mat, argv[2], PGMIO::PType::ASCII);
}
<|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.

// TODO(jorlow): Reenable when https://bugs.webkit.org/show_bug.cgi?id=28094
//               is fixed.  Until then, this will cause crashes even if the
//               individual tests are disabled.
#if 0

#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
//static const char* kTopLevelFiles[] = {
  //"window-attributes-exist.html"
//};

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
static const char* kSubDirFiles[] = {
  "clear.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"localstorage/onstorage-attribute-setwindow.html",
  //"simple-events.html",
  "simple-usage.html",
  //"string-conversion.html",
//  "window-open.html"
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage"))
  {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DOMStorageLayoutTests) {
  // TODO(jorlow): Enable these tests when we remove them from the
  //               test_exceptions.txt file.
  //InitializeForLayoutTest(test_dir_, FilePath(), false);
  //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)
  //  RunLayoutTest(kTopLevelFiles[i], false, true);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

#endif
<commit_msg>Another attempt to enable the local storage ui test based layout tests.<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/common/chrome_switches.h"
#include "chrome/test/ui/ui_layout_test.h"

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
//static const char* kTopLevelFiles[] = {
  //"window-attributes-exist.html"
//};

// TODO(jorlow): Enable these tests when we remove them from the
//               test_exceptions.txt file.
static const char* kSubDirFiles[] = {
  "clear.html",
  "delete-removal.html",
  "enumerate-storage.html",
  "enumerate-with-length-and-key.html",
  //"iframe-events.html",
  //"index-get-and-set.html",
  //"onstorage-attribute-markup.html",
  //"onstorage-attribute-setattribute.html",
  //"localstorage/onstorage-attribute-setwindow.html",
  //"simple-events.html",
  "simple-usage.html",
  //"string-conversion.html",
//  "window-open.html"
};

class DOMStorageTest : public UILayoutTest {
 protected:
  DOMStorageTest()
      : UILayoutTest(),
        test_dir_(FilePath().AppendASCII("LayoutTests").
                  AppendASCII("storage").AppendASCII("domstorage"))
  {
  }

  virtual ~DOMStorageTest() { }

  virtual void SetUp() {
    launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking);
    launch_arguments_.AppendSwitch(switches::kEnableLocalStorage);
    launch_arguments_.AppendSwitch(switches::kEnableSessionStorage);
    UILayoutTest::SetUp();
  }

  FilePath test_dir_;
};

TEST_F(DOMStorageTest, DOMStorageLayoutTests) {
  // TODO(jorlow): Enable these tests when we remove them from the
  //               test_exceptions.txt file.
  //InitializeForLayoutTest(test_dir_, FilePath(), false);
  //for (size_t i=0; i<arraysize(kTopLevelFiles); ++i)
  //  RunLayoutTest(kTopLevelFiles[i], false, true);
}

TEST_F(DOMStorageTest, LocalStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}

TEST_F(DOMStorageTest, SessionStorageLayoutTests) {
  InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"),
                          false);
  for (size_t i=0; i<arraysize(kSubDirFiles); ++i)
    RunLayoutTest(kSubDirFiles[i], false);
}
<|endoftext|>


<commit_before><commit_msg>make a rather large performance enhancement in MULTIPLE sound effects<commit_after><|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/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"

// This file contains tests for the ProfileManager that require a heavyweight
// InProcessBrowserTest.  These include tests involving profile deletion.

// TODO(jeremy): crbug.com/103355 - These tests should be enabled on all
// platforms.
#if defined(OS_MACOSX)
class ProfileManagerBrowserTest : public InProcessBrowserTest {
 protected:
  // An observer that returns back to test code after a new profile
  // is initialized.
  class BlockOnProfileInitObserver : public ProfileManagerObserver {
   public:
    void OnProfileCreated(Profile* profile, Status status) {
      if (status == ProfileManagerObserver::STATUS_INITIALIZED) {
        MessageLoop::current()->Quit();
      }
    }
  };
};

// Delete single profile and make sure a new one is created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // We should start out with 1 profile.
  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);

  // Delete singleton profile.
  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_FALSE(singleton_profile_path.empty());
  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);

  // Spin things till profile is actually deleted.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, singleton_profile_path);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}

// Delete all profiles in a multi profile setup and make sure a new one is
// created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteAllProfiles) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // Create an additional profile.
  BlockOnProfileInitObserver observer;
  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
  profile_manager->CreateProfileAsync(new_path, &observer);

  // Spin to allow profile creation to take place, loop is terminated
  // by BlockOnProfileInitObserver when the profile is created.
  ui_test_utils::RunMessageLoop();

  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);

  // Delete all profiles.
  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);
  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);
  EXPECT_FALSE(profile_path1.empty());
  EXPECT_FALSE(profile_path2.empty());
  profile_manager->ScheduleProfileForDeletion(profile_path1);
  profile_manager->ScheduleProfileForDeletion(profile_path2);

  // Spin things so deletion can take place.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, profile_path1);
  EXPECT_NE(new_profile_path, profile_path2);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}
#endif // OS_MACOSX
<commit_msg>Marking ProfileManagerBrowserTest.DeleteAllProfiles as flaky on mac.<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/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/ui_test_utils.h"

// This file contains tests for the ProfileManager that require a heavyweight
// InProcessBrowserTest.  These include tests involving profile deletion.

// TODO(jeremy): crbug.com/103355 - These tests should be enabled on all
// platforms.
#if defined(OS_MACOSX)
class ProfileManagerBrowserTest : public InProcessBrowserTest {
 protected:
  // An observer that returns back to test code after a new profile
  // is initialized.
  class BlockOnProfileInitObserver : public ProfileManagerObserver {
   public:
    void OnProfileCreated(Profile* profile, Status status) {
      if (status == ProfileManagerObserver::STATUS_INITIALIZED) {
        MessageLoop::current()->Quit();
      }
    }
  };
};

// Delete single profile and make sure a new one is created.
IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, DeleteSingletonProfile) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // We should start out with 1 profile.
  ASSERT_EQ(cache.GetNumberOfProfiles(), 1U);

  // Delete singleton profile.
  FilePath singleton_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_FALSE(singleton_profile_path.empty());
  profile_manager->ScheduleProfileForDeletion(singleton_profile_path);

  // Spin things till profile is actually deleted.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, singleton_profile_path);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}

// Delete all profiles in a multi profile setup and make sure a new one is
// created.

#if defined(OS_MACOSX)
// See crbug.com/104851
#define MAYBE_DeleteAllProfiles FLAKY_DeleteAllProfiles
#else
#define MAYBE_DeleteAllProfiles DeleteAllProfiles
#endif

IN_PROC_BROWSER_TEST_F(ProfileManagerBrowserTest, MAYBE_DeleteAllProfiles) {
  ProfileManager* profile_manager = g_browser_process->profile_manager();
  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();

  // Create an additional profile.
  BlockOnProfileInitObserver observer;
  FilePath new_path = profile_manager->GenerateNextProfileDirectoryPath();
  profile_manager->CreateProfileAsync(new_path, &observer);

  // Spin to allow profile creation to take place, loop is terminated
  // by BlockOnProfileInitObserver when the profile is created.
  ui_test_utils::RunMessageLoop();

  ASSERT_EQ(cache.GetNumberOfProfiles(), 2U);

  // Delete all profiles.
  FilePath profile_path1 = cache.GetPathOfProfileAtIndex(0);
  FilePath profile_path2 = cache.GetPathOfProfileAtIndex(1);
  EXPECT_FALSE(profile_path1.empty());
  EXPECT_FALSE(profile_path2.empty());
  profile_manager->ScheduleProfileForDeletion(profile_path1);
  profile_manager->ScheduleProfileForDeletion(profile_path2);

  // Spin things so deletion can take place.
  ui_test_utils::RunAllPendingInMessageLoop();

  // Make sure a new profile was created automatically.
  EXPECT_EQ(cache.GetNumberOfProfiles(), 1U);
  FilePath new_profile_path = cache.GetPathOfProfileAtIndex(0);
  EXPECT_NE(new_profile_path, profile_path1);
  EXPECT_NE(new_profile_path, profile_path2);

  // Make sure that last used profile preference is set correctly.
  Profile* last_used = ProfileManager::GetLastUsedProfile();
  EXPECT_EQ(new_profile_path, last_used->GetPath());
}
#endif // OS_MACOSX
<|endoftext|>


<commit_before>#pragma once

#include <tudocomp_stat/StatPhase.hpp>

#include <tudocomp/util.hpp>
#include <tudocomp/Env.hpp>
#include <tudocomp/Compressor.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/compressors/esp/EspContextImpl.hpp>
#include <tudocomp/compressors/esp/RoundContextImpl.hpp>

#include <tudocomp/compressors/esp/PlainSLPStrategy.hpp>

#include <tudocomp/compressors/esp/StdUnorderedMapIPD.hpp>

namespace tdc {

template<typename slp_strategy_t, typename ipd_t = esp::StdUnorderedMapIPD>
class EspCompressor: public Compressor {
public:
    inline static Meta meta() {
        Meta m("compressor", "esp", "ESP based grammar compression");
        m.option("slp_strategy").templated<slp_strategy_t, esp::PlainSLPStrategy>("slp_strategy");
        m.option("ipd").templated<ipd_t, esp::StdUnorderedMapIPD>("ipd");
        return m;
    }

    using Compressor::Compressor;

    inline virtual void compress(Input& input, Output& output) override {
        using namespace esp;

        auto phase0 = StatPhase("ESP Compressor");

        EspContext<ipd_t> context { &env(), true };
        SLP slp;

        {
            auto phase1 = StatPhase("Compress Phase");

            auto phase2 = StatPhase("Creating input view");
                auto in = input.as_view();

            context.debug.input_string(in);

            phase2.split("ESP Algorithm");
                slp = context.generate_grammar(in);
        }

        {
            auto phase1 = StatPhase("Encode Phase");

            auto phase2 = StatPhase("Creating strategy");
                const slp_strategy_t strategy { this->env().env_for_option("slp_strategy") };

            phase2.split("Encode SLP");
                strategy.encode(context.debug, std::move(slp), output);
        }

        context.debug.print_all();
    }

    inline virtual void decompress(Input& input, Output& output) override {
        auto phase0 = StatPhase("ESP Decompressor");

        auto phase1 = StatPhase("Creating strategy");
            const slp_strategy_t strategy { this->env().env_for_option("slp_strategy") };
        phase1.split("Decode SLP");
            auto slp = strategy.decode(input);

        phase1.split("Create output stream");
            auto out = output.as_stream();

        phase1.split("Derive text");
            if (!slp.empty) {
                slp.derive_text(out);
            } else {
                out << ""_v;
            }
    }
};

}
<commit_msg>Fix endless recursion in registry with recursive paramters<commit_after>#pragma once

#include <tudocomp_stat/StatPhase.hpp>

#include <tudocomp/util.hpp>
#include <tudocomp/Env.hpp>
#include <tudocomp/Compressor.hpp>
#include <tudocomp/ds/IntVector.hpp>
#include <tudocomp/compressors/esp/EspContextImpl.hpp>
#include <tudocomp/compressors/esp/RoundContextImpl.hpp>

#include <tudocomp/compressors/esp/PlainSLPStrategy.hpp>

#include <tudocomp/compressors/esp/StdUnorderedMapIPD.hpp>

namespace tdc {

template<typename slp_strategy_t, typename ipd_t = esp::StdUnorderedMapIPD>
class EspCompressor: public Compressor {
public:
    inline static Meta meta() {
        Meta m("compressor", "esp", "ESP based grammar compression");
        m.option("slp_strategy").templated<slp_strategy_t, esp::PlainSLPStrategy>("slp_strategy");
        m.option("ipd").templated<ipd_t, esp::StdUnorderedMapIPD>("ipd");
        return m;
    }

    using Compressor::Compressor;

    inline virtual void compress(Input& input, Output& output) override {
        using namespace esp;

        auto phase0 = StatPhase("ESP Compressor");

        EspContext<ipd_t> context { &env(), true };
        SLP slp;

        {
            auto phase1 = StatPhase("Compress Phase");

            auto phase2 = StatPhase("Creating input view");
                auto in = input.as_view();

            context.debug.input_string(in);

            phase2.split("ESP Algorithm");
                slp = context.generate_grammar(in);
        }

        phase0.log_stat("SLP size", slp.rules.size());

        {
            auto phase1 = StatPhase("Encode Phase");

            auto phase2 = StatPhase("Creating strategy");
                const slp_strategy_t strategy { this->env().env_for_option("slp_strategy") };

            phase2.split("Encode SLP");
                strategy.encode(context.debug, std::move(slp), output);
        }

        context.debug.print_all();
    }

    inline virtual void decompress(Input& input, Output& output) override {
        auto phase0 = StatPhase("ESP Decompressor");

        auto phase1 = StatPhase("Creating strategy");
            const slp_strategy_t strategy { this->env().env_for_option("slp_strategy") };
        phase1.split("Decode SLP");
            auto slp = strategy.decode(input);

        phase1.split("Create output stream");
            auto out = output.as_stream();

        phase1.split("Derive text");
            if (!slp.empty) {
                slp.derive_text(out);
            } else {
                out << ""_v;
            }
    }
};

}
<|endoftext|>


<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>

namespace visionaray
{

//-------------------------------------------------------------------------------------------------
// Accessors
//

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::color_type* simple_buffer_rt<ColorFormat, DepthFormat>::color()
{
    return color_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::depth_type* simple_buffer_rt<ColorFormat, DepthFormat>::depth()
{
    return depth_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::color_type const* simple_buffer_rt<ColorFormat, DepthFormat>::color() const
{
    return color_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::depth_type const* simple_buffer_rt<ColorFormat, DepthFormat>::depth() const
{
    return depth_buffer.data();
}

//-------------------------------------------------------------------------------------------------
// Interface
//

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::ref_type simple_buffer_rt<ColorFormat, DepthFormat>::ref()
{
    return typename simple_buffer_rt<ColorFormat, DepthFormat>::ref_type(
            color(),
            depth(),
            width(),
            height()
            );
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::clear_color_buffer(vec4 const& c)
{
    // Convert from RGBA32F to internal color format
    color_type cc;
    convert(
        pixel_format_constant<ColorFormat>{},
        pixel_format_constant<PF_RGBA32F>{},
        cc,
        c
        );

    std::fill(color_buffer.begin(), color_buffer.end(), cc);
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::clear_depth_buffer(float d)
{
    // Convert from DEPTH32F to internal depth format
    depth_type dd;
    convert(
        pixel_format_constant<DepthFormat>{},
        pixel_format_constant<PF_DEPTH32F>{},
        dd,
        d
        );

    std::fill(depth_buffer.begin(), depth_buffer.end(), dd);
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::begin_frame()
{
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::end_frame()
{
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::resize(int w, int h)
{
    render_target::resize(w, h);

    color_buffer.resize(w * h);

    if (DepthFormat != PF_UNSPECIFIED)
    {
        depth_buffer.resize(w * h);
    }
}

} // visionaray
<commit_msg>Compile fix<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.

#include <algorithm>

namespace visionaray
{

//-------------------------------------------------------------------------------------------------
// Accessors
//

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::color_type* simple_buffer_rt<ColorFormat, DepthFormat>::color()
{
    return color_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::depth_type* simple_buffer_rt<ColorFormat, DepthFormat>::depth()
{
    return depth_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::color_type const* simple_buffer_rt<ColorFormat, DepthFormat>::color() const
{
    return color_buffer.data();
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::depth_type const* simple_buffer_rt<ColorFormat, DepthFormat>::depth() const
{
    return depth_buffer.data();
}

//-------------------------------------------------------------------------------------------------
// Interface
//

template <pixel_format ColorFormat, pixel_format DepthFormat>
typename simple_buffer_rt<ColorFormat, DepthFormat>::ref_type simple_buffer_rt<ColorFormat, DepthFormat>::ref()
{
    return { color(), depth(), width(), height() };
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::clear_color_buffer(vec4 const& c)
{
    // Convert from RGBA32F to internal color format
    color_type cc;
    convert(
        pixel_format_constant<ColorFormat>{},
        pixel_format_constant<PF_RGBA32F>{},
        cc,
        c
        );

    std::fill(color_buffer.begin(), color_buffer.end(), cc);
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::clear_depth_buffer(float d)
{
    // Convert from DEPTH32F to internal depth format
    depth_type dd;
    convert(
        pixel_format_constant<DepthFormat>{},
        pixel_format_constant<PF_DEPTH32F>{},
        dd,
        d
        );

    std::fill(depth_buffer.begin(), depth_buffer.end(), dd);
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::begin_frame()
{
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::end_frame()
{
}

template <pixel_format ColorFormat, pixel_format DepthFormat>
void simple_buffer_rt<ColorFormat, DepthFormat>::resize(int w, int h)
{
    render_target::resize(w, h);

    color_buffer.resize(w * h);

    if (DepthFormat != PF_UNSPECIFIED)
    {
        depth_buffer.resize(w * h);
    }
}

} // visionaray
<|endoftext|>