<commit_before>#include "SoundSystem_oal.h"
#include "Channel_oal.h"
#include "DebugActor.h"
#include "utils/stringUtils.h"
#include "pthread.h"
#include "../oal.h"
#include "../null/SoundSystemNull.h"

//#ifdef EMSCRIPTEN
//#include "../emscripten/SoundSystemEmscripten.h
//#endif

namespace oxygine
{
    void check();

    SoundSystem* SoundSystem::create()
    {
        if (!SoundSystem::instance)
            SoundSystem::instance = new SoundSystemOAL;

        return SoundSystem::instance;
    }

    SoundSystemOAL::SoundSystemOAL(): _device(0), _context(0), _volume(1.0)
    {
#ifdef __S3E__
//      alcInit();
#endif
    }

    SoundSystemOAL::~SoundSystemOAL()
    {
    }

    void SoundSystemOAL::setContext()
    {
        alcMakeContextCurrent(_context);
        check();
    }

    void SoundSystemOAL::pause()
    {
        log::messageln("SoundSystemOAL::pause");
        /*
        for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)
        {
            ChannelOAL& channel = *i;
            channel.pause();
        }
        */

#if defined(__ANDROID__)
        //android needs special workaround
        alcSuspend();
#endif

#if defined(__S3E__)
        alcSuspendContext(_context);
        alcMakeContextCurrent(0);
#endif
    }

    void SoundSystemOAL::resume()
    {
        log::messageln("SoundSystemOAL::resume");

#if defined(__ANDROID__)
        alcResume();
#endif

#if defined(__S3E__)
        alcMakeContextCurrent(_context);
        alcProcessContext(_context);
#endif

        /*
        for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)
        {
            ChannelOAL& channel = *i;
            channel.resume();
        }
        */
    }

    void SoundSystemOAL::stop()
    {
        _channels.stop();
    }

    void SoundSystemOAL::setVolume(float v)
    {
        _volume = v;
        _channels.setVolume(v);
        check();
    }

    void SoundSystemOAL::init(int channels_num)
    {
        log::messageln("SoundSystemOAL init");
#ifdef __ANDROID__
        _device = alcOpenDevice("opensles");
#else
        _device = alcOpenDevice(0);
#endif
        if (!_device)
        {
            log::messageln("can't create alc device");
            return;
        }

        _context = alcCreateContext(_device, 0);

        if (!_context)
        {
            log::messageln("can't create alc context");
            return;
        }

        alcMakeContextCurrent(_context);

        /*
        ALCint nummono, numstereo;
        alcGetIntegerv(_device, ALC_MONO_SOURCES, 1, &nummono);
        alcGetIntegerv(_device, ALC_STEREO_SOURCES, 1, &numstereo);
        */

        _channels._channels.resize(channels_num);

        for (int i = 0; i < channels_num; ++i)
        {
            ALuint source = 0;
            alGenSources(1, &source);
            check();

            _channels._channels[i].init(this, i, source);
        }

        ChannelOAL::runThread();
        check();
    }

    void SoundSystemOAL::release()
    {
        stop();

        ChannelOAL::stopThread();
        _channels._channels.clear();
        alcMakeContextCurrent(0);
        alcDestroyContext(_context);
        _context = 0;

        alcCloseDevice(_device);
        _device = 0;
    }

    SoundOAL* SoundSystemOAL::createSound(std::vector<unsigned char>& buffer, bool swap)
    {
        if (!_context)
            return 0;

        SoundOAL* sound = 0;
        sound = new SoundOAL();
        sound->init(buffer, swap);
        check();

        return sound;
    }

    SoundOAL* SoundSystemOAL::createSound(const char* path)
    {
        if (!_context)
            return 0;

        SoundOAL* sound = 0;
        sound = new SoundOAL();
        bool res = sound->init(path);
        if (!res)
        {
            delete sound;
            return 0;
        }
        check();

        return sound;
    }

    void SoundSystemOAL::update()
    {
        if (!_device)
            return;

        _channels.update();
        check();

        if (DebugActor::instance)
        {
            char str[255];
            safe_sprintf(str, "channels: %d\n", _channels._channels.size() - getFreeChannelsNum());
            DebugActor::instance->addDebugString(str);
        }
    }

    int SoundSystemOAL::getFreeChannelsNum()
    {
        return _channels.getFreeNum();
    }

    ChannelOAL* SoundSystemOAL::getFreeChannel()
    {
        ChannelOAL* channel = _channels.getFree();
        check();
        return channel;
    }
}
<commit_msg>minor<commit_after>#include "SoundSystem_oal.h"
#include "Channel_oal.h"
#include "DebugActor.h"
#include "utils/stringUtils.h"
#include "pthread.h"
#include "../oal.h"
#include "../null/SoundSystemNull.h"

//#ifdef EMSCRIPTEN
//#include "../emscripten/SoundSystemEmscripten.h
//#endif

namespace oxygine
{
    void check();

    SoundSystem* SoundSystem::create()
    {
        if (!SoundSystem::instance)
            SoundSystem::instance = new SoundSystemOAL;

        return SoundSystem::instance;
    }

    SoundSystemOAL::SoundSystemOAL(): _device(0), _context(0), _volume(1.0)
    {
#ifdef __S3E__
//      alcInit();
#endif
    }

    SoundSystemOAL::~SoundSystemOAL()
    {
    }

    void SoundSystemOAL::setContext()
    {
        alcMakeContextCurrent(_context);
        check();
    }

    void SoundSystemOAL::pause()
    {
        log::messageln("SoundSystemOAL::pause");
        /*
        for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)
        {
            ChannelOAL& channel = *i;
            channel.pause();
        }
        */

#if defined(__ANDROID__)
        //android needs special workaround
        alcSuspend();
#endif

#if defined(__S3E__)
        alcSuspendContext(_context);
        alcMakeContextCurrent(0);
#endif
    }

    void SoundSystemOAL::resume()
    {
        log::messageln("SoundSystemOAL::resume");

#if defined(__ANDROID__)
        alcResume();
#endif

#if defined(__S3E__)
        alcMakeContextCurrent(_context);
        alcProcessContext(_context);
#endif

        /*
        for (channels::iterator i = _channels.begin(); i != _channels.end(); ++i)
        {
            ChannelOAL& channel = *i;
            channel.resume();
        }
        */
    }

    void SoundSystemOAL::stop()
    {
        _channels.stop();
    }

    void SoundSystemOAL::setVolume(float v)
    {
        _volume = v;
        _channels.setVolume(v);
        check();
    }

    void SoundSystemOAL::init(int channels_num)
    {
        log::messageln("SoundSystemOAL init");
#ifdef __ANDROID__
        _device = alcOpenDevice("opensles");
#else
        _device = alcOpenDevice(0);
#endif
        if (!_device)
        {
            log::messageln("can't create alc device");
            return;
        }

        _context = alcCreateContext(_device, 0);

        if (!_context)
        {
            log::messageln("can't create alc context");
            return;
        }

        alcMakeContextCurrent(_context);

        /*
        ALCint nummono, numstereo;
        alcGetIntegerv(_device, ALC_MONO_SOURCES, 1, &nummono);
        alcGetIntegerv(_device, ALC_STEREO_SOURCES, 1, &numstereo);
        */

        _channels._channels.resize(channels_num);

        for (int i = 0; i < channels_num; ++i)
        {
            ALuint source = 0;
            alGenSources(1, &source);
            check();

            _channels._channels[i].init(this, i, source);
        }

        ChannelOAL::runThread();
        check();
    }

    void SoundSystemOAL::release()
    {
        stop();

        ChannelOAL::stopThread();
        _channels._channels.clear();
        alcMakeContextCurrent(0);
        alcDestroyContext(_context);
        _context = 0;

        alcCloseDevice(_device);
        _device = 0;
    }

    SoundOAL* SoundSystemOAL::createSound(std::vector<unsigned char>& buffer, bool swap)
    {
        if (!_context)
            return 0;

        SoundOAL* sound = 0;
        sound = new SoundOAL();
        sound->init(buffer, swap);
        check();

        return sound;
    }

    SoundOAL* SoundSystemOAL::createSound(const char* path)
    {
        if (!_context)
            return 0;

        SoundOAL* sound = 0;
        sound = new SoundOAL();
        bool res = sound->init(path);
        if (!res)
        {
            delete sound;
            return 0;
        }
        check();

        return sound;
    }

    void SoundSystemOAL::update()
    {
        if (!_device)
            return;

        _channels.update();
        check();

        if (DebugActor::instance)
        {
            char str[255];
            safe_sprintf(str, "channels: %d", _channels._channels.size() - getFreeChannelsNum());
            DebugActor::instance->addDebugString(str);
        }
    }

    int SoundSystemOAL::getFreeChannelsNum()
    {
        return _channels.getFreeNum();
    }

    ChannelOAL* SoundSystemOAL::getFreeChannel()
    {
        ChannelOAL* channel = _channels.getFree();
        check();
        return channel;
    }
}
<|endoftext|>


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

#include "chrome/browser/chromeos/extensions/echo_private_api.h"

#include <string>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/ui/echo_dialog_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/extensions/api/echo_private.h"
#include "chrome/common/pref_names.h"
#include "chromeos/system/statistics_provider.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/common/extension.h"

namespace echo_api = extensions::api::echo_private;

using content::BrowserThread;

namespace {

// URL of "More info" link shown in echo dialog in GetUserConsent function.
const char kMoreInfoLink[] =
    "chrome-extension://honijodknafkokifofgiaalefdiedpko/main.html?"
    "answer=2677280";

}  // namespace

namespace chromeos {

namespace echo_offer {

void RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(prefs::kEchoCheckedOffers);
}

} // namespace echo_offer

} // namespace chromeos

EchoPrivateGetRegistrationCodeFunction::
    EchoPrivateGetRegistrationCodeFunction() {}

EchoPrivateGetRegistrationCodeFunction::
    ~EchoPrivateGetRegistrationCodeFunction() {}

void EchoPrivateGetRegistrationCodeFunction::GetRegistrationCode(
    const std::string& type) {
  // Possible ECHO code type and corresponding key name in StatisticsProvider.
  const std::string kCouponType = "COUPON_CODE";
  const std::string kGroupType = "GROUP_CODE";

  chromeos::system::StatisticsProvider* provider =
      chromeos::system::StatisticsProvider::GetInstance();
  std::string result;
  if (type == kCouponType) {
    provider->GetMachineStatistic(chromeos::system::kOffersCouponCodeKey,
                                  &result);
  } else if (type == kGroupType) {
    provider->GetMachineStatistic(chromeos::system::kOffersGroupCodeKey,
                                  &result);
  }

  results_ = echo_api::GetRegistrationCode::Results::Create(result);
  SendResponse(true);
}

bool EchoPrivateGetRegistrationCodeFunction::RunSync() {
  scoped_ptr<echo_api::GetRegistrationCode::Params> params =
      echo_api::GetRegistrationCode::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  GetRegistrationCode(params->type);
  return true;
}

EchoPrivateSetOfferInfoFunction::EchoPrivateSetOfferInfoFunction() {}

EchoPrivateSetOfferInfoFunction::~EchoPrivateSetOfferInfoFunction() {}

bool EchoPrivateSetOfferInfoFunction::RunSync() {
  scoped_ptr<echo_api::SetOfferInfo::Params> params =
      echo_api::SetOfferInfo::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  const std::string& service_id = params->id;
  base::DictionaryValue* dict = params->offer_info.
      additional_properties.DeepCopyWithoutEmptyChildren();

  PrefService* local_state = g_browser_process->local_state();
  DictionaryPrefUpdate offer_update(local_state, prefs::kEchoCheckedOffers);
  offer_update->SetWithoutPathExpansion("echo." + service_id, dict);
  return true;
}

EchoPrivateGetOfferInfoFunction::EchoPrivateGetOfferInfoFunction() {}

EchoPrivateGetOfferInfoFunction::~EchoPrivateGetOfferInfoFunction() {}

bool EchoPrivateGetOfferInfoFunction::RunSync() {
  scoped_ptr<echo_api::GetOfferInfo::Params> params =
      echo_api::GetOfferInfo::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  const std::string& service_id = params->id;
  PrefService* local_state = g_browser_process->local_state();
  const base::DictionaryValue* offer_infos = local_state->
      GetDictionary(prefs::kEchoCheckedOffers);

  const base::DictionaryValue* offer_info = NULL;
  if (!offer_infos->GetDictionaryWithoutPathExpansion(
         "echo." + service_id, &offer_info)) {
    error_ = "Not found";
    return false;
  }

  echo_api::GetOfferInfo::Results::Result result;
  result.additional_properties.MergeDictionary(offer_info);
  results_ = echo_api::GetOfferInfo::Results::Create(result);
  return true;
}

EchoPrivateGetOobeTimestampFunction::EchoPrivateGetOobeTimestampFunction() {
}

EchoPrivateGetOobeTimestampFunction::~EchoPrivateGetOobeTimestampFunction() {
}

bool EchoPrivateGetOobeTimestampFunction::RunAsync() {
  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(
          &EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread,
          this),
      base::Bind(
          &EchoPrivateGetOobeTimestampFunction::SendResponse, this));
  return true;
}

// Get the OOBE timestamp from file /home/chronos/.oobe_completed.
// The timestamp is used to determine when the user first activates the device.
// If we can get the timestamp info, return it as yyyy-mm-dd, otherwise, return
// an empty string.
bool EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread() {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  const char kOobeTimestampFile[] = "/home/chronos/.oobe_completed";
  std::string timestamp = "";
  base::File::Info fileInfo;
  if (base::GetFileInfo(base::FilePath(kOobeTimestampFile), &fileInfo)) {
    base::Time::Exploded ctime;
    fileInfo.creation_time.UTCExplode(&ctime);
    timestamp += base::StringPrintf("%u-%u-%u",
                                    ctime.year,
                                    ctime.month,
                                    ctime.day_of_month);
  }
  results_ = echo_api::GetOobeTimestamp::Results::Create(timestamp);
  return true;
}

EchoPrivateGetUserConsentFunction::EchoPrivateGetUserConsentFunction()
    : redeem_offers_allowed_(false) {
}

// static
scoped_refptr<EchoPrivateGetUserConsentFunction>
EchoPrivateGetUserConsentFunction::CreateForTest(
      const DialogShownTestCallback& dialog_shown_callback) {
  scoped_refptr<EchoPrivateGetUserConsentFunction> function(
      new EchoPrivateGetUserConsentFunction());
  function->dialog_shown_callback_ = dialog_shown_callback;
  return function;
}

EchoPrivateGetUserConsentFunction::~EchoPrivateGetUserConsentFunction() {}

bool EchoPrivateGetUserConsentFunction::RunAsync() {
   CheckRedeemOffersAllowed();
   return true;
}

void EchoPrivateGetUserConsentFunction::OnAccept() {
  Finalize(true);
}

void EchoPrivateGetUserConsentFunction::OnCancel() {
  Finalize(false);
}

void EchoPrivateGetUserConsentFunction::OnMoreInfoLinkClicked() {
  chrome::NavigateParams params(
      GetProfile(), GURL(kMoreInfoLink), ui::PAGE_TRANSITION_LINK);
  // Open the link in a new window. The echo dialog is modal, so the current
  // window is useless until the dialog is closed.
  params.disposition = NEW_WINDOW;
  chrome::Navigate(&params);
}

void EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed() {
  chromeos::CrosSettingsProvider::TrustedStatus status =
      chromeos::CrosSettings::Get()->PrepareTrustedValues(base::Bind(
          &EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed,
          this));
  if (status == chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED)
    return;

  bool allow = true;
  chromeos::CrosSettings::Get()->GetBoolean(
      chromeos::kAllowRedeemChromeOsRegistrationOffers, &allow);

  OnRedeemOffersAllowedChecked(allow);
}

void EchoPrivateGetUserConsentFunction::OnRedeemOffersAllowedChecked(
    bool is_allowed) {
  redeem_offers_allowed_ = is_allowed;

  scoped_ptr<echo_api::GetUserConsent::Params> params =
      echo_api::GetUserConsent::Params::Create(*args_);

  // Verify that the passed origin URL is valid.
  GURL service_origin = GURL(params->consent_requester.origin);
  if (!service_origin.is_valid()) {
    error_ = "Invalid origin.";
    SendResponse(false);
    return;
  }

  // Add ref to ensure the function stays around until the dialog listener is
  // called. The reference is release in |Finalize|.
  AddRef();

  // Create and show the dialog.
  chromeos::EchoDialogView* dialog = new chromeos::EchoDialogView(this);
  if (redeem_offers_allowed_) {
    dialog->InitForEnabledEcho(
        base::UTF8ToUTF16(params->consent_requester.service_name),
        base::UTF8ToUTF16(params->consent_requester.origin));
  } else {
    dialog->InitForDisabledEcho();
  }
  dialog->Show(GetCurrentBrowser()->window()->GetNativeWindow());

  // If there is a dialog_shown_callback_, invoke it with the created dialog.
  if (!dialog_shown_callback_.is_null())
    dialog_shown_callback_.Run(dialog);
}

void EchoPrivateGetUserConsentFunction::Finalize(bool consent) {
  // Consent should not be true if offers redeeming is disabled.
  CHECK(redeem_offers_allowed_ || !consent);
  results_ = echo_api::GetUserConsent::Results::Create(consent);
  SendResponse(true);

  // Release the reference added in |OnRedeemOffersAllowedChecked|, before
  // showing the dialog.
  Release();
}
<commit_msg>Fix crash in echoPrivate.getUserConsent when there are no browser windows<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/chromeos/extensions/echo_private_api.h"

#include <string>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/location.h"
#include "base/prefs/pref_registry_simple.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/ui/echo_dialog_view.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/api/echo_private.h"
#include "chrome/common/pref_names.h"
#include "chromeos/system/statistics_provider.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/web_contents.h"
#include "extensions/common/extension.h"

namespace echo_api = extensions::api::echo_private;

using content::BrowserThread;

namespace {

// URL of "More info" link shown in echo dialog in GetUserConsent function.
const char kMoreInfoLink[] =
    "chrome-extension://honijodknafkokifofgiaalefdiedpko/main.html?"
    "answer=2677280";

}  // namespace

namespace chromeos {

namespace echo_offer {

void RegisterPrefs(PrefRegistrySimple* registry) {
  registry->RegisterDictionaryPref(prefs::kEchoCheckedOffers);
}

} // namespace echo_offer

} // namespace chromeos

EchoPrivateGetRegistrationCodeFunction::
    EchoPrivateGetRegistrationCodeFunction() {}

EchoPrivateGetRegistrationCodeFunction::
    ~EchoPrivateGetRegistrationCodeFunction() {}

void EchoPrivateGetRegistrationCodeFunction::GetRegistrationCode(
    const std::string& type) {
  // Possible ECHO code type and corresponding key name in StatisticsProvider.
  const std::string kCouponType = "COUPON_CODE";
  const std::string kGroupType = "GROUP_CODE";

  chromeos::system::StatisticsProvider* provider =
      chromeos::system::StatisticsProvider::GetInstance();
  std::string result;
  if (type == kCouponType) {
    provider->GetMachineStatistic(chromeos::system::kOffersCouponCodeKey,
                                  &result);
  } else if (type == kGroupType) {
    provider->GetMachineStatistic(chromeos::system::kOffersGroupCodeKey,
                                  &result);
  }

  results_ = echo_api::GetRegistrationCode::Results::Create(result);
  SendResponse(true);
}

bool EchoPrivateGetRegistrationCodeFunction::RunSync() {
  scoped_ptr<echo_api::GetRegistrationCode::Params> params =
      echo_api::GetRegistrationCode::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);
  GetRegistrationCode(params->type);
  return true;
}

EchoPrivateSetOfferInfoFunction::EchoPrivateSetOfferInfoFunction() {}

EchoPrivateSetOfferInfoFunction::~EchoPrivateSetOfferInfoFunction() {}

bool EchoPrivateSetOfferInfoFunction::RunSync() {
  scoped_ptr<echo_api::SetOfferInfo::Params> params =
      echo_api::SetOfferInfo::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  const std::string& service_id = params->id;
  base::DictionaryValue* dict = params->offer_info.
      additional_properties.DeepCopyWithoutEmptyChildren();

  PrefService* local_state = g_browser_process->local_state();
  DictionaryPrefUpdate offer_update(local_state, prefs::kEchoCheckedOffers);
  offer_update->SetWithoutPathExpansion("echo." + service_id, dict);
  return true;
}

EchoPrivateGetOfferInfoFunction::EchoPrivateGetOfferInfoFunction() {}

EchoPrivateGetOfferInfoFunction::~EchoPrivateGetOfferInfoFunction() {}

bool EchoPrivateGetOfferInfoFunction::RunSync() {
  scoped_ptr<echo_api::GetOfferInfo::Params> params =
      echo_api::GetOfferInfo::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params);

  const std::string& service_id = params->id;
  PrefService* local_state = g_browser_process->local_state();
  const base::DictionaryValue* offer_infos = local_state->
      GetDictionary(prefs::kEchoCheckedOffers);

  const base::DictionaryValue* offer_info = NULL;
  if (!offer_infos->GetDictionaryWithoutPathExpansion(
         "echo." + service_id, &offer_info)) {
    error_ = "Not found";
    return false;
  }

  echo_api::GetOfferInfo::Results::Result result;
  result.additional_properties.MergeDictionary(offer_info);
  results_ = echo_api::GetOfferInfo::Results::Create(result);
  return true;
}

EchoPrivateGetOobeTimestampFunction::EchoPrivateGetOobeTimestampFunction() {
}

EchoPrivateGetOobeTimestampFunction::~EchoPrivateGetOobeTimestampFunction() {
}

bool EchoPrivateGetOobeTimestampFunction::RunAsync() {
  BrowserThread::PostTaskAndReplyWithResult(
      BrowserThread::FILE, FROM_HERE,
      base::Bind(
          &EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread,
          this),
      base::Bind(
          &EchoPrivateGetOobeTimestampFunction::SendResponse, this));
  return true;
}

// Get the OOBE timestamp from file /home/chronos/.oobe_completed.
// The timestamp is used to determine when the user first activates the device.
// If we can get the timestamp info, return it as yyyy-mm-dd, otherwise, return
// an empty string.
bool EchoPrivateGetOobeTimestampFunction::GetOobeTimestampOnFileThread() {
  DCHECK_CURRENTLY_ON(BrowserThread::FILE);

  const char kOobeTimestampFile[] = "/home/chronos/.oobe_completed";
  std::string timestamp = "";
  base::File::Info fileInfo;
  if (base::GetFileInfo(base::FilePath(kOobeTimestampFile), &fileInfo)) {
    base::Time::Exploded ctime;
    fileInfo.creation_time.UTCExplode(&ctime);
    timestamp += base::StringPrintf("%u-%u-%u",
                                    ctime.year,
                                    ctime.month,
                                    ctime.day_of_month);
  }
  results_ = echo_api::GetOobeTimestamp::Results::Create(timestamp);
  return true;
}

EchoPrivateGetUserConsentFunction::EchoPrivateGetUserConsentFunction()
    : redeem_offers_allowed_(false) {
}

// static
scoped_refptr<EchoPrivateGetUserConsentFunction>
EchoPrivateGetUserConsentFunction::CreateForTest(
      const DialogShownTestCallback& dialog_shown_callback) {
  scoped_refptr<EchoPrivateGetUserConsentFunction> function(
      new EchoPrivateGetUserConsentFunction());
  function->dialog_shown_callback_ = dialog_shown_callback;
  return function;
}

EchoPrivateGetUserConsentFunction::~EchoPrivateGetUserConsentFunction() {}

bool EchoPrivateGetUserConsentFunction::RunAsync() {
   CheckRedeemOffersAllowed();
   return true;
}

void EchoPrivateGetUserConsentFunction::OnAccept() {
  Finalize(true);
}

void EchoPrivateGetUserConsentFunction::OnCancel() {
  Finalize(false);
}

void EchoPrivateGetUserConsentFunction::OnMoreInfoLinkClicked() {
  chrome::NavigateParams params(
      GetProfile(), GURL(kMoreInfoLink), ui::PAGE_TRANSITION_LINK);
  // Open the link in a new window. The echo dialog is modal, so the current
  // window is useless until the dialog is closed.
  params.disposition = NEW_WINDOW;
  chrome::Navigate(&params);
}

void EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed() {
  chromeos::CrosSettingsProvider::TrustedStatus status =
      chromeos::CrosSettings::Get()->PrepareTrustedValues(base::Bind(
          &EchoPrivateGetUserConsentFunction::CheckRedeemOffersAllowed,
          this));
  if (status == chromeos::CrosSettingsProvider::TEMPORARILY_UNTRUSTED)
    return;

  bool allow = true;
  chromeos::CrosSettings::Get()->GetBoolean(
      chromeos::kAllowRedeemChromeOsRegistrationOffers, &allow);

  OnRedeemOffersAllowedChecked(allow);
}

void EchoPrivateGetUserConsentFunction::OnRedeemOffersAllowedChecked(
    bool is_allowed) {
  redeem_offers_allowed_ = is_allowed;

  scoped_ptr<echo_api::GetUserConsent::Params> params =
      echo_api::GetUserConsent::Params::Create(*args_);

  // Verify that the passed origin URL is valid.
  GURL service_origin = GURL(params->consent_requester.origin);
  if (!service_origin.is_valid()) {
    error_ = "Invalid origin.";
    SendResponse(false);
    return;
  }

  content::WebContents* web_contents = GetAssociatedWebContents();
  if (!web_contents) {
    error_ = "No web contents.";
    SendResponse(false);
    return;
  }

  // Add ref to ensure the function stays around until the dialog listener is
  // called. The reference is release in |Finalize|.
  AddRef();

  // Create and show the dialog.
  chromeos::EchoDialogView* dialog = new chromeos::EchoDialogView(this);
  if (redeem_offers_allowed_) {
    dialog->InitForEnabledEcho(
        base::UTF8ToUTF16(params->consent_requester.service_name),
        base::UTF8ToUTF16(params->consent_requester.origin));
  } else {
    dialog->InitForDisabledEcho();
  }
  dialog->Show(web_contents->GetTopLevelNativeWindow());

  // If there is a dialog_shown_callback_, invoke it with the created dialog.
  if (!dialog_shown_callback_.is_null())
    dialog_shown_callback_.Run(dialog);
}

void EchoPrivateGetUserConsentFunction::Finalize(bool consent) {
  // Consent should not be true if offers redeeming is disabled.
  CHECK(redeem_offers_allowed_ || !consent);
  results_ = echo_api::GetUserConsent::Results::Create(consent);
  SendResponse(true);

  // Release the reference added in |OnRedeemOffersAllowedChecked|, before
  // showing the dialog.
  Release();
}
<|endoftext|>


<commit_before>
#include <qregexp.h>
#include <qstylesheet.h>

#include <kdebug.h>
#include "oscarmessage.h"
#include "rtf2html.h"

OscarMessage::OscarMessage()
{
	timestamp = QDateTime::currentDateTime();
}

void OscarMessage::setText(const QString &txt, MessageFormat format)
{
	if(format == AimHtml)
	{
		kdDebug(14150) << k_funcinfo <<
			"AIM message text: " << txt << endl;

		mText = txt;
		mText.replace(
			QRegExp("(.*)", false),
			"\\1");

		mText.replace(
			QRegExp("(.*)", false),
			"\\1");

		mText.replace(
			QRegExp("(.*)", false),
			"\\4");
	}
	else if (format == Plain)
	{
		mText = QStyleSheet::escape(txt);
		mText.replace("\n",
			"
");
		mText.replace("\t",
			"     ");
		mText.replace(QRegExp("\\s\\s"),
			"  ");
	}
	else
	{
		RTF2HTML parser;
		/*kdDebug(14150) << k_funcinfo <<
			"Original message text: " << txt << endl;*/
		//TODO: encoding
		mText = parser.Parse(txt.latin1(), "");
		/*kdDebug(14150) << k_funcinfo <<
			"Message text after RTF2HTML: " << mText << endl;*/
	}
}

const QString &OscarMessage::text()
{
	return mText;
}

const OscarMessage::MessageType OscarMessage::type()
{
	return mType;
}

void OscarMessage::setType(const MessageType val)
{
	mType = val;
}
<commit_msg>Make Nicholas Pilon happy although it does not affect the outcome of the regexp, there is no html tag more complex than that in aim html<commit_after>
#include <qregexp.h>
#include <qstylesheet.h>

#include <kdebug.h>
#include "oscarmessage.h"
#include "rtf2html.h"

OscarMessage::OscarMessage()
{
	timestamp = QDateTime::currentDateTime();
}

void OscarMessage::setText(const QString &txt, MessageFormat format)
{
	if(format == AimHtml)
	{
		kdDebug(14150) << k_funcinfo <<
			"AIM message text: " << txt << endl;

		mText = txt;
		mText.replace(
			QRegExp("(.*)", false),
			"\\1");

		mText.replace(
			QRegExp("(.*)", false),
			"\\1");

		QRegExp re("(.*)", false);
		re.setMinimal(true);
		mText.replace(re,
			"\\4");
	}
	else if (format == Plain)
	{
		mText = QStyleSheet::escape(txt);
		mText.replace("\n",
			"
");
		mText.replace("\t",
			"     ");
		mText.replace(QRegExp("\\s\\s"),
			"  ");
	}
	else
	{
		RTF2HTML parser;
		/*kdDebug(14150) << k_funcinfo <<
			"Original message text: " << txt << endl;*/
		//TODO: encoding
		mText = parser.Parse(txt.latin1(), "");
		/*kdDebug(14150) << k_funcinfo <<
			"Message text after RTF2HTML: " << mText << endl;*/
	}
}

const QString &OscarMessage::text()
{
	return mText;
}

const OscarMessage::MessageType OscarMessage::type()
{
	return mType;
}

void OscarMessage::setType(const MessageType val)
{
	mType = val;
}
<|endoftext|>


<commit_before>#include <pamix_ui.hpp>

#include <pamix.hpp>

void pamix_ui::reset() {
	m_Entries = nullptr;
	m_VolumeBarLineNums.clear();
	m_EntrySizes.clear();
	m_NumDrawnEntries = 0;
	m_NumSkippedEntries = 0;
	m_SelectedEntry = m_SelectedChannel = 0;
}

void pamix_ui::drawVolumeBar(int y, int x, int width, double fill, double maxFill) const {

	int segments = width - 2;

	if (segments <= 0)
		return;

	if (fill < 0)
		fill = 0;
	else if (fill > maxFill)
		fill = maxFill;

	auto filled = (unsigned) (fill / maxFill * (double) segments);
	if (filled > segments)
		filled = (unsigned) segments;

	mvaddstr(y, x++, "[");
	mvaddstr(y, x + segments, "]");

	auto indexColorA = (int) (segments * ((double) 1 / 3));
	auto indexColorB = (int) (segments * ((double) 2 / 3));

	FEAT_UNICODE_STRING meter;

	meter.append(filled, SYM_VOLBAR);
	meter.append((unsigned) segments - filled, SYM_SPACE);
	attron(COLOR_PAIR(1));
	FEAT_UNICODE_MVADDNSTR(y, x, meter.c_str(), indexColorA);
	attroff(COLOR_PAIR(1));
	attron(COLOR_PAIR(2));
	FEAT_UNICODE_MVADDNSTR(y, x + indexColorA, meter.c_str() + indexColorA, indexColorB - indexColorA);
	attroff(COLOR_PAIR(2));
	attron(COLOR_PAIR(3));
	FEAT_UNICODE_MVADDNSTR(y, x + indexColorB, meter.c_str() + indexColorB, segments - indexColorB);
	attroff(COLOR_PAIR(3));
}

void string_maxlen_abs(std::string &str, unsigned max) {
	if (str.length() > max) {
		str = str.substr(0, max - 2);
		str.append("..");
	}
}

void string_maxlen_pct(std::string &str, double maxPct) {
	string_maxlen_abs(str, (unsigned) (COLS * maxPct));
}

void pamix_ui::redrawAll() {
	std::lock_guard<std::mutex> lockGuard(m_DrawMutex);

	if (!m_paInterface->isConnected()) {
		clear();
		mvprintw(1, 1, "No connection to pulseaudio yet");
		refresh();
		return;
	}

	clear();
	drawHeader();

	unsigned lineNumber = 2;
	unsigned entryIndex = 0;

	auto entryIter = m_Entries->begin();
	for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++)
		m_EntrySizes[entryIndex] = entryIter->second->m_Lock ? (char) 1 : entryIter->second->m_PAVolume.channels;

	entryIndex = m_NumSkippedEntries;
	entryIter = std::next(m_Entries->begin(), entryIndex);

	for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++) {
		Entry *entry = entryIter->second.get();

		std::string applicationName = entryIter->second ? entry->m_Name : "";
		pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
		char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
		bool isSelectedEntry = entryIndex == m_SelectedEntry;

		if (lineNumber + numChannels + 2 > (unsigned) LINES)
			break;

		lineNumber = drawEntryControlMeters(entry, entryIndex, lineNumber);

		double volumePeak = entry->m_Peak;
		m_VolumeBarLineNums[entryIter->first] = lineNumber;
		if (entry->m_Meter)
			drawVolumeBar(lineNumber++, 1, COLS - 2, volumePeak, 1.0);

		string_maxlen_pct(applicationName, 0.4);
		if (isSelectedEntry)
			attron(A_STANDOUT);
		mvprintw(lineNumber++, 1, applicationName.c_str());
		attroff(A_STANDOUT);

		bool isMuted = entry->m_Mute || averageVolume == PA_VOLUME_MUTED;
		printw(" %s %s", isMuted ? SYM_MUTE : "", entry->m_Lock ? SYM_LOCK : "");

		int curX = 0, curY = 0;
		getyx(stdscr, curY, curX);
		unsigned remainingChars = (unsigned) COLS - curX - 3;

		std::string displayName = getEntryDisplayName(entry);
		if (remainingChars < displayName.length()) {
			string_maxlen_abs(displayName, remainingChars);
			remainingChars = 0;
		} else {
			remainingChars -= displayName.length();
		}

		mvprintw(curY, curX + remainingChars + 1, displayName.c_str());
		lineNumber++;
	}

	m_NumDrawnEntries = entryIndex - m_NumSkippedEntries;
	refresh();
}

unsigned int pamix_ui::drawEntryControlMeters(const Entry *entry, unsigned entryIndex, unsigned int lineNumber) const {
	pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
	double dB = pa_sw_volume_to_dB(averageVolume);
	double vol = averageVolume / (double) PA_VOLUME_NORM;
	char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
	bool isSelectedEntry = entryIndex == m_SelectedEntry;
	if (entry->m_Meter) {
		if (entry->m_Lock) {
			drawVolumeBar(lineNumber, 32, COLS - 33, vol, MAX_VOL);

			std::string descriptionTemplate = "%.2fdB (%.2f)";
			if (isSelectedEntry)
				descriptionTemplate.insert(0, SYM_ARROW);
			mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), dB, vol);
		} else {
			for (char channel = 0; channel < numChannels; channel++) {
				std::string descriptionTemplate = "%.*s %.2fdB (%.2f)";

				uint32_t volume = entry->m_PAVolume.values[channel];
				bool isSelectedChannel = isSelectedEntry && channel == m_SelectedChannel;
				double channel_dB = pa_sw_volume_to_dB(volume);
				double channel_pct = volume / (double) PA_VOLUME_NORM;
				pa_channel_position_t channelPosition = entry->m_PAChannelMap.map[channel];
				std::string channelPrettyName = pa_channel_position_to_pretty_string(channelPosition);

				drawVolumeBar(lineNumber, 32, COLS - 33, channel_pct, MAX_VOL);
				if (isSelectedChannel)
					descriptionTemplate.insert(0, SYM_ARROW);

				unsigned indent = isSelectedChannel ? 13 : 15;
				mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), indent, channelPrettyName.c_str(), channel_dB,
				         channel_pct);
			}
		}
	}
	return lineNumber;
}

void pamix_ui::redrawVolumeBars() {
	std::lock_guard<std::mutex> lockGuard(m_DrawMutex);

	auto it = std::next(m_Entries->begin(), m_NumSkippedEntries);
	uint32_t index = 0;
	for (auto end = m_Entries->end(); it != end; it++, index++) {
		if (index >= m_NumSkippedEntries + m_NumDrawnEntries)
			break;
		uint32_t y = m_VolumeBarLineNums[it->first];
		if (it->second->m_Meter)
			drawVolumeBar(y, 1, COLS - 2, it->second->m_Peak, 1.0);
	}

	refresh();
}

void pamix_ui::drawHeader() const {
	mvprintw(0, 1, "%d/%d", m_Entries->empty() ? 0 : m_SelectedEntry + 1, m_Entries->size());
	mvprintw(0, 10, "%s", entryTypeNames[m_EntriesType]);
}

std::string pamix_ui::getEntryDisplayName(Entry *entry) {
	switch (m_EntriesType) {
		case ENTRY_SINK:
		case ENTRY_SOURCE: {
			auto deviceEntry = ((DeviceEntry *) entry);
			if (deviceEntry != nullptr) {
				const DeviceEntry::DeviceProfile *deviceProfile = deviceEntry->getPortProfile();
				if (deviceProfile != nullptr)
					return deviceProfile->description.empty() ? deviceProfile->name : deviceProfile->description;
				else
					return deviceEntry->m_Name;
			}
			return "";
		}
		case ENTRY_SINKINPUT: {
			auto sinkInput = (SinkInputEntry *) entry;
			return m_paInterface->getSinks()[sinkInput->m_Device]->m_Name;
		}
		case ENTRY_SOURCEOUTPUT: {
			auto sourceOutput = (SourceOutputEntry *) entry;
			return m_paInterface->getSources()[sourceOutput->m_Device]->m_Name;
		}
		case ENTRY_CARDS: {
			return ((CardEntry *) entry)->m_Profiles[((CardEntry *) entry)->m_Profile].description;
		}
		default:
			return "UNKNOWN ENTRY TYPE";
	}
}

pamix_ui::pamix_ui(PAInterface *paInterface) : m_paInterface(paInterface) {
	reset();
}

void pamix_ui::selectEntries(entry_type type) {
	switch (type) {
		case ENTRY_SINK:
			m_Entries = &m_paInterface->getSinks();
			break;
		case ENTRY_SOURCE:
			m_Entries = &m_paInterface->getSources();
			break;
		case ENTRY_SINKINPUT:
			m_Entries = &m_paInterface->getSinkInputs();
			break;
		case ENTRY_SOURCEOUTPUT:
			m_Entries = &m_paInterface->getSourceOutputs();
			break;
		case ENTRY_CARDS:
			m_Entries = &m_paInterface->getCards();
			break;
		default:
			return;
	}
	m_EntriesType = type;

	if (m_SelectedEntry > 0 && m_SelectedEntry >= m_Entries->size())
		m_SelectedEntry = (unsigned) m_Entries->size() - 1;
	auto currentEntry = getSelectedEntryIterator();
	if (currentEntry != m_Entries->end() && m_SelectedChannel > 0 &&
	    m_SelectedChannel >= currentEntry->second->m_PAVolume.channels)
		m_SelectedChannel = (unsigned) currentEntry->second->m_PAVolume.channels - 1;
}

int pamix_ui::getKeyInput() {
	std::lock_guard<std::mutex> guard(m_DrawMutex);
	return getch();
}

pamix_entry_iter_t pamix_ui::getSelectedEntryIterator() {
	if (m_SelectedEntry < m_Entries->size())
		return std::next(m_Entries->begin(), m_SelectedEntry);
	else
		return m_Entries->end();
}

void pamix_ui::adjustDisplayedEntries() {
	if (!m_Entries->empty())
		return;
	if (m_SelectedEntry >= m_NumSkippedEntries && m_SelectedEntry < m_NumSkippedEntries + m_NumDrawnEntries)
		return;
	if (m_SelectedEntry < m_NumSkippedEntries) {
		// scroll up until selected is at top
		m_NumSkippedEntries = m_SelectedEntry;
	} else {
		// scroll down until selected is at bottom
		uint32_t linesToFree = 0;
		uint32_t idx = m_NumSkippedEntries + m_NumDrawnEntries;
		for (; idx <= m_SelectedEntry; idx++)
			linesToFree += m_EntrySizes[idx] + 2;

		uint32_t linesFreed = 0;
		idx = m_NumSkippedEntries;
		while (linesFreed < linesToFree)
			linesFreed += m_EntrySizes[idx++] + 2;
		m_NumSkippedEntries = idx;
	}
}

void pamix_ui::selectNext(bool includeChannels) {
	moveSelection(1, includeChannels);
}

void pamix_ui::selectPrevious(bool includeChannels) {
	moveSelection(-1, includeChannels);
}

void pamix_ui::moveSelection(int delta, bool includeChannels) {
	if (m_SelectedEntry < m_Entries->size()) {
		auto it = getSelectedEntryIterator();

		int step = delta > 0 ? 1 : -1;

		for (int i = 0, numSteps = delta < 0 ? -delta : delta; i < numSteps; i++) {
			auto entryThresh = static_cast<int>(delta < 0 ? 0 : m_Entries->size() - 1);

			if (includeChannels && m_EntriesType != ENTRY_CARDS) {
				bool isLocked = it->second->m_Lock;
				int channelThresh = it->second->m_PAVolume.channels - 1;
				if (delta < 0)
					channelThresh = 0;

				if (!isLocked && m_SelectedChannel != channelThresh) {
					m_SelectedChannel += step;
					continue;
				}
			}

			if ((step == -1 && it == m_Entries->begin()) || (step == 1 && it == m_Entries->end()))
				break;

			if (m_SelectedEntry != entryThresh) {
				it = std::next(it, step);
				m_SelectedEntry += step;

				m_SelectedChannel = static_cast<unsigned int>(delta < 0 ? it->second->m_PAVolume.channels - (char) 1 : 0);
			}
		}
	}
	adjustDisplayedEntries();
}

<commit_msg>fix bug preventing entries from being scrolled.<commit_after>#include <pamix_ui.hpp>

#include <pamix.hpp>

void pamix_ui::reset() {
	m_Entries = nullptr;
	m_VolumeBarLineNums.clear();
	m_EntrySizes.clear();
	m_NumDrawnEntries = 0;
	m_NumSkippedEntries = 0;
	m_SelectedEntry = m_SelectedChannel = 0;
}

void pamix_ui::drawVolumeBar(int y, int x, int width, double fill, double maxFill) const {

	int segments = width - 2;

	if (segments <= 0)
		return;

	if (fill < 0)
		fill = 0;
	else if (fill > maxFill)
		fill = maxFill;

	auto filled = (unsigned) (fill / maxFill * (double) segments);
	if (filled > segments)
		filled = (unsigned) segments;

	mvaddstr(y, x++, "[");
	mvaddstr(y, x + segments, "]");

	auto indexColorA = (int) (segments * ((double) 1 / 3));
	auto indexColorB = (int) (segments * ((double) 2 / 3));

	FEAT_UNICODE_STRING meter;

	meter.append(filled, SYM_VOLBAR);
	meter.append((unsigned) segments - filled, SYM_SPACE);
	attron(COLOR_PAIR(1));
	FEAT_UNICODE_MVADDNSTR(y, x, meter.c_str(), indexColorA);
	attroff(COLOR_PAIR(1));
	attron(COLOR_PAIR(2));
	FEAT_UNICODE_MVADDNSTR(y, x + indexColorA, meter.c_str() + indexColorA, indexColorB - indexColorA);
	attroff(COLOR_PAIR(2));
	attron(COLOR_PAIR(3));
	FEAT_UNICODE_MVADDNSTR(y, x + indexColorB, meter.c_str() + indexColorB, segments - indexColorB);
	attroff(COLOR_PAIR(3));
}

void string_maxlen_abs(std::string &str, unsigned max) {
	if (str.length() > max) {
		str = str.substr(0, max - 2);
		str.append("..");
	}
}

void string_maxlen_pct(std::string &str, double maxPct) {
	string_maxlen_abs(str, (unsigned) (COLS * maxPct));
}

void pamix_ui::redrawAll() {
	std::lock_guard<std::mutex> lockGuard(m_DrawMutex);

	if (!m_paInterface->isConnected()) {
		clear();
		mvprintw(1, 1, "No connection to pulseaudio yet");
		refresh();
		return;
	}

	clear();
	drawHeader();

	unsigned lineNumber = 2;
	unsigned entryIndex = 0;

	auto entryIter = m_Entries->begin();
	for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++)
		m_EntrySizes[entryIndex] = entryIter->second->m_Lock ? (char) 1 : entryIter->second->m_PAVolume.channels;

	entryIndex = m_NumSkippedEntries;
	entryIter = std::next(m_Entries->begin(), entryIndex);

	for (auto end = m_Entries->end(); entryIter != end; entryIter++, entryIndex++) {
		Entry *entry = entryIter->second.get();

		std::string applicationName = entryIter->second ? entry->m_Name : "";
		pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
		char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
		bool isSelectedEntry = entryIndex == m_SelectedEntry;

		if (lineNumber + numChannels + 2 > (unsigned) LINES)
			break;

		lineNumber = drawEntryControlMeters(entry, entryIndex, lineNumber);

		double volumePeak = entry->m_Peak;
		m_VolumeBarLineNums[entryIter->first] = lineNumber;
		if (entry->m_Meter)
			drawVolumeBar(lineNumber++, 1, COLS - 2, volumePeak, 1.0);

		string_maxlen_pct(applicationName, 0.4);
		if (isSelectedEntry)
			attron(A_STANDOUT);
		mvprintw(lineNumber++, 1, applicationName.c_str());
		attroff(A_STANDOUT);

		bool isMuted = entry->m_Mute || averageVolume == PA_VOLUME_MUTED;
		printw(" %s %s", isMuted ? SYM_MUTE : "", entry->m_Lock ? SYM_LOCK : "");

		int curX = 0, curY = 0;
		getyx(stdscr, curY, curX);
		unsigned remainingChars = (unsigned) COLS - curX - 3;

		std::string displayName = getEntryDisplayName(entry);
		if (remainingChars < displayName.length()) {
			string_maxlen_abs(displayName, remainingChars);
			remainingChars = 0;
		} else {
			remainingChars -= displayName.length();
		}

		mvprintw(curY, curX + remainingChars + 1, displayName.c_str());
		lineNumber++;
	}

	m_NumDrawnEntries = entryIndex - m_NumSkippedEntries;
	refresh();
}

unsigned int pamix_ui::drawEntryControlMeters(const Entry *entry, unsigned entryIndex, unsigned int lineNumber) const {
	pa_volume_t averageVolume = pa_cvolume_avg(&entry->m_PAVolume);
	double dB = pa_sw_volume_to_dB(averageVolume);
	double vol = averageVolume / (double) PA_VOLUME_NORM;
	char numChannels = entry->m_Lock ? (char) 1 : entry->m_PAVolume.channels;
	bool isSelectedEntry = entryIndex == m_SelectedEntry;
	if (entry->m_Meter) {
		if (entry->m_Lock) {
			drawVolumeBar(lineNumber, 32, COLS - 33, vol, MAX_VOL);

			std::string descriptionTemplate = "%.2fdB (%.2f)";
			if (isSelectedEntry)
				descriptionTemplate.insert(0, SYM_ARROW);
			mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), dB, vol);
		} else {
			for (char channel = 0; channel < numChannels; channel++) {
				std::string descriptionTemplate = "%.*s %.2fdB (%.2f)";

				uint32_t volume = entry->m_PAVolume.values[channel];
				bool isSelectedChannel = isSelectedEntry && channel == m_SelectedChannel;
				double channel_dB = pa_sw_volume_to_dB(volume);
				double channel_pct = volume / (double) PA_VOLUME_NORM;
				pa_channel_position_t channelPosition = entry->m_PAChannelMap.map[channel];
				std::string channelPrettyName = pa_channel_position_to_pretty_string(channelPosition);

				drawVolumeBar(lineNumber, 32, COLS - 33, channel_pct, MAX_VOL);
				if (isSelectedChannel)
					descriptionTemplate.insert(0, SYM_ARROW);

				unsigned indent = isSelectedChannel ? 13 : 15;
				mvprintw(lineNumber++, 1, descriptionTemplate.c_str(), indent, channelPrettyName.c_str(), channel_dB,
				         channel_pct);
			}
		}
	}
	return lineNumber;
}

void pamix_ui::redrawVolumeBars() {
	std::lock_guard<std::mutex> lockGuard(m_DrawMutex);

	auto it = std::next(m_Entries->begin(), m_NumSkippedEntries);
	uint32_t index = 0;
	for (auto end = m_Entries->end(); it != end; it++, index++) {
		if (index >= m_NumSkippedEntries + m_NumDrawnEntries)
			break;
		uint32_t y = m_VolumeBarLineNums[it->first];
		if (it->second->m_Meter)
			drawVolumeBar(y, 1, COLS - 2, it->second->m_Peak, 1.0);
	}

	refresh();
}

void pamix_ui::drawHeader() const {
	mvprintw(0, 1, "%d/%d", m_Entries->empty() ? 0 : m_SelectedEntry + 1, m_Entries->size());
	mvprintw(0, 10, "%s", entryTypeNames[m_EntriesType]);
}

std::string pamix_ui::getEntryDisplayName(Entry *entry) {
	switch (m_EntriesType) {
		case ENTRY_SINK:
		case ENTRY_SOURCE: {
			auto deviceEntry = ((DeviceEntry *) entry);
			if (deviceEntry != nullptr) {
				const DeviceEntry::DeviceProfile *deviceProfile = deviceEntry->getPortProfile();
				if (deviceProfile != nullptr)
					return deviceProfile->description.empty() ? deviceProfile->name : deviceProfile->description;
				else
					return deviceEntry->m_Name;
			}
			return "";
		}
		case ENTRY_SINKINPUT: {
			auto sinkInput = (SinkInputEntry *) entry;
			return m_paInterface->getSinks()[sinkInput->m_Device]->m_Name;
		}
		case ENTRY_SOURCEOUTPUT: {
			auto sourceOutput = (SourceOutputEntry *) entry;
			return m_paInterface->getSources()[sourceOutput->m_Device]->m_Name;
		}
		case ENTRY_CARDS: {
			return ((CardEntry *) entry)->m_Profiles[((CardEntry *) entry)->m_Profile].description;
		}
		default:
			return "UNKNOWN ENTRY TYPE";
	}
}

pamix_ui::pamix_ui(PAInterface *paInterface) : m_paInterface(paInterface) {
	reset();
}

void pamix_ui::selectEntries(entry_type type) {
	switch (type) {
		case ENTRY_SINK:
			m_Entries = &m_paInterface->getSinks();
			break;
		case ENTRY_SOURCE:
			m_Entries = &m_paInterface->getSources();
			break;
		case ENTRY_SINKINPUT:
			m_Entries = &m_paInterface->getSinkInputs();
			break;
		case ENTRY_SOURCEOUTPUT:
			m_Entries = &m_paInterface->getSourceOutputs();
			break;
		case ENTRY_CARDS:
			m_Entries = &m_paInterface->getCards();
			break;
		default:
			return;
	}
	m_EntriesType = type;

	if (m_SelectedEntry > 0 && m_SelectedEntry >= m_Entries->size())
		m_SelectedEntry = (unsigned) m_Entries->size() - 1;
	auto currentEntry = getSelectedEntryIterator();
	if (currentEntry != m_Entries->end() && m_SelectedChannel > 0 &&
	    m_SelectedChannel >= currentEntry->second->m_PAVolume.channels)
		m_SelectedChannel = (unsigned) currentEntry->second->m_PAVolume.channels - 1;
}

int pamix_ui::getKeyInput() {
	std::lock_guard<std::mutex> guard(m_DrawMutex);
	return getch();
}

pamix_entry_iter_t pamix_ui::getSelectedEntryIterator() {
	if (m_SelectedEntry < m_Entries->size())
		return std::next(m_Entries->begin(), m_SelectedEntry);
	else
		return m_Entries->end();
}

void pamix_ui::adjustDisplayedEntries() {
	if (m_Entries->empty())
		return;
	if (m_SelectedEntry >= m_NumSkippedEntries && m_SelectedEntry < m_NumSkippedEntries + m_NumDrawnEntries)
		return;
	if (m_SelectedEntry < m_NumSkippedEntries) {
		// scroll up until selected is at top
		m_NumSkippedEntries = m_SelectedEntry;
	} else {
		// scroll down until selected is at bottom
		uint32_t linesToFree = 0;
		uint32_t idx = m_NumSkippedEntries + m_NumDrawnEntries;
		for (; idx <= m_SelectedEntry; idx++)
			linesToFree += m_EntrySizes[idx] + 2;

		uint32_t linesFreed = 0;
		idx = m_NumSkippedEntries;
		while (linesFreed < linesToFree)
			linesFreed += m_EntrySizes[idx++] + 2;
		m_NumSkippedEntries = idx;
	}
}

void pamix_ui::selectNext(bool includeChannels) {
	moveSelection(1, includeChannels);
}

void pamix_ui::selectPrevious(bool includeChannels) {
	moveSelection(-1, includeChannels);
}

void pamix_ui::moveSelection(int delta, bool includeChannels) {
	if (m_SelectedEntry < m_Entries->size()) {
		auto it = getSelectedEntryIterator();

		int step = delta > 0 ? 1 : -1;

		for (int i = 0, numSteps = delta < 0 ? -delta : delta; i < numSteps; i++) {
			auto entryThresh = static_cast<int>(delta < 0 ? 0 : m_Entries->size() - 1);

			if (includeChannels && m_EntriesType != ENTRY_CARDS) {
				bool isLocked = it->second->m_Lock;
				int channelThresh = it->second->m_PAVolume.channels - 1;
				if (delta < 0)
					channelThresh = 0;

				if (!isLocked && m_SelectedChannel != channelThresh) {
					m_SelectedChannel += step;
					continue;
				}
			}

			if ((step == -1 && it == m_Entries->begin()) || (step == 1 && it == m_Entries->end()))
				break;

			if (m_SelectedEntry != entryThresh) {
				it = std::next(it, step);
				m_SelectedEntry += step;

				m_SelectedChannel = static_cast<unsigned int>(delta < 0 ? it->second->m_PAVolume.channels - (char) 1 : 0);
			}
		}
	}
	adjustDisplayedEntries();
}

<|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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, History) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  host_resolver()->AddRule("www.a.com", "127.0.0.1");
  host_resolver()->AddRule("www.b.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("history")) << message_;
}
<commit_msg>Disable flaky test.  See http://crbug.com/26296 BUG=26296 TEST=none Review URL: http://codereview.chromium.org/346021<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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_History) {
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  host_resolver()->AddRule("www.a.com", "127.0.0.1");
  host_resolver()->AddRule("www.b.com", "127.0.0.1");
  StartHTTPServer();

  ASSERT_TRUE(RunExtensionTest("history")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2015-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <vector>
#include "prevector.h"

#include "serialize.h"
#include "streams.h"

#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)

template<unsigned int N, typename T>
class prevector_tester {
    typedef std::vector<T> realtype;
    realtype real_vector;
    realtype real_vector_alt;

    typedef prevector<N, T> pretype;
    pretype pre_vector;
    pretype pre_vector_alt;

    typedef typename pretype::size_type Size;
    bool passed = true;
    FastRandomContext rand_cache;
    uint256 rand_seed;

    template <typename A, typename B>
        void local_check_equal(A a, B b)
        {
            local_check(a == b);
        }
    void local_check(bool b)
    {
        passed &= b;
    }
    void test() {
        const pretype& const_pre_vector = pre_vector;
        local_check_equal(real_vector.size(), pre_vector.size());
        local_check_equal(real_vector.empty(), pre_vector.empty());
        for (Size s = 0; s < real_vector.size(); s++) {
             local_check(real_vector[s] == pre_vector[s]);
             local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));
             local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));
             local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
        }
        // local_check(realtype(pre_vector) == real_vector);
        local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
        local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
        size_t pos = 0;
        BOOST_FOREACH(const T& v, pre_vector) {
             local_check(v == real_vector[pos++]);
        }
        BOOST_REVERSE_FOREACH(const T& v, pre_vector) {
             local_check(v == real_vector[--pos]);
        }
        BOOST_FOREACH(const T& v, const_pre_vector) {
             local_check(v == real_vector[pos++]);
        }
        BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {
             local_check(v == real_vector[--pos]);
        }
        CDataStream ss1(SER_DISK, 0);
        CDataStream ss2(SER_DISK, 0);
        ss1 << real_vector;
        ss2 << pre_vector;
        local_check_equal(ss1.size(), ss2.size());
        for (Size s = 0; s < ss1.size(); s++) {
            local_check_equal(ss1[s], ss2[s]);
        }
    }

public:
    void resize(Size s) {
        real_vector.resize(s);
        local_check_equal(real_vector.size(), s);
        pre_vector.resize(s);
        local_check_equal(pre_vector.size(), s);
        test();
    }

    void reserve(Size s) {
        real_vector.reserve(s);
        local_check(real_vector.capacity() >= s);
        pre_vector.reserve(s);
        local_check(pre_vector.capacity() >= s);
        test();
    }

    void insert(Size position, const T& value) {
        real_vector.insert(real_vector.begin() + position, value);
        pre_vector.insert(pre_vector.begin() + position, value);
        test();
    }

    void insert(Size position, Size count, const T& value) {
        real_vector.insert(real_vector.begin() + position, count, value);
        pre_vector.insert(pre_vector.begin() + position, count, value);
        test();
    }

    template<typename I>
    void insert_range(Size position, I first, I last) {
        real_vector.insert(real_vector.begin() + position, first, last);
        pre_vector.insert(pre_vector.begin() + position, first, last);
        test();
    }

    void erase(Size position) {
        real_vector.erase(real_vector.begin() + position);
        pre_vector.erase(pre_vector.begin() + position);
        test();
    }

    void erase(Size first, Size last) {
        real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);
        pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);
        test();
    }

    void update(Size pos, const T& value) {
        real_vector[pos] = value;
        pre_vector[pos] = value;
        test();
    }

    void push_back(const T& value) {
        real_vector.push_back(value);
        pre_vector.push_back(value);
        test();
    }

    void pop_back() {
        real_vector.pop_back();
        pre_vector.pop_back();
        test();
    }

    void clear() {
        real_vector.clear();
        pre_vector.clear();
    }

    void assign(Size n, const T& value) {
        real_vector.assign(n, value);
        pre_vector.assign(n, value);
    }

    Size size() {
        return real_vector.size();
    }

    Size capacity() {
        return pre_vector.capacity();
    }

    void shrink_to_fit() {
        pre_vector.shrink_to_fit();
        test();
    }

    void swap() {
        real_vector.swap(real_vector_alt);
        pre_vector.swap(pre_vector_alt);
        test();
    }

    void move() {
        real_vector = std::move(real_vector_alt);
        real_vector_alt.clear();
        pre_vector = std::move(pre_vector_alt);
        pre_vector_alt.clear();
    }

    void copy() {
        real_vector = real_vector_alt;
        pre_vector = pre_vector_alt;
    }

    ~prevector_tester() {
        BOOST_CHECK_MESSAGE(passed, "insecure_rand: " + rand_seed.ToString());
    }

    prevector_tester() {
        seed_insecure_rand();
        rand_seed = insecure_rand_seed;
        rand_cache = insecure_rand_ctx;
    }
};

BOOST_AUTO_TEST_CASE(PrevectorTestInt)
{
    for (int j = 0; j < 64; j++) {
        prevector_tester<8, int> test;
        for (int i = 0; i < 2048; i++) {
            int r = insecure_rand();
            if ((r % 4) == 0) {
                test.insert(insecure_randrange(test.size() + 1), insecure_rand());
            }
            if (test.size() > 0 && ((r >> 2) % 4) == 1) {
                test.erase(insecure_randrange(test.size()));
            }
            if (((r >> 4) % 8) == 2) {
                int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_randrange(5)) - 2));
                test.resize(new_size);
            }
            if (((r >> 7) % 8) == 3) {
                test.insert(insecure_randrange(test.size() + 1), 1 + insecure_randrange(2), insecure_rand());
            }
            if (((r >> 10) % 8) == 4) {
                int del = std::min<int>(test.size(), 1 + (insecure_randrange(2)));
                int beg = insecure_randrange(test.size() + 1 - del);
                test.erase(beg, beg + del);
            }
            if (((r >> 13) % 16) == 5) {
                test.push_back(insecure_rand());
            }
            if (test.size() > 0 && ((r >> 17) % 16) == 6) {
                test.pop_back();
            }
            if (((r >> 21) % 32) == 7) {
                int values[4];
                int num = 1 + (insecure_randrange(4));
                for (int k = 0; k < num; k++) {
                    values[k] = insecure_rand();
                }
                test.insert_range(insecure_randrange(test.size() + 1), values, values + num);
            }
            if (((r >> 26) % 32) == 8) {
                int del = std::min<int>(test.size(), 1 + (insecure_randrange(4)));
                int beg = insecure_randrange(test.size() + 1 - del);
                test.erase(beg, beg + del);
            }
            r = insecure_rand();
            if (r % 32 == 9) {
                test.reserve(insecure_randrange(32));
            }
            if ((r >> 5) % 64 == 10) {
                test.shrink_to_fit();
            }
            if (test.size() > 0) {
                test.update(insecure_randrange(test.size()), insecure_rand());
            }
            if (((r >> 11) % 1024) == 11) {
                test.clear();
            }
            if (((r >> 21) % 512) == 12) {
                test.assign(insecure_randrange(32), insecure_rand());
            }
            if (((r >> 15) % 8) == 3) {
                test.swap();
            }
            if (((r >> 15) % 16) == 8) {
                test.copy();
            }
            if (((r >> 15) % 32) == 18) {
                test.move();
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Use randbits instead of ad-hoc emulation in prevector tests<commit_after>// Copyright (c) 2015-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <vector>
#include "prevector.h"

#include "serialize.h"
#include "streams.h"

#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(PrevectorTests, TestingSetup)

template<unsigned int N, typename T>
class prevector_tester {
    typedef std::vector<T> realtype;
    realtype real_vector;
    realtype real_vector_alt;

    typedef prevector<N, T> pretype;
    pretype pre_vector;
    pretype pre_vector_alt;

    typedef typename pretype::size_type Size;
    bool passed = true;
    FastRandomContext rand_cache;
    uint256 rand_seed;

    template <typename A, typename B>
        void local_check_equal(A a, B b)
        {
            local_check(a == b);
        }
    void local_check(bool b)
    {
        passed &= b;
    }
    void test() {
        const pretype& const_pre_vector = pre_vector;
        local_check_equal(real_vector.size(), pre_vector.size());
        local_check_equal(real_vector.empty(), pre_vector.empty());
        for (Size s = 0; s < real_vector.size(); s++) {
             local_check(real_vector[s] == pre_vector[s]);
             local_check(&(pre_vector[s]) == &(pre_vector.begin()[s]));
             local_check(&(pre_vector[s]) == &*(pre_vector.begin() + s));
             local_check(&(pre_vector[s]) == &*((pre_vector.end() + s) - real_vector.size()));
        }
        // local_check(realtype(pre_vector) == real_vector);
        local_check(pretype(real_vector.begin(), real_vector.end()) == pre_vector);
        local_check(pretype(pre_vector.begin(), pre_vector.end()) == pre_vector);
        size_t pos = 0;
        BOOST_FOREACH(const T& v, pre_vector) {
             local_check(v == real_vector[pos++]);
        }
        BOOST_REVERSE_FOREACH(const T& v, pre_vector) {
             local_check(v == real_vector[--pos]);
        }
        BOOST_FOREACH(const T& v, const_pre_vector) {
             local_check(v == real_vector[pos++]);
        }
        BOOST_REVERSE_FOREACH(const T& v, const_pre_vector) {
             local_check(v == real_vector[--pos]);
        }
        CDataStream ss1(SER_DISK, 0);
        CDataStream ss2(SER_DISK, 0);
        ss1 << real_vector;
        ss2 << pre_vector;
        local_check_equal(ss1.size(), ss2.size());
        for (Size s = 0; s < ss1.size(); s++) {
            local_check_equal(ss1[s], ss2[s]);
        }
    }

public:
    void resize(Size s) {
        real_vector.resize(s);
        local_check_equal(real_vector.size(), s);
        pre_vector.resize(s);
        local_check_equal(pre_vector.size(), s);
        test();
    }

    void reserve(Size s) {
        real_vector.reserve(s);
        local_check(real_vector.capacity() >= s);
        pre_vector.reserve(s);
        local_check(pre_vector.capacity() >= s);
        test();
    }

    void insert(Size position, const T& value) {
        real_vector.insert(real_vector.begin() + position, value);
        pre_vector.insert(pre_vector.begin() + position, value);
        test();
    }

    void insert(Size position, Size count, const T& value) {
        real_vector.insert(real_vector.begin() + position, count, value);
        pre_vector.insert(pre_vector.begin() + position, count, value);
        test();
    }

    template<typename I>
    void insert_range(Size position, I first, I last) {
        real_vector.insert(real_vector.begin() + position, first, last);
        pre_vector.insert(pre_vector.begin() + position, first, last);
        test();
    }

    void erase(Size position) {
        real_vector.erase(real_vector.begin() + position);
        pre_vector.erase(pre_vector.begin() + position);
        test();
    }

    void erase(Size first, Size last) {
        real_vector.erase(real_vector.begin() + first, real_vector.begin() + last);
        pre_vector.erase(pre_vector.begin() + first, pre_vector.begin() + last);
        test();
    }

    void update(Size pos, const T& value) {
        real_vector[pos] = value;
        pre_vector[pos] = value;
        test();
    }

    void push_back(const T& value) {
        real_vector.push_back(value);
        pre_vector.push_back(value);
        test();
    }

    void pop_back() {
        real_vector.pop_back();
        pre_vector.pop_back();
        test();
    }

    void clear() {
        real_vector.clear();
        pre_vector.clear();
    }

    void assign(Size n, const T& value) {
        real_vector.assign(n, value);
        pre_vector.assign(n, value);
    }

    Size size() {
        return real_vector.size();
    }

    Size capacity() {
        return pre_vector.capacity();
    }

    void shrink_to_fit() {
        pre_vector.shrink_to_fit();
        test();
    }

    void swap() {
        real_vector.swap(real_vector_alt);
        pre_vector.swap(pre_vector_alt);
        test();
    }

    void move() {
        real_vector = std::move(real_vector_alt);
        real_vector_alt.clear();
        pre_vector = std::move(pre_vector_alt);
        pre_vector_alt.clear();
    }

    void copy() {
        real_vector = real_vector_alt;
        pre_vector = pre_vector_alt;
    }

    ~prevector_tester() {
        BOOST_CHECK_MESSAGE(passed, "insecure_rand: " + rand_seed.ToString());
    }

    prevector_tester() {
        seed_insecure_rand();
        rand_seed = insecure_rand_seed;
        rand_cache = insecure_rand_ctx;
    }
};

BOOST_AUTO_TEST_CASE(PrevectorTestInt)
{
    for (int j = 0; j < 64; j++) {
        prevector_tester<8, int> test;
        for (int i = 0; i < 2048; i++) {
            if (insecure_randbits(2) == 0) {
                test.insert(insecure_randrange(test.size() + 1), insecure_rand());
            }
            if (test.size() > 0 && insecure_randbits(2) == 1) {
                test.erase(insecure_randrange(test.size()));
            }
            if (insecure_randbits(3) == 2) {
                int new_size = std::max<int>(0, std::min<int>(30, test.size() + (insecure_randrange(5)) - 2));
                test.resize(new_size);
            }
            if (insecure_randbits(3) == 3) {
                test.insert(insecure_randrange(test.size() + 1), 1 + insecure_randrange(2), insecure_rand());
            }
            if (insecure_randbits(3) == 4) {
                int del = std::min<int>(test.size(), 1 + (insecure_randrange(2)));
                int beg = insecure_randrange(test.size() + 1 - del);
                test.erase(beg, beg + del);
            }
            if (insecure_randbits(4) == 5) {
                test.push_back(insecure_rand());
            }
            if (test.size() > 0 && insecure_randbits(4) == 6) {
                test.pop_back();
            }
            if (insecure_randbits(5) == 7) {
                int values[4];
                int num = 1 + (insecure_randrange(4));
                for (int k = 0; k < num; k++) {
                    values[k] = insecure_rand();
                }
                test.insert_range(insecure_randrange(test.size() + 1), values, values + num);
            }
            if (insecure_randbits(5) == 8) {
                int del = std::min<int>(test.size(), 1 + (insecure_randrange(4)));
                int beg = insecure_randrange(test.size() + 1 - del);
                test.erase(beg, beg + del);
            }
            if (insecure_randbits(5) == 9) {
                test.reserve(insecure_randrange(32));
            }
            if (insecure_randbits(6) == 10) {
                test.shrink_to_fit();
            }
            if (test.size() > 0) {
                test.update(insecure_randrange(test.size()), insecure_rand());
            }
            if (insecure_randbits(10) == 11) {
                test.clear();
            }
            if (insecure_randbits(9) == 12) {
                test.assign(insecure_randrange(32), insecure_rand());
            }
            if (insecure_randbits(3) == 3) {
                test.swap();
            }
            if (insecure_randbits(4) == 8) {
                test.copy();
            }
            if (insecure_randbits(5) == 18) {
                test.move();
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

class ExtensionHistoryApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();

    host_resolver()->AddRule("www.a.com", "127.0.0.1");
    host_resolver()->AddRule("www.b.com", "127.0.0.1");

    ASSERT_TRUE(StartTestServer());
  }
};

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_MiscSearch) {
  ASSERT_TRUE(RunExtensionSubtest("history", "misc_search.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, TimedSearch) {
  ASSERT_TRUE(RunExtensionSubtest("history", "timed_search.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, Delete) {
  ASSERT_TRUE(RunExtensionSubtest("history", "delete.html")) << message_;
}

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_GetVisits) {
  ASSERT_TRUE(RunExtensionSubtest("history", "get_visits.html")) << message_;
}
<commit_msg>Mark all history tests as flaky.  They no longer time out or crash, but still fail flakily.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "net/base/mock_host_resolver.h"

class ExtensionHistoryApiTest : public ExtensionApiTest {
 public:
  virtual void SetUpInProcessBrowserTestFixture() {
    ExtensionApiTest::SetUpInProcessBrowserTestFixture();

    host_resolver()->AddRule("www.a.com", "127.0.0.1");
    host_resolver()->AddRule("www.b.com", "127.0.0.1");

    ASSERT_TRUE(StartTestServer());
  }
};

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_MiscSearch) {
  ASSERT_TRUE(RunExtensionSubtest("history", "misc_search.html")) << message_;
}

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_TimedSearch) {
  ASSERT_TRUE(RunExtensionSubtest("history", "timed_search.html")) << message_;
}

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_Delete) {
  ASSERT_TRUE(RunExtensionSubtest("history", "delete.html")) << message_;
}

// Flaky, http://crbug.com/26296.
IN_PROC_BROWSER_TEST_F(ExtensionHistoryApiTest, FLAKY_GetVisits) {
  ASSERT_TRUE(RunExtensionSubtest("history", "get_visits.html")) << message_;
}
<|endoftext|>


<commit_before>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 * @(#)root/roofitcore:$Id$
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

/**
\file RooNumIntConfig.cxx
\class RooNumIntConfig
\ingroup Roofitcore

RooNumIntConfig holds the configuration parameters of the various
numeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf
use this class in the (normalization) integral configuration interface
**/

#include "RooFit.h"
#include "Riostream.h"

#include "RooNumIntConfig.h"
#include "RooArgSet.h"
#include "RooAbsIntegrator.h"
#include "RooNumIntFactory.h"
#include "RooMsgService.h"

#include "TClass.h"

using namespace std;

ClassImp(RooNumIntConfig)

////////////////////////////////////////////////////////////////////////////////
/// Return reference to instance of default numeric integrator configuration object

RooNumIntConfig& RooNumIntConfig::defaultConfig()
{
  static RooNumIntConfig theConfig;
  static bool initStarted = false;

  if (!initStarted) {
    // This is needed to break a deadlock. We need the RooNumIntFactory constructor
    // to initialise us, but this constructor will call back to us again.
    // Here, we ensure that we can return the instance to the factory constructor by
    // flipping the bool, but we only return to the outside world when the factory
    // is done constructing (i.e. we leave this block).
    initStarted = true;
    RooNumIntFactory::instance();
  }

  return theConfig;
}

////////////////////////////////////////////////////////////////////////////////
/// Constructor

RooNumIntConfig::RooNumIntConfig() :
  _epsAbs(1e-7),
  _epsRel(1e-7),
  _printEvalCounter(kFALSE),
  _method1D("method1D","1D integration method"),
  _method2D("method2D","2D integration method"),
  _methodND("methodND","ND integration method"),
  _method1DOpen("method1DOpen","1D integration method in open domain"),
  _method2DOpen("method2DOpen","2D integration method in open domain"),
  _methodNDOpen("methodNDOpen","ND integration method in open domain")
{
  // Set all methods to undefined
  // Defined methods will be registered by static initialization routines
  // of the various numeric integrator engines
  _method1D.defineType("N/A",0) ;
  _method2D.defineType("N/A",0) ;
  _methodND.defineType("N/A",0) ;
  _method1DOpen.defineType("N/A",0) ;
  _method2DOpen.defineType("N/A",0) ;
  _methodNDOpen.defineType("N/A",0) ;
}

////////////////////////////////////////////////////////////////////////////////
/// Destructor

RooNumIntConfig::~RooNumIntConfig()
{
  // Delete all configuration data
  _configSets.Delete() ;
}

////////////////////////////////////////////////////////////////////////////////
/// Copy constructor

RooNumIntConfig::RooNumIntConfig(const RooNumIntConfig& other) :
  TObject(other), RooPrintable(other),
  _epsAbs(other._epsAbs),
  _epsRel(other._epsRel),
  _printEvalCounter(other._printEvalCounter),
  _method1D(other._method1D),
  _method2D(other._method2D),
  _methodND(other._methodND),
  _method1DOpen(other._method1DOpen),
  _method2DOpen(other._method2DOpen),
  _methodNDOpen(other._methodNDOpen)
{
  // Clone all configuration dat
  TIterator* iter = other._configSets.MakeIterator() ;
  RooArgSet* set ;
  while((set=(RooArgSet*)iter->Next())) {
    RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;
    setCopy->setName(set->GetName()) ;
   _configSets.Add(setCopy);
  }
  delete iter ;
}

////////////////////////////////////////////////////////////////////////////////
/// Assignment operator from other RooNumIntConfig

RooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other)
{
  // Prevent self-assignment
  if (&other==this) {
    return *this ;
  }

  // Copy common properties
  _epsAbs = other._epsAbs ;
  _epsRel = other._epsRel ;
  _method1D.setIndex(other._method1D.getCurrentIndex()) ;
  _method2D.setIndex(other._method2D.getCurrentIndex()) ;
  _methodND.setIndex(other._methodND.getCurrentIndex()) ;
  _method1DOpen.setIndex(other._method1DOpen.getCurrentIndex()) ;
  _method2DOpen.setIndex(other._method2DOpen.getCurrentIndex()) ;
  _methodNDOpen.setIndex(other._methodNDOpen.getCurrentIndex()) ;

  // Delete old integrator-specific configuration data
  _configSets.Delete() ;

  // Copy new integrator-specific data
  TIterator* iter = other._configSets.MakeIterator() ;
  RooArgSet* set ;
  while((set=(RooArgSet*)iter->Next())) {
    RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;
    setCopy->setName(set->GetName()) ;
   _configSets.Add(setCopy);
  }
  delete iter ;

  return *this ;
}

////////////////////////////////////////////////////////////////////////////////
/// Add a configuration section for a particular integrator. Integrator name and capabilities are
/// automatically determined from instance passed as 'proto'. The defaultConfig object is associated
/// as the default configuration for the integrator.

Bool_t RooNumIntConfig::addConfigSection(const RooAbsIntegrator* proto, const RooArgSet& inDefaultConfig)
{
  std::string name = proto->IsA()->GetName() ;

  // Register integrator for appropriate dimensionalities
  if (proto->canIntegrate1D()) {
    _method1D.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _method1DOpen.defineType(name) ;
    }
  }

  if (proto->canIntegrate2D()) {
    _method2D.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _method2DOpen.defineType(name) ;
    }
  }

  if (proto->canIntegrateND()) {
    _methodND.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _methodNDOpen.defineType(name) ;
    }
  }

  // Store default configuration parameters
  RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ;
  config->setName(name.c_str());
  _configSets.Add(config) ;

  return kFALSE ;
}

////////////////////////////////////////////////////////////////////////////////
/// Return section with configuration parameters for integrator with given (class) name

RooArgSet& RooNumIntConfig::getConfigSection(const char* name)
{
  return const_cast<RooArgSet&>((const_cast<const RooNumIntConfig*>(this)->getConfigSection(name))) ;
}

////////////////////////////////////////////////////////////////////////////////
/// Retrieve configuration information specific to integrator with given name

const RooArgSet& RooNumIntConfig::getConfigSection(const char* name) const
{
  static RooArgSet dummy ;
  RooArgSet* config = (RooArgSet*) _configSets.FindObject(name) ;
  if (!config) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::getIntegrator: ERROR: no configuration stored for integrator '" << name << "'" << endl ;
    return dummy ;
  }
  return *config ;
}

////////////////////////////////////////////////////////////////////////////////
/// Set absolute convergence criteria (convergence if abs(Err)<newEpsAbs)

void RooNumIntConfig::setEpsAbs(Double_t newEpsAbs)
{
  if (newEpsAbs<0) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::setEpsAbs: ERROR: target absolute precision must be greater or equal than zero" << endl ;
    return ;
  }
  _epsAbs = newEpsAbs ;
}

RooPrintable::StyleOption RooNumIntConfig::defaultPrintStyle(Option_t* opt) const
{
  if (!opt) {
    return kStandard ;
  }

  TString o(opt) ;
  o.ToLower() ;

  if (o.Contains("v")) {
    return kVerbose ;
  }
  return kStandard ;
}

////////////////////////////////////////////////////////////////////////////////
/// Set relative convergence criteria (convergence if abs(Err)/abs(Int)<newEpsRel)

void RooNumIntConfig::setEpsRel(Double_t newEpsRel)
{
  if (newEpsRel<0) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::setEpsRel: ERROR: target absolute precision must be greater or equal than zero" << endl ;
    return ;
  }
  _epsRel = newEpsRel ;
}

////////////////////////////////////////////////////////////////////////////////
/// Detailed printing interface

void RooNumIntConfig::printMultiline(ostream &os, Int_t /*content*/, Bool_t verbose, TString indent) const
{
  os << indent << "Requested precision: " << _epsAbs << " absolute, " << _epsRel << " relative" << endl << endl ;
  if (_printEvalCounter) {
    os << indent << "Printing of function evaluation counter for each integration enabled" << endl << endl ;
  }

  os << indent << "1-D integration method: " << _method1D.getCurrentLabel() ;
  if (_method1DOpen.getCurrentIndex()!=_method1D.getCurrentIndex()) {
    os << " (" << _method1DOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }
  os << indent << "2-D integration method: " << _method2D.getCurrentLabel() ;
  if (_method2DOpen.getCurrentIndex()!=_method2D.getCurrentIndex()) {
    os << " (" << _method2DOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }
  os << indent << "N-D integration method: " << _methodND.getCurrentLabel() ;
  if (_methodNDOpen.getCurrentIndex()!=_methodND.getCurrentIndex()) {
    os << " (" << _methodNDOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }

  if (verbose) {

    os << endl << "Available integration methods:" << endl << endl ;
    TIterator* cIter = _configSets.MakeIterator() ;
    RooArgSet* configSet ;
    while ((configSet=(RooArgSet*)cIter->Next())) {

      os << indent << "*** " << configSet->GetName() << " ***" << endl ;
      os << indent << "Capabilities: " ;
      const RooAbsIntegrator* proto = RooNumIntFactory::instance().getProtoIntegrator(configSet->GetName()) ;
      if (proto->canIntegrate1D()) os << "[1-D] " ;
      if (proto->canIntegrate2D()) os << "[2-D] " ;
      if (proto->canIntegrateND()) os << "[N-D] " ;
      if (proto->canIntegrateOpenEnded()) os << "[OpenEnded] " ;
      os << endl ;

      os << "Configuration: " << endl ;
      configSet->printMultiline(os,kName|kValue) ;
      //configSet->writeToStream(os,kFALSE) ;

      const char* depName = RooNumIntFactory::instance().getDepIntegratorName(configSet->GetName()) ;
      if (strlen(depName)>0) {
	os << indent << "(Depends on '" << depName << "')" << endl ;
      }
      os << endl ;

    }

    delete cIter ;
  }
}
<commit_msg>[RF] Correct an error message.<commit_after>/*****************************************************************************
 * Project: RooFit                                                           *
 * Package: RooFitCore                                                       *
 * @(#)root/roofitcore:$Id$
 * Authors:                                                                  *
 *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
 *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
 *                                                                           *
 * Copyright (c) 2000-2005, Regents of the University of California          *
 *                          and Stanford University. All rights reserved.    *
 *                                                                           *
 * Redistribution and use in source and binary forms,                        *
 * with or without modification, are permitted according to the terms        *
 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
 *****************************************************************************/

/**
\file RooNumIntConfig.cxx
\class RooNumIntConfig
\ingroup Roofitcore

RooNumIntConfig holds the configuration parameters of the various
numeric integrators used by RooRealIntegral. RooRealIntegral and RooAbsPdf
use this class in the (normalization) integral configuration interface
**/

#include "RooFit.h"
#include "Riostream.h"

#include "RooNumIntConfig.h"
#include "RooArgSet.h"
#include "RooAbsIntegrator.h"
#include "RooNumIntFactory.h"
#include "RooMsgService.h"

#include "TClass.h"

using namespace std;

ClassImp(RooNumIntConfig)

////////////////////////////////////////////////////////////////////////////////
/// Return reference to instance of default numeric integrator configuration object

RooNumIntConfig& RooNumIntConfig::defaultConfig()
{
  static RooNumIntConfig theConfig;
  static bool initStarted = false;

  if (!initStarted) {
    // This is needed to break a deadlock. We need the RooNumIntFactory constructor
    // to initialise us, but this constructor will call back to us again.
    // Here, we ensure that we can return the instance to the factory constructor by
    // flipping the bool, but we only return to the outside world when the factory
    // is done constructing (i.e. we leave this block).
    initStarted = true;
    RooNumIntFactory::instance();
  }

  return theConfig;
}

////////////////////////////////////////////////////////////////////////////////
/// Constructor

RooNumIntConfig::RooNumIntConfig() :
  _epsAbs(1e-7),
  _epsRel(1e-7),
  _printEvalCounter(kFALSE),
  _method1D("method1D","1D integration method"),
  _method2D("method2D","2D integration method"),
  _methodND("methodND","ND integration method"),
  _method1DOpen("method1DOpen","1D integration method in open domain"),
  _method2DOpen("method2DOpen","2D integration method in open domain"),
  _methodNDOpen("methodNDOpen","ND integration method in open domain")
{
  // Set all methods to undefined
  // Defined methods will be registered by static initialization routines
  // of the various numeric integrator engines
  _method1D.defineType("N/A",0) ;
  _method2D.defineType("N/A",0) ;
  _methodND.defineType("N/A",0) ;
  _method1DOpen.defineType("N/A",0) ;
  _method2DOpen.defineType("N/A",0) ;
  _methodNDOpen.defineType("N/A",0) ;
}

////////////////////////////////////////////////////////////////////////////////
/// Destructor

RooNumIntConfig::~RooNumIntConfig()
{
  // Delete all configuration data
  _configSets.Delete() ;
}

////////////////////////////////////////////////////////////////////////////////
/// Copy constructor

RooNumIntConfig::RooNumIntConfig(const RooNumIntConfig& other) :
  TObject(other), RooPrintable(other),
  _epsAbs(other._epsAbs),
  _epsRel(other._epsRel),
  _printEvalCounter(other._printEvalCounter),
  _method1D(other._method1D),
  _method2D(other._method2D),
  _methodND(other._methodND),
  _method1DOpen(other._method1DOpen),
  _method2DOpen(other._method2DOpen),
  _methodNDOpen(other._methodNDOpen)
{
  // Clone all configuration dat
  TIterator* iter = other._configSets.MakeIterator() ;
  RooArgSet* set ;
  while((set=(RooArgSet*)iter->Next())) {
    RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;
    setCopy->setName(set->GetName()) ;
   _configSets.Add(setCopy);
  }
  delete iter ;
}

////////////////////////////////////////////////////////////////////////////////
/// Assignment operator from other RooNumIntConfig

RooNumIntConfig& RooNumIntConfig::operator=(const RooNumIntConfig& other)
{
  // Prevent self-assignment
  if (&other==this) {
    return *this ;
  }

  // Copy common properties
  _epsAbs = other._epsAbs ;
  _epsRel = other._epsRel ;
  _method1D.setIndex(other._method1D.getCurrentIndex()) ;
  _method2D.setIndex(other._method2D.getCurrentIndex()) ;
  _methodND.setIndex(other._methodND.getCurrentIndex()) ;
  _method1DOpen.setIndex(other._method1DOpen.getCurrentIndex()) ;
  _method2DOpen.setIndex(other._method2DOpen.getCurrentIndex()) ;
  _methodNDOpen.setIndex(other._methodNDOpen.getCurrentIndex()) ;

  // Delete old integrator-specific configuration data
  _configSets.Delete() ;

  // Copy new integrator-specific data
  TIterator* iter = other._configSets.MakeIterator() ;
  RooArgSet* set ;
  while((set=(RooArgSet*)iter->Next())) {
    RooArgSet* setCopy = (RooArgSet*) set->snapshot() ;
    setCopy->setName(set->GetName()) ;
   _configSets.Add(setCopy);
  }
  delete iter ;

  return *this ;
}

////////////////////////////////////////////////////////////////////////////////
/// Add a configuration section for a particular integrator. Integrator name and capabilities are
/// automatically determined from instance passed as 'proto'. The defaultConfig object is associated
/// as the default configuration for the integrator.

Bool_t RooNumIntConfig::addConfigSection(const RooAbsIntegrator* proto, const RooArgSet& inDefaultConfig)
{
  std::string name = proto->IsA()->GetName() ;

  // Register integrator for appropriate dimensionalities
  if (proto->canIntegrate1D()) {
    _method1D.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _method1DOpen.defineType(name) ;
    }
  }

  if (proto->canIntegrate2D()) {
    _method2D.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _method2DOpen.defineType(name) ;
    }
  }

  if (proto->canIntegrateND()) {
    _methodND.defineType(name) ;
    if (proto->canIntegrateOpenEnded()) {
      _methodNDOpen.defineType(name) ;
    }
  }

  // Store default configuration parameters
  RooArgSet* config = (RooArgSet*) inDefaultConfig.snapshot() ;
  config->setName(name.c_str());
  _configSets.Add(config) ;

  return kFALSE ;
}

////////////////////////////////////////////////////////////////////////////////
/// Return section with configuration parameters for integrator with given (class) name

RooArgSet& RooNumIntConfig::getConfigSection(const char* name)
{
  return const_cast<RooArgSet&>((const_cast<const RooNumIntConfig*>(this)->getConfigSection(name))) ;
}

////////////////////////////////////////////////////////////////////////////////
/// Retrieve configuration information specific to integrator with given name

const RooArgSet& RooNumIntConfig::getConfigSection(const char* name) const
{
  static RooArgSet dummy ;
  RooArgSet* config = (RooArgSet*) _configSets.FindObject(name) ;
  if (!config) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::getConfigSection: ERROR: no configuration stored for integrator '" << name << "'" << endl ;
    return dummy ;
  }
  return *config ;
}

////////////////////////////////////////////////////////////////////////////////
/// Set absolute convergence criteria (convergence if abs(Err)<newEpsAbs)

void RooNumIntConfig::setEpsAbs(Double_t newEpsAbs)
{
  if (newEpsAbs<0) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::setEpsAbs: ERROR: target absolute precision must be greater or equal than zero" << endl ;
    return ;
  }
  _epsAbs = newEpsAbs ;
}

RooPrintable::StyleOption RooNumIntConfig::defaultPrintStyle(Option_t* opt) const
{
  if (!opt) {
    return kStandard ;
  }

  TString o(opt) ;
  o.ToLower() ;

  if (o.Contains("v")) {
    return kVerbose ;
  }
  return kStandard ;
}

////////////////////////////////////////////////////////////////////////////////
/// Set relative convergence criteria (convergence if abs(Err)/abs(Int)<newEpsRel)

void RooNumIntConfig::setEpsRel(Double_t newEpsRel)
{
  if (newEpsRel<0) {
    oocoutE((TObject*)0,InputArguments) << "RooNumIntConfig::setEpsRel: ERROR: target absolute precision must be greater or equal than zero" << endl ;
    return ;
  }
  _epsRel = newEpsRel ;
}

////////////////////////////////////////////////////////////////////////////////
/// Detailed printing interface

void RooNumIntConfig::printMultiline(ostream &os, Int_t /*content*/, Bool_t verbose, TString indent) const
{
  os << indent << "Requested precision: " << _epsAbs << " absolute, " << _epsRel << " relative" << endl << endl ;
  if (_printEvalCounter) {
    os << indent << "Printing of function evaluation counter for each integration enabled" << endl << endl ;
  }

  os << indent << "1-D integration method: " << _method1D.getCurrentLabel() ;
  if (_method1DOpen.getCurrentIndex()!=_method1D.getCurrentIndex()) {
    os << " (" << _method1DOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }
  os << indent << "2-D integration method: " << _method2D.getCurrentLabel() ;
  if (_method2DOpen.getCurrentIndex()!=_method2D.getCurrentIndex()) {
    os << " (" << _method2DOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }
  os << indent << "N-D integration method: " << _methodND.getCurrentLabel() ;
  if (_methodNDOpen.getCurrentIndex()!=_methodND.getCurrentIndex()) {
    os << " (" << _methodNDOpen.getCurrentLabel() << " if open-ended)" << endl ;
  } else {
    os << endl ;
  }

  if (verbose) {

    os << endl << "Available integration methods:" << endl << endl ;
    TIterator* cIter = _configSets.MakeIterator() ;
    RooArgSet* configSet ;
    while ((configSet=(RooArgSet*)cIter->Next())) {

      os << indent << "*** " << configSet->GetName() << " ***" << endl ;
      os << indent << "Capabilities: " ;
      const RooAbsIntegrator* proto = RooNumIntFactory::instance().getProtoIntegrator(configSet->GetName()) ;
      if (proto->canIntegrate1D()) os << "[1-D] " ;
      if (proto->canIntegrate2D()) os << "[2-D] " ;
      if (proto->canIntegrateND()) os << "[N-D] " ;
      if (proto->canIntegrateOpenEnded()) os << "[OpenEnded] " ;
      os << endl ;

      os << "Configuration: " << endl ;
      configSet->printMultiline(os,kName|kValue) ;
      //configSet->writeToStream(os,kFALSE) ;

      const char* depName = RooNumIntFactory::instance().getDepIntegratorName(configSet->GetName()) ;
      if (strlen(depName)>0) {
	os << indent << "(Depends on '" << depName << "')" << endl ;
      }
      os << endl ;

    }

    delete cIter ;
  }
}
<|endoftext|>