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

#include "MCTargetDesc/RISCVMCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

namespace {
class RISCVELFObjectWriter : public MCELFObjectTargetWriter {
public:
  RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit);

  ~RISCVELFObjectWriter() override;

protected:
  unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
                        const MCFixup &Fixup, bool IsPCRel) const override;
};
}

RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
    : MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV,
                              /*HasRelocationAddend*/ false) {}

RISCVELFObjectWriter::~RISCVELFObjectWriter() {}

unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx,
                                            const MCValue &Target,
                                            const MCFixup &Fixup,
                                            bool IsPCRel) const {
  // Determine the type of the relocation
  switch ((unsigned)Fixup.getKind()) {
  default:
    llvm_unreachable("invalid fixup kind!");
  }
}

MCObjectWriter *llvm::createRISCVELFObjectWriter(raw_pwrite_stream &OS,
                                                 uint8_t OSABI, bool Is64Bit) {
  MCELFObjectTargetWriter *MOTW = new RISCVELFObjectWriter(OSABI, Is64Bit);
  return createELFObjectWriter(MOTW, OS, /*IsLittleEndian*/ true);
}
<commit_msg>Removing a switch statement that contains a default label, but no case labels. Silences an MSVC warning; NFC.<commit_after>//===-- RISCVELFObjectWriter.cpp - RISCV ELF Writer -----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "MCTargetDesc/RISCVMCTargetDesc.h"
#include "llvm/MC/MCELFObjectWriter.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/Support/ErrorHandling.h"

using namespace llvm;

namespace {
class RISCVELFObjectWriter : public MCELFObjectTargetWriter {
public:
  RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit);

  ~RISCVELFObjectWriter() override;

protected:
  unsigned getRelocType(MCContext &Ctx, const MCValue &Target,
                        const MCFixup &Fixup, bool IsPCRel) const override;
};
}

RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit)
    : MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV,
                              /*HasRelocationAddend*/ false) {}

RISCVELFObjectWriter::~RISCVELFObjectWriter() {}

unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx,
                                            const MCValue &Target,
                                            const MCFixup &Fixup,
                                            bool IsPCRel) const {
  llvm_unreachable("invalid fixup kind!");
}

MCObjectWriter *llvm::createRISCVELFObjectWriter(raw_pwrite_stream &OS,
                                                 uint8_t OSABI, bool Is64Bit) {
  MCELFObjectTargetWriter *MOTW = new RISCVELFObjectWriter(OSABI, Is64Bit);
  return createELFObjectWriter(MOTW, OS, /*IsLittleEndian*/ true);
}
<|endoftext|>


<commit_before>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <algorithm>

#include "bm_sim/fields.h"

int Field::extract(const char *data, int hdr_offset) {
  if(hdr_offset == 0 && nbits % 8 == 0) {
    std::copy(data, data + nbytes, bytes.begin());
    if(arith) sync_value();
    return nbits;
  }

  int field_offset = (nbytes << 3) - nbits;
  int i;

  // necessary to ensure correct behavior when shifting right (no sign extension)
  unsigned char *udata = (unsigned char *) data;

  int offset = hdr_offset - field_offset;
  if (offset == 0) {
    std::copy(udata, udata + nbytes, bytes.begin());
    bytes[0] &= (0xFF >> field_offset);
  }
  else if (offset > 0) { /* shift left */
    for (i = 0; i < nbytes - 1; i++) {
      bytes[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset));
    }
    bytes[0] &= (0xFF >> field_offset);
    bytes[i] = udata[i] << offset;
    if((hdr_offset + nbits) > (nbytes << 3)) {
      bytes[i] |= (udata[i + 1] >> (8 - offset));
    }
  }
  else { /* shift right */
    offset = -offset;
    bytes[0] = udata[0] >> offset;
    for (i = 1; i < nbytes; i++) {
      bytes[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);
    }
  }

  if(arith) sync_value();

  return nbits;
}

int Field::deparse(char *data, int hdr_offset) const {
  if(hdr_offset == 0 && nbits % 8 == 0) {
    std::copy(bytes.begin(), bytes.end(), data);
    return nbits;
  }

  int field_offset = (nbytes << 3) - nbits;
  int hdr_bytes = (hdr_offset + nbits + 7) / 8;

  int i;

  // zero out bits we are going to write in data[0]
  data[0] &= (~(0xFF >> hdr_offset));

  int offset = field_offset - hdr_offset;
  if (offset == 0) {
    std::copy(bytes.begin() + 1, bytes.begin() + hdr_bytes, data + 1);
    data[0] |= bytes[0];
  }
  else if (offset > 0) { /* shift left */
    /* this assumes that the packet was memset to 0, TODO: improve */
    for (i = 0; i < hdr_bytes - 1; i++) {
      data[i] |= (bytes[i] << offset) | (bytes[i + 1] >> (8 - offset));
    }
    int tail_offset = (hdr_bytes << 3) - (hdr_offset + nbits);
    data[i] &= ((1 << tail_offset) - 1);
    data[i] |= bytes[i] << offset;
    if((field_offset + nbits) > (hdr_bytes << 3)) {
      data[i] |= (bytes[i + 1] >> (8 - offset));
    }
  }
  else { /* shift right */
    offset = -offset;
    data[0] |= (bytes[0] >> offset);
    if(hdr_bytes == 1) return nbits;
    for (i = 1; i < hdr_bytes - 1; i++) {
      data[i] = (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset);
    }
    int tail_offset = (hdr_bytes >> 3) - (hdr_offset + nbits);
    data[i] &= ((1 << tail_offset) - 1);
    data[i] |= (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset);
  }

  return nbits;
}
<commit_msg>fixed bug in deparser (yesterday's fix was wrong)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <algorithm>

#include "bm_sim/fields.h"

int Field::extract(const char *data, int hdr_offset) {
  if(hdr_offset == 0 && nbits % 8 == 0) {
    std::copy(data, data + nbytes, bytes.begin());
    if(arith) sync_value();
    return nbits;
  }

  int field_offset = (nbytes << 3) - nbits;
  int i;

  // necessary to ensure correct behavior when shifting right (no sign extension)
  unsigned char *udata = (unsigned char *) data;

  int offset = hdr_offset - field_offset;
  if (offset == 0) {
    std::copy(udata, udata + nbytes, bytes.begin());
    bytes[0] &= (0xFF >> field_offset);
  }
  else if (offset > 0) { /* shift left */
    for (i = 0; i < nbytes - 1; i++) {
      bytes[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset));
    }
    bytes[0] &= (0xFF >> field_offset);
    bytes[i] = udata[i] << offset;
    if((hdr_offset + nbits) > (nbytes << 3)) {
      bytes[i] |= (udata[i + 1] >> (8 - offset));
    }
  }
  else { /* shift right */
    offset = -offset;
    bytes[0] = udata[0] >> offset;
    for (i = 1; i < nbytes; i++) {
      bytes[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset);
    }
  }

  if(arith) sync_value();

  return nbits;
}

int Field::deparse(char *data, int hdr_offset) const {
  if(hdr_offset == 0 && nbits % 8 == 0) {
    std::copy(bytes.begin(), bytes.end(), data);
    return nbits;
  }

  int field_offset = (nbytes << 3) - nbits;
  int hdr_bytes = (hdr_offset + nbits + 7) / 8;

  int i;

  // zero out bits we are going to write in data[0]
  data[0] &= (~(0xFF >> hdr_offset));

  int offset = field_offset - hdr_offset;
  if (offset == 0) {
    std::copy(bytes.begin() + 1, bytes.begin() + hdr_bytes, data + 1);
    data[0] |= bytes[0];
  }
  else if (offset > 0) { /* shift left */
    /* this assumes that the packet was memset to 0, TODO: improve */
    for (i = 0; i < hdr_bytes - 1; i++) {
      data[i] |= (bytes[i] << offset) | (bytes[i + 1] >> (8 - offset));
    }
    int tail_offset = (hdr_bytes << 3) - (hdr_offset + nbits);
    data[i] &= ((1 << tail_offset) - 1);
    data[i] |= bytes[i] << offset;
    if((field_offset + nbits) > (hdr_bytes << 3)) {
      data[i] |= (bytes[i + 1] >> (8 - offset));
    }
  }
  else { /* shift right */
    offset = -offset;
    data[0] |= (bytes[0] >> offset);
    if(nbytes == 1) return nbits;
    for (i = 1; i < hdr_bytes - 1; i++) {
      data[i] = (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset);
    }
    int tail_offset = (hdr_bytes >> 3) - (hdr_offset + nbits);
    data[i] &= ((1 << tail_offset) - 1);
    data[i] |= (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset);
  }

  return nbits;
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include "precomp.hpp"
using namespace std;
#ifdef HAVE_CLAMDFFT
////////////////////////////////////////////////////////////////////////////
// Dft
PARAM_TEST_CASE(Dft, cv::Size, int)
{
    cv::Size dft_size;
    int	 dft_flags;
    virtual void SetUp()
    {
        dft_size  = GET_PARAM(0);
        dft_flags = GET_PARAM(1);
    }
};

TEST_P(Dft, C2C)
{
    cv::Mat a = randomMat(dft_size, CV_32FC2, 0.0, 100.0);
    cv::Mat b_gold;

    cv::ocl::oclMat d_b;

    cv::dft(a, b_gold, dft_flags);
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags);
    EXPECT_MAT_NEAR(b_gold, cv::Mat(d_b), a.size().area() * 1e-4);
}

TEST_P(Dft, R2C)
{
    cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 100.0);
    cv::Mat b_gold, b_gold_roi;

    cv::ocl::oclMat d_b, d_c;
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags);
    cv::dft(a, b_gold, cv::DFT_COMPLEX_OUTPUT | dft_flags);

    b_gold_roi = b_gold(cv::Rect(0, 0, d_b.cols, d_b.rows));
    EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4);

    cv::Mat c_gold;
    cv::dft(b_gold, c_gold, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
    EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4);
}

TEST_P(Dft, R2CthenC2R)
{
    cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 10.0);

    cv::ocl::oclMat d_b, d_c;
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), 0);
    cv::ocl::dft(d_b, d_c, a.size(), cv::DFT_SCALE | cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT);
    EXPECT_MAT_NEAR(a, d_c, a.size().area() * 1e-4);
}

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Dft, testing::Combine(
                            testing::Values(cv::Size(2, 3), cv::Size(5, 4), cv::Size(25, 20), cv::Size(512, 1), cv::Size(1024, 768)),
                            testing::Values(0, (int)cv::DFT_ROWS, (int)cv::DFT_SCALE) ));

////////////////////////////////////////////////////////////////////////////
// MulSpectrums

PARAM_TEST_CASE(MulSpectrums, cv::Size, DftFlags, bool)
{
    cv::Size size;
    int flag;
    bool ccorr;
    cv::Mat a, b;

    virtual void SetUp()
    {
        size  = GET_PARAM(0);
        flag  = GET_PARAM(1);
        ccorr = GET_PARAM(2);

        a = randomMat(size, CV_32FC2);
        b = randomMat(size, CV_32FC2);
    }
};

TEST_P(MulSpectrums, Simple)
{
    cv::ocl::oclMat c;
    cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, 1.0, ccorr);

    cv::Mat c_gold;
    cv::mulSpectrums(a, b, c_gold, flag, ccorr);

    EXPECT_MAT_NEAR(c_gold, c, 1e-2, "");
}

TEST_P(MulSpectrums, Scaled)
{
    float scale = 1.f / size.area();

    cv::ocl::oclMat c;
    cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, scale, ccorr);

    cv::Mat c_gold;
    cv::mulSpectrums(a, b, c_gold, flag, ccorr);
    c_gold.convertTo(c_gold, c_gold.type(), scale);

    EXPECT_MAT_NEAR(c_gold, c, 1e-2, "");
}

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, MulSpectrums, testing::Combine(
    DIFFERENT_SIZES,
    testing::Values(DftFlags(0)),
    testing::Values(false, true)));

////////////////////////////////////////////////////////
// Convolve

void static convolveDFT(const cv::Mat& A, const cv::Mat& B, cv::Mat& C, bool ccorr = false)
{
    // reallocate the output array if needed
    C.create(std::abs(A.rows - B.rows) + 1, std::abs(A.cols - B.cols) + 1, A.type());
    cv::Size dftSize;

    // compute the size of DFT transform
    dftSize.width = cv::getOptimalDFTSize(A.cols + B.cols - 1);
    dftSize.height = cv::getOptimalDFTSize(A.rows + B.rows - 1);

    // allocate temporary buffers and initialize them with 0s
    cv::Mat tempA(dftSize, A.type(), cv::Scalar::all(0));
    cv::Mat tempB(dftSize, B.type(), cv::Scalar::all(0));

    // copy A and B to the top-left corners of tempA and tempB, respectively
    cv::Mat roiA(tempA, cv::Rect(0, 0, A.cols, A.rows));
    A.copyTo(roiA);
    cv::Mat roiB(tempB, cv::Rect(0, 0, B.cols, B.rows));
    B.copyTo(roiB);

    // now transform the padded A & B in-place;
    // use "nonzeroRows" hint for faster processing
    cv::dft(tempA, tempA, 0, A.rows);
    cv::dft(tempB, tempB, 0, B.rows);

    // multiply the spectrums;
    // the function handles packed spectrum representations well
    cv::mulSpectrums(tempA, tempB, tempA, 0, ccorr);

    // transform the product back from the frequency domain.
    // Even though all the result rows will be non-zero,
    // you need only the first C.rows of them, and thus you
    // pass nonzeroRows == C.rows
    cv::dft(tempA, tempA, cv::DFT_INVERSE + cv::DFT_SCALE, C.rows);

    // now copy the result back to C.
    tempA(cv::Rect(0, 0, C.cols, C.rows)).copyTo(C);
}

IMPLEMENT_PARAM_CLASS(KSize, int);
IMPLEMENT_PARAM_CLASS(Ccorr, bool);

PARAM_TEST_CASE(Convolve_DFT, cv::Size, KSize, Ccorr)
{
    cv::Size size;
    int ksize;
    bool ccorr;

    cv::Mat src;
    cv::Mat kernel;

    cv::Mat dst_gold;

    virtual void SetUp()
    {
        size  = GET_PARAM(0);
        ksize = GET_PARAM(1);
        ccorr = GET_PARAM(2);
    }
};

TEST_P(Convolve_DFT, Accuracy)
{
    cv::Mat src = randomMat(size, CV_32FC1, 0.0, 100.0);
    cv::Mat kernel = randomMat(cv::Size(ksize, ksize), CV_32FC1, 0.0, 1.0);

    cv::ocl::oclMat dst;
    cv::ocl::convolve(cv::ocl::oclMat(src), cv::ocl::oclMat(kernel), dst, ccorr);

    cv::Mat dst_gold;
    convolveDFT(src, kernel, dst_gold, ccorr);

    EXPECT_MAT_NEAR(dst, dst_gold, 1e-1, "");
}
#define DIFFERENT_CONVOLVE_SIZES testing::Values(cv::Size(251, 257), cv::Size(113, 113), cv::Size(200, 480), cv::Size(1300, 1300))
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Convolve_DFT, testing::Combine(
    DIFFERENT_CONVOLVE_SIZES,
    testing::Values(KSize(19), KSize(23), KSize(45)),
    testing::Values(Ccorr(true)/*, Ccorr(false)*/))); // false ccorr cannot pass for some instances
#endif // HAVE_CLAMDFFT
<commit_msg>Warning fixes<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other oclMaterials provided with the distribution.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#include "precomp.hpp"
using namespace std;
#ifdef HAVE_CLAMDFFT
////////////////////////////////////////////////////////////////////////////
// Dft
PARAM_TEST_CASE(Dft, cv::Size, int)
{
    cv::Size dft_size;
    int	 dft_flags;
    virtual void SetUp()
    {
        dft_size  = GET_PARAM(0);
        dft_flags = GET_PARAM(1);
    }
};

TEST_P(Dft, C2C)
{
    cv::Mat a = randomMat(dft_size, CV_32FC2, 0.0, 100.0);
    cv::Mat b_gold;

    cv::ocl::oclMat d_b;

    cv::dft(a, b_gold, dft_flags);
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags);
    EXPECT_MAT_NEAR(b_gold, cv::Mat(d_b), a.size().area() * 1e-4);
}

TEST_P(Dft, R2C)
{
    cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 100.0);
    cv::Mat b_gold, b_gold_roi;

    cv::ocl::oclMat d_b, d_c;
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags);
    cv::dft(a, b_gold, cv::DFT_COMPLEX_OUTPUT | dft_flags);

    b_gold_roi = b_gold(cv::Rect(0, 0, d_b.cols, d_b.rows));
    EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4);

    cv::Mat c_gold;
    cv::dft(b_gold, c_gold, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE);
    EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4);
}

TEST_P(Dft, R2CthenC2R)
{
    cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 10.0);

    cv::ocl::oclMat d_b, d_c;
    cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), 0);
    cv::ocl::dft(d_b, d_c, a.size(), cv::DFT_SCALE | cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT);
    EXPECT_MAT_NEAR(a, d_c, a.size().area() * 1e-4);
}

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Dft, testing::Combine(
                            testing::Values(cv::Size(2, 3), cv::Size(5, 4), cv::Size(25, 20), cv::Size(512, 1), cv::Size(1024, 768)),
                            testing::Values(0, (int)cv::DFT_ROWS, (int)cv::DFT_SCALE) ));

////////////////////////////////////////////////////////////////////////////
// MulSpectrums

PARAM_TEST_CASE(MulSpectrums, cv::Size, DftFlags, bool)
{
    cv::Size size;
    int flag;
    bool ccorr;
    cv::Mat a, b;

    virtual void SetUp()
    {
        size  = GET_PARAM(0);
        flag  = GET_PARAM(1);
        ccorr = GET_PARAM(2);

        a = randomMat(size, CV_32FC2);
        b = randomMat(size, CV_32FC2);
    }
};

TEST_P(MulSpectrums, Simple)
{
    cv::ocl::oclMat c;
    cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, 1.0, ccorr);

    cv::Mat c_gold;
    cv::mulSpectrums(a, b, c_gold, flag, ccorr);

    EXPECT_MAT_NEAR(c_gold, c, 1e-2);
}

TEST_P(MulSpectrums, Scaled)
{
    float scale = 1.f / size.area();

    cv::ocl::oclMat c;
    cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, scale, ccorr);

    cv::Mat c_gold;
    cv::mulSpectrums(a, b, c_gold, flag, ccorr);
    c_gold.convertTo(c_gold, c_gold.type(), scale);

    EXPECT_MAT_NEAR(c_gold, c, 1e-2);
}

INSTANTIATE_TEST_CASE_P(OCL_ImgProc, MulSpectrums, testing::Combine(
    DIFFERENT_SIZES,
    testing::Values(DftFlags(0)),
    testing::Values(false, true)));

////////////////////////////////////////////////////////
// Convolve

void static convolveDFT(const cv::Mat& A, const cv::Mat& B, cv::Mat& C, bool ccorr = false)
{
    // reallocate the output array if needed
    C.create(std::abs(A.rows - B.rows) + 1, std::abs(A.cols - B.cols) + 1, A.type());
    cv::Size dftSize;

    // compute the size of DFT transform
    dftSize.width = cv::getOptimalDFTSize(A.cols + B.cols - 1);
    dftSize.height = cv::getOptimalDFTSize(A.rows + B.rows - 1);

    // allocate temporary buffers and initialize them with 0s
    cv::Mat tempA(dftSize, A.type(), cv::Scalar::all(0));
    cv::Mat tempB(dftSize, B.type(), cv::Scalar::all(0));

    // copy A and B to the top-left corners of tempA and tempB, respectively
    cv::Mat roiA(tempA, cv::Rect(0, 0, A.cols, A.rows));
    A.copyTo(roiA);
    cv::Mat roiB(tempB, cv::Rect(0, 0, B.cols, B.rows));
    B.copyTo(roiB);

    // now transform the padded A & B in-place;
    // use "nonzeroRows" hint for faster processing
    cv::dft(tempA, tempA, 0, A.rows);
    cv::dft(tempB, tempB, 0, B.rows);

    // multiply the spectrums;
    // the function handles packed spectrum representations well
    cv::mulSpectrums(tempA, tempB, tempA, 0, ccorr);

    // transform the product back from the frequency domain.
    // Even though all the result rows will be non-zero,
    // you need only the first C.rows of them, and thus you
    // pass nonzeroRows == C.rows
    cv::dft(tempA, tempA, cv::DFT_INVERSE + cv::DFT_SCALE, C.rows);

    // now copy the result back to C.
    tempA(cv::Rect(0, 0, C.cols, C.rows)).copyTo(C);
}

IMPLEMENT_PARAM_CLASS(KSize, int);
IMPLEMENT_PARAM_CLASS(Ccorr, bool);

PARAM_TEST_CASE(Convolve_DFT, cv::Size, KSize, Ccorr)
{
    cv::Size size;
    int ksize;
    bool ccorr;

    cv::Mat src;
    cv::Mat kernel;

    cv::Mat dst_gold;

    virtual void SetUp()
    {
        size  = GET_PARAM(0);
        ksize = GET_PARAM(1);
        ccorr = GET_PARAM(2);
    }
};

TEST_P(Convolve_DFT, Accuracy)
{
    cv::Mat src = randomMat(size, CV_32FC1, 0.0, 100.0);
    cv::Mat kernel = randomMat(cv::Size(ksize, ksize), CV_32FC1, 0.0, 1.0);

    cv::ocl::oclMat dst;
    cv::ocl::convolve(cv::ocl::oclMat(src), cv::ocl::oclMat(kernel), dst, ccorr);

    cv::Mat dst_gold;
    convolveDFT(src, kernel, dst_gold, ccorr);

    EXPECT_MAT_NEAR(dst, dst_gold, 1e-1);
}
#define DIFFERENT_CONVOLVE_SIZES testing::Values(cv::Size(251, 257), cv::Size(113, 113), cv::Size(200, 480), cv::Size(1300, 1300))
INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Convolve_DFT, testing::Combine(
    DIFFERENT_CONVOLVE_SIZES,
    testing::Values(KSize(19), KSize(23), KSize(45)),
    testing::Values(Ccorr(true)/*, Ccorr(false)*/))); // false ccorr cannot pass for some instances
#endif // HAVE_CLAMDFFT
<|endoftext|>


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

#include "net/spdy/spdy_session_pool.h"

#include "base/logging.h"
#include "net/spdy/spdy_session.h"

namespace net {

// The maximum number of sessions to open to a single domain.
static const size_t kMaxSessionsPerDomain = 1;

int SpdySessionPool::g_max_sessions_per_domain = kMaxSessionsPerDomain;

SpdySessionPool::SpdySessionPool() {}
SpdySessionPool::~SpdySessionPool() {
  CloseAllSessions();
}

scoped_refptr<SpdySession> SpdySessionPool::Get(
    const HostPortPair& host_port_pair, HttpNetworkSession* session) {
  scoped_refptr<SpdySession> spdy_session;
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (list) {
    if (list->size() >= static_cast<unsigned int>(g_max_sessions_per_domain)) {
      spdy_session = list->front();
      list->pop_front();
    }
  } else {
    list = AddSessionList(host_port_pair);
  }

  DCHECK(list);
  if (!spdy_session)
    spdy_session = new SpdySession(host_port_pair, session);

  DCHECK(spdy_session);
  list->push_back(spdy_session);
  DCHECK_LE(list->size(), static_cast<unsigned int>(g_max_sessions_per_domain));
  return spdy_session;
}

scoped_refptr<SpdySession> SpdySessionPool::GetSpdySessionFromSSLSocket(
    const HostPortPair& host_port_pair,
    HttpNetworkSession* session,
    ClientSocketHandle* connection) {
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (!list)
    list = AddSessionList(host_port_pair);
  DCHECK(list->empty());
  scoped_refptr<SpdySession> spdy_session(
      new SpdySession(host_port_pair, session));
  spdy_session->InitializeWithSSLSocket(connection);
  list->push_back(spdy_session);
  return spdy_session;
}

bool SpdySessionPool::HasSession(const HostPortPair& host_port_pair) const {
  if (GetSessionList(host_port_pair))
    return true;
  return false;
}

void SpdySessionPool::Remove(const scoped_refptr<SpdySession>& session) {
  SpdySessionList* list = GetSessionList(session->host_port_pair());
  CHECK(list);
  list->remove(session);
  if (list->empty())
    RemoveSessionList(session->host_port_pair());
}

SpdySessionPool::SpdySessionList*
    SpdySessionPool::AddSessionList(const HostPortPair& host_port_pair) {
  DCHECK(sessions_.find(host_port_pair) == sessions_.end());
  return sessions_[host_port_pair] = new SpdySessionList();
}

SpdySessionPool::SpdySessionList*
    SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) {
  SpdySessionsMap::iterator it = sessions_.find(host_port_pair);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

const SpdySessionPool::SpdySessionList*
    SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) const {
  SpdySessionsMap::const_iterator it = sessions_.find(host_port_pair);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

void SpdySessionPool::RemoveSessionList(const HostPortPair& host_port_pair) {
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (list) {
    delete list;
    sessions_.erase(host_port_pair);
  } else {
    DCHECK(false) << "removing orphaned session list";
  }
}

void SpdySessionPool::CloseAllSessions() {
  while (sessions_.size()) {
    SpdySessionList* list = sessions_.begin()->second;
    DCHECK(list);
    sessions_.erase(sessions_.begin()->first);
    while (list->size()) {
      scoped_refptr<SpdySession> session = list->front();
      list->pop_front();
      session->CloseAllStreams(net::ERR_ABORTED);
    }
    delete list;
  }
}

}  // namespace net
<commit_msg>With the GOAWAY code we now can have a case where we attempt to remove the session from the pool twice.  Recover, instead of abort, on that case.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "net/spdy/spdy_session_pool.h"

#include "base/logging.h"
#include "net/spdy/spdy_session.h"

namespace net {

// The maximum number of sessions to open to a single domain.
static const size_t kMaxSessionsPerDomain = 1;

int SpdySessionPool::g_max_sessions_per_domain = kMaxSessionsPerDomain;

SpdySessionPool::SpdySessionPool() {}
SpdySessionPool::~SpdySessionPool() {
  CloseAllSessions();
}

scoped_refptr<SpdySession> SpdySessionPool::Get(
    const HostPortPair& host_port_pair, HttpNetworkSession* session) {
  scoped_refptr<SpdySession> spdy_session;
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (list) {
    if (list->size() >= static_cast<unsigned int>(g_max_sessions_per_domain)) {
      spdy_session = list->front();
      list->pop_front();
    }
  } else {
    list = AddSessionList(host_port_pair);
  }

  DCHECK(list);
  if (!spdy_session)
    spdy_session = new SpdySession(host_port_pair, session);

  DCHECK(spdy_session);
  list->push_back(spdy_session);
  DCHECK_LE(list->size(), static_cast<unsigned int>(g_max_sessions_per_domain));
  return spdy_session;
}

scoped_refptr<SpdySession> SpdySessionPool::GetSpdySessionFromSSLSocket(
    const HostPortPair& host_port_pair,
    HttpNetworkSession* session,
    ClientSocketHandle* connection) {
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (!list)
    list = AddSessionList(host_port_pair);
  DCHECK(list->empty());
  scoped_refptr<SpdySession> spdy_session(
      new SpdySession(host_port_pair, session));
  spdy_session->InitializeWithSSLSocket(connection);
  list->push_back(spdy_session);
  return spdy_session;
}

bool SpdySessionPool::HasSession(const HostPortPair& host_port_pair) const {
  if (GetSessionList(host_port_pair))
    return true;
  return false;
}

void SpdySessionPool::Remove(const scoped_refptr<SpdySession>& session) {
  SpdySessionList* list = GetSessionList(session->host_port_pair());
  if (!list)
    return;
  list->remove(session);
  if (list->empty())
    RemoveSessionList(session->host_port_pair());
}

SpdySessionPool::SpdySessionList*
    SpdySessionPool::AddSessionList(const HostPortPair& host_port_pair) {
  DCHECK(sessions_.find(host_port_pair) == sessions_.end());
  return sessions_[host_port_pair] = new SpdySessionList();
}

SpdySessionPool::SpdySessionList*
    SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) {
  SpdySessionsMap::iterator it = sessions_.find(host_port_pair);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

const SpdySessionPool::SpdySessionList*
    SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) const {
  SpdySessionsMap::const_iterator it = sessions_.find(host_port_pair);
  if (it == sessions_.end())
    return NULL;
  return it->second;
}

void SpdySessionPool::RemoveSessionList(const HostPortPair& host_port_pair) {
  SpdySessionList* list = GetSessionList(host_port_pair);
  if (list) {
    delete list;
    sessions_.erase(host_port_pair);
  } else {
    DCHECK(false) << "removing orphaned session list";
  }
}

void SpdySessionPool::CloseAllSessions() {
  while (sessions_.size()) {
    SpdySessionList* list = sessions_.begin()->second;
    DCHECK(list);
    sessions_.erase(sessions_.begin()->first);
    while (list->size()) {
      scoped_refptr<SpdySession> session = list->front();
      list->pop_front();
      session->CloseAllStreams(net::ERR_ABORTED);
    }
    delete list;
  }
}

}  // namespace net
<|endoftext|>


<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 HOLDER 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 <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "buffer.h"
#include "primitive.h"
#include "address.h"
#include "socket.h"
#include "acceptor.h"
#include "socket_service.h"

void echo_tcp_server(void) {
  netpp::SocketService service;
#if defined(CHAOS_POSIX)
  netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555));
#else
  netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555));
#endif
  acceptor.set_non_blocking(true);
  std::vector<std::unique_ptr<std::thread>> threads;
  netpp::TcpSocket conn(service);
  acceptor.async_accept(conn,
      [&threads, &acceptor, &conn](const std::error_code& ec) {
        if (!ec) {
          threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) {
                  std::error_code ec;
                  std::vector<char> buf(1024);
                  for (;;) {
                    auto n = conn.read_some(netpp::buffer(buf));
                    if (n > 0)
                      conn.write_some(netpp::buffer(buf, n));
                    else
                      break;
                  }
                  conn.close();
                }, std::move(conn)));
        }
      });

  service.run();
  for (auto& t : threads)
    t->join();
}

void echo_tcp_client(void) {
  netpp::SocketService service;
  netpp::TcpSocket s(service, netpp::Tcp::v4());
  s.set_non_blocking(true);
  s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));

  std::string line;
  std::vector<char> buf(1024);
  while (std::getline(std::cin, line)) {
    if (line == "quit")
      break;
    s.write(netpp::buffer(line));

    buf.assign(buf.size(), 0);
    if (s.read(netpp::buffer(buf)) > 0)
      std::cout << "echo read: " << buf.data() << std::endl;
    else
      break;
  }
  s.close();
}

void echo_udp_server(void) {
  netpp::SocketService service;
  netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555));
  s.set_non_blocking(true);

  std::vector<char> buf(1024);
  for (;;) {
    netpp::Address addr(netpp::IP::v4());
    auto n = s.read_from(netpp::buffer(buf), addr);
    if (n > 0)
      s.write_to(netpp::buffer(buf, n), addr);
    else
      break;
  }
  s.close();
}

void echo_udp_client(void) {
  netpp::SocketService service;
  netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4());
  s.set_non_blocking(true);
  s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));

  std::string line;
  std::vector<char> buf(1024);
  while (std::getline(std::cin, line)) {
    if (line == "quit")
      break;
    s.write(netpp::buffer(line));

    buf.assign(buf.size(), 0);
    if (s.read(netpp::buffer(buf)) > 0)
      std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl;
  }
  s.close();
}

void echo_sample(const char* c) {
  netpp::startup();
  if (std::strcmp(c, "ts") == 0)
    echo_tcp_server();
  else if (std::strcmp(c, "tc") == 0)
    echo_tcp_client();
  else if (std::strcmp(c, "us") == 0)
    echo_udp_server();
  else if (std::strcmp(c, "uc") == 0)
    echo_udp_client();
  netpp::cleanup();
}

int main(int argc, char* argv[]) {
  CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);

  if (argc > 1)
    echo_sample(argv[1]);

  return 0;
}
<commit_msg>:construction: chore(demo): updated the demo using netpp<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
//    distribution.
//
// 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 HOLDER 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 <Chaos/Base/Platform.h>
#include <Chaos/Base/Types.h>
#include <cstring>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "buffer.h"
#include "primitive.h"
#include "address.h"
#include "socket.h"
#include "acceptor.h"
#include "socket_service.h"

class TcpConnection
  : private Chaos::UnCopyable
  , public std::enable_shared_from_this<TcpConnection> {
  netpp::TcpSocket socket_;
  std::vector<char> buffer_;

  static constexpr std::size_t kMaxBuffer = 1024;

  void do_read(void) {
    auto self(shared_from_this());
    socket_.async_read_some(netpp::buffer(buffer_),
        [this, self](const std::error_code& ec, std::size_t n) {
          if (!ec)
            do_write(n);
        });
  }

  void do_write(std::size_t n) {
    auto self(shared_from_this());
    socket_.async_write_some(netpp::buffer(buffer_, n),
        [this, self](const std::error_code& ec, std::size_t) {
          if (!ec)
            do_read();
        });
  }
public:
  TcpConnection(netpp::TcpSocket&& s)
    : socket_(std::move(s))
    , buffer_(kMaxBuffer) {
  }

  void start(void) {
    do_read();
  }
};

class EchoTcpServer : private Chaos::UnCopyable {
  netpp::Acceptor acceptor_;
  netpp::TcpSocket socket_;

  void do_accept(void) {
    acceptor_.async_accept(socket_, [this](const std::error_code& ec) {
          if (!ec)
            std::make_shared<TcpConnection>(std::move(socket_));

          do_accept();
        });
  }
public:
  EchoTcpServer(netpp::SocketService& service, std::uint16_t port)
#if defined(CHAOS_POSIX)
    : acceptor_(service, netpp::Address(netpp::IP::v6(), port))
#else
    : acceptor_(service, netpp::Address(netpp::IP::v4(), port))
#endif
    , socket_(service) {
    acceptor_.set_non_blocking(true);
  }

  void start(void) {
    do_accept();
  }
};

void echo_tcp_server(void) {
  netpp::SocketService service;
  EchoTcpServer server(service, 5555);
  server.start();

// #if defined(CHAOS_POSIX)
//   netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555));
// #else
//   netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555));
// #endif
//   acceptor.set_non_blocking(true);
//   std::vector<std::unique_ptr<std::thread>> threads;
//   netpp::TcpSocket conn(service);
//   acceptor.async_accept(conn,
//       [&threads, &acceptor, &conn](const std::error_code& ec) {
//         if (!ec) {
//           threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) {
//                   std::error_code ec;
//                   std::vector<char> buf(1024);
//                   for (;;) {
//                     auto n = conn.read_some(netpp::buffer(buf));
//                     if (n > 0)
//                       conn.write_some(netpp::buffer(buf, n));
//                     else
//                       break;
//                   }
//                   conn.close();
//                 }, std::move(conn)));
//         }
//       });

  service.run();

//   for (auto& t : threads)
//     t->join();
}

void echo_tcp_client(void) {
  netpp::SocketService service;
  netpp::TcpSocket s(service, netpp::Tcp::v4());
  s.set_non_blocking(true);
  s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));

  std::string line;
  std::vector<char> buf(1024);
  while (std::getline(std::cin, line)) {
    if (line == "quit")
      break;
    s.write(netpp::buffer(line));

    buf.assign(buf.size(), 0);
    if (s.read(netpp::buffer(buf)) > 0)
      std::cout << "echo read: " << buf.data() << std::endl;
    else
      break;
  }
  s.close();
}

void echo_udp_server(void) {
  netpp::SocketService service;
  netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555));
  s.set_non_blocking(true);

  std::vector<char> buf(1024);
  for (;;) {
    netpp::Address addr(netpp::IP::v4());
    auto n = s.read_from(netpp::buffer(buf), addr);
    if (n > 0)
      s.write_to(netpp::buffer(buf, n), addr);
    else
      break;
  }
  s.close();
}

void echo_udp_client(void) {
  netpp::SocketService service;
  netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4());
  s.set_non_blocking(true);
  s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555));

  std::string line;
  std::vector<char> buf(1024);
  while (std::getline(std::cin, line)) {
    if (line == "quit")
      break;
    s.write(netpp::buffer(line));

    buf.assign(buf.size(), 0);
    if (s.read(netpp::buffer(buf)) > 0)
      std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl;
  }
  s.close();
}

void echo_sample(const char* c) {
  netpp::startup();
  if (std::strcmp(c, "ts") == 0)
    echo_tcp_server();
  else if (std::strcmp(c, "tc") == 0)
    echo_tcp_client();
  else if (std::strcmp(c, "us") == 0)
    echo_udp_server();
  else if (std::strcmp(c, "uc") == 0)
    echo_udp_client();
  netpp::cleanup();
}

int main(int argc, char* argv[]) {
  CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);

  if (argc > 1)
    echo_sample(argv[1]);

  return 0;
}
<|endoftext|>


<commit_before>#include "dllist.cpp"

template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
    bool ownsItems = true;

public:
    DoubleLinkedChain(): front(NULL), back(NULL) {}

    DoubleLinkedChain(const DoubleLinkedList& l): front(l.front), back(l.back),
            ownsItems(false) {}

    DoubleLinkedChain& operator=(const DoubleLinkedList& l)
    {
        if (&other != this)
        {
            if (ownsItems)
                clean();

            front = l.front;
            back = l.back;
            ownsItems = false;
        }

        return *this;
    }

    ~DoubleLinkedChain()
    {
        if (ownsItems)
            clean();
    }

    void attachNext(const I& cur, const I& next)
    {
        if (cur.ptr && !cur.ptr->next)
            cur.ptr->next = next.ptr;
    }

    void attachPrev(const I& cur, const I& prev)
    {
        if (cur.ptr && !cur.ptr->prev)
            cur.ptr->prev = prev.ptr;
    }
};
<commit_msg>backup before major refactoring<commit_after>#include "dllist.cpp"

template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
    bool ownsItems = true;

public:
    DoubleLinkedChain(): front(NULL), back(NULL) {}

    DoubleLinkedChain(const DoubleLinkedList& l):
            front(l.front), back(l.back), ownsItems(false) {}

    DoubleLinkedChain& operator=(const DoubleLinkedList& l)
    {
        if (&other != this)
        {
            if (ownsItems)
                clean();

            front = l.front;
            back = l.back;
            ownsItems = false;
        }

        return *this;
    }

    ~DoubleLinkedChain()
    {
        if (ownsItems)
            clean();
    }

    void attachAtBegin(const I& it)
    {
        if (it && front)
        {
            front->prev = it.ptr;

            I begin = front;
            while (begin)
                begin--;
            front = begin.ptr;
        }
    }

    void attachAtEnd(const I& it)
    {
        if (it && back)
        {
            back->next = it.ptr;

            I end = back;
            while (end)
                end++;
            back = end.ptr;
        }
    }

    void attachAtPrev(const I& it, const I& prev)
    {
        if (it && prev && !it.ptr->prev)
            it.ptr->prev = prev.ptr;
    }

    void attachAtNext(const I& it, const I& next)
    {
        if (it && next && !it.ptr->next)
            it.ptr->next = next.ptr;
    }

};
<|endoftext|>


<commit_before><commit_msg>remove all variables for each step in dataman<commit_after><|endoftext|>


<commit_before>#include "QmitkFunctionalityCoordinator.h"
#include "QmitkFunctionality.h"
#include <QmitkStdMultiWidgetEditor.h>
#include <berryPlatformUI.h>
#include <berryIWorkbenchPage.h>

QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator()
: m_StandaloneFuntionality(NULL)
{
}

void QmitkFunctionalityCoordinator::SetWindow( berry::IWorkbenchWindow::Pointer window )
{
  m_Window = window;
  if(window.IsNotNull())
  {
    window->GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this));
    window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this));
  }
}

QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator()
{
}

berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const
{
  return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED |
    | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN
    | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED;
}

void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  // change the active standalone functionality
  this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
}

void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer partRef )
{
  // nothing to do here: see PartActivated()
}

void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef )
{
   // check for multiwidget and inform views that it is available now
  if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID )
  {
    for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin()
      ; it != m_Functionalities.end(); it++)
    {
      (*it)->StdMultiWidgetAvailable(*(partRef
        ->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget()));
    }
  }
  else
  {
    // Check for QmitkFunctionality
    QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
    if(_QmitkFunctionality.IsNotNull())
    {
      m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality
    }
  }
}

void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef )
{
  // check for multiwidget and inform views that it not available any more
  if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID )
  {

    QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>();
    for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin()
      ; it != m_Functionalities.end(); it++)
    {
      (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget()));
      (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence
    }
  }
  else
  {
    // check for functionality
    QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
    if(_QmitkFunctionality.IsNotNull())
    {
      // deactivate on close ( the standalone functionality may still be activated  )
      this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());

      // and set pointer to 0
      if(m_StandaloneFuntionality == _QmitkFunctionality.GetPointer())
        m_StandaloneFuntionality = 0;

      m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality
      // call PartClosed on the QmitkFunctionality
      _QmitkFunctionality->ClosePartProxy();
      //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden()
    }
  }
}

void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  if(_QmitkFunctionality != 0)
  {
    _QmitkFunctionality->SetVisible(false);
    _QmitkFunctionality->Hidden();
    // try to deactivate on hide (if is activated)
    this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());

    // tracking of Visible Standalone Functionalities
    m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer());
    // activate Functionality if just one Standalone Functionality is visible (old one gets deactivated)
    if(m_VisibleStandaloneFunctionalities.size() == 1)
      this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
  }
}

void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  if(_QmitkFunctionality.IsNotNull())
  {
    _QmitkFunctionality->SetVisible(true);
    _QmitkFunctionality->Visible();

    // tracking of Visible Standalone Functionalities
    m_VisibleStandaloneFunctionalities.insert(_QmitkFunctionality.GetPointer());
    // activate Functionality if just one Standalone Functionality is visible
    if(m_VisibleStandaloneFunctionalities.size() == 1)
      this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
  }
}

void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( QmitkFunctionality* functionality )
{
  if(functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality())
  {
    // deactivate old one if necessary
    this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality);
    m_StandaloneFuntionality = functionality;

    // call activated on this functionality
    m_StandaloneFuntionality->SetActivated(true);
    m_StandaloneFuntionality->Activated();
  }
}

void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(QmitkFunctionality* functionality)
{
  if(functionality && functionality->IsActivated())
  {
    functionality->SetActivated(false);
    functionality->Deactivated();
  }
}

void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer window )
{
  if(window.IsNotNull())
  {
    window->GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this));
    window->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this));
  }
}

void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window )
{

}<commit_msg>COMP (#3225): Removed unnecessary |<commit_after>#include "QmitkFunctionalityCoordinator.h"
#include "QmitkFunctionality.h"
#include <QmitkStdMultiWidgetEditor.h>
#include <berryPlatformUI.h>
#include <berryIWorkbenchPage.h>

QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator()
: m_StandaloneFuntionality(NULL)
{
}

void QmitkFunctionalityCoordinator::SetWindow( berry::IWorkbenchWindow::Pointer window )
{
  m_Window = window;
  if(window.IsNotNull())
  {
    window->GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this));
    window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this));
  }
}

QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator()
{
}

berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const
{
  return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED
    | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN
    | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED;
}

void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  // change the active standalone functionality
  this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
}

void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer partRef )
{
  // nothing to do here: see PartActivated()
}

void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef )
{
   // check for multiwidget and inform views that it is available now
  if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID )
  {
    for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin()
      ; it != m_Functionalities.end(); it++)
    {
      (*it)->StdMultiWidgetAvailable(*(partRef
        ->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget()));
    }
  }
  else
  {
    // Check for QmitkFunctionality
    QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
    if(_QmitkFunctionality.IsNotNull())
    {
      m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality
    }
  }
}

void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef )
{
  // check for multiwidget and inform views that it not available any more
  if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID )
  {

    QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>();
    for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin()
      ; it != m_Functionalities.end(); it++)
    {
      (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget()));
      (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence
    }
  }
  else
  {
    // check for functionality
    QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
    if(_QmitkFunctionality.IsNotNull())
    {
      // deactivate on close ( the standalone functionality may still be activated  )
      this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());

      // and set pointer to 0
      if(m_StandaloneFuntionality == _QmitkFunctionality.GetPointer())
        m_StandaloneFuntionality = 0;

      m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality
      // call PartClosed on the QmitkFunctionality
      _QmitkFunctionality->ClosePartProxy();
      //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden()
    }
  }
}

void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  if(_QmitkFunctionality != 0)
  {
    _QmitkFunctionality->SetVisible(false);
    _QmitkFunctionality->Hidden();
    // try to deactivate on hide (if is activated)
    this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());

    // tracking of Visible Standalone Functionalities
    m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer());
    // activate Functionality if just one Standalone Functionality is visible (old one gets deactivated)
    if(m_VisibleStandaloneFunctionalities.size() == 1)
      this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
  }
}

void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef )
{
  // Check for QmitkFunctionality
  QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>();
  if(_QmitkFunctionality.IsNotNull())
  {
    _QmitkFunctionality->SetVisible(true);
    _QmitkFunctionality->Visible();

    // tracking of Visible Standalone Functionalities
    m_VisibleStandaloneFunctionalities.insert(_QmitkFunctionality.GetPointer());
    // activate Functionality if just one Standalone Functionality is visible
    if(m_VisibleStandaloneFunctionalities.size() == 1)
      this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer());
  }
}

void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( QmitkFunctionality* functionality )
{
  if(functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality())
  {
    // deactivate old one if necessary
    this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality);
    m_StandaloneFuntionality = functionality;

    // call activated on this functionality
    m_StandaloneFuntionality->SetActivated(true);
    m_StandaloneFuntionality->Activated();
  }
}

void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(QmitkFunctionality* functionality)
{
  if(functionality && functionality->IsActivated())
  {
    functionality->SetActivated(false);
    functionality->Deactivated();
  }
}

void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer window )
{
  if(window.IsNotNull())
  {
    window->GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this));
    window->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this));
  }
}

void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window )
{

}<|endoftext|>


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

#include "chrome/browser/chromeos/accessibility/magnification_manager.h"

#include "ash/magnifier/magnification_controller.h"
#include "ash/magnifier/partial_magnification_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/prefs/pref_member.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"

namespace chromeos {

namespace {
const double kInitialMagnifiedScale = 2.0;
static MagnificationManager* g_magnification_manager = NULL;
}

class MagnificationManagerImpl : public MagnificationManager,
                                 public content::NotificationObserver {
 public:
  MagnificationManagerImpl() : first_time_update_(true),
                               profile_(NULL),
                               type_(ash::kDefaultMagnifierType),
                               enabled_(false) {
    registrar_.Add(this,
                  chrome::NOTIFICATION_PROFILE_CREATED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_SESSION_STARTED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_PROFILE_DESTROYED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE,
                  content::NotificationService::AllSources());
  }

  virtual ~MagnificationManagerImpl() {
    CHECK(this == g_magnification_manager);
  }

  // MagnificationManager implimentation:
  virtual bool IsMagnifierEnabled() const OVERRIDE {
    return enabled_;
  }

  virtual ash::MagnifierType GetMagnifierType() const OVERRIDE {
    return type_;
  }

  virtual void SetMagnifierEnabled(bool enabled) OVERRIDE {
    // This method may be invoked even when the other magnifier settings (e.g.
    // type or scale) are changed, so we need to call magnification controller
    // even if |enabled| is unchanged. Only if |enabled| is false and the
    // magnifier is already disabled, we are sure that we don't need to reflect
    // the new settings right now because the magnifier keeps disabled.
    if (!enabled && !enabled_)
      return;

    enabled_ = enabled;

    if (profile_) {
      PrefService* prefs = profile_->GetPrefs();
      DCHECK(prefs);
      if (enabled != prefs->GetBoolean(prefs::kScreenMagnifierEnabled)) {
        prefs->SetBoolean(prefs::kScreenMagnifierEnabled, enabled);
        prefs->CommitPendingWrite();
      }
    }

    NotifyMagnifierChanged();

    if (type_ == ash::MAGNIFIER_FULL) {
      ash::Shell::GetInstance()->magnification_controller()->SetEnabled(
          enabled_);
    } else {
      ash::Shell::GetInstance()->partial_magnification_controller()->SetEnabled(
          enabled_);
    }
  }

  virtual void SetMagnifierType(ash::MagnifierType type) OVERRIDE {
    if (type_ == type)
      return;

    DCHECK(type == ash::MAGNIFIER_FULL || type == ash::MAGNIFIER_PARTIAL);
    type_ = ash::MAGNIFIER_FULL;  // (leave out for full magnifier)

    if (profile_) {
      PrefService* prefs = profile_->GetPrefs();
      DCHECK(prefs);
      prefs->SetInteger(prefs::kScreenMagnifierType, type);
      prefs->CommitPendingWrite();
    }

    NotifyMagnifierChanged();
  }

  virtual void SaveScreenMagnifierScale(double scale) OVERRIDE {
    Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
    DCHECK(profile->GetPrefs());
    profile->GetPrefs()->SetDouble(prefs::kScreenMagnifierScale, scale);
  }

  virtual double GetSavedScreenMagnifierScale() const OVERRIDE {
    Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
    DCHECK(profile->GetPrefs());
    if (profile->GetPrefs()->HasPrefPath(prefs::kScreenMagnifierScale))
      return profile->GetPrefs()->GetDouble(prefs::kScreenMagnifierScale);
    return std::numeric_limits<double>::min();
  }

 private:
  void NotifyMagnifierChanged() {
      accessibility::AccessibilityStatusEventDetails details(
          enabled_, type_, ash::A11Y_NOTIFICATION_NONE);
      content::NotificationService::current()->Notify(
          chrome::NOTIFICATION_CROS_ACCESSIBILITY_TOGGLE_SCREEN_MAGNIFIER,
          content::NotificationService::AllSources(),
          content::Details<accessibility::AccessibilityStatusEventDetails>(
              &details));
  }

  bool IsMagnifierEnabledFromPref() {
    if (!profile_)
      return false;

    DCHECK(profile_->GetPrefs());
    return profile_->GetPrefs()->GetBoolean(prefs::kScreenMagnifierEnabled);
  }

  ash::MagnifierType GetMagnifierTypeFromPref() {
    return ash::MAGNIFIER_FULL;
  }

  void SetProfile(Profile* profile) {
    if (pref_change_registrar_) {
      pref_change_registrar_.reset();
    }

    if (profile) {
      pref_change_registrar_.reset(new PrefChangeRegistrar);
      pref_change_registrar_->Init(profile->GetPrefs());
      pref_change_registrar_->Add(
          prefs::kScreenMagnifierEnabled,
          base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref,
                     base::Unretained(this)));
      pref_change_registrar_->Add(
          prefs::kScreenMagnifierType,
          base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref,
                     base::Unretained(this)));
    }

    profile_ = profile;
    UpdateMagnifierStatusFromPref();
  }

  void UpdateMagnifierStatusFromPref() {
    bool enabled = IsMagnifierEnabledFromPref();
    if (!enabled) {
      SetMagnifierEnabled(enabled);
      SetMagnifierType(GetMagnifierTypeFromPref());
    } else {
      SetMagnifierType(GetMagnifierTypeFromPref());
      SetMagnifierEnabled(enabled);
    }
  }

  // content::NotificationObserver implimentation:
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE {
    switch (type) {
      // When entering the login screen or non-guest desktop.
      case chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE:
      case chrome::NOTIFICATION_SESSION_STARTED: {
        Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
        if (!profile->IsGuestSession())
          SetProfile(profile);
        break;
      }
      // When entering guest desktop, no NOTIFICATION_SESSION_STARTED event is
      // fired, so we use NOTIFICATION_PROFILE_CREATED event instead.
      case chrome::NOTIFICATION_PROFILE_CREATED: {
        Profile* profile = content::Source<Profile>(source).ptr();
        if (profile->IsGuestSession())
          SetProfile(profile);
        break;
      }
      case chrome::NOTIFICATION_PROFILE_DESTROYED: {
        SetProfile(NULL);
        break;
      }
    }
  }

  bool first_time_update_;
  Profile* profile_;
  ash::MagnifierType type_;
  bool enabled_;
  content::NotificationRegistrar registrar_;
  scoped_ptr<PrefChangeRegistrar> pref_change_registrar_;

  DISALLOW_COPY_AND_ASSIGN(MagnificationManagerImpl);
};

// static
void MagnificationManager::Initialize() {
  CHECK(g_magnification_manager == NULL);
  g_magnification_manager = new MagnificationManagerImpl();
}

// static
void MagnificationManager::Shutdown() {
  CHECK(g_magnification_manager);
  delete g_magnification_manager;
  g_magnification_manager = NULL;
}

// static
MagnificationManager* MagnificationManager::Get() {
  return g_magnification_manager;
}

}  // namespace chromeos
<commit_msg>Magnifier: Ignore Off-The-Record profile.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/accessibility/magnification_manager.h"

#include "ash/magnifier/magnification_controller.h"
#include "ash/magnifier/partial_magnification_controller.h"
#include "ash/shell.h"
#include "ash/system/tray/system_tray_notifier.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/singleton.h"
#include "base/prefs/pref_member.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"

namespace chromeos {

namespace {
const double kInitialMagnifiedScale = 2.0;
static MagnificationManager* g_magnification_manager = NULL;
}

class MagnificationManagerImpl : public MagnificationManager,
                                 public content::NotificationObserver {
 public:
  MagnificationManagerImpl() : first_time_update_(true),
                               profile_(NULL),
                               type_(ash::kDefaultMagnifierType),
                               enabled_(false) {
    registrar_.Add(this,
                  chrome::NOTIFICATION_PROFILE_CREATED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_SESSION_STARTED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_PROFILE_DESTROYED,
                  content::NotificationService::AllSources());
    registrar_.Add(this,
                  chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE,
                  content::NotificationService::AllSources());
  }

  virtual ~MagnificationManagerImpl() {
    CHECK(this == g_magnification_manager);
  }

  // MagnificationManager implimentation:
  virtual bool IsMagnifierEnabled() const OVERRIDE {
    return enabled_;
  }

  virtual ash::MagnifierType GetMagnifierType() const OVERRIDE {
    return type_;
  }

  virtual void SetMagnifierEnabled(bool enabled) OVERRIDE {
    // This method may be invoked even when the other magnifier settings (e.g.
    // type or scale) are changed, so we need to call magnification controller
    // even if |enabled| is unchanged. Only if |enabled| is false and the
    // magnifier is already disabled, we are sure that we don't need to reflect
    // the new settings right now because the magnifier keeps disabled.
    if (!enabled && !enabled_)
      return;

    enabled_ = enabled;

    if (profile_) {
      PrefService* prefs = profile_->GetPrefs();
      DCHECK(prefs);
      if (enabled != prefs->GetBoolean(prefs::kScreenMagnifierEnabled)) {
        prefs->SetBoolean(prefs::kScreenMagnifierEnabled, enabled);
        prefs->CommitPendingWrite();
      }
    }

    NotifyMagnifierChanged();

    if (type_ == ash::MAGNIFIER_FULL) {
      ash::Shell::GetInstance()->magnification_controller()->SetEnabled(
          enabled_);
    } else {
      ash::Shell::GetInstance()->partial_magnification_controller()->SetEnabled(
          enabled_);
    }
  }

  virtual void SetMagnifierType(ash::MagnifierType type) OVERRIDE {
    if (type_ == type)
      return;

    DCHECK(type == ash::MAGNIFIER_FULL || type == ash::MAGNIFIER_PARTIAL);
    type_ = ash::MAGNIFIER_FULL;  // (leave out for full magnifier)

    if (profile_) {
      PrefService* prefs = profile_->GetPrefs();
      DCHECK(prefs);
      prefs->SetInteger(prefs::kScreenMagnifierType, type);
      prefs->CommitPendingWrite();
    }

    NotifyMagnifierChanged();
  }

  virtual void SaveScreenMagnifierScale(double scale) OVERRIDE {
    Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
    DCHECK(profile->GetPrefs());
    profile->GetPrefs()->SetDouble(prefs::kScreenMagnifierScale, scale);
  }

  virtual double GetSavedScreenMagnifierScale() const OVERRIDE {
    Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord();
    DCHECK(profile->GetPrefs());
    if (profile->GetPrefs()->HasPrefPath(prefs::kScreenMagnifierScale))
      return profile->GetPrefs()->GetDouble(prefs::kScreenMagnifierScale);
    return std::numeric_limits<double>::min();
  }

 private:
  void NotifyMagnifierChanged() {
      accessibility::AccessibilityStatusEventDetails details(
          enabled_, type_, ash::A11Y_NOTIFICATION_NONE);
      content::NotificationService::current()->Notify(
          chrome::NOTIFICATION_CROS_ACCESSIBILITY_TOGGLE_SCREEN_MAGNIFIER,
          content::NotificationService::AllSources(),
          content::Details<accessibility::AccessibilityStatusEventDetails>(
              &details));
  }

  bool IsMagnifierEnabledFromPref() {
    if (!profile_)
      return false;

    DCHECK(profile_->GetPrefs());
    return profile_->GetPrefs()->GetBoolean(prefs::kScreenMagnifierEnabled);
  }

  ash::MagnifierType GetMagnifierTypeFromPref() {
    return ash::MAGNIFIER_FULL;
  }

  void SetProfile(Profile* profile) {
    if (pref_change_registrar_) {
      pref_change_registrar_.reset();
    }

    if (profile) {
      pref_change_registrar_.reset(new PrefChangeRegistrar);
      pref_change_registrar_->Init(profile->GetPrefs());
      pref_change_registrar_->Add(
          prefs::kScreenMagnifierEnabled,
          base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref,
                     base::Unretained(this)));
      pref_change_registrar_->Add(
          prefs::kScreenMagnifierType,
          base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref,
                     base::Unretained(this)));
    }

    profile_ = profile;
    UpdateMagnifierStatusFromPref();
  }

  void UpdateMagnifierStatusFromPref() {
    bool enabled = IsMagnifierEnabledFromPref();
    if (!enabled) {
      SetMagnifierEnabled(enabled);
      SetMagnifierType(GetMagnifierTypeFromPref());
    } else {
      SetMagnifierType(GetMagnifierTypeFromPref());
      SetMagnifierEnabled(enabled);
    }
  }

  // content::NotificationObserver implimentation:
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE {
    switch (type) {
      // When entering the login screen or non-guest desktop.
      case chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE:
      case chrome::NOTIFICATION_SESSION_STARTED: {
        Profile* profile = ProfileManager::GetDefaultProfile();
        if (!profile->IsGuestSession())
          SetProfile(profile);
        break;
      }
      // When entering guest desktop, no NOTIFICATION_SESSION_STARTED event is
      // fired, so we use NOTIFICATION_PROFILE_CREATED event instead.
      case chrome::NOTIFICATION_PROFILE_CREATED: {
        Profile* profile = content::Source<Profile>(source).ptr();
        if (profile->IsGuestSession() && !profile->IsOffTheRecord()) {
          SetProfile(profile);

          // In guest mode, 2 non-OTR profiles are created. We should use the
          // first one, not second one.
          registrar_.Remove(this,
                            chrome::NOTIFICATION_PROFILE_CREATED,
                            content::NotificationService::AllSources());
        }

        break;
      }
      case chrome::NOTIFICATION_PROFILE_DESTROYED: {
        SetProfile(NULL);
        break;
      }
    }
  }

  bool first_time_update_;
  Profile* profile_;
  ash::MagnifierType type_;
  bool enabled_;
  content::NotificationRegistrar registrar_;
  scoped_ptr<PrefChangeRegistrar> pref_change_registrar_;

  DISALLOW_COPY_AND_ASSIGN(MagnificationManagerImpl);
};

// static
void MagnificationManager::Initialize() {
  CHECK(g_magnification_manager == NULL);
  g_magnification_manager = new MagnificationManagerImpl();
}

// static
void MagnificationManager::Shutdown() {
  CHECK(g_magnification_manager);
  delete g_magnification_manager;
  g_magnification_manager = NULL;
}

// static
MagnificationManager* MagnificationManager::Get() {
  return g_magnification_manager;
}

}  // namespace chromeos
<|endoftext|>


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

#include "base/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  bool RunInstallTest(const std::string& page) {
    std::string base_url = base::StringPrintf(
        "http://www.example.com:%u/files/extensions/",
        test_server()->host_port_pair().port());

    std::string testing_install_base_url = base_url;
    testing_install_base_url += "good.crx";

    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kAppsGalleryUpdateURL, testing_install_base_url);

    std::string page_url = base_url;
    page_url += "api_test/extension_gallery_install/" + page;

    return RunPageTest(page_url.c_str());
  }
};

// http://crbug.com/55642 - failing on XP.
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
                       MAYBE_InstallAndUninstall) {
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  ASSERT_TRUE(test_server()->Start());

  BeginInstallFunction::SetIgnoreUserGestureForTests(true);
  ASSERT_TRUE(RunInstallTest("test.html"));
  ASSERT_TRUE(RunInstallTest("complete_without_begin.html"));
  ASSERT_TRUE(RunInstallTest("invalid_begin.html"));

  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html"));
}
<commit_msg>Add some extra debugging info for a flaky test.<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/stringprintf.h"
#if defined (OS_WIN)
#include "base/win/windows_version.h"
#endif  // defined (OS_WIN)

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/ui_test_utils.h"
#include "net/base/mock_host_resolver.h"

class ExtensionGalleryInstallApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  bool RunInstallTest(const std::string& page) {
    std::string base_url = base::StringPrintf(
        "http://www.example.com:%u/files/extensions/",
        test_server()->host_port_pair().port());

    std::string testing_install_base_url = base_url;
    testing_install_base_url += "good.crx";

    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
      switches::kAppsGalleryUpdateURL, testing_install_base_url);

    std::string page_url = base_url;
    page_url += "api_test/extension_gallery_install/" + page;

    return RunPageTest(page_url.c_str());
  }
};

namespace {

bool RunningOnXP() {
#if defined (OS_WIN)
  return GetVersion() < base::win::VERSION_VISTA;
#else
  return false;
#endif  // defined (OS_WIN)
}

}  // namespace

// TODO(asargent) - for some reason this test occasionally fails on XP,
// but not other versions of windows. http://crbug.com/55642
#if defined (OS_WIN)
#define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall
#else
#define MAYBE_InstallAndUninstall InstallAndUninstall
#endif
IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,
                       MAYBE_InstallAndUninstall) {
  if (RunningOnXP()) {
    LOG(INFO) << "Adding host resolver rule";
  }
  host_resolver()->AddRule("www.example.com", "127.0.0.1");
  if (RunningOnXP()) {
    LOG(INFO) << "Starting test server";
  }
  ASSERT_TRUE(test_server()->Start());

  if (RunningOnXP()) {
    LOG(INFO) << "Starting tests without user gesture checking";
  }
  BeginInstallFunction::SetIgnoreUserGestureForTests(true);
  ASSERT_TRUE(RunInstallTest("test.html"));
  ASSERT_TRUE(RunInstallTest("complete_without_begin.html"));
  ASSERT_TRUE(RunInstallTest("invalid_begin.html"));

  if (RunningOnXP()) {
    LOG(INFO) << "Starting tests with user gesture checking";
  }
  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html"));
}
<|endoftext|>