<commit_before>#define BOOST_TEST_MODULE TEST_TRAINERS

#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/training.h>
#include <dynet/grad-check.h>
#include <boost/test/unit_test.hpp>
#include <stdexcept>

using namespace dynet;
using namespace std;

struct TrainerTest {
  TrainerTest() {
    // initialize if necessary
    if(default_device == nullptr) {
      for (auto x : {"TrainerTest", "--dynet-mem", "10"}) {
        av.push_back(strdup(x));
      }
      char **argv = &av[0];
      int argc = av.size();
      dynet::initialize(argc, argv);
    }
    ones_vals = {1.f,1.f,1.f};
    param_vals = {1.1f,-2.2f,3.3f};
    param2_vals = {1.1f,-2.2f,3.3f};
  }
  ~TrainerTest() {
    for (auto x : av) free(x);
  }

  template <class T>
  std::string print_vec(const std::vector<T> vec) {
    ostringstream oss;
    if(vec.size()) oss << vec[0];
    for(size_t i = 1; i < vec.size(); i++)
      oss << ' ' << vec[i];
    return oss.str();
  }

  std::vector<float> ones_vals, param_vals, param2_vals;
  std::vector<char*> av;
};

// define the test suite
BOOST_FIXTURE_TEST_SUITE(trainer_test, TrainerTest);

// Test direction (does updating reduce the objective value)

#define DYNET_TRAINER_DIRECTION_TEST_CASE(name, TRAINER_TYPE)       \
BOOST_AUTO_TEST_CASE( name ) {                                      \
  dynet::ParameterCollection mod;                                   \
  dynet::Parameter param = mod.add_parameters({3});                 \
  TensorTools::set_elements(param.get_storage().values, param_vals);\
  TRAINER_TYPE trainer(mod);                                        \
  dynet::ComputationGraph cg;                                       \
  Expression x = parameter(cg, param);                              \
  Expression y = input(cg, {1, 3}, ones_vals);                      \
  Expression z = y * x;                                             \
  float before = as_scalar(cg.forward(z));                          \
  cg.backward(z);                                                   \
  trainer.update();                                                 \
  float after = as_scalar(cg.forward(z));                           \
  BOOST_CHECK_LT(after, before);                                    \
}                                                                   \

DYNET_TRAINER_DIRECTION_TEST_CASE(simple_sgd_direction, dynet::SimpleSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(cyclical_sgd_direction, dynet::CyclicalSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(momentum_sgd_direction, dynet::MomentumSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adagrad_direction, dynet::AdagradTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adadelta_direction, dynet::AdadeltaTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(rmsprop_direction, dynet::RMSPropTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adam_direction, dynet::AdamTrainer)

BOOST_AUTO_TEST_CASE( eg_direction ) {
  param_vals = {0.5f,0.1f,0.4f};// EGTrainer requires values belonging to simplex [0,1]
  dynet::ParameterCollection mod;
  dynet::Parameter param = mod.add_parameters({3});
  TensorTools::set_elements(param.get_storage().values,param_vals);
  EGTrainer trainer(mod);
  dynet::ComputationGraph cg;
  Expression x = parameter(cg, param);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y*x;
  float before = as_scalar(cg.forward(z));
  cg.backward(z);
  trainer.update();
  float after = as_scalar(cg.forward(z));
  BOOST_CHECK_EQUAL(after, before);
  param_vals = {1.1f,-2.2f,3.3f};// revert back to original values
}

// Test the restart method (TODO: for now only checks for errors)

#define DYNET_TRAINER_RESTART_TEST_CASE(name, TRAINER_TYPE)         \
BOOST_AUTO_TEST_CASE( name ) {                                      \
  dynet::ParameterCollection mod;                                   \
  dynet::Parameter param = mod.add_parameters({3});                 \
  TensorTools::set_elements(param.get_storage().values, param_vals);\
  TRAINER_TYPE trainer(mod);                                        \
  dynet::ComputationGraph cg;                                       \
  Expression x = parameter(cg, param);                              \
  Expression y = input(cg, {1, 3}, ones_vals);                      \
  Expression z = y * x;                                             \
  cg.forward(z);                                                    \
  cg.backward(z);                                                   \
  trainer.update();                                                 \
  trainer.restart(0.1);                                             \
}                                                                   \

DYNET_TRAINER_RESTART_TEST_CASE(simple_sgd_restart, dynet::SimpleSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(cyclical_sgd_restart, dynet::CyclicalSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(momentum_sgd_restart, dynet::MomentumSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adagrad_restart, dynet::AdagradTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adadelta_restart, dynet::AdadeltaTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(rmsprop_restart, dynet::RMSPropTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adam_restart, dynet::AdamTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(eg_restart, dynet::EGTrainer)

BOOST_AUTO_TEST_CASE( momentum_restart_correctness ) {
  dynet::ParameterCollection pc;
  dynet::Parameter param = pc.add_parameters({3});
  MomentumSGDTrainer trainer(pc, 1.0);
  dynet::ComputationGraph cg;
  Expression x1 = parameter(cg, param);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y * x1;
  cg.backward(z);
  trainer.update();
  vector<float> vp_val = as_vector(trainer.vp[0].h);
  // Test that the velocity has been updated
  for(size_t i = 0; i < vp_val.size(); ++i)
    BOOST_CHECK_EQUAL(vp_val[i], -1.0);
  trainer.restart(0.5);
  vp_val = as_vector(trainer.vp[0].h);
  // Test that the velocity has been reset to 0
  for(size_t i = 0; i < vp_val.size(); ++i)
    BOOST_CHECK_EQUAL(vp_val[i], 0);
  // Test that the learning rate has been set to 0.5
  BOOST_CHECK_EQUAL(trainer.learning_rate, 0.5);
}

// Test subset update

BOOST_AUTO_TEST_CASE( simple_sgd_update_subset ) {
  dynet::ParameterCollection mod;
  dynet::Parameter param = mod.add_parameters({3});
  dynet::Parameter param2 = mod.add_parameters({3});
  TensorTools::set_elements(param.get_storage().values,param_vals);
  TensorTools::set_elements(param2.get_storage().values,param2_vals);
  param2.set_updated(false);
  SimpleSGDTrainer trainer(mod);
  dynet::ComputationGraph cg;
  Expression x1 = parameter(cg, param);
  Expression x2 = parameter(cg, param2);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y*(x1+x2);
  cg.backward(z);
  trainer.update();
  vector<float> param_after = as_vector(param.get_storage().values);
  vector<float> param2_after = as_vector(param2.get_storage().values);
  for(size_t i = 0; i < param_after.size(); ++i)
    BOOST_CHECK_NE(param_vals[i], param_after[i]);
  for(size_t i = 0; i < param2_after.size(); ++i)
    BOOST_CHECK_EQUAL(param2_vals[i], param2_after[i]);
}

BOOST_AUTO_TEST_CASE( simple_edge_case_test_dynet_867 ) {
  ParameterCollection model;
  LookupParameter emb_weight = model.add_lookup_parameters(1, {1});
  Parameter foo = model.add_parameters({1, 1});
  SimpleSGDTrainer trainer(model);
  ComputationGraph cg;
  dynet::real zero;
  Expression loss2 = input(cg, zero);
  for (int i = 0; i < 1000; ++i)
    auto emb_read = dynet::lookup(cg, emb_weight, 0u);
  cg.backward(loss2);
  trainer.update();
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Tests: Fix warnings in test-trainers.cc (#884)<commit_after>#define BOOST_TEST_MODULE TEST_TRAINERS

#include <dynet/dynet.h>
#include <dynet/expr.h>
#include <dynet/training.h>
#include <dynet/grad-check.h>
#include <boost/test/unit_test.hpp>
#include <stdexcept>

using namespace dynet;
using namespace std;

struct TrainerTest {
  TrainerTest() {
    // initialize if necessary
    if(default_device == nullptr) {
      for (auto x : {"TrainerTest", "--dynet-mem", "10"}) {
        av.push_back(strdup(x));
      }
      char **argv = &av[0];
      int argc = av.size();
      dynet::initialize(argc, argv);
    }
    ones_vals = {1.f,1.f,1.f};
    param_vals = {1.1f,-2.2f,3.3f};
    param2_vals = {1.1f,-2.2f,3.3f};
  }
  ~TrainerTest() {
    for (auto x : av) free(x);
  }

  template <class T>
  std::string print_vec(const std::vector<T> vec) {
    ostringstream oss;
    if(vec.size()) oss << vec[0];
    for(size_t i = 1; i < vec.size(); i++)
      oss << ' ' << vec[i];
    return oss.str();
  }

  std::vector<float> ones_vals, param_vals, param2_vals;
  std::vector<char*> av;
};

// define the test suite
BOOST_FIXTURE_TEST_SUITE(trainer_test, TrainerTest);

// Test direction (does updating reduce the objective value)

#define DYNET_TRAINER_DIRECTION_TEST_CASE(name, TRAINER_TYPE)       \
BOOST_AUTO_TEST_CASE( name ) {                                      \
  dynet::ParameterCollection mod;                                   \
  dynet::Parameter param = mod.add_parameters({3});                 \
  TensorTools::set_elements(param.get_storage().values, param_vals);\
  TRAINER_TYPE trainer(mod);                                        \
  dynet::ComputationGraph cg;                                       \
  Expression x = parameter(cg, param);                              \
  Expression y = input(cg, {1, 3}, ones_vals);                      \
  Expression z = y * x;                                             \
  float before = as_scalar(cg.forward(z));                          \
  cg.backward(z);                                                   \
  trainer.update();                                                 \
  float after = as_scalar(cg.forward(z));                           \
  BOOST_CHECK_LT(after, before);                                    \
}                                                                   \

DYNET_TRAINER_DIRECTION_TEST_CASE(simple_sgd_direction, dynet::SimpleSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(cyclical_sgd_direction, dynet::CyclicalSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(momentum_sgd_direction, dynet::MomentumSGDTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adagrad_direction, dynet::AdagradTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adadelta_direction, dynet::AdadeltaTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(rmsprop_direction, dynet::RMSPropTrainer)

DYNET_TRAINER_DIRECTION_TEST_CASE(adam_direction, dynet::AdamTrainer)

BOOST_AUTO_TEST_CASE( eg_direction ) {
  param_vals = {0.5f,0.1f,0.4f};// EGTrainer requires values belonging to simplex [0,1]
  dynet::ParameterCollection mod;
  dynet::Parameter param = mod.add_parameters({3});
  TensorTools::set_elements(param.get_storage().values,param_vals);
  EGTrainer trainer(mod);
  dynet::ComputationGraph cg;
  Expression x = parameter(cg, param);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y*x;
  float before = as_scalar(cg.forward(z));
  cg.backward(z);
  trainer.update();
  float after = as_scalar(cg.forward(z));
  BOOST_CHECK_EQUAL(after, before);
  param_vals = {1.1f,-2.2f,3.3f};// revert back to original values
}

// Test the restart method (TODO: for now only checks for errors)

#define DYNET_TRAINER_RESTART_TEST_CASE(name, TRAINER_TYPE)         \
BOOST_AUTO_TEST_CASE( name ) {                                      \
  dynet::ParameterCollection mod;                                   \
  dynet::Parameter param = mod.add_parameters({3});                 \
  TensorTools::set_elements(param.get_storage().values, param_vals);\
  TRAINER_TYPE trainer(mod);                                        \
  dynet::ComputationGraph cg;                                       \
  Expression x = parameter(cg, param);                              \
  Expression y = input(cg, {1, 3}, ones_vals);                      \
  Expression z = y * x;                                             \
  cg.forward(z);                                                    \
  cg.backward(z);                                                   \
  trainer.update();                                                 \
  trainer.restart(0.1);                                             \
}                                                                   \

DYNET_TRAINER_RESTART_TEST_CASE(simple_sgd_restart, dynet::SimpleSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(cyclical_sgd_restart, dynet::CyclicalSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(momentum_sgd_restart, dynet::MomentumSGDTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adagrad_restart, dynet::AdagradTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adadelta_restart, dynet::AdadeltaTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(rmsprop_restart, dynet::RMSPropTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(adam_restart, dynet::AdamTrainer)

DYNET_TRAINER_RESTART_TEST_CASE(eg_restart, dynet::EGTrainer)

BOOST_AUTO_TEST_CASE( momentum_restart_correctness ) {
  dynet::ParameterCollection pc;
  dynet::Parameter param = pc.add_parameters({3});
  MomentumSGDTrainer trainer(pc, 1.0);
  dynet::ComputationGraph cg;
  Expression x1 = parameter(cg, param);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y * x1;
  cg.backward(z);
  trainer.update();
  vector<float> vp_val = as_vector(trainer.vp[0].h);
  // Test that the velocity has been updated
  for(size_t i = 0; i < vp_val.size(); ++i)
    BOOST_CHECK_EQUAL(vp_val[i], -1.0);
  trainer.restart(0.5);
  vp_val = as_vector(trainer.vp[0].h);
  // Test that the velocity has been reset to 0
  for(size_t i = 0; i < vp_val.size(); ++i)
    BOOST_CHECK_EQUAL(vp_val[i], 0);
  // Test that the learning rate has been set to 0.5
  BOOST_CHECK_EQUAL(trainer.learning_rate, 0.5);
}

// Test subset update

BOOST_AUTO_TEST_CASE( simple_sgd_update_subset ) {
  dynet::ParameterCollection mod;
  dynet::Parameter param = mod.add_parameters({3});
  dynet::Parameter param2 = mod.add_parameters({3});
  TensorTools::set_elements(param.get_storage().values,param_vals);
  TensorTools::set_elements(param2.get_storage().values,param2_vals);
  param2.set_updated(false);
  SimpleSGDTrainer trainer(mod);
  dynet::ComputationGraph cg;
  Expression x1 = parameter(cg, param);
  Expression x2 = parameter(cg, param2);
  Expression y = input(cg, {1,3}, ones_vals);
  Expression z = y*(x1+x2);
  cg.backward(z);
  trainer.update();
  vector<float> param_after = as_vector(param.get_storage().values);
  vector<float> param2_after = as_vector(param2.get_storage().values);
  for(size_t i = 0; i < param_after.size(); ++i)
    BOOST_CHECK_NE(param_vals[i], param_after[i]);
  for(size_t i = 0; i < param2_after.size(); ++i)
    BOOST_CHECK_EQUAL(param2_vals[i], param2_after[i]);
}

BOOST_AUTO_TEST_CASE( simple_edge_case_test_dynet_867 ) {
  ParameterCollection model;
  LookupParameter emb_weight = model.add_lookup_parameters(1, {1});
  model.add_parameters({1, 1});
  SimpleSGDTrainer trainer(model);
  ComputationGraph cg;
  dynet::real zero = 0.0;
  Expression loss2 = input(cg, zero);
  for (int i = 0; i < 1000; ++i)
    dynet::lookup(cg, emb_weight, 0u);
  cg.backward(loss2);
  trainer.update();
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>// test_Cryptor.cpp -- Test Sodium::Cryptor
//
// ISC License
//
// Copyright (c) 2017 Farid Hajji <farid@hajji.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Sodium::Cryptor Test
#include <boost/test/included/unit_test.hpp>

#include <sodium.h>
#include "cryptor.h"
#include "key.h"
#include "nonce.h"
#include <string>

using Sodium::Cryptor;
using Sodium::Key;
using Sodium::Nonce;

using data_t = Sodium::data_t;

bool
test_of_correctness(const std::string &plaintext)
{
  Cryptor sc    {};
  Key     key   (Cryptor::KEYSIZE);
  Nonce<> nonce {};

  data_t plainblob {plaintext.cbegin(), plaintext.cend()};

  data_t ciphertext = sc.encrypt(plainblob, key, nonce);
  data_t decrypted  = sc.decrypt(ciphertext, key, nonce);

  key.noaccess();

  BOOST_CHECK(ciphertext.size() == plainblob.size() + Sodium::Cryptor::MACSIZE);
  BOOST_CHECK(decrypted.size()  == plainblob.size());

  return plainblob == decrypted;
}

bool
test_of_correctness_detached(const std::string &plaintext)
{
  Cryptor sc    {};
  Key     key   (Cryptor::KEYSIZE);
  Nonce<> nonce {};

  data_t plainblob {plaintext.cbegin(), plaintext.cend()};
  data_t mac(Cryptor::MACSIZE);

  data_t ciphertext = sc.encrypt(plainblob, key, nonce, mac);
  data_t decrypted  = sc.decrypt(ciphertext, mac, key, nonce);

  key.noaccess();

  BOOST_CHECK(ciphertext.size() == plainblob.size());
  BOOST_CHECK(decrypted.size()  == plainblob.size());

  return plainblob == decrypted;
}

struct SodiumFixture {
  SodiumFixture()  {
    BOOST_REQUIRE(sodium_init() != -1);
    BOOST_TEST_MESSAGE("SodiumFixture(): sodium_init() successful.");
  }
  ~SodiumFixture() {
    BOOST_TEST_MESSAGE("~SodiumFixture(): teardown -- no-op.");
  }
};

BOOST_FIXTURE_TEST_SUITE ( sodium_test_suite, SodiumFixture );

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext_detached )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness_detached(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext_detached )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness_detached(plaintext));
}

BOOST_AUTO_TEST_SUITE_END ();
<commit_msg>Added falsifying unit tests to Sodium::Cryptor.<commit_after>// test_Cryptor.cpp -- Test Sodium::Cryptor
//
// ISC License
//
// Copyright (c) 2017 Farid Hajji <farid@hajji.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Sodium::Cryptor Test
#include <boost/test/included/unit_test.hpp>

#include <sodium.h>
#include "cryptor.h"
#include "key.h"
#include "nonce.h"
#include <string>

using Sodium::Cryptor;
using Sodium::Key;
using Sodium::Nonce;

using data_t = Sodium::data_t;

bool
test_of_correctness(const std::string &plaintext,
		    bool falsify_ciphertext=false,
		    bool falsify_mac=false)
{
  Cryptor sc    {};
  Key     key   (Cryptor::KEYSIZE);
  Nonce<> nonce {};

  data_t plainblob {plaintext.cbegin(), plaintext.cend()};

  data_t ciphertext = sc.encrypt(plainblob, key, nonce);

  BOOST_CHECK(ciphertext.size() == plainblob.size() + Cryptor::MACSIZE);

  if (! plaintext.empty() && falsify_ciphertext) {
    // ciphertext is of the form: (MAC || actual_ciphertext)
    ++ciphertext[Cryptor::MACSIZE]; // falsify ciphertext
  }

  if (falsify_mac) {
    // ciphertext is of the form: (MAC || actual_ciphertext)
    ++ciphertext[0]; // falsify MAC
  }

  try {
    data_t decrypted  = sc.decrypt(ciphertext, key, nonce);

    BOOST_CHECK(decrypted.size()  == plainblob.size());

    // decryption succeeded and plainblob == decrypted if and only if
    // we didn't falsify the ciphertext nor the MAC

    return !falsify_ciphertext &&
      !falsify_mac &&
      (plainblob == decrypted);
  }
  catch (std::exception &e) {
    // decryption failed. This is expected if and only if we falsified
    // the ciphertext OR we falsified the MAC (or both).

    return falsify_ciphertext || falsify_mac;
  }

  // NOTREACHED (hopefully)
  return false;
}

bool
test_of_correctness_detached(const std::string &plaintext,
			     bool falsify_ciphertext=false,
			     bool falsify_mac=false)
{
  Cryptor sc    {};
  Key     key   (Cryptor::KEYSIZE);
  Nonce<> nonce {};

  data_t plainblob {plaintext.cbegin(), plaintext.cend()};
  data_t mac(Cryptor::MACSIZE);

  data_t ciphertext = sc.encrypt(plainblob, key, nonce, mac);

  BOOST_CHECK(ciphertext.size() == plainblob.size());

  if (! plaintext.empty() && falsify_ciphertext)
    ++ciphertext[0]; // falsify ciphertext

  if (falsify_mac)
    ++mac[0]; // falsify MAC

  try {
    data_t decrypted  = sc.decrypt(ciphertext, mac, key, nonce);

    BOOST_CHECK(decrypted.size()  == plainblob.size());

    // decryption succeeded and plainblob == decrypted if and only if
    // we didn't falsify the ciphertext nor the MAC:

    return !falsify_ciphertext &&
      !falsify_mac &&
      (plainblob == decrypted);
  }
  catch (std::exception &e) {
    // decryption failed. This is expected if and only if we falsified
    // the ciphertext OR we falsified the MAC (or both).

    return falsify_ciphertext || falsify_mac;
  }

  // NOTREACHED (hopefully)
  return false;
}

struct SodiumFixture {
  SodiumFixture()  {
    BOOST_REQUIRE(sodium_init() != -1);
    BOOST_TEST_MESSAGE("SodiumFixture(): sodium_init() successful.");
  }
  ~SodiumFixture() {
    BOOST_TEST_MESSAGE("~SodiumFixture(): teardown -- no-op.");
  }
};

BOOST_FIXTURE_TEST_SUITE ( sodium_test_suite, SodiumFixture );

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_full_plaintext_detached )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness_detached(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_empty_plaintext_detached )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness_detached(plaintext));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_ciphertext )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness(plaintext, true, false));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_mac )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness(plaintext, false, true));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_mac_empty )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness(plaintext, false, true));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_ciphertext_and_mac )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness(plaintext, true, true));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_ciphertext_detached )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness_detached(plaintext, true, false));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_mac_detached )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness_detached(plaintext, false, true));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_mac_empty_detached )
{
  std::string plaintext {};
  BOOST_CHECK(test_of_correctness_detached(plaintext, false, true));
}

BOOST_AUTO_TEST_CASE( sodium_cryptor_test_falsify_ciphertext_and_mac_detached )
{
  std::string plaintext {"the quick brown fox jumps over the lazy dog"};
  BOOST_CHECK(test_of_correctness_detached(plaintext, true, true));
}

BOOST_AUTO_TEST_SUITE_END ();
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_api_native_image.h"

#include <string>
#include <vector>

#include "atom/common/node_includes.h"
#include "base/process/process_metrics.h"
#include "native_mate/dictionary.h"

namespace {

v8::Local<v8::Value> GetProcessMemoryInfo(v8::Isolate* isolate) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  std::unique_ptr<base::ProcessMetrics> metrics(
    base::ProcessMetrics::CreateCurrentProcessMetrics());

  dict.Set("workingSetSize", (double)(metrics->GetWorkingSetSize() >> 10));
  dict.Set("peakWorkingSetSize", (double)(metrics->GetPeakWorkingSetSize() >> 10));

  size_t private_bytes, shared_bytes;
  if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) {
    dict.Set("privateBytes", (double)(private_bytes >> 10));
    dict.Set("sharedBytes", (double)(shared_bytes >> 10));
  }

  return dict.GetHandle();
}

v8::Local<v8::Value> GetSystemMemoryInfo(v8::Isolate* isolate, mate::Arguments* args) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  base::SystemMemoryInfoKB memInfo;

  if (!base::GetSystemMemoryInfo(&memInfo)) {
    args->ThrowError("Unable to retrieve system memory information");
    return v8::Undefined(isolate);
  }

  dict.Set("total", memInfo.total);
  dict.Set("free", memInfo.free);

  // NB: These return bogus values on OS X
#if !defined(OS_MACOSX)
  dict.Set("swapTotal", memInfo.swap_total);
  dict.Set("swapFree", memInfo.swap_free);
#endif

  return dict.GetHandle();
}

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_process_stats, Initialize)
<commit_msg>Linting<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/api/atom_api_native_image.h"

#include <string>
#include <vector>

#include "atom/common/node_includes.h"
#include "base/process/process_metrics.h"
#include "native_mate/dictionary.h"

namespace {

v8::Local<v8::Value> GetProcessMemoryInfo(v8::Isolate* isolate) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  std::unique_ptr<base::ProcessMetrics> metrics(
    base::ProcessMetrics::CreateCurrentProcessMetrics());

  dict.Set("workingSetSize",
    static_cast<double>(metrics->GetWorkingSetSize() >> 10));
  dict.Set("peakWorkingSetSize",
    static_cast<double>(metrics->GetPeakWorkingSetSize() >> 10));

  size_t private_bytes, shared_bytes;
  if (metrics->GetMemoryBytes(&private_bytes, &shared_bytes)) {
    dict.Set("privateBytes", static_cast<double>(private_bytes >> 10));
    dict.Set("sharedBytes", static_cast<double>(shared_bytes >> 10));
  }

  return dict.GetHandle();
}

v8::Local<v8::Value> GetSystemMemoryInfo(
    v8::Isolate* isolate,
    mate::Arguments* args) {
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  base::SystemMemoryInfoKB memInfo;

  if (!base::GetSystemMemoryInfo(&memInfo)) {
    args->ThrowError("Unable to retrieve system memory information");
    return v8::Undefined(isolate);
  }

  dict.Set("total", memInfo.total);
  dict.Set("free", memInfo.free);

  // NB: These return bogus values on OS X
#if !defined(OS_MACOSX)
  dict.Set("swapTotal", memInfo.swap_total);
  dict.Set("swapFree", memInfo.swap_free);
#endif

  return dict.GetHandle();
}

void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context, void* priv) {
  mate::Dictionary dict(context->GetIsolate(), exports);
  dict.SetMethod("getProcessMemoryInfo", &GetProcessMemoryInfo);
  dict.SetMethod("getSystemMemoryInfo", &GetSystemMemoryInfo);
}

}  // namespace

NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_common_process_stats, Initialize)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: hfi_method.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-18 14:11:38 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_method.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_exception.hxx>
#include <ary/idl/i_param.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_funcdecl.hxx>
#include "hfi_doc.hxx"
#include "hfi_globalindex.hxx"
#include "hfi_typetext.hxx"

HF_IdlMethod::HF_IdlMethod( Environment &           io_rEnv,
                            Xml::Element &          o_cell)
    :   HtmlFactory_Idl(io_rEnv,&o_cell)
{
}

HF_IdlMethod::~HF_IdlMethod()
{
}

void
HF_IdlMethod::Produce_byData( const String &      i_sName,
                              type_id             i_nReturnType,
                              param_list &        i_rParams,
                              type_list &         i_rExceptions,
                              bool                i_bOneway,
                              const client &      i_ce ) const
{
    CurOut()
        >> *new Html::Label(i_sName)
            << new Html::ClassAttr(C_sMemberTitle)
            << i_sName;
    enter_ContentCell();
    write_Declaration( i_sName,
                       i_nReturnType,
                       i_rParams,
                       i_rExceptions,
                       i_bOneway );
    CurOut() << new Html::HorizontalLine;
    write_Docu(CurOut(), i_ce);
    leave_ContentCell();
}

void
HF_IdlMethod::write_Declaration( const String &      i_sName,
                                 type_id             i_nReturnType,
                                 param_list &        i_rParams,
                                 type_list &         i_rExceptions,
                                 bool                i_bOneway ) const
{
    HF_FunctionDeclaration
        aDecl(CurOut()) ;
    Xml::Element &
        front = aDecl.Add_ReturnLine();

    // Front:
    if (i_bOneway)
        front << "[oneway] ";
    HF_IdlTypeText
        aReturn(Env(), front,true);
    aReturn.Produce_byData(i_nReturnType);
    front
        << new Html::LineBreak
        >> *new Html::Bold
            << i_sName;

    //  Main line:
    Xml::Element &
        types = aDecl.Types();
    Xml::Element &
        names = aDecl.Names();
    bool bParams = bool( BOOL_OF(i_rParams) );
    if (bParams)
    {
        front
            << "(";
        HF_IdlTypeText
            aType( Env(), types, true );

        write_Param( aType, names, (*i_rParams) );

        for (++i_rParams; i_rParams; ++i_rParams)
        {
            types
                << new Html::LineBreak;
            names
                << ","
                << new Html::LineBreak;
            write_Param( aType, names, (*i_rParams) );
        }   // end for

        names
            << " )";
    }
    else
        front
            << "()";

    if ( BOOL_OF(i_rExceptions) )
    {
        Xml::Element &
            rExcOut = aDecl.Add_RaisesLine("raises", NOT bParams);
        HF_IdlTypeText
            aExc(Env(), rExcOut, true);
        aExc.Produce_byData(*i_rExceptions);

        for (++i_rExceptions; i_rExceptions; ++i_rExceptions)
        {
            rExcOut
                << ","
                << new Html::LineBreak;
            aExc.Produce_byData(*i_rExceptions);
        }   // end for

        rExcOut << " );";
    }
    else
    {
        if (bParams)
            aDecl.Names() << ";";
        else
            aDecl.Front() << ";";
    }
}

void
HF_IdlMethod::write_Param( HF_IdlTypeText &             o_type,
                           Xml::Element &               o_names,
                           const ary::idl::Parameter &  i_param ) const
{
    switch ( i_param.Direction() )
    {
        case ary::idl::param_in:
                    o_type.CurOut() << "[in] ";
                    break;
        case ary::idl::param_out:
                    o_type.CurOut() << "[out] ";
                    break;
        case ary::idl::param_inout:
                    o_type.CurOut() << "[inout] ";
                    break;
    }   // end switch

    o_type.Produce_byData( i_param.Type() );
    o_names
        << i_param.Name();
}

const String sContentBorder("0");
const String sContentWidth("96%");
const String sContentPadding("5");
const String sContentSpacing("0");

const String sBgWhite("#ffffff");
const String sCenter("center");

void
HF_IdlMethod::enter_ContentCell() const
{

    Xml::Element &
        rContentCell = CurOut()
                        >> *new Html::Table( sContentBorder,
                                             sContentWidth,
                                             sContentPadding,
                                             sContentSpacing )
                            << new Html::BgColorAttr(sBgWhite)
                            << new Html::AlignAttr(sCenter)
                            >> *new Html::TableRow
                                >> *new Html::TableCell;
    Out().Enter(rContentCell);
}

void
HF_IdlMethod::leave_ContentCell() const
{
    Out().Leave();
}

<commit_msg>INTEGRATION: CWS adc8 (1.2.66); FILE MERGED 2004/07/02 11:04:11 np 1.2.66.1: #i26261#<commit_after>/*************************************************************************
 *
 *  $RCSfile: hfi_method.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-12 15:26:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include "hfi_method.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/idl/i_exception.hxx>
#include <ary/idl/i_param.hxx>
#include <toolkit/hf_docentry.hxx>
#include <toolkit/hf_funcdecl.hxx>
#include "hfi_doc.hxx"
#include "hfi_globalindex.hxx"
#include "hfi_typetext.hxx"

HF_IdlMethod::HF_IdlMethod( Environment &           io_rEnv,
                            Xml::Element &          o_cell)
    :   HtmlFactory_Idl(io_rEnv,&o_cell)
{
}

HF_IdlMethod::~HF_IdlMethod()
{
}

void
HF_IdlMethod::Produce_byData( const String &      i_sName,
                              type_id             i_nReturnType,
                              param_list &        i_rParams,
                              type_list &         i_rExceptions,
                              bool                i_bOneway,
                              bool                i_bEllipse,
                              const client &      i_ce ) const
{
    CurOut()
        >> *new Html::Label(i_sName)
            << new Html::ClassAttr(C_sMemberTitle)
            << i_sName;
    enter_ContentCell();
    write_Declaration( i_sName,
                       i_nReturnType,
                       i_rParams,
                       i_rExceptions,
                       i_bOneway,
                       i_bEllipse );
    CurOut() << new Html::HorizontalLine;
    write_Docu(CurOut(), i_ce);
    leave_ContentCell();
}

void
HF_IdlMethod::write_Declaration( const String &      i_sName,
                                 type_id             i_nReturnType,
                                 param_list &        i_rParams,
                                 type_list &         i_rExceptions,
                                 bool                i_bOneway,
                                 bool                i_bEllipse ) const
{
    HF_FunctionDeclaration
        aDecl(CurOut()) ;
    Xml::Element &
        front = aDecl.Add_ReturnLine();

    // Front:
    if (i_bOneway)
        front << "[oneway] ";
    if (i_nReturnType.IsValid())
    {   // Normal function, but not constructors:
        HF_IdlTypeText
            aReturn(Env(), front,true);
        aReturn.Produce_byData(i_nReturnType);
        front
            << new Html::LineBreak;

    }
    front
        >> *new Html::Bold
            << i_sName;

    //  Main line:
    Xml::Element &
        types = aDecl.Types();
    Xml::Element &
        names = aDecl.Names();
    bool bParams = i_rParams.operator bool();
    if (bParams)
    {
        front
            << "(";
        HF_IdlTypeText
            aType( Env(), types, true );

        write_Param( aType, names, (*i_rParams) );

        for (++i_rParams; i_rParams; ++i_rParams)
        {
            types
                << new Html::LineBreak;
            names
                << ","
                << new Html::LineBreak;
            write_Param( aType, names, (*i_rParams) );
        }   // end for

        if (i_bEllipse)
        {
            names
                << " ...";
        }
        names
            << " )";
    }
    else
        front
            << "()";

    if ( i_rExceptions.operator bool() )
    {
        Xml::Element &
            rExcOut = aDecl.Add_RaisesLine("raises", NOT bParams);
        HF_IdlTypeText
            aExc(Env(), rExcOut, true);
        aExc.Produce_byData(*i_rExceptions);

        for (++i_rExceptions; i_rExceptions; ++i_rExceptions)
        {
            rExcOut
                << ","
                << new Html::LineBreak;
            aExc.Produce_byData(*i_rExceptions);
        }   // end for

        rExcOut << " );";
    }
    else
    {
        if (bParams)
            aDecl.Names() << ";";
        else
            aDecl.Front() << ";";
    }
}

void
HF_IdlMethod::write_Param( HF_IdlTypeText &             o_type,
                           Xml::Element &               o_names,
                           const ary::idl::Parameter &  i_param ) const
{
    switch ( i_param.Direction() )
    {
        case ary::idl::param_in:
                    o_type.CurOut() << "[in] ";
                    break;
        case ary::idl::param_out:
                    o_type.CurOut() << "[out] ";
                    break;
        case ary::idl::param_inout:
                    o_type.CurOut() << "[inout] ";
                    break;
    }   // end switch

    o_type.Produce_byData( i_param.Type() );
    o_names
        << i_param.Name();
}

const String sContentBorder("0");
const String sContentWidth("96%");
const String sContentPadding("5");
const String sContentSpacing("0");

const String sBgWhite("#ffffff");
const String sCenter("center");

void
HF_IdlMethod::enter_ContentCell() const
{

    Xml::Element &
        rContentCell = CurOut()
                        >> *new Html::Table( sContentBorder,
                                             sContentWidth,
                                             sContentPadding,
                                             sContentSpacing )
                            << new Html::BgColorAttr(sBgWhite)
                            << new Html::AlignAttr(sCenter)
                            >> *new Html::TableRow
                                >> *new Html::TableCell;
    Out().Enter(rContentCell);
}

void
HF_IdlMethod::leave_ContentCell() const
{
    Out().Leave();
}

<|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 "chrome/browser/chromeos/login/background_view.h"

#include <string>
#include <vector>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/oobe_progress_bar.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/shutdown_button.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "cros/chromeos_wm_ipc_enums.h"
#include "googleurl/src/gurl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/text_button.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"

// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>

using views::WidgetGtk;

namespace {

const SkColor kVersionColor = 0xff5c739f;

// Returns the corresponding step id for step constant.
int GetStepId(size_t step) {
  switch (step) {
    case chromeos::BackgroundView::SELECT_NETWORK:
      return IDS_OOBE_SELECT_NETWORK;
    case chromeos::BackgroundView::EULA:
      return IDS_OOBE_EULA;
    case chromeos::BackgroundView::SIGNIN:
      return IDS_OOBE_SIGNIN;
    case chromeos::BackgroundView::REGISTRATION:
      return IDS_OOBE_REGISTRATION;
    case chromeos::BackgroundView::PICTURE:
      return IDS_OOBE_PICTURE;
    default:
      NOTREACHED();
      return 0;
  }
}

// The same as TextButton but switches cursor to hand cursor when mouse
// is over the button.
class TextButtonWithHandCursorOver : public views::TextButton {
 public:
  TextButtonWithHandCursorOver(views::ButtonListener* listener,
                               const std::wstring& text)
      : views::TextButton(listener, text) {
  }

  virtual ~TextButtonWithHandCursorOver() {}

  virtual gfx::NativeCursor GetCursorForPoint(
      views::Event::EventType event_type,
      const gfx::Point& p) {
    if (!IsEnabled()) {
      return NULL;
    }
    return gdk_cursor_new(GDK_HAND2);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TextButtonWithHandCursorOver);
};

// This gets rid of the ugly X default cursor.
static void ResetXCursor() {
  // TODO(sky): nuke this once new window manager is in place.
  Display* display = x11_util::GetXDisplay();
  Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
  XID root_window = x11_util::GetX11RootWindow();
  XSetWindowAttributes attr;
  attr.cursor = cursor;
  XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}

}  // namespace

namespace chromeos {

///////////////////////////////////////////////////////////////////////////////
// BackgroundView public:

BackgroundView::BackgroundView()
    : status_area_(NULL),
      os_version_label_(NULL),
      boot_times_label_(NULL),
      progress_bar_(NULL),
      shutdown_button_(NULL),
      did_paint_(false),
#if defined(OFFICIAL_BUILD)
      is_official_build_(true),
#else
      is_official_build_(false),
#endif
      background_area_(NULL) {
}

void BackgroundView::Init(const GURL& background_url) {
  views::Painter* painter = CreateBackgroundPainter();
  set_background(views::Background::CreateBackgroundPainter(true, painter));
  InitStatusArea();
  InitInfoLabels();
  if (!background_url.is_empty()) {
    Profile* profile = ProfileManager::GetDefaultProfile();
    background_area_ = new DOMView();
    AddChildView(background_area_);
    background_area_->Init(profile, NULL);
    background_area_->SetVisible(false);
    background_area_->LoadURL(background_url);
  }
}

void BackgroundView::EnableShutdownButton(bool enable) {
  if (enable) {
    if (shutdown_button_)
      return;
    shutdown_button_ = new ShutdownButton();
    shutdown_button_->Init();
    AddChildView(shutdown_button_);
  } else {
    if (!shutdown_button_)
      return;
    delete shutdown_button_;
    shutdown_button_ = NULL;
  }
}

// static
views::Widget* BackgroundView::CreateWindowContainingView(
    const gfx::Rect& bounds,
    const GURL& background_url,
    BackgroundView** view) {
  ResetXCursor();

  WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
  window->Init(NULL, bounds);
  *view = new BackgroundView();
  (*view)->Init(background_url);

  if ((*view)->ScreenSaverEnabled())
    (*view)->ShowScreenSaver();

  window->SetContentsView(*view);

  (*view)->UpdateWindowType();

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);

  return window;
}

void BackgroundView::SetStatusAreaVisible(bool visible) {
  status_area_->SetVisible(visible);
}

void BackgroundView::SetStatusAreaEnabled(bool enable) {
  status_area_->EnableButtons(enable);
}

void BackgroundView::SetOobeProgressBarVisible(bool visible) {
  if (!progress_bar_ && visible)
    InitProgressBar();

  if (progress_bar_)
    progress_bar_->SetVisible(visible);
}

bool BackgroundView::IsOobeProgressBarVisible() {
  return progress_bar_ && progress_bar_->IsVisible();
}

void BackgroundView::SetOobeProgress(LoginStep step) {
  DCHECK(step < STEPS_COUNT);
  if (progress_bar_)
    progress_bar_->SetStep(GetStepId(step));
}

void BackgroundView::ShowScreenSaver() {
  SetStatusAreaVisible(false);
  background_area_->SetVisible(true);
}

void BackgroundView::HideScreenSaver() {
  SetStatusAreaVisible(true);
  // TODO(oshima): we need a way to suspend screen saver
  // to save power when it's not visible.
  background_area_->SetVisible(false);
}

bool BackgroundView::IsScreenSaverVisible() {
  return ScreenSaverEnabled() && background_area_->IsVisible();
}

bool BackgroundView::ScreenSaverEnabled() {
  return background_area_ != NULL;
}

///////////////////////////////////////////////////////////////////////////////
// BackgroundView protected:

void BackgroundView::Paint(gfx::Canvas* canvas) {
  views::View::Paint(canvas);
  if (!did_paint_) {
    did_paint_ = true;
    UpdateWindowType();
  }
}

void BackgroundView::Layout() {
  const int kCornerPadding = 5;
  const int kInfoLeftPadding = 15;
  const int kInfoBottomPadding = 15;
  const int kInfoBetweenLinesPadding = 4;
  const int kProgressBarBottomPadding = 20;
  const int kProgressBarWidth = 750;
  const int kProgressBarHeight = 70;
  gfx::Size status_area_size = status_area_->GetPreferredSize();
  status_area_->SetBounds(
      width() - status_area_size.width() - kCornerPadding,
      kCornerPadding,
      status_area_size.width(),
      status_area_size.height());
  gfx::Size version_size = os_version_label_->GetPreferredSize();
  int os_version_y = height() - version_size.height() - kInfoBottomPadding;
  if (!is_official_build_)
    os_version_y -= version_size.height() - kInfoBetweenLinesPadding;
  os_version_label_->SetBounds(
      kInfoLeftPadding,
      os_version_y,
      width() - 2 * kInfoLeftPadding,
      version_size.height());
  if (!is_official_build_) {
    boot_times_label_->SetBounds(
        kInfoLeftPadding,
        height() - (version_size.height() + kInfoBottomPadding),
        width() - 2 * kInfoLeftPadding,
        version_size.height());
  }
  if (progress_bar_) {
    progress_bar_->SetBounds(
        (width() - kProgressBarWidth) / 2,
        (height() - kProgressBarBottomPadding - kProgressBarHeight),
        kProgressBarWidth,
        kProgressBarHeight);
  }
  if (shutdown_button_) {
    shutdown_button_->LayoutIn(this);
  }
  if (background_area_)
    background_area_->SetBounds(this->bounds());
}

void BackgroundView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

gfx::NativeWindow BackgroundView::GetNativeWindow() const {
  return
      GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}

bool BackgroundView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->network_view()) {
    return true;
  }
  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->input_method_view()) {
    return false;
  }
  return true;
}

void BackgroundView::OpenButtonOptions(const views::View* button_view) {
  if (button_view == status_area_->network_view()) {
    if (proxy_settings_dialog_.get() == NULL) {
      proxy_settings_dialog_.reset(new ProxySettingsDialog(
          this, GetNativeWindow()));
    }
    proxy_settings_dialog_->Show();
  }
}

bool BackgroundView::IsBrowserMode() const {
  return false;
}

bool BackgroundView::IsScreenLockerMode() const {
  return false;
}

// Overridden from LoginHtmlDialog::Delegate:
void BackgroundView::OnLocaleChanged() {
  // Proxy settings dialog contains localized strings.
  proxy_settings_dialog_.reset();
}

///////////////////////////////////////////////////////////////////////////////
// BackgroundView private:

void BackgroundView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  AddChildView(status_area_);
}

void BackgroundView::InitInfoLabels() {
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();

  os_version_label_ = new views::Label();
  os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  os_version_label_->SetColor(kVersionColor);
  os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(os_version_label_);
  if (!is_official_build_) {
    boot_times_label_ = new views::Label();
    boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    boot_times_label_->SetColor(kVersionColor);
    boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
    AddChildView(boot_times_label_);
  }

  if (CrosLibrary::Get()->EnsureLoaded()) {
    version_loader_.GetVersion(
        &version_consumer_,
        NewCallback(this, &BackgroundView::OnVersion),
        is_official_build_?
            VersionLoader::VERSION_SHORT_WITH_DATE :
            VersionLoader::VERSION_FULL);
    if (!is_official_build_) {
      boot_times_loader_.GetBootTimes(
          &boot_times_consumer_,
          NewCallback(this, &BackgroundView::OnBootTimes));
    }
  } else {
    os_version_label_->SetText(
        ASCIIToWide(CrosLibrary::Get()->load_error_string()));
  }
}

void BackgroundView::InitProgressBar() {
  std::vector<int> steps;
  steps.push_back(GetStepId(SELECT_NETWORK));
#if defined(OFFICIAL_BUILD)
  steps.push_back(GetStepId(EULA));
#endif
  steps.push_back(GetStepId(SIGNIN));
#if defined(OFFICIAL_BUILD)
  if (WizardController::IsRegisterScreenDefined())
    steps.push_back(GetStepId(REGISTRATION));
#endif
  steps.push_back(GetStepId(PICTURE));
  progress_bar_ = new OobeProgressBar(steps);
  AddChildView(progress_bar_);
}

void BackgroundView::UpdateWindowType() {
  std::vector<int> params;
  params.push_back(did_paint_ ? 1 : 0);
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_BACKGROUND,
      &params);
}

void BackgroundView::OnVersion(
    VersionLoader::Handle handle, std::string version) {
  // TODO(jungshik): Is string concatenation OK here?
  std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_OS_NAME);
  version_text += ' ';
  version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
  version_text += ' ';
  version_text += version;

  // Workaround over incorrect width calculation in old fonts.
  // TODO(glotov): remove the following line when new fonts are used.
  version_text += ' ';
  os_version_label_->SetText(UTF8ToWide(version_text));
}

void BackgroundView::OnBootTimes(
    BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
  const char* kBootTimesNoChromeExec =
      "Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
  const char* kBootTimesChromeExec =
      "Boot took %.2f seconds "
      "(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
  std::string boot_times_text;

  if (boot_times.chrome > 0) {
    boot_times_text =
        base::StringPrintf(
            kBootTimesChromeExec,
            boot_times.total,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.system,
            boot_times.chrome);
  } else {
    boot_times_text =
        base::StringPrintf(
            kBootTimesNoChromeExec,
            boot_times.total,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.system);
  }
  // Use UTF8ToWide once this string is localized.
  boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}

}  // namespace chromeos
<commit_msg>Explicitly request to repaint background when removing the shutdown button.<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 "chrome/browser/chromeos/login/background_view.h"

#include <string>
#include <vector>
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "app/x11_util.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/oobe_progress_bar.h"
#include "chrome/browser/chromeos/login/proxy_settings_dialog.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/shutdown_button.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/chromeos/status/clock_menu_button.h"
#include "chrome/browser/chromeos/status/input_method_menu_button.h"
#include "chrome/browser/chromeos/status/network_menu_button.h"
#include "chrome/browser/chromeos/status/status_area_view.h"
#include "chrome/browser/chromeos/wm_ipc.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/views/dom_view.h"
#include "cros/chromeos_wm_ipc_enums.h"
#include "googleurl/src/gurl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/controls/button/text_button.h"
#include "views/controls/label.h"
#include "views/screen.h"
#include "views/widget/widget_gtk.h"

// X Windows headers have "#define Status int". That interferes with
// NetworkLibrary header which defines enum "Status".
#include <X11/cursorfont.h>
#include <X11/Xcursor/Xcursor.h>

using views::WidgetGtk;

namespace {

const SkColor kVersionColor = 0xff5c739f;

// Returns the corresponding step id for step constant.
int GetStepId(size_t step) {
  switch (step) {
    case chromeos::BackgroundView::SELECT_NETWORK:
      return IDS_OOBE_SELECT_NETWORK;
    case chromeos::BackgroundView::EULA:
      return IDS_OOBE_EULA;
    case chromeos::BackgroundView::SIGNIN:
      return IDS_OOBE_SIGNIN;
    case chromeos::BackgroundView::REGISTRATION:
      return IDS_OOBE_REGISTRATION;
    case chromeos::BackgroundView::PICTURE:
      return IDS_OOBE_PICTURE;
    default:
      NOTREACHED();
      return 0;
  }
}

// The same as TextButton but switches cursor to hand cursor when mouse
// is over the button.
class TextButtonWithHandCursorOver : public views::TextButton {
 public:
  TextButtonWithHandCursorOver(views::ButtonListener* listener,
                               const std::wstring& text)
      : views::TextButton(listener, text) {
  }

  virtual ~TextButtonWithHandCursorOver() {}

  virtual gfx::NativeCursor GetCursorForPoint(
      views::Event::EventType event_type,
      const gfx::Point& p) {
    if (!IsEnabled()) {
      return NULL;
    }
    return gdk_cursor_new(GDK_HAND2);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TextButtonWithHandCursorOver);
};

// This gets rid of the ugly X default cursor.
static void ResetXCursor() {
  // TODO(sky): nuke this once new window manager is in place.
  Display* display = x11_util::GetXDisplay();
  Cursor cursor = XCreateFontCursor(display, XC_left_ptr);
  XID root_window = x11_util::GetX11RootWindow();
  XSetWindowAttributes attr;
  attr.cursor = cursor;
  XChangeWindowAttributes(display, root_window, CWCursor, &attr);
}

}  // namespace

namespace chromeos {

///////////////////////////////////////////////////////////////////////////////
// BackgroundView public:

BackgroundView::BackgroundView()
    : status_area_(NULL),
      os_version_label_(NULL),
      boot_times_label_(NULL),
      progress_bar_(NULL),
      shutdown_button_(NULL),
      did_paint_(false),
#if defined(OFFICIAL_BUILD)
      is_official_build_(true),
#else
      is_official_build_(false),
#endif
      background_area_(NULL) {
}

void BackgroundView::Init(const GURL& background_url) {
  views::Painter* painter = CreateBackgroundPainter();
  set_background(views::Background::CreateBackgroundPainter(true, painter));
  InitStatusArea();
  InitInfoLabels();
  if (!background_url.is_empty()) {
    Profile* profile = ProfileManager::GetDefaultProfile();
    background_area_ = new DOMView();
    AddChildView(background_area_);
    background_area_->Init(profile, NULL);
    background_area_->SetVisible(false);
    background_area_->LoadURL(background_url);
  }
}

void BackgroundView::EnableShutdownButton(bool enable) {
  if (enable) {
    if (shutdown_button_)
      return;
    shutdown_button_ = new ShutdownButton();
    shutdown_button_->Init();
    AddChildView(shutdown_button_);
  } else {
    if (!shutdown_button_)
      return;
    delete shutdown_button_;
    shutdown_button_ = NULL;
    SchedulePaint();
  }
}

// static
views::Widget* BackgroundView::CreateWindowContainingView(
    const gfx::Rect& bounds,
    const GURL& background_url,
    BackgroundView** view) {
  ResetXCursor();

  WidgetGtk* window = new WidgetGtk(WidgetGtk::TYPE_WINDOW);
  window->Init(NULL, bounds);
  *view = new BackgroundView();
  (*view)->Init(background_url);

  if ((*view)->ScreenSaverEnabled())
    (*view)->ShowScreenSaver();

  window->SetContentsView(*view);

  (*view)->UpdateWindowType();

  // This keeps the window from flashing at startup.
  GdkWindow* gdk_window = window->GetNativeView()->window;
  gdk_window_set_back_pixmap(gdk_window, NULL, false);

  return window;
}

void BackgroundView::SetStatusAreaVisible(bool visible) {
  status_area_->SetVisible(visible);
}

void BackgroundView::SetStatusAreaEnabled(bool enable) {
  status_area_->EnableButtons(enable);
}

void BackgroundView::SetOobeProgressBarVisible(bool visible) {
  if (!progress_bar_ && visible)
    InitProgressBar();

  if (progress_bar_)
    progress_bar_->SetVisible(visible);
}

bool BackgroundView::IsOobeProgressBarVisible() {
  return progress_bar_ && progress_bar_->IsVisible();
}

void BackgroundView::SetOobeProgress(LoginStep step) {
  DCHECK(step < STEPS_COUNT);
  if (progress_bar_)
    progress_bar_->SetStep(GetStepId(step));
}

void BackgroundView::ShowScreenSaver() {
  SetStatusAreaVisible(false);
  background_area_->SetVisible(true);
}

void BackgroundView::HideScreenSaver() {
  SetStatusAreaVisible(true);
  // TODO(oshima): we need a way to suspend screen saver
  // to save power when it's not visible.
  background_area_->SetVisible(false);
}

bool BackgroundView::IsScreenSaverVisible() {
  return ScreenSaverEnabled() && background_area_->IsVisible();
}

bool BackgroundView::ScreenSaverEnabled() {
  return background_area_ != NULL;
}

///////////////////////////////////////////////////////////////////////////////
// BackgroundView protected:

void BackgroundView::Paint(gfx::Canvas* canvas) {
  views::View::Paint(canvas);
  if (!did_paint_) {
    did_paint_ = true;
    UpdateWindowType();
  }
}

void BackgroundView::Layout() {
  const int kCornerPadding = 5;
  const int kInfoLeftPadding = 15;
  const int kInfoBottomPadding = 15;
  const int kInfoBetweenLinesPadding = 4;
  const int kProgressBarBottomPadding = 20;
  const int kProgressBarWidth = 750;
  const int kProgressBarHeight = 70;
  gfx::Size status_area_size = status_area_->GetPreferredSize();
  status_area_->SetBounds(
      width() - status_area_size.width() - kCornerPadding,
      kCornerPadding,
      status_area_size.width(),
      status_area_size.height());
  gfx::Size version_size = os_version_label_->GetPreferredSize();
  int os_version_y = height() - version_size.height() - kInfoBottomPadding;
  if (!is_official_build_)
    os_version_y -= version_size.height() - kInfoBetweenLinesPadding;
  os_version_label_->SetBounds(
      kInfoLeftPadding,
      os_version_y,
      width() - 2 * kInfoLeftPadding,
      version_size.height());
  if (!is_official_build_) {
    boot_times_label_->SetBounds(
        kInfoLeftPadding,
        height() - (version_size.height() + kInfoBottomPadding),
        width() - 2 * kInfoLeftPadding,
        version_size.height());
  }
  if (progress_bar_) {
    progress_bar_->SetBounds(
        (width() - kProgressBarWidth) / 2,
        (height() - kProgressBarBottomPadding - kProgressBarHeight),
        kProgressBarWidth,
        kProgressBarHeight);
  }
  if (shutdown_button_) {
    shutdown_button_->LayoutIn(this);
  }
  if (background_area_)
    background_area_->SetBounds(this->bounds());
}

void BackgroundView::ChildPreferredSizeChanged(View* child) {
  Layout();
  SchedulePaint();
}

gfx::NativeWindow BackgroundView::GetNativeWindow() const {
  return
      GTK_WINDOW(static_cast<WidgetGtk*>(GetWidget())->GetNativeView());
}

bool BackgroundView::ShouldOpenButtonOptions(
    const views::View* button_view) const {
  if (button_view == status_area_->network_view()) {
    return true;
  }
  if (button_view == status_area_->clock_view() ||
      button_view == status_area_->input_method_view()) {
    return false;
  }
  return true;
}

void BackgroundView::OpenButtonOptions(const views::View* button_view) {
  if (button_view == status_area_->network_view()) {
    if (proxy_settings_dialog_.get() == NULL) {
      proxy_settings_dialog_.reset(new ProxySettingsDialog(
          this, GetNativeWindow()));
    }
    proxy_settings_dialog_->Show();
  }
}

bool BackgroundView::IsBrowserMode() const {
  return false;
}

bool BackgroundView::IsScreenLockerMode() const {
  return false;
}

// Overridden from LoginHtmlDialog::Delegate:
void BackgroundView::OnLocaleChanged() {
  // Proxy settings dialog contains localized strings.
  proxy_settings_dialog_.reset();
}

///////////////////////////////////////////////////////////////////////////////
// BackgroundView private:

void BackgroundView::InitStatusArea() {
  DCHECK(status_area_ == NULL);
  status_area_ = new StatusAreaView(this);
  status_area_->Init();
  AddChildView(status_area_);
}

void BackgroundView::InitInfoLabels() {
  ResourceBundle& rb = ResourceBundle::GetSharedInstance();

  os_version_label_ = new views::Label();
  os_version_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  os_version_label_->SetColor(kVersionColor);
  os_version_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
  AddChildView(os_version_label_);
  if (!is_official_build_) {
    boot_times_label_ = new views::Label();
    boot_times_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
    boot_times_label_->SetColor(kVersionColor);
    boot_times_label_->SetFont(rb.GetFont(ResourceBundle::SmallFont));
    AddChildView(boot_times_label_);
  }

  if (CrosLibrary::Get()->EnsureLoaded()) {
    version_loader_.GetVersion(
        &version_consumer_,
        NewCallback(this, &BackgroundView::OnVersion),
        is_official_build_?
            VersionLoader::VERSION_SHORT_WITH_DATE :
            VersionLoader::VERSION_FULL);
    if (!is_official_build_) {
      boot_times_loader_.GetBootTimes(
          &boot_times_consumer_,
          NewCallback(this, &BackgroundView::OnBootTimes));
    }
  } else {
    os_version_label_->SetText(
        ASCIIToWide(CrosLibrary::Get()->load_error_string()));
  }
}

void BackgroundView::InitProgressBar() {
  std::vector<int> steps;
  steps.push_back(GetStepId(SELECT_NETWORK));
#if defined(OFFICIAL_BUILD)
  steps.push_back(GetStepId(EULA));
#endif
  steps.push_back(GetStepId(SIGNIN));
#if defined(OFFICIAL_BUILD)
  if (WizardController::IsRegisterScreenDefined())
    steps.push_back(GetStepId(REGISTRATION));
#endif
  steps.push_back(GetStepId(PICTURE));
  progress_bar_ = new OobeProgressBar(steps);
  AddChildView(progress_bar_);
}

void BackgroundView::UpdateWindowType() {
  std::vector<int> params;
  params.push_back(did_paint_ ? 1 : 0);
  WmIpc::instance()->SetWindowType(
      GTK_WIDGET(GetNativeWindow()),
      WM_IPC_WINDOW_LOGIN_BACKGROUND,
      &params);
}

void BackgroundView::OnVersion(
    VersionLoader::Handle handle, std::string version) {
  // TODO(jungshik): Is string concatenation OK here?
  std::string version_text = l10n_util::GetStringUTF8(IDS_PRODUCT_OS_NAME);
  version_text += ' ';
  version_text += l10n_util::GetStringUTF8(IDS_VERSION_FIELD_PREFIX);
  version_text += ' ';
  version_text += version;

  // Workaround over incorrect width calculation in old fonts.
  // TODO(glotov): remove the following line when new fonts are used.
  version_text += ' ';
  os_version_label_->SetText(UTF8ToWide(version_text));
}

void BackgroundView::OnBootTimes(
    BootTimesLoader::Handle handle, BootTimesLoader::BootTimes boot_times) {
  const char* kBootTimesNoChromeExec =
      "Boot took %.2f seconds (firmware %.2fs, kernel %.2fs, system %.2fs)";
  const char* kBootTimesChromeExec =
      "Boot took %.2f seconds "
      "(firmware %.2fs, kernel %.2fs, system %.2fs, chrome %.2fs)";
  std::string boot_times_text;

  if (boot_times.chrome > 0) {
    boot_times_text =
        base::StringPrintf(
            kBootTimesChromeExec,
            boot_times.total,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.system,
            boot_times.chrome);
  } else {
    boot_times_text =
        base::StringPrintf(
            kBootTimesNoChromeExec,
            boot_times.total,
            boot_times.firmware,
            boot_times.pre_startup,
            boot_times.system);
  }
  // Use UTF8ToWide once this string is localized.
  boot_times_label_->SetText(ASCIIToWide(boot_times_text));
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// @(#)root/reflex:$Name:  $:$Id: NameLookup.cxx,v 1.7 2006/08/03 16:49:21 roiser Exp $
// Author: Stefan Roiser 2006

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "NameLookup.h"
#include "Reflex/Base.h"
#include "Reflex/Scope.h"
#include "Reflex/Type.h"
#include "Reflex/Tools.h"
#include "Reflex/internal/OwnedMember.h"

//-------------------------------------------------------------------------------
ROOT::Reflex::NameLookup::NameLookup(const std::string& name, const Scope& current):
   fCurrentScope(current), fLookupName(name), fPartialSuccess(false),
   fPosNamePart(0), fPosNamePartLen(std::string::npos) {
   // Initialize a NameLookup object used internally to keep track of lookup
   // states.
   }
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupType( const std::string & nam,
                                      const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup up a (possibly scoped) type name appearing in the scope context
// current. This is the public interface for type lookup.
   NameLookup lookup(nam, current);
   return lookup.LookupType();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupType() {
//-------------------------------------------------------------------------------
// Lookup a type using fLookupName, fCurrentScope.
   fPartialSuccess = false;
   fPosNamePart = 0;
   fPosNamePartLen = std::string::npos;
   FindNextScopePos();

   if ( fPosNamePart == 2 ) {
      fLookedAtUsingDir.clear();
      // ::A...
      fCurrentScope = Scope::GlobalScope();
      return LookupTypeInScope();
   } else
      // A...
      return LookupTypeInUnknownScope();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupTypeInScope() {
//-------------------------------------------------------------------------------
// Lookup a type in fCurrentScope.
// Checks sub-types, sub-scopes, using directives, and base classes for
// the name given by fLookupName, fPosNamePart, and fPosNamePartLen.
// If the name part is found, and another name part follows in fPosNamePart,
// LookupTypeInScope requests the scope found to lookup the next name
// part. fPartialMatch reflexts that the left part of the name was matched;
// even if the trailing part of fLookupName cannot be found, the lookup
// cannot continue on declaring scopes and has to fail.
// A list of lookups performed in namespaces pulled in via using directives is
// kept in fLookedAtUsingDir, to prevent infinite loops due to
//   namespace A{using namespace B;} namespace B{using namespace A;}
// loops.
// The lookup does not take the declaration order into account; the result of
// parts of the lookup algorithm which depend on the order will be unpredictable.

   if (!fCurrentScope) return Dummy::Type();
   if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end())
      // prevent inf loop from
      // ns A { using ns B; } ns B {using ns A;}
      return Dummy::Type();

   for ( Type_Iterator it = fCurrentScope.SubType_Begin(); it != fCurrentScope.SubType_End(); ++it ) {
      if ( 0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*it).Name() ) ) {
         fPartialSuccess = true;
         fLookedAtUsingDir.clear();
         FindNextScopePos();
         if (fPosNamePart == std::string::npos) return *it;
         if (it->IsTypedef()) fCurrentScope = it->FinalType();
         else fCurrentScope = *it;
         return LookupTypeInScope();
      }
   }

   for ( Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != fCurrentScope.SubScope_End(); ++in ) {
      // only take namespaces into account - classes were checked as part of SubType
      if (in->IsNamespace() &&
         0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*in).Name() ) ) {
         fPartialSuccess = true;
         fLookedAtUsingDir.clear();
         FindNextScopePos();
         if (fPosNamePart == std::string::npos) return Dummy::Type(); // namespace is no a type
         return LookupTypeInScope();
      }
   }

   if (fCurrentScope.UsingDirectiveSize()) {
      fLookedAtUsingDir.insert(fCurrentScope);
      Scope storeCurrentScope = fCurrentScope;
      for ( Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != storeCurrentScope.UsingDirective_End(); ++si ) {
         fCurrentScope = *si;
         const Type & t = LookupTypeInScope();
         if (fPartialSuccess) return t;
      }
      fCurrentScope = storeCurrentScope;
   }

   if (fPosNamePart == 0) // only for "BaseClass...", not for "A::BaseClass..."
      for ( Base_Iterator bi = fCurrentScope.Base_Begin(); bi != fCurrentScope.Base_End(); ++bi ) {
         if ( 0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*bi).Name() ) ) {
            fPartialSuccess = true;
            fLookedAtUsingDir.clear();
            FindNextScopePos();
            if (fPosNamePart == std::string::npos) return bi->ToType();
            fCurrentScope = bi->ToType().FinalType();
            return LookupTypeInScope();
         }
      }

   if (fCurrentScope.BaseSize()) {
      Scope storeCurrentScope = fCurrentScope;
      for ( Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != storeCurrentScope.Base_End(); ++bi ) {
         fCurrentScope = bi->ToScope();
         const Type & t = LookupTypeInScope();
         if ( fPartialSuccess) return t;
      }
      fCurrentScope = storeCurrentScope;
   }

   return Dummy::Type();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupTypeInUnknownScope() {
//-------------------------------------------------------------------------------
// Lookup a type in fCurrentScope and its declaring scopes.
   for (fPartialSuccess = false; !fPartialSuccess; fCurrentScope = fCurrentScope.DeclaringScope()) {
      fLookedAtUsingDir.clear();
      const Type & t = LookupTypeInScope();
      if (fPartialSuccess) return t;
      if (fCurrentScope.IsTopScope()) break;
   }
   return Dummy::Type();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMember( const std::string & nam,
                                        const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup a member.
   if ( Tools::GetBasePosition(nam)) return LookupMemberQualified( nam );
   else                              return LookupMemberUnqualified( nam, current );

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMemberQualified( const std::string & nam ) {
//-------------------------------------------------------------------------------
// Lookup of a qualified member.
   const Scope & bscope = Scope::ByName(Tools::GetScopeName(nam));
   if ( bscope ) {
      return LookupMemberUnqualified( Tools::GetBaseName(nam), bscope);
   }
   else {
      return Dummy::Member();
   }

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMemberUnqualified( const std::string & nam,
                                                   const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup of an unqualified member.
   const Member & m0 = current.MemberByName(nam);
   if ( m0 ) return m0;

   for ( Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si ) {
      const Member & m1 = LookupMember( nam, *si );
      if ( m1 ) return m1;
   }

   for ( Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++ bi ) {
      const Member & m2 = LookupMember( nam, bi->ToScope() );
      if ( m2 ) return m2;
   }

   if ( ! current.IsTopScope() ) return LookupMember( nam, current.DeclaringScope() );

   return Dummy::Member();

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type & ROOT::Reflex::NameLookup::AccessControl( const Type & typ,
                                                                    const Scope & /* current */ ) {
//-------------------------------------------------------------------------------
// Check access .

   //if ( typ.IsPublic()) return true;

   //else if ( typ.IsProtected() && current.HasBase(typ.DeclaringScope()) ) return true;

   return typ;

}

//-------------------------------------------------------------------------------
void
ROOT::Reflex::NameLookup::FindNextScopePos() {
//-------------------------------------------------------------------------------
// Move fPosNamePart to point to the next scope in fLookupName, updating
// fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize
// fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart
// will be set to std::string::npos and fPosNamePartLen will be set to 0.
   if (fPosNamePartLen != std::string::npos) {
      // we know the length, so jump
      fPosNamePart += fPosNamePartLen + 2;
      if (fPosNamePart > fLookupName.length()) {
         // past the string's end?
         fPosNamePart = std::string::npos;
         fPosNamePartLen = 0;
         return;
      }
   }
   else {
      // uninitialized
      // set fPosNamePartLen and check that fLookupName doesn't start with '::'
      if (fLookupName.compare(0, 2, "::") == 0)
         fPosNamePart = 2;
      else fPosNamePart = 0;
   }
   fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart));
   if (fPosNamePartLen == 0)
      // no next "::"
      fPosNamePartLen = fLookupName.length();
   else fPosNamePartLen -= 2; // no "::"
   // fPosNamePartLen -= fPosNamePart; No! We already look in substr()
}
<commit_msg>Stop type lookup in decl scope if !decl scope<commit_after>// @(#)root/reflex:$Name:  $:$Id: NameLookup.cxx,v 1.8 2006/08/07 14:20:07 axel Exp $
// Author: Stefan Roiser 2006

// Copyright CERN, CH-1211 Geneva 23, 2004-2006, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
#define REFLEX_BUILD
#endif

#include "NameLookup.h"
#include "Reflex/Base.h"
#include "Reflex/Scope.h"
#include "Reflex/Type.h"
#include "Reflex/Tools.h"
#include "Reflex/internal/OwnedMember.h"

//-------------------------------------------------------------------------------
ROOT::Reflex::NameLookup::NameLookup(const std::string& name, const Scope& current):
   fCurrentScope(current), fLookupName(name), fPartialSuccess(false),
   fPosNamePart(0), fPosNamePartLen(std::string::npos) {
   // Initialize a NameLookup object used internally to keep track of lookup
   // states.
   }
//-------------------------------------------------------------------------------

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupType( const std::string & nam,
                                      const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup up a (possibly scoped) type name appearing in the scope context
// current. This is the public interface for type lookup.
   NameLookup lookup(nam, current);
   return lookup.LookupType();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupType() {
//-------------------------------------------------------------------------------
// Lookup a type using fLookupName, fCurrentScope.
   fPartialSuccess = false;
   fPosNamePart = 0;
   fPosNamePartLen = std::string::npos;
   FindNextScopePos();

   if ( fPosNamePart == 2 ) {
      fLookedAtUsingDir.clear();
      // ::A...
      fCurrentScope = Scope::GlobalScope();
      return LookupTypeInScope();
   } else
      // A...
      return LookupTypeInUnknownScope();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupTypeInScope() {
//-------------------------------------------------------------------------------
// Lookup a type in fCurrentScope.
// Checks sub-types, sub-scopes, using directives, and base classes for
// the name given by fLookupName, fPosNamePart, and fPosNamePartLen.
// If the name part is found, and another name part follows in fPosNamePart,
// LookupTypeInScope requests the scope found to lookup the next name
// part. fPartialMatch reflexts that the left part of the name was matched;
// even if the trailing part of fLookupName cannot be found, the lookup
// cannot continue on declaring scopes and has to fail.
// A list of lookups performed in namespaces pulled in via using directives is
// kept in fLookedAtUsingDir, to prevent infinite loops due to
//   namespace A{using namespace B;} namespace B{using namespace A;}
// loops.
// The lookup does not take the declaration order into account; the result of
// parts of the lookup algorithm which depend on the order will be unpredictable.

   if (!fCurrentScope) return Dummy::Type();
   if (fLookedAtUsingDir.find(fCurrentScope) != fLookedAtUsingDir.end())
      // prevent inf loop from
      // ns A { using ns B; } ns B {using ns A;}
      return Dummy::Type();

   for ( Type_Iterator it = fCurrentScope.SubType_Begin(); it != fCurrentScope.SubType_End(); ++it ) {
      if ( 0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*it).Name() ) ) {
         fPartialSuccess = true;
         fLookedAtUsingDir.clear();
         FindNextScopePos();
         if (fPosNamePart == std::string::npos) return *it;
         if (it->IsTypedef()) fCurrentScope = it->FinalType();
         else fCurrentScope = *it;
         return LookupTypeInScope();
      }
   }

   for ( Scope_Iterator in = fCurrentScope.SubScope_Begin(); in != fCurrentScope.SubScope_End(); ++in ) {
      // only take namespaces into account - classes were checked as part of SubType
      if (in->IsNamespace() &&
         0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*in).Name() ) ) {
         fPartialSuccess = true;
         fLookedAtUsingDir.clear();
         FindNextScopePos();
         if (fPosNamePart == std::string::npos) return Dummy::Type(); // namespace is no a type
         return LookupTypeInScope();
      }
   }

   if (fCurrentScope.UsingDirectiveSize()) {
      fLookedAtUsingDir.insert(fCurrentScope);
      Scope storeCurrentScope = fCurrentScope;
      for ( Scope_Iterator si = storeCurrentScope.UsingDirective_Begin(); si != storeCurrentScope.UsingDirective_End(); ++si ) {
         fCurrentScope = *si;
         const Type & t = LookupTypeInScope();
         if (fPartialSuccess) return t;
      }
      fCurrentScope = storeCurrentScope;
   }

   if (fPosNamePart == 0) // only for "BaseClass...", not for "A::BaseClass..."
      for ( Base_Iterator bi = fCurrentScope.Base_Begin(); bi != fCurrentScope.Base_End(); ++bi ) {
         if ( 0 == fLookupName.compare(fPosNamePart, fPosNamePartLen, (*bi).Name() ) ) {
            fPartialSuccess = true;
            fLookedAtUsingDir.clear();
            FindNextScopePos();
            if (fPosNamePart == std::string::npos) return bi->ToType();
            fCurrentScope = bi->ToType().FinalType();
            return LookupTypeInScope();
         }
      }

   if (fCurrentScope.BaseSize()) {
      Scope storeCurrentScope = fCurrentScope;
      for ( Base_Iterator bi = storeCurrentScope.Base_Begin(); bi != storeCurrentScope.Base_End(); ++bi ) {
         fCurrentScope = bi->ToScope();
         const Type & t = LookupTypeInScope();
         if ( fPartialSuccess) return t;
      }
      fCurrentScope = storeCurrentScope;
   }

   return Dummy::Type();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type &
ROOT::Reflex::NameLookup::LookupTypeInUnknownScope() {
//-------------------------------------------------------------------------------
// Lookup a type in fCurrentScope and its declaring scopes.
   for (fPartialSuccess = false; !fPartialSuccess && fCurrentScope; fCurrentScope = fCurrentScope.DeclaringScope()) {
      fLookedAtUsingDir.clear();
      const Type & t = LookupTypeInScope();
      if (fPartialSuccess) return t;
      if (fCurrentScope.IsTopScope()) break;
   }
   return Dummy::Type();
}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMember( const std::string & nam,
                                        const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup a member.
   if ( Tools::GetBasePosition(nam)) return LookupMemberQualified( nam );
   else                              return LookupMemberUnqualified( nam, current );

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMemberQualified( const std::string & nam ) {
//-------------------------------------------------------------------------------
// Lookup of a qualified member.
   const Scope & bscope = Scope::ByName(Tools::GetScopeName(nam));
   if ( bscope ) {
      return LookupMemberUnqualified( Tools::GetBaseName(nam), bscope);
   }
   else {
      return Dummy::Member();
   }

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Member &
ROOT::Reflex::NameLookup::LookupMemberUnqualified( const std::string & nam,
                                                   const Scope & current ) {
//-------------------------------------------------------------------------------
// Lookup of an unqualified member.
   const Member & m0 = current.MemberByName(nam);
   if ( m0 ) return m0;

   for ( Scope_Iterator si = current.UsingDirective_Begin(); si != current.UsingDirective_End(); ++si ) {
      const Member & m1 = LookupMember( nam, *si );
      if ( m1 ) return m1;
   }

   for ( Base_Iterator bi = current.Base_Begin(); bi != current.Base_End(); ++ bi ) {
      const Member & m2 = LookupMember( nam, bi->ToScope() );
      if ( m2 ) return m2;
   }

   if ( ! current.IsTopScope() ) return LookupMember( nam, current.DeclaringScope() );

   return Dummy::Member();

}

//-------------------------------------------------------------------------------
const ROOT::Reflex::Type & ROOT::Reflex::NameLookup::AccessControl( const Type & typ,
                                                                    const Scope & /* current */ ) {
//-------------------------------------------------------------------------------
// Check access .

   //if ( typ.IsPublic()) return true;

   //else if ( typ.IsProtected() && current.HasBase(typ.DeclaringScope()) ) return true;

   return typ;

}

//-------------------------------------------------------------------------------
void
ROOT::Reflex::NameLookup::FindNextScopePos() {
//-------------------------------------------------------------------------------
// Move fPosNamePart to point to the next scope in fLookupName, updating
// fPosNamePartLen. If fPosNamePartLen == std::string::npos, initialize
// fPosNamePart and fPosNamePartLen. If there is no next scope left, fPosNamePart
// will be set to std::string::npos and fPosNamePartLen will be set to 0.
   if (fPosNamePartLen != std::string::npos) {
      // we know the length, so jump
      fPosNamePart += fPosNamePartLen + 2;
      if (fPosNamePart > fLookupName.length()) {
         // past the string's end?
         fPosNamePart = std::string::npos;
         fPosNamePartLen = 0;
         return;
      }
   }
   else {
      // uninitialized
      // set fPosNamePartLen and check that fLookupName doesn't start with '::'
      if (fLookupName.compare(0, 2, "::") == 0)
         fPosNamePart = 2;
      else fPosNamePart = 0;
   }
   fPosNamePartLen = Tools::GetFirstScopePosition(fLookupName.substr(fPosNamePart));
   if (fPosNamePartLen == 0)
      // no next "::"
      fPosNamePartLen = fLookupName.length();
   else fPosNamePartLen -= 2; // no "::"
   // fPosNamePartLen -= fPosNamePart; No! We already look in substr()
}
<|endoftext|>