<commit_before>#include <itomp_cio_planner/optimization/phase_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>

namespace itomp_cio_planner
{

PhaseManager::PhaseManager()
    : phase_(0), num_points_(0)
{
    support_foot_ = 0; // any
    agent_id_ = 0;
}

PhaseManager::~PhaseManager()
{

}

void PhaseManager::init(int num_points)
{
    num_points_ = num_points;
}

bool PhaseManager::updateParameter(const ItompTrajectoryIndex& index) const
{
    int state = (int)(PlanningParameters::getInstance()->getTemporaryVariable(0) + 0.0001);

    switch(state)
    {
    case 0: // standing up
    {
        // no contact force from foot
        if (index.point == 0)
        {
            if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE)
            {
                if (index.element < 24)
                    return false;
            }
        }

        // fix only root_x, root_y
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT &&
                (index.point == 0 || index.point == num_points_ - 1) &&
                (index.element < 2))
            return false;
    }
    break;

    case 1: // side walking
    case 2:
        break;

    case 3: // luggage turn right
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;

        // overhead bin_rotating
        if (getPhase() != 0 && index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE &&
                index.point > 0 && index.point < 20 &&
                index.element >= 12 && index.element < 24) // turn right
            //index.element < 12) // turn left
            return false;

        break;

    case 4: // luggage turn left
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;

        // overhead bin_rotating
        if (getPhase() != 0 && index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE &&
                index.point > 0 && index.point < 20 &&
                //index.element >= 12 && index.element < 24) // turn right
                index.element < 12) // turn left
            return false;

        break;

    case 5: // luggage
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;
        break;

    case 10: // walking
        // Do not update joint values of start/goal points
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT &&
                (index.point == 0 || index.point == num_points_ - 1))
            return false;

    case 20: // SCA two-footstep planning

        if (getPhase() == 0 && (index.point != 0 && index.point != num_points_ - 1))
            return false;

        if (getPhase() != 0)
        {
            if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_POSITION)
            {
                if (index.point == 0 || index.point == num_points_ - 1)
                    return false;
            }
            else if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE)
            {
                //if (index.element % 3 != 2)
                  //  return false;

                int parameter_point = index.point / 5;
                if (parameter_point % 4 != 0)
                {
                    if (4 < parameter_point) // left contact
                    {
                        if (support_foot_ & 0x1) // left foot can be support foot
                        {
                            if (index.element < 12)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            if (index.element >= 12 && index.element < 24)
                            {
                                return false;
                            }
                        }
                    }
                    else // right contact
                    {
                        if (support_foot_ & 0x1)
                        {
                            if (index.element >= 12 && index.element < 24)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            if (index.element < 12)
                            {
                                return false;
                            }
                        }
                    }
                }
            }
        }

        break;
    }

    if (state != 0)
    {
        if (PhaseManager::getInstance()->getPhase() == 0 &&
                (index.point == 0 || (index.point == num_points_ - 1 && index.element >= 3)) &&
                index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT)
            return false;

        if (PhaseManager::getInstance()->getPhase() != 0 &&
                (index.point == 0 || index.point == num_points_ - 1) &&
                index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT)
            return false;
    }

    return true;
}

}
<commit_msg>optimize goal state in phase 2<commit_after>#include <itomp_cio_planner/optimization/phase_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>

namespace itomp_cio_planner
{

PhaseManager::PhaseManager()
    : phase_(0), num_points_(0)
{
    support_foot_ = 0; // any
    agent_id_ = 0;
}

PhaseManager::~PhaseManager()
{

}

void PhaseManager::init(int num_points)
{
    num_points_ = num_points;
}

bool PhaseManager::updateParameter(const ItompTrajectoryIndex& index) const
{
    int state = (int)(PlanningParameters::getInstance()->getTemporaryVariable(0) + 0.0001);

    switch(state)
    {
    case 0: // standing up
    {
        // no contact force from foot
        if (index.point == 0)
        {
            if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE)
            {
                if (index.element < 24)
                    return false;
            }
        }

        // fix only root_x, root_y
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT &&
                (index.point == 0 || index.point == num_points_ - 1) &&
                (index.element < 2))
            return false;
    }
    break;

    case 1: // side walking
    case 2:
        break;

    case 3: // luggage turn right
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;

        // overhead bin_rotating
        if (getPhase() != 0 && index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE &&
                index.point > 0 && index.point < 20 &&
                index.element >= 12 && index.element < 24) // turn right
            //index.element < 12) // turn left
            return false;

        break;

    case 4: // luggage turn left
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;

        // overhead bin_rotating
        if (getPhase() != 0 && index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE &&
                index.point > 0 && index.point < 20 &&
                //index.element >= 12 && index.element < 24) // turn right
                index.element < 12) // turn left
            return false;

        break;

    case 5: // luggage
        // overhead bin_all
        // Do not update joint values of start/goal point
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT && (index.point == 0 || index.point == num_points_ - 1))
            return false;
        break;

    case 10: // walking
        // Do not update joint values of start/goal points
        if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT &&
                (index.point == 0 || index.point == num_points_ - 1))
            return false;

    case 20: // SCA two-footstep planning

        if (getPhase() == 0 && (index.point != 0 && index.point != num_points_ - 1))
            return false;

        if (getPhase() != 0)
        {
            if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_POSITION)
            {
                if (index.point == 0 || index.point == num_points_ - 1)
                    return false;
            }
            else if (index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_CONTACT_FORCE)
            {
                //if (index.element % 3 != 2)
                  //  return false;

                int parameter_point = index.point / 5;
                if (parameter_point % 4 != 0)
                {
                    if (4 < parameter_point) // left contact
                    {
                        if (support_foot_ & 0x1) // left foot can be support foot
                        {
                            if (index.element < 12)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            if (index.element >= 12 && index.element < 24)
                            {
                                return false;
                            }
                        }
                    }
                    else // right contact
                    {
                        if (support_foot_ & 0x1)
                        {
                            if (index.element >= 12 && index.element < 24)
                            {
                                return false;
                            }
                        }
                        else
                        {
                            if (index.element < 12)
                            {
                                return false;
                            }
                        }
                    }
                }
            }
        }

        break;
    }

    if (state != 0)
    {
        if (PhaseManager::getInstance()->getPhase() == 0 &&
                (index.point == 0 || (index.point == num_points_ - 1 && index.element >= 3)) &&
                index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT)
            return false;

        if (PhaseManager::getInstance()->getPhase() != 0 &&
                (index.point == 0 || (index.point == num_points_ - 1 && index.element < 2)) &&
                index.sub_component == ItompTrajectory::SUB_COMPONENT_TYPE_JOINT)
            return false;
    }

    return true;
}

}
<|endoftext|>


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

#include "chrome/browser/chromeos/system_access.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/observer_list.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/name_value_pairs_parser.h"

namespace chromeos {  // NOLINT

namespace { // NOLINT

// The filepath to the timezone file that symlinks to the actual timezone file.
const char kTimezoneSymlink[] = "/var/lib/timezone/localtime";
const char kTimezoneSymlink2[] = "/var/lib/timezone/localtime2";

// The directory that contains all the timezone files. So for timezone
// "US/Pacific", the actual timezone file is: "/usr/share/zoneinfo/US/Pacific"
const char kTimezoneFilesDir[] = "/usr/share/zoneinfo/";

// The system command that returns the hardware class.
const char kHardwareClassKey[] = "hardware_class";
const char* kHardwareClassTool[] = { "/usr/bin/hardware_class" };
const char kUnknownHardwareClass[] = "unknown";

// Command to get machine hardware info and key/value delimiters.
// /tmp/machine-info is generated by platform/init/chromeos_startup.
const char* kMachineHardwareInfoTool[] = { "cat", "/tmp/machine-info" };
const char kMachineHardwareInfoEq[] = "=";
const char kMachineHardwareInfoDelim[] = " \n";

// Command to get machine OS info and key/value delimiters.
const char* kMachineOSInfoTool[] = { "cat", "/etc/lsb-release" };
const char kMachineOSInfoEq[] = "=";
const char kMachineOSInfoDelim[] = "\n";

// Command to get  HWID and key.
const char kHwidKey[] = "hwid";
const char* kHwidTool[] = { "cat", "/sys/devices/platform/chromeos_acpi/HWID" };

// Command to get VPD info and key/value delimiters.
const char* kVpdTool[] = { "cat", "/var/log/vpd_2.0.txt" };
const char kVpdEq[] = "=";
const char kVpdDelim[] = "\n";

// Fallback time zone ID used in case of an unexpected error.
const char kFallbackTimeZoneId[] = "America/Los_Angeles";

class SystemAccessImpl : public SystemAccess {
 public:
  // SystemAccess.implementation:
  virtual const icu::TimeZone& GetTimezone();
  virtual void SetTimezone(const icu::TimeZone& timezone);
  virtual bool GetMachineStatistic(const std::string& name,
                                   std::string* result);
  virtual void AddObserver(Observer* observer);
  virtual void RemoveObserver(Observer* observer);

  static SystemAccessImpl* GetInstance();

 private:
  friend struct DefaultSingletonTraits<SystemAccessImpl>;

  SystemAccessImpl();

  // Updates the machine statistcs by examining the system.
  void UpdateMachineStatistics();

  scoped_ptr<icu::TimeZone> timezone_;
  ObserverList<Observer> observers_;
  NameValuePairsParser::NameValueMap machine_info_;

  DISALLOW_COPY_AND_ASSIGN(SystemAccessImpl);
};

std::string GetTimezoneIDAsString() {
  // Look at kTimezoneSymlink, see which timezone we are symlinked to.
  char buf[256];
  const ssize_t len = readlink(kTimezoneSymlink, buf,
                               sizeof(buf)-1);
  if (len == -1) {
    LOG(ERROR) << "GetTimezoneID: Cannot read timezone symlink "
               << kTimezoneSymlink;
    return std::string();
  }

  std::string timezone(buf, len);
  // Remove kTimezoneFilesDir from the beginning.
  if (timezone.find(kTimezoneFilesDir) != 0) {
    LOG(ERROR) << "GetTimezoneID: Timezone symlink is wrong "
               << timezone;
    return std::string();
  }

  return timezone.substr(strlen(kTimezoneFilesDir));
}

void SetTimezoneIDFromString(const std::string& id) {
  // Change the kTimezoneSymlink symlink to the path for this timezone.
  // We want to do this in an atomic way. So we are going to create the symlink
  // at kTimezoneSymlink2 and then move it to kTimezoneSymlink

  FilePath timezone_symlink(kTimezoneSymlink);
  FilePath timezone_symlink2(kTimezoneSymlink2);
  FilePath timezone_file(kTimezoneFilesDir + id);

  // Make sure timezone_file exists.
  if (!file_util::PathExists(timezone_file)) {
    LOG(ERROR) << "SetTimezoneID: Cannot find timezone file "
               << timezone_file.value();
    return;
  }

  // Delete old symlink2 if it exists.
  file_util::Delete(timezone_symlink2, false);

  // Create new symlink2.
  if (symlink(timezone_file.value().c_str(),
              timezone_symlink2.value().c_str()) == -1) {
    LOG(ERROR) << "SetTimezoneID: Unable to create symlink "
               << timezone_symlink2.value() << " to " << timezone_file.value();
    return;
  }

  // Move symlink2 to symlink.
  if (!file_util::ReplaceFile(timezone_symlink2, timezone_symlink)) {
    LOG(ERROR) << "SetTimezoneID: Unable to move symlink "
               << timezone_symlink2.value() << " to "
               << timezone_symlink.value();
  }
}

const icu::TimeZone& SystemAccessImpl::GetTimezone() {
  return *timezone_.get();
}

void SystemAccessImpl::SetTimezone(const icu::TimeZone& timezone) {
  timezone_.reset(timezone.clone());
  icu::UnicodeString unicode;
  timezone.getID(unicode);
  std::string id;
  UTF16ToUTF8(unicode.getBuffer(), unicode.length(), &id);
  VLOG(1) << "Setting timezone to " << id;
  chromeos::SetTimezoneIDFromString(id);
  icu::TimeZone::setDefault(timezone);
  FOR_EACH_OBSERVER(Observer, observers_, TimezoneChanged(timezone));
}

bool SystemAccessImpl::GetMachineStatistic(
    const std::string& name, std::string* result) {
  NameValuePairsParser::NameValueMap::iterator iter = machine_info_.find(name);
  if (iter != machine_info_.end()) {
    *result = iter->second;
    return true;
  }
  return false;
}

void SystemAccessImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void SystemAccessImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

SystemAccessImpl::SystemAccessImpl() {
  // Get Statistics
  UpdateMachineStatistics();
  // Get Timezone
  std::string id = GetTimezoneIDAsString();
  if (id.empty()) {
    id = kFallbackTimeZoneId;
    LOG(ERROR) << "Got an empty string for timezone, default to " << id;
  }
  icu::TimeZone* timezone =
      icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(id));
  timezone_.reset(timezone);
  icu::TimeZone::setDefault(*timezone);
  VLOG(1) << "Timezone is " << id;
}

void SystemAccessImpl::UpdateMachineStatistics() {
  NameValuePairsParser parser(&machine_info_);
  if (!parser.GetSingleValueFromTool(arraysize(kHardwareClassTool),
                                     kHardwareClassTool,
                                     kHardwareClassKey)) {
    // Use kUnknownHardwareClass if the hardware class command fails.
    parser.AddNameValuePair(kHardwareClassKey, kUnknownHardwareClass);
  }
  parser.ParseNameValuePairsFromTool(arraysize(kMachineHardwareInfoTool),
                                     kMachineHardwareInfoTool,
                                     kMachineHardwareInfoEq,
                                     kMachineHardwareInfoDelim);
  parser.ParseNameValuePairsFromTool(arraysize(kMachineOSInfoTool),
                                     kMachineOSInfoTool,
                                     kMachineOSInfoEq,
                                     kMachineOSInfoDelim);
  parser.GetSingleValueFromTool(arraysize(kHwidTool), kHwidTool, kHwidKey);
  parser.ParseNameValuePairsFromTool(
      arraysize(kVpdTool), kVpdTool, kVpdEq, kVpdDelim);
}

SystemAccessImpl* SystemAccessImpl::GetInstance() {
  return Singleton<SystemAccessImpl,
                   DefaultSingletonTraits<SystemAccessImpl> >::get();
}

}  // namespace

SystemAccess* SystemAccess::GetInstance() {
  return SystemAccessImpl::GetInstance();
}

}  // namespace chromeos
<commit_msg>Use 'crossystem hwid' to obtain the HWID (hardware_class).<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/system_access.h"

#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/observer_list.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/name_value_pairs_parser.h"

namespace chromeos {  // NOLINT

namespace { // NOLINT

// The filepath to the timezone file that symlinks to the actual timezone file.
const char kTimezoneSymlink[] = "/var/lib/timezone/localtime";
const char kTimezoneSymlink2[] = "/var/lib/timezone/localtime2";

// The directory that contains all the timezone files. So for timezone
// "US/Pacific", the actual timezone file is: "/usr/share/zoneinfo/US/Pacific"
const char kTimezoneFilesDir[] = "/usr/share/zoneinfo/";

// The system command that returns the hardware class.
const char kHardwareClassKey[] = "hardware_class";
const char* kHardwareClassTool[] = { "crossystem", "hwid" };
const char kUnknownHardwareClass[] = "unknown";

// Command to get machine hardware info and key/value delimiters.
// /tmp/machine-info is generated by platform/init/chromeos_startup.
const char* kMachineHardwareInfoTool[] = { "cat", "/tmp/machine-info" };
const char kMachineHardwareInfoEq[] = "=";
const char kMachineHardwareInfoDelim[] = " \n";

// Command to get machine OS info and key/value delimiters.
const char* kMachineOSInfoTool[] = { "cat", "/etc/lsb-release" };
const char kMachineOSInfoEq[] = "=";
const char kMachineOSInfoDelim[] = "\n";

// Command to get  HWID and key.
const char kHwidKey[] = "hwid";
const char* kHwidTool[] = { "cat", "/sys/devices/platform/chromeos_acpi/HWID" };

// Command to get VPD info and key/value delimiters.
const char* kVpdTool[] = { "cat", "/var/log/vpd_2.0.txt" };
const char kVpdEq[] = "=";
const char kVpdDelim[] = "\n";

// Fallback time zone ID used in case of an unexpected error.
const char kFallbackTimeZoneId[] = "America/Los_Angeles";

class SystemAccessImpl : public SystemAccess {
 public:
  // SystemAccess.implementation:
  virtual const icu::TimeZone& GetTimezone();
  virtual void SetTimezone(const icu::TimeZone& timezone);
  virtual bool GetMachineStatistic(const std::string& name,
                                   std::string* result);
  virtual void AddObserver(Observer* observer);
  virtual void RemoveObserver(Observer* observer);

  static SystemAccessImpl* GetInstance();

 private:
  friend struct DefaultSingletonTraits<SystemAccessImpl>;

  SystemAccessImpl();

  // Updates the machine statistcs by examining the system.
  void UpdateMachineStatistics();

  scoped_ptr<icu::TimeZone> timezone_;
  ObserverList<Observer> observers_;
  NameValuePairsParser::NameValueMap machine_info_;

  DISALLOW_COPY_AND_ASSIGN(SystemAccessImpl);
};

std::string GetTimezoneIDAsString() {
  // Look at kTimezoneSymlink, see which timezone we are symlinked to.
  char buf[256];
  const ssize_t len = readlink(kTimezoneSymlink, buf,
                               sizeof(buf)-1);
  if (len == -1) {
    LOG(ERROR) << "GetTimezoneID: Cannot read timezone symlink "
               << kTimezoneSymlink;
    return std::string();
  }

  std::string timezone(buf, len);
  // Remove kTimezoneFilesDir from the beginning.
  if (timezone.find(kTimezoneFilesDir) != 0) {
    LOG(ERROR) << "GetTimezoneID: Timezone symlink is wrong "
               << timezone;
    return std::string();
  }

  return timezone.substr(strlen(kTimezoneFilesDir));
}

void SetTimezoneIDFromString(const std::string& id) {
  // Change the kTimezoneSymlink symlink to the path for this timezone.
  // We want to do this in an atomic way. So we are going to create the symlink
  // at kTimezoneSymlink2 and then move it to kTimezoneSymlink

  FilePath timezone_symlink(kTimezoneSymlink);
  FilePath timezone_symlink2(kTimezoneSymlink2);
  FilePath timezone_file(kTimezoneFilesDir + id);

  // Make sure timezone_file exists.
  if (!file_util::PathExists(timezone_file)) {
    LOG(ERROR) << "SetTimezoneID: Cannot find timezone file "
               << timezone_file.value();
    return;
  }

  // Delete old symlink2 if it exists.
  file_util::Delete(timezone_symlink2, false);

  // Create new symlink2.
  if (symlink(timezone_file.value().c_str(),
              timezone_symlink2.value().c_str()) == -1) {
    LOG(ERROR) << "SetTimezoneID: Unable to create symlink "
               << timezone_symlink2.value() << " to " << timezone_file.value();
    return;
  }

  // Move symlink2 to symlink.
  if (!file_util::ReplaceFile(timezone_symlink2, timezone_symlink)) {
    LOG(ERROR) << "SetTimezoneID: Unable to move symlink "
               << timezone_symlink2.value() << " to "
               << timezone_symlink.value();
  }
}

const icu::TimeZone& SystemAccessImpl::GetTimezone() {
  return *timezone_.get();
}

void SystemAccessImpl::SetTimezone(const icu::TimeZone& timezone) {
  timezone_.reset(timezone.clone());
  icu::UnicodeString unicode;
  timezone.getID(unicode);
  std::string id;
  UTF16ToUTF8(unicode.getBuffer(), unicode.length(), &id);
  VLOG(1) << "Setting timezone to " << id;
  chromeos::SetTimezoneIDFromString(id);
  icu::TimeZone::setDefault(timezone);
  FOR_EACH_OBSERVER(Observer, observers_, TimezoneChanged(timezone));
}

bool SystemAccessImpl::GetMachineStatistic(
    const std::string& name, std::string* result) {
  NameValuePairsParser::NameValueMap::iterator iter = machine_info_.find(name);
  if (iter != machine_info_.end()) {
    *result = iter->second;
    return true;
  }
  return false;
}

void SystemAccessImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void SystemAccessImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

SystemAccessImpl::SystemAccessImpl() {
  // Get Statistics
  UpdateMachineStatistics();
  // Get Timezone
  std::string id = GetTimezoneIDAsString();
  if (id.empty()) {
    id = kFallbackTimeZoneId;
    LOG(ERROR) << "Got an empty string for timezone, default to " << id;
  }
  icu::TimeZone* timezone =
      icu::TimeZone::createTimeZone(icu::UnicodeString::fromUTF8(id));
  timezone_.reset(timezone);
  icu::TimeZone::setDefault(*timezone);
  VLOG(1) << "Timezone is " << id;
}

void SystemAccessImpl::UpdateMachineStatistics() {
  NameValuePairsParser parser(&machine_info_);
  if (!parser.GetSingleValueFromTool(arraysize(kHardwareClassTool),
                                     kHardwareClassTool,
                                     kHardwareClassKey)) {
    // Use kUnknownHardwareClass if the hardware class command fails.
    parser.AddNameValuePair(kHardwareClassKey, kUnknownHardwareClass);
  }
  parser.ParseNameValuePairsFromTool(arraysize(kMachineHardwareInfoTool),
                                     kMachineHardwareInfoTool,
                                     kMachineHardwareInfoEq,
                                     kMachineHardwareInfoDelim);
  parser.ParseNameValuePairsFromTool(arraysize(kMachineOSInfoTool),
                                     kMachineOSInfoTool,
                                     kMachineOSInfoEq,
                                     kMachineOSInfoDelim);
  parser.GetSingleValueFromTool(arraysize(kHwidTool), kHwidTool, kHwidKey);
  parser.ParseNameValuePairsFromTool(
      arraysize(kVpdTool), kVpdTool, kVpdEq, kVpdDelim);
}

SystemAccessImpl* SystemAccessImpl::GetInstance() {
  return Singleton<SystemAccessImpl,
                   DefaultSingletonTraits<SystemAccessImpl> >::get();
}

}  // namespace

SystemAccess* SystemAccess::GetInstance() {
  return SystemAccessImpl::GetInstance();
}

}  // namespace chromeos
<|endoftext|>


<commit_before><commit_msg>Attempt 2 at landing this. This fixes the incognito mode ui test failures.<commit_after><|endoftext|>


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

#include "chrome/browser/gtk/bookmark_utils_gtk.h"

#include "app/gtk_dnd_util.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/gfx/gtk_util.h"
#include "base/pickle.h"
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"

namespace {

// Used in gtk_selection_data_set(). (I assume from this parameter that gtk has
// to some really exotic hardware...)
const int kBitsInAByte = 8;

// Maximum number of characters on a bookmark button.
const size_t kMaxCharsOnAButton = 15;

// Max size of each component of the button tooltips.
const size_t kMaxTooltipTitleLength = 100;
const size_t kMaxTooltipURLLength = 400;

// Only used for the background of the drag widget.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4);

// Padding between the chrome button highlight border and the contents (favicon,
// text).
// TODO(estade): we need to adjust the top and bottom padding, but first we need
// to give the bookmark bar more space (at the expense of the toolbar).
const int kButtonPaddingTop = 0;
const int kButtonPaddingBottom = 0;
const int kButtonPaddingLeft = 2;
const int kButtonPaddingRight = 0;

void* AsVoid(const BookmarkNode* node) {
  return const_cast<BookmarkNode*>(node);
}

}  // namespace

namespace bookmark_utils {

const char kBookmarkNode[] = "bookmark-node";

// Spacing between the buttons on the bar.
const int kBarButtonPadding = 4;

GdkPixbuf* GetPixbufForNode(const BookmarkNode* node, BookmarkModel* model,
                            bool native) {
  GdkPixbuf* pixbuf;

  if (node->is_url()) {
    if (model->GetFavIcon(node).width() != 0) {
      pixbuf = gfx::GdkPixbufFromSkBitmap(&model->GetFavIcon(node));
    } else {
      pixbuf = GtkThemeProvider::GetDefaultFavicon(native);
      g_object_ref(pixbuf);
    }
  } else {
    pixbuf = GtkThemeProvider::GetFolderIcon(native);
    g_object_ref(pixbuf);
  }

  return pixbuf;
}

GtkWidget* GetDragRepresentation(const BookmarkNode* node,
                                 BookmarkModel* model,
                                 GtkThemeProvider* provider) {
  // Build a windowed representation for our button.
  GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
  if (!provider->UseGtkTheme()) {
    // TODO(erg): Theme wise, which color should I be picking here?
    // COLOR_BUTTON_BACKGROUND doesn't match the default theme!
    gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &kBackgroundColor);
  }
  gtk_widget_realize(window);

  GtkWidget* frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
  gtk_container_add(GTK_CONTAINER(window), frame);
  gtk_widget_show(frame);

  GtkWidget* floating_button = provider->BuildChromeButton();
  bookmark_utils::ConfigureButtonForNode(node, model, floating_button,
                                         provider);
  gtk_container_add(GTK_CONTAINER(frame), floating_button);
  gtk_widget_show(floating_button);

  return window;
}

void ConfigureButtonForNode(const BookmarkNode* node, BookmarkModel* model,
                            GtkWidget* button, GtkThemeProvider* provider) {
  GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));
  if (former_child)
    gtk_container_remove(GTK_CONTAINER(button), former_child);

  std::string tooltip = BuildTooltipFor(node);
  if (!tooltip.empty())
    gtk_widget_set_tooltip_markup(button, tooltip.c_str());

  // We pack the button manually (rather than using gtk_button_set_*) so that
  // we can have finer control over its label.
  GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model,
                                                       provider->UseGtkTheme());
  GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
  g_object_unref(pixbuf);

  GtkWidget* box = gtk_hbox_new(FALSE, kBarButtonPadding);
  gtk_box_pack_start(GTK_BOX(box), image, FALSE, FALSE, 0);

  std::string label_string = WideToUTF8(node->GetTitle());
  if (!label_string.empty()) {
    GtkWidget* label = gtk_label_new(label_string.c_str());
    gtk_label_set_max_width_chars(GTK_LABEL(label), kMaxCharsOnAButton);
    gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END);
    gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);
    SetButtonTextColors(label, provider);
  }

  GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
  // If we are not showing the label, don't set any padding, so that the icon
  // will just be centered.
  if (label_string.c_str()) {
    gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),
        kButtonPaddingTop, kButtonPaddingBottom,
        kButtonPaddingLeft, kButtonPaddingRight);
  }
  gtk_container_add(GTK_CONTAINER(alignment), box);
  gtk_container_add(GTK_CONTAINER(button), alignment);

  g_object_set_data(G_OBJECT(button), bookmark_utils::kBookmarkNode,
                    AsVoid(node));

  gtk_widget_show_all(alignment);
}

std::string BuildTooltipFor(const BookmarkNode* node) {
  const std::string& url = node->GetURL().possibly_invalid_spec();
  const std::string& title = WideToUTF8(node->GetTitle());

  std::string truncated_url = WideToUTF8(l10n_util::TruncateString(
      UTF8ToWide(url), kMaxTooltipURLLength));
  gchar* escaped_url_cstr = g_markup_escape_text(truncated_url.c_str(),
                                                 truncated_url.size());
  std::string escaped_url(escaped_url_cstr);
  g_free(escaped_url_cstr);

  std::string tooltip;
  if (url == title || title.empty()) {
    return escaped_url;
  } else {
    std::string truncated_title = WideToUTF8(l10n_util::TruncateString(
      node->GetTitle(), kMaxTooltipTitleLength));
    gchar* escaped_title_cstr = g_markup_escape_text(truncated_title.c_str(),
                                                     truncated_title.size());
    std::string escaped_title(escaped_title_cstr);
    g_free(escaped_title_cstr);

    if (!escaped_url.empty())
      return std::string("") + escaped_title + "\n" + escaped_url;
    else
      return std::string("") + escaped_title + "";
  }
}

const BookmarkNode* BookmarkNodeForWidget(GtkWidget* widget) {
  return reinterpret_cast<const BookmarkNode*>(
      g_object_get_data(G_OBJECT(widget), bookmark_utils::kBookmarkNode));
}

void SetButtonTextColors(GtkWidget* label, GtkThemeProvider* provider) {
  if (provider->UseGtkTheme()) {
    gtk_util::SetLabelColor(label, NULL);
  } else {
    GdkColor color = provider->GetGdkColor(
        BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
    gtk_util::SetLabelColor(label, &color);
  }
}

// DnD-related -----------------------------------------------------------------

void WriteBookmarkToSelection(const BookmarkNode* node,
                              GtkSelectionData* selection_data,
                              guint target_type,
                              Profile* profile) {
  DCHECK(node);
  std::vector<const BookmarkNode*> nodes;
  nodes.push_back(node);
  WriteBookmarksToSelection(nodes, selection_data, target_type, profile);
}

void WriteBookmarksToSelection(const std::vector<const BookmarkNode*>& nodes,
                               GtkSelectionData* selection_data,
                               guint target_type,
                               Profile* profile) {
  switch (target_type) {
    case GtkDndUtil::CHROME_BOOKMARK_ITEM: {
      BookmarkDragData data(nodes);
      Pickle pickle;
      data.WriteToPickle(profile, &pickle);

      gtk_selection_data_set(selection_data, selection_data->target,
                             kBitsInAByte,
                             static_cast<const guchar*>(pickle.data()),
                             pickle.size());
      break;
    }
    case GtkDndUtil::TEXT_URI_LIST: {
      gchar** uris = reinterpret_cast<gchar**>(malloc(sizeof(gchar*) *
                                               (nodes.size() + 1)));
      for (size_t i = 0; i < nodes.size(); ++i) {
        // If the node is a folder, this will be empty. TODO(estade): figure out
        // if there are any ramifications to passing an empty URI. After a
        // little testing, it seems fine.
        const GURL& url = nodes[i]->GetURL();
        // This const cast should be safe as gtk_selection_data_set_uris()
        // makes copies.
        uris[i] = const_cast<gchar*>(url.spec().c_str());
      }
      uris[nodes.size()] = NULL;

      gtk_selection_data_set_uris(selection_data, uris);
      free(uris);
      break;
    }
    default: {
      DLOG(ERROR) << "Unsupported drag get type!";
    }
  }
}

std::vector<const BookmarkNode*> GetNodesFromSelection(
    GdkDragContext* context,
    GtkSelectionData* selection_data,
    guint target_type,
    Profile* profile,
    gboolean* delete_selection_data,
    gboolean* dnd_success) {
  *delete_selection_data = FALSE;
  *dnd_success = FALSE;

  if ((selection_data != NULL) && (selection_data->length >= 0)) {
    if (context->action == GDK_ACTION_MOVE) {
      *delete_selection_data = TRUE;
    }

    switch (target_type) {
      case GtkDndUtil::CHROME_BOOKMARK_ITEM: {
        *dnd_success = TRUE;
        Pickle pickle(reinterpret_cast<char*>(selection_data->data),
                      selection_data->length);
        BookmarkDragData drag_data;
        drag_data.ReadFromPickle(&pickle);
        return drag_data.GetNodes(profile);
      }
      default: {
        DLOG(ERROR) << "Unsupported drag received type: " << target_type;
      }
    }
  }

  return std::vector<const BookmarkNode*>();
}

bool CreateNewBookmarkFromNamedUrl(GtkSelectionData* selection_data,
    BookmarkModel* model, const BookmarkNode* parent, int idx) {
  GURL url;
  string16 title;
  if (!GtkDndUtil::ExtractNamedURL(selection_data, &url, &title))
    return false;

  model->AddURL(parent, idx, UTF16ToWideHack(title), url);
  return true;
}

bool CreateNewBookmarksFromURIList(GtkSelectionData* selection_data,
    BookmarkModel* model, const BookmarkNode* parent, int idx) {
  std::vector<GURL> urls;
  GtkDndUtil::ExtractURIList(selection_data, &urls);
  for (size_t i = 0; i < urls.size(); ++i) {
    std::string title = GetNameForURL(urls[i]);
    model->AddURL(parent, idx++, UTF8ToWide(title), urls[i]);
  }
  return true;
}

}  // namespace bookmark_utils
<commit_msg>GTK: Don't ellipsize the Other Bookmarks button.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/gtk/bookmark_utils_gtk.h"

#include "app/gtk_dnd_util.h"
#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/gfx/gtk_util.h"
#include "base/pickle.h"
#include "base/string_util.h"
#include "chrome/browser/bookmarks/bookmark_drag_data.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/gtk/gtk_chrome_button.h"
#include "chrome/browser/gtk/gtk_theme_provider.h"
#include "chrome/browser/profile.h"
#include "chrome/common/gtk_util.h"

namespace {

// Used in gtk_selection_data_set(). (I assume from this parameter that gtk has
// to some really exotic hardware...)
const int kBitsInAByte = 8;

// Maximum number of characters on a bookmark button.
const size_t kMaxCharsOnAButton = 15;

// Max size of each component of the button tooltips.
const size_t kMaxTooltipTitleLength = 100;
const size_t kMaxTooltipURLLength = 400;

// Only used for the background of the drag widget.
const GdkColor kBackgroundColor = GDK_COLOR_RGB(0xe6, 0xed, 0xf4);

// Padding between the chrome button highlight border and the contents (favicon,
// text).
// TODO(estade): we need to adjust the top and bottom padding, but first we need
// to give the bookmark bar more space (at the expense of the toolbar).
const int kButtonPaddingTop = 0;
const int kButtonPaddingBottom = 0;
const int kButtonPaddingLeft = 2;
const int kButtonPaddingRight = 0;

void* AsVoid(const BookmarkNode* node) {
  return const_cast<BookmarkNode*>(node);
}

}  // namespace

namespace bookmark_utils {

const char kBookmarkNode[] = "bookmark-node";

// Spacing between the buttons on the bar.
const int kBarButtonPadding = 4;

GdkPixbuf* GetPixbufForNode(const BookmarkNode* node, BookmarkModel* model,
                            bool native) {
  GdkPixbuf* pixbuf;

  if (node->is_url()) {
    if (model->GetFavIcon(node).width() != 0) {
      pixbuf = gfx::GdkPixbufFromSkBitmap(&model->GetFavIcon(node));
    } else {
      pixbuf = GtkThemeProvider::GetDefaultFavicon(native);
      g_object_ref(pixbuf);
    }
  } else {
    pixbuf = GtkThemeProvider::GetFolderIcon(native);
    g_object_ref(pixbuf);
  }

  return pixbuf;
}

GtkWidget* GetDragRepresentation(const BookmarkNode* node,
                                 BookmarkModel* model,
                                 GtkThemeProvider* provider) {
  // Build a windowed representation for our button.
  GtkWidget* window = gtk_window_new(GTK_WINDOW_POPUP);
  if (!provider->UseGtkTheme()) {
    // TODO(erg): Theme wise, which color should I be picking here?
    // COLOR_BUTTON_BACKGROUND doesn't match the default theme!
    gtk_widget_modify_bg(window, GTK_STATE_NORMAL, &kBackgroundColor);
  }
  gtk_widget_realize(window);

  GtkWidget* frame = gtk_frame_new(NULL);
  gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
  gtk_container_add(GTK_CONTAINER(window), frame);
  gtk_widget_show(frame);

  GtkWidget* floating_button = provider->BuildChromeButton();
  bookmark_utils::ConfigureButtonForNode(node, model, floating_button,
                                         provider);
  gtk_container_add(GTK_CONTAINER(frame), floating_button);
  gtk_widget_show(floating_button);

  return window;
}

void ConfigureButtonForNode(const BookmarkNode* node, BookmarkModel* model,
                            GtkWidget* button, GtkThemeProvider* provider) {
  GtkWidget* former_child = gtk_bin_get_child(GTK_BIN(button));
  if (former_child)
    gtk_container_remove(GTK_CONTAINER(button), former_child);

  std::string tooltip = BuildTooltipFor(node);
  if (!tooltip.empty())
    gtk_widget_set_tooltip_markup(button, tooltip.c_str());

  // We pack the button manually (rather than using gtk_button_set_*) so that
  // we can have finer control over its label.
  GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model,
                                                       provider->UseGtkTheme());
  GtkWidget* image = gtk_image_new_from_pixbuf(pixbuf);
  g_object_unref(pixbuf);

  GtkWidget* box = gtk_hbox_new(FALSE, kBarButtonPadding);
  gtk_box_pack_start(GTK_BOX(box), image, FALSE, FALSE, 0);

  std::string label_string = WideToUTF8(node->GetTitle());
  if (!label_string.empty()) {
    GtkWidget* label = gtk_label_new(label_string.c_str());

    // Ellipsize long bookmark names.
    if (node != model->other_node()) {
      gtk_label_set_max_width_chars(GTK_LABEL(label), kMaxCharsOnAButton);
      gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END);
    }

    gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 0);
    SetButtonTextColors(label, provider);
  }

  GtkWidget* alignment = gtk_alignment_new(0.0, 0.0, 1.0, 1.0);
  // If we are not showing the label, don't set any padding, so that the icon
  // will just be centered.
  if (label_string.c_str()) {
    gtk_alignment_set_padding(GTK_ALIGNMENT(alignment),
        kButtonPaddingTop, kButtonPaddingBottom,
        kButtonPaddingLeft, kButtonPaddingRight);
  }
  gtk_container_add(GTK_CONTAINER(alignment), box);
  gtk_container_add(GTK_CONTAINER(button), alignment);

  g_object_set_data(G_OBJECT(button), bookmark_utils::kBookmarkNode,
                    AsVoid(node));

  gtk_widget_show_all(alignment);
}

std::string BuildTooltipFor(const BookmarkNode* node) {
  const std::string& url = node->GetURL().possibly_invalid_spec();
  const std::string& title = WideToUTF8(node->GetTitle());

  std::string truncated_url = WideToUTF8(l10n_util::TruncateString(
      UTF8ToWide(url), kMaxTooltipURLLength));
  gchar* escaped_url_cstr = g_markup_escape_text(truncated_url.c_str(),
                                                 truncated_url.size());
  std::string escaped_url(escaped_url_cstr);
  g_free(escaped_url_cstr);

  std::string tooltip;
  if (url == title || title.empty()) {
    return escaped_url;
  } else {
    std::string truncated_title = WideToUTF8(l10n_util::TruncateString(
      node->GetTitle(), kMaxTooltipTitleLength));
    gchar* escaped_title_cstr = g_markup_escape_text(truncated_title.c_str(),
                                                     truncated_title.size());
    std::string escaped_title(escaped_title_cstr);
    g_free(escaped_title_cstr);

    if (!escaped_url.empty())
      return std::string("") + escaped_title + "\n" + escaped_url;
    else
      return std::string("") + escaped_title + "";
  }
}

const BookmarkNode* BookmarkNodeForWidget(GtkWidget* widget) {
  return reinterpret_cast<const BookmarkNode*>(
      g_object_get_data(G_OBJECT(widget), bookmark_utils::kBookmarkNode));
}

void SetButtonTextColors(GtkWidget* label, GtkThemeProvider* provider) {
  if (provider->UseGtkTheme()) {
    gtk_util::SetLabelColor(label, NULL);
  } else {
    GdkColor color = provider->GetGdkColor(
        BrowserThemeProvider::COLOR_BOOKMARK_TEXT);
    gtk_util::SetLabelColor(label, &color);
  }
}

// DnD-related -----------------------------------------------------------------

void WriteBookmarkToSelection(const BookmarkNode* node,
                              GtkSelectionData* selection_data,
                              guint target_type,
                              Profile* profile) {
  DCHECK(node);
  std::vector<const BookmarkNode*> nodes;
  nodes.push_back(node);
  WriteBookmarksToSelection(nodes, selection_data, target_type, profile);
}

void WriteBookmarksToSelection(const std::vector<const BookmarkNode*>& nodes,
                               GtkSelectionData* selection_data,
                               guint target_type,
                               Profile* profile) {
  switch (target_type) {
    case GtkDndUtil::CHROME_BOOKMARK_ITEM: {
      BookmarkDragData data(nodes);
      Pickle pickle;
      data.WriteToPickle(profile, &pickle);

      gtk_selection_data_set(selection_data, selection_data->target,
                             kBitsInAByte,
                             static_cast<const guchar*>(pickle.data()),
                             pickle.size());
      break;
    }
    case GtkDndUtil::TEXT_URI_LIST: {
      gchar** uris = reinterpret_cast<gchar**>(malloc(sizeof(gchar*) *
                                               (nodes.size() + 1)));
      for (size_t i = 0; i < nodes.size(); ++i) {
        // If the node is a folder, this will be empty. TODO(estade): figure out
        // if there are any ramifications to passing an empty URI. After a
        // little testing, it seems fine.
        const GURL& url = nodes[i]->GetURL();
        // This const cast should be safe as gtk_selection_data_set_uris()
        // makes copies.
        uris[i] = const_cast<gchar*>(url.spec().c_str());
      }
      uris[nodes.size()] = NULL;

      gtk_selection_data_set_uris(selection_data, uris);
      free(uris);
      break;
    }
    default: {
      DLOG(ERROR) << "Unsupported drag get type!";
    }
  }
}

std::vector<const BookmarkNode*> GetNodesFromSelection(
    GdkDragContext* context,
    GtkSelectionData* selection_data,
    guint target_type,
    Profile* profile,
    gboolean* delete_selection_data,
    gboolean* dnd_success) {
  *delete_selection_data = FALSE;
  *dnd_success = FALSE;

  if ((selection_data != NULL) && (selection_data->length >= 0)) {
    if (context->action == GDK_ACTION_MOVE) {
      *delete_selection_data = TRUE;
    }

    switch (target_type) {
      case GtkDndUtil::CHROME_BOOKMARK_ITEM: {
        *dnd_success = TRUE;
        Pickle pickle(reinterpret_cast<char*>(selection_data->data),
                      selection_data->length);
        BookmarkDragData drag_data;
        drag_data.ReadFromPickle(&pickle);
        return drag_data.GetNodes(profile);
      }
      default: {
        DLOG(ERROR) << "Unsupported drag received type: " << target_type;
      }
    }
  }

  return std::vector<const BookmarkNode*>();
}

bool CreateNewBookmarkFromNamedUrl(GtkSelectionData* selection_data,
    BookmarkModel* model, const BookmarkNode* parent, int idx) {
  GURL url;
  string16 title;
  if (!GtkDndUtil::ExtractNamedURL(selection_data, &url, &title))
    return false;

  model->AddURL(parent, idx, UTF16ToWideHack(title), url);
  return true;
}

bool CreateNewBookmarksFromURIList(GtkSelectionData* selection_data,
    BookmarkModel* model, const BookmarkNode* parent, int idx) {
  std::vector<GURL> urls;
  GtkDndUtil::ExtractURIList(selection_data, &urls);
  for (size_t i = 0; i < urls.size(); ++i) {
    std::string title = GetNameForURL(urls[i]);
    model->AddURL(parent, idx++, UTF8ToWide(title), urls[i]);
  }
  return true;
}

}  // namespace bookmark_utils
<|endoftext|>


<commit_before><commit_msg>Only call gtk_window_present on an alert dialog if the activation state of the window is changing to active.  The signal gets sent even when windows are going inactive (to make the frame light blue), but we only want to do anything if the window is trying to become active.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove two unneeded uses of std::floor in the GTK tab code.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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/views/html_dialog_view.h"

#include "base/keyboard_codes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/window.h"

namespace browser {

// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowHtmlDialogView(gfx::NativeWindow parent, Browser* browser,
                        HtmlDialogUIDelegate* delegate) {
  HtmlDialogView* html_view =
      new HtmlDialogView(browser->profile(), delegate);
  views::Window::CreateChromeWindow(parent, gfx::Rect(), html_view);
  html_view->InitDialog();
  html_view->window()->Show();
}

}  // namespace browser

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, public:

HtmlDialogView::HtmlDialogView(Profile* profile,
                               HtmlDialogUIDelegate* delegate)
    : DOMView(),
      HtmlDialogTabContentsDelegate(profile),
      delegate_(delegate) {
}

HtmlDialogView::~HtmlDialogView() {
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, views::View implementation:

gfx::Size HtmlDialogView::GetPreferredSize() {
  gfx::Size out;
  if (delegate_)
    delegate_->GetDialogSize(&out);
  return out;
}

bool HtmlDialogView::AcceleratorPressed(const views::Accelerator& accelerator) {
  // Pressing ESC closes the dialog.
  DCHECK_EQ(base::VKEY_ESCAPE, accelerator.GetKeyCode());
  OnDialogClosed(std::string());
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, views::WindowDelegate implementation:

bool HtmlDialogView::CanResize() const {
  return true;
}

bool HtmlDialogView::IsModal() const {
  if (delegate_)
    return delegate_->IsDialogModal();
  else
    return false;
}

std::wstring HtmlDialogView::GetWindowTitle() const {
  if (delegate_)
    return delegate_->GetDialogTitle();
  else
    return std::wstring();
}

void HtmlDialogView::WindowClosing() {
  // If we still have a delegate that means we haven't notified it of the
  // dialog closing. This happens if the user clicks the Close button on the
  // dialog.
  if (delegate_)
    OnDialogClosed("");
}

views::View* HtmlDialogView::GetContentsView() {
  return this;
}

views::View* HtmlDialogView::GetInitiallyFocusedView() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogUIDelegate implementation:

bool HtmlDialogView::IsDialogModal() const {
  return IsModal();
}

std::wstring HtmlDialogView::GetDialogTitle() const {
  return GetWindowTitle();
}

GURL HtmlDialogView::GetDialogContentURL() const {
  if (delegate_)
    return delegate_->GetDialogContentURL();
  else
    return GURL();
}

void HtmlDialogView::GetDOMMessageHandlers(
    std::vector<DOMMessageHandler*>* handlers) const {
  if (delegate_)
    delegate_->GetDOMMessageHandlers(handlers);
}

void HtmlDialogView::GetDialogSize(gfx::Size* size) const {
  if (delegate_)
    delegate_->GetDialogSize(size);
}

std::string HtmlDialogView::GetDialogArgs() const {
  if (delegate_)
    return delegate_->GetDialogArgs();
  else
    return std::string();
}

void HtmlDialogView::OnDialogClosed(const std::string& json_retval) {
  HtmlDialogUIDelegate* dialog_delegate = delegate_;
  delegate_ = NULL;  // We will not communicate further with the delegate.
  HtmlDialogTabContentsDelegate::Detach();
  dialog_delegate->OnDialogClosed(json_retval);
  window()->Close();
}

////////////////////////////////////////////////////////////////////////////////
// TabContentsDelegate implementation:

void HtmlDialogView::MoveContents(TabContents* source, const gfx::Rect& pos) {
  // The contained web page wishes to resize itself. We let it do this because
  // if it's a dialog we know about, we trust it not to be mean to the user.
  GetWidget()->SetBounds(pos);
}

void HtmlDialogView::ToolbarSizeChanged(TabContents* source,
                                        bool is_animating) {
  Layout();
}

// A simplified version of BrowserView::HandleKeyboardEvent().
// We don't handle global keyboard shortcuts here, but that's fine since
// they're all browser-specific. (This may change in the future.)
void HtmlDialogView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
#if defined(OS_WIN)
  // Any unhandled keyboard/character messages should be defproced.
  // This allows stuff like F10, etc to work correctly.
  DefWindowProc(event.os_event.hwnd, event.os_event.message,
                  event.os_event.wParam, event.os_event.lParam);
#endif
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView:

void HtmlDialogView::InitDialog() {
  // Now Init the DOMView. This view runs in its own process to render the html.
  DOMView::Init(profile(), NULL);

  tab_contents_->set_delegate(this);

  // Set the delegate. This must be done before loading the page. See
  // the comment above HtmlDialogUI in its header file for why.
  HtmlDialogUI::GetPropertyAccessor().SetProperty(tab_contents_->property_bag(),
                                                  this);

  // Pressing the ESC key will close the dialog.
  AddAccelerator(views::Accelerator(base::VKEY_ESCAPE, false, false, false));

  DOMView::LoadURL(delegate_->GetDialogContentURL());
}
<commit_msg>Fix potential NULL pointer error in HtmlDialogView::InitDialog.<commit_after>// Copyright (c) 2006-2008 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/views/html_dialog_view.h"

#include "base/keyboard_codes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "views/widget/root_view.h"
#include "views/widget/widget.h"
#include "views/window/window.h"

namespace browser {

// Declared in browser_dialogs.h so that others don't need to depend on our .h.
void ShowHtmlDialogView(gfx::NativeWindow parent, Browser* browser,
                        HtmlDialogUIDelegate* delegate) {
  HtmlDialogView* html_view =
      new HtmlDialogView(browser->profile(), delegate);
  views::Window::CreateChromeWindow(parent, gfx::Rect(), html_view);
  html_view->InitDialog();
  html_view->window()->Show();
}

}  // namespace browser

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, public:

HtmlDialogView::HtmlDialogView(Profile* profile,
                               HtmlDialogUIDelegate* delegate)
    : DOMView(),
      HtmlDialogTabContentsDelegate(profile),
      delegate_(delegate) {
}

HtmlDialogView::~HtmlDialogView() {
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, views::View implementation:

gfx::Size HtmlDialogView::GetPreferredSize() {
  gfx::Size out;
  if (delegate_)
    delegate_->GetDialogSize(&out);
  return out;
}

bool HtmlDialogView::AcceleratorPressed(const views::Accelerator& accelerator) {
  // Pressing ESC closes the dialog.
  DCHECK_EQ(base::VKEY_ESCAPE, accelerator.GetKeyCode());
  OnDialogClosed(std::string());
  return true;
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView, views::WindowDelegate implementation:

bool HtmlDialogView::CanResize() const {
  return true;
}

bool HtmlDialogView::IsModal() const {
  if (delegate_)
    return delegate_->IsDialogModal();
  else
    return false;
}

std::wstring HtmlDialogView::GetWindowTitle() const {
  if (delegate_)
    return delegate_->GetDialogTitle();
  else
    return std::wstring();
}

void HtmlDialogView::WindowClosing() {
  // If we still have a delegate that means we haven't notified it of the
  // dialog closing. This happens if the user clicks the Close button on the
  // dialog.
  if (delegate_)
    OnDialogClosed("");
}

views::View* HtmlDialogView::GetContentsView() {
  return this;
}

views::View* HtmlDialogView::GetInitiallyFocusedView() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogUIDelegate implementation:

bool HtmlDialogView::IsDialogModal() const {
  return IsModal();
}

std::wstring HtmlDialogView::GetDialogTitle() const {
  return GetWindowTitle();
}

GURL HtmlDialogView::GetDialogContentURL() const {
  if (delegate_)
    return delegate_->GetDialogContentURL();
  else
    return GURL();
}

void HtmlDialogView::GetDOMMessageHandlers(
    std::vector<DOMMessageHandler*>* handlers) const {
  if (delegate_)
    delegate_->GetDOMMessageHandlers(handlers);
}

void HtmlDialogView::GetDialogSize(gfx::Size* size) const {
  if (delegate_)
    delegate_->GetDialogSize(size);
}

std::string HtmlDialogView::GetDialogArgs() const {
  if (delegate_)
    return delegate_->GetDialogArgs();
  else
    return std::string();
}

void HtmlDialogView::OnDialogClosed(const std::string& json_retval) {
  HtmlDialogUIDelegate* dialog_delegate = delegate_;
  delegate_ = NULL;  // We will not communicate further with the delegate.
  HtmlDialogTabContentsDelegate::Detach();
  dialog_delegate->OnDialogClosed(json_retval);
  window()->Close();
}

////////////////////////////////////////////////////////////////////////////////
// TabContentsDelegate implementation:

void HtmlDialogView::MoveContents(TabContents* source, const gfx::Rect& pos) {
  // The contained web page wishes to resize itself. We let it do this because
  // if it's a dialog we know about, we trust it not to be mean to the user.
  GetWidget()->SetBounds(pos);
}

void HtmlDialogView::ToolbarSizeChanged(TabContents* source,
                                        bool is_animating) {
  Layout();
}

// A simplified version of BrowserView::HandleKeyboardEvent().
// We don't handle global keyboard shortcuts here, but that's fine since
// they're all browser-specific. (This may change in the future.)
void HtmlDialogView::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
#if defined(OS_WIN)
  // Any unhandled keyboard/character messages should be defproced.
  // This allows stuff like F10, etc to work correctly.
  DefWindowProc(event.os_event.hwnd, event.os_event.message,
                  event.os_event.wParam, event.os_event.lParam);
#endif
}

////////////////////////////////////////////////////////////////////////////////
// HtmlDialogView:

void HtmlDialogView::InitDialog() {
  // Now Init the DOMView. This view runs in its own process to render the html.
  DOMView::Init(profile(), NULL);

  tab_contents_->set_delegate(this);

  // Set the delegate. This must be done before loading the page. See
  // the comment above HtmlDialogUI in its header file for why.
  HtmlDialogUI::GetPropertyAccessor().SetProperty(tab_contents_->property_bag(),
                                                  this);

  // Pressing the ESC key will close the dialog.
  AddAccelerator(views::Accelerator(base::VKEY_ESCAPE, false, false, false));

  DOMView::LoadURL(GetDialogContentURL());
}
<|endoftext|>


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

#include "chrome/renderer/webview_color_overlay.h"

#include "base/logging.h"
#include "content/public/renderer/render_view.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/gfx/size.h"
#include "ui/gfx/skia_util.h"

#if WEBKIT_USING_CG
#include "skia/ext/skia_utils_mac.h"
#endif

WebViewColorOverlay::WebViewColorOverlay(content::RenderView* render_view,
                                         SkColor color)
    : render_view_(render_view),
      color_(color) {
  render_view_->GetWebView()->addPageOverlay(this, 0);
}

WebViewColorOverlay::~WebViewColorOverlay() {
  render_view_->GetWebView()->removePageOverlay(this);
}

void WebViewColorOverlay::paintPageOverlay(WebKit::WebCanvas* canvas) {
  SkRect rect = gfx::RectToSkRect(gfx::Rect(render_view_->GetSize()));

#if WEBKIT_USING_SKIA
  SkPaint paint;
  paint.setColor(color_);
  paint.setStyle(SkPaint::kFill_Style);
  canvas->drawRect(rect, paint);
#elif WEBKIT_USING_CG
  CGContextSaveGState(canvas);
  CGColorRef color = gfx::SkColorToCGColorRef(color_);
  CGContextSetFillColorWithColor(canvas, color);
  CGColorRelease(color);
  CGContextFillRect(canvas, gfx::SkRectToCGRect(rect));
  CGContextRestoreGState(canvas);
#else
  NOTIMPLEMENTED();
#endif
}
<commit_msg>Fix null pointer exception in WebViewColorOverlay.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/webview_color_overlay.h"

#include "base/logging.h"
#include "content/public/renderer/render_view.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkRect.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#include "ui/gfx/size.h"
#include "ui/gfx/skia_util.h"

#if WEBKIT_USING_CG
#include "skia/ext/skia_utils_mac.h"
#endif

WebViewColorOverlay::WebViewColorOverlay(content::RenderView* render_view,
                                         SkColor color)
    : render_view_(render_view),
      color_(color) {
  render_view_->GetWebView()->addPageOverlay(this, 0);
}

WebViewColorOverlay::~WebViewColorOverlay() {
  if (render_view_->GetWebView())
    render_view_->GetWebView()->removePageOverlay(this);
}

void WebViewColorOverlay::paintPageOverlay(WebKit::WebCanvas* canvas) {
  SkRect rect = gfx::RectToSkRect(gfx::Rect(render_view_->GetSize()));

#if WEBKIT_USING_SKIA
  SkPaint paint;
  paint.setColor(color_);
  paint.setStyle(SkPaint::kFill_Style);
  canvas->drawRect(rect, paint);
#elif WEBKIT_USING_CG
  CGContextSaveGState(canvas);
  CGColorRef color = gfx::SkColorToCGColorRef(color_);
  CGContextSetFillColorWithColor(canvas, color);
  CGColorRelease(color);
  CGContextFillRect(canvas, gfx::SkRectToCGRect(rect));
  CGContextRestoreGState(canvas);
#else
  NOTIMPLEMENTED();
#endif
}
<|endoftext|>


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

#include "content/test/test_launcher.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/scoped_temp_dir.h"
#include "chrome/app/chrome_main_delegate.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/base/chrome_test_suite.h"
#include "content/app/content_main.h"

#if defined(OS_MACOSX)
#include "chrome/browser/chrome_browser_application_mac.h"
#endif  // defined(OS_MACOSX)

#if defined(OS_WIN)
#include "content/app/startup_helper_win.h"
#include "sandbox/src/sandbox_types.h"
#endif  // defined(OS_WIN)

class ChromeTestLauncherDelegate : public test_launcher::TestLauncherDelegate {
 public:
  ChromeTestLauncherDelegate() {
  }

  virtual ~ChromeTestLauncherDelegate() {
  }

  virtual void EarlyInitialize() OVERRIDE {
#if defined(OS_MACOSX)
    chrome_browser_application_mac::RegisterBrowserCrApp();
#endif
  }

  virtual bool Run(int argc, char** argv, int* return_code) OVERRIDE {
#if defined(OS_WIN)
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kProcessType)) {
      sandbox::SandboxInterfaceInfo sandbox_info = {0};
      content::InitializeSandboxInfo(&sandbox_info);
      ChromeMainDelegate chrome_main_delegate;
      *return_code = content::ContentMain(GetModuleHandle(NULL),
                                          &sandbox_info,
                                          &chrome_main_delegate);
      return true;
    }
#elif defined(OS_LINUX)
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kProcessType)) {
      ChromeMainDelegate chrome_main_delegate;
      *return_code = content::ContentMain(argc,
                                          const_cast<const char**>(argv),
                                          &chrome_main_delegate);
      return true;
    }
#endif  // defined(OS_WIN)

    return false;
  }

  virtual int RunTestSuite(int argc, char** argv) OVERRIDE {
    return ChromeTestSuite(argc, argv).Run();
  }

  virtual bool AdjustChildProcessCommandLine(
      CommandLine* command_line) OVERRIDE {
    CommandLine new_command_line(command_line->GetProgram());
    CommandLine::SwitchMap switches = command_line->GetSwitches();

    // Strip out user-data-dir if present.  We will add it back in again later.
    switches.erase(switches::kUserDataDir);

    for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
         iter != switches.end(); ++iter) {
      new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
    }

    // Create a new user data dir and pass it to the child.
    ScopedTempDir temp_dir;
    if (!temp_dir.CreateUniqueTempDir() || !temp_dir.IsValid()) {
      LOG(ERROR) << "Error creating temp profile directory";
      return false;
    }
    new_command_line.AppendSwitchPath(switches::kUserDataDir, temp_dir.path());

    // file:// access for ChromeOS.
    new_command_line.AppendSwitch(switches::kAllowFileAccess);

    *command_line = new_command_line;
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ChromeTestLauncherDelegate);
};

int main(int argc, char** argv) {
  ChromeTestLauncherDelegate launcher_delegate;
  return test_launcher::LaunchTests(&launcher_delegate, argc, argv);
}
<commit_msg>First attempt at fixing the tests that time out in Win7 Sync builder. http://build.chromium.org/p/chromium/builders/Win7%20Sync/builds/10936<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/test/test_launcher.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/scoped_temp_dir.h"
#include "chrome/app/chrome_main_delegate.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/base/chrome_test_suite.h"
#include "content/app/content_main.h"

#if defined(OS_MACOSX)
#include "chrome/browser/chrome_browser_application_mac.h"
#endif  // defined(OS_MACOSX)

#if defined(OS_WIN)
#include "base/base_switches.h"
#include "content/common/sandbox_policy.h"
#include "sandbox/src/dep.h"
#include "sandbox/src/sandbox_factory.h"
#include "sandbox/src/sandbox_types.h"

// The entry point signature of chrome.dll.
typedef int (*DLL_MAIN)(HINSTANCE, sandbox::SandboxInterfaceInfo*, wchar_t*);
#endif  // defined(OS_WIN)

class ChromeTestLauncherDelegate : public test_launcher::TestLauncherDelegate {
 public:
  ChromeTestLauncherDelegate() {
  }

  virtual ~ChromeTestLauncherDelegate() {
  }

  virtual void EarlyInitialize() OVERRIDE {
#if defined(OS_MACOSX)
    chrome_browser_application_mac::RegisterBrowserCrApp();
#endif
  }

  virtual bool Run(int argc, char** argv, int* return_code) OVERRIDE {
#if defined(OS_WIN)
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kProcessType)) {
      // TODO(phajdan.jr): Make this not use chrome.dll.
      // This is a child process, call ChromeMain.
      FilePath chrome_path(command_line->GetProgram().DirName());
      chrome_path = chrome_path.Append(chrome::kBrowserResourcesDll);
      HMODULE dll = LoadLibrary(chrome_path.value().c_str());
      DLL_MAIN entry_point =
          reinterpret_cast<DLL_MAIN>(::GetProcAddress(dll, "ChromeMain"));
      if (!entry_point)
        return false;

      // Initialize the sandbox services.
      sandbox::SandboxInterfaceInfo sandbox_info = {0};
      sandbox_info.target_services =
          sandbox::SandboxFactory::GetTargetServices();
      *return_code =
          entry_point(GetModuleHandle(NULL), &sandbox_info, GetCommandLineW());
      return true;
    }
#elif defined(OS_LINUX)
    CommandLine* command_line = CommandLine::ForCurrentProcess();
    if (command_line->HasSwitch(switches::kProcessType)) {
      ChromeMainDelegate chrome_main_delegate;
      *return_code = content::ContentMain(argc,
                                          const_cast<const char**>(argv),
                                          &chrome_main_delegate);
      return true;
    }
#endif  // defined(OS_WIN)

    return false;
  }

  virtual int RunTestSuite(int argc, char** argv) OVERRIDE {
    return ChromeTestSuite(argc, argv).Run();
  }

  virtual bool AdjustChildProcessCommandLine(
      CommandLine* command_line) OVERRIDE {
    CommandLine new_command_line(command_line->GetProgram());
    CommandLine::SwitchMap switches = command_line->GetSwitches();

    // Strip out user-data-dir if present.  We will add it back in again later.
    switches.erase(switches::kUserDataDir);

    for (CommandLine::SwitchMap::const_iterator iter = switches.begin();
         iter != switches.end(); ++iter) {
      new_command_line.AppendSwitchNative((*iter).first, (*iter).second);
    }

    // Create a new user data dir and pass it to the child.
    ScopedTempDir temp_dir;
    if (!temp_dir.CreateUniqueTempDir() || !temp_dir.IsValid()) {
      LOG(ERROR) << "Error creating temp profile directory";
      return false;
    }
    new_command_line.AppendSwitchPath(switches::kUserDataDir, temp_dir.path());

    // file:// access for ChromeOS.
    new_command_line.AppendSwitch(switches::kAllowFileAccess);

    *command_line = new_command_line;
    return true;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ChromeTestLauncherDelegate);
};

int main(int argc, char** argv) {
  ChromeTestLauncherDelegate launcher_delegate;
  return test_launcher::LaunchTests(&launcher_delegate, argc, argv);
}
<|endoftext|>


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

#include "chrome/test/test_launcher/test_runner.h"

#include <vector>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"

namespace {

const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests";

// Retrieves the list of tests to run by running gtest with the
// --gtest_list_tests flag in a forked process and parsing its output.
// |command_line| should contain the command line used to start the browser
// test launcher, it is expected that it does not contain the
// --gtest_list_tests flag already.
// Note: we cannot implement this in-process for InProcessTestRunner as GTest
// prints to the stdout and there are no good way of temporarily redirecting
// outputs.
bool GetTestList(const CommandLine& command_line,
                 std::vector<std::string>* test_list) {
  DCHECK(!command_line.HasSwitch(kGTestListTestsFlag));

  // Run ourselves with the --gtest_list_tests option and read the output.
  CommandLine new_command_line(command_line);
  new_command_line.AppendSwitch(kGTestListTestsFlag);
  std::string output;
  if (!base::GetAppOutput(new_command_line, &output))
    return false;

  // The output looks like:
  // TestCase.
  //   Test1
  //   Test2
  // OtherTestCase.
  //   FooTest
  // ...
  std::vector<std::string> lines;
  SplitString(output, '\n', &lines);

  std::string test_case;
  for (std::vector<std::string>::const_iterator iter = lines.begin();
       iter != lines.end(); ++iter) {
    std::string line = *iter;
    if (line.empty())
      continue;  // Just ignore empty lines if any.

    if (line[line.size() - 1] == '.') {
      // This is a new test case.
      test_case = line;
      continue;
    }

    if (!command_line.HasSwitch(kGTestRunDisabledTestsFlag) &&
        line.find("DISABLED") != std::string::npos)
      continue;  // Skip disabled tests.

    // We are dealing with a test.
    test_list->push_back(test_case + line);
  }
  return true;
}

}  // namespace

namespace tests {

TestRunner::TestRunner() {
}

TestRunner::~TestRunner() {
}

bool RunTests(const TestRunnerFactory& test_runner_factory) {
  const CommandLine* command_line = CommandLine::ForCurrentProcess();

  DCHECK(!command_line->HasSwitch(kGTestListTestsFlag));

  // First let's get the list of tests we need to run.
  std::vector<std::string> test_list;
  if (!GetTestList(*command_line, &test_list)) {
    printf("Failed to retrieve the tests to run.\n");
    return false;
  }

  if (test_list.empty()) {
    printf("No tests to run.\n");
    return false;
  }

  int test_run_count = 0;
  std::vector<std::string> failed_tests;
  for (std::vector<std::string>::const_iterator iter = test_list.begin();
       iter != test_list.end(); ++iter) {
    std::string test_name = *iter;
    scoped_ptr<TestRunner> test_runner(test_runner_factory.CreateTestRunner());
    if (!test_runner.get() || !test_runner->Init())
      return false;
    test_run_count++;
    if (!test_runner->RunTest(test_name.c_str())) {
      if (std::find(failed_tests.begin(), failed_tests.end(), test_name) ==
          failed_tests.end()) {
        failed_tests.push_back(*iter);
      }
    }
  }

  printf("%d test%s run\n", test_run_count, test_run_count > 1 ? "s" : "");
  printf("%d test%s failed\n", static_cast<int>(failed_tests.size()),
                               failed_tests.size() > 1 ? "s" : "");
  if (failed_tests.empty())
    return true;

  printf("Failing tests:\n");
  for (std::vector<std::string>::const_iterator iter = failed_tests.begin();
       iter != failed_tests.end(); ++iter) {
    printf("%s\n", iter->c_str());
  }

  return false;
}

}  // namespace
<commit_msg>Fix a problem in browser_tests launcher which was interpreting the line 'YOU HAVE x FLAKY TESTS' as a test name.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/test/test_launcher/test_runner.h"

#include <vector>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "base/string_util.h"

namespace {

const char kGTestListTestsFlag[] = "gtest_list_tests";
const char kGTestRunDisabledTestsFlag[] = "gtest_also_run_disabled_tests";

// Retrieves the list of tests to run by running gtest with the
// --gtest_list_tests flag in a forked process and parsing its output.
// |command_line| should contain the command line used to start the browser
// test launcher, it is expected that it does not contain the
// --gtest_list_tests flag already.
// Note: we cannot implement this in-process for InProcessTestRunner as GTest
// prints to the stdout and there are no good way of temporarily redirecting
// outputs.
bool GetTestList(const CommandLine& command_line,
                 std::vector<std::string>* test_list) {
  DCHECK(!command_line.HasSwitch(kGTestListTestsFlag));

  // Run ourselves with the --gtest_list_tests option and read the output.
  CommandLine new_command_line(command_line);
  new_command_line.AppendSwitch(kGTestListTestsFlag);
  std::string output;
  if (!base::GetAppOutput(new_command_line, &output))
    return false;

  // The output looks like:
  // TestCase.
  //   Test1
  //   Test2
  // OtherTestCase.
  //   FooTest
  // ...
  std::vector<std::string> lines;
  SplitString(output, '\n', &lines);

  std::string test_case;
  for (std::vector<std::string>::const_iterator iter = lines.begin();
       iter != lines.end(); ++iter) {
    std::string line = *iter;

    // Ignore empty and metadata lines (like "YOU HAVE x FLAKY TESTS").
    if (line.empty() || line.find(' ') != std::string::npos)
      continue;

    if (line[line.size() - 1] == '.') {
      // This is a new test case.
      test_case = line;
      continue;
    }

    if (!command_line.HasSwitch(kGTestRunDisabledTestsFlag) &&
        line.find("DISABLED") != std::string::npos)
      continue;  // Skip disabled tests.

    // We are dealing with a test.
    test_list->push_back(test_case + line);
  }
  return true;
}

}  // namespace

namespace tests {

TestRunner::TestRunner() {
}

TestRunner::~TestRunner() {
}

bool RunTests(const TestRunnerFactory& test_runner_factory) {
  const CommandLine* command_line = CommandLine::ForCurrentProcess();

  DCHECK(!command_line->HasSwitch(kGTestListTestsFlag));

  // First let's get the list of tests we need to run.
  std::vector<std::string> test_list;
  if (!GetTestList(*command_line, &test_list)) {
    printf("Failed to retrieve the tests to run.\n");
    return false;
  }

  if (test_list.empty()) {
    printf("No tests to run.\n");
    return false;
  }

  int test_run_count = 0;
  std::vector<std::string> failed_tests;
  for (std::vector<std::string>::const_iterator iter = test_list.begin();
       iter != test_list.end(); ++iter) {
    std::string test_name = *iter;
    scoped_ptr<TestRunner> test_runner(test_runner_factory.CreateTestRunner());
    if (!test_runner.get() || !test_runner->Init())
      return false;
    test_run_count++;
    if (!test_runner->RunTest(test_name.c_str())) {
      if (std::find(failed_tests.begin(), failed_tests.end(), test_name) ==
          failed_tests.end()) {
        failed_tests.push_back(*iter);
      }
    }
  }

  printf("%d test%s run\n", test_run_count, test_run_count > 1 ? "s" : "");
  printf("%d test%s failed\n", static_cast<int>(failed_tests.size()),
                               failed_tests.size() > 1 ? "s" : "");
  if (failed_tests.empty())
    return true;

  printf("Failing tests:\n");
  for (std::vector<std::string>::const_iterator iter = failed_tests.begin();
       iter != failed_tests.end(); ++iter) {
    printf("%s\n", iter->c_str());
  }

  return false;
}

}  // namespace
<|endoftext|>