<commit_before>//============================================================================
// include/vsmc/opencl/cl_manip.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_OPENCL_CL_MANIP_HPP
#define VSMC_OPENCL_CL_MANIP_HPP

#include <vsmc/internal/common.hpp>
#include <vsmc/opencl/internal/cl_wrapper.hpp>

namespace vsmc {

/// \brief Query the preferred factor of local size
/// \ingroup OpenCL
///
/// \param kern An OpenCL kernel
/// \param dev An OpenCL device
/// \param factor Multiplier factor of local size for optimzied performance
/// \param lmax Maximum of the local size
/// \param lmulmax Maximum of the local size that is a multiple of the factor
inline void cl_minmax_local_size (
        const ::cl::Kernel &kern, const ::cl::Device &dev,
        std::size_t &factor, std::size_t &lmax, std::size_t &lmulmax)
{
    try {
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, &factor);
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_WORK_GROUP_SIZE, &lmax);
        if (factor == 0 || factor > lmax) {
            factor = lmax = lmulmax = 0;
            return;
        }
        lmulmax = (lmax / factor) * factor;
    } catch (::cl::Error) {
        factor = lmax = lmulmax = 0;
    }
}

/// \brief The minimum global size that is a multiple of the local size
/// \ingroup OpenCL
inline std::size_t cl_min_global_size (std::size_t N, std::size_t local_size)
{
    if (local_size == 0)
        return N;

    return (local_size && N % local_size) ?
        (N / local_size + 1) * local_size : N;
}

/// \brief The preferred global and local size
/// \ingroup OpenCL
///
/// \return The difference between the preferred global size and the N
inline std::size_t cl_preferred_work_size (std::size_t N,
        const ::cl::Kernel &kern, const ::cl::Device &dev,
        std::size_t &global_size, std::size_t &local_size)
{
    cl::size_t<3> reqd_size;
    try {
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_COMPILE_WORK_GROUP_SIZE, &reqd_size);
    } catch (::cl::Error) {
        reqd_size[0] = 0;
    }

    if (reqd_size[0] != 0) {
        local_size = reqd_size[0];
        global_size = cl_min_global_size(N, local_size);

        return global_size - N;
    }

    std::size_t factor;
    std::size_t lmax;
    std::size_t lmulmax;
    cl_minmax_local_size(kern, dev, factor, lmax, lmulmax);
    if (lmax == 0) {
        global_size = N;
        local_size = 0;

        return global_size - N;
    }

    local_size = lmulmax;
    global_size = cl_min_global_size(N, local_size);
    std::size_t diff_size = global_size - N;
    std::size_t maxmul = lmulmax / factor;
    for (std::size_t mul = maxmul; mul >= 1; --mul) {
        std::size_t l = mul * factor;
        std::size_t g = cl_min_global_size(N, l);
        std::size_t d = g - N;
        if (d < diff_size) {
            local_size = l;
            global_size = g;
            diff_size = d;
        }
    }

    return diff_size;
}

inline void cl_set_kernel_args (::cl::Kernel &, cl_uint) {}

#if VSMC_HAS_CXX11_VARIADIC_TEMPLATES
/// \brief Set OpenCL kernel arguments
/// \ingroup OpenCL
///
/// \details
/// The first argument `arg1` is set with index `offset` and the next with
/// index `offset + 1` and so on. For C++11 implementations that support
/// variadic template, there can be arbitrary number of arguments (or limited
/// by the compiler's implementation). Otherwise this function supports up to
/// 16 arguments.
template <typename Arg1, typename... Args>
inline void cl_set_kernel_args (::cl::Kernel &kern, cl_uint offset,
        const Arg1 &arg1, const Args &... args)
{
    kern.setArg(offset, arg1);
    cl_set_kernel_args(kern, offset + 1, args...);
}
#else // VSMC_HAS_CXX11_VARIADIC_TEMPLATES
#include <vsmc/opencl/internal/cl_set_kernel_args.hpp>
#endif // VSMC_HAS_CXX11_VARIADIC_TEMPLATES

} // namespace vsmc

#endif // VSMC_OPENCL_CL_MANIP_HPP
<commit_msg>prefer small group size<commit_after>//============================================================================
// include/vsmc/opencl/cl_manip.hpp
//----------------------------------------------------------------------------
//
//                         vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================

#ifndef VSMC_OPENCL_CL_MANIP_HPP
#define VSMC_OPENCL_CL_MANIP_HPP

#include <vsmc/internal/common.hpp>
#include <vsmc/opencl/internal/cl_wrapper.hpp>

namespace vsmc {

/// \brief Query the preferred factor of local size
/// \ingroup OpenCL
///
/// \param kern An OpenCL kernel
/// \param dev An OpenCL device
/// \param factor Multiplier factor of local size for optimzied performance
/// \param lmax Maximum of the local size
/// \param mmax Maximum of the multiplier of the factor
inline void cl_minmax_local_size (
        const ::cl::Kernel &kern, const ::cl::Device &dev,
        std::size_t &factor, std::size_t &lmax, std::size_t &mmax)
{
    try {
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, &factor);
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_WORK_GROUP_SIZE, &lmax);
        if (factor == 0 || factor > lmax) {
            factor = lmax = mmax = 0;
            return;
        }
        mmax = lmax / factor;
    } catch (::cl::Error) {
        factor = lmax = mmax = 0;
    }
}

/// \brief The minimum global size that is a multiple of the local size
/// \ingroup OpenCL
inline std::size_t cl_min_global_size (std::size_t N, std::size_t local_size)
{
    if (local_size == 0)
        return N;

    return (local_size && N % local_size) ?
        (N / local_size + 1) * local_size : N;
}

/// \brief The preferred global and local size
/// \ingroup OpenCL
///
/// \return The difference between the preferred global size and the N
inline std::size_t cl_preferred_work_size (std::size_t N,
        const ::cl::Kernel &kern, const ::cl::Device &dev,
        std::size_t &global_size, std::size_t &local_size)
{
    cl::size_t<3> reqd_size;
    try {
        kern.getWorkGroupInfo(dev,
                CL_KERNEL_COMPILE_WORK_GROUP_SIZE, &reqd_size);
    } catch (::cl::Error) {
        reqd_size[0] = 0;
    }

    if (reqd_size[0] != 0) {
        local_size = reqd_size[0];
        global_size = cl_min_global_size(N, local_size);

        return global_size - N;
    }

    std::size_t factor;
    std::size_t lmax;
    std::size_t mmax;
    cl_minmax_local_size(kern, dev, factor, lmax, mmax);
    if (lmax == 0) {
        global_size = N;
        local_size = 0;

        return global_size - N;
    }

    local_size = factor;
    global_size = cl_min_global_size(N, local_size);
    std::size_t diff_size = global_size - N;
    for (std::size_t m = 1; m <= mmax; ++m) {
        std::size_t l = m * factor;
        std::size_t g = cl_min_global_size(N, l);
        std::size_t d = g - N;
        if (d < diff_size) {
            local_size = l;
            global_size = g;
            diff_size = d;
        }
    }

    return diff_size;
}

inline void cl_set_kernel_args (::cl::Kernel &, cl_uint) {}

#if VSMC_HAS_CXX11_VARIADIC_TEMPLATES
/// \brief Set OpenCL kernel arguments
/// \ingroup OpenCL
///
/// \details
/// The first argument `arg1` is set with index `offset` and the next with
/// index `offset + 1` and so on. For C++11 implementations that support
/// variadic template, there can be arbitrary number of arguments (or limited
/// by the compiler's implementation). Otherwise this function supports up to
/// 16 arguments.
template <typename Arg1, typename... Args>
inline void cl_set_kernel_args (::cl::Kernel &kern, cl_uint offset,
        const Arg1 &arg1, const Args &... args)
{
    kern.setArg(offset, arg1);
    cl_set_kernel_args(kern, offset + 1, args...);
}
#else // VSMC_HAS_CXX11_VARIADIC_TEMPLATES
#include <vsmc/opencl/internal/cl_set_kernel_args.hpp>
#endif // VSMC_HAS_CXX11_VARIADIC_TEMPLATES

} // namespace vsmc

#endif // VSMC_OPENCL_CL_MANIP_HPP
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/utility/ivf_file_writer.h"

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"

namespace webrtc {

IvfFileWriter::IvfFileWriter(const std::string& file_name,
                             std::unique_ptr<FileWrapper> file,
                             VideoCodecType codec_type)
    : codec_type_(codec_type),
      num_frames_(0),
      width_(0),
      height_(0),
      last_timestamp_(-1),
      using_capture_timestamps_(false),
      file_name_(file_name),
      file_(std::move(file)) {}

IvfFileWriter::~IvfFileWriter() {
  Close();
}

const size_t kIvfHeaderSize = 32;

std::unique_ptr<IvfFileWriter> IvfFileWriter::Open(const std::string& file_name,
                                                   VideoCodecType codec_type) {
  std::unique_ptr<IvfFileWriter> file_writer;
  std::unique_ptr<FileWrapper> file(FileWrapper::Create());
  if (file->OpenFile(file_name.c_str(), false) != 0)
    return file_writer;

  file_writer.reset(new IvfFileWriter(
      file_name, std::unique_ptr<FileWrapper>(std::move(file)), codec_type));
  if (!file_writer->WriteHeader())
    file_writer.reset();

  return file_writer;
}

bool IvfFileWriter::WriteHeader() {
  if (file_->Rewind() != 0) {
    LOG(LS_WARNING) << "Unable to rewind output file " << file_name_;
    return false;
  }

  uint8_t ivf_header[kIvfHeaderSize] = {0};
  ivf_header[0] = 'D';
  ivf_header[1] = 'K';
  ivf_header[2] = 'I';
  ivf_header[3] = 'F';
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[4], 0);   // Version.
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[6], 32);  // Header size.

  switch (codec_type_) {
    case kVideoCodecVP8:
      ivf_header[8] = 'V';
      ivf_header[9] = 'P';
      ivf_header[10] = '8';
      ivf_header[11] = '0';
      break;
    case kVideoCodecVP9:
      ivf_header[8] = 'V';
      ivf_header[9] = 'P';
      ivf_header[10] = '9';
      ivf_header[11] = '0';
      break;
    case kVideoCodecH264:
      ivf_header[8] = 'H';
      ivf_header[9] = '2';
      ivf_header[10] = '6';
      ivf_header[11] = '4';
      break;
    default:
      LOG(LS_ERROR) << "Unknown CODEC type: " << codec_type_;
      return false;
  }

  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[12], width_);
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[14], height_);
  // Render timestamps are in ms (1/1000 scale), while RTP timestamps use a
  // 90kHz clock.
  ByteWriter<uint32_t>::WriteLittleEndian(
      &ivf_header[16], using_capture_timestamps_ ? 1000 : 90000);
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[20], 1);
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[24],
                                          static_cast<uint32_t>(num_frames_));
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[28], 0);  // Reserved.

  if (!file_->Write(ivf_header, kIvfHeaderSize)) {
    LOG(LS_ERROR) << "Unable to write IVF header for file " << file_name_;
    return false;
  }

  return true;
}

bool IvfFileWriter::InitFromFirstFrame(const EncodedImage& encoded_image) {
  width_ = encoded_image._encodedWidth;
  height_ = encoded_image._encodedHeight;
  RTC_CHECK_GT(width_, 0);
  RTC_CHECK_GT(height_, 0);
  using_capture_timestamps_ = encoded_image._timeStamp == 0;

  if (!WriteHeader())
    return false;

  std::string codec_name;
  switch (codec_type_) {
    case kRtpVideoVp8:
      codec_name = "VP8";
      break;
    case kRtpVideoVp9:
      codec_name = "VP9";
      break;
    case kRtpVideoH264:
      codec_name = "H264";
      break;
    default:
      codec_name = "Unkown";
  }
  LOG(LS_WARNING) << "Created IVF file " << file_name_
                  << " for codec data of type " << codec_name
                  << " at resolution " << width_ << " x " << height_
                  << ", using " << (using_capture_timestamps_ ? "1" : "90")
                  << "kHz clock resolution.";
  return true;
}

bool IvfFileWriter::WriteFrame(const EncodedImage& encoded_image) {
  RTC_DCHECK(file_->Open());

  if (num_frames_ == 0 && !InitFromFirstFrame(encoded_image))
    return false;

  if ((encoded_image._encodedWidth > 0 || encoded_image._encodedHeight > 0) &&
      (encoded_image._encodedHeight != height_ ||
       encoded_image._encodedWidth != width_)) {
    LOG(LS_WARNING)
        << "Incomig frame has diffferent resolution then previous: (" << width_
        << "x" << height_ << ") -> (" << encoded_image._encodedWidth << "x"
        << encoded_image._encodedHeight << ")";
  }

  int64_t timestamp = using_capture_timestamps_
                          ? encoded_image.capture_time_ms_
                          : wrap_handler_.Unwrap(encoded_image._timeStamp);
  if (last_timestamp_ != -1 && timestamp <= last_timestamp_) {
    LOG(LS_WARNING) << "Timestamp no increasing: " << last_timestamp_ << " -> "
                    << timestamp;
  }
  last_timestamp_ = timestamp;

  const size_t kFrameHeaderSize = 12;
  uint8_t frame_header[kFrameHeaderSize] = {};
  ByteWriter<uint32_t>::WriteLittleEndian(
      &frame_header[0], static_cast<uint32_t>(encoded_image._length));
  ByteWriter<uint64_t>::WriteLittleEndian(&frame_header[4], timestamp);
  if (!file_->Write(frame_header, kFrameHeaderSize) ||
      !file_->Write(encoded_image._buffer, encoded_image._length)) {
    LOG(LS_ERROR) << "Unable to write frame to file " << file_name_;
    return false;
  }

  ++num_frames_;
  return true;
}

bool IvfFileWriter::Close() {
  if (!file_->Open())
    return false;

  if (num_frames_ == 0) {
    // No frame written to file, close and remove it entirely if possible.
    file_->CloseFile();
    if (remove(file_name_.c_str()) != 0)
      LOG(LS_WARNING) << "Failed to remove empty IVF file " << file_name_;

    return true;
  }

  return WriteHeader() && (file_->CloseFile() == 0);
}

}  // namespace webrtc
<commit_msg>Fix codec name logging in ivf_file_writer.cc<commit_after>/*
 *  Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/modules/video_coding/utility/ivf_file_writer.h"

#include "webrtc/base/checks.h"
#include "webrtc/base/logging.h"
#include "webrtc/modules/rtp_rtcp/source/byte_io.h"

namespace webrtc {

IvfFileWriter::IvfFileWriter(const std::string& file_name,
                             std::unique_ptr<FileWrapper> file,
                             VideoCodecType codec_type)
    : codec_type_(codec_type),
      num_frames_(0),
      width_(0),
      height_(0),
      last_timestamp_(-1),
      using_capture_timestamps_(false),
      file_name_(file_name),
      file_(std::move(file)) {}

IvfFileWriter::~IvfFileWriter() {
  Close();
}

const size_t kIvfHeaderSize = 32;

std::unique_ptr<IvfFileWriter> IvfFileWriter::Open(const std::string& file_name,
                                                   VideoCodecType codec_type) {
  std::unique_ptr<IvfFileWriter> file_writer;
  std::unique_ptr<FileWrapper> file(FileWrapper::Create());
  if (file->OpenFile(file_name.c_str(), false) != 0)
    return file_writer;

  file_writer.reset(new IvfFileWriter(
      file_name, std::unique_ptr<FileWrapper>(std::move(file)), codec_type));
  if (!file_writer->WriteHeader())
    file_writer.reset();

  return file_writer;
}

bool IvfFileWriter::WriteHeader() {
  if (file_->Rewind() != 0) {
    LOG(LS_WARNING) << "Unable to rewind output file " << file_name_;
    return false;
  }

  uint8_t ivf_header[kIvfHeaderSize] = {0};
  ivf_header[0] = 'D';
  ivf_header[1] = 'K';
  ivf_header[2] = 'I';
  ivf_header[3] = 'F';
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[4], 0);   // Version.
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[6], 32);  // Header size.

  switch (codec_type_) {
    case kVideoCodecVP8:
      ivf_header[8] = 'V';
      ivf_header[9] = 'P';
      ivf_header[10] = '8';
      ivf_header[11] = '0';
      break;
    case kVideoCodecVP9:
      ivf_header[8] = 'V';
      ivf_header[9] = 'P';
      ivf_header[10] = '9';
      ivf_header[11] = '0';
      break;
    case kVideoCodecH264:
      ivf_header[8] = 'H';
      ivf_header[9] = '2';
      ivf_header[10] = '6';
      ivf_header[11] = '4';
      break;
    default:
      LOG(LS_ERROR) << "Unknown CODEC type: " << codec_type_;
      return false;
  }

  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[12], width_);
  ByteWriter<uint16_t>::WriteLittleEndian(&ivf_header[14], height_);
  // Render timestamps are in ms (1/1000 scale), while RTP timestamps use a
  // 90kHz clock.
  ByteWriter<uint32_t>::WriteLittleEndian(
      &ivf_header[16], using_capture_timestamps_ ? 1000 : 90000);
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[20], 1);
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[24],
                                          static_cast<uint32_t>(num_frames_));
  ByteWriter<uint32_t>::WriteLittleEndian(&ivf_header[28], 0);  // Reserved.

  if (!file_->Write(ivf_header, kIvfHeaderSize)) {
    LOG(LS_ERROR) << "Unable to write IVF header for file " << file_name_;
    return false;
  }

  return true;
}

bool IvfFileWriter::InitFromFirstFrame(const EncodedImage& encoded_image) {
  width_ = encoded_image._encodedWidth;
  height_ = encoded_image._encodedHeight;
  RTC_CHECK_GT(width_, 0);
  RTC_CHECK_GT(height_, 0);
  using_capture_timestamps_ = encoded_image._timeStamp == 0;

  if (!WriteHeader())
    return false;

  std::string codec_name;
  switch (codec_type_) {
    case kVideoCodecVP8:
      codec_name = "VP8";
      break;
    case kVideoCodecVP9:
      codec_name = "VP9";
      break;
    case kVideoCodecH264:
      codec_name = "H264";
      break;
    default:
      codec_name = "Unknown";
  }
  LOG(LS_WARNING) << "Created IVF file " << file_name_
                  << " for codec data of type " << codec_name
                  << " at resolution " << width_ << " x " << height_
                  << ", using " << (using_capture_timestamps_ ? "1" : "90")
                  << "kHz clock resolution.";
  return true;
}

bool IvfFileWriter::WriteFrame(const EncodedImage& encoded_image) {
  RTC_DCHECK(file_->Open());

  if (num_frames_ == 0 && !InitFromFirstFrame(encoded_image))
    return false;

  if ((encoded_image._encodedWidth > 0 || encoded_image._encodedHeight > 0) &&
      (encoded_image._encodedHeight != height_ ||
       encoded_image._encodedWidth != width_)) {
    LOG(LS_WARNING)
        << "Incomig frame has diffferent resolution then previous: (" << width_
        << "x" << height_ << ") -> (" << encoded_image._encodedWidth << "x"
        << encoded_image._encodedHeight << ")";
  }

  int64_t timestamp = using_capture_timestamps_
                          ? encoded_image.capture_time_ms_
                          : wrap_handler_.Unwrap(encoded_image._timeStamp);
  if (last_timestamp_ != -1 && timestamp <= last_timestamp_) {
    LOG(LS_WARNING) << "Timestamp no increasing: " << last_timestamp_ << " -> "
                    << timestamp;
  }
  last_timestamp_ = timestamp;

  const size_t kFrameHeaderSize = 12;
  uint8_t frame_header[kFrameHeaderSize] = {};
  ByteWriter<uint32_t>::WriteLittleEndian(
      &frame_header[0], static_cast<uint32_t>(encoded_image._length));
  ByteWriter<uint64_t>::WriteLittleEndian(&frame_header[4], timestamp);
  if (!file_->Write(frame_header, kFrameHeaderSize) ||
      !file_->Write(encoded_image._buffer, encoded_image._length)) {
    LOG(LS_ERROR) << "Unable to write frame to file " << file_name_;
    return false;
  }

  ++num_frames_;
  return true;
}

bool IvfFileWriter::Close() {
  if (!file_->Open())
    return false;

  if (num_frames_ == 0) {
    // No frame written to file, close and remove it entirely if possible.
    file_->CloseFile();
    if (remove(file_name_.c_str()) != 0)
      LOG(LS_WARNING) << "Failed to remove empty IVF file " << file_name_;

    return true;
  }

  return WriteHeader() && (file_->CloseFile() == 0);
}

}  // namespace webrtc
<|endoftext|>


<commit_before>#include "GameController.h"

#include "Tools/Debug/DebugRequest.h"
#include <PlatformInterface/Platform.h>

GameController::GameController()
  :
  lastWhistleCount(0),
  returnMessage(GameReturnData::alive)
{
  DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);

  // TODO: make it parameters?
  // load values from config
  const Configuration& config = naoth::Platform::getInstance().theConfiguration;

  if (config.hasKey("player", "NumOfPlayer")) {
    getPlayerInfo().playersPerTeam = config.getInt("player", "NumOfPlayer");
  } else {
    std::cerr << "[GameData] " << "No number of players (NumOfPlayers) given" << std::endl;
  }

  if (config.hasKey("player", "PlayerNumber")) {
    getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
  } else {
    std::cerr << "[PlayerInfo] " << "No player number (PlayerNumber) given" << std::endl;
    getPlayerInfo().playerNumber = 3;
  }

  if (config.hasKey("player", "TeamNumber")) {
    getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
  } else {
    std::cerr << "[PlayerInfo] " << "No team number (TeamNumber) given" << std::endl;
    getPlayerInfo().teamNumber = 0;
  }

  if (config.hasKey("player", "TeamName")) {
    getPlayerInfo().teamName = config.getString("player", "TeamName");
  } else {
    std::cerr << "[PlayerInfo] " << "No team name (TeamName) given" << std::endl;
    getPlayerInfo().teamName = "unknown";
  }

  // NOTE: default team color is red
  getPlayerInfo().teamColor = GameData::red;
  if (config.hasKey("player", "TeamColor"))
  {
    getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString("player", "TeamColor"));
    if (getPlayerInfo().teamColor == GameData::unknown_team_color)
    {
      std::cerr << "[GameData] " << "Invalid team color (TeamColor) \""
        << config.getString("player", "TeamColor") << "\" given" << std::endl;
    }
  } else {
    std::cerr << "[GameData] " << "No team color (TeamColor) given" << std::endl;
  }
}

void GameController::execute()
{
  PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;
  GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;

  // try update from the game controller message
  if ( getGameData().valid )
  {
    getPlayerInfo().update(getGameData());

    // reset return message if old message was accepted
    if( returnMessage == GameReturnData::manual_penalise
        && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)
    {
      returnMessage = GameReturnData::alive;
    }
    else if(returnMessage == GameReturnData::manual_unpenalise
            && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)
    {
      returnMessage = GameReturnData::alive;
    }
  }

  // keep the manual penalized state
  if(returnMessage == GameReturnData::manual_penalise) {
    getPlayerInfo().robotState = PlayerInfo::penalized;
  }

  handleButtons();
  handleHeadButtons();

  DEBUG_REQUEST("gamecontroller:initial",
    getPlayerInfo().robotState = PlayerInfo::initial;
  );
  DEBUG_REQUEST("gamecontroller:ready",
    getPlayerInfo().robotState = PlayerInfo::ready;
  );
  DEBUG_REQUEST("gamecontroller:set",
    getPlayerInfo().robotState = PlayerInfo::set;
  );
  DEBUG_REQUEST("gamecontroller:play",
    getPlayerInfo().robotState = PlayerInfo::playing;
  );

  // remember the whistle counter before set
  if(getPlayerInfo().robotState == PlayerInfo::ready) {
    lastWhistleCount = getWhistlePercept().counter;
  }
  // whistle overrides gamecontroller when in set
  else if(getGameData().gameState == GameData::set)
  {
    // switch from set to play
    if(getWhistlePercept().counter > lastWhistleCount) {
      getPlayerInfo().robotState = PlayerInfo::playing;
    }
  }

  if(  oldRobotState != getPlayerInfo().robotState
    || oldTeamColor  != getPlayerInfo().teamColor
    || getPlayerInfo().robotState == PlayerInfo::initial)
  {
    updateLEDs();
  }

  // provide the return message
  getGameReturnData().team = getPlayerInfo().teamNumber;
  getGameReturnData().player = getPlayerInfo().playerNumber;
  getGameReturnData().message = returnMessage;
} // end execute

void GameController::handleButtons()
{
  if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)
  {
    switch (getPlayerInfo().robotState)
    {
    case PlayerInfo::initial:
    case PlayerInfo::ready:
    case PlayerInfo::set:
    case PlayerInfo::playing:
    case PlayerInfo::finished:
    {
      getPlayerInfo().robotState = PlayerInfo::penalized;
      returnMessage = GameReturnData::manual_penalise;
      break;
    }
    case PlayerInfo::penalized:
    {
      getPlayerInfo().robotState = PlayerInfo::playing;
      returnMessage = GameReturnData::manual_unpenalise;
      break;
    }
    default:
      ASSERT(false);
    }
  }

  // re-set team color or kickoff in initial
  if (getPlayerInfo().robotState == PlayerInfo::initial)
  {
    if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )
    {
      // switch team color
      GameData::TeamColor oldColor = getPlayerInfo().teamColor;
      if (oldColor == GameData::blue) {
        getPlayerInfo().teamColor = GameData::red;
      } else if (oldColor == GameData::red) {
        getPlayerInfo().teamColor = GameData::yellow;
      } else if (oldColor == GameData::yellow) {
        getPlayerInfo().teamColor = GameData::black;
      } else if (oldColor == GameData::black) {
        getPlayerInfo().teamColor = GameData::blue;
      } else { // set to red by default
        getPlayerInfo().teamColor = GameData::red;
      }
    }

    if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )
    {
      // switch kick off team
      getPlayerInfo().kickoff = !getPlayerInfo().kickoff;
    }
  }

  // go back from penalized to initial both foot bumpers are pressed for more than 1s
  else if (getPlayerInfo().robotState == PlayerInfo::penalized &&
    (  getButtonState()[ButtonState::LeftFoot].isPressed &&
       getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )
    &&
    (  getButtonState()[ButtonState::RightFoot].isPressed &&
       getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )
    )
  {
    getPlayerInfo().robotState = PlayerInfo::initial;
    returnMessage = GameReturnData::manual_unpenalise;
  }

} // end handleButtons

void GameController::handleHeadButtons()
{
  getSoundPlayData().mute = true;
  getSoundPlayData().soundFile = "";

  if(   getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED
     && getPlayerInfo().robotState == PlayerInfo::initial)
  {
    int playerNumber = getPlayerInfo().playerNumber;
    if(playerNumber <= 9)
    {
      std::stringstream ssWav;
      ssWav << playerNumber;
      ssWav << ".wav";
      getSoundPlayData().mute = false;
      getSoundPlayData().soundFile = ssWav.str();
    }
  }
}

void GameController::updateLEDs()
{
  // reset
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;

  for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
  {
    getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;
  }

  // show game state in torso
  switch (getPlayerInfo().robotState)
  {
    case PlayerInfo::ready:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
      break;
    case PlayerInfo::set:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    case PlayerInfo::playing:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      break;
    case PlayerInfo::penalized:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    default:
      break;
  }

  // show team color on left foot
  if (getPlayerInfo().teamColor == GameData::red)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;
  }
  else if (getPlayerInfo().teamColor == GameData::blue)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
  }
  else if(getPlayerInfo().teamColor == GameData::yellow)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;
  }
  else if(getPlayerInfo().teamColor == GameData::black)
  {
      // LED off
  }

  // show kickoff state on right foot and head in initial, ready and set
  if (getPlayerInfo().robotState == PlayerInfo::initial
    || getPlayerInfo().robotState == PlayerInfo::ready
    || getPlayerInfo().robotState == PlayerInfo::set)
  {
    if (getPlayerInfo().kickoff)
    {
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;

      for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
      {
        getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;
      }
    }
  }
} // end updateLEDs

GameController::~GameController()
{
}
<commit_msg>bugfix: debug penalize works again<commit_after>#include "GameController.h"

#include "Tools/Debug/DebugRequest.h"
#include <PlatformInterface/Platform.h>

GameController::GameController()
  :
  lastWhistleCount(0),
  returnMessage(GameReturnData::alive)
{
  DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
  DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);

  // TODO: make it parameters?
  // load values from config
  const Configuration& config = naoth::Platform::getInstance().theConfiguration;

  if (config.hasKey("player", "NumOfPlayer")) {
    getPlayerInfo().playersPerTeam = config.getInt("player", "NumOfPlayer");
  } else {
    std::cerr << "[GameData] " << "No number of players (NumOfPlayers) given" << std::endl;
  }

  if (config.hasKey("player", "PlayerNumber")) {
    getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
  } else {
    std::cerr << "[PlayerInfo] " << "No player number (PlayerNumber) given" << std::endl;
    getPlayerInfo().playerNumber = 3;
  }

  if (config.hasKey("player", "TeamNumber")) {
    getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
  } else {
    std::cerr << "[PlayerInfo] " << "No team number (TeamNumber) given" << std::endl;
    getPlayerInfo().teamNumber = 0;
  }

  if (config.hasKey("player", "TeamName")) {
    getPlayerInfo().teamName = config.getString("player", "TeamName");
  } else {
    std::cerr << "[PlayerInfo] " << "No team name (TeamName) given" << std::endl;
    getPlayerInfo().teamName = "unknown";
  }

  // NOTE: default team color is red
  getPlayerInfo().teamColor = GameData::red;
  if (config.hasKey("player", "TeamColor"))
  {
    getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString("player", "TeamColor"));
    if (getPlayerInfo().teamColor == GameData::unknown_team_color)
    {
      std::cerr << "[GameData] " << "Invalid team color (TeamColor) \""
        << config.getString("player", "TeamColor") << "\" given" << std::endl;
    }
  } else {
    std::cerr << "[GameData] " << "No team color (TeamColor) given" << std::endl;
  }
}

void GameController::execute()
{
  PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;
  GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;

  // try update from the game controller message
  if ( getGameData().valid )
  {
    getPlayerInfo().update(getGameData());

    // reset return message if old message was accepted
    if( returnMessage == GameReturnData::manual_penalise
        && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)
    {
      returnMessage = GameReturnData::alive;
    }
    else if(returnMessage == GameReturnData::manual_unpenalise
            && getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)
    {
      returnMessage = GameReturnData::alive;
    }
  }

  // keep the manual penalized state
  if(returnMessage == GameReturnData::manual_penalise) {
    getPlayerInfo().robotState = PlayerInfo::penalized;
  }

  handleButtons();
  handleHeadButtons();

  DEBUG_REQUEST("gamecontroller:initial",
    getPlayerInfo().robotState = PlayerInfo::initial;
  );
  DEBUG_REQUEST("gamecontroller:ready",
    getPlayerInfo().robotState = PlayerInfo::ready;
  );
  DEBUG_REQUEST("gamecontroller:set",
    getPlayerInfo().robotState = PlayerInfo::set;
  );
  DEBUG_REQUEST("gamecontroller:play",
    getPlayerInfo().robotState = PlayerInfo::playing;
  );
  DEBUG_REQUEST("gamecontroller:penalized",
    getPlayerInfo().robotState = PlayerInfo::penalized;
  );

  // remember the whistle counter before set
  if(getPlayerInfo().robotState == PlayerInfo::ready) {
    lastWhistleCount = getWhistlePercept().counter;
  }
  // whistle overrides gamecontroller when in set
  else if(getGameData().gameState == GameData::set)
  {
    // switch from set to play
    if(getWhistlePercept().counter > lastWhistleCount) {
      getPlayerInfo().robotState = PlayerInfo::playing;
    }
  }

  if(  oldRobotState != getPlayerInfo().robotState
    || oldTeamColor  != getPlayerInfo().teamColor
    || getPlayerInfo().robotState == PlayerInfo::initial)
  {
    updateLEDs();
  }

  // provide the return message
  getGameReturnData().team = getPlayerInfo().teamNumber;
  getGameReturnData().player = getPlayerInfo().playerNumber;
  getGameReturnData().message = returnMessage;
} // end execute

void GameController::handleButtons()
{
  if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)
  {
    switch (getPlayerInfo().robotState)
    {
    case PlayerInfo::initial:
    case PlayerInfo::ready:
    case PlayerInfo::set:
    case PlayerInfo::playing:
    case PlayerInfo::finished:
    {
      getPlayerInfo().robotState = PlayerInfo::penalized;
      returnMessage = GameReturnData::manual_penalise;
      break;
    }
    case PlayerInfo::penalized:
    {
      getPlayerInfo().robotState = PlayerInfo::playing;
      returnMessage = GameReturnData::manual_unpenalise;
      break;
    }
    default:
      ASSERT(false);
    }
  }

  // re-set team color or kickoff in initial
  if (getPlayerInfo().robotState == PlayerInfo::initial)
  {
    if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )
    {
      // switch team color
      GameData::TeamColor oldColor = getPlayerInfo().teamColor;
      if (oldColor == GameData::blue) {
        getPlayerInfo().teamColor = GameData::red;
      } else if (oldColor == GameData::red) {
        getPlayerInfo().teamColor = GameData::yellow;
      } else if (oldColor == GameData::yellow) {
        getPlayerInfo().teamColor = GameData::black;
      } else if (oldColor == GameData::black) {
        getPlayerInfo().teamColor = GameData::blue;
      } else { // set to red by default
        getPlayerInfo().teamColor = GameData::red;
      }
    }

    if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )
    {
      // switch kick off team
      getPlayerInfo().kickoff = !getPlayerInfo().kickoff;
    }
  }

  // go back from penalized to initial both foot bumpers are pressed for more than 1s
  else if (getPlayerInfo().robotState == PlayerInfo::penalized &&
    (  getButtonState()[ButtonState::LeftFoot].isPressed &&
       getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )
    &&
    (  getButtonState()[ButtonState::RightFoot].isPressed &&
       getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )
    )
  {
    getPlayerInfo().robotState = PlayerInfo::initial;
    returnMessage = GameReturnData::manual_unpenalise;
  }

} // end handleButtons

void GameController::handleHeadButtons()
{
  getSoundPlayData().mute = true;
  getSoundPlayData().soundFile = "";

  if(   getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED
     && getPlayerInfo().robotState == PlayerInfo::initial)
  {
    int playerNumber = getPlayerInfo().playerNumber;
    if(playerNumber <= 9)
    {
      std::stringstream ssWav;
      ssWav << playerNumber;
      ssWav << ".wav";
      getSoundPlayData().mute = false;
      getSoundPlayData().soundFile = ssWav.str();
    }
  }
}

void GameController::updateLEDs()
{
  // reset
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;

  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
  getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;

  for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
  {
    getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;
  }

  // show game state in torso
  switch (getPlayerInfo().robotState)
  {
    case PlayerInfo::ready:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
      break;
    case PlayerInfo::set:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    case PlayerInfo::playing:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
      break;
    case PlayerInfo::penalized:
        getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
      break;
    default:
      break;
  }

  // show team color on left foot
  if (getPlayerInfo().teamColor == GameData::red)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;
  }
  else if (getPlayerInfo().teamColor == GameData::blue)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
  }
  else if(getPlayerInfo().teamColor == GameData::yellow)
  {
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
    getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;
  }
  else if(getPlayerInfo().teamColor == GameData::black)
  {
      // LED off
  }

  // show kickoff state on right foot and head in initial, ready and set
  if (getPlayerInfo().robotState == PlayerInfo::initial
    || getPlayerInfo().robotState == PlayerInfo::ready
    || getPlayerInfo().robotState == PlayerInfo::set)
  {
    if (getPlayerInfo().kickoff)
    {
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
      getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;

      for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
      {
        getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;
      }
    }
  }
} // end updateLEDs

GameController::~GameController()
{
}
<|endoftext|>


<commit_before>/*
** Copyright 2009-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef BAM_CCB_CONFIGURATION_BOOL_EXPRESSION_HH
#  define CCB_BAM_CONFIGURATION_BOOL_EXPRESSION_HH

#  include <string>
#  include "com/centreon/broker/namespace.hh"

CCB_BEGIN()

namespace                 bam{
  namespace               configuration{
    /**
     *@class bool_expression bool_expression.hh  "com/centreon/broker/bam/configuration/bool_expression.h"
     *
     *@brief A pseudo-kpi triggered by a the value of a boolean expression.
     */
    class                   bool_expression {
    public:
                            bool_expression(
			      unsigned int id = 0,
			      double impact = 0.0,
			      std::string const& expression = "",
			      bool impact_if = false,
			      bool state = false);
                            bool_expression(bool_expression const& right);
      bool_expression&      operator=(bool_expression const& right);
                            ~bool_expression();

      unsigned int          get_id() const;
      double                get_impact() const;
      std::string const&    get_expression() const;
      bool                  get_impact_if() const;
      bool                  get_state() const;

      void                  set_impact(double d);
      void                  set_expression(std::string const& s);
      void                  set_impact_if(bool b);
      void                  set_state(bool s);

    private:
      unsigned int          _id;
      double                _impact;
      std::string           _expression;
      bool                  _impact_if;
      bool                  _state;
    };
  }
}

CCB_END()

#endif // !CCB_BAM_CONFIGURATION_BOOL_EXPRESSION_HH
<commit_msg>BAM: style update AGAIN on configuration/bool_expression.hh.<commit_after>/*
** Copyright 2009-2014 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#ifndef BAM_CCB_CONFIGURATION_BOOL_EXPRESSION_HH
#  define CCB_BAM_CONFIGURATION_BOOL_EXPRESSION_HH

#  include <string>
#  include "com/centreon/broker/namespace.hh"

CCB_BEGIN()

namespace                   bam {
  namespace                 configuration {
    /**
     *@class bool_expression bool_expression.hh  "com/centreon/broker/bam/configuration/bool_expression.h"
     *
     *@brief A pseudo-kpi triggered by a the value of a boolean expression.
     */
    class                   bool_expression {
    public:
                            bool_expression(
                              unsigned int id = 0,
                              double impact = 0.0,
                              std::string const& expression = "",
                              bool impact_if = false,
                              bool state = false);
                            bool_expression(bool_expression const& right);
                            ~bool_expression();
      bool_expression&      operator=(bool_expression const& right);

      unsigned int          get_id() const;
      double                get_impact() const;
      std::string const&    get_expression() const;
      bool                  get_impact_if() const;
      bool                  get_state() const;

      void                  set_impact(double d);
      void                  set_expression(std::string const& s);
      void                  set_impact_if(bool b);
      void                  set_state(bool s);

    private:
      unsigned int          _id;
      double                _impact;
      std::string           _expression;
      bool                  _impact_if;
      bool                  _state;
    };
  }
}

CCB_END()

#endif // !CCB_BAM_CONFIGURATION_BOOL_EXPRESSION_HH
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLIndexChapterInfoEntryContext.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: dvo $ $Date: 2000-11-14 14:42:50 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLINDEXCHAPTERINFOENTRYCONTEXT_HXX_
#define _XMLOFF_XMLINDEXCHAPTERINFOENTRYCONTEXT_HXX_

#ifndef _XMLOFF_XMLINDEXSIMPLEENTRYCONTEXT_HXX_
#include "XMLIndexSimpleEntryContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLIndexTemplateContext;

/**
 * Import chapter info index entry templates
 */
class XMLIndexChapterInfoEntryContext : public XMLIndexSimpleEntryContext
{
    // chapter format
    sal_Int16 nChapterInfo;
    sal_Bool bChapterInfoOK;

public:

    TYPEINFO();

    XMLIndexChapterInfoEntryContext(
        SvXMLImport& rImport,
        XMLIndexTemplateContext& rTemplate,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName );

    ~XMLIndexChapterInfoEntryContext();

protected:

    /** process parameters */
    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    /** fill property values for this template entry */
    virtual void FillPropertyValues(
        ::com::sun::star::uno::Sequence<
            ::com::sun::star::beans::PropertyValue> & rValues);
};

#endif
<commit_msg>INTEGRATION: CWS oasis (1.1.290); FILE MERGED 2004/06/16 07:53:55 mib 1.1.290.1: #i20153#: new package URI schema, namespaced conditions<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLIndexChapterInfoEntryContext.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:32:26 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_XMLINDEXCHAPTERINFOENTRYCONTEXT_HXX_
#define _XMLOFF_XMLINDEXCHAPTERINFOENTRYCONTEXT_HXX_

#ifndef _XMLOFF_XMLINDEXSIMPLEENTRYCONTEXT_HXX_
#include "XMLIndexSimpleEntryContext.hxx"
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

namespace com { namespace sun { namespace star {
    namespace xml { namespace sax { class XAttributeList; } }
} } }
namespace rtl { class OUString; }
class XMLIndexTemplateContext;

/**
 * Import chapter info index entry templates
 */
class XMLIndexChapterInfoEntryContext : public XMLIndexSimpleEntryContext
{
    // chapter format
    sal_Int16 nChapterInfo;
    sal_Bool bChapterInfoOK;
    sal_Bool bTOC;

public:

    TYPEINFO();

    XMLIndexChapterInfoEntryContext(
        SvXMLImport& rImport,
        XMLIndexTemplateContext& rTemplate,
        sal_uInt16 nPrfx,
        const ::rtl::OUString& rLocalName,
        sal_Bool bTOC );

    ~XMLIndexChapterInfoEntryContext();

protected:

    /** process parameters */
    virtual void StartElement(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::xml::sax::XAttributeList> & xAttrList);

    /** fill property values for this template entry */
    virtual void FillPropertyValues(
        ::com::sun::star::uno::Sequence<
            ::com::sun::star::beans::PropertyValue> & rValues);
};

#endif
<|endoftext|>


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

#include "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"

namespace chrome {

namespace {

const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";

class TabCaptureApiTest : public ExtensionApiTest {
 public:
  TabCaptureApiTest() {}

  void AddExtensionToCommandLineWhitelist() {
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kWhitelistedExtensionID, kExtensionId);
  }
};

}  // namespace

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests_audio.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_EndToEnd DISABLED_EndToEnd
#else
#define MAYBE_EndToEnd EndToEnd
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif
#if defined(OS_MACOSX)
  // TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.
  // http://crbug.com/174640
  if (base::mac::IsOSSnowLeopard())
    return;
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "end_to_end.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest
#else
#define MAYBE_GetUserMediaTest GetUserMediaTest
#endif
// Test that we can't get tabCapture streams using GetUserMedia directly.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {
  ExtensionTestMessageListener listener("ready", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "get_user_media_test.html")) << message_;

  EXPECT_TRUE(listener.WaitUntilSatisfied());

  content::OpenURLParams params(GURL("about:blank"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();
  int render_process_id = rvh->GetProcess()->GetID();
  int routing_id = rvh->GetRoutingID();

  listener.Reply(base::StringPrintf("%i:%i", render_process_id, routing_id));

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission
#else
#define MAYBE_ActiveTabPermission ActiveTabPermission
#endif
// Make sure tabCapture.capture only works if the tab has been granted
// permission via an extension icon click or the extension is whitelisted.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {
  ExtensionTestMessageListener before_open_tab("ready1", true);
  ExtensionTestMessageListener before_grant_permission("ready2", true);
  ExtensionTestMessageListener before_open_new_tab("ready3", true);
  ExtensionTestMessageListener before_whitelist_extension("ready4", true);

  ASSERT_TRUE(RunExtensionSubtest(
      "tab_capture/experimental", "active_tab_permission_test.html"))
          << message_;

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());
  content::OpenURLParams params(GURL("http://google.com"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);
  before_open_tab.Reply("");

  // Grant permission and make sure capture succeeds.
  EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());
  ExtensionService* extension_service =
      Profile::FromBrowserContext(web_contents->GetBrowserContext())
          ->GetExtensionService();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(kExtensionId, false);
  extensions::TabHelper::FromWebContents(web_contents)
      ->active_tab_permission_granter()->GrantIfRequested(extension);
  before_grant_permission.Reply("");

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());
  browser()->OpenURL(params);
  before_open_new_tab.Reply("");

  // Add extension to whitelist and make sure capture succeeds.
  EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());
  AddExtensionToCommandLineWhitelist();
  before_whitelist_extension.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#elif defined(USE_AURA) || defined(OS_MACOSX)
// These don't always fire fullscreen events when run in tests. Tested manually.
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#elif defined(OS_LINUX)
// Flaky to get out of fullscreen in tests. Tested manually.
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#else
#define MAYBE_FullscreenEvents FullscreenEvents
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_FullscreenEvents) {
#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();

  content::OpenURLParams params(GURL("chrome://version"),
                                content::Referrer(),
                                CURRENT_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  ExtensionTestMessageListener listeners_setup("ready1", true);
  ExtensionTestMessageListener fullscreen_entered("ready2", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "fullscreen_test.html")) << message_;
  EXPECT_TRUE(listeners_setup.WaitUntilSatisfied());

  // Toggle fullscreen after setting up listeners.
  browser()->fullscreen_controller()->ToggleFullscreenModeForTab(web_contents,
                                                                 true);
  listeners_setup.Reply("");

  // Toggle again after JS should have the event.
  EXPECT_TRUE(fullscreen_entered.WaitUntilSatisfied());
  browser()->fullscreen_controller()->ToggleFullscreenModeForTab(web_contents,
                                                                 false);
  fullscreen_entered.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

}  // namespace chrome
<commit_msg>Disable TabCaptureApiTest.ApiTests on cros and linux because it's flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/basictypes.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"

namespace chrome {

namespace {

const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";

class TabCaptureApiTest : public ExtensionApiTest {
 public:
  TabCaptureApiTest() {}

  void AddExtensionToCommandLineWhitelist() {
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kWhitelistedExtensionID, kExtensionId);
  }
};

}  // namespace

// http://crbug.com/261493
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
#define MAYBE_ApiTests DISABLED_ApiTests
#else
#define MAYBE_ApiTests ApiTests
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ApiTests) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests.html")) << message_;
}

IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTestsAudio) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "api_tests_audio.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_EndToEnd DISABLED_EndToEnd
#else
#define MAYBE_EndToEnd EndToEnd
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_EndToEnd) {
  extensions::FeatureSwitch::ScopedOverride tab_capture(
      extensions::FeatureSwitch::tab_capture(), true);

#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif
#if defined(OS_MACOSX)
  // TODO(miu): Disabled for Mac OS X 10.6 due to timeout issues.
  // http://crbug.com/174640
  if (base::mac::IsOSSnowLeopard())
    return;
#endif

  AddExtensionToCommandLineWhitelist();
  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "end_to_end.html")) << message_;
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_GetUserMediaTest DISABLED_GetUserMediaTest
#else
#define MAYBE_GetUserMediaTest GetUserMediaTest
#endif
// Test that we can't get tabCapture streams using GetUserMedia directly.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GetUserMediaTest) {
  ExtensionTestMessageListener listener("ready", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "get_user_media_test.html")) << message_;

  EXPECT_TRUE(listener.WaitUntilSatisfied());

  content::OpenURLParams params(GURL("about:blank"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  content::RenderViewHost* const rvh = web_contents->GetRenderViewHost();
  int render_process_id = rvh->GetProcess()->GetID();
  int routing_id = rvh->GetRoutingID();

  listener.Reply(base::StringPrintf("%i:%i", render_process_id, routing_id));

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_ActiveTabPermission DISABLED_ActiveTabPermission
#else
#define MAYBE_ActiveTabPermission ActiveTabPermission
#endif
// Make sure tabCapture.capture only works if the tab has been granted
// permission via an extension icon click or the extension is whitelisted.
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ActiveTabPermission) {
  ExtensionTestMessageListener before_open_tab("ready1", true);
  ExtensionTestMessageListener before_grant_permission("ready2", true);
  ExtensionTestMessageListener before_open_new_tab("ready3", true);
  ExtensionTestMessageListener before_whitelist_extension("ready4", true);

  ASSERT_TRUE(RunExtensionSubtest(
      "tab_capture/experimental", "active_tab_permission_test.html"))
          << message_;

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_tab.WaitUntilSatisfied());
  content::OpenURLParams params(GURL("http://google.com"), content::Referrer(),
                                NEW_FOREGROUND_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);
  before_open_tab.Reply("");

  // Grant permission and make sure capture succeeds.
  EXPECT_TRUE(before_grant_permission.WaitUntilSatisfied());
  ExtensionService* extension_service =
      Profile::FromBrowserContext(web_contents->GetBrowserContext())
          ->GetExtensionService();
  const extensions::Extension* extension =
      extension_service->GetExtensionById(kExtensionId, false);
  extensions::TabHelper::FromWebContents(web_contents)
      ->active_tab_permission_granter()->GrantIfRequested(extension);
  before_grant_permission.Reply("");

  // Open a new tab and make sure capture is denied.
  EXPECT_TRUE(before_open_new_tab.WaitUntilSatisfied());
  browser()->OpenURL(params);
  before_open_new_tab.Reply("");

  // Add extension to whitelist and make sure capture succeeds.
  EXPECT_TRUE(before_whitelist_extension.WaitUntilSatisfied());
  AddExtensionToCommandLineWhitelist();
  before_whitelist_extension.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

// http://crbug.com/177163
#if defined(OS_WIN) && !defined(NDEBUG)
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#elif defined(USE_AURA) || defined(OS_MACOSX)
// These don't always fire fullscreen events when run in tests. Tested manually.
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#elif defined(OS_LINUX)
// Flaky to get out of fullscreen in tests. Tested manually.
#define MAYBE_FullscreenEvents DISABLED_FullscreenEvents
#else
#define MAYBE_FullscreenEvents FullscreenEvents
#endif
IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_FullscreenEvents) {
#if defined(OS_WIN)
  // TODO(justinlin): Disabled for WinXP due to timeout issues.
  if (base::win::GetVersion() < base::win::VERSION_VISTA) {
    return;
  }
#endif

  AddExtensionToCommandLineWhitelist();

  content::OpenURLParams params(GURL("chrome://version"),
                                content::Referrer(),
                                CURRENT_TAB,
                                content::PAGE_TRANSITION_LINK, false);
  content::WebContents* web_contents = browser()->OpenURL(params);

  ExtensionTestMessageListener listeners_setup("ready1", true);
  ExtensionTestMessageListener fullscreen_entered("ready2", true);

  ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental",
                                  "fullscreen_test.html")) << message_;
  EXPECT_TRUE(listeners_setup.WaitUntilSatisfied());

  // Toggle fullscreen after setting up listeners.
  browser()->fullscreen_controller()->ToggleFullscreenModeForTab(web_contents,
                                                                 true);
  listeners_setup.Reply("");

  // Toggle again after JS should have the event.
  EXPECT_TRUE(fullscreen_entered.WaitUntilSatisfied());
  browser()->fullscreen_controller()->ToggleFullscreenModeForTab(web_contents,
                                                                 false);
  fullscreen_entered.Reply("");

  ResultCatcher catcher;
  catcher.RestrictToProfile(browser()->profile());
  EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
}

}  // namespace chrome
<|endoftext|>


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

#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/speech/speech_input_bubble_controller.h"
#include "gfx/rect.h"
#include "testing/gtest/include/gtest/gtest.h"

class SkBitmap;

namespace speech_input {

// A mock bubble class which fakes a focus change or recognition cancel by the
// user and closing of the info bubble.
class MockSpeechInputBubble : public SpeechInputBubbleBase {
 public:
  enum BubbleType {
    BUBBLE_TEST_FOCUS_CHANGED,
    BUBBLE_TEST_CLICK_CANCEL,
    BUBBLE_TEST_CLICK_TRY_AGAIN,
  };

  MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) {
    MessageLoop::current()->PostTask(
        FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate));
  }

  static void InvokeDelegate(Delegate* delegate) {
    switch (type_) {
      case BUBBLE_TEST_FOCUS_CHANGED:
        delegate->InfoBubbleFocusChanged();
        break;
      case BUBBLE_TEST_CLICK_CANCEL:
        delegate->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL);
        break;
      case BUBBLE_TEST_CLICK_TRY_AGAIN:
        delegate->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN);
        break;
    }
  }

  static void set_type(BubbleType type) {
    type_ = type;
  }
  static BubbleType type() {
    return type_;
  }

  virtual void Show() {}
  virtual void Hide() {}
  virtual void UpdateLayout() {}
  virtual void SetImage(const SkBitmap&) {}

 private:
  static BubbleType type_;
};

// The test fixture.
class SpeechInputBubbleControllerTest
    : public SpeechInputBubbleControllerDelegate,
      public testing::Test {
 public:
  SpeechInputBubbleControllerTest()
      : io_loop_(MessageLoop::TYPE_IO),
        ui_thread_(ChromeThread::UI),  // constructs a new thread and loop
        io_thread_(ChromeThread::IO, &io_loop_),  // resuses main thread loop
        cancel_clicked_(false),
        try_again_clicked_(false),
        focus_changed_(false),
        controller_(ALLOW_THIS_IN_INITIALIZER_LIST(
            new SpeechInputBubbleController(this))) {
    EXPECT_EQ(NULL, test_fixture_);
    test_fixture_ = this;
  }

  ~SpeechInputBubbleControllerTest() {
    test_fixture_ = NULL;
  }

  // SpeechInputBubbleControllerDelegate methods.
  virtual void InfoBubbleButtonClicked(int caller_id,
                                       SpeechInputBubble::Button button) {
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));
    if (button == SpeechInputBubble::BUTTON_CANCEL) {
      cancel_clicked_ = true;
    } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) {
      try_again_clicked_ = true;
    }
    MessageLoop::current()->Quit();
  }

  virtual void InfoBubbleFocusChanged(int caller_id) {
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));
    focus_changed_ = true;
    MessageLoop::current()->Quit();
  }

  // testing::Test methods.
  virtual void SetUp() {
    SpeechInputBubble::set_factory(
        &SpeechInputBubbleControllerTest::CreateBubble);
    ui_thread_.Start();
  }

  virtual void TearDown() {
    SpeechInputBubble::set_factory(NULL);
    ui_thread_.Stop();
  }

  static void ActivateBubble() {
    if (MockSpeechInputBubble::type() ==
        MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED) {
      test_fixture_->controller_->SetBubbleRecordingMode(kBubbleCallerId);
    } else {
      test_fixture_->controller_->SetBubbleMessage(kBubbleCallerId,
                                                   ASCIIToUTF16("Test"));
    }
  }

  static SpeechInputBubble* CreateBubble(TabContents* tab_contents,
                                         SpeechInputBubble::Delegate* delegate,
                                         const gfx::Rect& element_rect) {
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
    // Set up to activate the bubble soon after it gets created, since we test
    // events sent by the bubble and those are handled only when the bubble is
    // active.
    MessageLoop::current()->PostTask(FROM_HERE,
                                     NewRunnableFunction(&ActivateBubble));
    return new MockSpeechInputBubble(tab_contents, delegate, element_rect);
  }

 protected:
  // The main thread of the test is marked as the IO thread and we create a new
  // one for the UI thread.
  MessageLoop io_loop_;
  ChromeThread ui_thread_;
  ChromeThread io_thread_;
  bool cancel_clicked_;
  bool try_again_clicked_;
  bool focus_changed_;
  scoped_refptr<SpeechInputBubbleController> controller_;

  static const int kBubbleCallerId;
  static SpeechInputBubbleControllerTest* test_fixture_;
};

SpeechInputBubbleControllerTest*
SpeechInputBubbleControllerTest::test_fixture_ = NULL;

const int SpeechInputBubbleControllerTest::kBubbleCallerId = 1;

MockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ =
    MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED;

// Test that the speech bubble UI gets created in the UI thread and that the
// focus changed callback comes back in the IO thread.
//
// Crashes on Win only.  http://crbug.com/54044
#if defined(OS_WIN)
#define MAYBE_TestFocusChanged DISABLED_TestFocusChanged
#else
#define MAYBE_TestFocusChanged TestFocusChanged
#endif
TEST_F(SpeechInputBubbleControllerTest, MAYBE_TestFocusChanged) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_TRUE(focus_changed_);
  EXPECT_FALSE(cancel_clicked_);
  EXPECT_FALSE(try_again_clicked_);
  controller_->CloseBubble(kBubbleCallerId);
}

// Test that the speech bubble UI gets created in the UI thread and that the
// recognition cancelled callback comes back in the IO thread.
TEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_CLICK_CANCEL);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_TRUE(cancel_clicked_);
  EXPECT_FALSE(try_again_clicked_);
  EXPECT_FALSE(focus_changed_);
  controller_->CloseBubble(kBubbleCallerId);
}

// Test that the speech bubble UI gets created in the UI thread and that the
// try-again button click event comes back in the IO thread.
TEST_F(SpeechInputBubbleControllerTest, TestTryAgainClicked) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_CLICK_TRY_AGAIN);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_FALSE(cancel_clicked_);
  EXPECT_TRUE(try_again_clicked_);
  EXPECT_FALSE(focus_changed_);
  controller_->CloseBubble(kBubbleCallerId);
}

}  // namespace speech_input
<commit_msg>Add some log messages to track down a test timing out occasionally.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/utf_string_conversions.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/speech/speech_input_bubble_controller.h"
#include "gfx/rect.h"
#include "testing/gtest/include/gtest/gtest.h"

class SkBitmap;

namespace speech_input {

// A mock bubble class which fakes a focus change or recognition cancel by the
// user and closing of the info bubble.
class MockSpeechInputBubble : public SpeechInputBubbleBase {
 public:
  enum BubbleType {
    BUBBLE_TEST_FOCUS_CHANGED,
    BUBBLE_TEST_CLICK_CANCEL,
    BUBBLE_TEST_CLICK_TRY_AGAIN,
  };

  MockSpeechInputBubble(TabContents*, Delegate* delegate, const gfx::Rect&) {
    LOG(INFO) << "MockSpeechInputBubble created";
    MessageLoop::current()->PostTask(
        FROM_HERE, NewRunnableFunction(&InvokeDelegate, delegate));
  }

  static void InvokeDelegate(Delegate* delegate) {
    LOG(INFO) << "MockSpeechInputBubble invoking delegate for type " << type_;
    switch (type_) {
      case BUBBLE_TEST_FOCUS_CHANGED:
        delegate->InfoBubbleFocusChanged();
        break;
      case BUBBLE_TEST_CLICK_CANCEL:
        delegate->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_CANCEL);
        break;
      case BUBBLE_TEST_CLICK_TRY_AGAIN:
        delegate->InfoBubbleButtonClicked(SpeechInputBubble::BUTTON_TRY_AGAIN);
        break;
    }
  }

  static void set_type(BubbleType type) {
    type_ = type;
  }
  static BubbleType type() {
    return type_;
  }

  virtual void Show() {}
  virtual void Hide() {}
  virtual void UpdateLayout() {}
  virtual void SetImage(const SkBitmap&) {}

 private:
  static BubbleType type_;
};

// The test fixture.
class SpeechInputBubbleControllerTest
    : public SpeechInputBubbleControllerDelegate,
      public testing::Test {
 public:
  SpeechInputBubbleControllerTest()
      : io_loop_(MessageLoop::TYPE_IO),
        ui_thread_(ChromeThread::UI),  // constructs a new thread and loop
        io_thread_(ChromeThread::IO, &io_loop_),  // resuses main thread loop
        cancel_clicked_(false),
        try_again_clicked_(false),
        focus_changed_(false),
        controller_(ALLOW_THIS_IN_INITIALIZER_LIST(
            new SpeechInputBubbleController(this))) {
    EXPECT_EQ(NULL, test_fixture_);
    test_fixture_ = this;
  }

  ~SpeechInputBubbleControllerTest() {
    test_fixture_ = NULL;
  }

  // SpeechInputBubbleControllerDelegate methods.
  virtual void InfoBubbleButtonClicked(int caller_id,
                                       SpeechInputBubble::Button button) {
    LOG(INFO) << "Received InfoBubbleButtonClicked for button " << button;
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));
    if (button == SpeechInputBubble::BUTTON_CANCEL) {
      cancel_clicked_ = true;
    } else if (button == SpeechInputBubble::BUTTON_TRY_AGAIN) {
      try_again_clicked_ = true;
    }
    MessageLoop::current()->Quit();
  }

  virtual void InfoBubbleFocusChanged(int caller_id) {
    LOG(INFO) << "Received InfoBubbleFocusChanged";
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::IO));
    focus_changed_ = true;
    MessageLoop::current()->Quit();
  }

  // testing::Test methods.
  virtual void SetUp() {
    SpeechInputBubble::set_factory(
        &SpeechInputBubbleControllerTest::CreateBubble);
    ui_thread_.Start();
  }

  virtual void TearDown() {
    SpeechInputBubble::set_factory(NULL);
    ui_thread_.Stop();
  }

  static void ActivateBubble() {
    if (MockSpeechInputBubble::type() ==
        MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED) {
      test_fixture_->controller_->SetBubbleRecordingMode(kBubbleCallerId);
    } else {
      test_fixture_->controller_->SetBubbleMessage(kBubbleCallerId,
                                                   ASCIIToUTF16("Test"));
    }
  }

  static SpeechInputBubble* CreateBubble(TabContents* tab_contents,
                                         SpeechInputBubble::Delegate* delegate,
                                         const gfx::Rect& element_rect) {
    EXPECT_TRUE(ChromeThread::CurrentlyOn(ChromeThread::UI));
    // Set up to activate the bubble soon after it gets created, since we test
    // events sent by the bubble and those are handled only when the bubble is
    // active.
    MessageLoop::current()->PostTask(FROM_HERE,
                                     NewRunnableFunction(&ActivateBubble));
    return new MockSpeechInputBubble(tab_contents, delegate, element_rect);
  }

 protected:
  // The main thread of the test is marked as the IO thread and we create a new
  // one for the UI thread.
  MessageLoop io_loop_;
  ChromeThread ui_thread_;
  ChromeThread io_thread_;
  bool cancel_clicked_;
  bool try_again_clicked_;
  bool focus_changed_;
  scoped_refptr<SpeechInputBubbleController> controller_;

  static const int kBubbleCallerId;
  static SpeechInputBubbleControllerTest* test_fixture_;
};

SpeechInputBubbleControllerTest*
SpeechInputBubbleControllerTest::test_fixture_ = NULL;

const int SpeechInputBubbleControllerTest::kBubbleCallerId = 1;

MockSpeechInputBubble::BubbleType MockSpeechInputBubble::type_ =
    MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED;

// Test that the speech bubble UI gets created in the UI thread and that the
// focus changed callback comes back in the IO thread.
//
// This test times out sometimes on windows, see http://crbug.com/54044. To
// help find the cause it is left running so we can collect logs when it fails.
#if defined(OS_WIN)
#define MAYBE_TestFocusChanged FLAKY_TestFocusChanged
#else
#define MAYBE_TestFocusChanged TestFocusChanged
#endif
TEST_F(SpeechInputBubbleControllerTest, MAYBE_TestFocusChanged) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_FOCUS_CHANGED);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_TRUE(focus_changed_);
  EXPECT_FALSE(cancel_clicked_);
  EXPECT_FALSE(try_again_clicked_);
  controller_->CloseBubble(kBubbleCallerId);
}

// Test that the speech bubble UI gets created in the UI thread and that the
// recognition cancelled callback comes back in the IO thread.
TEST_F(SpeechInputBubbleControllerTest, TestRecognitionCancelled) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_CLICK_CANCEL);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_TRUE(cancel_clicked_);
  EXPECT_FALSE(try_again_clicked_);
  EXPECT_FALSE(focus_changed_);
  controller_->CloseBubble(kBubbleCallerId);
}

// Test that the speech bubble UI gets created in the UI thread and that the
// try-again button click event comes back in the IO thread.
TEST_F(SpeechInputBubbleControllerTest, TestTryAgainClicked) {
  MockSpeechInputBubble::set_type(
      MockSpeechInputBubble::BUBBLE_TEST_CLICK_TRY_AGAIN);

  controller_->CreateBubble(kBubbleCallerId, 1, 1, gfx::Rect(1, 1));
  MessageLoop::current()->Run();
  EXPECT_FALSE(cancel_clicked_);
  EXPECT_TRUE(try_again_clicked_);
  EXPECT_FALSE(focus_changed_);
  controller_->CloseBubble(kBubbleCallerId);
}

}  // namespace speech_input
<|endoftext|>


<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "lexer.h"

#include <stdio.h>

#include "eval_env.h"
#include "util.h"

bool Lexer::Error(const string& message, string* err) {
  // Compute line/column.
  int line = 1;
  const char* context = input_.str_;
  for (const char* p = input_.str_; p < last_token_; ++p) {
    if (*p == '\n') {
      ++line;
      context = p + 1;
    }
  }
  int col = last_token_ ? last_token_ - context : 0;

  char buf[1024];
  snprintf(buf, sizeof(buf), "%s:%d: ", filename_.AsString().c_str(), line);
  *err = buf;
  *err += message + "\n";

  // Add some context to the message.
  const int kTruncateColumn = 72;
  if (col > 0 && col < kTruncateColumn) {
    int len;
    bool truncated = true;
    for (len = 0; len < kTruncateColumn; ++len) {
      if (context[len] == 0 || context[len] == '\n') {
        truncated = false;
        break;
      }
    }
    *err += string(context, len);
    if (truncated)
      *err += "...";
    *err += "\n";
    *err += string(col, ' ');
    *err += "^ near here\n";
  }

  return false;
}

Lexer::Lexer(const char* input) {
  Start("input", input);
}

void Lexer::Start(StringPiece filename, StringPiece input) {
  filename_ = filename;
  input_ = input;
  ofs_ = input_.str_;
  last_token_ = NULL;
}

const char* Lexer::TokenName(Token t) {
  switch (t) {
  case ERROR:    return "lexing error";
  case BUILD:    return "'build'";
  case COLON:    return "':'";
  case DEFAULT:  return "'default'";
  case EQUALS:   return "'='";
  case IDENT:    return "identifier";
  case INCLUDE:  return "'include'";
  case INDENT:   return "indent";
  case NEWLINE:  return "newline";
  case PIPE2:    return "'||'";
  case PIPE:     return "'|'";
  case RULE:     return "'rule'";
  case SUBNINJA: return "'subninja'";
  case TEOF:     return "eof";
  }
  return NULL;  // not reached
}

void Lexer::UnreadToken() {
  ofs_ = last_token_;
}

Lexer::Token Lexer::ReadToken() {
  const char* p = ofs_;
  const char* q;
  const char* start;
  Lexer::Token token;
  for (;;) {
    start = p;
    /*!re2c
    re2c:define:YYCTYPE = "char";
    re2c:define:YYCURSOR = p;
    re2c:define:YYMARKER = q;
    re2c:yyfill:enable = 0;

    nul = "\000";
    simple_varname = [a-zA-Z0-9_-]+;
    varname = [a-zA-Z0-9_.-]+;

    [ ]*"#"[^\000\n]*"\n" { continue; }
    [\n]       { token = NEWLINE;  break; }
    [ ]+       { token = INDENT;   break; }
    "build"    { token = BUILD;    break; }
    "rule"     { token = RULE;     break; }
    "default"  { token = DEFAULT;  break; }
    "="        { token = EQUALS;   break; }
    ":"        { token = COLON;    break; }
    "||"       { token = PIPE2;    break; }
    "|"        { token = PIPE;     break; }
    "include"  { token = INCLUDE;  break; }
    "subninja" { token = SUBNINJA; break; }
    varname    { token = IDENT;    break; }
    nul        { token = TEOF;     break; }
    [^]        { token = ERROR;    break; }
    */
  }

  last_token_ = start;
  ofs_ = p;
  if (token != NEWLINE && token != TEOF)
    EatWhitespace();
  return token;
}

bool Lexer::PeekToken(Token token) {
  Token t = ReadToken();
  if (t == token)
    return true;
  UnreadToken();
  return false;
}

void Lexer::EatWhitespace() {
  const char* p = ofs_;
  for (;;) {
    ofs_ = p;
    /*!re2c
    [ ]+  { continue; }
    "$\n" { continue; }
    nul   { break; }
    [^]   { break; }
    */
  }
}

bool Lexer::ReadIdent(string* out) {
  const char* p = ofs_;
  for (;;) {
    const char* start = p;
    /*!re2c
    varname {
      out->assign(start, p - start);
      break;
    }
    [^] { return false; }
    */
  }
  ofs_ = p;
  EatWhitespace();
  return true;
}

bool Lexer::ReadEvalString(EvalString* eval, bool path, string* err) {
  const char* p = ofs_;
  const char* q;
  const char* start;
  for (;;) {
    start = p;
    /*!re2c
    [^$ :\n|\000]+ {
      eval->AddText(StringPiece(start, p - start));
      continue;
    }
    [ :|\n] {
      if (path) {
        p = start;
        break;
      } else {
        if (*start == '\n')
          break;
        eval->AddText(StringPiece(start, 1));
        continue;
      }
    }
    "$$" {
      eval->AddText(StringPiece("$", 1));
      continue;
    }
    "$ " {
      eval->AddText(StringPiece(" ", 1));
      continue;
    }
    "$\n"[ ]* {
      continue;
    }
    "${"varname"}" {
      eval->AddSpecial(StringPiece(start + 2, p - start - 3));
      continue;
    }
    "$"simple_varname {
      eval->AddSpecial(StringPiece(start + 1, p - start - 1));
      continue;
    }
    "$". {
      last_token_ = start;
      return Error("bad $-escape (literal $ must be written as $$)", err);
    }
    nul {
      last_token_ = start;
      return Error("unexpected EOF", err);
    }
    [^] {
      last_token_ = start;
      return Error("lexing error", err);
    }
    */
  }
  last_token_ = start;
  ofs_ = p;
  if (path)
    EatWhitespace();
  // Non-path strings end in newlines, so there's no whitespace to eat.
  return true;
}
<commit_msg>Lexer: Remove the trailing newline from lexer.in.cc not just lexer.cc<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "lexer.h"

#include <stdio.h>

#include "eval_env.h"
#include "util.h"

bool Lexer::Error(const string& message, string* err) {
  // Compute line/column.
  int line = 1;
  const char* context = input_.str_;
  for (const char* p = input_.str_; p < last_token_; ++p) {
    if (*p == '\n') {
      ++line;
      context = p + 1;
    }
  }
  int col = last_token_ ? last_token_ - context : 0;

  char buf[1024];
  snprintf(buf, sizeof(buf), "%s:%d: ", filename_.AsString().c_str(), line);
  *err = buf;
  *err += message + "\n";

  // Add some context to the message.
  const int kTruncateColumn = 72;
  if (col > 0 && col < kTruncateColumn) {
    int len;
    bool truncated = true;
    for (len = 0; len < kTruncateColumn; ++len) {
      if (context[len] == 0 || context[len] == '\n') {
        truncated = false;
        break;
      }
    }
    *err += string(context, len);
    if (truncated)
      *err += "...";
    *err += "\n";
    *err += string(col, ' ');
    *err += "^ near here";
  }

  return false;
}

Lexer::Lexer(const char* input) {
  Start("input", input);
}

void Lexer::Start(StringPiece filename, StringPiece input) {
  filename_ = filename;
  input_ = input;
  ofs_ = input_.str_;
  last_token_ = NULL;
}

const char* Lexer::TokenName(Token t) {
  switch (t) {
  case ERROR:    return "lexing error";
  case BUILD:    return "'build'";
  case COLON:    return "':'";
  case DEFAULT:  return "'default'";
  case EQUALS:   return "'='";
  case IDENT:    return "identifier";
  case INCLUDE:  return "'include'";
  case INDENT:   return "indent";
  case NEWLINE:  return "newline";
  case PIPE2:    return "'||'";
  case PIPE:     return "'|'";
  case RULE:     return "'rule'";
  case SUBNINJA: return "'subninja'";
  case TEOF:     return "eof";
  }
  return NULL;  // not reached
}

void Lexer::UnreadToken() {
  ofs_ = last_token_;
}

Lexer::Token Lexer::ReadToken() {
  const char* p = ofs_;
  const char* q;
  const char* start;
  Lexer::Token token;
  for (;;) {
    start = p;
    /*!re2c
    re2c:define:YYCTYPE = "char";
    re2c:define:YYCURSOR = p;
    re2c:define:YYMARKER = q;
    re2c:yyfill:enable = 0;

    nul = "\000";
    simple_varname = [a-zA-Z0-9_-]+;
    varname = [a-zA-Z0-9_.-]+;

    [ ]*"#"[^\000\n]*"\n" { continue; }
    [\n]       { token = NEWLINE;  break; }
    [ ]+       { token = INDENT;   break; }
    "build"    { token = BUILD;    break; }
    "rule"     { token = RULE;     break; }
    "default"  { token = DEFAULT;  break; }
    "="        { token = EQUALS;   break; }
    ":"        { token = COLON;    break; }
    "||"       { token = PIPE2;    break; }
    "|"        { token = PIPE;     break; }
    "include"  { token = INCLUDE;  break; }
    "subninja" { token = SUBNINJA; break; }
    varname    { token = IDENT;    break; }
    nul        { token = TEOF;     break; }
    [^]        { token = ERROR;    break; }
    */
  }

  last_token_ = start;
  ofs_ = p;
  if (token != NEWLINE && token != TEOF)
    EatWhitespace();
  return token;
}

bool Lexer::PeekToken(Token token) {
  Token t = ReadToken();
  if (t == token)
    return true;
  UnreadToken();
  return false;
}

void Lexer::EatWhitespace() {
  const char* p = ofs_;
  for (;;) {
    ofs_ = p;
    /*!re2c
    [ ]+  { continue; }
    "$\n" { continue; }
    nul   { break; }
    [^]   { break; }
    */
  }
}

bool Lexer::ReadIdent(string* out) {
  const char* p = ofs_;
  for (;;) {
    const char* start = p;
    /*!re2c
    varname {
      out->assign(start, p - start);
      break;
    }
    [^] { return false; }
    */
  }
  ofs_ = p;
  EatWhitespace();
  return true;
}

bool Lexer::ReadEvalString(EvalString* eval, bool path, string* err) {
  const char* p = ofs_;
  const char* q;
  const char* start;
  for (;;) {
    start = p;
    /*!re2c
    [^$ :\n|\000]+ {
      eval->AddText(StringPiece(start, p - start));
      continue;
    }
    [ :|\n] {
      if (path) {
        p = start;
        break;
      } else {
        if (*start == '\n')
          break;
        eval->AddText(StringPiece(start, 1));
        continue;
      }
    }
    "$$" {
      eval->AddText(StringPiece("$", 1));
      continue;
    }
    "$ " {
      eval->AddText(StringPiece(" ", 1));
      continue;
    }
    "$\n"[ ]* {
      continue;
    }
    "${"varname"}" {
      eval->AddSpecial(StringPiece(start + 2, p - start - 3));
      continue;
    }
    "$"simple_varname {
      eval->AddSpecial(StringPiece(start + 1, p - start - 1));
      continue;
    }
    "$". {
      last_token_ = start;
      return Error("bad $-escape (literal $ must be written as $$)", err);
    }
    nul {
      last_token_ = start;
      return Error("unexpected EOF", err);
    }
    [^] {
      last_token_ = start;
      return Error("lexing error", err);
    }
    */
  }
  last_token_ = start;
  ofs_ = p;
  if (path)
    EatWhitespace();
  // Non-path strings end in newlines, so there's no whitespace to eat.
  return true;
}
<|endoftext|>