<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <blas.hpp>
#include <cublas_v2.h>
#include <cuda_runtime.h>
#include <platform.hpp>

#include <arith.hpp>
#include <common/err_common.hpp>
#include <complex.hpp>
#include <cublas.hpp>
#include <err_cuda.hpp>
#include <math.hpp>
#include <reduce.hpp>
#include <cassert>
#include <stdexcept>
#include <string>

namespace cuda {

cublasOperation_t toCblasTranspose(af_mat_prop opt) {
    cublasOperation_t out = CUBLAS_OP_N;
    switch (opt) {
        case AF_MAT_NONE: out = CUBLAS_OP_N; break;
        case AF_MAT_TRANS: out = CUBLAS_OP_T; break;
        case AF_MAT_CTRANS: out = CUBLAS_OP_C; break;
        default: AF_ERROR("INVALID af_mat_prop", AF_ERR_ARG);
    }
    return out;
}

template<typename T>
struct gemm_func_def_t {
    typedef cublasStatus_t (*gemm_func_def)(cublasHandle_t, cublasOperation_t,
                                            cublasOperation_t, int, int, int,
                                            const T *, const T *, int,
                                            const T *, int, const T *, T *,
                                            int);
};

template<typename T>
struct gemmBatched_func_def_t {
    typedef cublasStatus_t (*gemmBatched_func_def)(
        cublasHandle_t, cublasOperation_t, cublasOperation_t, int, int, int,
        const T *, const T **, int, const T **, int, const T *, T **, int, int);
};

template<typename T>
struct gemv_func_def_t {
    typedef cublasStatus_t (*gemv_func_def)(cublasHandle_t, cublasOperation_t,
                                            int, int, const T *, const T *, int,
                                            const T *, int, const T *, T *,
                                            int);
};

template<typename T>
struct trsm_func_def_t {
    typedef cublasStatus_t (*trsm_func_def)(cublasHandle_t, cublasSideMode_t,
                                            cublasFillMode_t, cublasOperation_t,
                                            cublasDiagType_t, int, int,
                                            const T *, const T *, int, T *,
                                            int);
};

#define BLAS_FUNC_DEF(FUNC) \
    template<typename T>    \
    typename FUNC##_func_def_t<T>::FUNC##_func_def FUNC##_func();

#define BLAS_FUNC(FUNC, TYPE, PREFIX)                                       \
    template<>                                                              \
    typename FUNC##_func_def_t<TYPE>::FUNC##_func_def FUNC##_func<TYPE>() { \
        return (FUNC##_func_def_t<TYPE>::FUNC##_func_def) &                 \
               cublas##PREFIX##FUNC;                                        \
    }

BLAS_FUNC_DEF(gemm)
BLAS_FUNC(gemm, float, S)
BLAS_FUNC(gemm, cfloat, C)
BLAS_FUNC(gemm, double, D)
BLAS_FUNC(gemm, cdouble, Z)

BLAS_FUNC_DEF(gemmBatched)
BLAS_FUNC(gemmBatched, float, S)
BLAS_FUNC(gemmBatched, cfloat, C)
BLAS_FUNC(gemmBatched, double, D)
BLAS_FUNC(gemmBatched, cdouble, Z)

BLAS_FUNC_DEF(gemv)
BLAS_FUNC(gemv, float, S)
BLAS_FUNC(gemv, cfloat, C)
BLAS_FUNC(gemv, double, D)
BLAS_FUNC(gemv, cdouble, Z)

BLAS_FUNC_DEF(trsm)
BLAS_FUNC(trsm, float, S)
BLAS_FUNC(trsm, cfloat, C)
BLAS_FUNC(trsm, double, D)
BLAS_FUNC(trsm, cdouble, Z)

#undef BLAS_FUNC
#undef BLAS_FUNC_DEF

template<typename T, bool conjugate>
struct dot_func_def_t {
    typedef cublasStatus_t (*dot_func_def)(cublasHandle_t, int, const T *, int,
                                           const T *, int, T *);
};

#define BLAS_FUNC_DEF(FUNC)              \
    template<typename T, bool conjugate> \
    typename FUNC##_func_def_t<T, conjugate>::FUNC##_func_def FUNC##_func();

#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX)                       \
    template<>                                                         \
    typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def       \
        FUNC##_func<TYPE, CONJUGATE>() {                               \
        return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \
               cublas##PREFIX##FUNC;                                   \
    }

BLAS_FUNC_DEF(dot)
BLAS_FUNC(dot, float, true, S)
BLAS_FUNC(dot, double, true, D)
BLAS_FUNC(dot, float, false, S)
BLAS_FUNC(dot, double, false, D)

#undef BLAS_FUNC

#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX, SUFFIX)               \
    template<>                                                         \
    typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def       \
        FUNC##_func<TYPE, CONJUGATE>() {                               \
        return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \
               cublas##PREFIX##FUNC##SUFFIX;                           \
    }

BLAS_FUNC_DEF(dot)
BLAS_FUNC(dot, cfloat, true, C, c)
BLAS_FUNC(dot, cdouble, true, Z, c)
BLAS_FUNC(dot, cfloat, false, C, u)
BLAS_FUNC(dot, cdouble, false, Z, u)

#undef BLAS_FUNC
#undef BLAS_FUNC_DEF

using namespace std;

template<typename T>
Array<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,
                af_mat_prop optRhs) {
    cublasOperation_t lOpts = toCblasTranspose(optLhs);
    cublasOperation_t rOpts = toCblasTranspose(optRhs);

    int aRowDim = (lOpts == CUBLAS_OP_N) ? 0 : 1;
    int aColDim = (lOpts == CUBLAS_OP_N) ? 1 : 0;
    int bColDim = (rOpts == CUBLAS_OP_N) ? 1 : 0;

    dim4 lDims = lhs.dims();
    dim4 rDims = rhs.dims();
    int M      = lDims[aRowDim];
    int N      = rDims[bColDim];
    int K      = lDims[aColDim];

    dim_t d2     = std::max(lDims[2], rDims[2]);
    dim_t d3     = std::max(lDims[3], rDims[3]);
    dim4 oDims   = dim4(M, N, d2, d3);
    Array<T> out = createEmptyArray<T>(oDims);

    T alpha = scalar<T>(1);
    T beta  = scalar<T>(0);

    dim4 lStrides = lhs.strides();
    dim4 rStrides = rhs.strides();
    dim4 oStrides = out.strides();

    if (oDims.ndims() <= 2) {
        if (rDims[bColDim] == 1) {
            dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1];
            N          = lDims[aColDim];
            CUBLAS_CHECK(gemv_func<T>()(blasHandle(), lOpts, lDims[0], lDims[1],
                                        &alpha, lhs.get(), lStrides[1],
                                        rhs.get(), incr, &beta, out.get(), 1));
        } else {
            CUBLAS_CHECK(gemm_func<T>()(blasHandle(), lOpts, rOpts, M, N, K,
                                        &alpha, lhs.get(), lStrides[1],
                                        rhs.get(), rStrides[1], &beta,
                                        out.get(), oDims[0]));
        }
    } else {
        int batchSize = oDims[2] * oDims[3];
        std::vector<const T *> lptrs(batchSize);
        std::vector<const T *> rptrs(batchSize);
        std::vector<T *> optrs(batchSize);

        bool is_l_d2_batched = oDims[2] == lDims[2];
        bool is_l_d3_batched = oDims[3] == lDims[3];

        bool is_r_d2_batched = oDims[2] == rDims[2];
        bool is_r_d3_batched = oDims[3] == rDims[3];

        const T *lptr = lhs.get();
        const T *rptr = rhs.get();
        T *optr       = out.get();

        for (int n = 0; n < batchSize; n++) {
            int w    = n / oDims[2];
            int z    = n - w * oDims[2];
            int loff = z * (is_l_d2_batched * lStrides[2]) +
                       w * (is_l_d3_batched * lStrides[3]);
            int roff = z * (is_r_d2_batched * rStrides[2]) +
                       w * (is_r_d3_batched * rStrides[3]);
            lptrs[n] = lptr + loff;
            rptrs[n] = rptr + roff;
            optrs[n] = optr + z * oStrides[2] + w * oStrides[3];
        }

        auto d_lptrs = memAlloc<uchar>(batchSize);
        auto d_rptrs = memAlloc<uchar>(batchSize);
        auto d_optrs = memAlloc<uchar>(batchSize);

        size_t bytes = batchSize * sizeof(T **);
        CUDA_CHECK(cudaMemcpyAsync(d_lptrs.get(), lptrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));
        CUDA_CHECK(cudaMemcpyAsync(d_rptrs.get(), rptrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));
        CUDA_CHECK(cudaMemcpyAsync(d_optrs.get(), optrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));

        CUDA_CHECK(cudaStreamSynchronize(getActiveStream()));

        CUBLAS_CHECK(gemmBatched_func<T>()(
            blasHandle(), lOpts, rOpts, M, N, K, &alpha,
            (const T **)d_lptrs.get(), lStrides[1], (const T **)d_rptrs.get(),
            rStrides[1], &beta, (T **)d_optrs.get(), oStrides[1], batchSize));
    }

    return out;
}

template<typename T>
Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,
             af_mat_prop optRhs) {
    const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs));
    const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs));

    const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims());
    return reduce<af_add_t, T, T>(temp, 0, false, 0);
}

template<typename T>
void trsm(const Array<T> &lhs, Array<T> &rhs, af_mat_prop trans, bool is_upper,
          bool is_left, bool is_unit) {
    // dim4 lDims = lhs.dims();
    dim4 rDims = rhs.dims();
    int M      = rDims[0];
    int N      = rDims[1];

    T alpha = scalar<T>(1);

    dim4 lStrides = lhs.strides();
    dim4 rStrides = rhs.strides();

    CUBLAS_CHECK(trsm_func<T>()(
        blasHandle(), is_left ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT,
        is_upper ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER,
        toCblasTranspose(trans),
        is_unit ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT, M, N, &alpha,
        lhs.get(), lStrides[1], rhs.get(), rStrides[1]));
}

#define INSTANTIATE_BLAS(TYPE)                                \
    template Array<TYPE> matmul<TYPE>(const Array<TYPE> &lhs, \
                                      const Array<TYPE> &rhs, \
                                      af_mat_prop optLhs, af_mat_prop optRhs);

INSTANTIATE_BLAS(float)
INSTANTIATE_BLAS(cfloat)
INSTANTIATE_BLAS(double)
INSTANTIATE_BLAS(cdouble)

#define INSTANTIATE_DOT(TYPE)                                                  \
    template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs,                     \
                                   const Array<TYPE> &rhs, af_mat_prop optLhs, \
                                   af_mat_prop optRhs);

INSTANTIATE_DOT(float)
INSTANTIATE_DOT(double)
INSTANTIATE_DOT(cfloat)
INSTANTIATE_DOT(cdouble)

#define INSTANTIATE_TRSM(TYPE)                                               \
    template void trsm<TYPE>(const Array<TYPE> &lhs, Array<TYPE> &rhs,       \
                             af_mat_prop trans, bool is_upper, bool is_left, \
                             bool is_unit);

INSTANTIATE_TRSM(float)
INSTANTIATE_TRSM(cfloat)
INSTANTIATE_TRSM(double)
INSTANTIATE_TRSM(cdouble)

}  // namespace cuda
<commit_msg>Fix error in batch matmul because of invalid buffer size<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <blas.hpp>
#include <cublas_v2.h>
#include <cuda_runtime.h>
#include <platform.hpp>

#include <arith.hpp>
#include <common/err_common.hpp>
#include <complex.hpp>
#include <cublas.hpp>
#include <err_cuda.hpp>
#include <math.hpp>
#include <reduce.hpp>
#include <cassert>
#include <stdexcept>
#include <string>

namespace cuda {

cublasOperation_t toCblasTranspose(af_mat_prop opt) {
    cublasOperation_t out = CUBLAS_OP_N;
    switch (opt) {
        case AF_MAT_NONE: out = CUBLAS_OP_N; break;
        case AF_MAT_TRANS: out = CUBLAS_OP_T; break;
        case AF_MAT_CTRANS: out = CUBLAS_OP_C; break;
        default: AF_ERROR("INVALID af_mat_prop", AF_ERR_ARG);
    }
    return out;
}

template<typename T>
struct gemm_func_def_t {
    typedef cublasStatus_t (*gemm_func_def)(cublasHandle_t, cublasOperation_t,
                                            cublasOperation_t, int, int, int,
                                            const T *, const T *, int,
                                            const T *, int, const T *, T *,
                                            int);
};

template<typename T>
struct gemmBatched_func_def_t {
    typedef cublasStatus_t (*gemmBatched_func_def)(
        cublasHandle_t, cublasOperation_t, cublasOperation_t, int, int, int,
        const T *, const T **, int, const T **, int, const T *, T **, int, int);
};

template<typename T>
struct gemv_func_def_t {
    typedef cublasStatus_t (*gemv_func_def)(cublasHandle_t, cublasOperation_t,
                                            int, int, const T *, const T *, int,
                                            const T *, int, const T *, T *,
                                            int);
};

template<typename T>
struct trsm_func_def_t {
    typedef cublasStatus_t (*trsm_func_def)(cublasHandle_t, cublasSideMode_t,
                                            cublasFillMode_t, cublasOperation_t,
                                            cublasDiagType_t, int, int,
                                            const T *, const T *, int, T *,
                                            int);
};

#define BLAS_FUNC_DEF(FUNC) \
    template<typename T>    \
    typename FUNC##_func_def_t<T>::FUNC##_func_def FUNC##_func();

#define BLAS_FUNC(FUNC, TYPE, PREFIX)                                       \
    template<>                                                              \
    typename FUNC##_func_def_t<TYPE>::FUNC##_func_def FUNC##_func<TYPE>() { \
        return (FUNC##_func_def_t<TYPE>::FUNC##_func_def) &                 \
               cublas##PREFIX##FUNC;                                        \
    }

BLAS_FUNC_DEF(gemm)
BLAS_FUNC(gemm, float, S)
BLAS_FUNC(gemm, cfloat, C)
BLAS_FUNC(gemm, double, D)
BLAS_FUNC(gemm, cdouble, Z)

BLAS_FUNC_DEF(gemmBatched)
BLAS_FUNC(gemmBatched, float, S)
BLAS_FUNC(gemmBatched, cfloat, C)
BLAS_FUNC(gemmBatched, double, D)
BLAS_FUNC(gemmBatched, cdouble, Z)

BLAS_FUNC_DEF(gemv)
BLAS_FUNC(gemv, float, S)
BLAS_FUNC(gemv, cfloat, C)
BLAS_FUNC(gemv, double, D)
BLAS_FUNC(gemv, cdouble, Z)

BLAS_FUNC_DEF(trsm)
BLAS_FUNC(trsm, float, S)
BLAS_FUNC(trsm, cfloat, C)
BLAS_FUNC(trsm, double, D)
BLAS_FUNC(trsm, cdouble, Z)

#undef BLAS_FUNC
#undef BLAS_FUNC_DEF

template<typename T, bool conjugate>
struct dot_func_def_t {
    typedef cublasStatus_t (*dot_func_def)(cublasHandle_t, int, const T *, int,
                                           const T *, int, T *);
};

#define BLAS_FUNC_DEF(FUNC)              \
    template<typename T, bool conjugate> \
    typename FUNC##_func_def_t<T, conjugate>::FUNC##_func_def FUNC##_func();

#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX)                       \
    template<>                                                         \
    typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def       \
        FUNC##_func<TYPE, CONJUGATE>() {                               \
        return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \
               cublas##PREFIX##FUNC;                                   \
    }

BLAS_FUNC_DEF(dot)
BLAS_FUNC(dot, float, true, S)
BLAS_FUNC(dot, double, true, D)
BLAS_FUNC(dot, float, false, S)
BLAS_FUNC(dot, double, false, D)

#undef BLAS_FUNC

#define BLAS_FUNC(FUNC, TYPE, CONJUGATE, PREFIX, SUFFIX)               \
    template<>                                                         \
    typename FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def       \
        FUNC##_func<TYPE, CONJUGATE>() {                               \
        return (FUNC##_func_def_t<TYPE, CONJUGATE>::FUNC##_func_def) & \
               cublas##PREFIX##FUNC##SUFFIX;                           \
    }

BLAS_FUNC_DEF(dot)
BLAS_FUNC(dot, cfloat, true, C, c)
BLAS_FUNC(dot, cdouble, true, Z, c)
BLAS_FUNC(dot, cfloat, false, C, u)
BLAS_FUNC(dot, cdouble, false, Z, u)

#undef BLAS_FUNC
#undef BLAS_FUNC_DEF

using namespace std;

template<typename T>
Array<T> matmul(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,
                af_mat_prop optRhs) {
    cublasOperation_t lOpts = toCblasTranspose(optLhs);
    cublasOperation_t rOpts = toCblasTranspose(optRhs);

    int aRowDim = (lOpts == CUBLAS_OP_N) ? 0 : 1;
    int aColDim = (lOpts == CUBLAS_OP_N) ? 1 : 0;
    int bColDim = (rOpts == CUBLAS_OP_N) ? 1 : 0;

    dim4 lDims = lhs.dims();
    dim4 rDims = rhs.dims();
    int M      = lDims[aRowDim];
    int N      = rDims[bColDim];
    int K      = lDims[aColDim];

    dim_t d2     = std::max(lDims[2], rDims[2]);
    dim_t d3     = std::max(lDims[3], rDims[3]);
    dim4 oDims   = dim4(M, N, d2, d3);
    Array<T> out = createEmptyArray<T>(oDims);

    T alpha = scalar<T>(1);
    T beta  = scalar<T>(0);

    dim4 lStrides = lhs.strides();
    dim4 rStrides = rhs.strides();
    dim4 oStrides = out.strides();

    if (oDims.ndims() <= 2) {
        if (rDims[bColDim] == 1) {
            dim_t incr = (optRhs == AF_MAT_NONE) ? rStrides[0] : rStrides[1];
            N          = lDims[aColDim];
            CUBLAS_CHECK(gemv_func<T>()(blasHandle(), lOpts, lDims[0], lDims[1],
                                        &alpha, lhs.get(), lStrides[1],
                                        rhs.get(), incr, &beta, out.get(), 1));
        } else {
            CUBLAS_CHECK(gemm_func<T>()(blasHandle(), lOpts, rOpts, M, N, K,
                                        &alpha, lhs.get(), lStrides[1],
                                        rhs.get(), rStrides[1], &beta,
                                        out.get(), oDims[0]));
        }
    } else {
        int batchSize = oDims[2] * oDims[3];
        std::vector<const T *> lptrs(batchSize);
        std::vector<const T *> rptrs(batchSize);
        std::vector<T *> optrs(batchSize);

        bool is_l_d2_batched = oDims[2] == lDims[2];
        bool is_l_d3_batched = oDims[3] == lDims[3];

        bool is_r_d2_batched = oDims[2] == rDims[2];
        bool is_r_d3_batched = oDims[3] == rDims[3];

        const T *lptr = lhs.get();
        const T *rptr = rhs.get();
        T *optr       = out.get();

        for (int n = 0; n < batchSize; n++) {
            int w    = n / oDims[2];
            int z    = n - w * oDims[2];
            int loff = z * (is_l_d2_batched * lStrides[2]) +
                       w * (is_l_d3_batched * lStrides[3]);
            int roff = z * (is_r_d2_batched * rStrides[2]) +
                       w * (is_r_d3_batched * rStrides[3]);
            lptrs[n] = lptr + loff;
            rptrs[n] = rptr + roff;
            optrs[n] = optr + z * oStrides[2] + w * oStrides[3];
        }

        size_t bytes = batchSize * sizeof(T **);
        auto d_lptrs = memAlloc<uchar>(bytes);
        auto d_rptrs = memAlloc<uchar>(bytes);
        auto d_optrs = memAlloc<uchar>(bytes);
        CUDA_CHECK(cudaMemcpyAsync(d_lptrs.get(), lptrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));
        CUDA_CHECK(cudaMemcpyAsync(d_rptrs.get(), rptrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));
        CUDA_CHECK(cudaMemcpyAsync(d_optrs.get(), optrs.data(), bytes,
                                   cudaMemcpyHostToDevice, getActiveStream()));

        // Call this before the gemm call so that you don't have to wait for the
        // computation. Even though it would make more sense to put it
        // afterwards
        CUDA_CHECK(cudaStreamSynchronize(getActiveStream()));

        CUBLAS_CHECK(gemmBatched_func<T>()(
            blasHandle(), lOpts, rOpts, M, N, K, &alpha,
            (const T **)d_lptrs.get(), lStrides[1], (const T **)d_rptrs.get(),
            rStrides[1], &beta, (T **)d_optrs.get(), oStrides[1], batchSize));
    }

    return out;
}

template<typename T>
Array<T> dot(const Array<T> &lhs, const Array<T> &rhs, af_mat_prop optLhs,
             af_mat_prop optRhs) {
    const Array<T> lhs_ = (optLhs == AF_MAT_NONE ? lhs : conj<T>(lhs));
    const Array<T> rhs_ = (optRhs == AF_MAT_NONE ? rhs : conj<T>(rhs));

    const Array<T> temp = arithOp<T, af_mul_t>(lhs_, rhs_, lhs_.dims());
    return reduce<af_add_t, T, T>(temp, 0, false, 0);
}

template<typename T>
void trsm(const Array<T> &lhs, Array<T> &rhs, af_mat_prop trans, bool is_upper,
          bool is_left, bool is_unit) {
    // dim4 lDims = lhs.dims();
    dim4 rDims = rhs.dims();
    int M      = rDims[0];
    int N      = rDims[1];

    T alpha = scalar<T>(1);

    dim4 lStrides = lhs.strides();
    dim4 rStrides = rhs.strides();

    CUBLAS_CHECK(trsm_func<T>()(
        blasHandle(), is_left ? CUBLAS_SIDE_LEFT : CUBLAS_SIDE_RIGHT,
        is_upper ? CUBLAS_FILL_MODE_UPPER : CUBLAS_FILL_MODE_LOWER,
        toCblasTranspose(trans),
        is_unit ? CUBLAS_DIAG_UNIT : CUBLAS_DIAG_NON_UNIT, M, N, &alpha,
        lhs.get(), lStrides[1], rhs.get(), rStrides[1]));
}

#define INSTANTIATE_BLAS(TYPE)                                \
    template Array<TYPE> matmul<TYPE>(const Array<TYPE> &lhs, \
                                      const Array<TYPE> &rhs, \
                                      af_mat_prop optLhs, af_mat_prop optRhs);

INSTANTIATE_BLAS(float)
INSTANTIATE_BLAS(cfloat)
INSTANTIATE_BLAS(double)
INSTANTIATE_BLAS(cdouble)

#define INSTANTIATE_DOT(TYPE)                                                  \
    template Array<TYPE> dot<TYPE>(const Array<TYPE> &lhs,                     \
                                   const Array<TYPE> &rhs, af_mat_prop optLhs, \
                                   af_mat_prop optRhs);

INSTANTIATE_DOT(float)
INSTANTIATE_DOT(double)
INSTANTIATE_DOT(cfloat)
INSTANTIATE_DOT(cdouble)

#define INSTANTIATE_TRSM(TYPE)                                               \
    template void trsm<TYPE>(const Array<TYPE> &lhs, Array<TYPE> &rhs,       \
                             af_mat_prop trans, bool is_upper, bool is_left, \
                             bool is_unit);

INSTANTIATE_TRSM(float)
INSTANTIATE_TRSM(cfloat)
INSTANTIATE_TRSM(double)
INSTANTIATE_TRSM(cdouble)

}  // namespace cuda
<|endoftext|>


<commit_before>/*

Copyright (c) 2009-2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/bandwidth_manager.hpp"
#include "libtorrent/time.hpp"

namespace libtorrent
{

	bandwidth_manager::bandwidth_manager(int channel
#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT
		, bool log = false
#endif
		)
		: m_queued_bytes(0)
		, m_channel(channel)
		, m_abort(false)
	{
#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT
		if (log)
			m_log.open("bandwidth_limiter.log", std::ios::trunc);
		m_start = time_now();
#endif
	}

	void bandwidth_manager::close()
	{
		m_abort = true;
		m_queue.clear();
		m_queued_bytes = 0;
	}

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
	bool bandwidth_manager::is_queued(bandwidth_socket const* peer) const
	{
		for (queue_t::const_iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			if (i->peer.get() == peer) return true;
		}
		return false;
	}
#endif

	int bandwidth_manager::queue_size() const
	{
		return m_queue.size();
	}

	int bandwidth_manager::queued_bytes() const
	{
		return m_queued_bytes;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	int bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer
		, int blk, int priority
		, bandwidth_channel* chan1
		, bandwidth_channel* chan2
		, bandwidth_channel* chan3
		, bandwidth_channel* chan4
		, bandwidth_channel* chan5
		)
	{
		INVARIANT_CHECK;
		if (m_abort) return 0;

		TORRENT_ASSERT(blk > 0);
		TORRENT_ASSERT(priority > 0);
		TORRENT_ASSERT(!is_queued(peer.get()));

		bw_request bwr(peer, blk, priority);
		int i = 0;
		if (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;
		if (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;
		if (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;
		if (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;
		if (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;
		if (i == 0)
		{
			// the connection is not rate limited by any of its
			// bandwidth channels, or it doesn't belong to any
			// channels. There's no point in adding it to
			// the queue, just satisfy the request immediately
			return blk;
		}
		m_queued_bytes += blk;
		m_queue.push_back(bwr);
		return 0;
	}

#if defined TORRENT_DEBUG && !defined TORRENT_DISABLE_INVARIANT_CHECKS
	void bandwidth_manager::check_invariant() const
	{
		int queued = 0;
		for (queue_t::const_iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			queued += i->request_size - i->assigned;
		}
		TORRENT_ASSERT(queued == m_queued_bytes);
	}
#endif

	void bandwidth_manager::update_quotas(time_duration const& dt)
	{
		if (m_abort) return;
		if (m_queue.empty()) return;

		INVARIANT_CHECK;

		int dt_milliseconds = total_milliseconds(dt);
		if (dt_milliseconds > 3000) dt_milliseconds = 3000;

		// for each bandwidth channel, call update_quota(dt)

		std::vector<bandwidth_channel*> channels;

		for (queue_t::iterator i = m_queue.begin();
			i != m_queue.end();)
		{
			if (i->peer->is_disconnecting())
			{
				m_queued_bytes -= i->request_size - i->assigned;

				// return all assigned quota to all the
				// bandwidth channels this peer belongs to
				for (int j = 0; j < 5 && i->channel[j]; ++j)
				{
					bandwidth_channel* bwc = i->channel[j];
					bwc->return_quota(i->assigned);
				}

				i = m_queue.erase(i);
				continue;
			}
			for (int j = 0; j < 5 && i->channel[j]; ++j)
			{
				bandwidth_channel* bwc = i->channel[j];
				bwc->tmp = 0;
			}
			++i;
		}

		for (queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			for (int j = 0; j < 5 && i->channel[j]; ++j)
			{
				bandwidth_channel* bwc = i->channel[j];
				if (bwc->tmp == 0) channels.push_back(bwc);
				TORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority);
				bwc->tmp += i->priority;
			}
		}

		for (std::vector<bandwidth_channel*>::iterator i = channels.begin()
			, end(channels.end()); i != end; ++i)
		{
			(*i)->update_quota(dt_milliseconds);
		}

		queue_t tm;

		for (queue_t::iterator i = m_queue.begin();
			i != m_queue.end();)
		{
			int a = i->assign_bandwidth();
			if (i->assigned == i->request_size
				|| (i->ttl <= 0 && i->assigned > 0))
			{
				a += i->request_size - i->assigned;
				TORRENT_ASSERT(i->assigned <= i->request_size);
				tm.push_back(*i);
				i = m_queue.erase(i);
			}
			else
			{
				++i;
			}
			m_queued_bytes -= a;
		}

		while (!tm.empty())
		{
			bw_request& bwr = tm.back();
			bwr.peer->assign_bandwidth(m_channel, bwr.assigned);
			tm.pop_back();
		}
	}
}

<commit_msg>fix bandwidth-limit-logging build<commit_after>/*

Copyright (c) 2009-2012, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/bandwidth_manager.hpp"
#include "libtorrent/time.hpp"

namespace libtorrent
{

	bandwidth_manager::bandwidth_manager(int channel
#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT
		, bool log
#endif
		)
		: m_queued_bytes(0)
		, m_channel(channel)
		, m_abort(false)
	{
#ifdef TORRENT_VERBOSE_BANDWIDTH_LIMIT
		if (log)
			m_log.open("bandwidth_limiter.log", std::ios::trunc);
		m_start = time_now();
#endif
	}

	void bandwidth_manager::close()
	{
		m_abort = true;
		m_queue.clear();
		m_queued_bytes = 0;
	}

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
	bool bandwidth_manager::is_queued(bandwidth_socket const* peer) const
	{
		for (queue_t::const_iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			if (i->peer.get() == peer) return true;
		}
		return false;
	}
#endif

	int bandwidth_manager::queue_size() const
	{
		return m_queue.size();
	}

	int bandwidth_manager::queued_bytes() const
	{
		return m_queued_bytes;
	}

	// non prioritized means that, if there's a line for bandwidth,
	// others will cut in front of the non-prioritized peers.
	// this is used by web seeds
	int bandwidth_manager::request_bandwidth(boost::intrusive_ptr<bandwidth_socket> const& peer
		, int blk, int priority
		, bandwidth_channel* chan1
		, bandwidth_channel* chan2
		, bandwidth_channel* chan3
		, bandwidth_channel* chan4
		, bandwidth_channel* chan5
		)
	{
		INVARIANT_CHECK;
		if (m_abort) return 0;

		TORRENT_ASSERT(blk > 0);
		TORRENT_ASSERT(priority > 0);
		TORRENT_ASSERT(!is_queued(peer.get()));

		bw_request bwr(peer, blk, priority);
		int i = 0;
		if (chan1 && chan1->throttle() > 0) bwr.channel[i++] = chan1;
		if (chan2 && chan2->throttle() > 0) bwr.channel[i++] = chan2;
		if (chan3 && chan3->throttle() > 0) bwr.channel[i++] = chan3;
		if (chan4 && chan4->throttle() > 0) bwr.channel[i++] = chan4;
		if (chan5 && chan5->throttle() > 0) bwr.channel[i++] = chan5;
		if (i == 0)
		{
			// the connection is not rate limited by any of its
			// bandwidth channels, or it doesn't belong to any
			// channels. There's no point in adding it to
			// the queue, just satisfy the request immediately
			return blk;
		}
		m_queued_bytes += blk;
		m_queue.push_back(bwr);
		return 0;
	}

#if defined TORRENT_DEBUG && !defined TORRENT_DISABLE_INVARIANT_CHECKS
	void bandwidth_manager::check_invariant() const
	{
		int queued = 0;
		for (queue_t::const_iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			queued += i->request_size - i->assigned;
		}
		TORRENT_ASSERT(queued == m_queued_bytes);
	}
#endif

	void bandwidth_manager::update_quotas(time_duration const& dt)
	{
		if (m_abort) return;
		if (m_queue.empty()) return;

		INVARIANT_CHECK;

		int dt_milliseconds = total_milliseconds(dt);
		if (dt_milliseconds > 3000) dt_milliseconds = 3000;

		// for each bandwidth channel, call update_quota(dt)

		std::vector<bandwidth_channel*> channels;

		for (queue_t::iterator i = m_queue.begin();
			i != m_queue.end();)
		{
			if (i->peer->is_disconnecting())
			{
				m_queued_bytes -= i->request_size - i->assigned;

				// return all assigned quota to all the
				// bandwidth channels this peer belongs to
				for (int j = 0; j < 5 && i->channel[j]; ++j)
				{
					bandwidth_channel* bwc = i->channel[j];
					bwc->return_quota(i->assigned);
				}

				i = m_queue.erase(i);
				continue;
			}
			for (int j = 0; j < 5 && i->channel[j]; ++j)
			{
				bandwidth_channel* bwc = i->channel[j];
				bwc->tmp = 0;
			}
			++i;
		}

		for (queue_t::iterator i = m_queue.begin()
			, end(m_queue.end()); i != end; ++i)
		{
			for (int j = 0; j < 5 && i->channel[j]; ++j)
			{
				bandwidth_channel* bwc = i->channel[j];
				if (bwc->tmp == 0) channels.push_back(bwc);
				TORRENT_ASSERT(INT_MAX - bwc->tmp > i->priority);
				bwc->tmp += i->priority;
			}
		}

		for (std::vector<bandwidth_channel*>::iterator i = channels.begin()
			, end(channels.end()); i != end; ++i)
		{
			(*i)->update_quota(dt_milliseconds);
		}

		queue_t tm;

		for (queue_t::iterator i = m_queue.begin();
			i != m_queue.end();)
		{
			int a = i->assign_bandwidth();
			if (i->assigned == i->request_size
				|| (i->ttl <= 0 && i->assigned > 0))
			{
				a += i->request_size - i->assigned;
				TORRENT_ASSERT(i->assigned <= i->request_size);
				tm.push_back(*i);
				i = m_queue.erase(i);
			}
			else
			{
				++i;
			}
			m_queued_bytes -= a;
		}

		while (!tm.empty())
		{
			bw_request& bwr = tm.back();
			bwr.peer->assign_bandwidth(m_channel, bwr.assigned);
			tm.pop_back();
		}
	}
}

<|endoftext|>


<commit_before>#ifdef LINUX_PLATFORM

#include "LinuxEventLoop.hpp"

#include "Application.hpp"
#include "Context.hpp"
#include "InputService.hpp"
#include "TimeService.hpp"
#include "Global.hpp"
#include "Profiler.hpp"
#include "Render.hpp"
#include "Log.hpp"

using namespace std;

namespace MPACK
{
	namespace Core
	{
		typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);

		LinuxEventLoop::LinuxEventLoop(void *data)
			: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0),
			  m_newWidth(0), m_newHeight(0), m_enabled(false), m_glContext(NULL),
			  m_isResizing(false)
		{
		}

		ReturnValue LinuxEventLoop::Run(Application* pApplication)
		{
			m_pApplication = pApplication;
			m_isRunning=true;

			if(InitializeDisplay() == RETURN_VALUE_KO)
			{
				LOGE("LinuxEventLoop::Run failed to InitializeDisplay()");
				return RETURN_VALUE_KO;
			}
			Graphics::Render::SetScreenSize(m_width,m_height);
			m_pApplication->onActivate();

			// Global step loop.
			while(m_isRunning)
			{
				ProcessEvents();
				if(!m_isResizing)
				{
					if(m_pApplication->onStep() != RETURN_VALUE_OK)
					{
						m_isRunning=false;
					}
				}
				SwapBuffers();
			}

			m_pApplication->onDeactivate();
			DestroyDisplay();
			return RETURN_VALUE_OK;
		}

		void LinuxEventLoop::ShowCursor()
		{
			Display* mainDisplay = XOpenDisplay(NULL);

			XUndefineCursor(mainDisplay, m_XWindow);

			XCloseDisplay(mainDisplay);
		}

		void LinuxEventLoop::HideCursor()
		{
			Display* mainDisplay = XOpenDisplay(NULL);

			Pixmap blank;
			XColor dummy;
			char data[1] = {0};

			/* make a blank cursor */
			blank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);
			Cursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);
			XFreePixmap (mainDisplay, blank);

			XDefineCursor(mainDisplay, m_XWindow, m_cursor);

			XCloseDisplay(mainDisplay);
		}

		void* LinuxEventLoop::GetWindowHandle() const
		{
			return (void *)(&m_XWindow);
		}

		ReturnValue LinuxEventLoop::InitializeDisplay()
		{
			int width = 800;
			int height = 600;
			m_width = width;
			m_height = height;
			m_newWidth = width;
			m_newHeight = height;
			int bpp = 32;
			bool fullscreen=false;

			m_display = XOpenDisplay(0);

			if (m_display == NULL)
			{
				LOGE("Could not open the display");
				return RETURN_VALUE_KO;
			}

			m_screenID = DefaultScreen(m_display); //Get the default screen id
			Window root = RootWindow(m_display, m_screenID);

			int n = 0, modeNum = 0;
			XF86VidModeModeInfo **modes;
			if (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))
			{
				LOGE("Could not query the video modes");
				return RETURN_VALUE_KO;
			}

			m_XF86DeskMode = *modes[0];

			int bestMode = -1;
			for (int i = 0; i < modeNum; i++)
			{
				if ((modes[i]->hdisplay == width) &&
					(modes[i]->vdisplay == height))
				{
					bestMode = i;
				}
			}

			if (bestMode == -1)
			{
				LOGE("Could not find a suitable graphics mode");
				return RETURN_VALUE_KO;
			}

			int doubleBufferedAttribList [] = {
				GLX_RGBA, GLX_DOUBLEBUFFER,
				GLX_RED_SIZE, 4,
				GLX_GREEN_SIZE, 4,
				GLX_BLUE_SIZE, 4,
				GLX_ALPHA_SIZE, 4,
				GLX_DEPTH_SIZE, 16,
				None
			};

			XVisualInfo* vi = NULL;
			//Attempt to create a double buffered window
			vi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);

			if (vi == NULL)
			{
				LOGE("Could not create a double buffered window");
				return RETURN_VALUE_KO;
			}

			Colormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);

			m_XSetAttr.background_pixel = 0;
			m_XSetAttr.border_pixel = 0;
			m_XSetAttr.colormap = cmap;
			m_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
										StructureNotifyMask;
			m_XSetAttr.override_redirect = False;

			unsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

			if (fullscreen)
			{
				windowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

				XF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);
				XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
				m_XSetAttr.override_redirect = True;
			}

			m_XWindow = XCreateWindow(m_display, root,
										  0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
										  windowAttributes, &m_XSetAttr);

			{
				XSizeHints sizehints;
				sizehints.x = 0;
				sizehints.y = 0;
				sizehints.width  = width;
				sizehints.height = height;
				sizehints.flags = USSize | USPosition;
				XSetNormalHints(m_display, m_XWindow, &sizehints);
			}

			//Create a GL 2.1 context
			GLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);
			XFree(vi);

			if (m_glContext == NULL)
			{
				LOGE("Could not create a GL 2.1 context, please check your graphics drivers");
				return RETURN_VALUE_KO;
			}

			m_GL3Supported = false; //we're not using GL3.0 here!

			string title = "MPACK";

			if (fullscreen)
			{
				XWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);
				XMapRaised(m_display, m_XWindow);
				XGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);
				XGrabPointer(m_display, m_XWindow, True, ButtonPressMask,
							 GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);

				m_isFullscreen = true;
			}
			else
			{
				Atom wmDelete = XInternAtom(m_display, "WM_DELETE_WINDOW", True);
				XSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);

				XSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);
				XMapRaised(m_display, m_XWindow);
			}

			XFree(modes);

			//Make the new context current
			glXMakeCurrent(m_display, m_XWindow, m_glContext);

			typedef int (*PFNGLXSWAPINTERVALMESA)(int interval);
			PFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;

			glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)"glXSwapIntervalMESA");
			if( !glXSwapIntervalMESA )
			{
				 return RETURN_VALUE_KO;
			}

			glXSwapIntervalMESA(0);

			return RETURN_VALUE_OK;
		}

		void LinuxEventLoop::DestroyDisplay()
		{
			if(m_glContext)
			{
				glXMakeCurrent(m_display, None, NULL);
				glXDestroyContext(m_display, m_glContext);
				m_glContext = NULL;
			}

			if(m_isFullscreen)
			{
				XF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);
				XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
			}

			XCloseDisplay(m_display);
		}

		void LinuxEventLoop::ProcessEvents()
		{
			Global::pContext->pTimeService->Update();
			Global::pContext->pInputService->Update();

			XEvent event;

			int width, height;

			while (XPending(m_display) > 0)
			{
				XNextEvent(m_display, &event);
				switch (event.type)
				{
					case Expose:
					break;
					case ConfigureNotify:
						width = event.xconfigure.width;
						height = event.xconfigure.height;
						if(width != m_newWidth || height != m_newHeight)
						{
							m_newWidth = width;
							m_newHeight = height;
							m_isResizing = true;
						}
					break;
					case KeyPress:
						Global::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
					break;
					case KeyRelease:
						Global::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
					break;
					case ClientMessage:
						if (string(XGetAtomName(m_display, event.xclient.message_type)) == string("WM_PROTOCOLS"))
						{
							m_isRunning = false;
							return;
						}
					break;
					default:
					break;
				}
			}

			if (Global::pContext->pInputService->GetMouse()->ButtonUp(Input::MouseButton::MBC_LEFT) == 1)
			{
				if(m_isResizing)
				{
					if (m_newWidth != m_width || m_newHeight != m_height)
					{
						m_width = m_newWidth;
						m_height = m_newHeight;
						m_pApplication->onDeactivate();
						Graphics::Render::SetScreenSize(m_width,m_height);
						m_pApplication->onActivate();
					}
					m_isResizing = false;
				}
			}
		}

		void LinuxEventLoop::SwapBuffers()
		{
			PROFILE_BEGIN("SwapBuffers");
			glXSwapBuffers(m_display, m_XWindow);
			PROFILE_END();
		}
	}
}

#endif
<commit_msg>Refactor error messages<commit_after>#ifdef LINUX_PLATFORM

#include "LinuxEventLoop.hpp"

#include "Application.hpp"
#include "Context.hpp"
#include "InputService.hpp"
#include "TimeService.hpp"
#include "Global.hpp"
#include "Profiler.hpp"
#include "Render.hpp"
#include "Log.hpp"

using namespace std;

namespace MPACK
{
	namespace Core
	{
		typedef GLXContext ( * PFNGLXCREATECONTEXTATTRIBSARBPROC) (Display *dpy, GLXFBConfig config, GLXContext share_context, Bool direct, const int *attrib_list);

		LinuxEventLoop::LinuxEventLoop(void *data)
			: m_isFullscreen(false), m_isRunning(false), m_width(0), m_height(0),
			  m_newWidth(0), m_newHeight(0), m_enabled(false), m_glContext(NULL),
			  m_isResizing(false)
		{
		}

		ReturnValue LinuxEventLoop::Run(Application* pApplication)
		{
			m_pApplication = pApplication;
			m_isRunning=true;

			if(InitializeDisplay() == RETURN_VALUE_KO)
			{
				LOGE("LinuxEventLoop::Run() failed to InitializeDisplay()");
				return RETURN_VALUE_KO;
			}
			Graphics::Render::SetScreenSize(m_width,m_height);
			m_pApplication->onActivate();

			// Global step loop.
			while(m_isRunning)
			{
				ProcessEvents();
				if(!m_isResizing)
				{
					if(m_pApplication->onStep() != RETURN_VALUE_OK)
					{
						m_isRunning=false;
					}
				}
				SwapBuffers();
			}

			m_pApplication->onDeactivate();
			DestroyDisplay();
			return RETURN_VALUE_OK;
		}

		void LinuxEventLoop::ShowCursor()
		{
			Display* mainDisplay = XOpenDisplay(NULL);

			XUndefineCursor(mainDisplay, m_XWindow);

			XCloseDisplay(mainDisplay);
		}

		void LinuxEventLoop::HideCursor()
		{
			Display* mainDisplay = XOpenDisplay(NULL);

			Pixmap blank;
			XColor dummy;
			char data[1] = {0};

			/* make a blank cursor */
			blank = XCreateBitmapFromData (mainDisplay, m_XWindow, data, 1, 1);
			Cursor m_cursor = XCreatePixmapCursor(mainDisplay, blank, blank, &dummy, &dummy, 0, 0);
			XFreePixmap (mainDisplay, blank);

			XDefineCursor(mainDisplay, m_XWindow, m_cursor);

			XCloseDisplay(mainDisplay);
		}

		void* LinuxEventLoop::GetWindowHandle() const
		{
			return (void *)(&m_XWindow);
		}

		ReturnValue LinuxEventLoop::InitializeDisplay()
		{
			int width = 800;
			int height = 600;
			m_width = width;
			m_height = height;
			m_newWidth = width;
			m_newHeight = height;
			int bpp = 32;
			bool fullscreen=false;

			m_display = XOpenDisplay(0);

			if (m_display == NULL)
			{
				LOGE("LinuxEventLoop::InitializeDisplay() could not open the display");
				return RETURN_VALUE_KO;
			}

			m_screenID = DefaultScreen(m_display); //Get the default screen id
			Window root = RootWindow(m_display, m_screenID);

			int n = 0, modeNum = 0;
			XF86VidModeModeInfo **modes;
			if (!XF86VidModeGetAllModeLines(m_display, m_screenID, &modeNum, &modes))
			{
				LOGE("LinuxEventLoop::InitializeDisplay() could not query the video modes");
				return RETURN_VALUE_KO;
			}

			m_XF86DeskMode = *modes[0];

			int bestMode = -1;
			for (int i = 0; i < modeNum; i++)
			{
				if ((modes[i]->hdisplay == width) &&
					(modes[i]->vdisplay == height))
				{
					bestMode = i;
				}
			}

			if (bestMode == -1)
			{
				LOGE("LinuxEventLoop::InitializeDisplay() could not find a suitable graphics mode");
				return RETURN_VALUE_KO;
			}

			int doubleBufferedAttribList [] = {
				GLX_RGBA, GLX_DOUBLEBUFFER,
				GLX_RED_SIZE, 4,
				GLX_GREEN_SIZE, 4,
				GLX_BLUE_SIZE, 4,
				GLX_ALPHA_SIZE, 4,
				GLX_DEPTH_SIZE, 16,
				None
			};

			XVisualInfo* vi = NULL;
			//Attempt to create a double buffered window
			vi = glXChooseVisual(m_display, m_screenID, doubleBufferedAttribList);

			if (vi == NULL)
			{
				LOGE("LinuxEventLoop::InitializeDisplay() could not create a double buffered window");
				return RETURN_VALUE_KO;
			}

			Colormap cmap = XCreateColormap(m_display, root, vi->visual, AllocNone);

			m_XSetAttr.background_pixel = 0;
			m_XSetAttr.border_pixel = 0;
			m_XSetAttr.colormap = cmap;
			m_XSetAttr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask |
										StructureNotifyMask;
			m_XSetAttr.override_redirect = False;

			unsigned long windowAttributes = CWBackPixel | CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

			if (fullscreen)
			{
				windowAttributes = CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect;

				XF86VidModeSwitchToMode(m_display, m_screenID, modes[bestMode]);
				XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
				m_XSetAttr.override_redirect = True;
			}

			m_XWindow = XCreateWindow(m_display, root,
										  0, 0, width, height, 0, vi->depth, InputOutput, vi->visual,
										  windowAttributes, &m_XSetAttr);

			{
				XSizeHints sizehints;
				sizehints.x = 0;
				sizehints.y = 0;
				sizehints.width  = width;
				sizehints.height = height;
				sizehints.flags = USSize | USPosition;
				XSetNormalHints(m_display, m_XWindow, &sizehints);
			}

			//Create a GL 2.1 context
			GLXContext m_glContext = glXCreateContext(m_display, vi, 0, GL_TRUE);
			XFree(vi);

			if (m_glContext == NULL)
			{
				LOGE("LinuxEventLoop::InitializeDisplay() could not create a GL 2.1 context, please check your graphics drivers");
				return RETURN_VALUE_KO;
			}

			m_GL3Supported = false; //we're not using GL3.0 here!

			string title = "MPACK";

			if (fullscreen)
			{
				XWarpPointer(m_display, None, m_XWindow, 0, 0, 0, 0, 0, 0);
				XMapRaised(m_display, m_XWindow);
				XGrabKeyboard(m_display, m_XWindow, True, GrabModeAsync, GrabModeAsync, CurrentTime);
				XGrabPointer(m_display, m_XWindow, True, ButtonPressMask,
							 GrabModeAsync, GrabModeAsync, m_XWindow, None, CurrentTime);

				m_isFullscreen = true;
			}
			else
			{
				Atom wmDelete = XInternAtom(m_display, "WM_DELETE_WINDOW", True);
				XSetWMProtocols(m_display, m_XWindow, &wmDelete, 1);

				XSetStandardProperties(m_display, m_XWindow, title.c_str(), None, 0, NULL, 0, NULL);
				XMapRaised(m_display, m_XWindow);
			}

			XFree(modes);

			//Make the new context current
			glXMakeCurrent(m_display, m_XWindow, m_glContext);

			typedef int (*PFNGLXSWAPINTERVALMESA)(int interval);
			PFNGLXSWAPINTERVALMESA glXSwapIntervalMESA = NULL;

			glXSwapIntervalMESA = (PFNGLXSWAPINTERVALMESA)glXGetProcAddress((unsigned char*)"glXSwapIntervalMESA");
			if( !glXSwapIntervalMESA )
			{
				 return RETURN_VALUE_KO;
			}

			glXSwapIntervalMESA(0);

			return RETURN_VALUE_OK;
		}

		void LinuxEventLoop::DestroyDisplay()
		{
			if(m_glContext)
			{
				glXMakeCurrent(m_display, None, NULL);
				glXDestroyContext(m_display, m_glContext);
				m_glContext = NULL;
			}

			if(m_isFullscreen)
			{
				XF86VidModeSwitchToMode(m_display, m_screenID, &m_XF86DeskMode);
				XF86VidModeSetViewPort(m_display, m_screenID, 0, 0);
			}

			XCloseDisplay(m_display);
		}

		void LinuxEventLoop::ProcessEvents()
		{
			Global::pContext->pTimeService->Update();
			Global::pContext->pInputService->Update();

			XEvent event;

			int width, height;

			while (XPending(m_display) > 0)
			{
				XNextEvent(m_display, &event);
				switch (event.type)
				{
					case Expose:
					break;
					case ConfigureNotify:
						width = event.xconfigure.width;
						height = event.xconfigure.height;
						if(width != m_newWidth || height != m_newHeight)
						{
							m_newWidth = width;
							m_newHeight = height;
							m_isResizing = true;
						}
					break;
					case KeyPress:
						Global::pContext->pInputService->GetKeyboard()->HandleKeyDown(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
					break;
					case KeyRelease:
						Global::pContext->pInputService->GetKeyboard()->HandleKeyUp(Global::pContext->pInputService->GetKeyboard()->TranslateCode(XLookupKeysym(&event.xkey,0)));
					break;
					case ClientMessage:
						if (string(XGetAtomName(m_display, event.xclient.message_type)) == string("WM_PROTOCOLS"))
						{
							m_isRunning = false;
							return;
						}
					break;
					default:
					break;
				}
			}

			if (Global::pContext->pInputService->GetMouse()->ButtonUp(Input::MouseButton::MBC_LEFT) == 1)
			{
				if(m_isResizing)
				{
					if (m_newWidth != m_width || m_newHeight != m_height)
					{
						m_width = m_newWidth;
						m_height = m_newHeight;
						m_pApplication->onDeactivate();
						Graphics::Render::SetScreenSize(m_width,m_height);
						m_pApplication->onActivate();
					}
					m_isResizing = false;
				}
			}
		}

		void LinuxEventLoop::SwapBuffers()
		{
			PROFILE_BEGIN("SwapBuffers");
			glXSwapBuffers(m_display, m_XWindow);
			PROFILE_END();
		}
	}
}

#endif
<|endoftext|>


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

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser),
        running_(false) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    if (running_)
      MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    running_ = true;
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
    running_ = false;
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  // Are we currently running the message loop?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    if (!chromeos::ScreenLocker::GetTester()->IsLocked())
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

  void LockScreenWithUser(test::ScreenLockerTester* tester,
                          const std::string& user) {
    UserManager::Get()->UserLoggedIn(user);
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    if (!tester->IsLocked()) {
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    }
    EXPECT_TRUE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  if (!chromeos::ScreenLocker::GetTester()->IsLocked())
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            ui::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, FLAKY_TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

// See http://crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

// See http://crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  tester->SetPassword("password");
  EXPECT_EQ("password", tester->GetPassword());
  // Escape clears the password.
  ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
                            ui::VKEY_ESCAPE, false, false, false, false);
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_EQ("", tester->GetPassword());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<commit_msg>Disable crashing tests, my previous checkin to mark them flaky did not help.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop.h"
#include "chrome/browser/automation/ui_controls.h"
#include "chrome/browser/chromeos/cros/cros_in_process_browser_test.h"
#include "chrome/browser/chromeos/cros/mock_input_method_library.h"
#include "chrome/browser/chromeos/cros/mock_screen_lock_library.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_locker_tester.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/browser_dialogs.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "content/common/notification_service.h"
#include "content/common/notification_type.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "views/controls/textfield/textfield.h"
#include "views/window/window_gtk.h"

namespace {

// An object that wait for lock state and fullscreen state.
class Waiter : public NotificationObserver {
 public:
  explicit Waiter(Browser* browser)
      : browser_(browser),
        running_(false) {
    registrar_.Add(this,
                   NotificationType::SCREEN_LOCK_STATE_CHANGED,
                   NotificationService::AllSources());
    handler_id_ = g_signal_connect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        "window-state-event",
        G_CALLBACK(OnWindowStateEventThunk),
        this);
  }

  ~Waiter() {
    g_signal_handler_disconnect(
        G_OBJECT(browser_->window()->GetNativeHandle()),
        handler_id_);
  }

  virtual void Observe(NotificationType type,
                       const NotificationSource& source,
                       const NotificationDetails& details) {
    DCHECK(type == NotificationType::SCREEN_LOCK_STATE_CHANGED);
    if (running_)
      MessageLoop::current()->Quit();
  }

  // Wait until the two conditions are met.
  void Wait(bool locker_state, bool fullscreen) {
    running_ = true;
    scoped_ptr<chromeos::test::ScreenLockerTester>
        tester(chromeos::ScreenLocker::GetTester());
    while (tester->IsLocked() != locker_state ||
           browser_->window()->IsFullscreen() != fullscreen) {
      ui_test_utils::RunMessageLoop();
    }
    // Make sure all pending tasks are executed.
    ui_test_utils::RunAllPendingInMessageLoop();
    running_ = false;
  }

  CHROMEGTK_CALLBACK_1(Waiter, gboolean, OnWindowStateEvent,
                       GdkEventWindowState*);

 private:
  Browser* browser_;
  gulong handler_id_;
  NotificationRegistrar registrar_;

  // Are we currently running the message loop?
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(Waiter);
};

gboolean Waiter::OnWindowStateEvent(GtkWidget* widget,
                                    GdkEventWindowState* event) {
  MessageLoop::current()->Quit();
  return false;
}

}  // namespace

namespace chromeos {

class ScreenLockerTest : public CrosInProcessBrowserTest {
 public:
  ScreenLockerTest() : mock_screen_lock_library_(NULL),
                       mock_input_method_library_(NULL) {
  }

 protected:
  MockScreenLockLibrary *mock_screen_lock_library_;
  MockInputMethodLibrary *mock_input_method_library_;

  // Test the no password mode with different unlock scheme given by
  // |unlock| function.
  void TestNoPassword(void (unlock)(views::Widget*)) {
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    UserManager::Get()->OffTheRecordUserLoggedIn();
    ScreenLocker::Show();
    scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
    tester->EmulateWindowManagerReady();
    if (!chromeos::ScreenLocker::GetTester()->IsLocked())
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    EXPECT_TRUE(tester->IsLocked());
    tester->InjectMockAuthenticator("", "");

    unlock(tester->GetWidget());

    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_TRUE(tester->IsLocked());

    // Emulate LockScreen request from PowerManager (via SessionManager).
    ScreenLocker::Hide();
    ui_test_utils::RunAllPendingInMessageLoop();
    EXPECT_FALSE(tester->IsLocked());
  }

  void LockScreenWithUser(test::ScreenLockerTester* tester,
                          const std::string& user) {
    UserManager::Get()->UserLoggedIn(user);
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    if (!tester->IsLocked()) {
      ui_test_utils::WaitForNotification(
          NotificationType::SCREEN_LOCK_STATE_CHANGED);
    }
    EXPECT_TRUE(tester->IsLocked());
  }

 private:
  virtual void SetUpInProcessBrowserTestFixture() {
    cros_mock_->InitStatusAreaMocks();
    cros_mock_->InitMockScreenLockLibrary();
    mock_screen_lock_library_ = cros_mock_->mock_screen_lock_library();
    mock_input_method_library_ = cros_mock_->mock_input_method_library();
    EXPECT_CALL(*mock_screen_lock_library_, AddObserver(testing::_))
        .Times(1)
        .RetiresOnSaturation();
    EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockCompleted())
        .Times(1)
        .RetiresOnSaturation();
    // Expectations for the status are on the screen lock window.
    cros_mock_->SetStatusAreaMocksExpectations();
    // Expectations for the status area on the browser window.
    cros_mock_->SetStatusAreaMocksExpectations();
  }

  virtual void SetUpCommandLine(CommandLine* command_line) {
    command_line->AppendSwitchASCII(switches::kLoginProfile, "user");
    command_line->AppendSwitch(switches::kNoFirstRun);
  }

  DISALLOW_COPY_AND_ASSIGN(ScreenLockerTest);
};

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestBasic) {
  EXPECT_CALL(*mock_input_method_library_, GetNumActiveInputMethods())
      .Times(1)
      .WillRepeatedly((testing::Return(0)))
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  UserManager::Get()->UserLoggedIn("user");
  ScreenLocker::Show();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  tester->EmulateWindowManagerReady();
  if (!chromeos::ScreenLocker::GetTester()->IsLocked())
    ui_test_utils::WaitForNotification(
        NotificationType::SCREEN_LOCK_STATE_CHANGED);

  // Test to make sure that the widget is actually appearing and is of
  // reasonable size, preventing a regression of
  // http://code.google.com/p/chromium-os/issues/detail?id=5987
  gfx::Rect lock_bounds = tester->GetChildWidget()->GetWindowScreenBounds();
  EXPECT_GT(lock_bounds.width(), 10);
  EXPECT_GT(lock_bounds.height(), 10);

  tester->InjectMockAuthenticator("user", "pass");
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("fail");
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_TRUE(tester->IsLocked());
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  // Successful authentication simply send a unlock request to PowerManager.
  EXPECT_TRUE(tester->IsLocked());

  // Emulate LockScreen request from PowerManager (via SessionManager).
  // TODO(oshima): Find out better way to handle this in mock.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, TestFullscreenExit) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenUnlockRequested())
      .Times(1)
      .RetiresOnSaturation();
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  {
    Waiter waiter(browser());
    browser()->ToggleFullscreenMode();
    waiter.Wait(false /* not locked */, true /* full screen */);
    EXPECT_TRUE(browser()->window()->IsFullscreen());
    EXPECT_FALSE(tester->IsLocked());
  }
  {
    Waiter waiter(browser());
    UserManager::Get()->UserLoggedIn("user");
    ScreenLocker::Show();
    tester->EmulateWindowManagerReady();
    waiter.Wait(true /* locked */, false /* full screen */);
    EXPECT_FALSE(browser()->window()->IsFullscreen());
    EXPECT_TRUE(tester->IsLocked());
  }
  tester->InjectMockAuthenticator("user", "pass");
  tester->EnterPassword("pass");
  ui_test_utils::RunAllPendingInMessageLoop();
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

void MouseMove(views::Widget* widget) {
  ui_controls::SendMouseMove(10, 10);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithMouseMove) {
  TestNoPassword(MouseMove);
}

void MouseClick(views::Widget* widget) {
  ui_controls::SendMouseClick(ui_controls::RIGHT);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest,
    DISABLED_TestNoPasswordWithMouseClick) {
  TestNoPassword(MouseClick);
}

void KeyPress(views::Widget* widget) {
  ui_controls::SendKeyPress(GTK_WINDOW(widget->GetNativeView()),
                            ui::VKEY_SPACE, false, false, false, false);
}

IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestNoPasswordWithKeyPress) {
  TestNoPassword(KeyPress);
}

// See http://crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestShowTwice) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(2)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  // Calling Show again simply send LockCompleted signal.
  ScreenLocker::Show();
  EXPECT_TRUE(tester->IsLocked());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

// See http://crbug.com/78764.
IN_PROC_BROWSER_TEST_F(ScreenLockerTest, DISABLED_TestEscape) {
  EXPECT_CALL(*mock_screen_lock_library_, NotifyScreenLockCompleted())
      .Times(1)
      .RetiresOnSaturation();
  scoped_ptr<test::ScreenLockerTester> tester(ScreenLocker::GetTester());
  LockScreenWithUser(tester.get(), "user");

  // Ensure there's a profile or this test crashes.
  ProfileManager::GetDefaultProfile();

  tester->SetPassword("password");
  EXPECT_EQ("password", tester->GetPassword());
  // Escape clears the password.
  ui_controls::SendKeyPress(GTK_WINDOW(tester->GetWidget()->GetNativeView()),
                            ui::VKEY_ESCAPE, false, false, false, false);
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_EQ("", tester->GetPassword());

  // Close the locker to match expectations.
  ScreenLocker::Hide();
  ui_test_utils::RunAllPendingInMessageLoop();
  EXPECT_FALSE(tester->IsLocked());
}

}  // namespace chromeos
<|endoftext|>


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

#include <vector>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.

class ExtensionStartupTestBase : public InProcessBrowserTest {
 public:
  ExtensionStartupTestBase() : enable_extensions_(false) {
  }

 protected:
  // InProcessBrowserTest
  virtual void SetUpCommandLine(CommandLine* command_line) {
    EnableDOMAutomation();

    FilePath profile_dir;
    PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
    profile_dir = profile_dir.AppendASCII("Default");
    file_util::CreateDirectory(profile_dir);

    preferences_file_ = profile_dir.AppendASCII("Preferences");
    user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
    extensions_dir_ = profile_dir.AppendASCII("Extensions");

    if (enable_extensions_) {
      FilePath src_dir;
      PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
      src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");

      file_util::CopyFile(src_dir.AppendASCII("Preferences"),
                          preferences_file_);
      file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
                               profile_dir, true);  // recursive
    } else {
      command_line->AppendSwitch(switches::kDisableExtensions);
    }

    if (!load_extension_.value().empty()) {
      command_line->AppendSwitchWithValue(switches::kLoadExtension,
                                          load_extension_.ToWStringHack());
      command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck);
    }
  }

  virtual void TearDown() {
    EXPECT_TRUE(file_util::Delete(preferences_file_, false));

    // TODO(phajdan.jr): Check return values of the functions below, carefully.
    file_util::Delete(user_scripts_dir_, true);
    file_util::Delete(extensions_dir_, true);
  }

  void WaitForServicesToStart(int num_expected_extensions,
                              bool expect_extensions_enabled) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    if (!service->is_ready())
      ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
    ASSERT_TRUE(service->is_ready());

    ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
              service->extensions()->size());
    ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());

    UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
    if (!master->ScriptsReady()) {
      ui_test_utils::WaitForNotification(
          NotificationType::USER_SCRIPTS_UPDATED);
    }
    ASSERT_TRUE(master->ScriptsReady());
  }

  void TestInjection(bool expect_css, bool expect_script) {
    // Load a page affected by the content script and test to see the effect.
    FilePath test_file;
    PathService::Get(chrome::DIR_TEST_DATA, &test_file);
    test_file = test_file.AppendASCII("extensions")
                         .AppendASCII("test_file.html");

    ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));

    bool result = false;
    ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send("
        L"document.defaultView.getComputedStyle(document.body, null)."
        L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
        &result);
    EXPECT_EQ(expect_css, result);

    result = false;
    ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send(document.title == 'Modified')",
        &result);
    EXPECT_EQ(expect_script, result);
  }

  FilePath preferences_file_;
  FilePath extensions_dir_;
  FilePath user_scripts_dir_;
  bool enable_extensions_;
  FilePath load_extension_;
};

// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.

class ExtensionsStartupTest : public ExtensionStartupTestBase {
 public:
  ExtensionsStartupTest() {
    enable_extensions_ = true;
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {
  WaitForServicesToStart(4, true);  // 1 component extension and 3 others.
  TestInjection(true, true);
}

// Tests that disallowing file access on an extension prevents it from injecting
// script into a page with a file URL.
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, NoFileAccess) {
  WaitForServicesToStart(4, true);  // 1 component extension and 3 others.

  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  for (size_t i = 0; i < service->extensions()->size(); ++i) {
    if (service->AllowFileAccess(service->extensions()->at(i))) {
      service->SetAllowFileAccess(service->extensions()->at(i), false);
      ui_test_utils::WaitForNotification(
           NotificationType::USER_SCRIPTS_UPDATED);
    }
  }

  TestInjection(false, false);
}

// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.

class ExtensionsLoadTest : public ExtensionStartupTestBase {
 public:
  ExtensionsLoadTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
    load_extension_ = load_extension_
        .AppendASCII("extensions")
        .AppendASCII("good")
        .AppendASCII("Extensions")
        .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
        .AppendASCII("1.0.0.0");
  }
};

// Flaky (times out) on Mac/Windows. http://crbug.com/46301.
#if defined(OS_MACOSX) || defined(OS_WIN)
#define MAYBE_Test FLAKY_Test
#else
#define MAYBE_Test Test
#endif
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {
  WaitForServicesToStart(1, false);
  TestInjection(true, true);
}
<commit_msg>Disable ExtensionsStartupTest.NoFileAccess on Mac.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/notification_details.h"
#include "chrome/common/notification_observer.h"
#include "chrome/common/notification_registrar.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/net_util.h"

// This file contains high-level startup tests for the extensions system. We've
// had many silly bugs where command line flags did not get propagated correctly
// into the services, so we didn't start correctly.

class ExtensionStartupTestBase : public InProcessBrowserTest {
 public:
  ExtensionStartupTestBase() : enable_extensions_(false) {
  }

 protected:
  // InProcessBrowserTest
  virtual void SetUpCommandLine(CommandLine* command_line) {
    EnableDOMAutomation();

    FilePath profile_dir;
    PathService::Get(chrome::DIR_USER_DATA, &profile_dir);
    profile_dir = profile_dir.AppendASCII("Default");
    file_util::CreateDirectory(profile_dir);

    preferences_file_ = profile_dir.AppendASCII("Preferences");
    user_scripts_dir_ = profile_dir.AppendASCII("User Scripts");
    extensions_dir_ = profile_dir.AppendASCII("Extensions");

    if (enable_extensions_) {
      FilePath src_dir;
      PathService::Get(chrome::DIR_TEST_DATA, &src_dir);
      src_dir = src_dir.AppendASCII("extensions").AppendASCII("good");

      file_util::CopyFile(src_dir.AppendASCII("Preferences"),
                          preferences_file_);
      file_util::CopyDirectory(src_dir.AppendASCII("Extensions"),
                               profile_dir, true);  // recursive
    } else {
      command_line->AppendSwitch(switches::kDisableExtensions);
    }

    if (!load_extension_.value().empty()) {
      command_line->AppendSwitchWithValue(switches::kLoadExtension,
                                          load_extension_.ToWStringHack());
      command_line->AppendSwitch(switches::kDisableExtensionsFileAccessCheck);
    }
  }

  virtual void TearDown() {
    EXPECT_TRUE(file_util::Delete(preferences_file_, false));

    // TODO(phajdan.jr): Check return values of the functions below, carefully.
    file_util::Delete(user_scripts_dir_, true);
    file_util::Delete(extensions_dir_, true);
  }

  void WaitForServicesToStart(int num_expected_extensions,
                              bool expect_extensions_enabled) {
    ExtensionsService* service = browser()->profile()->GetExtensionsService();
    if (!service->is_ready())
      ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY);
    ASSERT_TRUE(service->is_ready());

    ASSERT_EQ(static_cast<uint32>(num_expected_extensions),
              service->extensions()->size());
    ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled());

    UserScriptMaster* master = browser()->profile()->GetUserScriptMaster();
    if (!master->ScriptsReady()) {
      ui_test_utils::WaitForNotification(
          NotificationType::USER_SCRIPTS_UPDATED);
    }
    ASSERT_TRUE(master->ScriptsReady());
  }

  void TestInjection(bool expect_css, bool expect_script) {
    // Load a page affected by the content script and test to see the effect.
    FilePath test_file;
    PathService::Get(chrome::DIR_TEST_DATA, &test_file);
    test_file = test_file.AppendASCII("extensions")
                         .AppendASCII("test_file.html");

    ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file));

    bool result = false;
    ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send("
        L"document.defaultView.getComputedStyle(document.body, null)."
        L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')",
        &result);
    EXPECT_EQ(expect_css, result);

    result = false;
    ui_test_utils::ExecuteJavaScriptAndExtractBool(
        browser()->GetSelectedTabContents()->render_view_host(), L"",
        L"window.domAutomationController.send(document.title == 'Modified')",
        &result);
    EXPECT_EQ(expect_script, result);
  }

  FilePath preferences_file_;
  FilePath extensions_dir_;
  FilePath user_scripts_dir_;
  bool enable_extensions_;
  FilePath load_extension_;
};

// ExtensionsStartupTest
// Ensures that we can startup the browser with --enable-extensions and some
// extensions installed and see them run and do basic things.

class ExtensionsStartupTest : public ExtensionStartupTestBase {
 public:
  ExtensionsStartupTest() {
    enable_extensions_ = true;
  }
};

IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) {
  WaitForServicesToStart(4, true);  // 1 component extension and 3 others.
  TestInjection(true, true);
}

// Sometimes times out on Mac.  http://crbug.com/48151
#if defined(OS_MACOSX)
#define MAYBE_NoFileAccess DISABLED_NoFileAccess
#else
#define MAYBE_NoFileAccess NoFileAccess
#endif
// Tests that disallowing file access on an extension prevents it from injecting
// script into a page with a file URL.
IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_NoFileAccess) {
  WaitForServicesToStart(4, true);  // 1 component extension and 3 others.

  ExtensionsService* service = browser()->profile()->GetExtensionsService();
  for (size_t i = 0; i < service->extensions()->size(); ++i) {
    if (service->AllowFileAccess(service->extensions()->at(i))) {
      service->SetAllowFileAccess(service->extensions()->at(i), false);
      ui_test_utils::WaitForNotification(
           NotificationType::USER_SCRIPTS_UPDATED);
    }
  }

  TestInjection(false, false);
}

// ExtensionsLoadTest
// Ensures that we can startup the browser with --load-extension and see them
// run.

class ExtensionsLoadTest : public ExtensionStartupTestBase {
 public:
  ExtensionsLoadTest() {
    PathService::Get(chrome::DIR_TEST_DATA, &load_extension_);
    load_extension_ = load_extension_
        .AppendASCII("extensions")
        .AppendASCII("good")
        .AppendASCII("Extensions")
        .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
        .AppendASCII("1.0.0.0");
  }
};

// Flaky (times out) on Mac/Windows. http://crbug.com/46301.
#if defined(OS_MACOSX) || defined(OS_WIN)
#define MAYBE_Test FLAKY_Test
#else
#define MAYBE_Test Test
#endif
IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) {
  WaitForServicesToStart(1, false);
  TestInjection(true, true);
}
<|endoftext|>


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

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif

//........................................................................
namespace connectivity
{
//........................................................................

    namespace hsqldb
    {
        class ODriverDelegator;
        class OConnectionController : public ::cppu::WeakImplHelper2<
                                                    ::com::sun::star::lang::XServiceInfo,
                                                    ::com::sun::star::frame::XTerminateListener >
        {
            ODriverDelegator* m_pDriver;
            protected:
                virtual ~OConnectionController() {m_pDriver = NULL;}
            public:
                OConnectionController(ODriverDelegator* _pDriver) : m_pDriver(_pDriver){}

                // XServiceInfo
                virtual ::rtl::OUString SAL_CALL getImplementationName()
                    throw ( ::com::sun::star::uno::RuntimeException );
                virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
                    throw ( ::com::sun::star::uno::RuntimeException );
                virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                    throw ( ::com::sun::star::uno::RuntimeException );

                // XEventListener
                virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                    throw( ::com::sun::star::uno::RuntimeException );

                // XTerminateListener
                virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
                    throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException );
                virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
                    throw( ::com::sun::star::uno::RuntimeException );
        };
    }
//........................................................................
}   // namespace connectivity
//........................................................................
#endif // CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.94); FILE MERGED 2005/09/05 17:24:03 rt 1.2.94.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: HTerminateListener.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:05:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX
#define CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX

#ifndef _CPPUHELPER_COMPBASE2_HXX_
#include <cppuhelper/compbase2.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XTERMINATELISTENER_HPP_
#include <com/sun/star/frame/XTerminateListener.hpp>
#endif

//........................................................................
namespace connectivity
{
//........................................................................

    namespace hsqldb
    {
        class ODriverDelegator;
        class OConnectionController : public ::cppu::WeakImplHelper2<
                                                    ::com::sun::star::lang::XServiceInfo,
                                                    ::com::sun::star::frame::XTerminateListener >
        {
            ODriverDelegator* m_pDriver;
            protected:
                virtual ~OConnectionController() {m_pDriver = NULL;}
            public:
                OConnectionController(ODriverDelegator* _pDriver) : m_pDriver(_pDriver){}

                // XServiceInfo
                virtual ::rtl::OUString SAL_CALL getImplementationName()
                    throw ( ::com::sun::star::uno::RuntimeException );
                virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
                    throw ( ::com::sun::star::uno::RuntimeException );
                virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
                    throw ( ::com::sun::star::uno::RuntimeException );

                // XEventListener
                virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source )
                    throw( ::com::sun::star::uno::RuntimeException );

                // XTerminateListener
                virtual void SAL_CALL queryTermination( const ::com::sun::star::lang::EventObject& aEvent )
                    throw( ::com::sun::star::frame::TerminationVetoException, ::com::sun::star::uno::RuntimeException );
                virtual void SAL_CALL notifyTermination( const ::com::sun::star::lang::EventObject& aEvent )
                    throw( ::com::sun::star::uno::RuntimeException );
        };
    }
//........................................................................
}   // namespace connectivity
//........................................................................
#endif // CONNECTIVITY_HSQLDB_TERMINATELISTENER_HXX
<|endoftext|>


<commit_before><commit_msg>Throw sane exception when wrong type used in PreparedStatement.<commit_after><|endoftext|>


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

#include "chrome/browser/ui/views/location_bar/location_icon_view.h"

LocationIconView::LocationIconView(const LocationBarView* location_bar)
    : ALLOW_THIS_IN_INITIALIZER_LIST(click_handler_(this, location_bar)) {
}

LocationIconView::~LocationIconView() {
}

bool LocationIconView::OnMousePressed(const views::MouseEvent& event) {
  // We want to show the dialog on mouse release; that is the standard behavior
  // for buttons.
  return true;
}

void LocationIconView::OnMouseReleased(const views::MouseEvent& event,
                                       bool canceled) {
  click_handler_.OnMouseReleased(event, canceled);
}
<commit_msg>views: Show a tooltip for the location icon in the omnibox.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/location_bar/location_icon_view.h"

#include "base/utf_string_conversions.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

LocationIconView::LocationIconView(const LocationBarView* location_bar)
    : ALLOW_THIS_IN_INITIALIZER_LIST(click_handler_(this, location_bar)) {
  SetTooltipText(UTF16ToWide(l10n_util::GetStringUTF16(
      IDS_TOOLTIP_LOCATION_ICON)));
}

LocationIconView::~LocationIconView() {
}

bool LocationIconView::OnMousePressed(const views::MouseEvent& event) {
  // We want to show the dialog on mouse release; that is the standard behavior
  // for buttons.
  return true;
}

void LocationIconView::OnMouseReleased(const views::MouseEvent& event,
                                       bool canceled) {
  click_handler_.OnMouseReleased(event, canceled);
}
<|endoftext|>