<commit_before>//===--- ParentVirtualCallCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ParentVirtualCallCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/FixIt.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
#include <cctype>

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace bugprone {

using BasesVector = llvm::SmallVector<const CXXRecordDecl *, 5>;

static bool isParentOf(const CXXRecordDecl &Parent,
                       const CXXRecordDecl &ThisClass) {
  if (Parent.getCanonicalDecl() == ThisClass.getCanonicalDecl())
    return true;
  const auto ClassIter = std::find_if(
      ThisClass.bases().begin(), ThisClass.bases().end(),
      [=](const CXXBaseSpecifier &Base) {
        auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
        assert(BaseDecl);
        return Parent.getCanonicalDecl() == BaseDecl->getCanonicalDecl();
      });
  return ClassIter != ThisClass.bases_end();
}

static BasesVector getParentsByGrandParent(const CXXRecordDecl &GrandParent,
                                           const CXXRecordDecl &ThisClass,
                                           const CXXMethodDecl &MemberDecl) {
  BasesVector Result;
  for (const auto &Base : ThisClass.bases()) {
    const auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
    const CXXMethodDecl *ActualMemberDecl =
        MemberDecl.getCorrespondingMethodInClass(BaseDecl);
    if (!ActualMemberDecl)
      continue;
    // TypePtr is the nearest base class to ThisClass between ThisClass and
    // GrandParent, where MemberDecl is overridden. TypePtr is the class the
    // check proposes to fix to.
    const Type *TypePtr =
        ActualMemberDecl->getThisType(ActualMemberDecl->getASTContext())
            .getTypePtr();
    const CXXRecordDecl *RecordDeclType = TypePtr->getPointeeCXXRecordDecl();
    assert(RecordDeclType && "TypePtr is not a pointer to CXXRecordDecl!");
    if (RecordDeclType->getCanonicalDecl()->isDerivedFrom(&GrandParent))
      Result.emplace_back(RecordDeclType);
  }

  return Result;
}

static std::string getNameAsString(const NamedDecl *Decl) {
  std::string QualName;
  llvm::raw_string_ostream OS(QualName);
  PrintingPolicy PP(Decl->getASTContext().getPrintingPolicy());
  PP.SuppressUnwrittenScope = true;
  Decl->printQualifiedName(OS, PP);
  return OS.str();
}

// Returns E as written in the source code. Used to handle 'using' and
// 'typedef'ed names of grand-parent classes.
static std::string getExprAsString(const clang::Expr &E,
                                   clang::ASTContext &AC) {
  std::string Text = tooling::fixit::getText(E, AC).str();
  Text.erase(std::remove_if(Text.begin(), Text.end(), std::isspace),
             Text.end());
  return Text;
}

void ParentVirtualCallCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      cxxMemberCallExpr(
          callee(memberExpr(hasDescendant(implicitCastExpr(
                                hasImplicitDestinationType(pointsTo(
                                    type(anything()).bind("castToType"))),
                                hasSourceExpression(cxxThisExpr(hasType(
                                    type(anything()).bind("thisType")))))))
                     .bind("member")),
          callee(cxxMethodDecl(isVirtual())))
          .bind("call"),
      this);
}

void ParentVirtualCallCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call");
  assert(MatchedDecl);

  const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
  assert(Member);

  if (!Member->getQualifier())
    return;

  const auto *MemberDecl = cast<CXXMethodDecl>(Member->getMemberDecl());

  const auto *ThisTypePtr = Result.Nodes.getNodeAs<PointerType>("thisType");
  assert(ThisTypePtr);

  const auto *ThisType = ThisTypePtr->getPointeeCXXRecordDecl();
  assert(ThisType);

  const auto *CastToTypePtr = Result.Nodes.getNodeAs<Type>("castToType");
  assert(CastToTypePtr);

  const auto *CastToType = CastToTypePtr->getAsCXXRecordDecl();
  assert(CastToType);

  if (isParentOf(*CastToType, *ThisType))
    return;

  const BasesVector Parents =
      getParentsByGrandParent(*CastToType, *ThisType, *MemberDecl);

  if (Parents.empty())
    return;

  std::string ParentsStr;
  ParentsStr.reserve(30 * Parents.size());
  for (const CXXRecordDecl *Parent : Parents) {
    if (!ParentsStr.empty())
      ParentsStr.append(" or ");
    ParentsStr.append("'").append(getNameAsString(Parent)).append("'");
  }

  assert(Member->getQualifierLoc().getSourceRange().getBegin().isValid());
  auto Diag = diag(Member->getQualifierLoc().getSourceRange().getBegin(),
                   "qualified name '%0' refers to a member overridden "
                   "in subclass%1; did you mean %2?")
              << getExprAsString(*Member, *Result.Context)
              << (Parents.size() > 1 ? "es" : "") << ParentsStr;

  // Propose a fix if there's only one parent class...
  if (Parents.size() == 1 &&
      // ...unless parent class is templated
      !isa<ClassTemplateSpecializationDecl>(Parents.front()))
    Diag << FixItHint::CreateReplacement(
        Member->getQualifierLoc().getSourceRange(),
        getNameAsString(Parents.front()) + "::");
}

} // namespace bugprone
} // namespace tidy
} // namespace clang
<commit_msg>[clang-tidy] One more fix compilation for ParentVirtualCallCheck.cpp: find_if predicate<commit_after>//===--- ParentVirtualCallCheck.cpp - clang-tidy---------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "ParentVirtualCallCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Tooling/FixIt.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
#include <cctype>

using namespace clang::ast_matchers;

namespace clang {
namespace tidy {
namespace bugprone {

using BasesVector = llvm::SmallVector<const CXXRecordDecl *, 5>;

static bool isParentOf(const CXXRecordDecl &Parent,
                       const CXXRecordDecl &ThisClass) {
  if (Parent.getCanonicalDecl() == ThisClass.getCanonicalDecl())
    return true;
  const auto ClassIter = std::find_if(
      ThisClass.bases().begin(), ThisClass.bases().end(),
      [=](const CXXBaseSpecifier &Base) {
        auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
        assert(BaseDecl);
        return Parent.getCanonicalDecl() == BaseDecl->getCanonicalDecl();
      });
  return ClassIter != ThisClass.bases_end();
}

static BasesVector getParentsByGrandParent(const CXXRecordDecl &GrandParent,
                                           const CXXRecordDecl &ThisClass,
                                           const CXXMethodDecl &MemberDecl) {
  BasesVector Result;
  for (const auto &Base : ThisClass.bases()) {
    const auto *BaseDecl = Base.getType()->getAsCXXRecordDecl();
    const CXXMethodDecl *ActualMemberDecl =
        MemberDecl.getCorrespondingMethodInClass(BaseDecl);
    if (!ActualMemberDecl)
      continue;
    // TypePtr is the nearest base class to ThisClass between ThisClass and
    // GrandParent, where MemberDecl is overridden. TypePtr is the class the
    // check proposes to fix to.
    const Type *TypePtr =
        ActualMemberDecl->getThisType(ActualMemberDecl->getASTContext())
            .getTypePtr();
    const CXXRecordDecl *RecordDeclType = TypePtr->getPointeeCXXRecordDecl();
    assert(RecordDeclType && "TypePtr is not a pointer to CXXRecordDecl!");
    if (RecordDeclType->getCanonicalDecl()->isDerivedFrom(&GrandParent))
      Result.emplace_back(RecordDeclType);
  }

  return Result;
}

static std::string getNameAsString(const NamedDecl *Decl) {
  std::string QualName;
  llvm::raw_string_ostream OS(QualName);
  PrintingPolicy PP(Decl->getASTContext().getPrintingPolicy());
  PP.SuppressUnwrittenScope = true;
  Decl->printQualifiedName(OS, PP);
  return OS.str();
}

// Returns E as written in the source code. Used to handle 'using' and
// 'typedef'ed names of grand-parent classes.
static std::string getExprAsString(const clang::Expr &E,
                                   clang::ASTContext &AC) {
  std::string Text = tooling::fixit::getText(E, AC).str();
  Text.erase(
      std::remove_if(
          Text.begin(), Text.end(),
          [](char c) { return std::isspace(static_cast<unsigned char>(c)); }),
      Text.end());
  return Text;
}

void ParentVirtualCallCheck::registerMatchers(MatchFinder *Finder) {
  Finder->addMatcher(
      cxxMemberCallExpr(
          callee(memberExpr(hasDescendant(implicitCastExpr(
                                hasImplicitDestinationType(pointsTo(
                                    type(anything()).bind("castToType"))),
                                hasSourceExpression(cxxThisExpr(hasType(
                                    type(anything()).bind("thisType")))))))
                     .bind("member")),
          callee(cxxMethodDecl(isVirtual())))
          .bind("call"),
      this);
}

void ParentVirtualCallCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *MatchedDecl = Result.Nodes.getNodeAs<CXXMemberCallExpr>("call");
  assert(MatchedDecl);

  const auto *Member = Result.Nodes.getNodeAs<MemberExpr>("member");
  assert(Member);

  if (!Member->getQualifier())
    return;

  const auto *MemberDecl = cast<CXXMethodDecl>(Member->getMemberDecl());

  const auto *ThisTypePtr = Result.Nodes.getNodeAs<PointerType>("thisType");
  assert(ThisTypePtr);

  const auto *ThisType = ThisTypePtr->getPointeeCXXRecordDecl();
  assert(ThisType);

  const auto *CastToTypePtr = Result.Nodes.getNodeAs<Type>("castToType");
  assert(CastToTypePtr);

  const auto *CastToType = CastToTypePtr->getAsCXXRecordDecl();
  assert(CastToType);

  if (isParentOf(*CastToType, *ThisType))
    return;

  const BasesVector Parents =
      getParentsByGrandParent(*CastToType, *ThisType, *MemberDecl);

  if (Parents.empty())
    return;

  std::string ParentsStr;
  ParentsStr.reserve(30 * Parents.size());
  for (const CXXRecordDecl *Parent : Parents) {
    if (!ParentsStr.empty())
      ParentsStr.append(" or ");
    ParentsStr.append("'").append(getNameAsString(Parent)).append("'");
  }

  assert(Member->getQualifierLoc().getSourceRange().getBegin().isValid());
  auto Diag = diag(Member->getQualifierLoc().getSourceRange().getBegin(),
                   "qualified name '%0' refers to a member overridden "
                   "in subclass%1; did you mean %2?")
              << getExprAsString(*Member, *Result.Context)
              << (Parents.size() > 1 ? "es" : "") << ParentsStr;

  // Propose a fix if there's only one parent class...
  if (Parents.size() == 1 &&
      // ...unless parent class is templated
      !isa<ClassTemplateSpecializationDecl>(Parents.front()))
    Diag << FixItHint::CreateReplacement(
        Member->getQualifierLoc().getSourceRange(),
        getNameAsString(Parents.front()) + "::");
}

} // namespace bugprone
} // namespace tidy
} // namespace clang
<|endoftext|>


<commit_before>// The runtime wants to pull a number of variables out of the
// environment but calling getenv is not threadsafe, so every value
// that might come from the environment is loaded here, once, during
// init.

#include "rust_internal.h"

// The environment variables that the runtime knows about
#define RUST_THREADS "RUST_THREADS"
#define RUST_MIN_STACK "RUST_MIN_STACK"
#define RUST_LOG "RUST_LOG"
#define CHECK_CLAIMS "CHECK_CLAIMS"
#define DETAILED_LEAKS "DETAILED_LEAKS"
#define RUST_SEED "RUST_SEED"

#if defined(__WIN32__)
static int
get_num_cpus() {
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);

    return (int) sysinfo.dwNumberOfProcessors;
}
#elif defined(__BSD__)
static int
get_num_cpus() {
    /* swiped from http://stackoverflow.com/questions/150355/
       programmatically-find-the-number-of-cores-on-a-machine */

    unsigned int numCPU;
    int mib[4];
    size_t len = sizeof(numCPU);

    /* set the mib for hw.ncpu */
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;

    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);

    if( numCPU < 1 ) {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );

        if( numCPU < 1 ) {
            numCPU = 1;
        }
    }
    return numCPU;
}
#elif defined(__GNUC__)
static int
get_num_cpus() {
    return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif

static int
get_num_threads()
{
    char *env = getenv(RUST_THREADS);
    if(env) {
        int num = atoi(env);
        if(num > 0)
            return num;
    }
    return get_num_cpus();
}

static size_t
get_min_stk_size() {
    char *stack_size = getenv(RUST_MIN_STACK);
    if(stack_size) {
        return strtol(stack_size, NULL, 0);
    }
    else {
        return 0x300000;
    }
}

static char*
copyenv(const char* name) {
    char *envvar = getenv(name);
    if (!envvar) {
        return NULL;
    } else {
        size_t slen = strlen(envvar);
        size_t buflen = slen + 1;
        char *var = (char*)malloc(buflen);
        memset(var, 0, buflen);
        strncpy(var, envvar, slen);
        return var;
    }
}

rust_env*
load_env() {
    rust_env *env = (rust_env*)malloc(sizeof(rust_env));

    env->num_sched_threads = (size_t)get_num_threads();
    env->min_stack_size = get_min_stk_size();
    env->logspec = copyenv(RUST_LOG);
    env->check_claims = getenv(CHECK_CLAIMS) != NULL;
    env->detailed_leaks = getenv(DETAILED_LEAKS) != NULL;
    env->rust_seed = copyenv(RUST_SEED);

    return env;
}

void
free_env(rust_env *env) {
    free(env->logspec);
    free(env->rust_seed);
    free(env);
}
<commit_msg>Revert "rt: Turn on big stacks again. Unwinding still doesn't always succeed on mac"<commit_after>// The runtime wants to pull a number of variables out of the
// environment but calling getenv is not threadsafe, so every value
// that might come from the environment is loaded here, once, during
// init.

#include "rust_internal.h"

// The environment variables that the runtime knows about
#define RUST_THREADS "RUST_THREADS"
#define RUST_MIN_STACK "RUST_MIN_STACK"
#define RUST_LOG "RUST_LOG"
#define CHECK_CLAIMS "CHECK_CLAIMS"
#define DETAILED_LEAKS "DETAILED_LEAKS"
#define RUST_SEED "RUST_SEED"

#if defined(__WIN32__)
static int
get_num_cpus() {
    SYSTEM_INFO sysinfo;
    GetSystemInfo(&sysinfo);

    return (int) sysinfo.dwNumberOfProcessors;
}
#elif defined(__BSD__)
static int
get_num_cpus() {
    /* swiped from http://stackoverflow.com/questions/150355/
       programmatically-find-the-number-of-cores-on-a-machine */

    unsigned int numCPU;
    int mib[4];
    size_t len = sizeof(numCPU);

    /* set the mib for hw.ncpu */
    mib[0] = CTL_HW;
    mib[1] = HW_AVAILCPU;  // alternatively, try HW_NCPU;

    /* get the number of CPUs from the system */
    sysctl(mib, 2, &numCPU, &len, NULL, 0);

    if( numCPU < 1 ) {
        mib[1] = HW_NCPU;
        sysctl( mib, 2, &numCPU, &len, NULL, 0 );

        if( numCPU < 1 ) {
            numCPU = 1;
        }
    }
    return numCPU;
}
#elif defined(__GNUC__)
static int
get_num_cpus() {
    return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif

static int
get_num_threads()
{
    char *env = getenv(RUST_THREADS);
    if(env) {
        int num = atoi(env);
        if(num > 0)
            return num;
    }
    return get_num_cpus();
}

static size_t
get_min_stk_size() {
    char *stack_size = getenv(RUST_MIN_STACK);
    if(stack_size) {
        return strtol(stack_size, NULL, 0);
    }
    else {
        return 0x300;
    }
}

static char*
copyenv(const char* name) {
    char *envvar = getenv(name);
    if (!envvar) {
        return NULL;
    } else {
        size_t slen = strlen(envvar);
        size_t buflen = slen + 1;
        char *var = (char*)malloc(buflen);
        memset(var, 0, buflen);
        strncpy(var, envvar, slen);
        return var;
    }
}

rust_env*
load_env() {
    rust_env *env = (rust_env*)malloc(sizeof(rust_env));

    env->num_sched_threads = (size_t)get_num_threads();
    env->min_stack_size = get_min_stk_size();
    env->logspec = copyenv(RUST_LOG);
    env->check_claims = getenv(CHECK_CLAIMS) != NULL;
    env->detailed_leaks = getenv(DETAILED_LEAKS) != NULL;
    env->rust_seed = copyenv(RUST_SEED);

    return env;
}

void
free_env(rust_env *env) {
    free(env->logspec);
    free(env->rust_seed);
    free(env);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#include <uavcan/marshal/float_spec.hpp>
#include <uavcan/build_config.hpp>
#include <cmath>

#if !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION
namespace uavcan
{
typedef union
{
    uint32_t u;
    float f;
} fp32;

/*
 * IEEE754Converter
 */
uint16_t IEEE754Converter::nativeIeeeToHalf(float value)
{
    /*
     * https://gist.github.com/rygorous/2156668
     * Public domain, by Fabian "ryg" Giesen
     */
    const fp32 f32infty = { 255U << 23 };
    const fp32 f16infty = { 31U << 23 };
    const fp32 magic = { 15U << 23 };
    const uint32_t sign_mask = 0x80000000U;
    const uint32_t round_mask = ~0xFFFU;

    fp32 in;
    uint16_t out;

    in.f = value;

    uint32_t sign = in.u & sign_mask;
    in.u ^= sign;

    if (in.u >= f32infty.u) /* Inf or NaN (all exponent bits set) */
    {
        /* NaN->sNaN and Inf->Inf */
        out = (in.u > f32infty.u) ? 0x7FFFU : 0x7C00U;
    }
    else /* (De)normalized number or zero */
    {
        in.u &= round_mask;
        in.f *= magic.f;
        in.u -= round_mask;
        if (in.u > f16infty.u)
        {
            in.u = f16infty.u; /* Clamp to signed infinity if overflowed */
        }

        out = uint16_t(in.u >> 13); /* Take the bits! */
    }

    out |= uint16_t(sign >> 16);

    return out;
}

float IEEE754Converter::halfToNativeIeee(uint16_t value)
{
    /*
     * https://gist.github.com/rygorous/2144712
     * Public domain, by Fabian "ryg" Giesen
     */
    const fp32 magic = { (254U - 15U) << 23 };
    const fp32 was_infnan = { (127U + 16U) << 23 };
    fp32 out;

    out.u = (value & 0x7FFFU) << 13;   /* exponent/mantissa bits */
    out.f *= magic.f;                  /* exponent adjust */
    if (out.f >= was_infnan.f)         /* make sure Inf/NaN survive */
    {
        out.u |= 255U << 23;
    }
    out.u |= (value & 0x8000U) << 16;  /* sign bit */

    return out.f;
}
}
#endif // !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION
<commit_msg>Minor style fix in IEEE754Converter; no changes to the logic<commit_after>/*
 * Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
 */

#include <uavcan/marshal/float_spec.hpp>
#include <uavcan/build_config.hpp>
#include <cmath>

namespace uavcan
{

#if !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION

union Fp32
{
    uint32_t u;
    float f;
};

/*
 * IEEE754Converter
 */
uint16_t IEEE754Converter::nativeIeeeToHalf(float value)
{
    /*
     * https://gist.github.com/rygorous/2156668
     * Public domain, by Fabian "ryg" Giesen
     */
    const Fp32 f32infty = { 255U << 23 };
    const Fp32 f16infty = { 31U << 23 };
    const Fp32 magic = { 15U << 23 };
    const uint32_t sign_mask = 0x80000000U;
    const uint32_t round_mask = ~0xFFFU;

    Fp32 in;
    uint16_t out;

    in.f = value;

    uint32_t sign = in.u & sign_mask;
    in.u ^= sign;

    if (in.u >= f32infty.u) /* Inf or NaN (all exponent bits set) */
    {
        /* NaN->sNaN and Inf->Inf */
        out = (in.u > f32infty.u) ? 0x7FFFU : 0x7C00U;
    }
    else /* (De)normalized number or zero */
    {
        in.u &= round_mask;
        in.f *= magic.f;
        in.u -= round_mask;
        if (in.u > f16infty.u)
        {
            in.u = f16infty.u; /* Clamp to signed infinity if overflowed */
        }

        out = uint16_t(in.u >> 13); /* Take the bits! */
    }

    out |= uint16_t(sign >> 16);

    return out;
}

float IEEE754Converter::halfToNativeIeee(uint16_t value)
{
    /*
     * https://gist.github.com/rygorous/2144712
     * Public domain, by Fabian "ryg" Giesen
     */
    const Fp32 magic = { (254U - 15U) << 23 };
    const Fp32 was_infnan = { (127U + 16U) << 23 };
    Fp32 out;

    out.u = (value & 0x7FFFU) << 13;   /* exponent/mantissa bits */
    out.f *= magic.f;                  /* exponent adjust */
    if (out.f >= was_infnan.f)         /* make sure Inf/NaN survive */
    {
        out.u |= 255U << 23;
    }
    out.u |= (value & 0x8000U) << 16;  /* sign bit */

    return out.f;
}

#endif // !UAVCAN_USE_EXTERNAL_FLOAT16_CONVERSION

}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program EGL Module
 * ---------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Simple Context construction test.
 *//*--------------------------------------------------------------------*/

#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"

namespace deqp
{
namespace egl
{

using std::vector;
using tcu::TestLog;
using namespace eglw;

static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };

static const struct
{
	const char*		name;
	EGLenum			api;
	EGLint			apiBit;
	const EGLint*	ctxAttrs;
} s_apis[] =
{
	{ "OpenGL",			EGL_OPENGL_API,		EGL_OPENGL_BIT,			DE_NULL		},
	{ "OpenGL ES 1",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES_BIT,		s_es1Attrs	},
	{ "OpenGL ES 2",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES2_BIT,		s_es2Attrs	},
	{ "OpenGL ES 3",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES3_BIT_KHR,	s_es3Attrs	},
	{ "OpenVG",			EGL_OPENVG_API,		EGL_OPENVG_BIT,			DE_NULL		}
};

class CreateContextCase : public SimpleConfigCase
{
public:
						CreateContextCase			(EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
						~CreateContextCase			(void);

	void				executeForConfig			(EGLDisplay display, EGLConfig config);
};

CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
	: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}

CreateContextCase::~CreateContextCase (void)
{
}

void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
	const Library&	egl		= m_eglTestCtx.getLibrary();
	TestLog&		log		= m_testCtx.getLog();
	EGLint			id		= eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
	EGLint			apiBits	= eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);

	for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
	{
		if ((apiBits & s_apis[apiNdx].apiBit) == 0)
			continue; // Not supported API

		log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
		EGLU_CHECK_MSG(egl, "init");

		EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));

		EGLContext	context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
		EGLenum		err		= egl.getError();

		if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
		{
			log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
			m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
		}
		else
		{
			// Destroy
			EGLU_CHECK_CALL(egl, destroyContext(display, context));
			log << TestLog::Message << "  Pass" << TestLog::EndMessage;
		}
	}
}

class CreateContextNoConfigCase : public TestCase
{
public:
	CreateContextNoConfigCase (EglTestContext& eglTestCtx)
		: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
	{
	}

	IterateResult iterate (void)
	{
		const eglw::Library&		egl		= m_eglTestCtx.getLibrary();
		const eglu::UniqueDisplay	display	(egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
		tcu::TestLog&				log		= m_testCtx.getLog();

		if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
			TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");

		m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");

		for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
		{
			const EGLenum	api		= s_apis[apiNdx].api;

			if (egl.bindAPI(api) == EGL_FALSE)
			{
				TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
				log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
				continue;
			}

			log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;

			const EGLContext	context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
			const EGLenum		err		= egl.getError();

			if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
			{
				log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
				m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
			}
			else
			{
				// Destroy
				EGLU_CHECK_CALL(egl, destroyContext(*display, context));
				log << TestLog::Message << "  Pass" << TestLog::EndMessage;
			}
		}

		return STOP;
	}
};

CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
	: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}

CreateContextTests::~CreateContextTests (void)
{
}

void CreateContextTests::init (void)
{
	vector<NamedFilterList>	filterLists;
	getDefaultFilterLists(filterLists, eglu::FilterList());

	for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
		addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));

	addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}

} // egl
} // deqp
<commit_msg>Handle unsupported no_config contexts am: b60ae978ad am: d9829199ed am: f35ed9f82c<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program EGL Module
 * ---------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief Simple Context construction test.
 *//*--------------------------------------------------------------------*/

#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"

namespace deqp
{
namespace egl
{

using std::vector;
using tcu::TestLog;
using namespace eglw;

static const EGLint s_glAttrs[]  = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };
static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };

static const struct
{
	const char*		name;
	EGLenum			api;
	EGLint			apiBit;
	bool			noConfigOptional;
	const EGLint*	ctxAttrs;
} s_apis[] =
{
	{ "OpenGL",			EGL_OPENGL_API,		EGL_OPENGL_BIT,			false,	s_glAttrs	},
	{ "OpenGL ES 1",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES_BIT,		true,	s_es1Attrs	},
	{ "OpenGL ES 2",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES2_BIT,		true,	s_es2Attrs	},
	{ "OpenGL ES 3",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES3_BIT_KHR,	false,	s_es3Attrs	},
	{ "OpenVG",			EGL_OPENVG_API,		EGL_OPENVG_BIT,			false,	DE_NULL		}
};

class CreateContextCase : public SimpleConfigCase
{
public:
						CreateContextCase			(EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
						~CreateContextCase			(void);

	void				executeForConfig			(EGLDisplay display, EGLConfig config);
};

CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
	: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}

CreateContextCase::~CreateContextCase (void)
{
}

void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
	const Library&	egl		= m_eglTestCtx.getLibrary();
	TestLog&		log		= m_testCtx.getLog();
	EGLint			id		= eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
	EGLint			apiBits	= eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);

	for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
	{
		if ((apiBits & s_apis[apiNdx].apiBit) == 0)
			continue; // Not supported API

		log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
		EGLU_CHECK_MSG(egl, "init");

		EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));

		EGLContext	context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
		EGLenum		err		= egl.getError();

		if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
		{
			log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
			m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
		}
		else
		{
			// Destroy
			EGLU_CHECK_CALL(egl, destroyContext(display, context));
			log << TestLog::Message << "  Pass" << TestLog::EndMessage;
		}
	}
}

class CreateContextNoConfigCase : public TestCase
{
public:
	CreateContextNoConfigCase (EglTestContext& eglTestCtx)
		: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
	{
	}

	IterateResult iterate (void)
	{
		const eglw::Library&		egl		= m_eglTestCtx.getLibrary();
		const eglu::UniqueDisplay	display	(egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
		tcu::TestLog&				log		= m_testCtx.getLog();

		if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
			TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");

		m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");

		for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
		{
			const EGLenum	api		= s_apis[apiNdx].api;

			if (egl.bindAPI(api) == EGL_FALSE)
			{
				TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
				log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
				continue;
			}

			log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;

			const EGLContext	context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
			const EGLenum		err		= egl.getError();

			if (context == EGL_NO_CONTEXT && err == EGL_BAD_MATCH && s_apis[apiNdx].noConfigOptional)
			{
				log << TestLog::Message << "  Unsupported" << TestLog::EndMessage;
			}
			else if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
			{
				log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
				m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
			}
			else
			{
				// Destroy
				EGLU_CHECK_CALL(egl, destroyContext(*display, context));
				log << TestLog::Message << "  Pass" << TestLog::EndMessage;
			}
		}

		return STOP;
	}
};

CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
	: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}

CreateContextTests::~CreateContextTests (void)
{
}

void CreateContextTests::init (void)
{
	vector<NamedFilterList>	filterLists;
	getDefaultFilterLists(filterLists, eglu::FilterList());

	for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
		addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));

	addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}

} // egl
} // deqp
<|endoftext|>


<commit_before>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else if ( argumentList.getSwitch("-snr_mom_sigmacut") )
        {
            options.snrMode = SNRMode::MomSigmaCut;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            options.downsampling = argumentList.getSwitch("-downsampling");
            if ( options.downsampling )
            {
                observation.setDownsampling(argumentList.getSwitchArgument<unsigned int>("-downsampling_factor"));
                Integration::readTunedIntegrationConf(kernelConfigurations.downsamplingParameters, argumentList.getSwitchArgument<std::string>("-downsampling_configuration"));
            }
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        else if (options.snrMode == SNRMode::MomSigmaCut)
        {
            options.nSigma = argumentList.getSwitchArgument<float>("-nsigma");
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.maxStdSigmaCutParameters, argumentList.getSwitchArgument<std::string>("-max_std_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad | -snr_mom_sigmacut] [-downsampling]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDownsampling: -downsampling_factor ... -downsampling_configuration ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
    std::cerr << "\tMOM Sigma Cut SNR: -nsigma ... -max_file ... -max_std_file ... -mom_stepone_file ... -mom_steptwo_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<commit_msg>No need to read max_file in mom_sigma_cut.<commit_after>// Copyright 2017 Netherlands Institute for Radio Astronomy (ASTRON)
// Copyright 2017 Netherlands eScience Center
//
// 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 <CommandLine.hpp>

void processCommandLineOptions(isa::utils::ArgumentList &argumentList, Options &options, DeviceOptions &deviceOptions, DataOptions &dataOptions, HostMemoryDumpFiles & hostMemoryDumpFiles, KernelConfigurations &kernelConfigurations, GeneratorOptions &generatorOptions, AstroData::Observation &observation)
{
    try
    {
        options.debug = argumentList.getSwitch("-debug");
        options.print = argumentList.getSwitch("-print");
        options.dataDump = argumentList.getSwitch("-data_dump");
        if (options.dataDump)
        {
            hostMemoryDumpFiles.dumpFilesPrefix = argumentList.getSwitchArgument<std::string>("-dump_prefix");
        }
        options.splitBatchesDedispersion = argumentList.getSwitch("-splitbatches_dedispersion");
        options.subbandDedispersion = argumentList.getSwitch("-subband_dedispersion");
        options.compactResults = argumentList.getSwitch("-compact_results");
        options.threshold = argumentList.getSwitchArgument<float>("-threshold");
        deviceOptions.platformID = argumentList.getSwitchArgument<unsigned int>("-opencl_platform");
        deviceOptions.deviceID = argumentList.getSwitchArgument<unsigned int>("-opencl_device");
        deviceOptions.deviceName = argumentList.getSwitchArgument<std::string>("-device_name");
        deviceOptions.synchronized = argumentList.getSwitch("-sync");
        AstroData::readPaddingConf(deviceOptions.padding, argumentList.getSwitchArgument<std::string>("-padding_file"));
        if (argumentList.getSwitch("-snr_standard"))
        {
            options.snrMode = SNRMode::Standard;
        }
        else if (argumentList.getSwitch("-snr_momad"))
        {
            options.snrMode = SNRMode::Momad;
        }
        else if ( argumentList.getSwitch("-snr_mom_sigmacut") )
        {
            options.snrMode = SNRMode::MomSigmaCut;
        }
        else
        {
            // Default option right now is to use the standard mode.
            options.snrMode = SNRMode::Standard;
        }
        if ( inputBits >= 8 )
        {
            options.downsampling = argumentList.getSwitch("-downsampling");
            if ( options.downsampling )
            {
                observation.setDownsampling(argumentList.getSwitchArgument<unsigned int>("-downsampling_factor"));
                Integration::readTunedIntegrationConf(kernelConfigurations.downsamplingParameters, argumentList.getSwitchArgument<std::string>("-downsampling_configuration"));
            }
        }
        dataOptions.dataLOFAR = argumentList.getSwitch("-lofar");
#ifndef HAVE_HDF5
        if (dataOptions.dataLOFAR)
        {
            std::cerr << "Not compiled with HDF5 support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_HDF5
        dataOptions.dataPSRDADA = argumentList.getSwitch("-dada");
#ifndef HAVE_PSRDADA
        if (dataOptions.dataPSRDADA)
        {
            std::cerr << "Not compiled with PSRDADA support." << std::endl;
            throw std::exception();
        };
#endif // HAVE_PSRDADA
        dataOptions.dataSIGPROC = argumentList.getSwitch("-sigproc");
        if (!((((!(dataOptions.dataLOFAR && dataOptions.dataSIGPROC) && dataOptions.dataPSRDADA) || (!(dataOptions.dataLOFAR && dataOptions.dataPSRDADA) && dataOptions.dataSIGPROC)) || (!(dataOptions.dataSIGPROC && dataOptions.dataPSRDADA) && dataOptions.dataLOFAR)) || ((!dataOptions.dataLOFAR && !dataOptions.dataSIGPROC) && !dataOptions.dataPSRDADA)))
        {
            std::cerr << "-lofar -sigproc and -dada are mutually exclusive." << std::endl;
            throw std::exception();
        }
        dataOptions.channelsFile = argumentList.getSwitchArgument<std::string>("-zapped_channels");
        dataOptions.integrationFile = argumentList.getSwitchArgument<std::string>("-integration_steps");
        if (!options.subbandDedispersion)
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionSingleStepParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_file"));
        }
        else
        {
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepOneParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_stepone_file"));
            Dedispersion::readTunedDedispersionConf(kernelConfigurations.dedispersionStepTwoParameters, argumentList.getSwitchArgument<std::string>("-dedispersion_steptwo_file"));
        }
        Integration::readTunedIntegrationConf(kernelConfigurations.integrationParameters, argumentList.getSwitchArgument<std::string>("-integration_file"));
        if (options.snrMode == SNRMode::Standard)
        {
            SNR::readTunedSNRConf(kernelConfigurations.snrParameters, argumentList.getSwitchArgument<std::string>("-snr_file"));
        }
        else if (options.snrMode == SNRMode::Momad)
        {
            SNR::readTunedSNRConf(kernelConfigurations.maxParameters, argumentList.getSwitchArgument<std::string>("-max_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansAbsoluteDeviationParameters, argumentList.getSwitchArgument<std::string>("-momad_file"));
        }
        else if (options.snrMode == SNRMode::MomSigmaCut)
        {
            options.nSigma = argumentList.getSwitchArgument<float>("-nsigma");
            SNR::readTunedSNRConf(kernelConfigurations.maxStdSigmaCutParameters, argumentList.getSwitchArgument<std::string>("-max_std_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepOneParameters, argumentList.getSwitchArgument<std::string>("-mom_stepone_file"));
            SNR::readTunedSNRConf(kernelConfigurations.medianOfMediansStepTwoParameters, argumentList.getSwitchArgument<std::string>("-mom_steptwo_file"));
        }
        if (dataOptions.dataLOFAR)
        {
#ifdef HAVE_HDF5
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.headerFile = argumentList.getSwitchArgument<std::string>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            dataOptions.limit = argumentList.getSwitch("-limit");
            if (dataOptions.limit)
            {
                observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            }
#endif // HAVE_HDF5
        }
        else if (dataOptions.dataSIGPROC)
        {
            observation.setNrBeams(1);
            observation.setNrSynthesizedBeams(1);
            dataOptions.streamingMode = argumentList.getSwitch("-stream");
            dataOptions.headerSizeSIGPROC = argumentList.getSwitchArgument<unsigned int>("-header");
            dataOptions.dataFile = argumentList.getSwitchArgument<std::string>("-data");
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
        }
        else if (dataOptions.dataPSRDADA)
        {
#ifdef HAVE_PSRDADA
            dataOptions.dadaKey = std::stoi("0x" + argumentList.getSwitchArgument<std::string>("-dada_key"), 0, 16);
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"), 1, 1.0f, 1.0f);
            }
            else
            {
                observation.setFrequencyRange(1, 1, 1.0f, 1.0f);
            }
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
#endif // HAVE_PSRDADA
        }
        else
        {
            observation.setNrBeams(argumentList.getSwitchArgument<unsigned int>("-beams"));
            observation.setNrSynthesizedBeams(argumentList.getSwitchArgument<unsigned int>("-synthesized_beams"));
            observation.setNrBatches(argumentList.getSwitchArgument<unsigned int>("-batches"));
            if (options.subbandDedispersion)
            {
                observation.setFrequencyRange(argumentList.getSwitchArgument<unsigned int>("-subbands"),
                                              argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            else
            {
                observation.setFrequencyRange(1, argumentList.getSwitchArgument<unsigned int>("-channels"),
                                              argumentList.getSwitchArgument<float>("-min_freq"),
                                              argumentList.getSwitchArgument<float>("-channel_bandwidth"));
            }
            observation.setNrSamplesPerBatch(argumentList.getSwitchArgument<unsigned int>("-samples"));
            observation.setSamplingTime(argumentList.getSwitchArgument<float>("-sampling_time"));
            generatorOptions.random = argumentList.getSwitch("-random");
            generatorOptions.width = argumentList.getSwitchArgument<unsigned int>("-width");
            generatorOptions.DM = argumentList.getSwitchArgument<float>("-dm");
        }
        dataOptions.outputFile = argumentList.getSwitchArgument<std::string>("-output");
        if (options.subbandDedispersion)
        {
            observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-subbanding_dms"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_first"),
                                   argumentList.getSwitchArgument<float>("-subbanding_dm_step"), true);
        }
        observation.setDMRange(argumentList.getSwitchArgument<unsigned int>("-dms"),
                               argumentList.getSwitchArgument<float>("-dm_first"),
                               argumentList.getSwitchArgument<float>("-dm_step"));
    }
    catch (isa::utils::EmptyCommandLine &err)
    {
        usage(argumentList.getName());
        throw;
    }
    catch (isa::utils::SwitchNotFound &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
    catch (std::exception &err)
    {
        std::cerr << err.what() << std::endl;
        throw;
    }
}

void usage(const std::string &program)
{
    std::cerr << program << " [-debug] [-print] [-data_dump] -opencl_platform ... -opencl_device ... -device_name ... [-sync]";
    std::cerr << "  -padding_file ... -zapped_channels ... -integration_steps ... -integration_file ...";
    std::cerr << " [-splitbatches_dedispersion] [-subband_dedispersion] [-snr_standard | -snr_momad | -snr_mom_sigmacut] [-downsampling]";
    std::cerr << " [-compact_results] -output ... -dms ... -dm_first ... -dm_step ... -threshold ... [-sigproc]";
#ifdef HAVE_HDF5
    std::cerr << " [-lofar]";
#endif // HAVE_HDF5
#ifdef HAVE_PSRDADA
    std::cerr << " [-dada]";
#endif // HAVE_PSRDADA
    std::cerr << std::endl;
    std::cerr << "\tData dump: -dump_prefix ..." << std::endl;
    std::cerr << "\tDownsampling: -downsampling_factor ... -downsampling_configuration ..." << std::endl;
    std::cerr << "\tDedispersion: -dedispersion_file ..." << std::endl;
    std::cerr << "\tSubband Dedispersion: -subband_dedispersion -dedispersion_stepone_file ...";
    std::cerr << "-dedispersion_steptwo_file ... -subbands ... -subbanding_dms ... -subbanding_dm_first ...";
    std::cerr << "-subbanding_dm_step ..." << std::endl;
    std::cerr << "\tStandard SNR: -snr_file" << std::endl;
    std::cerr << "\tMOMAD SNR: -max_file ... -mom_stepone_file ... -mom_steptwo_file ... -momad_file ..." << std::endl;
    std::cerr << "\tMOM Sigma Cut SNR: -nsigma ... -max_std_file ... -mom_stepone_file ... -mom_steptwo_file ..." << std::endl;
#ifdef HAVE_HDF5
    std::cerr << "\tLOFAR: -lofar -header ... -data ... [-limit]" << std::endl;
    std::cerr << "\t\t -limit -batches ..." << std::endl;
#endif // HAVE_HDF5
    std::cerr << "\tSIGPROC: -sigproc [-stream] -header ... -data ... -batches ... -channels ... -min_freq ...";
    std::cerr << "-channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
#ifdef HAVE_PSRDADA
    std::cerr << "\tPSRDADA: -dada -dada_key ... -beams ... -synthesized_beams ... -batches ..." << std::endl;
#endif // HAVE_PSRDADA
    std::cerr << "\t [-random] -width ... -dm ... -beams ... -synthesized_beams ... -batches ... -channels ...";
    std::cerr << "-min_freq ... -channel_bandwidth ... -samples ... -sampling_time ..." << std::endl;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007, Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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.
 */

#include <nsIDocShellTreeItem.h>
#include <nsComponentManagerUtils.h>
#include <nsCOMPtr.h>
#include <nsIWebBrowser.h>
#include <nsIWebBrowserFocus.h>
#include <nsIWebBrowserChrome.h>
#include <nsIEmbeddingSiteWindow.h>
#include <nsIDOMWindow2.h>
#include <nsIDOMEventTarget.h>
#include <nsIBaseWindow.h>
#include <nsIInterfaceRequestorUtils.h>
#include <jscntxt.h>
#include <nsIJSContextStack.h>
#include <nsIScriptGlobalObject.h>
#include <nsIScriptContext.h>
#include <pyxpcom/PyXPCOM.h>

#include <gtk/gtkfixed.h>
#include <gtk/gtkwindow.h>

#include "hulahop-web-view.h"

struct _HulahopWebView {
	GtkBin base_instance;

	nsCOMPtr<nsIWebBrowser>  browser;
	nsCOMPtr<nsIBaseWindow>  base_window;

    GtkWidget *offscreen_window;
    GtkWidget *mozilla_widget;
};

G_DEFINE_TYPE(HulahopWebView, hulahop_web_view, GTK_TYPE_BIN)

static GObjectClass *parent_class = NULL;

static gboolean
child_focus_in_cb(GtkWidget      *widget,
                  GdkEventFocus  *event,
                  HulahopWebView *web_view)
{
    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Activate();

    return FALSE;
}

static gboolean
child_focus_out_cb(GtkWidget      *widget,
                   GdkEventFocus  *event,
                   HulahopWebView *web_view)
{
    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Deactivate();

    return FALSE;
}

static gboolean
child_button_press_cb(GtkWidget      *widget,
                      GdkEventFocus  *event,
                      HulahopWebView *web_view)
{
    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Activate();

    return FALSE;
}

static void
hulahop_web_view_unrealize(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    gtk_widget_reparent(web_view->mozilla_widget, web_view->offscreen_window);

    GTK_WIDGET_CLASS(parent_class)->unrealize(widget);
}

void
hulahop_web_view_setup(HulahopWebView *web_view)
{
    web_view->base_window->Create();
    web_view->mozilla_widget = GTK_BIN(web_view)->child;
}

static void
hulahop_web_view_realize(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);
    GdkWindowAttr attributes;
    gint attributes_mask;

    GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);

    attributes.window_type = GDK_WINDOW_CHILD;
    attributes.x = widget->allocation.x;
    attributes.y = widget->allocation.y;
    attributes.width = widget->allocation.width;
    attributes.height = widget->allocation.height;
    attributes.wclass = GDK_INPUT_OUTPUT;
    attributes.visual = gtk_widget_get_visual(widget);
    attributes.colormap = gtk_widget_get_colormap(widget);
    attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;

    attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;

    widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
                                    &attributes, attributes_mask);
    gdk_window_set_user_data(widget->window, widget);

    widget->style = gtk_style_attach (widget->style, widget->window);
    gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);

    if (web_view->mozilla_widget) {
        gtk_widget_reparent(web_view->mozilla_widget, widget);
    } else {
        HULAHOP_WEB_VIEW_GET_CLASS(web_view)->setup(web_view);
    }

    g_assert(web_view->mozilla_widget);

    g_signal_connect_object(web_view->mozilla_widget,
                            "focus-in-event",
                            G_CALLBACK(child_focus_in_cb),
                            web_view, (GConnectFlags)0);
    g_signal_connect_object(web_view->mozilla_widget,
                            "focus-out-event",
                            G_CALLBACK(child_focus_out_cb),
                            web_view, (GConnectFlags)0);

    /*
     * xulrunner-1.9.2 doesn't like receiving click events on text inputs
     * without being told that it has been focused first. However, GTK+
     * sends button-press-event before focus-in-event, so we must use
     * button-press-event to tell mozilla that it has been given focus.
     *
     * Ordinarily, mozilla would not let us bind to button_press_event here
     * because it has it's own handler which stops emission of the signal
     * (our handler would simply not be called). This workaround will only
     * come into effect with a patched xulrunner at time of writing.
     *
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=533245
     */
    g_signal_connect_object(web_view->mozilla_widget,
                            "button-press-event",
                            G_CALLBACK(child_button_press_cb),
                            web_view, (GConnectFlags)0);
}

static void
hulahop_web_view_map(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    GTK_WIDGET_SET_FLAGS(widget, GTK_MAPPED);

    nsCOMPtr<nsIWebBrowserChrome> webBrowserChrome;
    web_view->browser->GetContainerWindow(getter_AddRefs(webBrowserChrome));
    NS_ENSURE_TRUE(webBrowserChrome, );

    nsCOMPtr<nsIEmbeddingSiteWindow> embeddingSiteWindow;
    embeddingSiteWindow = do_QueryInterface(webBrowserChrome);
    NS_ENSURE_TRUE(embeddingSiteWindow, );

    embeddingSiteWindow->SetVisibility(PR_TRUE);

    web_view->base_window->SetVisibility(PR_TRUE);

    gdk_window_show(widget->window);
}

static void
hulahop_web_view_unmap(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);

    nsCOMPtr<nsIWebBrowserChrome> webBrowserChrome;
    web_view->browser->GetContainerWindow(getter_AddRefs(webBrowserChrome));
    NS_ENSURE_TRUE(webBrowserChrome, );

    nsCOMPtr<nsIEmbeddingSiteWindow> embeddingSiteWindow;
    embeddingSiteWindow = do_QueryInterface(webBrowserChrome);
    NS_ENSURE_TRUE(embeddingSiteWindow, );

    embeddingSiteWindow->SetVisibility(PR_FALSE);

    web_view->base_window->SetVisibility(PR_FALSE);

    gdk_window_hide(widget->window);
}

static void
hulahop_web_view_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    widget->allocation = *allocation;

    if (GTK_WIDGET_REALIZED(widget)) {
        gdk_window_move_resize(widget->window,
                               allocation->x, allocation->y,
                               allocation->width, allocation->height);

        web_view->base_window->SetSize(allocation->width,
                                       allocation->height, PR_TRUE);
    }
}

static void
hulahop_web_view_dispose(GObject *object)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(object);

    if (web_view->offscreen_window) {
        gtk_widget_destroy(web_view->offscreen_window);
        web_view->offscreen_window = NULL;
    }

    if (web_view->base_window) {
        web_view->base_window->Destroy();
        web_view->base_window = NULL;
    }
}

static void
hulahop_web_view_class_init(HulahopWebViewClass *web_view_class)
{
    GObjectClass *gobject_class = G_OBJECT_CLASS(web_view_class);
    GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(web_view_class);

    parent_class = (GObjectClass *) g_type_class_peek_parent(web_view_class);

    widget_class->realize = hulahop_web_view_realize;
    widget_class->unrealize = hulahop_web_view_unrealize;
    widget_class->map = hulahop_web_view_map;
    widget_class->unmap = hulahop_web_view_unmap;
    widget_class->size_allocate = hulahop_web_view_size_allocate;

    gobject_class->dispose = hulahop_web_view_dispose;

    web_view_class->setup = hulahop_web_view_setup;
}

static void
hulahop_web_view_init(HulahopWebView *web_view)
{
    web_view->offscreen_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_widget_realize(web_view->offscreen_window);

    web_view->browser = do_CreateInstance
            ("@mozilla.org/embedding/browser/nsWebBrowser;1");
    g_assert(web_view->browser);

    nsCOMPtr<nsIDocShellTreeItem> item = do_QueryInterface(web_view->browser);
    item->SetItemType(nsIDocShellTreeItem::typeContentWrapper);

    web_view->base_window = do_QueryInterface(web_view->browser);
    g_assert(web_view->base_window);

    nsresult rv;
    rv = web_view->base_window->InitWindow(web_view, nsnull, 0, 0, 100, 100);
    g_assert(NS_SUCCEEDED(rv));

    GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(web_view), GTK_NO_WINDOW);
}

PyObject *
hulahop_web_view_get_browser(HulahopWebView *web_view)
{
    return PyObject_FromNSInterface(web_view->browser,
                                    NS_GET_IID(nsIWebBrowser));
}

PyObject *
hulahop_web_view_get_window_root(HulahopWebView *web_view)
{
    nsresult rv;

    nsCOMPtr<nsIDOMWindow> contentWindow;
    rv = web_view->browser->GetContentDOMWindow(getter_AddRefs(contentWindow));
    NS_ENSURE_SUCCESS(rv, NULL);

    nsCOMPtr<nsIDOMWindow2> domWindow(do_QueryInterface(contentWindow));
    NS_ENSURE_TRUE (domWindow, NULL);

    nsCOMPtr<nsIDOMEventTarget> eventTarget;
    domWindow->GetWindowRoot(getter_AddRefs(eventTarget));
    NS_ENSURE_TRUE (eventTarget, NULL);

    return PyObject_FromNSInterface(eventTarget,
                                    NS_GET_IID(nsIDOMEventTarget));
}

void
hulahop_web_view_grab_focus(HulahopWebView *web_view)
{
    if (web_view->mozilla_widget) {
        gtk_widget_grab_focus(web_view->mozilla_widget);
    }
}

void
hulahop_web_view_push_js_context(HulahopWebView *web_view)
{
    nsCOMPtr<nsIJSContextStack> stack(do_GetService("@mozilla.org/js/xpc/ContextStack;1"));
    nsresult rv = stack->Push(nsnull);
    g_assert(NS_SUCCEEDED(rv));
}

void
hulahop_web_view_pop_js_context(HulahopWebView *web_view)
{
    nsCOMPtr<nsIJSContextStack> stack(do_GetService("@mozilla.org/js/xpc/ContextStack;1"));
    nsresult rv = stack->Pop(nsnull);
    g_assert(NS_SUCCEEDED(rv));
}

void
hulahop_web_view_evaluate_script(HulahopWebView *web_view, const char *script)
{
    nsresult rv;

    nsCOMPtr<nsIDOMWindow> contentWindow;
    rv = web_view->browser->GetContentDOMWindow(getter_AddRefs(contentWindow));
    NS_ENSURE_SUCCESS(rv,);

    nsCOMPtr<nsIScriptGlobalObject> globalObject = do_QueryInterface(contentWindow);
	NS_ENSURE_TRUE(globalObject,);

	nsIScriptContext *context = globalObject->GetContext();
	NS_ENSURE_TRUE(context,);

    context->EvaluateString(NS_ConvertUTF8toUTF16(script), nsnull, nsnull,
                            nsnull, 0, nsnull, nsnull, nsnull);
}
<commit_msg>Use "event" signal to work around Mozilla focus issue (Daniel Drake)<commit_after>/*
 * Copyright (C) 2007, Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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.
 */

#include <nsIDocShellTreeItem.h>
#include <nsComponentManagerUtils.h>
#include <nsCOMPtr.h>
#include <nsIWebBrowser.h>
#include <nsIWebBrowserFocus.h>
#include <nsIWebBrowserChrome.h>
#include <nsIEmbeddingSiteWindow.h>
#include <nsIDOMWindow2.h>
#include <nsIDOMEventTarget.h>
#include <nsIBaseWindow.h>
#include <nsIInterfaceRequestorUtils.h>
#include <jscntxt.h>
#include <nsIJSContextStack.h>
#include <nsIScriptGlobalObject.h>
#include <nsIScriptContext.h>
#include <pyxpcom/PyXPCOM.h>

#include <gtk/gtkfixed.h>
#include <gtk/gtkwindow.h>

#include "hulahop-web-view.h"

struct _HulahopWebView {
	GtkBin base_instance;

	nsCOMPtr<nsIWebBrowser>  browser;
	nsCOMPtr<nsIBaseWindow>  base_window;

    GtkWidget *offscreen_window;
    GtkWidget *mozilla_widget;
};

G_DEFINE_TYPE(HulahopWebView, hulahop_web_view, GTK_TYPE_BIN)

static GObjectClass *parent_class = NULL;

static gboolean
child_focus_in_cb(GtkWidget      *widget,
                  GdkEventFocus  *event,
                  HulahopWebView *web_view)
{
    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Activate();

    return FALSE;
}

static gboolean
child_focus_out_cb(GtkWidget      *widget,
                   GdkEventFocus  *event,
                   HulahopWebView *web_view)
{
    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Deactivate();

    return FALSE;
}

static gboolean
child_event_cb(GtkWidget      *widget,
               GdkEvent       *event,
               HulahopWebView *web_view)
{
    if (event->type != GDK_BUTTON_PRESS)
        return FALSE;

    nsCOMPtr<nsIWebBrowserFocus> webBrowserFocus;
    webBrowserFocus = do_QueryInterface(web_view->browser);
    NS_ENSURE_TRUE(webBrowserFocus, FALSE);

    webBrowserFocus->Activate();

    return FALSE;
}

static void
hulahop_web_view_unrealize(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    gtk_widget_reparent(web_view->mozilla_widget, web_view->offscreen_window);

    GTK_WIDGET_CLASS(parent_class)->unrealize(widget);
}

void
hulahop_web_view_setup(HulahopWebView *web_view)
{
    web_view->base_window->Create();
    web_view->mozilla_widget = GTK_BIN(web_view)->child;
}

static void
hulahop_web_view_realize(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);
    GdkWindowAttr attributes;
    gint attributes_mask;

    GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);

    attributes.window_type = GDK_WINDOW_CHILD;
    attributes.x = widget->allocation.x;
    attributes.y = widget->allocation.y;
    attributes.width = widget->allocation.width;
    attributes.height = widget->allocation.height;
    attributes.wclass = GDK_INPUT_OUTPUT;
    attributes.visual = gtk_widget_get_visual(widget);
    attributes.colormap = gtk_widget_get_colormap(widget);
    attributes.event_mask = gtk_widget_get_events(widget) | GDK_EXPOSURE_MASK;

    attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;

    widget->window = gdk_window_new(gtk_widget_get_parent_window(widget),
                                    &attributes, attributes_mask);
    gdk_window_set_user_data(widget->window, widget);

    widget->style = gtk_style_attach (widget->style, widget->window);
    gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);

    if (web_view->mozilla_widget) {
        gtk_widget_reparent(web_view->mozilla_widget, widget);
    } else {
        HULAHOP_WEB_VIEW_GET_CLASS(web_view)->setup(web_view);
    }

    g_assert(web_view->mozilla_widget);

    g_signal_connect_object(web_view->mozilla_widget,
                            "focus-in-event",
                            G_CALLBACK(child_focus_in_cb),
                            web_view, (GConnectFlags)0);
    g_signal_connect_object(web_view->mozilla_widget,
                            "focus-out-event",
                            G_CALLBACK(child_focus_out_cb),
                            web_view, (GConnectFlags)0);

    /*
     * xulrunner-1.9.2 doesn't like receiving click events on text inputs
     * without being told that it has been focused first. However, GTK+
     * sends button-press-event before focus-in-event, so we must use
     * button-press-event to tell mozilla that it has been given focus.
     *
     * Mozilla does not let us bind to button_press_event here because it has
     * it's own handler which stops emission of the signal (our handler would
     * simply not be called). So, we catch the relevant event via the earlier
     * "event" signal.
     *
     * See https://bugzilla.mozilla.org/show_bug.cgi?id=533245
     */
    g_signal_connect_object(web_view->mozilla_widget,
                            "event",
                            G_CALLBACK(child_event_cb),
                            web_view, (GConnectFlags)0);
}

static void
hulahop_web_view_map(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    GTK_WIDGET_SET_FLAGS(widget, GTK_MAPPED);

    nsCOMPtr<nsIWebBrowserChrome> webBrowserChrome;
    web_view->browser->GetContainerWindow(getter_AddRefs(webBrowserChrome));
    NS_ENSURE_TRUE(webBrowserChrome, );

    nsCOMPtr<nsIEmbeddingSiteWindow> embeddingSiteWindow;
    embeddingSiteWindow = do_QueryInterface(webBrowserChrome);
    NS_ENSURE_TRUE(embeddingSiteWindow, );

    embeddingSiteWindow->SetVisibility(PR_TRUE);

    web_view->base_window->SetVisibility(PR_TRUE);

    gdk_window_show(widget->window);
}

static void
hulahop_web_view_unmap(GtkWidget *widget)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);

    nsCOMPtr<nsIWebBrowserChrome> webBrowserChrome;
    web_view->browser->GetContainerWindow(getter_AddRefs(webBrowserChrome));
    NS_ENSURE_TRUE(webBrowserChrome, );

    nsCOMPtr<nsIEmbeddingSiteWindow> embeddingSiteWindow;
    embeddingSiteWindow = do_QueryInterface(webBrowserChrome);
    NS_ENSURE_TRUE(embeddingSiteWindow, );

    embeddingSiteWindow->SetVisibility(PR_FALSE);

    web_view->base_window->SetVisibility(PR_FALSE);

    gdk_window_hide(widget->window);
}

static void
hulahop_web_view_size_allocate(GtkWidget *widget, GtkAllocation *allocation)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(widget);

    widget->allocation = *allocation;

    if (GTK_WIDGET_REALIZED(widget)) {
        gdk_window_move_resize(widget->window,
                               allocation->x, allocation->y,
                               allocation->width, allocation->height);

        web_view->base_window->SetSize(allocation->width,
                                       allocation->height, PR_TRUE);
    }
}

static void
hulahop_web_view_dispose(GObject *object)
{
    HulahopWebView *web_view = HULAHOP_WEB_VIEW(object);

    if (web_view->offscreen_window) {
        gtk_widget_destroy(web_view->offscreen_window);
        web_view->offscreen_window = NULL;
    }

    if (web_view->base_window) {
        web_view->base_window->Destroy();
        web_view->base_window = NULL;
    }
}

static void
hulahop_web_view_class_init(HulahopWebViewClass *web_view_class)
{
    GObjectClass *gobject_class = G_OBJECT_CLASS(web_view_class);
    GtkWidgetClass *widget_class = GTK_WIDGET_CLASS(web_view_class);

    parent_class = (GObjectClass *) g_type_class_peek_parent(web_view_class);

    widget_class->realize = hulahop_web_view_realize;
    widget_class->unrealize = hulahop_web_view_unrealize;
    widget_class->map = hulahop_web_view_map;
    widget_class->unmap = hulahop_web_view_unmap;
    widget_class->size_allocate = hulahop_web_view_size_allocate;

    gobject_class->dispose = hulahop_web_view_dispose;

    web_view_class->setup = hulahop_web_view_setup;
}

static void
hulahop_web_view_init(HulahopWebView *web_view)
{
    web_view->offscreen_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_widget_realize(web_view->offscreen_window);

    web_view->browser = do_CreateInstance
            ("@mozilla.org/embedding/browser/nsWebBrowser;1");
    g_assert(web_view->browser);

    nsCOMPtr<nsIDocShellTreeItem> item = do_QueryInterface(web_view->browser);
    item->SetItemType(nsIDocShellTreeItem::typeContentWrapper);

    web_view->base_window = do_QueryInterface(web_view->browser);
    g_assert(web_view->base_window);

    nsresult rv;
    rv = web_view->base_window->InitWindow(web_view, nsnull, 0, 0, 100, 100);
    g_assert(NS_SUCCEEDED(rv));

    GTK_WIDGET_UNSET_FLAGS(GTK_WIDGET(web_view), GTK_NO_WINDOW);
}

PyObject *
hulahop_web_view_get_browser(HulahopWebView *web_view)
{
    return PyObject_FromNSInterface(web_view->browser,
                                    NS_GET_IID(nsIWebBrowser));
}

PyObject *
hulahop_web_view_get_window_root(HulahopWebView *web_view)
{
    nsresult rv;

    nsCOMPtr<nsIDOMWindow> contentWindow;
    rv = web_view->browser->GetContentDOMWindow(getter_AddRefs(contentWindow));
    NS_ENSURE_SUCCESS(rv, NULL);

    nsCOMPtr<nsIDOMWindow2> domWindow(do_QueryInterface(contentWindow));
    NS_ENSURE_TRUE (domWindow, NULL);

    nsCOMPtr<nsIDOMEventTarget> eventTarget;
    domWindow->GetWindowRoot(getter_AddRefs(eventTarget));
    NS_ENSURE_TRUE (eventTarget, NULL);

    return PyObject_FromNSInterface(eventTarget,
                                    NS_GET_IID(nsIDOMEventTarget));
}

void
hulahop_web_view_grab_focus(HulahopWebView *web_view)
{
    if (web_view->mozilla_widget) {
        gtk_widget_grab_focus(web_view->mozilla_widget);
    }
}

void
hulahop_web_view_push_js_context(HulahopWebView *web_view)
{
    nsCOMPtr<nsIJSContextStack> stack(do_GetService("@mozilla.org/js/xpc/ContextStack;1"));
    nsresult rv = stack->Push(nsnull);
    g_assert(NS_SUCCEEDED(rv));
}

void
hulahop_web_view_pop_js_context(HulahopWebView *web_view)
{
    nsCOMPtr<nsIJSContextStack> stack(do_GetService("@mozilla.org/js/xpc/ContextStack;1"));
    nsresult rv = stack->Pop(nsnull);
    g_assert(NS_SUCCEEDED(rv));
}

void
hulahop_web_view_evaluate_script(HulahopWebView *web_view, const char *script)
{
    nsresult rv;

    nsCOMPtr<nsIDOMWindow> contentWindow;
    rv = web_view->browser->GetContentDOMWindow(getter_AddRefs(contentWindow));
    NS_ENSURE_SUCCESS(rv,);

    nsCOMPtr<nsIScriptGlobalObject> globalObject = do_QueryInterface(contentWindow);
	NS_ENSURE_TRUE(globalObject,);

	nsIScriptContext *context = globalObject->GetContext();
	NS_ENSURE_TRUE(context,);

    context->EvaluateString(NS_ConvertUTF8toUTF16(script), nsnull, nsnull,
                            nsnull, 0, nsnull, nsnull, nsnull);
}
<|endoftext|>


<commit_before>#include "crt.h"
#include "exp.h"
#include "exceptions.h"
#include <sstream>

namespace YAML
{
	namespace Exp
	{
		unsigned ParseHex(const std::string& str, const Mark& mark)
		{
			unsigned value = 0;
			for(std::size_t i=0;i<str.size();i++) {
				char ch = str[i];
				int digit = 0;
				if('a' <= ch && ch <= 'f')
					digit = ch - 'a' + 10;
				else if('A' <= ch && ch <= 'F')
					digit = ch - 'A' + 10;
				else if('0' <= ch && ch <= '9')
					digit = ch - '0';
				else
					throw ParserException(mark, ErrorMsg::INVALID_HEX);

				value = (value << 4) + digit;
			}

			return value;
		}

		std::string Str(unsigned ch)
		{
			return std::string("") + static_cast<char>(ch);
		}

		// Escape
		// . Translates the next 'codeLength' characters into a hex number and returns the result.
		// . Throws if it's not actually hex.
		std::string Escape(Stream& in, int codeLength)
		{
			// grab string
			std::string str;
			for(int i=0;i<codeLength;i++)
				str += in.get();

			// get the value
			unsigned value = ParseHex(str, in.mark());

			// legal unicode?
			if((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
				std::stringstream msg;
				msg << ErrorMsg::INVALID_UNICODE << value;
				throw ParserException(in.mark(), msg.str());
			}

			// now break it up into chars
			if(value <= 0x7F)
				return Str(value);
			else if(value <= 0x7FF)
				return Str(0xC0 + (value >> 6)) + Str(0x80 + (value & 0x3F));
			else if(value <= 0xFFFF)
				return Str(0xE0 + (value >> 12)) + Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F));
			else
				return Str(0xF0 + (value >> 18)) + Str(0x80 + ((value >> 12) & 0x3F)) +
					Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F));
		}

		// Escape
		// . Escapes the sequence starting 'in' (it must begin with a '\' or single quote)
		//   and returns the result.
		// . Throws if it's an unknown escape character.
		std::string Escape(Stream& in)
		{
			// eat slash
			char escape = in.get();

			// switch on escape character
			char ch = in.get();

			// first do single quote, since it's easier
			if(escape == '\'' && ch == '\'')
				return "\'";

			// now do the slash (we're not gonna check if it's a slash - you better pass one!)
			switch(ch) {
				case '0': return std::string(1, '\x00');
				case 'a': return "\x07";
				case 'b': return "\x08";
				case 't':
                case '\t': return "\x09";
				case 'n': return "\x0A";
				case 'v': return "\x0B";
				case 'f': return "\x0C";
				case 'r': return "\x0D";
				case 'e': return "\x1B";
				case ' ': return "\x20";
				case '\"': return "\"";
				case '\'': return "\'";
				case '\\': return "\\";
				case '/': return "/";
				case 'N': return "\x85";
				case '_': return "\xA0";
				case 'L': return "\xE2\x80\xA8";  // LS (#x2028)
				case 'P': return "\xE2\x80\xA9";  // PS (#x2029)
				case 'x': return Escape(in, 2);
				case 'u': return Escape(in, 4);
				case 'U': return Escape(in, 8);
			}

			std::stringstream msg;
			throw ParserException(in.mark(), ErrorMsg::INVALID_ESCAPE + ch);
		}
	}
}
<commit_msg>Small refactoring<commit_after>#include "crt.h"
#include "exp.h"
#include "exceptions.h"
#include <sstream>

namespace YAML
{
	namespace Exp
	{
		unsigned ParseHex(const std::string& str, const Mark& mark)
		{
			unsigned value = 0;
			for(std::size_t i=0;i<str.size();i++) {
				char ch = str[i];
				int digit = 0;
				if('a' <= ch && ch <= 'f')
					digit = ch - 'a' + 10;
				else if('A' <= ch && ch <= 'F')
					digit = ch - 'A' + 10;
				else if('0' <= ch && ch <= '9')
					digit = ch - '0';
				else
					throw ParserException(mark, ErrorMsg::INVALID_HEX);

				value = (value << 4) + digit;
			}

			return value;
		}

		std::string Str(unsigned ch)
		{
			return std::string(1, static_cast<char>(ch));
		}

		// Escape
		// . Translates the next 'codeLength' characters into a hex number and returns the result.
		// . Throws if it's not actually hex.
		std::string Escape(Stream& in, int codeLength)
		{
			// grab string
			std::string str;
			for(int i=0;i<codeLength;i++)
				str += in.get();

			// get the value
			unsigned value = ParseHex(str, in.mark());

			// legal unicode?
			if((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) {
				std::stringstream msg;
				msg << ErrorMsg::INVALID_UNICODE << value;
				throw ParserException(in.mark(), msg.str());
			}

			// now break it up into chars
			if(value <= 0x7F)
				return Str(value);
			else if(value <= 0x7FF)
				return Str(0xC0 + (value >> 6)) + Str(0x80 + (value & 0x3F));
			else if(value <= 0xFFFF)
				return Str(0xE0 + (value >> 12)) + Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F));
			else
				return Str(0xF0 + (value >> 18)) + Str(0x80 + ((value >> 12) & 0x3F)) +
					Str(0x80 + ((value >> 6) & 0x3F)) + Str(0x80 + (value & 0x3F));
		}

		// Escape
		// . Escapes the sequence starting 'in' (it must begin with a '\' or single quote)
		//   and returns the result.
		// . Throws if it's an unknown escape character.
		std::string Escape(Stream& in)
		{
			// eat slash
			char escape = in.get();

			// switch on escape character
			char ch = in.get();

			// first do single quote, since it's easier
			if(escape == '\'' && ch == '\'')
				return "\'";

			// now do the slash (we're not gonna check if it's a slash - you better pass one!)
			switch(ch) {
				case '0': return std::string(1, '\x00');
				case 'a': return "\x07";
				case 'b': return "\x08";
				case 't':
                case '\t': return "\x09";
				case 'n': return "\x0A";
				case 'v': return "\x0B";
				case 'f': return "\x0C";
				case 'r': return "\x0D";
				case 'e': return "\x1B";
				case ' ': return "\x20";
				case '\"': return "\"";
				case '\'': return "\'";
				case '\\': return "\\";
				case '/': return "/";
				case 'N': return "\x85";
				case '_': return "\xA0";
				case 'L': return "\xE2\x80\xA8";  // LS (#x2028)
				case 'P': return "\xE2\x80\xA9";  // PS (#x2029)
				case 'x': return Escape(in, 2);
				case 'u': return Escape(in, 4);
				case 'U': return Escape(in, 8);
			}

			std::stringstream msg;
			throw ParserException(in.mark(), ErrorMsg::INVALID_ESCAPE + ch);
		}
	}
}
<|endoftext|>


<commit_before>#include "CountPrimes.hpp"

#include <vector>

using namespace std;

int CountPrimes::countPrimes(int n) {
    int result = 0;
    vector<bool> notPrime(n, false);
    notPrime[1] = true;
    int base = 2;

    while (base * base < n) {
        // marking
        for (int i = base; i * base < n; i++)
            notPrime[i * base] = true;

        // update new base
        int i = base + 1;

        while (i < n && notPrime[i])
            i++;

        base = i;
    }

    for (int i = 1; i < n; i++)
        if (!notPrime[i])
            result++;

    return result;
}
<commit_msg>Refine Problem 204. Count Primes<commit_after>#include "CountPrimes.hpp"

#include <cmath>
#include <vector>

using namespace std;

int CountPrimes::countPrimes(int n) {
    vector<bool> prime(n, true);
    prime[0] = false, prime[1] = false;
    for (int i = 0; i < sqrt(n); i++) {
        if (prime[i]) {
            for (int j = i * i; j < n; j += i) {
                prime[j] = false;
            }
        }
    }

    int ret = 0;
    for (int i = 0; i < prime.size(); i++)
        if (prime[i]) ret++;
    return ret;
}
<|endoftext|>